@agentchatme/agent-core 0.7.3 → 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
@@ -7,12 +7,15 @@ import {
7
7
  DEFAULT_API_BASE,
8
8
  FAILED_CYCLE_OUTCOMES,
9
9
  HEARTBEAT_FILE,
10
+ HOST_FILE,
10
11
  IDENTITY_ANCHOR_ATTEMPTS,
12
+ INSTALL_ID_FILE,
11
13
  INTEGRATION_STATUS_FILE,
12
14
  INTEGRATION_STATUS_STALE_MS,
13
15
  LEASE_RENEW_MS,
14
16
  LEASE_STALE_MS,
15
17
  LEGACY_STATUS_FILE,
18
+ LISTENER_ID_FILE,
16
19
  MANUAL,
17
20
  MANUAL_FETCH_TIMEOUT_MS,
18
21
  MANUAL_FILENAME,
@@ -22,9 +25,13 @@ import {
22
25
  MANUAL_URL,
23
26
  PausedConversations,
24
27
  REPEATED_FAILED_CYCLES,
28
+ SETUP_GRACE_MS,
29
+ SETUP_STATES,
25
30
  SOCKET_STATES,
26
31
  STANDBY_MARKER_FRESH_MS,
32
+ STOPPED_REPORT_TIMEOUT_MS,
27
33
  TEXTS_CACHE_FILE,
34
+ VERIFY_STEP,
28
35
  acquireAgentLock,
29
36
  acquireLeaderLock,
30
37
  acquireLease,
@@ -43,15 +50,21 @@ import {
43
50
  clearAlwaysOnOptOut,
44
51
  clearAlwaysOnWanted,
45
52
  clearCredentials,
53
+ clearInstallId,
46
54
  clearIntegrationStatus,
47
55
  clearPending,
48
56
  clearStandby,
57
+ codeCommandOf,
58
+ codeMayWork,
49
59
  couldNotProcessPath,
50
60
  credentialsPath,
61
+ daemonPidOf,
51
62
  describeCouldNotProcessCounts,
52
63
  describeIdentityBlock,
64
+ describeListenerStopped,
53
65
  describeManualSync,
54
66
  describePausedConversations,
67
+ ensureInstallId,
55
68
  envApiKey,
56
69
  envKeyConflict,
57
70
  external_exports,
@@ -60,12 +73,14 @@ import {
60
73
  fetchServedTexts,
61
74
  followIdentityAnchor,
62
75
  formatIntegrationStatus,
76
+ formatSetupVerdict,
63
77
  fromKitResult,
64
78
  hasAnchorAt,
65
79
  holderLive,
66
80
  identityBlockState,
67
81
  identityLineOf,
68
82
  idle,
83
+ installIdPath,
69
84
  integrationStatusAge,
70
85
  integrationStatusFresh,
71
86
  integrationStatusPath,
@@ -73,6 +88,8 @@ import {
73
88
  isRunnerFactory,
74
89
  isSetupOfferBody,
75
90
  leaseHolder,
91
+ listenerIdPath,
92
+ listenerReasonKindOf,
76
93
  loadTexts,
77
94
  manualFrontMatter,
78
95
  manualPointer,
@@ -81,31 +98,46 @@ import {
81
98
  markAlwaysOnOptOut,
82
99
  markAlwaysOnWanted,
83
100
  markStandby,
101
+ newInstallId,
102
+ newerRelease,
84
103
  normalizeHandle,
85
104
  parseLease,
86
105
  pendingPath,
87
106
  pidAlive,
88
107
  placeAnchorAt,
108
+ reachabilityOf,
89
109
  readAlwaysOnInstalledVersion,
90
110
  readAnchorHandleAt,
91
111
  readAnchorHandleFrom,
92
112
  readCachedTexts,
93
113
  readCredentials,
114
+ readInstallId,
94
115
  readIntegrationStatus,
116
+ readListener,
117
+ readListenerInstanceId,
95
118
  readManualVersion,
96
119
  readPending,
120
+ readRememberedHost,
121
+ rememberHost,
97
122
  removeAnchorAt,
98
123
  renderAnchorBlock,
99
124
  renderDeclinedBlock,
100
125
  renderUnregisteredBlock,
101
126
  repeatedFailedRuns,
127
+ reportListenerStopped,
128
+ resendLeftS,
102
129
  resetLeaseObservations,
103
130
  resolveIdentity,
104
131
  resolveManualPointer,
132
+ runLine,
105
133
  runtimeCheckFailingNow,
106
134
  servedManualUrl,
135
+ serviceDryRun,
136
+ setupVerdict,
137
+ shellValue,
107
138
  standbyMarkerPath,
108
139
  standbyWaiting,
140
+ startCommandOf,
109
141
  statePath,
110
142
  stripAnchorBlock,
111
143
  syncManual,
@@ -116,7 +148,7 @@ import {
116
148
  writeIntegrationStatus,
117
149
  writeOfferAt,
118
150
  writePending
119
- } from "./chunk-FPAOQGMV.js";
151
+ } from "./chunk-6GMYBMID.js";
120
152
  import {
121
153
  HOSTED_MCP_PATH,
122
154
  PROBE_KILL_WAIT_MS,
@@ -124,7 +156,7 @@ import {
124
156
  hostedMcpUrl,
125
157
  probeHostedMcp,
126
158
  runProbe
127
- } from "./chunk-7TTV2CQX.js";
159
+ } from "./chunk-WYBLSTYB.js";
128
160
  import {
129
161
  DEFAULT_RUN_BUDGET_MS,
130
162
  DEFAULT_RUN_PROFILE,
@@ -143,6 +175,8 @@ import {
143
175
  clientIdentityOf,
144
176
  clientNameOf,
145
177
  describeRunProfile,
178
+ hostIdentityOf,
179
+ installMethodOf,
146
180
  integrationDisabled,
147
181
  integrationDisabledBy,
148
182
  isRunProfile,
@@ -155,7 +189,7 @@ import {
155
189
  spawnCommand,
156
190
  spawnCommandSync,
157
191
  workdirExposesHome
158
- } from "./chunk-5KMQ23O6.js";
192
+ } from "./chunk-LPTOKVEE.js";
159
193
 
160
194
  // src/integration/tray.ts
161
195
  import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
@@ -222,10 +256,14 @@ function runContextEnv(env, request) {
222
256
  }
223
257
 
224
258
  // src/identity/commands.ts
259
+ import * as fs from "fs";
225
260
  import * as readline from "readline";
226
261
  import { AgentChatClient, integration as kit } from "agentchatme";
227
262
 
228
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
+ }
229
267
  function anchorLabelOf(profile) {
230
268
  if (profile.anchorLabel !== void 0) return profile.anchorLabel;
231
269
  if (profile.anchorFile === void 0) return "identity line";
@@ -234,6 +272,73 @@ function anchorLabelOf(profile) {
234
272
  return slash >= 0 ? file.slice(slash + 1) : file;
235
273
  }
236
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
+
237
342
  // src/identity/commands.ts
238
343
  var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
239
344
  function errorText(err) {
@@ -281,32 +386,6 @@ function handleInput(raw) {
281
386
  const handle = raw?.trim().replace(/^@/, "").toLowerCase();
282
387
  return handle ? handle : void 0;
283
388
  }
284
- var VERIFY_STEP = { register: "verify", recover: "recover_verify" };
285
- function shellValue(value) {
286
- return /^[A-Za-z0-9@%+=:,./_-]+$/.test(value) ? value : JSON.stringify(value);
287
- }
288
- function receivedAtMs(pending) {
289
- const at = Date.parse(pending.received_at);
290
- return Number.isFinite(at) ? at : null;
291
- }
292
- function codeMayWork(pending, now = Date.now()) {
293
- const received = receivedAtMs(pending);
294
- if (pending.flow.expires_in_s !== void 0 && received !== null) return received + pending.flow.expires_in_s * 1e3 > now;
295
- if (pending.flow.expires_at !== void 0) {
296
- const at = Date.parse(pending.flow.expires_at);
297
- if (Number.isFinite(at)) return at > now;
298
- }
299
- return true;
300
- }
301
- function resendLeftS(pending, now = Date.now()) {
302
- if (pending === null || pending.flow.resend_after_s === void 0) return 0;
303
- const received = receivedAtMs(pending);
304
- if (received === null) return 0;
305
- return Math.max(0, Math.ceil((pending.flow.resend_after_s * 1e3 - (now - received)) / 1e3));
306
- }
307
- function runLine(command, waitS = 0) {
308
- return waitS > 0 ? `Wait ${waitS} s, then run \`${command}\`` : `Run \`${command}\``;
309
- }
310
389
  async function askOnTerminal(question) {
311
390
  if (question.field === "new_code") {
312
391
  const answer2 = await prompt("Send a new code? [y/N] ");
@@ -319,40 +398,98 @@ async function askOnTerminal(question) {
319
398
  if (question.field === "code") return answer.toLowerCase() === "new" ? { answer: "new_code" } : { answer: "value", value: answer };
320
399
  return { answer: "value", value: (question.field === "handle" ? handleInput(answer) : emailInput(answer)) ?? "" };
321
400
  }
322
- 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.";
323
- 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 = {}) {
324
408
  const invocation = () => profile.invocation();
325
409
  const LABEL = profile.label;
326
- 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
+ }
327
464
  function envKeyRefusal() {
328
465
  const conflict = envKeyConflict(profile.home());
329
466
  if (conflict === null) return null;
330
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 -`;
331
468
  }
332
- const apiClient = (apiKey, apiBase) => new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
333
- 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 });
334
471
  async function served(apiKey, apiBase) {
335
472
  const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5e3 });
336
473
  return loaded === null ? NO_TEXTS : contextOf(loaded.texts);
337
474
  }
338
- async function printExtraStatus(context) {
339
- if (profile.extraStatus === void 0) return;
475
+ async function extraStatusOf(context) {
476
+ if (profile.extraStatus === void 0) return { lines: [], problem: null };
340
477
  try {
341
- for (const line of await profile.extraStatus(context)) console.log(line);
478
+ return placementReportOf(await profile.extraStatus(context));
342
479
  } catch (err) {
343
- 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 };
344
481
  }
345
482
  }
346
483
  async function placeIdentity(handle, apiKey, apiBase) {
347
484
  const { identityLine, manual } = await served(apiKey, apiBase);
348
485
  if (profile.place !== void 0) {
349
486
  try {
350
- return await profile.place(handle, apiKey, identityLine, manual);
487
+ return placementReportOf(await profile.place(handle, apiKey, identityLine, manual));
351
488
  } catch (err) {
352
- 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 };
353
490
  }
354
491
  }
355
- return writeOurAnchor(handle, identityLine);
492
+ return { lines: writeOurAnchor(handle, identityLine), problem: null };
356
493
  }
357
494
  function writeOurAnchor(handle, identityLine) {
358
495
  if (profile.anchorFile === void 0) return [];
@@ -375,24 +512,119 @@ function createIdentityCommands(profile) {
375
512
  }
376
513
  }
377
514
  function startCommand(kind, input, blank) {
378
- const email = blank === "email" ? "<email>" : shellValue(input.email);
379
- const handle = blank === "handle" ? "<handle>" : input.handle !== void 0 ? shellValue(input.handle) : null;
380
- if (kind === "recover") return `${invocation()} recover${handle !== null ? ` --handle ${handle}` : ""} --email ${email}`;
381
- return [
382
- `${invocation()} register --email ${email} --handle ${handle ?? "<handle>"}`,
383
- ...input.display_name !== void 0 ? [`--display-name ${shellValue(input.display_name)}`] : [],
384
- ...input.description !== void 0 ? [`--description ${shellValue(input.description)}`] : []
385
- ].join(" ");
515
+ return startCommandOf(invocation(), kind, input, blank);
386
516
  }
387
517
  function codeCommand(kind, flow, code) {
388
- const value = code !== void 0 ? shellValue(code) : flow.code_length !== void 0 ? `<${flow.code_length} digits>` : "<code>";
389
- 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 });
390
620
  }
391
621
  function nextSteps(kind, result, called, input, code, held) {
392
622
  const beforeNewCode = Math.max(result.flow.retry_after_s ?? 0, result.flow.resend_after_s ?? resendLeftS(held));
393
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)}\``] : [];
394
624
  switch (result.action) {
395
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":
396
628
  return [];
397
629
  case "ask_code":
398
630
  return [runLine(codeCommand(kind, result.flow))];
@@ -412,11 +644,14 @@ function createIdentityCommands(profile) {
412
644
  }
413
645
  case "stop":
414
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 [];
415
650
  }
416
651
  }
417
652
  function report(result, lines, ok) {
418
- const said = result.message.length > 0 ? result.message : result.code ?? `HTTP ${result.httpStatus}`;
419
- 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");
420
655
  if (ok) console.log(text);
421
656
  else console.error(text);
422
657
  return ok ? 0 : 1;
@@ -432,15 +667,19 @@ function createIdentityCommands(profile) {
432
667
  clearPending(home);
433
668
  clearOfferDeclined(home);
434
669
  const placed = await placeIdentity(handle, apiKey, apiBase);
670
+ const listener = await placeListener(placed.problem);
671
+ const hint = profile.ensureListener === void 0 ? [SESSION_HINT] : [];
435
672
  const lines = kind === "register" ? [
436
673
  `API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`,
437
- ...placed,
674
+ ...placed.lines,
675
+ ...listener.lines,
438
676
  "",
439
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.`,
440
678
  `Other agents can DM you at @${handle}. Check \`${invocation()} status\` any time.`,
441
- NEXT_HINT
442
- ] : [`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];
443
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 });
444
683
  return 0;
445
684
  }
446
685
  async function startSignup(kind, input, apiBase) {
@@ -469,15 +708,18 @@ ${runLine(startCommand(kind, input))} again.`);
469
708
  return 1;
470
709
  }
471
710
  if (result.action === "ask_code") {
472
- writePending(home, {
711
+ const pending = {
473
712
  kind,
474
713
  flow: result.flow,
475
714
  received_at: (/* @__PURE__ */ new Date()).toISOString(),
476
715
  ...input,
477
716
  ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}
478
- });
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);
479
721
  }
480
- 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);
481
723
  }
482
724
  async function submitPendingCode(kind, rawCode, apiBase) {
483
725
  const home = profile.home();
@@ -594,7 +836,7 @@ login does not adopt an exported key in place of the one this home holds; nothin
594
836
  console.log("Using the key from AGENTCHAT_API_KEY.");
595
837
  } else if (process.stdin.isTTY !== true) {
596
838
  console.error(
597
- `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.`
598
840
  );
599
841
  return 1;
600
842
  } else {
@@ -625,17 +867,21 @@ The key was not saved.`);
625
867
  created_at: (/* @__PURE__ */ new Date()).toISOString()
626
868
  });
627
869
  clearOfferDeclined(home);
870
+ const placed = await placeIdentity(check.handle, apiKey, apiBase);
871
+ const listener = await placeListener(placed.problem);
628
872
  console.log(
629
873
  [
630
874
  `Signed in as @${check.handle} for ${LABEL}.`,
631
875
  `API key stored at ${credentialsPath(home)} (never commit this file).`,
632
- ...await placeIdentity(check.handle, apiKey, apiBase),
633
- NEXT_HINT,
876
+ ...placed.lines,
877
+ ...listener.lines,
878
+ ...profile.ensureListener === void 0 ? [SESSION_HINT] : [],
634
879
  ...onArgv ? [
635
- `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).`
636
881
  ] : []
637
882
  ].join("\n")
638
883
  );
884
+ await confirm({ ensure: listener.ensure, tools: placed.problem, afterSignIn: true, replacedPid: listener.replacedPid });
639
885
  return 0;
640
886
  }
641
887
  async function runRecover(opts) {
@@ -705,7 +951,9 @@ The key was not saved.`);
705
951
  const identity = resolveIdentity(home);
706
952
  const pending = readPending(home);
707
953
  const integration = readIntegrationStatus(home);
954
+ const listenerOf = (handle) => profile.ensureListener !== void 0 ? readListener(home, handle) : null;
708
955
  if (identity === null) {
956
+ const setup2 = setupVerdict({ ...verdictBase(), identity: null, pending, server: null, listener: null });
709
957
  if (opts.json) {
710
958
  console.log(
711
959
  JSON.stringify({
@@ -713,27 +961,26 @@ The key was not saved.`);
713
961
  host: profile.id,
714
962
  pending: pending !== null,
715
963
  pending_kind: pending?.kind ?? null,
716
- integration
964
+ integration,
965
+ setup: setup2
717
966
  })
718
967
  );
719
- } else if (pending !== null) {
720
- const what = pending.kind === "recover" ? `an account recovery${pending.handle !== void 0 ? ` for @${pending.handle}` : ""}` : `a registration for @${pending.handle ?? "?"}`;
721
- console.log(
722
- 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)}`
723
- );
724
- } else {
725
- 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));
726
971
  }
727
972
  return 0;
728
973
  }
729
974
  let me;
730
- const client = apiClient(identity.apiKey, identity.apiBase);
975
+ const client2 = apiClient(identity.apiKey, identity.apiBase);
731
976
  try {
732
- me = await client.getMe();
977
+ me = await client2.getMe();
733
978
  } catch (err) {
734
979
  const status = httpStatusOf(err);
735
980
  const refused = status === 401 || status === 403;
736
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) });
737
984
  if (opts.json) {
738
985
  const offline = anchorView(anchorFile, NO_TEXTS, null);
739
986
  console.log(
@@ -747,31 +994,42 @@ The key was not saved.`);
747
994
  home,
748
995
  anchor: offline.present,
749
996
  anchor_error: offline.error,
750
- integration
997
+ integration,
998
+ setup: setup2
751
999
  })
752
1000
  );
1001
+ if (setup2 !== null) say(setup2);
753
1002
  } else {
754
- console.error(
755
- 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}`
756
- );
757
1003
  const cached = readCachedTexts(home, profile.client.runtime);
758
1004
  const context = cached === null ? NO_TEXTS : contextOf(cached.texts);
1005
+ const extra2 = await extraStatusOf(context);
759
1006
  console.log(
760
1007
  [
1008
+ // First: what this means and what to do (a refused key is not an unreachable server).
1009
+ ...setup2 !== null ? [say(setup2)] : [],
761
1010
  `${identity.handle !== null ? `@${identity.handle}` : "This agent"} \u2014 ${refused ? `key refused (HTTP ${status})` : "AgentChat unreachable"} (${LABEL})`,
762
1011
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
763
1012
  `API: ${identity.apiBase}`,
764
1013
  ...anchorFile === null ? [] : [`Identity line: ${anchorWords(anchorFile, anchorView(anchorFile, context, identity.handle))}`],
765
- ...formatIntegrationStatus(integration)
1014
+ ...formatIntegrationStatus(integration),
1015
+ ...extra2.lines
766
1016
  ].join("\n")
767
1017
  );
768
- await printExtraStatus(context);
769
1018
  }
770
1019
  return 1;
771
1020
  }
772
- const tray = await traySummary(client).catch(() => null);
1021
+ const tray = await traySummary(client2).catch(() => null);
773
1022
  const texts = await served(identity.apiKey, identity.apiBase);
774
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
+ });
775
1033
  if (opts.json) {
776
1034
  console.log(
777
1035
  JSON.stringify({
@@ -792,13 +1050,17 @@ The key was not saved.`);
792
1050
  anchor_state: anchor.state?.state ?? null,
793
1051
  /** Why the runtime does not load the instruction file now, or null. */
794
1052
  anchor_not_loaded: anchor.state?.notLoaded ?? null,
795
- integration
1053
+ integration,
1054
+ /** Whether setup is done and what is left (`setupVerdict`); null when this host has nothing to judge. */
1055
+ setup
796
1056
  })
797
1057
  );
1058
+ if (setup !== null) say(setup);
798
1059
  } else {
799
1060
  const trayLine = tray === null ? "Tray: could not be read" : `Tray: ${tray.waiting}${tray.truncated ? "+" : ""} conversation(s) waiting${tray.deferred > 0 ? `, ${tray.deferred} deferred` : ""}`;
800
1061
  console.log(
801
1062
  [
1063
+ ...setup !== null ? [say(setup)] : [],
802
1064
  `@${me.handle} \u2014 ${me.status ?? "active"} (${LABEL})`,
803
1065
  trayLine,
804
1066
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
@@ -806,19 +1068,22 @@ The key was not saved.`);
806
1068
  ...anchorFile === null ? [] : [
807
1069
  `Identity line: ${anchorWords(anchorFile, anchor)}`
808
1070
  ],
809
- ...formatIntegrationStatus(integration)
1071
+ ...formatIntegrationStatus(integration),
1072
+ ...extra.lines
810
1073
  ].join("\n")
811
1074
  );
812
- await printExtraStatus(texts);
813
1075
  }
814
1076
  return 0;
815
1077
  }
816
- function runLogout() {
1078
+ async function runLogout() {
817
1079
  const home = profile.home();
818
1080
  const anchorFile = profile.anchorFile?.() ?? null;
819
1081
  const reports = [];
820
1082
  let any = false;
821
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}`);
822
1087
  if (clearCredentials(home)) {
823
1088
  any = true;
824
1089
  reports.push(" credentials deleted");
@@ -873,7 +1138,7 @@ The key was not saved.`);
873
1138
  if (before.state === "unreadable") return { name: "identity-line", verdict: "FAIL", detail: before.what };
874
1139
  const repairable = before.state === "missing" || before.state === "setup_offer" || before.state === "stale";
875
1140
  if (fix && repairable) {
876
- const report2 = await placeIdentity(creds.handle, creds.api_key, apiBase);
1141
+ const report2 = (await placeIdentity(creds.handle, creds.api_key, apiBase)).lines;
877
1142
  const failed = report2.some((l) => l.includes("FAILED") || l.includes("not written"));
878
1143
  if (failed) return { name: "identity-line", verdict: "FAIL", detail: `could not repair: ${report2.join("; ")}` };
879
1144
  const after = readIdentityLine(anchorFile, creds.handle, texts);
@@ -895,6 +1160,7 @@ The key was not saved.`);
895
1160
  const refusal = envKeyRefusal();
896
1161
  if (refusal !== null) checks.push({ name: "env-key", verdict: "FAIL", detail: refusal });
897
1162
  const creds = readCredentials(home);
1163
+ let server = null;
898
1164
  if (creds === null) {
899
1165
  checks.push({
900
1166
  name: "credentials",
@@ -906,9 +1172,10 @@ The key was not saved.`);
906
1172
  const identity = resolveIdentity(home);
907
1173
  if (identity !== null) {
908
1174
  try {
909
- const client = apiClient(identity.apiKey, identity.apiBase);
1175
+ const client2 = apiClient(identity.apiKey, identity.apiBase);
910
1176
  const started = Date.now();
911
- const me = await client.getMe();
1177
+ const me = await client2.getMe();
1178
+ server = { kind: "ok", handle: me.handle, reachability: reachabilityOf(me) };
912
1179
  const verdict = (me.status ?? "active") === "active" ? "PASS" : "WARN";
913
1180
  checks.push({
914
1181
  name: "api-auth",
@@ -923,6 +1190,7 @@ The key was not saved.`);
923
1190
  });
924
1191
  }
925
1192
  } catch (err) {
1193
+ server = serverViewOfError(err);
926
1194
  checks.push({ name: "api-auth", verdict: "FAIL", detail: `getMe failed: ${String(err)}` });
927
1195
  }
928
1196
  }
@@ -933,6 +1201,14 @@ The key was not saved.`);
933
1201
  );
934
1202
  if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true));
935
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
+ }
936
1212
  const integration = readIntegrationStatus(home);
937
1213
  const runsFailing = integration?.runs_failing ?? null;
938
1214
  const gaveUp = integration?.unservable ?? null;
@@ -1009,21 +1285,36 @@ The key was not saved.`);
1009
1285
  }
1010
1286
  }
1011
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
+ }
1012
1301
  return checks.some((c) => c.verdict === "FAIL") ? 1 : 0;
1013
1302
  }
1014
1303
  return {
1015
- runRegister,
1016
- runLogin,
1017
- runRecover,
1018
- runStatus,
1304
+ runRegister: tracked("register", runRegister),
1305
+ runLogin: tracked("login", runLogin),
1306
+ runRecover: tracked("recover", runRecover),
1307
+ runStatus: tracked("status", runStatus),
1019
1308
  runLogout,
1020
- runDoctor
1309
+ runDoctor: tracked("doctor", runDoctor),
1310
+ confirmSetup,
1311
+ reportSetup
1021
1312
  };
1022
1313
  }
1023
1314
 
1024
1315
  // src/daemon/service.ts
1025
1316
  import * as crypto from "crypto";
1026
- import * as fs from "fs";
1317
+ import * as fs2 from "fs";
1027
1318
  import * as os from "os";
1028
1319
  import * as path from "path";
1029
1320
  function serviceLabelFor(base, home, defaultHome) {
@@ -1063,7 +1354,7 @@ function stableServicePath(value, nodePath = process.execPath) {
1063
1354
  if (!trimmed || transientPathEntry(trimmed)) continue;
1064
1355
  let resolved = trimmed;
1065
1356
  try {
1066
- resolved = fs.realpathSync(trimmed);
1357
+ resolved = fs2.realpathSync(trimmed);
1067
1358
  } catch {
1068
1359
  }
1069
1360
  const key = process.platform === "win32" ? resolved.toLowerCase() : resolved;
@@ -1176,7 +1467,7 @@ function parseServiceHome(text, format) {
1176
1467
  function canonicalPath(p) {
1177
1468
  const resolved = path.resolve(p);
1178
1469
  try {
1179
- return fs.realpathSync(resolved);
1470
+ return fs2.realpathSync(resolved);
1180
1471
  } catch {
1181
1472
  return resolved;
1182
1473
  }
@@ -1189,10 +1480,10 @@ function sameHome(a, b) {
1189
1480
  function launchdSightings(label) {
1190
1481
  const out = [];
1191
1482
  const plistPath = launchdPlistPath(label);
1192
- if (fs.existsSync(plistPath)) {
1483
+ if (fs2.existsSync(plistPath)) {
1193
1484
  let text = "";
1194
1485
  try {
1195
- text = fs.readFileSync(plistPath, "utf-8");
1486
+ text = fs2.readFileSync(plistPath, "utf-8");
1196
1487
  } catch {
1197
1488
  }
1198
1489
  out.push({ where: plistPath, home: parseServiceHome(text, "plist"), loaded: false });
@@ -1209,7 +1500,7 @@ function launchdSightings(label) {
1209
1500
  const loadedFrom = /^\s*path = (.+)$/m.exec(text)?.[1]?.trim();
1210
1501
  if (loadedFrom !== void 0) {
1211
1502
  try {
1212
- home = parseServiceHome(fs.readFileSync(loadedFrom, "utf-8"), "plist");
1503
+ home = parseServiceHome(fs2.readFileSync(loadedFrom, "utf-8"), "plist");
1213
1504
  } catch {
1214
1505
  }
1215
1506
  }
@@ -1222,10 +1513,10 @@ function launchdSightings(label) {
1222
1513
  function systemdSightings(label) {
1223
1514
  const out = [];
1224
1515
  const unitPath = systemdUnitPath(label);
1225
- if (fs.existsSync(unitPath)) {
1516
+ if (fs2.existsSync(unitPath)) {
1226
1517
  let text = "";
1227
1518
  try {
1228
- text = fs.readFileSync(unitPath, "utf-8");
1519
+ text = fs2.readFileSync(unitPath, "utf-8");
1229
1520
  } catch {
1230
1521
  }
1231
1522
  out.push({ where: unitPath, home: parseServiceHome(text, "systemd"), loaded: false });
@@ -1243,7 +1534,7 @@ function systemdSightings(label) {
1243
1534
  const fragment = props.get("FragmentPath") ?? "";
1244
1535
  let home = null;
1245
1536
  try {
1246
- if (fragment) home = parseServiceHome(fs.readFileSync(fragment, "utf-8"), "systemd");
1537
+ if (fragment) home = parseServiceHome(fs2.readFileSync(fragment, "utf-8"), "systemd");
1247
1538
  } catch {
1248
1539
  }
1249
1540
  out.push({ where: `the loaded systemd unit ${label}${fragment ? ` (${fragment})` : ""}`, home, loaded: true });
@@ -1305,7 +1596,7 @@ function systemdUnit(p) {
1305
1596
  function installSystemd(p) {
1306
1597
  assertServesHome(p.label, p.home, "replace");
1307
1598
  const unitPath = systemdUnitPath(p.label);
1308
- fs.mkdirSync(path.dirname(unitPath), { recursive: true });
1599
+ fs2.mkdirSync(path.dirname(unitPath), { recursive: true });
1309
1600
  atomicWriteFile(unitPath, systemdUnit(p), 384);
1310
1601
  log.info(`wrote ${unitPath}`);
1311
1602
  if (registrationSkipped()) return;
@@ -1335,7 +1626,7 @@ function uninstallSystemd(label, home) {
1335
1626
  }
1336
1627
  }
1337
1628
  const unitPath = systemdUnitPath(label);
1338
- if (fs.existsSync(unitPath)) fs.rmSync(unitPath);
1629
+ if (fs2.existsSync(unitPath)) fs2.rmSync(unitPath);
1339
1630
  if (!registrationSkipped()) {
1340
1631
  const reload = run("systemctl", ["--user", "daemon-reload"]);
1341
1632
  if (!reload.ok) log.warn(`systemctl daemon-reload failed after uninstall: ${reload.out}`);
@@ -1349,7 +1640,7 @@ function statusSystemd(label, home) {
1349
1640
  return `systemd ${label}: ${active} (${enabled})${foreignNote(label, home)}`;
1350
1641
  }
1351
1642
  function dryRunStatus(name, definitionPath) {
1352
- return `${name}: not queried (AGENTCHAT_SERVICE_DRY_RUN) \u2014 definition ${fs.existsSync(definitionPath) ? `written at ${definitionPath}` : "not written"}`;
1643
+ return `${name}: not queried (AGENTCHAT_SERVICE_DRY_RUN) \u2014 definition ${fs2.existsSync(definitionPath) ? `written at ${definitionPath}` : "not written"}`;
1353
1644
  }
1354
1645
  function foreignNote(label, home) {
1355
1646
  const loaded = sightings(label).find((s) => s.loaded);
@@ -1394,7 +1685,7 @@ function launchdPlist(p) {
1394
1685
  function installLaunchd(p) {
1395
1686
  assertServesHome(p.label, p.home, "replace");
1396
1687
  const plistPath = launchdPlistPath(p.label);
1397
- fs.mkdirSync(path.dirname(plistPath), { recursive: true });
1688
+ fs2.mkdirSync(path.dirname(plistPath), { recursive: true });
1398
1689
  atomicWriteFile(plistPath, launchdPlist(p), 384);
1399
1690
  log.info(`wrote ${plistPath}`);
1400
1691
  if (registrationSkipped()) return;
@@ -1422,7 +1713,7 @@ function uninstallLaunchd(label, home) {
1422
1713
  );
1423
1714
  }
1424
1715
  }
1425
- if (fs.existsSync(plistPath)) fs.rmSync(plistPath);
1716
+ if (fs2.existsSync(plistPath)) fs2.rmSync(plistPath);
1426
1717
  log.info(`service ${launchdLabel(label)} removed`);
1427
1718
  }
1428
1719
  function statusLaunchd(label, home) {
@@ -1439,7 +1730,7 @@ function isWslFromVersion(version) {
1439
1730
  function isWsl() {
1440
1731
  if (process.platform !== "linux") return false;
1441
1732
  try {
1442
- return isWslFromVersion(fs.readFileSync("/proc/version", "utf-8"));
1733
+ return isWslFromVersion(fs2.readFileSync("/proc/version", "utf-8"));
1443
1734
  } catch {
1444
1735
  return false;
1445
1736
  }
@@ -1514,9 +1805,9 @@ function killLauncher(label, mode) {
1514
1805
  function lockedDaemonPid(home) {
1515
1806
  const file = path.join(home, DAEMON_LOCK_FILE);
1516
1807
  try {
1517
- const holder = parseLease(fs.readFileSync(file, "utf-8"));
1808
+ const holder = parseLease(fs2.readFileSync(file, "utf-8"));
1518
1809
  if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null;
1519
- return holderLive(holder, { mtimeMs: fs.statSync(file).mtimeMs }) ? holder.pid : null;
1810
+ return holderLive(holder, { mtimeMs: fs2.statSync(file).mtimeMs }) ? holder.pid : null;
1520
1811
  } catch {
1521
1812
  return null;
1522
1813
  }
@@ -1532,7 +1823,7 @@ function stopRunningWindowsDaemon(label, mode, home) {
1532
1823
  }
1533
1824
  function installWindows(p, mode) {
1534
1825
  const master = winMasterDir();
1535
- fs.mkdirSync(master, { recursive: true });
1826
+ fs2.mkdirSync(master, { recursive: true });
1536
1827
  const masterVbs = path.join(master, `${p.label}.vbs`);
1537
1828
  if (mode === "win32") {
1538
1829
  atomicWriteFile(masterVbs, launcherVbs(winCommandNative(p), p.env), 384);
@@ -1553,11 +1844,11 @@ function installWindows(p, mode) {
1553
1844
  }
1554
1845
  function enableWindows(label, mode, home) {
1555
1846
  const masterVbs = path.join(winMasterDir(), `${label}.vbs`);
1556
- if (!fs.existsSync(masterVbs)) throw new Error(`no ${label} daemon installed \u2014 run install first`);
1847
+ if (!fs2.existsSync(masterVbs)) throw new Error(`no ${label} daemon installed \u2014 run install first`);
1557
1848
  const startup = winStartupDir(mode);
1558
- fs.mkdirSync(startup, { recursive: true });
1849
+ fs2.mkdirSync(startup, { recursive: true });
1559
1850
  const startupVbs = path.join(startup, `${label}.vbs`);
1560
- fs.copyFileSync(masterVbs, startupVbs);
1851
+ fs2.copyFileSync(masterVbs, startupVbs);
1561
1852
  if (registrationSkipped()) return;
1562
1853
  stopRunningWindowsDaemon(label, mode, home);
1563
1854
  if (mode === "win32") startDetached("wscript.exe", [startupVbs]);
@@ -1565,7 +1856,7 @@ function enableWindows(label, mode, home) {
1565
1856
  }
1566
1857
  function disableWindows(label, mode) {
1567
1858
  const startupVbs = path.join(winStartupDir(mode), `${label}.vbs`);
1568
- if (fs.existsSync(startupVbs)) fs.rmSync(startupVbs);
1859
+ if (fs2.existsSync(startupVbs)) fs2.rmSync(startupVbs);
1569
1860
  if (!registrationSkipped()) {
1570
1861
  const killed = killLauncher(label, mode);
1571
1862
  if (!killed.ok) {
@@ -1577,14 +1868,14 @@ function uninstallWindows(label, mode) {
1577
1868
  disableWindows(label, mode);
1578
1869
  for (const f of [`${label}.vbs`, `${label}.sh`]) {
1579
1870
  const m = path.join(winMasterDir(), f);
1580
- if (fs.existsSync(m)) fs.rmSync(m);
1871
+ if (fs2.existsSync(m)) fs2.rmSync(m);
1581
1872
  }
1582
1873
  }
1583
1874
  function statusWindows(label, mode) {
1584
- const installed = fs.existsSync(path.join(winMasterDir(), `${label}.vbs`));
1875
+ const installed = fs2.existsSync(path.join(winMasterDir(), `${label}.vbs`));
1585
1876
  let enabled = false;
1586
1877
  try {
1587
- enabled = fs.existsSync(path.join(winStartupDir(mode), `${label}.vbs`));
1878
+ enabled = fs2.existsSync(path.join(winStartupDir(mode), `${label}.vbs`));
1588
1879
  } catch {
1589
1880
  }
1590
1881
  const host = mode === "wsl" ? "wsl" : "windows";
@@ -1641,22 +1932,22 @@ function serviceDefinitionCurrent(opts) {
1641
1932
  const wm = winMode();
1642
1933
  if (wm === "win32") {
1643
1934
  const file = path.join(winMasterDir(), `${p.label}.vbs`);
1644
- return fs.existsSync(file) && fs.readFileSync(file, "utf-8") === launcherVbs(winCommandNative(p), p.env);
1935
+ return fs2.existsSync(file) && fs2.readFileSync(file, "utf-8") === launcherVbs(winCommandNative(p), p.env);
1645
1936
  }
1646
1937
  if (wm === "wsl") {
1647
1938
  const script = path.join(winMasterDir(), `${p.label}.sh`);
1648
1939
  const vbs = path.join(winMasterDir(), `${p.label}.vbs`);
1649
1940
  const distro = serviceValue("WSL distro", process.env["WSL_DISTRO_NAME"] ?? "");
1650
1941
  if (!distro) return false;
1651
- return fs.existsSync(script) && fs.existsSync(vbs) && fs.readFileSync(script, "utf-8") === wslScriptContent(p) && fs.readFileSync(vbs, "utf-8") === launcherVbs(`wsl.exe -d "${distro}" -e bash "${script}"`, {});
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}"`, {});
1652
1943
  }
1653
1944
  if (serviceHostOs() === "linux") {
1654
1945
  const file = systemdUnitPath(p.label);
1655
- return fs.existsSync(file) && fs.readFileSync(file, "utf-8") === systemdUnit(p);
1946
+ return fs2.existsSync(file) && fs2.readFileSync(file, "utf-8") === systemdUnit(p);
1656
1947
  }
1657
1948
  if (serviceHostOs() === "darwin") {
1658
1949
  const file = launchdPlistPath(p.label);
1659
- return fs.existsSync(file) && fs.readFileSync(file, "utf-8") === launchdPlist(p);
1950
+ return fs2.existsSync(file) && fs2.readFileSync(file, "utf-8") === launchdPlist(p);
1660
1951
  }
1661
1952
  return false;
1662
1953
  } catch {
@@ -1664,9 +1955,9 @@ function serviceDefinitionCurrent(opts) {
1664
1955
  }
1665
1956
  }
1666
1957
  function unitInstalled(label) {
1667
- if (winMode()) return fs.existsSync(path.join(winMasterDir(), `${label}.vbs`));
1668
- if (serviceHostOs() === "linux") return fs.existsSync(systemdUnitPath(label));
1669
- if (serviceHostOs() === "darwin") return fs.existsSync(launchdPlistPath(label));
1958
+ if (winMode()) return fs2.existsSync(path.join(winMasterDir(), `${label}.vbs`));
1959
+ if (serviceHostOs() === "linux") return fs2.existsSync(systemdUnitPath(label));
1960
+ if (serviceHostOs() === "darwin") return fs2.existsSync(launchdPlistPath(label));
1670
1961
  return false;
1671
1962
  }
1672
1963
  function serviceInstalled(opts) {
@@ -1685,7 +1976,9 @@ export {
1685
1976
  FALLBACK_RUN_PROFILE,
1686
1977
  HEARTBEAT_FILE,
1687
1978
  HOSTED_MCP_PATH,
1979
+ HOST_FILE,
1688
1980
  IDENTITY_ANCHOR_ATTEMPTS,
1981
+ INSTALL_ID_FILE,
1689
1982
  INTEGRATION_ENV,
1690
1983
  INTEGRATION_ENV_LEGACY,
1691
1984
  INTEGRATION_ENV_LEGACY_REMOVAL,
@@ -1694,6 +1987,7 @@ export {
1694
1987
  LEASE_RENEW_MS,
1695
1988
  LEASE_STALE_MS,
1696
1989
  LEGACY_STATUS_FILE,
1990
+ LISTENER_ID_FILE,
1697
1991
  MANUAL,
1698
1992
  MANUAL_FETCH_TIMEOUT_MS,
1699
1993
  MANUAL_FILENAME,
@@ -1710,8 +2004,16 @@ export {
1710
2004
  RUN_CONTEXT_ENV,
1711
2005
  RUN_PROFILES,
1712
2006
  RUN_PROFILE_ENV,
2007
+ SETUP_GRACE_MS,
2008
+ SETUP_STATES,
2009
+ SETUP_WAIT_MS,
1713
2010
  SOCKET_STATES,
1714
2011
  STANDBY_MARKER_FRESH_MS,
2012
+ STOPPED_REPORT_TIMEOUT_MS,
2013
+ TELEMETRY_ENV,
2014
+ TELEMETRY_PATH,
2015
+ TELEMETRY_TIMEOUT_MS,
2016
+ TELEMETRY_VERSION,
1715
2017
  TEXTS_CACHE_FILE,
1716
2018
  VERSION,
1717
2019
  acquireAgentLock,
@@ -1735,6 +2037,7 @@ export {
1735
2037
  clearAlwaysOnOptOut,
1736
2038
  clearAlwaysOnWanted,
1737
2039
  clearCredentials,
2040
+ clearInstallId,
1738
2041
  clearIntegrationStatus,
1739
2042
  clearOfferDeclined,
1740
2043
  clearPending,
@@ -1745,11 +2048,14 @@ export {
1745
2048
  couldNotProcessPath,
1746
2049
  createIdentityCommands,
1747
2050
  credentialsPath,
2051
+ daemonPidOf,
1748
2052
  describeCouldNotProcessCounts,
1749
2053
  describeIdentityBlock,
2054
+ describeListenerStopped,
1750
2055
  describeManualSync,
1751
2056
  describePausedConversations,
1752
2057
  describeRunProfile,
2058
+ ensureInstallId,
1753
2059
  envApiKey,
1754
2060
  envKeyConflict,
1755
2061
  failedCyclesInARow,
@@ -1757,13 +2063,18 @@ export {
1757
2063
  fetchServedTexts,
1758
2064
  followIdentityAnchor,
1759
2065
  formatIntegrationStatus,
2066
+ formatSetupVerdict,
1760
2067
  fromKitResult,
1761
2068
  hasAnchorAt,
1762
2069
  holderLive,
2070
+ hostIdentityOf,
1763
2071
  hostedMcpUrl,
2072
+ httpTelemetrySender,
1764
2073
  identityBlockState,
1765
2074
  identityLineOf,
1766
2075
  idle,
2076
+ installIdPath,
2077
+ installMethodOf,
1767
2078
  installService,
1768
2079
  integrationDisabled,
1769
2080
  integrationDisabledBy,
@@ -1776,6 +2087,8 @@ export {
1776
2087
  isSetupOfferBody,
1777
2088
  launchdPlist,
1778
2089
  leaseHolder,
2090
+ listenerIdPath,
2091
+ listenerReasonKindOf,
1779
2092
  loadTexts,
1780
2093
  log,
1781
2094
  manualFrontMatter,
@@ -1785,6 +2098,8 @@ export {
1785
2098
  markAlwaysOnOptOut,
1786
2099
  markAlwaysOnWanted,
1787
2100
  markStandby,
2101
+ newInstallId,
2102
+ newerRelease,
1788
2103
  normalizeHandle,
1789
2104
  offerDeclined,
1790
2105
  ownProfileLine,
@@ -1793,24 +2108,32 @@ export {
1793
2108
  pendingPath,
1794
2109
  pidAlive,
1795
2110
  placeAnchorAt,
2111
+ placementReportOf,
1796
2112
  planForTest,
1797
2113
  probeHostedMcp,
2114
+ reachabilityOf,
1798
2115
  readAlwaysOnInstalledVersion,
1799
2116
  readAnchorHandleAt,
1800
2117
  readAnchorHandleFrom,
1801
2118
  readCachedTexts,
1802
2119
  readCredentials,
2120
+ readInstallId,
1803
2121
  readIntegrationStatus,
1804
2122
  readJsonFile,
2123
+ readListener,
2124
+ readListenerInstanceId,
1805
2125
  readManualVersion,
1806
2126
  readPending,
2127
+ readRememberedHost,
1807
2128
  readState,
1808
2129
  recordOfferDeclined,
2130
+ rememberHost,
1809
2131
  removeAnchorAt,
1810
2132
  renderAnchorBlock,
1811
2133
  renderDeclinedBlock,
1812
2134
  renderUnregisteredBlock,
1813
2135
  repeatedFailedRuns,
2136
+ reportListenerStopped,
1814
2137
  resetLeaseObservations,
1815
2138
  resolveIdentity,
1816
2139
  resolveManualPointer,
@@ -1820,6 +2143,7 @@ export {
1820
2143
  runProbe,
1821
2144
  runProfileWarning,
1822
2145
  runtimeCheckFailingNow,
2146
+ sendSetupVerdict,
1823
2147
  servedManualUrl,
1824
2148
  serviceDefinitionCurrent,
1825
2149
  serviceInstalled,
@@ -1827,6 +2151,8 @@ export {
1827
2151
  serviceStatus,
1828
2152
  setServiceCommandRunnerForTests,
1829
2153
  setServiceHostOsForTests,
2154
+ setupVerdict,
2155
+ setupVerdictEvent,
1830
2156
  spawnCommand,
1831
2157
  spawnCommandSync,
1832
2158
  standbyMarkerPath,
@@ -1836,6 +2162,7 @@ export {
1836
2162
  syncManual,
1837
2163
  systemdQuote,
1838
2164
  systemdUnit,
2165
+ telemetryOff,
1839
2166
  textsCachePath,
1840
2167
  traySummary,
1841
2168
  uninstallService,