@agentchatme/agent-core 0.4.0 → 0.5.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,12 +1,12 @@
1
1
  import {
2
+ AGENT_LOCK_DIR_ENV,
3
+ DAEMON_LOCK_FILE,
2
4
  DEFAULT_API_BASE,
3
- DEFAULT_RUN_BUDGET_MS,
4
- DEFAULT_RUN_PROFILE,
5
5
  FAILED_CYCLE_OUTCOMES,
6
6
  HEARTBEAT_FILE,
7
- INTEGRATION_ENV,
8
- INTEGRATION_ENV_LEGACY,
9
7
  INTEGRATION_STATUS_FILE,
8
+ LEASE_RENEW_MS,
9
+ LEASE_STALE_MS,
10
10
  LEGACY_STATUS_FILE,
11
11
  MANUAL,
12
12
  MANUAL_FETCH_TIMEOUT_MS,
@@ -16,17 +16,21 @@ import {
16
16
  MANUAL_SKILL_NAME,
17
17
  MANUAL_URL,
18
18
  REPEATED_FAILED_CYCLES,
19
- RUN_BUDGET_ENV,
20
- RUN_PROFILES,
21
- RUN_PROFILE_ENV,
22
19
  SOCKET_STATES,
20
+ STANDBY_MARKER_FRESH_MS,
23
21
  TEXTS_CACHE_FILE,
22
+ acquireAgentLock,
24
23
  acquireLeaderLock,
24
+ acquireLease,
25
+ agentLockDir,
26
+ agentLockPath,
27
+ agentLockRefusal,
25
28
  alwaysOnHealth,
26
29
  alwaysOnOptedOut,
27
30
  alwaysOnState,
28
31
  alwaysOnWanted,
29
32
  beat,
33
+ bootedAt,
30
34
  checkManual,
31
35
  clearAlwaysOnInstalledVersion,
32
36
  clearAlwaysOnOptOut,
@@ -34,6 +38,7 @@ import {
34
38
  clearCredentials,
35
39
  clearIntegrationStatus,
36
40
  clearPending,
41
+ clearStandby,
37
42
  credentialsPath,
38
43
  describeManualSync,
39
44
  envApiKey,
@@ -43,13 +48,13 @@ import {
43
48
  fetchServedTexts,
44
49
  formatIntegrationStatus,
45
50
  fromKitResult,
51
+ holderLive,
52
+ identityLineOf,
46
53
  idle,
47
- integrationDisabled,
48
- integrationDisabledBy,
49
54
  integrationStatusAge,
50
55
  integrationStatusPath,
51
- isRunProfile,
52
56
  isRunnerFactory,
57
+ leaseHolder,
53
58
  loadTexts,
54
59
  manualFrontMatter,
55
60
  manualPointer,
@@ -57,42 +62,63 @@ import {
57
62
  markAlwaysOnInstalledVersion,
58
63
  markAlwaysOnOptOut,
59
64
  markAlwaysOnWanted,
65
+ markStandby,
66
+ normalizeHandle,
67
+ parseLease,
60
68
  pendingPath,
69
+ pidAlive,
61
70
  readAlwaysOnInstalledVersion,
62
71
  readCachedTexts,
63
72
  readCredentials,
64
73
  readIntegrationStatus,
65
74
  readManualVersion,
66
75
  readPending,
76
+ resetLeaseObservations,
67
77
  resolveIdentity,
68
- resolveRunBudgetMs,
69
- resolveRunProfile,
78
+ standbyMarkerPath,
79
+ standbyWaiting,
70
80
  statePath,
71
81
  syncManual,
72
82
  textsCachePath,
73
83
  writeCredentials,
74
84
  writeIntegrationStatus,
75
85
  writePending
76
- } from "./chunk-W3LYBKIV.js";
86
+ } from "./chunk-NAAHIK7Z.js";
77
87
  import {
78
88
  HOSTED_MCP_PATH,
89
+ PROBE_KILL_WAIT_MS,
90
+ VERSION,
79
91
  hostedMcpUrl,
80
- probeHostedMcp
81
- } from "./chunk-HOY2FERJ.js";
92
+ probeHostedMcp,
93
+ runProbe
94
+ } from "./chunk-UE7DKW3C.js";
82
95
  import {
96
+ DEFAULT_RUN_BUDGET_MS,
97
+ DEFAULT_RUN_PROFILE,
98
+ INTEGRATION_ENV,
99
+ INTEGRATION_ENV_LEGACY,
100
+ INTEGRATION_ENV_LEGACY_REMOVAL,
101
+ PEER_RUN_WARNING,
102
+ RUN_BUDGET_ENV,
103
+ RUN_PROFILES,
104
+ RUN_PROFILE_ENV,
83
105
  atomicCopyFile,
84
106
  atomicWriteFile,
85
107
  clientHeadersOf,
86
108
  clientIdentityOf,
87
109
  clientNameOf,
110
+ integrationDisabled,
111
+ integrationDisabledBy,
112
+ isRunProfile,
88
113
  log,
89
114
  readJsonFile,
115
+ resolveRunBudgetMs,
116
+ resolveRunProfile,
117
+ runProfileWarning,
90
118
  spawnCommand,
91
- spawnCommandSync
92
- } from "./chunk-NCSF3CCV.js";
93
-
94
- // src/version.ts
95
- var VERSION = "0.4.0";
119
+ spawnCommandSync,
120
+ workdirExposesHome
121
+ } from "./chunk-AFDD53DD.js";
96
122
 
97
123
  // src/integration/tray.ts
98
124
  import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
@@ -138,115 +164,161 @@ function clearOfferDeclined(home) {
138
164
  writeState(home, state);
139
165
  }
140
166
 
141
- // src/skill/identity-line.ts
142
- function identityLineOf(texts) {
143
- return texts.identity_line;
144
- }
145
- function normalizeHandle(handle) {
146
- return handle.trim().replace(/^@/, "").toLowerCase();
147
- }
148
-
149
167
  // src/anchor/block.ts
150
168
  import * as fs from "fs";
151
169
  import * as path from "path";
152
- var ANCHOR_START = "<!-- agentchat:start -->";
153
- var ANCHOR_END = "<!-- agentchat:end -->";
154
- var LEGACY_ANCHOR_START = "<!-- agentchat-skill:start -->";
155
- var LEGACY_ANCHOR_END = "<!-- agentchat-skill:end -->";
156
- function renderAnchorBlock(identityLine) {
157
- const line = identityLine.trim();
158
- if (line.length === 0) throw new Error("renderAnchorBlock: the identity line is empty");
159
- return [ANCHOR_START, line, ANCHOR_END].join("\n");
170
+ import { integration as kit } from "agentchatme";
171
+ var ANCHOR_START = kit.anchor.START_MARKER;
172
+ var ANCHOR_END = kit.anchor.END_MARKER;
173
+ var MARKER_LINES = /* @__PURE__ */ new Set([
174
+ kit.anchor.START_MARKER,
175
+ kit.anchor.END_MARKER,
176
+ kit.anchor.LEGACY_START_MARKER,
177
+ kit.anchor.LEGACY_END_MARKER
178
+ ]);
179
+ function renderAnchorBlock(identityLine, handle) {
180
+ if (typeof identityLine !== "string" || identityLine.trim().length === 0) throw new Error("renderAnchorBlock: the identity line is empty");
181
+ if (typeof handle !== "string" || kit.anchor.normalizeHandle(handle).length === 0) throw new Error("renderAnchorBlock: the handle is empty");
182
+ if (identityLine.split(/\r?\n/).some((line) => MARKER_LINES.has(line.trim()))) {
183
+ throw new Error("renderAnchorBlock: the identity line holds an AgentChat marker line");
184
+ }
185
+ return kit.anchor.render({ identity_line: identityLine, identity_line_template: "" }, handle);
160
186
  }
161
187
  function writeAnchor(filePath, block, expectHandle) {
162
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
163
- const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf-8") : "";
164
- fs.writeFileSync(filePath, upsertAnchorBlock(existing, block), "utf-8");
165
188
  if (expectHandle !== void 0) {
166
- const verify = fs.readFileSync(filePath, "utf-8");
167
- if (!verify.includes(`@${expectHandle}`)) {
168
- throw new Error(
169
- `writeAnchor: handle @${expectHandle} did not land in ${filePath} \u2014 remove the agentchat block manually and re-run.`
170
- );
189
+ const bare = kit.anchor.normalizeHandle(expectHandle);
190
+ const claimed = kit.anchor.find(block)?.handle ?? null;
191
+ if (claimed !== bare) {
192
+ throw new Error(`writeAnchor: the block for ${filePath} does not name @${bare} \u2014 nothing was written`);
171
193
  }
172
194
  }
195
+ const existing = readInstructionFile(filePath) ?? { bom: "", text: "" };
196
+ const next = untilStable(existing.text, (text) => kit.anchor.replace(text, block));
197
+ if (next !== existing.text) writeInstructionFile(filePath, existing.bom + next);
198
+ if (expectHandle !== void 0 && readInstructionFile(filePath)?.text !== next) {
199
+ throw new Error(`writeAnchor: ${filePath} did not read back as written \u2014 remove the agentchat block manually and re-run`);
200
+ }
173
201
  return "written";
174
202
  }
203
+ function untilStable(text, step) {
204
+ let current = text;
205
+ for (let i = 0; i < 8; i++) {
206
+ const next = step(current);
207
+ if (next === current) return current;
208
+ current = next;
209
+ }
210
+ return current;
211
+ }
175
212
  function removeAnchorAt(filePath) {
176
- if (!fs.existsSync(filePath)) return "noop";
177
- const existing = fs.readFileSync(filePath, "utf-8");
178
- const next = stripAnchorBlock(existing);
179
- if (next === existing) return "noop";
180
- fs.writeFileSync(filePath, next, "utf-8");
213
+ const existing = readInstructionFile(filePath);
214
+ if (existing === null) return "noop";
215
+ const next = untilStable(existing.text, (text) => kit.anchor.remove(text));
216
+ if (next === existing.text) return "noop";
217
+ writeInstructionFile(filePath, existing.bom + next);
181
218
  return "removed";
182
219
  }
183
220
  function hasAnchorAt(filePath) {
184
- if (!fs.existsSync(filePath)) return false;
185
- return findBlock(fs.readFileSync(filePath, "utf-8"), ANCHOR_START, ANCHOR_END) !== null;
186
- }
187
- function anchorIsCurrentAt(filePath, identityLine) {
188
- if (!fs.existsSync(filePath)) return false;
189
- const text = fs.readFileSync(filePath, "utf-8");
190
- const block = findBlock(text, ANCHOR_START, ANCHOR_END);
191
- if (block === null) return false;
192
- return text.slice(block.from, block.to) === renderAnchorBlock(identityLine);
193
- }
194
- var IDENTITY_HANDLE_RE = /I am @([^\s]+) on AgentChat/;
195
- var LEGACY_HANDLE_RE = /\*\*@([^*\s]+)\*\*/;
196
- function readAnchorHandleAt(filePath) {
197
- if (!fs.existsSync(filePath)) return null;
198
- return readAnchorHandleFrom(fs.readFileSync(filePath, "utf-8"));
199
- }
200
- function readAnchorHandleFrom(text) {
201
- const block = findBlock(text, ANCHOR_START, ANCHOR_END);
202
- if (block === null) return null;
203
- const inside = text.slice(block.from, block.to);
204
- const match = IDENTITY_HANDLE_RE.exec(inside) ?? LEGACY_HANDLE_RE.exec(inside);
205
- return match?.[1] ?? null;
206
- }
207
- function lineAnchoredIndex(text, marker, fromIndex = 0) {
208
- let idx = text.indexOf(marker, fromIndex);
209
- while (idx >= 0) {
210
- const lineStart = text.lastIndexOf("\n", idx - 1) + 1;
211
- const lineEndRaw = text.indexOf("\n", idx);
212
- const lineEnd = lineEndRaw === -1 ? text.length : lineEndRaw;
213
- if (text.slice(lineStart, lineEnd).trim() === marker) {
214
- return { start: lineStart, end: lineEnd };
215
- }
216
- idx = text.indexOf(marker, idx + marker.length);
221
+ const file = readInstructionFile(filePath);
222
+ return file !== null && kit.anchor.find(file.text) !== null;
223
+ }
224
+ function anchorIsCurrentAt(filePath, identityLine, handle) {
225
+ const file = readInstructionFile(filePath);
226
+ if (file === null) return false;
227
+ let expected;
228
+ try {
229
+ expected = renderAnchorBlock(identityLine, handle);
230
+ } catch {
231
+ return false;
217
232
  }
218
- return null;
233
+ if (kit.anchor.find(file.text) === null) return false;
234
+ return kit.anchor.replace(file.text, expected) === file.text;
219
235
  }
220
- function findBlock(text, startMarker, endMarker) {
221
- const start = lineAnchoredIndex(text, startMarker);
222
- if (start === null) return null;
223
- const end = lineAnchoredIndex(text, endMarker, start.end);
224
- if (end === null) return null;
225
- return { from: start.start, to: end.end };
236
+ function readAnchorHandleAt(filePath, template) {
237
+ const file = readInstructionFile(filePath);
238
+ return file === null ? null : readAnchorHandleFrom(file.text, template);
239
+ }
240
+ function readAnchorHandleFrom(text, template) {
241
+ return kit.anchor.find(text.replace(/^\uFEFF/, ""), { template })?.handle ?? null;
226
242
  }
227
243
  function upsertAnchorBlock(existing, block) {
228
- const cleaned = stripAnchorBlock(existing);
229
- const trimmed = cleaned.replace(/\n+$/, "");
230
- if (trimmed.length === 0) return block + "\n";
231
- return trimmed + "\n\n" + block + "\n";
244
+ return kit.anchor.replace(existing, block);
232
245
  }
233
246
  function stripAnchorBlock(existing) {
234
- const afterUnified = stripAllBlocks(existing, ANCHOR_START, ANCHOR_END);
235
- return stripAllBlocks(afterUnified, LEGACY_ANCHOR_START, LEGACY_ANCHOR_END);
236
- }
237
- function stripAllBlocks(existing, start, end) {
238
- let text = existing;
239
- for (let i = 0; i < 1e4; i++) {
240
- const block = findBlock(text, start, end);
241
- if (block === null) return text;
242
- const before = text.slice(0, block.from).replace(/\n+$/, "");
243
- const after = text.slice(block.to).replace(/^\n+/, "");
244
- if (before.length === 0 && after.length === 0) return "";
245
- if (before.length === 0) text = after.endsWith("\n") ? after : after + "\n";
246
- else if (after.length === 0) text = before + "\n";
247
- else text = before + "\n\n" + after + (after.endsWith("\n") ? "" : "\n");
247
+ return kit.anchor.remove(existing);
248
+ }
249
+ var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
250
+ function readInstructionFile(filePath) {
251
+ let bytes;
252
+ try {
253
+ bytes = fs.readFileSync(filePath);
254
+ } catch (err) {
255
+ if (err.code === "ENOENT") return null;
256
+ throw err;
257
+ }
258
+ let decoded;
259
+ try {
260
+ decoded = UTF8.decode(bytes);
261
+ } catch {
262
+ 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)`);
263
+ }
264
+ return decoded.startsWith("\uFEFF") ? { bom: "\uFEFF", text: decoded.slice(1) } : { bom: "", text: decoded };
265
+ }
266
+ function resolveWriteTarget(filePath) {
267
+ let current = filePath;
268
+ for (let hops = 0; hops < 40; hops++) {
269
+ let stat;
270
+ try {
271
+ stat = fs.lstatSync(current);
272
+ } catch (err) {
273
+ if (err.code === "ENOENT") return current;
274
+ throw err;
275
+ }
276
+ if (!stat.isSymbolicLink()) return current;
277
+ const link = fs.readlinkSync(current);
278
+ const joined = path.isAbsolute(link) ? link : `${fs.realpathSync.native(path.dirname(current))}${path.sep}${link}`;
279
+ current = path.join(fs.realpathSync.native(path.dirname(joined)), path.basename(joined));
280
+ }
281
+ throw Object.assign(new Error(`${filePath}: too many symbolic links`), { code: "ELOOP" });
282
+ }
283
+ var IN_PLACE_FALLBACK_CODES = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS", "EBUSY", "EXDEV"]);
284
+ function stillWritable(file) {
285
+ try {
286
+ fs.accessSync(file, fs.constants.W_OK);
287
+ return true;
288
+ } catch {
289
+ return false;
290
+ }
291
+ }
292
+ function writeInstructionFile(filePath, data) {
293
+ const target = resolveWriteTarget(filePath);
294
+ let existing = null;
295
+ try {
296
+ existing = fs.statSync(target);
297
+ } catch (err) {
298
+ if (err.code !== "ENOENT") throw err;
299
+ }
300
+ if (existing !== null) {
301
+ if (!existing.isFile()) throw new Error(`${filePath} is not a regular file`);
302
+ fs.accessSync(target, fs.constants.W_OK);
303
+ } else {
304
+ fs.mkdirSync(path.dirname(target), { recursive: true });
305
+ }
306
+ try {
307
+ atomicWriteFile(target, data, existing === null ? void 0 : existing.mode & 4095);
308
+ } catch (err) {
309
+ const code = err.code;
310
+ if (existing !== null && code !== void 0 && IN_PLACE_FALLBACK_CODES.has(code) && stillWritable(target)) {
311
+ fs.writeFileSync(target, data, "utf-8");
312
+ return;
313
+ }
314
+ throw err;
315
+ }
316
+ if (existing !== null && typeof process.getuid === "function" && process.getuid() === 0 && (existing.uid !== 0 || existing.gid !== 0)) {
317
+ try {
318
+ fs.chownSync(target, existing.uid, existing.gid);
319
+ } catch {
320
+ }
248
321
  }
249
- return text;
250
322
  }
251
323
 
252
324
  // src/anchor/offer.ts
@@ -326,6 +398,13 @@ var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
326
398
  function validHandle(handle) {
327
399
  return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle);
328
400
  }
401
+ var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
402
+ function errorText(err) {
403
+ return err instanceof Error ? err.message : String(err);
404
+ }
405
+ function contextOf(texts) {
406
+ return { identityLine: identityLineOf(texts), identityLineTemplate: texts.identity_line_template, manual: texts.manual };
407
+ }
329
408
  async function prompt(question) {
330
409
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
331
410
  try {
@@ -401,7 +480,7 @@ function createIdentityCommands(profile) {
401
480
  const apiClient = (apiKey, apiBase, budget = "quick") => budget === "quick" ? new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } }) : new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 15e3 });
402
481
  async function served(apiKey, apiBase) {
403
482
  const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5e3 });
404
- return loaded === null ? { identityLine: null, manual: null } : { identityLine: identityLineOf(loaded.texts), manual: loaded.texts.manual };
483
+ return loaded === null ? NO_TEXTS : contextOf(loaded.texts);
405
484
  }
406
485
  async function printExtraStatus(context) {
407
486
  if (profile.extraStatus === void 0) return;
@@ -426,14 +505,14 @@ function createIdentityCommands(profile) {
426
505
  if (profile.anchorFile === void 0) return [];
427
506
  const file = profile.anchorFile();
428
507
  const label = anchorLabelOf(profile);
429
- if (profile.isWired !== void 0 && !profile.isWired() && !hasAnchorAt(file)) return [];
430
- if (identityLine === null) {
431
- return [
432
- ` ${label}: identity line not written \u2014 GET /v1/texts could not be reached and nothing is cached; run \`${invocation()} doctor --fix\` once online`
433
- ];
434
- }
435
508
  try {
436
- writeAnchor(file, profile.renderAnchor(identityLine), handle);
509
+ if (profile.isWired !== void 0 && !profile.isWired() && !hasAnchorAt(file)) return [];
510
+ if (identityLine === null) {
511
+ return [
512
+ ` ${label}: identity line not written \u2014 GET /v1/texts could not be reached and nothing is cached; run \`${invocation()} doctor --fix\` once online`
513
+ ];
514
+ }
515
+ writeAnchor(file, profile.renderAnchor(identityLine, handle), handle);
437
516
  return [` ${label}: @${handle} \u2192 ${file}`];
438
517
  } catch (err) {
439
518
  return [` ${label}: FAILED \u2014 ${String(err)}`];
@@ -718,6 +797,16 @@ function createIdentityCommands(profile) {
718
797
  return 1;
719
798
  }
720
799
  }
800
+ function anchorView(file, identityLine, handle) {
801
+ if (file === null) return { present: null, current: null, error: null };
802
+ try {
803
+ const present = hasAnchorAt(file);
804
+ const current = identityLine === null || handle === null ? null : anchorIsCurrentAt(file, identityLine, handle);
805
+ return { present, current, error: null };
806
+ } catch (err) {
807
+ return { present: null, current: null, error: errorText(err) };
808
+ }
809
+ }
721
810
  async function runStatus(opts) {
722
811
  const home = profile.home();
723
812
  const anchorFile = profile.anchorFile?.() ?? null;
@@ -732,9 +821,7 @@ function createIdentityCommands(profile) {
732
821
  host: profile.id,
733
822
  pending: pending !== null,
734
823
  pending_kind: pending?.kind ?? null,
735
- integration,
736
- // The previous key, kept one release for scripts that read it.
737
- doorbell: integration
824
+ integration
738
825
  })
739
826
  );
740
827
  } else if (pending?.kind === "recover") {
@@ -760,6 +847,7 @@ function createIdentityCommands(profile) {
760
847
  const refused = status === 401 || status === 403;
761
848
  const detail = apiErr(err);
762
849
  if (opts.json) {
850
+ const offline = anchorView(anchorFile, null, null);
763
851
  console.log(
764
852
  JSON.stringify({
765
853
  configured: true,
@@ -769,9 +857,9 @@ function createIdentityCommands(profile) {
769
857
  key_source: identity.source,
770
858
  api_base: identity.apiBase,
771
859
  home,
772
- anchor: anchorFile === null ? null : hasAnchorAt(anchorFile),
773
- integration,
774
- doorbell: integration
860
+ anchor: offline.present,
861
+ anchor_error: offline.error,
862
+ integration
775
863
  })
776
864
  );
777
865
  } else {
@@ -787,14 +875,14 @@ function createIdentityCommands(profile) {
787
875
  ].join("\n")
788
876
  );
789
877
  const cached = readCachedTexts(home, profile.client.runtime);
790
- await printExtraStatus(cached === null ? { identityLine: null, manual: null } : { identityLine: identityLineOf(cached.texts), manual: cached.texts.manual });
878
+ await printExtraStatus(cached === null ? NO_TEXTS : contextOf(cached.texts));
791
879
  }
792
880
  return 1;
793
881
  }
794
882
  const tray = await traySummary(client).catch(() => null);
795
883
  const texts = await served(identity.apiKey, identity.apiBase);
796
884
  const identityLine = texts.identityLine;
797
- const anchorCurrent = identityLine === null || anchorFile === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
885
+ const anchor = anchorView(anchorFile, identityLine, me.handle);
798
886
  if (opts.json) {
799
887
  console.log(
800
888
  JSON.stringify({
@@ -806,11 +894,12 @@ function createIdentityCommands(profile) {
806
894
  key_source: identity.source,
807
895
  api_base: identity.apiBase,
808
896
  home,
809
- anchor: anchorFile === null ? null : hasAnchorAt(anchorFile),
810
- /** null: the served texts were unavailable (or there is no instruction file), so currency could not be checked. */
811
- anchor_current: anchorCurrent,
812
- integration,
813
- doorbell: integration
897
+ anchor: anchor.present,
898
+ /** null: the served texts were unavailable (or there is no instruction file, or it cannot be read), so currency could not be checked. */
899
+ anchor_current: anchor.current,
900
+ /** Why the instruction file could not be read, or null. */
901
+ anchor_error: anchor.error,
902
+ integration
814
903
  })
815
904
  );
816
905
  } else {
@@ -822,7 +911,7 @@ function createIdentityCommands(profile) {
822
911
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
823
912
  `API: ${identity.apiBase}`,
824
913
  ...anchorFile === null ? [] : [
825
- `Identity line: ${hasAnchorAt(anchorFile) ? anchorCurrent === null ? "present (served texts unavailable \u2014 not checked)" : anchorCurrent ? "current" : "present (older text \u2014 `doctor --fix` refreshes it)" : "missing"} (${anchorFile})`
914
+ `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})`
826
915
  ],
827
916
  ...formatIntegrationStatus(integration)
828
917
  ].join("\n")
@@ -841,9 +930,16 @@ function createIdentityCommands(profile) {
841
930
  any = true;
842
931
  reports.push(" credentials deleted");
843
932
  }
844
- if (anchorFile !== null && removeAnchorAt(anchorFile) === "removed") {
845
- any = true;
846
- reports.push(` ${anchorLabelOf(profile)} identity line removed`);
933
+ if (anchorFile !== null) {
934
+ try {
935
+ if (removeAnchorAt(anchorFile) === "removed") {
936
+ any = true;
937
+ reports.push(` ${anchorLabelOf(profile)} identity line removed`);
938
+ }
939
+ } catch (err) {
940
+ any = true;
941
+ reports.push(` could not remove the identity line from ${anchorFile}: ${errorText(err)} \u2014 remove the agentchat block by hand`);
942
+ }
847
943
  }
848
944
  if (profile.unplace !== void 0) {
849
945
  try {
@@ -866,9 +962,20 @@ function createIdentityCommands(profile) {
866
962
  );
867
963
  return 0;
868
964
  }
869
- async function identityLineCheck(anchorFile, creds, apiBase, identityLine, fix) {
870
- const claimed = readAnchorHandleAt(anchorFile);
871
- const current = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
965
+ function readIdentityLine(anchorFile, handle, texts) {
966
+ const claimed = readAnchorHandleAt(anchorFile, texts.identityLineTemplate);
967
+ const current = texts.identityLine === null ? null : anchorIsCurrentAt(anchorFile, texts.identityLine, handle);
968
+ return { claimed, current };
969
+ }
970
+ async function identityLineCheck(anchorFile, creds, apiBase, texts, fix) {
971
+ let claimed;
972
+ let current;
973
+ try {
974
+ ;
975
+ ({ claimed, current } = readIdentityLine(anchorFile, creds.handle, texts));
976
+ } catch (err) {
977
+ return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile}: ${errorText(err)}` };
978
+ }
872
979
  if (claimed === creds.handle && current === true) {
873
980
  return { name: "identity-line", verdict: "PASS", detail: `@${claimed} in ${anchorFile}` };
874
981
  }
@@ -879,11 +986,16 @@ function createIdentityCommands(profile) {
879
986
  if (fix) {
880
987
  const report = await placeIdentity(creds.handle, creds.api_key, apiBase);
881
988
  const failed = report.some((l) => l.includes("FAILED") || l.includes("not written"));
882
- return {
883
- name: "identity-line",
884
- verdict: failed ? "FAIL" : "PASS",
885
- detail: failed ? `could not repair: ${report.join("; ")}` : `repaired \u2192 @${creds.handle}`
886
- };
989
+ if (failed) return { name: "identity-line", verdict: "FAIL", detail: `could not repair: ${report.join("; ")}` };
990
+ try {
991
+ const after = readIdentityLine(anchorFile, creds.handle, texts);
992
+ if (after.claimed === creds.handle && after.current !== false) {
993
+ return { name: "identity-line", verdict: "PASS", detail: `repaired \u2192 @${creds.handle}` };
994
+ }
995
+ return { name: "identity-line", verdict: "FAIL", detail: `repair did not take: ${anchorFile} still ${after.claimed === null ? "has no identity line" : after.claimed !== creds.handle ? `says @${after.claimed}` : "differs from the served block"}${report.length > 0 ? ` (${report.join("; ").trim()})` : ""}` };
996
+ } catch (err) {
997
+ return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile} after the repair: ${errorText(err)}` };
998
+ }
887
999
  }
888
1000
  return { name: "identity-line", verdict: "WARN", detail: `${why} \u2014 repair with \`${invocation()} doctor --fix\`` };
889
1001
  }
@@ -891,8 +1003,7 @@ function createIdentityCommands(profile) {
891
1003
  const home = profile.home();
892
1004
  const anchorFile = profile.anchorFile?.() ?? null;
893
1005
  const checks = [];
894
- let identityLine = null;
895
- let manual = null;
1006
+ let texts = NO_TEXTS;
896
1007
  checks.push({ name: "node", verdict: "PASS", detail: process.version });
897
1008
  checks.push({ name: "home", verdict: "PASS", detail: home });
898
1009
  const creds = readCredentials(home);
@@ -928,13 +1039,36 @@ function createIdentityCommands(profile) {
928
1039
  }
929
1040
  }
930
1041
  const apiBase = identity?.apiBase ?? creds.api_base ?? DEFAULT_API_BASE;
931
- ({ identityLine, manual } = await served(creds.api_key, apiBase));
1042
+ texts = await served(creds.api_key, apiBase);
932
1043
  checks.push(
933
- identityLine === null ? { name: "texts", verdict: "WARN", detail: "GET /v1/texts could not be reached and nothing is cached \u2014 the identity line cannot be checked or placed until it can" } : { name: "texts", verdict: "PASS", detail: "served texts in hand" }
1044
+ texts.identityLine === null ? { name: "texts", verdict: "WARN", detail: "GET /v1/texts could not be reached and nothing is cached \u2014 the identity line cannot be checked or placed until it can" } : { name: "texts", verdict: "PASS", detail: "served texts in hand" }
934
1045
  );
935
- if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, identityLine, opts.fix === true));
1046
+ if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true));
936
1047
  }
937
1048
  const integration = readIntegrationStatus(home);
1049
+ const runsFailing = integration?.runs_failing ?? null;
1050
+ const gaveUp = integration?.unservable ?? null;
1051
+ if (gaveUp !== null) {
1052
+ checks.push({
1053
+ name: "runs",
1054
+ verdict: "FAIL",
1055
+ detail: gaveUp.reason === "key_refused" ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); it looks again at ${gaveUp.retry_at} (every 5 min) and takes the agent back whenever no other listener holds it, but only a key the server accepts can serve \u2014 sign in again here (login/recover; that clears this at once), or log out if another home serves the agent` : `this home gave the agent up: ${gaveUp.detail} (since ${gaveUp.since}); its runtime is checked again at ${gaveUp.retry_at} (every 60 s) and a check that passes clears this; it takes the agent back whenever no other listener holds it`
1056
+ });
1057
+ } else if (runsFailing !== null) {
1058
+ checks.push({
1059
+ name: "runs",
1060
+ verdict: "FAIL",
1061
+ detail: `runs failing: ${runsFailing.reason} \u2014 since ${runsFailing.since}, ${runsFailing.runs_missed} run(s) missed (checked ${runsFailing.checked_at}); fix that, and the next run that succeeds clears this`
1062
+ });
1063
+ }
1064
+ const standby = integration?.standby ?? null;
1065
+ if (standby !== null) {
1066
+ checks.push({
1067
+ name: "single-listener",
1068
+ verdict: "WARN",
1069
+ detail: `another listener serves this agent: ${standby.home ?? "another identity home"}${standby.pid !== null ? ` (pid ${standby.pid})` : ""}; this one stands by (no socket, no run) so no message is answered twice`
1070
+ });
1071
+ }
938
1072
  const cycles = integration?.recent_cycles ?? [];
939
1073
  if (cycles.length > 0) {
940
1074
  const failing = failedCyclesInARow(integration);
@@ -947,7 +1081,13 @@ function createIdentityCommands(profile) {
947
1081
  } : { name: "wake-cycles", verdict: "PASS", detail: `last cycle ${last.outcome} at ${last.at} (${cycles.length} recent)` }
948
1082
  );
949
1083
  }
950
- if (profile.extraDoctorChecks !== void 0) checks.push(...await profile.extraDoctorChecks({ ...opts, identityLine, manual }));
1084
+ if (profile.extraDoctorChecks !== void 0) {
1085
+ try {
1086
+ checks.push(...await profile.extraDoctorChecks({ ...opts, ...texts }));
1087
+ } catch (err) {
1088
+ checks.push({ name: "host", verdict: "FAIL", detail: `the ${LABEL} checks failed: ${errorText(err)}` });
1089
+ }
1090
+ }
951
1091
  console.log(checks.map((c) => `${c.verdict.padEnd(4)} ${c.name}: ${c.detail}`).join("\n"));
952
1092
  return checks.some((c) => c.verdict === "FAIL") ? 1 : 0;
953
1093
  }
@@ -1452,9 +1592,11 @@ function killLauncher(label, mode) {
1452
1592
  return run(mode === "win32" ? "powershell" : "powershell.exe", ["-NoProfile", "-Command", ps]);
1453
1593
  }
1454
1594
  function lockedDaemonPid(home) {
1595
+ const file = path2.join(home, DAEMON_LOCK_FILE);
1455
1596
  try {
1456
- const pid = Number.parseInt(fs2.readFileSync(path2.join(home, "daemon.lock"), "utf-8").trim(), 10);
1457
- return Number.isInteger(pid) && pid > 0 ? pid : null;
1597
+ const holder = parseLease(fs2.readFileSync(file, "utf-8"));
1598
+ if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null;
1599
+ return holderLive(holder, { mtimeMs: fs2.statSync(file).mtimeMs }) ? holder.pid : null;
1458
1600
  } catch {
1459
1601
  return null;
1460
1602
  }
@@ -1611,8 +1753,10 @@ function serviceInstalled(opts) {
1611
1753
  return unitInstalled(serviceLabel(opts.label));
1612
1754
  }
1613
1755
  export {
1756
+ AGENT_LOCK_DIR_ENV,
1614
1757
  ANCHOR_END,
1615
1758
  ANCHOR_START,
1759
+ DAEMON_LOCK_FILE,
1616
1760
  DEFAULT_API_BASE,
1617
1761
  DEFAULT_RUN_BUDGET_MS,
1618
1762
  DEFAULT_RUN_PROFILE,
@@ -1621,7 +1765,10 @@ export {
1621
1765
  HOSTED_MCP_PATH,
1622
1766
  INTEGRATION_ENV,
1623
1767
  INTEGRATION_ENV_LEGACY,
1768
+ INTEGRATION_ENV_LEGACY_REMOVAL,
1624
1769
  INTEGRATION_STATUS_FILE,
1770
+ LEASE_RENEW_MS,
1771
+ LEASE_STALE_MS,
1625
1772
  LEGACY_STATUS_FILE,
1626
1773
  MANUAL,
1627
1774
  MANUAL_FETCH_TIMEOUT_MS,
@@ -1630,14 +1777,22 @@ export {
1630
1777
  MANUAL_MAX_REDIRECTS,
1631
1778
  MANUAL_SKILL_NAME,
1632
1779
  MANUAL_URL,
1780
+ PEER_RUN_WARNING,
1781
+ PROBE_KILL_WAIT_MS,
1633
1782
  REPEATED_FAILED_CYCLES,
1634
1783
  RUN_BUDGET_ENV,
1635
1784
  RUN_PROFILES,
1636
1785
  RUN_PROFILE_ENV,
1637
1786
  SOCKET_STATES,
1787
+ STANDBY_MARKER_FRESH_MS,
1638
1788
  TEXTS_CACHE_FILE,
1639
1789
  VERSION,
1790
+ acquireAgentLock,
1640
1791
  acquireLeaderLock,
1792
+ acquireLease,
1793
+ agentLockDir,
1794
+ agentLockPath,
1795
+ agentLockRefusal,
1641
1796
  alwaysOnHealth,
1642
1797
  alwaysOnOptedOut,
1643
1798
  alwaysOnState,
@@ -1647,6 +1802,7 @@ export {
1647
1802
  atomicCopyFile,
1648
1803
  atomicWriteFile,
1649
1804
  beat,
1805
+ bootedAt,
1650
1806
  checkManual,
1651
1807
  clearAlwaysOnInstalledVersion,
1652
1808
  clearAlwaysOnOptOut,
@@ -1655,6 +1811,7 @@ export {
1655
1811
  clearIntegrationStatus,
1656
1812
  clearOfferDeclined,
1657
1813
  clearPending,
1814
+ clearStandby,
1658
1815
  clientHeadersOf,
1659
1816
  clientIdentityOf,
1660
1817
  clientNameOf,
@@ -1668,6 +1825,7 @@ export {
1668
1825
  formatIntegrationStatus,
1669
1826
  fromKitResult,
1670
1827
  hasAnchorAt,
1828
+ holderLive,
1671
1829
  hostedMcpUrl,
1672
1830
  identityLineOf,
1673
1831
  idle,
@@ -1679,6 +1837,7 @@ export {
1679
1837
  isRunProfile,
1680
1838
  isRunnerFactory,
1681
1839
  launchdPlist,
1840
+ leaseHolder,
1682
1841
  loadTexts,
1683
1842
  log,
1684
1843
  manualFrontMatter,
@@ -1687,10 +1846,13 @@ export {
1687
1846
  markAlwaysOnInstalledVersion,
1688
1847
  markAlwaysOnOptOut,
1689
1848
  markAlwaysOnWanted,
1849
+ markStandby,
1690
1850
  normalizeHandle,
1691
1851
  offerDeclined,
1852
+ parseLease,
1692
1853
  parseServiceHome,
1693
1854
  pendingPath,
1855
+ pidAlive,
1694
1856
  planForTest,
1695
1857
  probeHostedMcp,
1696
1858
  readAlwaysOnInstalledVersion,
@@ -1708,9 +1870,12 @@ export {
1708
1870
  renderAnchorBlock,
1709
1871
  renderDeclinedBlock,
1710
1872
  renderUnregisteredBlock,
1873
+ resetLeaseObservations,
1711
1874
  resolveIdentity,
1712
1875
  resolveRunBudgetMs,
1713
1876
  resolveRunProfile,
1877
+ runProbe,
1878
+ runProfileWarning,
1714
1879
  serviceDefinitionCurrent,
1715
1880
  serviceInstalled,
1716
1881
  serviceLabelFor,
@@ -1719,6 +1884,8 @@ export {
1719
1884
  setServiceHostOsForTests,
1720
1885
  spawnCommand,
1721
1886
  spawnCommandSync,
1887
+ standbyMarkerPath,
1888
+ standbyWaiting,
1722
1889
  statePath,
1723
1890
  stripAnchorBlock,
1724
1891
  syncManual,
@@ -1728,6 +1895,7 @@ export {
1728
1895
  traySummary,
1729
1896
  uninstallService,
1730
1897
  upsertAnchorBlock,
1898
+ workdirExposesHome,
1731
1899
  writeAnchor,
1732
1900
  writeCredentials,
1733
1901
  writeIntegrationStatus,