@agentchatme/agent-core 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,9 +2,11 @@ import {
2
2
  DEFAULT_API_BASE,
3
3
  DEFAULT_RUN_BUDGET_MS,
4
4
  DEFAULT_RUN_PROFILE,
5
+ FAILED_CYCLE_OUTCOMES,
5
6
  HEARTBEAT_FILE,
6
7
  INTEGRATION_ENV,
7
8
  INTEGRATION_ENV_LEGACY,
9
+ INTEGRATION_ENV_LEGACY_REMOVAL,
8
10
  INTEGRATION_STATUS_FILE,
9
11
  LEGACY_STATUS_FILE,
10
12
  MANUAL,
@@ -14,24 +16,18 @@ import {
14
16
  MANUAL_MAX_REDIRECTS,
15
17
  MANUAL_SKILL_NAME,
16
18
  MANUAL_URL,
17
- ManualFollower,
19
+ REPEATED_FAILED_CYCLES,
18
20
  RUN_BUDGET_ENV,
19
21
  RUN_PROFILES,
20
22
  RUN_PROFILE_ENV,
21
23
  SOCKET_STATES,
22
24
  TEXTS_CACHE_FILE,
23
- TEXTS_REFRESH_MS,
24
- TEXTS_RETRY_MS,
25
- TextsStore,
26
25
  acquireLeaderLock,
27
26
  alwaysOnHealth,
28
27
  alwaysOnOptedOut,
29
28
  alwaysOnState,
30
29
  alwaysOnWanted,
31
- atomicCopyFile,
32
- atomicWriteFile,
33
30
  beat,
34
- buildRunPrompts,
35
31
  checkManual,
36
32
  clearAlwaysOnInstalledVersion,
37
33
  clearAlwaysOnOptOut,
@@ -39,56 +35,74 @@ import {
39
35
  clearCredentials,
40
36
  clearIntegrationStatus,
41
37
  clearPending,
42
- clientHeadersOf,
43
- clientIdentityOf,
44
38
  credentialsPath,
45
39
  describeManualSync,
40
+ envApiKey,
46
41
  external_exports,
42
+ failedCyclesInARow,
47
43
  fetchIdentityLine,
48
44
  fetchServedTexts,
49
45
  formatIntegrationStatus,
50
- identityLineOf,
46
+ fromKitResult,
51
47
  idle,
52
48
  integrationDisabled,
53
49
  integrationDisabledBy,
54
50
  integrationStatusAge,
55
51
  integrationStatusPath,
56
52
  isRunProfile,
53
+ isRunnerFactory,
57
54
  loadTexts,
58
- log,
59
55
  manualFrontMatter,
60
56
  manualPointer,
61
57
  manualVersion,
62
58
  markAlwaysOnInstalledVersion,
63
59
  markAlwaysOnOptOut,
64
60
  markAlwaysOnWanted,
65
- normalizeHandle,
66
61
  pendingPath,
67
62
  readAlwaysOnInstalledVersion,
68
63
  readCachedTexts,
69
64
  readCredentials,
70
65
  readIntegrationStatus,
71
- readJsonFile,
72
66
  readManualVersion,
73
67
  readPending,
74
68
  resolveIdentity,
75
69
  resolveRunBudgetMs,
76
70
  resolveRunProfile,
77
- spawnCommand,
78
- spawnCommandSync,
79
71
  statePath,
80
72
  syncManual,
81
73
  textsCachePath,
82
- trayHasWaiting,
83
- traySummary,
84
- writeCachedTexts,
85
74
  writeCredentials,
86
75
  writeIntegrationStatus,
87
76
  writePending
88
- } from "./chunk-4YF2K5ND.js";
77
+ } from "./chunk-7LAAAXUO.js";
78
+ import {
79
+ HOSTED_MCP_PATH,
80
+ VERSION,
81
+ hostedMcpUrl,
82
+ probeHostedMcp
83
+ } from "./chunk-XDWBTX5J.js";
84
+ import {
85
+ atomicCopyFile,
86
+ atomicWriteFile,
87
+ clientHeadersOf,
88
+ clientIdentityOf,
89
+ clientNameOf,
90
+ log,
91
+ readJsonFile,
92
+ spawnCommand,
93
+ spawnCommandSync
94
+ } from "./chunk-QDM4EFI7.js";
89
95
 
90
- // src/version.ts
91
- var VERSION = "0.3.1";
96
+ // src/integration/tray.ts
97
+ import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
98
+ async function traySummary(client) {
99
+ const tray = await client.inbox.tray({ limit: INBOX_TRAY_MAX_LIMIT });
100
+ return {
101
+ waiting: Array.isArray(tray.conversations) ? tray.conversations.length : 0,
102
+ deferred: typeof tray.deferred === "number" ? tray.deferred : 0,
103
+ truncated: tray.truncated === true
104
+ };
105
+ }
92
106
 
93
107
  // src/identity/state.ts
94
108
  var StateSchema = external_exports.object({
@@ -123,107 +137,170 @@ function clearOfferDeclined(home) {
123
137
  writeState(home, state);
124
138
  }
125
139
 
140
+ // src/skill/identity-line.ts
141
+ import { integration as kit } from "agentchatme";
142
+ function identityLineOf(texts) {
143
+ return texts.identity_line;
144
+ }
145
+ function normalizeHandle(handle) {
146
+ return kit.anchor.normalizeHandle(handle);
147
+ }
148
+
126
149
  // src/anchor/block.ts
127
150
  import * as fs from "fs";
128
151
  import * as path from "path";
129
- var ANCHOR_START = "<!-- agentchat:start -->";
130
- var ANCHOR_END = "<!-- agentchat:end -->";
131
- var LEGACY_ANCHOR_START = "<!-- agentchat-skill:start -->";
132
- var LEGACY_ANCHOR_END = "<!-- agentchat-skill:end -->";
133
- function renderAnchorBlock(identityLine) {
134
- const line = identityLine.trim();
135
- if (line.length === 0) throw new Error("renderAnchorBlock: the identity line is empty");
136
- return [ANCHOR_START, line, ANCHOR_END].join("\n");
152
+ import { integration as kit2 } from "agentchatme";
153
+ var ANCHOR_START = kit2.anchor.START_MARKER;
154
+ var ANCHOR_END = kit2.anchor.END_MARKER;
155
+ var MARKER_LINES = /* @__PURE__ */ new Set([
156
+ kit2.anchor.START_MARKER,
157
+ kit2.anchor.END_MARKER,
158
+ kit2.anchor.LEGACY_START_MARKER,
159
+ kit2.anchor.LEGACY_END_MARKER
160
+ ]);
161
+ function renderAnchorBlock(identityLine, handle) {
162
+ if (typeof identityLine !== "string" || identityLine.trim().length === 0) throw new Error("renderAnchorBlock: the identity line is empty");
163
+ if (typeof handle !== "string" || kit2.anchor.normalizeHandle(handle).length === 0) throw new Error("renderAnchorBlock: the handle is empty");
164
+ if (identityLine.split(/\r?\n/).some((line) => MARKER_LINES.has(line.trim()))) {
165
+ throw new Error("renderAnchorBlock: the identity line holds an AgentChat marker line");
166
+ }
167
+ return kit2.anchor.render({ identity_line: identityLine, identity_line_template: "" }, handle);
137
168
  }
138
169
  function writeAnchor(filePath, block, expectHandle) {
139
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
140
- const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf-8") : "";
141
- fs.writeFileSync(filePath, upsertAnchorBlock(existing, block), "utf-8");
142
170
  if (expectHandle !== void 0) {
143
- const verify = fs.readFileSync(filePath, "utf-8");
144
- if (!verify.includes(`@${expectHandle}`)) {
145
- throw new Error(
146
- `writeAnchor: handle @${expectHandle} did not land in ${filePath} \u2014 remove the agentchat block manually and re-run.`
147
- );
171
+ const bare = kit2.anchor.normalizeHandle(expectHandle);
172
+ const claimed = kit2.anchor.find(block)?.handle ?? null;
173
+ if (claimed !== bare) {
174
+ throw new Error(`writeAnchor: the block for ${filePath} does not name @${bare} \u2014 nothing was written`);
148
175
  }
149
176
  }
177
+ const existing = readInstructionFile(filePath) ?? { bom: "", text: "" };
178
+ const next = untilStable(existing.text, (text) => kit2.anchor.replace(text, block));
179
+ if (next !== existing.text) writeInstructionFile(filePath, existing.bom + next);
180
+ if (expectHandle !== void 0 && readInstructionFile(filePath)?.text !== next) {
181
+ throw new Error(`writeAnchor: ${filePath} did not read back as written \u2014 remove the agentchat block manually and re-run`);
182
+ }
150
183
  return "written";
151
184
  }
185
+ function untilStable(text, step) {
186
+ let current = text;
187
+ for (let i = 0; i < 8; i++) {
188
+ const next = step(current);
189
+ if (next === current) return current;
190
+ current = next;
191
+ }
192
+ return current;
193
+ }
152
194
  function removeAnchorAt(filePath) {
153
- if (!fs.existsSync(filePath)) return "noop";
154
- const existing = fs.readFileSync(filePath, "utf-8");
155
- const next = stripAnchorBlock(existing);
156
- if (next === existing) return "noop";
157
- fs.writeFileSync(filePath, next, "utf-8");
195
+ const existing = readInstructionFile(filePath);
196
+ if (existing === null) return "noop";
197
+ const next = untilStable(existing.text, (text) => kit2.anchor.remove(text));
198
+ if (next === existing.text) return "noop";
199
+ writeInstructionFile(filePath, existing.bom + next);
158
200
  return "removed";
159
201
  }
160
202
  function hasAnchorAt(filePath) {
161
- if (!fs.existsSync(filePath)) return false;
162
- return findBlock(fs.readFileSync(filePath, "utf-8"), ANCHOR_START, ANCHOR_END) !== null;
163
- }
164
- function anchorIsCurrentAt(filePath, identityLine) {
165
- if (!fs.existsSync(filePath)) return false;
166
- const text = fs.readFileSync(filePath, "utf-8");
167
- const block = findBlock(text, ANCHOR_START, ANCHOR_END);
168
- if (block === null) return false;
169
- return text.slice(block.from, block.to) === renderAnchorBlock(identityLine);
170
- }
171
- var IDENTITY_HANDLE_RE = /I am @([^\s]+) on AgentChat/;
172
- var LEGACY_HANDLE_RE = /\*\*@([^*\s]+)\*\*/;
173
- function readAnchorHandleAt(filePath) {
174
- if (!fs.existsSync(filePath)) return null;
175
- return readAnchorHandleFrom(fs.readFileSync(filePath, "utf-8"));
176
- }
177
- function readAnchorHandleFrom(text) {
178
- const block = findBlock(text, ANCHOR_START, ANCHOR_END);
179
- if (block === null) return null;
180
- const inside = text.slice(block.from, block.to);
181
- const match = IDENTITY_HANDLE_RE.exec(inside) ?? LEGACY_HANDLE_RE.exec(inside);
182
- return match?.[1] ?? null;
183
- }
184
- function lineAnchoredIndex(text, marker, fromIndex = 0) {
185
- let idx = text.indexOf(marker, fromIndex);
186
- while (idx >= 0) {
187
- const lineStart = text.lastIndexOf("\n", idx - 1) + 1;
188
- const lineEndRaw = text.indexOf("\n", idx);
189
- const lineEnd = lineEndRaw === -1 ? text.length : lineEndRaw;
190
- if (text.slice(lineStart, lineEnd).trim() === marker) {
191
- return { start: lineStart, end: lineEnd };
192
- }
193
- idx = text.indexOf(marker, idx + marker.length);
203
+ const file = readInstructionFile(filePath);
204
+ return file !== null && kit2.anchor.find(file.text) !== null;
205
+ }
206
+ function anchorIsCurrentAt(filePath, identityLine, handle) {
207
+ const file = readInstructionFile(filePath);
208
+ if (file === null) return false;
209
+ let expected;
210
+ try {
211
+ expected = renderAnchorBlock(identityLine, handle);
212
+ } catch {
213
+ return false;
194
214
  }
195
- return null;
215
+ if (kit2.anchor.find(file.text) === null) return false;
216
+ return kit2.anchor.replace(file.text, expected) === file.text;
196
217
  }
197
- function findBlock(text, startMarker, endMarker) {
198
- const start = lineAnchoredIndex(text, startMarker);
199
- if (start === null) return null;
200
- const end = lineAnchoredIndex(text, endMarker, start.end);
201
- if (end === null) return null;
202
- return { from: start.start, to: end.end };
218
+ function readAnchorHandleAt(filePath, template) {
219
+ const file = readInstructionFile(filePath);
220
+ return file === null ? null : readAnchorHandleFrom(file.text, template);
221
+ }
222
+ function readAnchorHandleFrom(text, template) {
223
+ return kit2.anchor.find(text.replace(/^\uFEFF/, ""), { template })?.handle ?? null;
203
224
  }
204
225
  function upsertAnchorBlock(existing, block) {
205
- const cleaned = stripAnchorBlock(existing);
206
- const trimmed = cleaned.replace(/\n+$/, "");
207
- if (trimmed.length === 0) return block + "\n";
208
- return trimmed + "\n\n" + block + "\n";
226
+ return kit2.anchor.replace(existing, block);
209
227
  }
210
228
  function stripAnchorBlock(existing) {
211
- const afterUnified = stripAllBlocks(existing, ANCHOR_START, ANCHOR_END);
212
- return stripAllBlocks(afterUnified, LEGACY_ANCHOR_START, LEGACY_ANCHOR_END);
213
- }
214
- function stripAllBlocks(existing, start, end) {
215
- let text = existing;
216
- for (let i = 0; i < 1e4; i++) {
217
- const block = findBlock(text, start, end);
218
- if (block === null) return text;
219
- const before = text.slice(0, block.from).replace(/\n+$/, "");
220
- const after = text.slice(block.to).replace(/^\n+/, "");
221
- if (before.length === 0 && after.length === 0) return "";
222
- if (before.length === 0) text = after.endsWith("\n") ? after : after + "\n";
223
- else if (after.length === 0) text = before + "\n";
224
- else text = before + "\n\n" + after + (after.endsWith("\n") ? "" : "\n");
229
+ return kit2.anchor.remove(existing);
230
+ }
231
+ var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
232
+ function readInstructionFile(filePath) {
233
+ let bytes;
234
+ try {
235
+ bytes = fs.readFileSync(filePath);
236
+ } catch (err) {
237
+ if (err.code === "ENOENT") return null;
238
+ throw err;
239
+ }
240
+ let decoded;
241
+ try {
242
+ decoded = UTF8.decode(bytes);
243
+ } catch {
244
+ 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)`);
245
+ }
246
+ return decoded.startsWith("\uFEFF") ? { bom: "\uFEFF", text: decoded.slice(1) } : { bom: "", text: decoded };
247
+ }
248
+ function resolveWriteTarget(filePath) {
249
+ let current = filePath;
250
+ for (let hops = 0; hops < 40; hops++) {
251
+ let stat;
252
+ try {
253
+ stat = fs.lstatSync(current);
254
+ } catch (err) {
255
+ if (err.code === "ENOENT") return current;
256
+ throw err;
257
+ }
258
+ if (!stat.isSymbolicLink()) return current;
259
+ const link = fs.readlinkSync(current);
260
+ const joined = path.isAbsolute(link) ? link : `${fs.realpathSync.native(path.dirname(current))}${path.sep}${link}`;
261
+ current = path.join(fs.realpathSync.native(path.dirname(joined)), path.basename(joined));
262
+ }
263
+ throw Object.assign(new Error(`${filePath}: too many symbolic links`), { code: "ELOOP" });
264
+ }
265
+ var IN_PLACE_FALLBACK_CODES = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS", "EBUSY", "EXDEV"]);
266
+ function stillWritable(file) {
267
+ try {
268
+ fs.accessSync(file, fs.constants.W_OK);
269
+ return true;
270
+ } catch {
271
+ return false;
272
+ }
273
+ }
274
+ function writeInstructionFile(filePath, data) {
275
+ const target = resolveWriteTarget(filePath);
276
+ let existing = null;
277
+ try {
278
+ existing = fs.statSync(target);
279
+ } catch (err) {
280
+ if (err.code !== "ENOENT") throw err;
281
+ }
282
+ if (existing !== null) {
283
+ if (!existing.isFile()) throw new Error(`${filePath} is not a regular file`);
284
+ fs.accessSync(target, fs.constants.W_OK);
285
+ } else {
286
+ fs.mkdirSync(path.dirname(target), { recursive: true });
287
+ }
288
+ try {
289
+ atomicWriteFile(target, data, existing === null ? void 0 : existing.mode & 4095);
290
+ } catch (err) {
291
+ const code = err.code;
292
+ if (existing !== null && code !== void 0 && IN_PLACE_FALLBACK_CODES.has(code) && stillWritable(target)) {
293
+ fs.writeFileSync(target, data, "utf-8");
294
+ return;
295
+ }
296
+ throw err;
297
+ }
298
+ if (existing !== null && typeof process.getuid === "function" && process.getuid() === 0 && (existing.uid !== 0 || existing.gid !== 0)) {
299
+ try {
300
+ fs.chownSync(target, existing.uid, existing.gid);
301
+ } catch {
302
+ }
225
303
  }
226
- return text;
227
304
  }
228
305
 
229
306
  // src/anchor/offer.ts
@@ -285,83 +362,6 @@ function renderDeclinedBlock(copy) {
285
362
  ].join("\n");
286
363
  }
287
364
 
288
- // src/integration/mcp-probe.ts
289
- var HOSTED_MCP_PATH = "/mcp";
290
- var MCP_PROTOCOL_VERSION = "2025-06-18";
291
- function hostedMcpUrl(apiBase) {
292
- return `${apiBase.replace(/\/+$/, "")}${HOSTED_MCP_PATH}`;
293
- }
294
- async function probeHostedMcp(params) {
295
- const fetchImpl = params.fetch ?? fetch;
296
- const controller = new AbortController();
297
- const timer = setTimeout(() => controller.abort(), params.timeoutMs ?? 1e4);
298
- try {
299
- const res = await fetchImpl(hostedMcpUrl(params.apiBase), {
300
- method: "POST",
301
- headers: {
302
- authorization: `Bearer ${params.apiKey}`,
303
- "content-type": "application/json",
304
- accept: "application/json, text/event-stream",
305
- ...clientHeadersOf(params.client)
306
- },
307
- body: JSON.stringify({
308
- jsonrpc: "2.0",
309
- id: 1,
310
- method: "initialize",
311
- params: {
312
- protocolVersion: MCP_PROTOCOL_VERSION,
313
- capabilities: {},
314
- clientInfo: {
315
- name: params.clientName ?? params.client.runtime,
316
- version: params.clientVersion ?? params.client.version
317
- }
318
- }
319
- }),
320
- signal: controller.signal
321
- });
322
- if (!res.ok) {
323
- return {
324
- ok: false,
325
- status: res.status,
326
- error: res.status === 401 ? "the key does not authenticate against the hosted MCP server" : `HTTP ${res.status}`
327
- };
328
- }
329
- const result = readInitializeResult(await res.text());
330
- if (!result) return { ok: false, status: res.status, error: "no initialize result in the answer" };
331
- const serverInfo = result.serverInfo ?? {};
332
- return {
333
- ok: true,
334
- status: res.status,
335
- ...typeof serverInfo.name === "string" ? { serverName: serverInfo.name } : {},
336
- ...typeof serverInfo.version === "string" ? { serverVersion: serverInfo.version } : {},
337
- ...typeof result.protocolVersion === "string" ? { protocolVersion: result.protocolVersion } : {}
338
- };
339
- } catch (err) {
340
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
341
- } finally {
342
- clearTimeout(timer);
343
- }
344
- }
345
- function readInitializeResult(text) {
346
- const candidates = [];
347
- const trimmed = text.trim();
348
- if (trimmed.startsWith("{")) candidates.push(trimmed);
349
- for (const line of text.split(/\r?\n/)) {
350
- if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
351
- }
352
- for (const candidate of candidates) {
353
- try {
354
- const parsed = JSON.parse(candidate);
355
- const result = parsed.result;
356
- if (result && typeof result === "object" && !Array.isArray(result)) {
357
- return result;
358
- }
359
- } catch {
360
- }
361
- }
362
- return null;
363
- }
364
-
365
365
  // src/identity/commands.ts
366
366
  import * as readline from "readline";
367
367
  import { AgentChatClient } from "agentchatme";
@@ -369,6 +369,7 @@ import { AgentChatClient } from "agentchatme";
369
369
  // src/identity/host-profile.ts
370
370
  function anchorLabelOf(profile) {
371
371
  if (profile.anchorLabel !== void 0) return profile.anchorLabel;
372
+ if (profile.anchorFile === void 0) return "identity line";
372
373
  const file = profile.anchorFile();
373
374
  const slash = Math.max(file.lastIndexOf("/"), file.lastIndexOf("\\"));
374
375
  return slash >= 0 ? file.slice(slash + 1) : file;
@@ -379,6 +380,13 @@ var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
379
380
  function validHandle(handle) {
380
381
  return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle);
381
382
  }
383
+ var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
384
+ function errorText(err) {
385
+ return err instanceof Error ? err.message : String(err);
386
+ }
387
+ function contextOf(texts) {
388
+ return { identityLine: identityLineOf(texts), identityLineTemplate: texts.identity_line_template, manual: texts.manual };
389
+ }
382
390
  async function prompt(question) {
383
391
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
384
392
  try {
@@ -454,7 +462,7 @@ function createIdentityCommands(profile) {
454
462
  const apiClient = (apiKey, apiBase, budget = "quick") => budget === "quick" ? new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } }) : new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 15e3 });
455
463
  async function served(apiKey, apiBase) {
456
464
  const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5e3 });
457
- return loaded === null ? { identityLine: null, manual: null } : { identityLine: identityLineOf(loaded.texts), manual: loaded.texts.manual };
465
+ return loaded === null ? NO_TEXTS : contextOf(loaded.texts);
458
466
  }
459
467
  async function printExtraStatus(context) {
460
468
  if (profile.extraStatus === void 0) return;
@@ -476,16 +484,17 @@ function createIdentityCommands(profile) {
476
484
  return writeOurAnchor(handle, identityLine);
477
485
  }
478
486
  function writeOurAnchor(handle, identityLine) {
487
+ if (profile.anchorFile === void 0) return [];
479
488
  const file = profile.anchorFile();
480
489
  const label = anchorLabelOf(profile);
481
- if (profile.isWired !== void 0 && !profile.isWired() && !hasAnchorAt(file)) return [];
482
- if (identityLine === null) {
483
- return [
484
- ` ${label}: identity line not written \u2014 GET /v1/texts could not be reached and nothing is cached; run \`${invocation()} doctor --fix\` once online`
485
- ];
486
- }
487
490
  try {
488
- writeAnchor(file, profile.renderAnchor(identityLine), handle);
491
+ if (profile.isWired !== void 0 && !profile.isWired() && !hasAnchorAt(file)) return [];
492
+ if (identityLine === null) {
493
+ return [
494
+ ` ${label}: identity line not written \u2014 GET /v1/texts could not be reached and nothing is cached; run \`${invocation()} doctor --fix\` once online`
495
+ ];
496
+ }
497
+ writeAnchor(file, profile.renderAnchor(identityLine, handle), handle);
489
498
  return [` ${label}: @${handle} \u2192 ${file}`];
490
499
  } catch (err) {
491
500
  return [` ${label}: FAILED \u2014 ${String(err)}`];
@@ -770,9 +779,19 @@ function createIdentityCommands(profile) {
770
779
  return 1;
771
780
  }
772
781
  }
782
+ function anchorView(file, identityLine, handle) {
783
+ if (file === null) return { present: null, current: null, error: null };
784
+ try {
785
+ const present = hasAnchorAt(file);
786
+ const current = identityLine === null || handle === null ? null : anchorIsCurrentAt(file, identityLine, handle);
787
+ return { present, current, error: null };
788
+ } catch (err) {
789
+ return { present: null, current: null, error: errorText(err) };
790
+ }
791
+ }
773
792
  async function runStatus(opts) {
774
793
  const home = profile.home();
775
- const anchorFile = profile.anchorFile();
794
+ const anchorFile = profile.anchorFile?.() ?? null;
776
795
  const identity = resolveIdentity(home);
777
796
  const pending = readPending(home);
778
797
  const integration = readIntegrationStatus(home);
@@ -784,9 +803,7 @@ function createIdentityCommands(profile) {
784
803
  host: profile.id,
785
804
  pending: pending !== null,
786
805
  pending_kind: pending?.kind ?? null,
787
- integration,
788
- // The previous key, kept one release for scripts that read it.
789
- doorbell: integration
806
+ integration
790
807
  })
791
808
  );
792
809
  } else if (pending?.kind === "recover") {
@@ -812,6 +829,7 @@ function createIdentityCommands(profile) {
812
829
  const refused = status === 401 || status === 403;
813
830
  const detail = apiErr(err);
814
831
  if (opts.json) {
832
+ const offline = anchorView(anchorFile, null, null);
815
833
  console.log(
816
834
  JSON.stringify({
817
835
  configured: true,
@@ -821,9 +839,9 @@ function createIdentityCommands(profile) {
821
839
  key_source: identity.source,
822
840
  api_base: identity.apiBase,
823
841
  home,
824
- anchor: hasAnchorAt(anchorFile),
825
- integration,
826
- doorbell: integration
842
+ anchor: offline.present,
843
+ anchor_error: offline.error,
844
+ integration
827
845
  })
828
846
  );
829
847
  } else {
@@ -839,14 +857,14 @@ function createIdentityCommands(profile) {
839
857
  ].join("\n")
840
858
  );
841
859
  const cached = readCachedTexts(home, profile.client.runtime);
842
- await printExtraStatus(cached === null ? { identityLine: null, manual: null } : { identityLine: identityLineOf(cached.texts), manual: cached.texts.manual });
860
+ await printExtraStatus(cached === null ? NO_TEXTS : contextOf(cached.texts));
843
861
  }
844
862
  return 1;
845
863
  }
846
864
  const tray = await traySummary(client).catch(() => null);
847
865
  const texts = await served(identity.apiKey, identity.apiBase);
848
866
  const identityLine = texts.identityLine;
849
- const anchorCurrent = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
867
+ const anchor = anchorView(anchorFile, identityLine, me.handle);
850
868
  if (opts.json) {
851
869
  console.log(
852
870
  JSON.stringify({
@@ -858,11 +876,12 @@ function createIdentityCommands(profile) {
858
876
  key_source: identity.source,
859
877
  api_base: identity.apiBase,
860
878
  home,
861
- anchor: hasAnchorAt(anchorFile),
862
- /** null: the served texts were unavailable, so currency could not be checked. */
863
- anchor_current: anchorCurrent,
864
- integration,
865
- doorbell: integration
879
+ anchor: anchor.present,
880
+ /** null: the served texts were unavailable (or there is no instruction file, or it cannot be read), so currency could not be checked. */
881
+ anchor_current: anchor.current,
882
+ /** Why the instruction file could not be read, or null. */
883
+ anchor_error: anchor.error,
884
+ integration
866
885
  })
867
886
  );
868
887
  } else {
@@ -873,7 +892,9 @@ function createIdentityCommands(profile) {
873
892
  trayLine,
874
893
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
875
894
  `API: ${identity.apiBase}`,
876
- `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})`,
895
+ ...anchorFile === null ? [] : [
896
+ `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})`
897
+ ],
877
898
  ...formatIntegrationStatus(integration)
878
899
  ].join("\n")
879
900
  );
@@ -883,7 +904,7 @@ function createIdentityCommands(profile) {
883
904
  }
884
905
  function runLogout() {
885
906
  const home = profile.home();
886
- const anchorFile = profile.anchorFile();
907
+ const anchorFile = profile.anchorFile?.() ?? null;
887
908
  const reports = [];
888
909
  let any = false;
889
910
  const identity = resolveIdentity(home);
@@ -891,9 +912,16 @@ function createIdentityCommands(profile) {
891
912
  any = true;
892
913
  reports.push(" credentials deleted");
893
914
  }
894
- if (removeAnchorAt(anchorFile) === "removed") {
895
- any = true;
896
- reports.push(` ${anchorLabelOf(profile)} identity line removed`);
915
+ if (anchorFile !== null) {
916
+ try {
917
+ if (removeAnchorAt(anchorFile) === "removed") {
918
+ any = true;
919
+ reports.push(` ${anchorLabelOf(profile)} identity line removed`);
920
+ }
921
+ } catch (err) {
922
+ any = true;
923
+ reports.push(` could not remove the identity line from ${anchorFile}: ${errorText(err)} \u2014 remove the agentchat block by hand`);
924
+ }
897
925
  }
898
926
  if (profile.unplace !== void 0) {
899
927
  try {
@@ -916,12 +944,48 @@ function createIdentityCommands(profile) {
916
944
  );
917
945
  return 0;
918
946
  }
947
+ function readIdentityLine(anchorFile, handle, texts) {
948
+ const claimed = readAnchorHandleAt(anchorFile, texts.identityLineTemplate);
949
+ const current = texts.identityLine === null ? null : anchorIsCurrentAt(anchorFile, texts.identityLine, handle);
950
+ return { claimed, current };
951
+ }
952
+ async function identityLineCheck(anchorFile, creds, apiBase, texts, fix) {
953
+ let claimed;
954
+ let current;
955
+ try {
956
+ ;
957
+ ({ claimed, current } = readIdentityLine(anchorFile, creds.handle, texts));
958
+ } catch (err) {
959
+ return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile}: ${errorText(err)}` };
960
+ }
961
+ if (claimed === creds.handle && current === true) {
962
+ return { name: "identity-line", verdict: "PASS", detail: `@${claimed} in ${anchorFile}` };
963
+ }
964
+ if (claimed === creds.handle && current === null) {
965
+ return { name: "identity-line", verdict: "WARN", detail: `@${claimed} in ${anchorFile} (currency not checked: served texts unavailable)` };
966
+ }
967
+ const why = claimed === null ? `no identity line in ${anchorFile}` : claimed !== creds.handle ? `${anchorFile} says @${claimed} but this agent is @${creds.handle}` : `${anchorFile} carries an older identity text for @${claimed}`;
968
+ if (fix) {
969
+ const report = await placeIdentity(creds.handle, creds.api_key, apiBase);
970
+ const failed = report.some((l) => l.includes("FAILED") || l.includes("not written"));
971
+ if (failed) return { name: "identity-line", verdict: "FAIL", detail: `could not repair: ${report.join("; ")}` };
972
+ try {
973
+ const after = readIdentityLine(anchorFile, creds.handle, texts);
974
+ if (after.claimed === creds.handle && after.current !== false) {
975
+ return { name: "identity-line", verdict: "PASS", detail: `repaired \u2192 @${creds.handle}` };
976
+ }
977
+ return { name: "identity-line", verdict: "FAIL", detail: `repair did not take: ${anchorFile} still ${after.claimed === null ? "has no identity line" : after.claimed !== creds.handle ? `says @${after.claimed}` : "differs from the served block"}${report.length > 0 ? ` (${report.join("; ").trim()})` : ""}` };
978
+ } catch (err) {
979
+ return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile} after the repair: ${errorText(err)}` };
980
+ }
981
+ }
982
+ return { name: "identity-line", verdict: "WARN", detail: `${why} \u2014 repair with \`${invocation()} doctor --fix\`` };
983
+ }
919
984
  async function runDoctor(opts = {}) {
920
985
  const home = profile.home();
921
- const anchorFile = profile.anchorFile();
986
+ const anchorFile = profile.anchorFile?.() ?? null;
922
987
  const checks = [];
923
- let identityLine = null;
924
- let manual = null;
988
+ let texts = NO_TEXTS;
925
989
  checks.push({ name: "node", verdict: "PASS", detail: process.version });
926
990
  checks.push({ name: "home", verdict: "PASS", detail: home });
927
991
  const creds = readCredentials(home);
@@ -957,36 +1021,32 @@ function createIdentityCommands(profile) {
957
1021
  }
958
1022
  }
959
1023
  const apiBase = identity?.apiBase ?? creds.api_base ?? DEFAULT_API_BASE;
960
- ({ identityLine, manual } = await served(creds.api_key, apiBase));
961
- const claimed = readAnchorHandleAt(anchorFile);
962
- const current = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
1024
+ texts = await served(creds.api_key, apiBase);
963
1025
  checks.push(
964
- 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" }
1026
+ 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" }
965
1027
  );
966
- if (claimed === creds.handle && current === true) {
967
- checks.push({ name: "identity-line", verdict: "PASS", detail: `@${claimed} in ${anchorFile}` });
968
- } else if (claimed === creds.handle && current === null) {
969
- checks.push({ name: "identity-line", verdict: "WARN", detail: `@${claimed} in ${anchorFile} (currency not checked: served texts unavailable)` });
970
- } else {
971
- 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}`;
972
- if (opts.fix === true) {
973
- const report = await placeIdentity(creds.handle, creds.api_key, apiBase);
974
- const failed = report.some((l) => l.includes("FAILED") || l.includes("not written"));
975
- checks.push({
976
- name: "identity-line",
977
- verdict: failed ? "FAIL" : "PASS",
978
- detail: failed ? `could not repair: ${report.join("; ")}` : `repaired \u2192 @${creds.handle}`
979
- });
980
- } else {
981
- checks.push({
982
- name: "identity-line",
983
- verdict: "WARN",
984
- detail: `${why} \u2014 repair with \`${invocation()} doctor --fix\``
985
- });
986
- }
1028
+ if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true));
1029
+ }
1030
+ const integration = readIntegrationStatus(home);
1031
+ const cycles = integration?.recent_cycles ?? [];
1032
+ if (cycles.length > 0) {
1033
+ const failing = failedCyclesInARow(integration);
1034
+ const last = cycles[cycles.length - 1];
1035
+ checks.push(
1036
+ failing !== null && failing.count >= REPEATED_FAILED_CYCLES ? {
1037
+ name: "wake-cycles",
1038
+ verdict: "WARN",
1039
+ detail: `the last ${failing.count} wake cycles did not get done (latest: ${failing.latest.outcome}${failing.latest.failure ? ` \u2014 ${failing.latest.failure}` : ""}); the cards stay on the tray`
1040
+ } : { name: "wake-cycles", verdict: "PASS", detail: `last cycle ${last.outcome} at ${last.at} (${cycles.length} recent)` }
1041
+ );
1042
+ }
1043
+ if (profile.extraDoctorChecks !== void 0) {
1044
+ try {
1045
+ checks.push(...await profile.extraDoctorChecks({ ...opts, ...texts }));
1046
+ } catch (err) {
1047
+ checks.push({ name: "host", verdict: "FAIL", detail: `the ${LABEL} checks failed: ${errorText(err)}` });
987
1048
  }
988
1049
  }
989
- if (profile.extraDoctorChecks !== void 0) checks.push(...await profile.extraDoctorChecks({ ...opts, identityLine, manual }));
990
1050
  console.log(checks.map((c) => `${c.verdict.padEnd(4)} ${c.name}: ${c.detail}`).join("\n"));
991
1051
  return checks.some((c) => c.verdict === "FAIL") ? 1 : 0;
992
1052
  }
@@ -1655,10 +1715,12 @@ export {
1655
1715
  DEFAULT_API_BASE,
1656
1716
  DEFAULT_RUN_BUDGET_MS,
1657
1717
  DEFAULT_RUN_PROFILE,
1718
+ FAILED_CYCLE_OUTCOMES,
1658
1719
  HEARTBEAT_FILE,
1659
1720
  HOSTED_MCP_PATH,
1660
1721
  INTEGRATION_ENV,
1661
1722
  INTEGRATION_ENV_LEGACY,
1723
+ INTEGRATION_ENV_LEGACY_REMOVAL,
1662
1724
  INTEGRATION_STATUS_FILE,
1663
1725
  LEGACY_STATUS_FILE,
1664
1726
  MANUAL,
@@ -1668,15 +1730,12 @@ export {
1668
1730
  MANUAL_MAX_REDIRECTS,
1669
1731
  MANUAL_SKILL_NAME,
1670
1732
  MANUAL_URL,
1671
- ManualFollower,
1733
+ REPEATED_FAILED_CYCLES,
1672
1734
  RUN_BUDGET_ENV,
1673
1735
  RUN_PROFILES,
1674
1736
  RUN_PROFILE_ENV,
1675
1737
  SOCKET_STATES,
1676
1738
  TEXTS_CACHE_FILE,
1677
- TEXTS_REFRESH_MS,
1678
- TEXTS_RETRY_MS,
1679
- TextsStore,
1680
1739
  VERSION,
1681
1740
  acquireLeaderLock,
1682
1741
  alwaysOnHealth,
@@ -1688,7 +1747,6 @@ export {
1688
1747
  atomicCopyFile,
1689
1748
  atomicWriteFile,
1690
1749
  beat,
1691
- buildRunPrompts,
1692
1750
  checkManual,
1693
1751
  clearAlwaysOnInstalledVersion,
1694
1752
  clearAlwaysOnOptOut,
@@ -1699,12 +1757,16 @@ export {
1699
1757
  clearPending,
1700
1758
  clientHeadersOf,
1701
1759
  clientIdentityOf,
1760
+ clientNameOf,
1702
1761
  createIdentityCommands,
1703
1762
  credentialsPath,
1704
1763
  describeManualSync,
1764
+ envApiKey,
1765
+ failedCyclesInARow,
1705
1766
  fetchIdentityLine,
1706
1767
  fetchServedTexts,
1707
1768
  formatIntegrationStatus,
1769
+ fromKitResult,
1708
1770
  hasAnchorAt,
1709
1771
  hostedMcpUrl,
1710
1772
  identityLineOf,
@@ -1715,6 +1777,7 @@ export {
1715
1777
  integrationStatusAge,
1716
1778
  integrationStatusPath,
1717
1779
  isRunProfile,
1780
+ isRunnerFactory,
1718
1781
  launchdPlist,
1719
1782
  loadTexts,
1720
1783
  log,
@@ -1762,12 +1825,10 @@ export {
1762
1825
  systemdQuote,
1763
1826
  systemdUnit,
1764
1827
  textsCachePath,
1765
- trayHasWaiting,
1766
1828
  traySummary,
1767
1829
  uninstallService,
1768
1830
  upsertAnchorBlock,
1769
1831
  writeAnchor,
1770
- writeCachedTexts,
1771
1832
  writeCredentials,
1772
1833
  writeIntegrationStatus,
1773
1834
  writePending,