@agentchatme/agent-core 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,21 @@
1
1
  import {
2
2
  AGENT_LOCK_DIR_ENV,
3
+ ANCHOR_END,
4
+ ANCHOR_START,
3
5
  COULD_NOT_PROCESS_FILE,
4
6
  DAEMON_LOCK_FILE,
5
7
  DEFAULT_API_BASE,
6
8
  FAILED_CYCLE_OUTCOMES,
7
9
  HEARTBEAT_FILE,
10
+ HOST_FILE,
11
+ IDENTITY_ANCHOR_ATTEMPTS,
12
+ INSTALL_ID_FILE,
8
13
  INTEGRATION_STATUS_FILE,
9
14
  INTEGRATION_STATUS_STALE_MS,
10
15
  LEASE_RENEW_MS,
11
16
  LEASE_STALE_MS,
12
17
  LEGACY_STATUS_FILE,
18
+ LISTENER_ID_FILE,
13
19
  MANUAL,
14
20
  MANUAL_FETCH_TIMEOUT_MS,
15
21
  MANUAL_FILENAME,
@@ -19,9 +25,13 @@ import {
19
25
  MANUAL_URL,
20
26
  PausedConversations,
21
27
  REPEATED_FAILED_CYCLES,
28
+ SETUP_GRACE_MS,
29
+ SETUP_STATES,
22
30
  SOCKET_STATES,
23
31
  STANDBY_MARKER_FRESH_MS,
32
+ STOPPED_REPORT_TIMEOUT_MS,
24
33
  TEXTS_CACHE_FILE,
34
+ VERIFY_STEP,
25
35
  acquireAgentLock,
26
36
  acquireLeaderLock,
27
37
  acquireLease,
@@ -32,6 +42,7 @@ import {
32
42
  alwaysOnOptedOut,
33
43
  alwaysOnState,
34
44
  alwaysOnWanted,
45
+ anchorIsCurrentAt,
35
46
  beat,
36
47
  bootedAt,
37
48
  checkManual,
@@ -39,31 +50,46 @@ import {
39
50
  clearAlwaysOnOptOut,
40
51
  clearAlwaysOnWanted,
41
52
  clearCredentials,
53
+ clearInstallId,
42
54
  clearIntegrationStatus,
43
55
  clearPending,
44
56
  clearStandby,
57
+ codeCommandOf,
58
+ codeMayWork,
45
59
  couldNotProcessPath,
46
60
  credentialsPath,
61
+ daemonPidOf,
47
62
  describeCouldNotProcessCounts,
63
+ describeIdentityBlock,
64
+ describeListenerStopped,
48
65
  describeManualSync,
49
66
  describePausedConversations,
67
+ ensureInstallId,
50
68
  envApiKey,
51
69
  envKeyConflict,
52
70
  external_exports,
53
71
  failedCyclesInARow,
54
72
  fetchIdentityLine,
55
73
  fetchServedTexts,
74
+ followIdentityAnchor,
56
75
  formatIntegrationStatus,
76
+ formatSetupVerdict,
57
77
  fromKitResult,
78
+ hasAnchorAt,
58
79
  holderLive,
80
+ identityBlockState,
59
81
  identityLineOf,
60
82
  idle,
83
+ installIdPath,
61
84
  integrationStatusAge,
62
85
  integrationStatusFresh,
63
86
  integrationStatusPath,
64
87
  integrationStatusStaleFor,
65
88
  isRunnerFactory,
89
+ isSetupOfferBody,
66
90
  leaseHolder,
91
+ listenerIdPath,
92
+ listenerReasonKindOf,
67
93
  loadTexts,
68
94
  manualFrontMatter,
69
95
  manualPointer,
@@ -72,29 +98,57 @@ import {
72
98
  markAlwaysOnOptOut,
73
99
  markAlwaysOnWanted,
74
100
  markStandby,
101
+ newInstallId,
102
+ newerRelease,
75
103
  normalizeHandle,
76
104
  parseLease,
77
105
  pendingPath,
78
106
  pidAlive,
107
+ placeAnchorAt,
108
+ reachabilityOf,
79
109
  readAlwaysOnInstalledVersion,
110
+ readAnchorHandleAt,
111
+ readAnchorHandleFrom,
80
112
  readCachedTexts,
81
113
  readCredentials,
114
+ readInstallId,
82
115
  readIntegrationStatus,
116
+ readListener,
117
+ readListenerInstanceId,
83
118
  readManualVersion,
84
119
  readPending,
120
+ readRememberedHost,
121
+ rememberHost,
122
+ removeAnchorAt,
123
+ renderAnchorBlock,
124
+ renderDeclinedBlock,
125
+ renderUnregisteredBlock,
85
126
  repeatedFailedRuns,
127
+ reportListenerStopped,
128
+ resendLeftS,
86
129
  resetLeaseObservations,
87
130
  resolveIdentity,
131
+ resolveManualPointer,
132
+ runLine,
88
133
  runtimeCheckFailingNow,
134
+ servedManualUrl,
135
+ serviceDryRun,
136
+ setupVerdict,
137
+ shellValue,
89
138
  standbyMarkerPath,
90
139
  standbyWaiting,
140
+ startCommandOf,
91
141
  statePath,
142
+ stripAnchorBlock,
92
143
  syncManual,
93
144
  textsCachePath,
145
+ upsertAnchorBlock,
146
+ writeAnchor,
94
147
  writeCredentials,
95
148
  writeIntegrationStatus,
149
+ writeOfferAt,
96
150
  writePending
97
- } from "./chunk-AQTRC7G4.js";
151
+ } from "./chunk-6GMYBMID.js";
98
152
  import {
99
153
  HOSTED_MCP_PATH,
100
154
  PROBE_KILL_WAIT_MS,
@@ -102,7 +156,7 @@ import {
102
156
  hostedMcpUrl,
103
157
  probeHostedMcp,
104
158
  runProbe
105
- } from "./chunk-4PCDVXAR.js";
159
+ } from "./chunk-WYBLSTYB.js";
106
160
  import {
107
161
  DEFAULT_RUN_BUDGET_MS,
108
162
  DEFAULT_RUN_PROFILE,
@@ -121,6 +175,8 @@ import {
121
175
  clientIdentityOf,
122
176
  clientNameOf,
123
177
  describeRunProfile,
178
+ hostIdentityOf,
179
+ installMethodOf,
124
180
  integrationDisabled,
125
181
  integrationDisabledBy,
126
182
  isRunProfile,
@@ -133,7 +189,7 @@ import {
133
189
  spawnCommand,
134
190
  spawnCommandSync,
135
191
  workdirExposesHome
136
- } from "./chunk-5KMQ23O6.js";
192
+ } from "./chunk-LPTOKVEE.js";
137
193
 
138
194
  // src/integration/tray.ts
139
195
  import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
@@ -179,201 +235,6 @@ function clearOfferDeclined(home) {
179
235
  writeState(home, state);
180
236
  }
181
237
 
182
- // src/anchor/block.ts
183
- import * as fs from "fs";
184
- import * as path from "path";
185
- import { integration as kit } from "agentchatme";
186
- var ANCHOR_START = kit.anchor.START_MARKER;
187
- var ANCHOR_END = kit.anchor.END_MARKER;
188
- var MARKER_LINES = /* @__PURE__ */ new Set([
189
- kit.anchor.START_MARKER,
190
- kit.anchor.END_MARKER,
191
- kit.anchor.LEGACY_START_MARKER,
192
- kit.anchor.LEGACY_END_MARKER
193
- ]);
194
- function renderAnchorBlock(identityLine, handle) {
195
- if (typeof identityLine !== "string" || identityLine.trim().length === 0) throw new Error("renderAnchorBlock: the identity line is empty");
196
- if (typeof handle !== "string" || kit.anchor.normalizeHandle(handle).length === 0) throw new Error("renderAnchorBlock: the handle is empty");
197
- if (identityLine.split(/\r?\n/).some((line) => MARKER_LINES.has(line.trim()))) {
198
- throw new Error("renderAnchorBlock: the identity line holds an AgentChat marker line");
199
- }
200
- return kit.anchor.render({ identity_line: identityLine, identity_line_template: "" }, handle);
201
- }
202
- function writeAnchor(filePath, block, expectHandle) {
203
- if (expectHandle !== void 0) {
204
- const bare = kit.anchor.normalizeHandle(expectHandle);
205
- const claimed = kit.anchor.find(block)?.handle ?? null;
206
- if (claimed !== bare) {
207
- throw new Error(`writeAnchor: the block for ${filePath} does not name @${bare} \u2014 nothing was written`);
208
- }
209
- }
210
- const existing = readInstructionFile(filePath) ?? { bom: "", text: "" };
211
- const next = untilStable(existing.text, (text) => kit.anchor.replace(text, block));
212
- if (next !== existing.text) writeInstructionFile(filePath, existing.bom + next);
213
- if (expectHandle !== void 0 && readInstructionFile(filePath)?.text !== next) {
214
- throw new Error(`writeAnchor: ${filePath} did not read back as written \u2014 remove the agentchat block manually and re-run`);
215
- }
216
- return "written";
217
- }
218
- function untilStable(text, step) {
219
- let current = text;
220
- for (let i = 0; i < 8; i++) {
221
- const next = step(current);
222
- if (next === current) return current;
223
- current = next;
224
- }
225
- return current;
226
- }
227
- function removeAnchorAt(filePath) {
228
- const existing = readInstructionFile(filePath);
229
- if (existing === null) return "noop";
230
- const next = untilStable(existing.text, (text) => kit.anchor.remove(text));
231
- if (next === existing.text) return "noop";
232
- writeInstructionFile(filePath, existing.bom + next);
233
- return "removed";
234
- }
235
- function hasAnchorAt(filePath) {
236
- const file = readInstructionFile(filePath);
237
- return file !== null && kit.anchor.find(file.text) !== null;
238
- }
239
- function anchorIsCurrentAt(filePath, identityLine, handle) {
240
- const file = readInstructionFile(filePath);
241
- if (file === null) return false;
242
- let expected;
243
- try {
244
- expected = renderAnchorBlock(identityLine, handle);
245
- } catch {
246
- return false;
247
- }
248
- if (kit.anchor.find(file.text) === null) return false;
249
- return kit.anchor.replace(file.text, expected) === file.text;
250
- }
251
- function readAnchorHandleAt(filePath, template) {
252
- const file = readInstructionFile(filePath);
253
- return file === null ? null : readAnchorHandleFrom(file.text, template);
254
- }
255
- function readAnchorHandleFrom(text, template) {
256
- return kit.anchor.find(text.replace(/^\uFEFF/, ""), { template })?.handle ?? null;
257
- }
258
- function upsertAnchorBlock(existing, block) {
259
- return kit.anchor.replace(existing, block);
260
- }
261
- function stripAnchorBlock(existing) {
262
- return kit.anchor.remove(existing);
263
- }
264
- var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
265
- function readInstructionFile(filePath) {
266
- let bytes;
267
- try {
268
- bytes = fs.readFileSync(filePath);
269
- } catch (err) {
270
- if (err.code === "ENOENT") return null;
271
- throw err;
272
- }
273
- let decoded;
274
- try {
275
- decoded = UTF8.decode(bytes);
276
- } catch {
277
- throw new Error(`${filePath} is not UTF-8 text; the AgentChat block is not read or written there (save the file as UTF-8 and run the command again)`);
278
- }
279
- return decoded.startsWith("\uFEFF") ? { bom: "\uFEFF", text: decoded.slice(1) } : { bom: "", text: decoded };
280
- }
281
- function resolveWriteTarget(filePath) {
282
- let current = filePath;
283
- for (let hops = 0; hops < 40; hops++) {
284
- let stat;
285
- try {
286
- stat = fs.lstatSync(current);
287
- } catch (err) {
288
- if (err.code === "ENOENT") return current;
289
- throw err;
290
- }
291
- if (!stat.isSymbolicLink()) return current;
292
- const link = fs.readlinkSync(current);
293
- const joined = path.isAbsolute(link) ? link : `${fs.realpathSync.native(path.dirname(current))}${path.sep}${link}`;
294
- current = path.join(fs.realpathSync.native(path.dirname(joined)), path.basename(joined));
295
- }
296
- throw Object.assign(new Error(`${filePath}: too many symbolic links`), { code: "ELOOP" });
297
- }
298
- var IN_PLACE_FALLBACK_CODES = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS", "EBUSY", "EXDEV"]);
299
- function stillWritable(file) {
300
- try {
301
- fs.accessSync(file, fs.constants.W_OK);
302
- return true;
303
- } catch {
304
- return false;
305
- }
306
- }
307
- function writeInstructionFile(filePath, data) {
308
- const target = resolveWriteTarget(filePath);
309
- let existing = null;
310
- try {
311
- existing = fs.statSync(target);
312
- } catch (err) {
313
- if (err.code !== "ENOENT") throw err;
314
- }
315
- if (existing !== null) {
316
- if (!existing.isFile()) throw new Error(`${filePath} is not a regular file`);
317
- fs.accessSync(target, fs.constants.W_OK);
318
- } else {
319
- fs.mkdirSync(path.dirname(target), { recursive: true });
320
- }
321
- try {
322
- atomicWriteFile(target, data, existing === null ? void 0 : existing.mode & 4095);
323
- } catch (err) {
324
- const code = err.code;
325
- if (existing !== null && code !== void 0 && IN_PLACE_FALLBACK_CODES.has(code) && stillWritable(target)) {
326
- fs.writeFileSync(target, data, "utf-8");
327
- return;
328
- }
329
- throw err;
330
- }
331
- if (existing !== null && typeof process.getuid === "function" && process.getuid() === 0 && (existing.uid !== 0 || existing.gid !== 0)) {
332
- try {
333
- fs.chownSync(target, existing.uid, existing.gid);
334
- } catch {
335
- }
336
- }
337
- }
338
-
339
- // src/anchor/offer.ts
340
- function renderUnregisteredBlock(copy) {
341
- const { invoke, label } = copy;
342
- return [
343
- ANCHOR_START,
344
- "## AgentChat is installed \u2014 this agent has no account yet",
345
- "",
346
- `[AgentChat](https://agentchat.me) gives you, the ${label} agent, a persistent \`@handle\` other AI agents can DM. AgentChat is installed for this ${label} agent, but it does not have an AgentChat account yet.`,
347
- "",
348
- "**Offer this ONCE, early, and only if it fits the conversation.** Never interrupt work in progress for it, and never raise it twice in one session.",
349
- "",
350
- `FIRST ask exactly: "Do you already have an AgentChat account for this ${label} agent, or should I create a new one?"`,
351
- "",
352
- "**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.",
353
- "",
354
- `- **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.`,
355
- `- **Existing account, with its API key:** ask the user to run \`${invoke} login\` in their own terminal and paste the key when it asks. Never ask them to paste the key into this conversation, and never put a key in a command you run: a command line is visible to every user of the machine.`,
356
- `- **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>\``,
357
- "- **When it is done:** tell the user the @handle and where the API key is stored, exactly as the command printed them.",
358
- "- Never reuse another active coding agent\u2019s account; each reachable agent needs its own.",
359
- "",
360
- `**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.`,
361
- ANCHOR_END
362
- ].join("\n");
363
- }
364
- function renderDeclinedBlock(copy) {
365
- const { invoke, label } = copy;
366
- return [
367
- ANCHOR_START,
368
- "## AgentChat",
369
- "",
370
- `AgentChat is installed for this ${label} agent, but no handle is configured and the user has said not for now. **Do not offer to set it up.** Mention it only if they ask about AgentChat or about messaging other agents.`,
371
- "",
372
- `If they ask to set it up later: ${invoke} register --email <email> --handle <handle>`,
373
- ANCHOR_END
374
- ].join("\n");
375
- }
376
-
377
238
  // src/integration/run-context.ts
378
239
  var RUN_CONTEXT_ENV = {
379
240
  wakeKind: "AGENTCHAT_WAKE_KIND",
@@ -395,10 +256,14 @@ function runContextEnv(env, request) {
395
256
  }
396
257
 
397
258
  // src/identity/commands.ts
259
+ import * as fs from "fs";
398
260
  import * as readline from "readline";
399
- import { AgentChatClient, integration as kit2 } from "agentchatme";
261
+ import { AgentChatClient, integration as kit } from "agentchatme";
400
262
 
401
263
  // src/identity/host-profile.ts
264
+ function placementReportOf(output) {
265
+ return Array.isArray(output) ? { lines: output, problem: null } : { lines: output.lines, problem: output.problem ?? null };
266
+ }
402
267
  function anchorLabelOf(profile) {
403
268
  if (profile.anchorLabel !== void 0) return profile.anchorLabel;
404
269
  if (profile.anchorFile === void 0) return "identity line";
@@ -407,6 +272,73 @@ function anchorLabelOf(profile) {
407
272
  return slash >= 0 ? file.slice(slash + 1) : file;
408
273
  }
409
274
 
275
+ // src/identity/telemetry.ts
276
+ import { clientIdentityHeaders, HttpTransport } from "agentchatme";
277
+ var TELEMETRY_ENV = "AGENTCHAT_TELEMETRY";
278
+ var TELEMETRY_PATH = "/v1/telemetry";
279
+ var TELEMETRY_VERSION = 1;
280
+ var TELEMETRY_TIMEOUT_MS = 1500;
281
+ function telemetryOff(env = process.env) {
282
+ const v = env[TELEMETRY_ENV]?.trim().toLowerCase();
283
+ return v === "off" || v === "0" || v === "false";
284
+ }
285
+ var REASON_SHAPE = /^[a-z][a-z0-9_]{0,31}$/;
286
+ function clampInt(value, min, max) {
287
+ if (!Number.isFinite(value)) return min;
288
+ return Math.min(max, Math.max(min, Math.round(value)));
289
+ }
290
+ function setupVerdictEvent(verdict, facts) {
291
+ const now = facts.now ?? Date.now();
292
+ const reason = verdict.reason;
293
+ return {
294
+ name: "setup_verdict",
295
+ at: new Date(now).toISOString(),
296
+ props: {
297
+ state: verdict.state,
298
+ command: facts.command,
299
+ needs_person: verdict.needs_person,
300
+ ...reason !== null && REASON_SHAPE.test(reason) ? { reason } : {},
301
+ exit_code: clampInt(facts.exitCode, 0, 255),
302
+ duration_ms: clampInt(now - facts.startedAt, 0, 6e5)
303
+ }
304
+ };
305
+ }
306
+ var httpTelemetrySender = async (request) => {
307
+ const transport = new HttpTransport({
308
+ baseUrl: request.apiBase,
309
+ defaultHeaders: clientIdentityHeaders(request.clientIdentity),
310
+ ...request.apiKey !== null ? { apiKey: request.apiKey } : {},
311
+ timeoutMs: TELEMETRY_TIMEOUT_MS,
312
+ retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 }
313
+ });
314
+ await transport.request("POST", TELEMETRY_PATH, { body: request.body, signal: request.signal });
315
+ };
316
+ async function sendSetupVerdict(verdict, opts) {
317
+ const env = opts.env ?? process.env;
318
+ if (telemetryOff(env)) return;
319
+ if (opts.apiKey === null && opts.clientIdentity.installId === void 0) return;
320
+ const sender = opts.sender ?? (serviceDryRun(env) ? null : httpTelemetrySender);
321
+ if (sender === null) return;
322
+ const controller = new AbortController();
323
+ const timeoutMs = opts.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
324
+ let timer;
325
+ try {
326
+ const body = { version: TELEMETRY_VERSION, events: [setupVerdictEvent(verdict, opts)] };
327
+ const sent = sender({ apiBase: opts.apiBase, apiKey: opts.apiKey, clientIdentity: opts.clientIdentity, body, signal: controller.signal }).catch(() => void 0);
328
+ const timedOut = new Promise((resolve2) => {
329
+ timer = setTimeout(() => {
330
+ controller.abort();
331
+ resolve2();
332
+ }, timeoutMs);
333
+ timer.unref?.();
334
+ });
335
+ await Promise.race([sent, timedOut]);
336
+ } catch {
337
+ } finally {
338
+ if (timer !== void 0) clearTimeout(timer);
339
+ }
340
+ }
341
+
410
342
  // src/identity/commands.ts
411
343
  var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
412
344
  function errorText(err) {
@@ -454,32 +386,6 @@ function handleInput(raw) {
454
386
  const handle = raw?.trim().replace(/^@/, "").toLowerCase();
455
387
  return handle ? handle : void 0;
456
388
  }
457
- var VERIFY_STEP = { register: "verify", recover: "recover_verify" };
458
- function shellValue(value) {
459
- return /^[A-Za-z0-9@%+=:,./_-]+$/.test(value) ? value : JSON.stringify(value);
460
- }
461
- function receivedAtMs(pending) {
462
- const at = Date.parse(pending.received_at);
463
- return Number.isFinite(at) ? at : null;
464
- }
465
- function codeMayWork(pending, now = Date.now()) {
466
- const received = receivedAtMs(pending);
467
- if (pending.flow.expires_in_s !== void 0 && received !== null) return received + pending.flow.expires_in_s * 1e3 > now;
468
- if (pending.flow.expires_at !== void 0) {
469
- const at = Date.parse(pending.flow.expires_at);
470
- if (Number.isFinite(at)) return at > now;
471
- }
472
- return true;
473
- }
474
- function resendLeftS(pending, now = Date.now()) {
475
- if (pending === null || pending.flow.resend_after_s === void 0) return 0;
476
- const received = receivedAtMs(pending);
477
- if (received === null) return 0;
478
- return Math.max(0, Math.ceil((pending.flow.resend_after_s * 1e3 - (now - received)) / 1e3));
479
- }
480
- function runLine(command, waitS = 0) {
481
- return waitS > 0 ? `Wait ${waitS} s, then run \`${command}\`` : `Run \`${command}\``;
482
- }
483
389
  async function askOnTerminal(question) {
484
390
  if (question.field === "new_code") {
485
391
  const answer2 = await prompt("Send a new code? [y/N] ");
@@ -492,40 +398,98 @@ async function askOnTerminal(question) {
492
398
  if (question.field === "code") return answer.toLowerCase() === "new" ? { answer: "new_code" } : { answer: "value", value: answer };
493
399
  return { answer: "value", value: (question.field === "handle" ? handleInput(answer) : emailInput(answer)) ?? "" };
494
400
  }
495
- 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.";
496
- function createIdentityCommands(profile) {
401
+ var SESSION_HINT = "Open a new session for the hosted AgentChat tools to pick up the key.";
402
+ var SETUP_WAIT_MS = 3e4;
403
+ var SETUP_POLL_MS = 500;
404
+ var REACHABILITY_RETRIES = 3;
405
+ var HOST_DEADLINE_MS = 3e3;
406
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, Math.max(0, ms)));
407
+ function createIdentityCommands(profile, options = {}) {
497
408
  const invocation = () => profile.invocation();
498
409
  const LABEL = profile.label;
499
- const clientIdentity = clientIdentityOf(profile.client);
410
+ let client = profile.client;
411
+ let prepared = null;
412
+ const clientIdentityNow = () => clientIdentityOf(client);
413
+ function prepareClient() {
414
+ prepared ??= (async () => {
415
+ const installId = telemetryOff() ? null : ensureInstallId(profile.home());
416
+ let host = null;
417
+ if (profile.host !== void 0) {
418
+ let timer;
419
+ try {
420
+ const late = new Promise((resolve2) => {
421
+ timer = setTimeout(() => resolve2(null), HOST_DEADLINE_MS);
422
+ timer.unref?.();
423
+ });
424
+ host = await Promise.race([Promise.resolve(profile.host()), late]);
425
+ } catch {
426
+ host = null;
427
+ } finally {
428
+ if (timer !== void 0) clearTimeout(timer);
429
+ }
430
+ }
431
+ if (host !== null && fs.existsSync(profile.home())) rememberHost(profile.home(), host);
432
+ client = { ...profile.client, ...installId !== null ? { installId } : {}, ...host !== null ? { host } : {} };
433
+ })();
434
+ return prepared;
435
+ }
436
+ let said = null;
437
+ function say(verdict) {
438
+ said = verdict;
439
+ return formatSetupVerdict(verdict);
440
+ }
441
+ async function reportSetup(opts) {
442
+ const verdict = said;
443
+ if (verdict === null) return;
444
+ said = null;
445
+ const identity = resolveIdentity(profile.home());
446
+ await sendSetupVerdict(verdict, {
447
+ ...opts,
448
+ apiBase: identity?.apiBase ?? process.env["AGENTCHAT_API_BASE"]?.trim() ?? DEFAULT_API_BASE,
449
+ apiKey: identity?.apiKey ?? null,
450
+ clientIdentity: clientIdentityNow(),
451
+ ...options.telemetrySender !== void 0 ? { sender: options.telemetrySender } : {}
452
+ });
453
+ }
454
+ function tracked(command, run2) {
455
+ return async (...args) => {
456
+ const startedAt = Date.now();
457
+ said = null;
458
+ await prepareClient();
459
+ const code = await run2(...args);
460
+ await reportSetup({ command, exitCode: code, startedAt });
461
+ return code;
462
+ };
463
+ }
500
464
  function envKeyRefusal() {
501
465
  const conflict = envKeyConflict(profile.home());
502
466
  if (conflict === null) return null;
503
467
  return `${conflict}. Unset AGENTCHAT_API_KEY, or, to sign this home in with that key on purpose: printenv AGENTCHAT_API_KEY | ${invocation()} login --api-key -`;
504
468
  }
505
- const apiClient = (apiKey, apiBase) => new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
506
- const accountOptions = (apiBase) => ({ clientIdentity, apiBase, timeoutMs: 15e3 });
469
+ const apiClient = (apiKey, apiBase) => new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity: clientIdentityNow(), timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
470
+ const accountOptions = (apiBase) => ({ clientIdentity: clientIdentityNow(), apiBase, timeoutMs: 15e3 });
507
471
  async function served(apiKey, apiBase) {
508
472
  const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5e3 });
509
473
  return loaded === null ? NO_TEXTS : contextOf(loaded.texts);
510
474
  }
511
- async function printExtraStatus(context) {
512
- if (profile.extraStatus === void 0) return;
475
+ async function extraStatusOf(context) {
476
+ if (profile.extraStatus === void 0) return { lines: [], problem: null };
513
477
  try {
514
- for (const line of await profile.extraStatus(context)) console.log(line);
478
+ return placementReportOf(await profile.extraStatus(context));
515
479
  } catch (err) {
516
- console.log(` (host status failed: ${err instanceof Error ? err.message : String(err)})`);
480
+ return { lines: [` (host status failed: ${err instanceof Error ? err.message : String(err)})`], problem: null };
517
481
  }
518
482
  }
519
483
  async function placeIdentity(handle, apiKey, apiBase) {
520
484
  const { identityLine, manual } = await served(apiKey, apiBase);
521
485
  if (profile.place !== void 0) {
522
486
  try {
523
- return await profile.place(handle, apiKey, identityLine, manual);
487
+ return placementReportOf(await profile.place(handle, apiKey, identityLine, manual));
524
488
  } catch (err) {
525
- return [` placement FAILED \u2014 ${String(err)}; repair with \`${invocation()} doctor --fix\``];
489
+ return { lines: [` placement FAILED \u2014 ${String(err)}; repair with \`${invocation()} doctor --fix\``], problem: null };
526
490
  }
527
491
  }
528
- return writeOurAnchor(handle, identityLine);
492
+ return { lines: writeOurAnchor(handle, identityLine), problem: null };
529
493
  }
530
494
  function writeOurAnchor(handle, identityLine) {
531
495
  if (profile.anchorFile === void 0) return [];
@@ -538,31 +502,129 @@ function createIdentityCommands(profile) {
538
502
  ` ${label}: identity line not written \u2014 GET /v1/texts could not be reached and nothing is cached; run \`${invocation()} doctor --fix\` once online`
539
503
  ];
540
504
  }
541
- writeAnchor(file, profile.renderAnchor(identityLine, handle), handle);
505
+ const placed = placeAnchorAt(file, { handle, identityLine, template: null, mode: "setup", fix: `${invocation()} doctor --fix` });
506
+ if (placed.outcome === "hand_edited" || placed.outcome === "several_blocks") return [` ${label}: WARNING \u2014 ${placed.detail}`];
507
+ if (placed.outcome === "failed") return [` ${label}: FAILED \u2014 ${placed.detail}`];
508
+ if (placed.outcome === "replaced_other") return [` ${label}: ${placed.detail}`];
542
509
  return [` ${label}: @${handle} \u2192 ${file}`];
543
510
  } catch (err) {
544
511
  return [` ${label}: FAILED \u2014 ${String(err)}`];
545
512
  }
546
513
  }
547
514
  function startCommand(kind, input, blank) {
548
- const email = blank === "email" ? "<email>" : shellValue(input.email);
549
- const handle = blank === "handle" ? "<handle>" : input.handle !== void 0 ? shellValue(input.handle) : null;
550
- if (kind === "recover") return `${invocation()} recover${handle !== null ? ` --handle ${handle}` : ""} --email ${email}`;
551
- return [
552
- `${invocation()} register --email ${email} --handle ${handle ?? "<handle>"}`,
553
- ...input.display_name !== void 0 ? [`--display-name ${shellValue(input.display_name)}`] : [],
554
- ...input.description !== void 0 ? [`--description ${shellValue(input.description)}`] : []
555
- ].join(" ");
515
+ return startCommandOf(invocation(), kind, input, blank);
556
516
  }
557
517
  function codeCommand(kind, flow, code) {
558
- const value = code !== void 0 ? shellValue(code) : flow.code_length !== void 0 ? `<${flow.code_length} digits>` : "<code>";
559
- return `${invocation()} ${kind} --code ${value}`;
518
+ return codeCommandOf(invocation(), kind, flow, code);
519
+ }
520
+ function verdictBase() {
521
+ return { invocation: invocation(), label: LABEL, version: profile.client.version, home: profile.home() };
522
+ }
523
+ async function ensureListenerOnce() {
524
+ if (profile.ensureListener === void 0) return null;
525
+ if (alwaysOnOptedOut(profile.home())) return { outcome: "opted_out", detail: null };
526
+ try {
527
+ return await profile.ensureListener();
528
+ } catch (err) {
529
+ return { outcome: "failed", detail: errorText(err) };
530
+ }
531
+ }
532
+ function listenerLine(ensure) {
533
+ switch (ensure.outcome) {
534
+ case "installed":
535
+ return ` listener: registered${ensure.detail ? ` (${ensure.detail})` : ""}`;
536
+ case "current":
537
+ return ` listener: already registered${ensure.detail ? ` (${ensure.detail})` : ""}`;
538
+ case "opted_out":
539
+ return ` listener: off \u2014 switched off by the person you work with (\`${invocation()} daemon install\` turns it on)`;
540
+ case "failed":
541
+ return ` listener: FAILED \u2014 ${ensure.detail ?? "no reason given"}`;
542
+ }
543
+ }
544
+ function serverViewOfError(err) {
545
+ const status = httpStatusOf(err);
546
+ const code = err?.code;
547
+ const detail = describeApiError(err);
548
+ if (status === 403 && code === "SUSPENDED") return { kind: "suspended", detail };
549
+ if (status === 401 || status === 403) return { kind: "refused", detail };
550
+ return { kind: "unreachable", detail };
551
+ }
552
+ function listenerSettled(r) {
553
+ const d = r.daemon;
554
+ if (d.kind === "start_failure") return listenerReasonKindOf(d.detail) !== "other";
555
+ return r.optedOut || d.kind === "ready" || d.kind === "standby" || d.kind === "unservable" || d.kind === "off" || d.kind === "blocked";
556
+ }
557
+ async function waitForListener(handle, replacedPid) {
558
+ const home = profile.home();
559
+ const read = () => readListener(home, handle, { replacedPid });
560
+ const budget = options.setupWaitMs ?? SETUP_WAIT_MS;
561
+ const poll = options.setupPollMs ?? SETUP_POLL_MS;
562
+ const started = Date.now();
563
+ console.log(`Waiting up to ${Math.round(budget / 1e3)} s for the listener to connect as @${handle}\u2026`);
564
+ let reading = read();
565
+ while (!listenerSettled(reading) && Date.now() - started < budget) {
566
+ await sleep(Math.min(poll, budget - (Date.now() - started)));
567
+ reading = read();
568
+ }
569
+ const took = `${Math.max(1, Math.ceil((Date.now() - started) / 1e3))} s`;
570
+ const kind = reading.daemon.kind;
571
+ console.log(
572
+ kind === "ready" ? ` listener: connected after ${took}` : kind === "standby" ? ` listener: another listener on this computer serves @${handle} (after ${took})` : listenerSettled(reading) ? ` listener: not connected (after ${took})` : ` listener: not connected after ${Math.round(budget / 1e3)} s`
573
+ );
574
+ return reading;
575
+ }
576
+ async function confirm(opts) {
577
+ const home = profile.home();
578
+ const identity = resolveIdentity(home);
579
+ const pending = readPending(home);
580
+ const base = { ...verdictBase(), pending, ensure: opts.ensure, tools: opts.tools, afterSignIn: opts.afterSignIn };
581
+ if (identity === null) {
582
+ const verdict2 = setupVerdict({ ...base, identity: null, server: null, listener: null });
583
+ if (verdict2 !== null) console.log(say(verdict2));
584
+ return verdict2;
585
+ }
586
+ const hasListener = profile.ensureListener !== void 0;
587
+ if (!hasListener && opts.tools === null && opts.afterSignIn) return null;
588
+ const registered = opts.ensure?.outcome === "installed" || opts.ensure?.outcome === "current";
589
+ const canWait = hasListener && identity.handle !== null && opts.tools === null && registered && !(options.serviceDryRun ?? serviceDryRun());
590
+ const replacedPid = opts.ensure?.outcome === "installed" ? opts.replacedPid ?? null : null;
591
+ const readOpts = { replacedPid };
592
+ let reading = hasListener ? canWait ? await waitForListener(identity.handle, replacedPid) : readListener(home, identity.handle, readOpts) : null;
593
+ let verdict = null;
594
+ for (let attempt = 0; ; attempt++) {
595
+ let server;
596
+ try {
597
+ const me = await apiClient(identity.apiKey, identity.apiBase).getMe();
598
+ server = { kind: "ok", handle: me.handle, reachability: reachabilityOf(me) };
599
+ } catch (err) {
600
+ server = opts.afterSignIn ? { kind: "ok", handle: identity.handle ?? "?", reachability: null } : serverViewOfError(err);
601
+ }
602
+ if (hasListener && server.kind === "ok" && server.handle !== identity.handle) reading = readListener(home, server.handle, readOpts);
603
+ verdict = setupVerdict({ ...base, identity: { handle: identity.handle, source: identity.source }, server, listener: reading });
604
+ if (!(canWait && verdict?.state === "listener_starting" && reading?.daemon.kind === "ready" && attempt < REACHABILITY_RETRIES)) break;
605
+ await sleep(1e3);
606
+ }
607
+ if (verdict !== null) console.log(say(verdict));
608
+ return verdict;
609
+ }
610
+ async function placeListener(tools) {
611
+ const replacedPid = daemonPidOf(profile.home());
612
+ if (profile.ensureListener === void 0) return { ensure: null, lines: [], replacedPid };
613
+ if (tools !== null) return { ensure: null, lines: [" listener: not registered until the AgentChat tools are in place (below)"], replacedPid };
614
+ const ensure = await ensureListenerOnce();
615
+ return { ensure, lines: ensure !== null ? [listenerLine(ensure)] : [], replacedPid };
616
+ }
617
+ async function confirmSetup(opts = {}) {
618
+ await prepareClient();
619
+ return confirm({ ensure: opts.ensure ?? null, tools: opts.tools ?? null, afterSignIn: false, replacedPid: opts.replacedPid ?? null });
560
620
  }
561
621
  function nextSteps(kind, result, called, input, code, held) {
562
622
  const beforeNewCode = Math.max(result.flow.retry_after_s ?? 0, result.flow.resend_after_s ?? resendLeftS(held));
563
623
  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)}\``] : [];
564
624
  switch (result.action) {
565
625
  case "done":
626
+ // A connector sign-up's answer (SDK 1.10+); these commands never start one. The server's sentence is all there is to say.
627
+ case "connect":
566
628
  return [];
567
629
  case "ask_code":
568
630
  return [runLine(codeCommand(kind, result.flow))];
@@ -582,11 +644,14 @@ function createIdentityCommands(profile) {
582
644
  }
583
645
  case "stop":
584
646
  return heldCode;
647
+ // A connector sign-in's last answer (a flow started with `finish: "connector"`): this package never starts one, so there is nothing to run next.
648
+ case "connect":
649
+ return [];
585
650
  }
586
651
  }
587
652
  function report(result, lines, ok) {
588
- const said = result.message.length > 0 ? result.message : result.code ?? `HTTP ${result.httpStatus}`;
589
- const text = [said, ...lines].join("\n");
653
+ const said2 = result.message.length > 0 ? result.message : result.code ?? `HTTP ${result.httpStatus}`;
654
+ const text = [said2, ...lines].join("\n");
590
655
  if (ok) console.log(text);
591
656
  else console.error(text);
592
657
  return ok ? 0 : 1;
@@ -602,15 +667,19 @@ function createIdentityCommands(profile) {
602
667
  clearPending(home);
603
668
  clearOfferDeclined(home);
604
669
  const placed = await placeIdentity(handle, apiKey, apiBase);
670
+ const listener = await placeListener(placed.problem);
671
+ const hint = profile.ensureListener === void 0 ? [SESSION_HINT] : [];
605
672
  const lines = kind === "register" ? [
606
673
  `API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`,
607
- ...placed,
674
+ ...placed.lines,
675
+ ...listener.lines,
608
676
  "",
609
677
  `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.`,
610
678
  `Other agents can DM you at @${handle}. Check \`${invocation()} status\` any time.`,
611
- NEXT_HINT
612
- ] : [`New API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`, ...placed, NEXT_HINT];
679
+ ...hint
680
+ ] : [`New API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`, ...placed.lines, ...listener.lines, ...hint];
613
681
  console.log([...message !== null && message.length > 0 ? [message] : [], ...lines].join("\n"));
682
+ await confirm({ ensure: listener.ensure, tools: placed.problem, afterSignIn: true, replacedPid: listener.replacedPid });
614
683
  return 0;
615
684
  }
616
685
  async function startSignup(kind, input, apiBase) {
@@ -619,7 +688,7 @@ function createIdentityCommands(profile) {
619
688
  const held = before !== null && before.kind === kind && before.email === input.email ? before : null;
620
689
  let result;
621
690
  try {
622
- result = kind === "register" ? await kit2.account.start(
691
+ result = kind === "register" ? await kit.account.start(
623
692
  "register",
624
693
  {
625
694
  email: input.email,
@@ -628,7 +697,7 @@ function createIdentityCommands(profile) {
628
697
  ...input.description !== void 0 ? { description: input.description } : {}
629
698
  },
630
699
  accountOptions(apiBase)
631
- ) : await kit2.account.start(
700
+ ) : await kit.account.start(
632
701
  "recover",
633
702
  { email: input.email, ...input.handle !== void 0 ? { handle: input.handle } : {} },
634
703
  accountOptions(apiBase)
@@ -639,15 +708,18 @@ ${runLine(startCommand(kind, input))} again.`);
639
708
  return 1;
640
709
  }
641
710
  if (result.action === "ask_code") {
642
- writePending(home, {
711
+ const pending = {
643
712
  kind,
644
713
  flow: result.flow,
645
714
  received_at: (/* @__PURE__ */ new Date()).toISOString(),
646
715
  ...input,
647
716
  ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}
648
- });
717
+ };
718
+ writePending(home, pending);
719
+ const verdict = setupVerdict({ ...verdictBase(), identity: null, pending, server: null, listener: null });
720
+ return report(result, verdict?.state === "code_pending" ? [say(verdict)] : nextSteps(kind, result, "start", input, void 0, held), true);
649
721
  }
650
- return report(result, nextSteps(kind, result, "start", input, void 0, held), result.action === "ask_code");
722
+ return report(result, nextSteps(kind, result, "start", input, void 0, held), false);
651
723
  }
652
724
  async function submitPendingCode(kind, rawCode, apiBase) {
653
725
  const home = profile.home();
@@ -674,7 +746,7 @@ ${runLine(startCommand(kind, input))} again.`);
674
746
  const base = pending.api_base ?? apiBase;
675
747
  let result;
676
748
  try {
677
- result = await kit2.account.submitCode(pending.flow, code, accountOptions(base));
749
+ result = await kit.account.submitCode(pending.flow, code, accountOptions(base));
678
750
  } catch (err) {
679
751
  console.error(`Could not reach AgentChat: ${errorText(err)}
680
752
  ${runLine(codeCommand(kind, pending.flow, code))} again.`);
@@ -698,7 +770,7 @@ ${runLine(codeCommand(kind, pending.flow, code))} again.`);
698
770
  async function converse(kind, input, apiBase) {
699
771
  let outcome;
700
772
  try {
701
- outcome = await kit2.account.run({
773
+ outcome = await kit.account.run({
702
774
  kind,
703
775
  input,
704
776
  ...accountOptions(apiBase),
@@ -764,7 +836,7 @@ login does not adopt an exported key in place of the one this home holds; nothin
764
836
  console.log("Using the key from AGENTCHAT_API_KEY.");
765
837
  } else if (process.stdin.isTTY !== true) {
766
838
  console.error(
767
- `Missing API key. Run \`${invocation()} login\` in a terminal and paste the key when it asks, or pipe it in from a file: \`${invocation()} login --api-key - < key.txt\`. Never put the key itself on a command line: \`ps\` and shell history can see it there.`
839
+ `Missing API key. If an AgentChat answer gave you the key, write it alone into a file with your file-editing tool; if the person you work with holds it, ask them to save it into a file and tell you where (never to paste it into a conversation). Then run \`${invocation()} login --api-key - < <that file>\` and delete the file. A person at a terminal can run \`${invocation()} login\` and paste it when it asks. Never put the key itself on a command line: \`ps\` and shell history can see it there.`
768
840
  );
769
841
  return 1;
770
842
  } else {
@@ -777,7 +849,7 @@ login does not adopt an exported key in place of the one this home holds; nothin
777
849
  }
778
850
  let check;
779
851
  try {
780
- check = await kit2.account.checkKey(apiKey, accountOptions(apiBase));
852
+ check = await kit.account.checkKey(apiKey, accountOptions(apiBase));
781
853
  } catch (err) {
782
854
  console.error(`Login failed: ${errorText(err)}
783
855
  The key was not saved.`);
@@ -795,17 +867,21 @@ The key was not saved.`);
795
867
  created_at: (/* @__PURE__ */ new Date()).toISOString()
796
868
  });
797
869
  clearOfferDeclined(home);
870
+ const placed = await placeIdentity(check.handle, apiKey, apiBase);
871
+ const listener = await placeListener(placed.problem);
798
872
  console.log(
799
873
  [
800
874
  `Signed in as @${check.handle} for ${LABEL}.`,
801
875
  `API key stored at ${credentialsPath(home)} (never commit this file).`,
802
- ...await placeIdentity(check.handle, apiKey, apiBase),
803
- NEXT_HINT,
876
+ ...placed.lines,
877
+ ...listener.lines,
878
+ ...profile.ensureListener === void 0 ? [SESSION_HINT] : [],
804
879
  ...onArgv ? [
805
- `Note: the key was on this command line, where \`ps\` and shell history can see it. Next time run \`${invocation()} login\` and paste it, or pipe it in: \`${invocation()} login --api-key - < key.txt\`.`
880
+ `Note: the key was on this command line, where \`ps\` and shell history can see it. Next time write it into a file with your file-editing tool and pipe it in: \`${invocation()} login --api-key - < <that file>\` (or run \`${invocation()} login\` in a terminal and paste it).`
806
881
  ] : []
807
882
  ].join("\n")
808
883
  );
884
+ await confirm({ ensure: listener.ensure, tools: placed.problem, afterSignIn: true, replacedPid: listener.replacedPid });
809
885
  return 0;
810
886
  }
811
887
  async function runRecover(opts) {
@@ -831,15 +907,37 @@ The key was not saved.`);
831
907
  }
832
908
  return startSignup("recover", { email, ...handle !== void 0 ? { handle } : {} }, apiBase);
833
909
  }
834
- function anchorView(file, identityLine, handle) {
835
- if (file === null) return { present: null, current: null, error: null };
910
+ function loadNoteFor(handle, texts) {
836
911
  try {
837
- const present = hasAnchorAt(file);
838
- const current = identityLine === null || handle === null ? null : anchorIsCurrentAt(file, identityLine, handle);
839
- return { present, current, error: null };
840
- } catch (err) {
841
- return { present: null, current: null, error: errorText(err) };
912
+ return profile.anchorLoadNote?.(handle, { identityLine: texts.identityLine, template: texts.identityLineTemplate }) ?? null;
913
+ } catch {
914
+ return null;
915
+ }
916
+ }
917
+ function anchorView(file, texts, handle) {
918
+ if (file === null) return { present: null, current: null, error: null, state: null };
919
+ if (handle === null) {
920
+ try {
921
+ return { present: hasAnchorAt(file), current: null, error: null, state: null };
922
+ } catch (err) {
923
+ return { present: null, current: null, error: errorText(err), state: null };
924
+ }
842
925
  }
926
+ const state = identityBlockState(file, { handle, identityLine: texts.identityLine, template: texts.identityLineTemplate, loadNote: loadNoteFor(handle, texts) });
927
+ if (state.state === "unreadable") return { present: null, current: null, error: state.what.replace(/^cannot read [^:]*: /, ""), state };
928
+ return {
929
+ present: state.state !== "missing",
930
+ current: texts.identityLine === null ? null : state.state === "current",
931
+ error: null,
932
+ state
933
+ };
934
+ }
935
+ function anchorWords(file, view) {
936
+ if (view.error !== null) return `unreadable \u2014 ${view.error} (${file})`;
937
+ const state = view.state;
938
+ if (state === null) return `${view.present ? "present" : "missing"} (${file})`;
939
+ if (state.verdict === "PASS") return `current (${file})${state.loadNote !== null ? `; ${state.loadNote.note}` : ""}`;
940
+ return describeIdentityBlock(state, `${invocation()} doctor --fix`);
843
941
  }
844
942
  async function runStatus(opts) {
845
943
  const home = profile.home();
@@ -853,7 +951,9 @@ The key was not saved.`);
853
951
  const identity = resolveIdentity(home);
854
952
  const pending = readPending(home);
855
953
  const integration = readIntegrationStatus(home);
954
+ const listenerOf = (handle) => profile.ensureListener !== void 0 ? readListener(home, handle) : null;
856
955
  if (identity === null) {
956
+ const setup2 = setupVerdict({ ...verdictBase(), identity: null, pending, server: null, listener: null });
857
957
  if (opts.json) {
858
958
  console.log(
859
959
  JSON.stringify({
@@ -861,29 +961,28 @@ The key was not saved.`);
861
961
  host: profile.id,
862
962
  pending: pending !== null,
863
963
  pending_kind: pending?.kind ?? null,
864
- integration
964
+ integration,
965
+ setup: setup2
865
966
  })
866
967
  );
867
- } else if (pending !== null) {
868
- const what = pending.kind === "recover" ? `an account recovery${pending.handle !== void 0 ? ` for @${pending.handle}` : ""}` : `a registration for @${pending.handle ?? "?"}`;
869
- console.log(
870
- 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)}`
871
- );
872
- } else {
873
- console.log(`No AgentChat identity for this ${LABEL} agent. Set one up with: ${invocation()} register`);
968
+ if (setup2 !== null) say(setup2);
969
+ } else if (setup2 !== null) {
970
+ console.log(say(setup2));
874
971
  }
875
972
  return 0;
876
973
  }
877
974
  let me;
878
- const client = apiClient(identity.apiKey, identity.apiBase);
975
+ const client2 = apiClient(identity.apiKey, identity.apiBase);
879
976
  try {
880
- me = await client.getMe();
977
+ me = await client2.getMe();
881
978
  } catch (err) {
882
979
  const status = httpStatusOf(err);
883
980
  const refused = status === 401 || status === 403;
884
981
  const detail = describeApiError(err);
982
+ const server = serverViewOfError(err);
983
+ const setup2 = setupVerdict({ ...verdictBase(), identity: { handle: identity.handle, source: identity.source }, pending, server, listener: listenerOf(identity.handle) });
885
984
  if (opts.json) {
886
- const offline = anchorView(anchorFile, null, null);
985
+ const offline = anchorView(anchorFile, NO_TEXTS, null);
887
986
  console.log(
888
987
  JSON.stringify({
889
988
  configured: true,
@@ -895,30 +994,42 @@ The key was not saved.`);
895
994
  home,
896
995
  anchor: offline.present,
897
996
  anchor_error: offline.error,
898
- integration
997
+ integration,
998
+ setup: setup2
899
999
  })
900
1000
  );
1001
+ if (setup2 !== null) say(setup2);
901
1002
  } else {
902
- console.error(
903
- refused ? `AgentChat refused this agent's key (${detail}). Sign in with a current key: \`${invocation()} login\`; lost it? \`${recoverUsage(invocation())}\`.` : `Could not reach AgentChat: ${detail}`
904
- );
1003
+ const cached = readCachedTexts(home, profile.client.runtime);
1004
+ const context = cached === null ? NO_TEXTS : contextOf(cached.texts);
1005
+ const extra2 = await extraStatusOf(context);
905
1006
  console.log(
906
1007
  [
1008
+ // First: what this means and what to do (a refused key is not an unreachable server).
1009
+ ...setup2 !== null ? [say(setup2)] : [],
907
1010
  `${identity.handle !== null ? `@${identity.handle}` : "This agent"} \u2014 ${refused ? `key refused (HTTP ${status})` : "AgentChat unreachable"} (${LABEL})`,
908
1011
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
909
1012
  `API: ${identity.apiBase}`,
910
- ...formatIntegrationStatus(integration)
1013
+ ...anchorFile === null ? [] : [`Identity line: ${anchorWords(anchorFile, anchorView(anchorFile, context, identity.handle))}`],
1014
+ ...formatIntegrationStatus(integration),
1015
+ ...extra2.lines
911
1016
  ].join("\n")
912
1017
  );
913
- const cached = readCachedTexts(home, profile.client.runtime);
914
- await printExtraStatus(cached === null ? NO_TEXTS : contextOf(cached.texts));
915
1018
  }
916
1019
  return 1;
917
1020
  }
918
- const tray = await traySummary(client).catch(() => null);
1021
+ const tray = await traySummary(client2).catch(() => null);
919
1022
  const texts = await served(identity.apiKey, identity.apiBase);
920
- const identityLine = texts.identityLine;
921
- const anchor = anchorView(anchorFile, identityLine, me.handle);
1023
+ const anchor = anchorView(anchorFile, texts, me.handle);
1024
+ const extra = await extraStatusOf(texts);
1025
+ const setup = setupVerdict({
1026
+ ...verdictBase(),
1027
+ identity: { handle: identity.handle, source: identity.source },
1028
+ pending,
1029
+ server: { kind: "ok", handle: me.handle, reachability: reachabilityOf(me) },
1030
+ listener: listenerOf(me.handle),
1031
+ tools: extra.problem
1032
+ });
922
1033
  if (opts.json) {
923
1034
  console.log(
924
1035
  JSON.stringify({
@@ -935,42 +1046,62 @@ The key was not saved.`);
935
1046
  anchor_current: anchor.current,
936
1047
  /** Why the instruction file could not be read, or null. */
937
1048
  anchor_error: anchor.error,
938
- integration
1049
+ /** The block as the daemon reads it (`identityBlockState`: current, stale, missing, setup_offer, hand_edited, other_agent, several_blocks, unreadable), or null. */
1050
+ anchor_state: anchor.state?.state ?? null,
1051
+ /** Why the runtime does not load the instruction file now, or null. */
1052
+ anchor_not_loaded: anchor.state?.notLoaded ?? null,
1053
+ integration,
1054
+ /** Whether setup is done and what is left (`setupVerdict`); null when this host has nothing to judge. */
1055
+ setup
939
1056
  })
940
1057
  );
1058
+ if (setup !== null) say(setup);
941
1059
  } else {
942
1060
  const trayLine = tray === null ? "Tray: could not be read" : `Tray: ${tray.waiting}${tray.truncated ? "+" : ""} conversation(s) waiting${tray.deferred > 0 ? `, ${tray.deferred} deferred` : ""}`;
943
1061
  console.log(
944
1062
  [
1063
+ ...setup !== null ? [say(setup)] : [],
945
1064
  `@${me.handle} \u2014 ${me.status ?? "active"} (${LABEL})`,
946
1065
  trayLine,
947
1066
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
948
1067
  `API: ${identity.apiBase}`,
949
1068
  ...anchorFile === null ? [] : [
950
- `Identity line: ${anchor.error !== null ? `unreadable \u2014 ${anchor.error}` : anchor.present ? anchor.current === null ? "present (served texts unavailable \u2014 not checked)" : anchor.current ? "current" : "present (older text \u2014 `doctor --fix` refreshes it)" : "missing"} (${anchorFile})`
1069
+ `Identity line: ${anchorWords(anchorFile, anchor)}`
951
1070
  ],
952
- ...formatIntegrationStatus(integration)
1071
+ ...formatIntegrationStatus(integration),
1072
+ ...extra.lines
953
1073
  ].join("\n")
954
1074
  );
955
- await printExtraStatus(texts);
956
1075
  }
957
1076
  return 0;
958
1077
  }
959
- function runLogout() {
1078
+ async function runLogout() {
960
1079
  const home = profile.home();
961
1080
  const anchorFile = profile.anchorFile?.() ?? null;
962
1081
  const reports = [];
963
1082
  let any = false;
964
1083
  const identity = resolveIdentity(home);
1084
+ const stopped = await reportListenerStopped({ home, client: profile.client, identity });
1085
+ const stoppedLine = describeListenerStopped(stopped);
1086
+ if (stoppedLine !== null) reports.push(` ${stoppedLine}`);
965
1087
  if (clearCredentials(home)) {
966
1088
  any = true;
967
1089
  reports.push(" credentials deleted");
968
1090
  }
969
1091
  if (anchorFile !== null) {
970
1092
  try {
971
- if (removeAnchorAt(anchorFile) === "removed") {
1093
+ const cached = readCachedTexts(home, profile.client.runtime);
1094
+ const removed = removeAnchorAt(anchorFile, {
1095
+ handle: identity?.handle ?? null,
1096
+ identityLine: cached?.texts.identity_line ?? null,
1097
+ template: cached?.texts.identity_line_template ?? null
1098
+ });
1099
+ if (removed.action === "removed") {
972
1100
  any = true;
973
1101
  reports.push(` ${anchorLabelOf(profile)} identity line removed`);
1102
+ } else if (removed.action === "kept") {
1103
+ any = true;
1104
+ reports.push(` ${removed.detail}`);
974
1105
  }
975
1106
  } catch (err) {
976
1107
  any = true;
@@ -999,41 +1130,25 @@ The key was not saved.`);
999
1130
  return 0;
1000
1131
  }
1001
1132
  function readIdentityLine(anchorFile, handle, texts) {
1002
- const claimed = readAnchorHandleAt(anchorFile, texts.identityLineTemplate);
1003
- const current = texts.identityLine === null ? null : anchorIsCurrentAt(anchorFile, texts.identityLine, handle);
1004
- return { claimed, current };
1133
+ return identityBlockState(anchorFile, { handle, identityLine: texts.identityLine, template: texts.identityLineTemplate, loadNote: loadNoteFor(handle, texts) });
1005
1134
  }
1006
1135
  async function identityLineCheck(anchorFile, creds, apiBase, texts, fix) {
1007
- let claimed;
1008
- let current;
1009
- try {
1010
- ;
1011
- ({ claimed, current } = readIdentityLine(anchorFile, creds.handle, texts));
1012
- } catch (err) {
1013
- return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile}: ${errorText(err)}` };
1014
- }
1015
- if (claimed === creds.handle && current === true) {
1016
- return { name: "identity-line", verdict: "PASS", detail: `@${claimed} in ${anchorFile}` };
1017
- }
1018
- if (claimed === creds.handle && current === null) {
1019
- return { name: "identity-line", verdict: "WARN", detail: `@${claimed} in ${anchorFile} (currency not checked: served texts unavailable)` };
1020
- }
1021
- 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}`;
1022
- if (fix) {
1023
- const report2 = await placeIdentity(creds.handle, creds.api_key, apiBase);
1136
+ const fixCommand = `${invocation()} doctor --fix`;
1137
+ const before = readIdentityLine(anchorFile, creds.handle, texts);
1138
+ if (before.state === "unreadable") return { name: "identity-line", verdict: "FAIL", detail: before.what };
1139
+ const repairable = before.state === "missing" || before.state === "setup_offer" || before.state === "stale";
1140
+ if (fix && repairable) {
1141
+ const report2 = (await placeIdentity(creds.handle, creds.api_key, apiBase)).lines;
1024
1142
  const failed = report2.some((l) => l.includes("FAILED") || l.includes("not written"));
1025
1143
  if (failed) return { name: "identity-line", verdict: "FAIL", detail: `could not repair: ${report2.join("; ")}` };
1026
- try {
1027
- const after = readIdentityLine(anchorFile, creds.handle, texts);
1028
- if (after.claimed === creds.handle && after.current !== false) {
1029
- return { name: "identity-line", verdict: "PASS", detail: `repaired \u2192 @${creds.handle}` };
1030
- }
1031
- 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()})` : ""}` };
1032
- } catch (err) {
1033
- return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile} after the repair: ${errorText(err)}` };
1144
+ const after = readIdentityLine(anchorFile, creds.handle, texts);
1145
+ if (after.state === "current") {
1146
+ return { name: "identity-line", verdict: after.verdict, detail: after.loadNote === null ? `repaired \u2192 @${creds.handle}` : `repaired \u2192 @${creds.handle} in ${anchorFile}; ${after.loadNote.note}` };
1034
1147
  }
1148
+ if (after.state === "unreadable") return { name: "identity-line", verdict: "FAIL", detail: `${after.what} (after the repair)` };
1149
+ return { name: "identity-line", verdict: "FAIL", detail: `repair did not take: ${after.what}${report2.length > 0 ? ` (${report2.join("; ").trim()})` : ""}` };
1035
1150
  }
1036
- return { name: "identity-line", verdict: "WARN", detail: `${why} \u2014 repair with \`${invocation()} doctor --fix\`` };
1151
+ return { name: "identity-line", verdict: before.verdict, detail: describeIdentityBlock(before, fixCommand) };
1037
1152
  }
1038
1153
  async function runDoctor(opts = {}) {
1039
1154
  const home = profile.home();
@@ -1045,6 +1160,7 @@ The key was not saved.`);
1045
1160
  const refusal = envKeyRefusal();
1046
1161
  if (refusal !== null) checks.push({ name: "env-key", verdict: "FAIL", detail: refusal });
1047
1162
  const creds = readCredentials(home);
1163
+ let server = null;
1048
1164
  if (creds === null) {
1049
1165
  checks.push({
1050
1166
  name: "credentials",
@@ -1056,9 +1172,10 @@ The key was not saved.`);
1056
1172
  const identity = resolveIdentity(home);
1057
1173
  if (identity !== null) {
1058
1174
  try {
1059
- const client = apiClient(identity.apiKey, identity.apiBase);
1175
+ const client2 = apiClient(identity.apiKey, identity.apiBase);
1060
1176
  const started = Date.now();
1061
- const me = await client.getMe();
1177
+ const me = await client2.getMe();
1178
+ server = { kind: "ok", handle: me.handle, reachability: reachabilityOf(me) };
1062
1179
  const verdict = (me.status ?? "active") === "active" ? "PASS" : "WARN";
1063
1180
  checks.push({
1064
1181
  name: "api-auth",
@@ -1073,6 +1190,7 @@ The key was not saved.`);
1073
1190
  });
1074
1191
  }
1075
1192
  } catch (err) {
1193
+ server = serverViewOfError(err);
1076
1194
  checks.push({ name: "api-auth", verdict: "FAIL", detail: `getMe failed: ${String(err)}` });
1077
1195
  }
1078
1196
  }
@@ -1083,6 +1201,14 @@ The key was not saved.`);
1083
1201
  );
1084
1202
  if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true));
1085
1203
  }
1204
+ let ensure = null;
1205
+ if (opts.fix === true && profile.ensureListener !== void 0) {
1206
+ ensure = await ensureListenerOnce();
1207
+ if (ensure?.outcome === "installed") checks.push({ name: "listener", verdict: "PASS", detail: `registered${ensure.detail ? ` (${ensure.detail})` : ""}` });
1208
+ else if (ensure?.outcome === "failed") {
1209
+ checks.push({ name: "listener", verdict: "FAIL", detail: `could not be registered: ${ensure.detail ?? "no reason given"} \u2014 \`${invocation()} daemon install\` tries again` });
1210
+ }
1211
+ }
1086
1212
  const integration = readIntegrationStatus(home);
1087
1213
  const runsFailing = integration?.runs_failing ?? null;
1088
1214
  const gaveUp = integration?.unservable ?? null;
@@ -1159,15 +1285,30 @@ The key was not saved.`);
1159
1285
  }
1160
1286
  }
1161
1287
  console.log(checks.map((c) => `${c.verdict.padEnd(4)} ${c.name}: ${c.detail}`).join("\n"));
1288
+ if (refusal === null) {
1289
+ const identity = resolveIdentity(home);
1290
+ const handle = server?.kind === "ok" ? server.handle : identity?.handle ?? null;
1291
+ const verdict = setupVerdict({
1292
+ ...verdictBase(),
1293
+ identity: identity === null ? null : { handle: identity.handle, source: identity.source },
1294
+ pending: readPending(home),
1295
+ server: identity === null ? null : server,
1296
+ listener: profile.ensureListener !== void 0 ? readListener(home, handle) : null,
1297
+ ensure
1298
+ });
1299
+ if (verdict !== null) console.log(say(verdict));
1300
+ }
1162
1301
  return checks.some((c) => c.verdict === "FAIL") ? 1 : 0;
1163
1302
  }
1164
1303
  return {
1165
- runRegister,
1166
- runLogin,
1167
- runRecover,
1168
- runStatus,
1304
+ runRegister: tracked("register", runRegister),
1305
+ runLogin: tracked("login", runLogin),
1306
+ runRecover: tracked("recover", runRecover),
1307
+ runStatus: tracked("status", runStatus),
1169
1308
  runLogout,
1170
- runDoctor
1309
+ runDoctor: tracked("doctor", runDoctor),
1310
+ confirmSetup,
1311
+ reportSetup
1171
1312
  };
1172
1313
  }
1173
1314
 
@@ -1175,10 +1316,10 @@ The key was not saved.`);
1175
1316
  import * as crypto from "crypto";
1176
1317
  import * as fs2 from "fs";
1177
1318
  import * as os from "os";
1178
- import * as path2 from "path";
1319
+ import * as path from "path";
1179
1320
  function serviceLabelFor(base, home, defaultHome) {
1180
1321
  const key = (p) => {
1181
- const resolved = path2.resolve(p);
1322
+ const resolved = path.resolve(p);
1182
1323
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
1183
1324
  };
1184
1325
  if (key(home) === key(defaultHome)) return serviceLabel(base);
@@ -1205,7 +1346,7 @@ function transientPathEntry(value) {
1205
1346
  return /\/node_modules\/\.bin\/?$/i.test(normalized) || /\/node_modules\/npm\/node_modules\/@npmcli\/run-script\/lib\/node-gyp-bin\/?$/i.test(normalized) || /\/\.[^/]+\/tmp\//i.test(normalized);
1206
1347
  }
1207
1348
  function stableServicePath(value, nodePath = process.execPath) {
1208
- const entries = [path2.dirname(nodePath), ...value.split(path2.delimiter)];
1349
+ const entries = [path.dirname(nodePath), ...value.split(path.delimiter)];
1209
1350
  const seen = /* @__PURE__ */ new Set();
1210
1351
  const stable = [];
1211
1352
  for (const raw of entries) {
@@ -1221,7 +1362,7 @@ function stableServicePath(value, nodePath = process.execPath) {
1221
1362
  seen.add(key);
1222
1363
  stable.push(resolved);
1223
1364
  }
1224
- return stable.join(path2.delimiter);
1365
+ return stable.join(path.delimiter);
1225
1366
  }
1226
1367
  function plan(opts) {
1227
1368
  const env = {};
@@ -1243,8 +1384,8 @@ function plan(opts) {
1243
1384
  return {
1244
1385
  label: serviceLabel(opts.label),
1245
1386
  node: serviceValue("Node path", process.execPath),
1246
- bin: serviceValue("entry path", path2.resolve(opts.entry)),
1247
- home: serviceValue("home path", path2.resolve(opts.home)),
1387
+ bin: serviceValue("entry path", path.resolve(opts.entry)),
1388
+ home: serviceValue("home path", path.resolve(opts.home)),
1248
1389
  env
1249
1390
  };
1250
1391
  }
@@ -1324,7 +1465,7 @@ function parseServiceHome(text, format) {
1324
1465
  return exec === void 0 ? null : homeFromArgs(systemdWords(exec.slice("ExecStart=".length)));
1325
1466
  }
1326
1467
  function canonicalPath(p) {
1327
- const resolved = path2.resolve(p);
1468
+ const resolved = path.resolve(p);
1328
1469
  try {
1329
1470
  return fs2.realpathSync(resolved);
1330
1471
  } catch {
@@ -1427,7 +1568,7 @@ function servesHome(label, home) {
1427
1568
  return sightings(label).some((s) => s.home !== null && sameHome(s.home, home));
1428
1569
  }
1429
1570
  function systemdUnitPath(label) {
1430
- return path2.join(os.homedir(), ".config", "systemd", "user", `${label}.service`);
1571
+ return path.join(os.homedir(), ".config", "systemd", "user", `${label}.service`);
1431
1572
  }
1432
1573
  function systemdQuote(value) {
1433
1574
  return '"' + value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/"/g, '\\"').replace(/\$/g, "$$$$").replace(/%/g, "%%") + '"';
@@ -1455,7 +1596,7 @@ function systemdUnit(p) {
1455
1596
  function installSystemd(p) {
1456
1597
  assertServesHome(p.label, p.home, "replace");
1457
1598
  const unitPath = systemdUnitPath(p.label);
1458
- fs2.mkdirSync(path2.dirname(unitPath), { recursive: true });
1599
+ fs2.mkdirSync(path.dirname(unitPath), { recursive: true });
1459
1600
  atomicWriteFile(unitPath, systemdUnit(p), 384);
1460
1601
  log.info(`wrote ${unitPath}`);
1461
1602
  if (registrationSkipped()) return;
@@ -1507,7 +1648,7 @@ function foreignNote(label, home) {
1507
1648
  return ` \u2014 but it serves ${loaded.home}, not this config (${home})`;
1508
1649
  }
1509
1650
  function launchdPlistPath(label) {
1510
- return path2.join(os.homedir(), "Library", "LaunchAgents", `${launchdLabel(label)}.plist`);
1651
+ return path.join(os.homedir(), "Library", "LaunchAgents", `${launchdLabel(label)}.plist`);
1511
1652
  }
1512
1653
  var launchdLabel = (label) => `me.agentchat.${label}`;
1513
1654
  function xmlEscape(value) {
@@ -1517,7 +1658,7 @@ function launchdPlist(p) {
1517
1658
  const args = [p.node, p.bin, "--home", p.home];
1518
1659
  const argXml = args.map((a) => ` <string>${xmlEscape(a)}</string>`).join("\n");
1519
1660
  const envXml = Object.entries(p.env).map(([k, v]) => ` <key>${xmlEscape(k)}</key><string>${xmlEscape(v)}</string>`).join("\n");
1520
- const logPath = path2.join(p.home, "daemon.log");
1661
+ const logPath = path.join(p.home, "daemon.log");
1521
1662
  return [
1522
1663
  '<?xml version="1.0" encoding="UTF-8"?>',
1523
1664
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -1544,7 +1685,7 @@ function launchdPlist(p) {
1544
1685
  function installLaunchd(p) {
1545
1686
  assertServesHome(p.label, p.home, "replace");
1546
1687
  const plistPath = launchdPlistPath(p.label);
1547
- fs2.mkdirSync(path2.dirname(plistPath), { recursive: true });
1688
+ fs2.mkdirSync(path.dirname(plistPath), { recursive: true });
1548
1689
  atomicWriteFile(plistPath, launchdPlist(p), 384);
1549
1690
  log.info(`wrote ${plistPath}`);
1550
1691
  if (registrationSkipped()) return;
@@ -1610,16 +1751,16 @@ function winMode() {
1610
1751
  return hostOs === "win32" || hostOs === "wsl" ? hostOs : null;
1611
1752
  }
1612
1753
  function winMasterDir() {
1613
- return path2.join(os.homedir(), ".agentchat", "daemon");
1754
+ return path.join(os.homedir(), ".agentchat", "daemon");
1614
1755
  }
1615
1756
  function winStartupDir(mode) {
1616
1757
  if (mode === "win32") {
1617
- return path2.join(os.homedir(), "AppData", "Roaming", "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
1758
+ return path.join(os.homedir(), "AppData", "Roaming", "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
1618
1759
  }
1619
1760
  const appdata = run("cmd.exe", ["/c", "echo %APPDATA%"]).out.split(/\r?\n/).pop()?.trim() ?? "";
1620
1761
  const base = run("wslpath", ["-u", appdata]).out.trim();
1621
1762
  if (!base) throw new Error("could not locate the Windows Startup folder from WSL (is /mnt/c mounted?)");
1622
- return path2.join(base, "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
1763
+ return path.join(base, "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
1623
1764
  }
1624
1765
  var vbsEscape = (s) => s.replace(/"/g, '""');
1625
1766
  var shQuote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
@@ -1662,7 +1803,7 @@ function killLauncher(label, mode) {
1662
1803
  return run(mode === "win32" ? "powershell" : "powershell.exe", ["-NoProfile", "-Command", ps]);
1663
1804
  }
1664
1805
  function lockedDaemonPid(home) {
1665
- const file = path2.join(home, DAEMON_LOCK_FILE);
1806
+ const file = path.join(home, DAEMON_LOCK_FILE);
1666
1807
  try {
1667
1808
  const holder = parseLease(fs2.readFileSync(file, "utf-8"));
1668
1809
  if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null;
@@ -1683,11 +1824,11 @@ function stopRunningWindowsDaemon(label, mode, home) {
1683
1824
  function installWindows(p, mode) {
1684
1825
  const master = winMasterDir();
1685
1826
  fs2.mkdirSync(master, { recursive: true });
1686
- const masterVbs = path2.join(master, `${p.label}.vbs`);
1827
+ const masterVbs = path.join(master, `${p.label}.vbs`);
1687
1828
  if (mode === "win32") {
1688
1829
  atomicWriteFile(masterVbs, launcherVbs(winCommandNative(p), p.env), 384);
1689
1830
  } else {
1690
- const scriptPath = path2.join(master, `${p.label}.sh`);
1831
+ const scriptPath = path.join(master, `${p.label}.sh`);
1691
1832
  atomicWriteFile(scriptPath, wslScriptContent(p), 448);
1692
1833
  const distro = serviceValue("WSL distro", process.env["WSL_DISTRO_NAME"] ?? "");
1693
1834
  if (!distro) throw new Error("WSL_DISTRO_NAME is not set \u2014 cannot target the right WSL distro");
@@ -1702,11 +1843,11 @@ function installWindows(p, mode) {
1702
1843
  log.info(`service ${p.label} installed (starts at login)`);
1703
1844
  }
1704
1845
  function enableWindows(label, mode, home) {
1705
- const masterVbs = path2.join(winMasterDir(), `${label}.vbs`);
1846
+ const masterVbs = path.join(winMasterDir(), `${label}.vbs`);
1706
1847
  if (!fs2.existsSync(masterVbs)) throw new Error(`no ${label} daemon installed \u2014 run install first`);
1707
1848
  const startup = winStartupDir(mode);
1708
1849
  fs2.mkdirSync(startup, { recursive: true });
1709
- const startupVbs = path2.join(startup, `${label}.vbs`);
1850
+ const startupVbs = path.join(startup, `${label}.vbs`);
1710
1851
  fs2.copyFileSync(masterVbs, startupVbs);
1711
1852
  if (registrationSkipped()) return;
1712
1853
  stopRunningWindowsDaemon(label, mode, home);
@@ -1714,7 +1855,7 @@ function enableWindows(label, mode, home) {
1714
1855
  else startDetached("cmd.exe", ["/c", "start", "", "/b", "wscript.exe", winPathFromWsl(startupVbs)]);
1715
1856
  }
1716
1857
  function disableWindows(label, mode) {
1717
- const startupVbs = path2.join(winStartupDir(mode), `${label}.vbs`);
1858
+ const startupVbs = path.join(winStartupDir(mode), `${label}.vbs`);
1718
1859
  if (fs2.existsSync(startupVbs)) fs2.rmSync(startupVbs);
1719
1860
  if (!registrationSkipped()) {
1720
1861
  const killed = killLauncher(label, mode);
@@ -1726,15 +1867,15 @@ function disableWindows(label, mode) {
1726
1867
  function uninstallWindows(label, mode) {
1727
1868
  disableWindows(label, mode);
1728
1869
  for (const f of [`${label}.vbs`, `${label}.sh`]) {
1729
- const m = path2.join(winMasterDir(), f);
1870
+ const m = path.join(winMasterDir(), f);
1730
1871
  if (fs2.existsSync(m)) fs2.rmSync(m);
1731
1872
  }
1732
1873
  }
1733
1874
  function statusWindows(label, mode) {
1734
- const installed = fs2.existsSync(path2.join(winMasterDir(), `${label}.vbs`));
1875
+ const installed = fs2.existsSync(path.join(winMasterDir(), `${label}.vbs`));
1735
1876
  let enabled = false;
1736
1877
  try {
1737
- enabled = fs2.existsSync(path2.join(winStartupDir(mode), `${label}.vbs`));
1878
+ enabled = fs2.existsSync(path.join(winStartupDir(mode), `${label}.vbs`));
1738
1879
  } catch {
1739
1880
  }
1740
1881
  const host = mode === "wsl" ? "wsl" : "windows";
@@ -1761,7 +1902,7 @@ function installService(opts) {
1761
1902
  }
1762
1903
  function uninstallService(opts) {
1763
1904
  const label = serviceLabel(opts.label);
1764
- const home = path2.resolve(opts.home);
1905
+ const home = path.resolve(opts.home);
1765
1906
  const wm = winMode();
1766
1907
  if (wm) return uninstallWindows(label, wm);
1767
1908
  if (serviceHostOs() === "linux") {
@@ -1778,7 +1919,7 @@ function uninstallService(opts) {
1778
1919
  }
1779
1920
  function serviceStatus(opts) {
1780
1921
  const label = serviceLabel(opts.label);
1781
- const home = path2.resolve(opts.home);
1922
+ const home = path.resolve(opts.home);
1782
1923
  const wm = winMode();
1783
1924
  if (wm) return statusWindows(label, wm);
1784
1925
  if (serviceHostOs() === "linux") return statusSystemd(label, home);
@@ -1790,12 +1931,12 @@ function serviceDefinitionCurrent(opts) {
1790
1931
  const p = plan(opts);
1791
1932
  const wm = winMode();
1792
1933
  if (wm === "win32") {
1793
- const file = path2.join(winMasterDir(), `${p.label}.vbs`);
1934
+ const file = path.join(winMasterDir(), `${p.label}.vbs`);
1794
1935
  return fs2.existsSync(file) && fs2.readFileSync(file, "utf-8") === launcherVbs(winCommandNative(p), p.env);
1795
1936
  }
1796
1937
  if (wm === "wsl") {
1797
- const script = path2.join(winMasterDir(), `${p.label}.sh`);
1798
- const vbs = path2.join(winMasterDir(), `${p.label}.vbs`);
1938
+ const script = path.join(winMasterDir(), `${p.label}.sh`);
1939
+ const vbs = path.join(winMasterDir(), `${p.label}.vbs`);
1799
1940
  const distro = serviceValue("WSL distro", process.env["WSL_DISTRO_NAME"] ?? "");
1800
1941
  if (!distro) return false;
1801
1942
  return fs2.existsSync(script) && fs2.existsSync(vbs) && fs2.readFileSync(script, "utf-8") === wslScriptContent(p) && fs2.readFileSync(vbs, "utf-8") === launcherVbs(`wsl.exe -d "${distro}" -e bash "${script}"`, {});
@@ -1814,7 +1955,7 @@ function serviceDefinitionCurrent(opts) {
1814
1955
  }
1815
1956
  }
1816
1957
  function unitInstalled(label) {
1817
- if (winMode()) return fs2.existsSync(path2.join(winMasterDir(), `${label}.vbs`));
1958
+ if (winMode()) return fs2.existsSync(path.join(winMasterDir(), `${label}.vbs`));
1818
1959
  if (serviceHostOs() === "linux") return fs2.existsSync(systemdUnitPath(label));
1819
1960
  if (serviceHostOs() === "darwin") return fs2.existsSync(launchdPlistPath(label));
1820
1961
  return false;
@@ -1835,6 +1976,9 @@ export {
1835
1976
  FALLBACK_RUN_PROFILE,
1836
1977
  HEARTBEAT_FILE,
1837
1978
  HOSTED_MCP_PATH,
1979
+ HOST_FILE,
1980
+ IDENTITY_ANCHOR_ATTEMPTS,
1981
+ INSTALL_ID_FILE,
1838
1982
  INTEGRATION_ENV,
1839
1983
  INTEGRATION_ENV_LEGACY,
1840
1984
  INTEGRATION_ENV_LEGACY_REMOVAL,
@@ -1843,6 +1987,7 @@ export {
1843
1987
  LEASE_RENEW_MS,
1844
1988
  LEASE_STALE_MS,
1845
1989
  LEGACY_STATUS_FILE,
1990
+ LISTENER_ID_FILE,
1846
1991
  MANUAL,
1847
1992
  MANUAL_FETCH_TIMEOUT_MS,
1848
1993
  MANUAL_FILENAME,
@@ -1859,8 +2004,16 @@ export {
1859
2004
  RUN_CONTEXT_ENV,
1860
2005
  RUN_PROFILES,
1861
2006
  RUN_PROFILE_ENV,
2007
+ SETUP_GRACE_MS,
2008
+ SETUP_STATES,
2009
+ SETUP_WAIT_MS,
1862
2010
  SOCKET_STATES,
1863
2011
  STANDBY_MARKER_FRESH_MS,
2012
+ STOPPED_REPORT_TIMEOUT_MS,
2013
+ TELEMETRY_ENV,
2014
+ TELEMETRY_PATH,
2015
+ TELEMETRY_TIMEOUT_MS,
2016
+ TELEMETRY_VERSION,
1864
2017
  TEXTS_CACHE_FILE,
1865
2018
  VERSION,
1866
2019
  acquireAgentLock,
@@ -1884,6 +2037,7 @@ export {
1884
2037
  clearAlwaysOnOptOut,
1885
2038
  clearAlwaysOnWanted,
1886
2039
  clearCredentials,
2040
+ clearInstallId,
1887
2041
  clearIntegrationStatus,
1888
2042
  clearOfferDeclined,
1889
2043
  clearPending,
@@ -1894,22 +2048,33 @@ export {
1894
2048
  couldNotProcessPath,
1895
2049
  createIdentityCommands,
1896
2050
  credentialsPath,
2051
+ daemonPidOf,
1897
2052
  describeCouldNotProcessCounts,
2053
+ describeIdentityBlock,
2054
+ describeListenerStopped,
1898
2055
  describeManualSync,
1899
2056
  describePausedConversations,
1900
2057
  describeRunProfile,
2058
+ ensureInstallId,
1901
2059
  envApiKey,
1902
2060
  envKeyConflict,
1903
2061
  failedCyclesInARow,
1904
2062
  fetchIdentityLine,
1905
2063
  fetchServedTexts,
2064
+ followIdentityAnchor,
1906
2065
  formatIntegrationStatus,
2066
+ formatSetupVerdict,
1907
2067
  fromKitResult,
1908
2068
  hasAnchorAt,
1909
2069
  holderLive,
2070
+ hostIdentityOf,
1910
2071
  hostedMcpUrl,
2072
+ httpTelemetrySender,
2073
+ identityBlockState,
1911
2074
  identityLineOf,
1912
2075
  idle,
2076
+ installIdPath,
2077
+ installMethodOf,
1913
2078
  installService,
1914
2079
  integrationDisabled,
1915
2080
  integrationDisabledBy,
@@ -1919,8 +2084,11 @@ export {
1919
2084
  integrationStatusStaleFor,
1920
2085
  isRunProfile,
1921
2086
  isRunnerFactory,
2087
+ isSetupOfferBody,
1922
2088
  launchdPlist,
1923
2089
  leaseHolder,
2090
+ listenerIdPath,
2091
+ listenerReasonKindOf,
1924
2092
  loadTexts,
1925
2093
  log,
1926
2094
  manualFrontMatter,
@@ -1930,6 +2098,8 @@ export {
1930
2098
  markAlwaysOnOptOut,
1931
2099
  markAlwaysOnWanted,
1932
2100
  markStandby,
2101
+ newInstallId,
2102
+ newerRelease,
1933
2103
  normalizeHandle,
1934
2104
  offerDeclined,
1935
2105
  ownProfileLine,
@@ -1937,38 +2107,52 @@ export {
1937
2107
  parseServiceHome,
1938
2108
  pendingPath,
1939
2109
  pidAlive,
2110
+ placeAnchorAt,
2111
+ placementReportOf,
1940
2112
  planForTest,
1941
2113
  probeHostedMcp,
2114
+ reachabilityOf,
1942
2115
  readAlwaysOnInstalledVersion,
1943
2116
  readAnchorHandleAt,
1944
2117
  readAnchorHandleFrom,
1945
2118
  readCachedTexts,
1946
2119
  readCredentials,
2120
+ readInstallId,
1947
2121
  readIntegrationStatus,
1948
2122
  readJsonFile,
2123
+ readListener,
2124
+ readListenerInstanceId,
1949
2125
  readManualVersion,
1950
2126
  readPending,
2127
+ readRememberedHost,
1951
2128
  readState,
1952
2129
  recordOfferDeclined,
2130
+ rememberHost,
1953
2131
  removeAnchorAt,
1954
2132
  renderAnchorBlock,
1955
2133
  renderDeclinedBlock,
1956
2134
  renderUnregisteredBlock,
1957
2135
  repeatedFailedRuns,
2136
+ reportListenerStopped,
1958
2137
  resetLeaseObservations,
1959
2138
  resolveIdentity,
2139
+ resolveManualPointer,
1960
2140
  resolveRunBudgetMs,
1961
2141
  resolveRunProfile,
1962
2142
  runContextEnv,
1963
2143
  runProbe,
1964
2144
  runProfileWarning,
1965
2145
  runtimeCheckFailingNow,
2146
+ sendSetupVerdict,
2147
+ servedManualUrl,
1966
2148
  serviceDefinitionCurrent,
1967
2149
  serviceInstalled,
1968
2150
  serviceLabelFor,
1969
2151
  serviceStatus,
1970
2152
  setServiceCommandRunnerForTests,
1971
2153
  setServiceHostOsForTests,
2154
+ setupVerdict,
2155
+ setupVerdictEvent,
1972
2156
  spawnCommand,
1973
2157
  spawnCommandSync,
1974
2158
  standbyMarkerPath,
@@ -1978,6 +2162,7 @@ export {
1978
2162
  syncManual,
1979
2163
  systemdQuote,
1980
2164
  systemdUnit,
2165
+ telemetryOff,
1981
2166
  textsCachePath,
1982
2167
  traySummary,
1983
2168
  uninstallService,
@@ -1986,6 +2171,7 @@ export {
1986
2171
  writeAnchor,
1987
2172
  writeCredentials,
1988
2173
  writeIntegrationStatus,
2174
+ writeOfferAt,
1989
2175
  writePending,
1990
2176
  writeState,
1991
2177
  xmlEscape