@agentchatme/agent-core 0.3.0 → 0.4.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
@@ -2,6 +2,7 @@ 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,
@@ -14,24 +15,18 @@ import {
14
15
  MANUAL_MAX_REDIRECTS,
15
16
  MANUAL_SKILL_NAME,
16
17
  MANUAL_URL,
17
- ManualFollower,
18
+ REPEATED_FAILED_CYCLES,
18
19
  RUN_BUDGET_ENV,
19
20
  RUN_PROFILES,
20
21
  RUN_PROFILE_ENV,
21
22
  SOCKET_STATES,
22
23
  TEXTS_CACHE_FILE,
23
- TEXTS_REFRESH_MS,
24
- TEXTS_RETRY_MS,
25
- TextsStore,
26
24
  acquireLeaderLock,
27
25
  alwaysOnHealth,
28
26
  alwaysOnOptedOut,
29
27
  alwaysOnState,
30
28
  alwaysOnWanted,
31
- atomicCopyFile,
32
- atomicWriteFile,
33
29
  beat,
34
- buildRunPrompts,
35
30
  checkManual,
36
31
  clearAlwaysOnInstalledVersion,
37
32
  clearAlwaysOnOptOut,
@@ -39,56 +34,76 @@ import {
39
34
  clearCredentials,
40
35
  clearIntegrationStatus,
41
36
  clearPending,
42
- clientHeadersOf,
43
- clientIdentityOf,
44
37
  credentialsPath,
45
38
  describeManualSync,
39
+ envApiKey,
46
40
  external_exports,
41
+ failedCyclesInARow,
47
42
  fetchIdentityLine,
48
43
  fetchServedTexts,
49
44
  formatIntegrationStatus,
50
- identityLineOf,
45
+ fromKitResult,
51
46
  idle,
52
47
  integrationDisabled,
53
48
  integrationDisabledBy,
54
49
  integrationStatusAge,
55
50
  integrationStatusPath,
56
51
  isRunProfile,
52
+ isRunnerFactory,
57
53
  loadTexts,
58
- log,
59
54
  manualFrontMatter,
60
55
  manualPointer,
61
56
  manualVersion,
62
57
  markAlwaysOnInstalledVersion,
63
58
  markAlwaysOnOptOut,
64
59
  markAlwaysOnWanted,
65
- normalizeHandle,
66
60
  pendingPath,
67
61
  readAlwaysOnInstalledVersion,
68
62
  readCachedTexts,
69
63
  readCredentials,
70
64
  readIntegrationStatus,
71
- readJsonFile,
72
65
  readManualVersion,
73
66
  readPending,
74
67
  resolveIdentity,
75
68
  resolveRunBudgetMs,
76
69
  resolveRunProfile,
77
- spawnCommand,
78
- spawnCommandSync,
79
70
  statePath,
80
71
  syncManual,
81
72
  textsCachePath,
82
- trayHasWaiting,
83
- traySummary,
84
- writeCachedTexts,
85
73
  writeCredentials,
86
74
  writeIntegrationStatus,
87
75
  writePending
88
- } from "./chunk-KUZZ3MW2.js";
76
+ } from "./chunk-W3LYBKIV.js";
77
+ import {
78
+ HOSTED_MCP_PATH,
79
+ hostedMcpUrl,
80
+ probeHostedMcp
81
+ } from "./chunk-HOY2FERJ.js";
82
+ import {
83
+ atomicCopyFile,
84
+ atomicWriteFile,
85
+ clientHeadersOf,
86
+ clientIdentityOf,
87
+ clientNameOf,
88
+ log,
89
+ readJsonFile,
90
+ spawnCommand,
91
+ spawnCommandSync
92
+ } from "./chunk-NCSF3CCV.js";
89
93
 
90
94
  // src/version.ts
91
- var VERSION = "0.3.0";
95
+ var VERSION = "0.4.0";
96
+
97
+ // src/integration/tray.ts
98
+ import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
99
+ async function traySummary(client) {
100
+ const tray = await client.inbox.tray({ limit: INBOX_TRAY_MAX_LIMIT });
101
+ return {
102
+ waiting: Array.isArray(tray.conversations) ? tray.conversations.length : 0,
103
+ deferred: typeof tray.deferred === "number" ? tray.deferred : 0,
104
+ truncated: tray.truncated === true
105
+ };
106
+ }
92
107
 
93
108
  // src/identity/state.ts
94
109
  var StateSchema = external_exports.object({
@@ -123,6 +138,14 @@ function clearOfferDeclined(home) {
123
138
  writeState(home, state);
124
139
  }
125
140
 
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
+
126
149
  // src/anchor/block.ts
127
150
  import * as fs from "fs";
128
151
  import * as path from "path";
@@ -285,83 +308,6 @@ function renderDeclinedBlock(copy) {
285
308
  ].join("\n");
286
309
  }
287
310
 
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
311
  // src/identity/commands.ts
366
312
  import * as readline from "readline";
367
313
  import { AgentChatClient } from "agentchatme";
@@ -369,6 +315,7 @@ import { AgentChatClient } from "agentchatme";
369
315
  // src/identity/host-profile.ts
370
316
  function anchorLabelOf(profile) {
371
317
  if (profile.anchorLabel !== void 0) return profile.anchorLabel;
318
+ if (profile.anchorFile === void 0) return "identity line";
372
319
  const file = profile.anchorFile();
373
320
  const slash = Math.max(file.lastIndexOf("/"), file.lastIndexOf("\\"));
374
321
  return slash >= 0 ? file.slice(slash + 1) : file;
@@ -476,6 +423,7 @@ function createIdentityCommands(profile) {
476
423
  return writeOurAnchor(handle, identityLine);
477
424
  }
478
425
  function writeOurAnchor(handle, identityLine) {
426
+ if (profile.anchorFile === void 0) return [];
479
427
  const file = profile.anchorFile();
480
428
  const label = anchorLabelOf(profile);
481
429
  if (profile.isWired !== void 0 && !profile.isWired() && !hasAnchorAt(file)) return [];
@@ -772,7 +720,7 @@ function createIdentityCommands(profile) {
772
720
  }
773
721
  async function runStatus(opts) {
774
722
  const home = profile.home();
775
- const anchorFile = profile.anchorFile();
723
+ const anchorFile = profile.anchorFile?.() ?? null;
776
724
  const identity = resolveIdentity(home);
777
725
  const pending = readPending(home);
778
726
  const integration = readIntegrationStatus(home);
@@ -821,7 +769,7 @@ function createIdentityCommands(profile) {
821
769
  key_source: identity.source,
822
770
  api_base: identity.apiBase,
823
771
  home,
824
- anchor: hasAnchorAt(anchorFile),
772
+ anchor: anchorFile === null ? null : hasAnchorAt(anchorFile),
825
773
  integration,
826
774
  doorbell: integration
827
775
  })
@@ -846,7 +794,7 @@ function createIdentityCommands(profile) {
846
794
  const tray = await traySummary(client).catch(() => null);
847
795
  const texts = await served(identity.apiKey, identity.apiBase);
848
796
  const identityLine = texts.identityLine;
849
- const anchorCurrent = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
797
+ const anchorCurrent = identityLine === null || anchorFile === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
850
798
  if (opts.json) {
851
799
  console.log(
852
800
  JSON.stringify({
@@ -858,8 +806,8 @@ function createIdentityCommands(profile) {
858
806
  key_source: identity.source,
859
807
  api_base: identity.apiBase,
860
808
  home,
861
- anchor: hasAnchorAt(anchorFile),
862
- /** null: the served texts were unavailable, so currency could not be checked. */
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. */
863
811
  anchor_current: anchorCurrent,
864
812
  integration,
865
813
  doorbell: integration
@@ -873,7 +821,9 @@ function createIdentityCommands(profile) {
873
821
  trayLine,
874
822
  `Key source: ${identity.source} (${identity.source === "file" ? credentialsPath(home) : "AGENTCHAT_API_KEY"})`,
875
823
  `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})`,
824
+ ...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})`
826
+ ],
877
827
  ...formatIntegrationStatus(integration)
878
828
  ].join("\n")
879
829
  );
@@ -883,7 +833,7 @@ function createIdentityCommands(profile) {
883
833
  }
884
834
  function runLogout() {
885
835
  const home = profile.home();
886
- const anchorFile = profile.anchorFile();
836
+ const anchorFile = profile.anchorFile?.() ?? null;
887
837
  const reports = [];
888
838
  let any = false;
889
839
  const identity = resolveIdentity(home);
@@ -891,7 +841,7 @@ function createIdentityCommands(profile) {
891
841
  any = true;
892
842
  reports.push(" credentials deleted");
893
843
  }
894
- if (removeAnchorAt(anchorFile) === "removed") {
844
+ if (anchorFile !== null && removeAnchorAt(anchorFile) === "removed") {
895
845
  any = true;
896
846
  reports.push(` ${anchorLabelOf(profile)} identity line removed`);
897
847
  }
@@ -916,9 +866,30 @@ function createIdentityCommands(profile) {
916
866
  );
917
867
  return 0;
918
868
  }
869
+ async function identityLineCheck(anchorFile, creds, apiBase, identityLine, fix) {
870
+ const claimed = readAnchorHandleAt(anchorFile);
871
+ const current = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
872
+ if (claimed === creds.handle && current === true) {
873
+ return { name: "identity-line", verdict: "PASS", detail: `@${claimed} in ${anchorFile}` };
874
+ }
875
+ if (claimed === creds.handle && current === null) {
876
+ return { name: "identity-line", verdict: "WARN", detail: `@${claimed} in ${anchorFile} (currency not checked: served texts unavailable)` };
877
+ }
878
+ 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}`;
879
+ if (fix) {
880
+ const report = await placeIdentity(creds.handle, creds.api_key, apiBase);
881
+ 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
+ };
887
+ }
888
+ return { name: "identity-line", verdict: "WARN", detail: `${why} \u2014 repair with \`${invocation()} doctor --fix\`` };
889
+ }
919
890
  async function runDoctor(opts = {}) {
920
891
  const home = profile.home();
921
- const anchorFile = profile.anchorFile();
892
+ const anchorFile = profile.anchorFile?.() ?? null;
922
893
  const checks = [];
923
894
  let identityLine = null;
924
895
  let manual = null;
@@ -958,33 +929,23 @@ function createIdentityCommands(profile) {
958
929
  }
959
930
  const apiBase = identity?.apiBase ?? creds.api_base ?? DEFAULT_API_BASE;
960
931
  ({ identityLine, manual } = await served(creds.api_key, apiBase));
961
- const claimed = readAnchorHandleAt(anchorFile);
962
- const current = identityLine === null ? null : anchorIsCurrentAt(anchorFile, identityLine);
963
932
  checks.push(
964
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" }
965
934
  );
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
- }
987
- }
935
+ if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, identityLine, opts.fix === true));
936
+ }
937
+ const integration = readIntegrationStatus(home);
938
+ const cycles = integration?.recent_cycles ?? [];
939
+ if (cycles.length > 0) {
940
+ const failing = failedCyclesInARow(integration);
941
+ const last = cycles[cycles.length - 1];
942
+ checks.push(
943
+ failing !== null && failing.count >= REPEATED_FAILED_CYCLES ? {
944
+ name: "wake-cycles",
945
+ verdict: "WARN",
946
+ 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`
947
+ } : { name: "wake-cycles", verdict: "PASS", detail: `last cycle ${last.outcome} at ${last.at} (${cycles.length} recent)` }
948
+ );
988
949
  }
989
950
  if (profile.extraDoctorChecks !== void 0) checks.push(...await profile.extraDoctorChecks({ ...opts, identityLine, manual }));
990
951
  console.log(checks.map((c) => `${c.verdict.padEnd(4)} ${c.name}: ${c.detail}`).join("\n"));
@@ -1655,6 +1616,7 @@ export {
1655
1616
  DEFAULT_API_BASE,
1656
1617
  DEFAULT_RUN_BUDGET_MS,
1657
1618
  DEFAULT_RUN_PROFILE,
1619
+ FAILED_CYCLE_OUTCOMES,
1658
1620
  HEARTBEAT_FILE,
1659
1621
  HOSTED_MCP_PATH,
1660
1622
  INTEGRATION_ENV,
@@ -1668,15 +1630,12 @@ export {
1668
1630
  MANUAL_MAX_REDIRECTS,
1669
1631
  MANUAL_SKILL_NAME,
1670
1632
  MANUAL_URL,
1671
- ManualFollower,
1633
+ REPEATED_FAILED_CYCLES,
1672
1634
  RUN_BUDGET_ENV,
1673
1635
  RUN_PROFILES,
1674
1636
  RUN_PROFILE_ENV,
1675
1637
  SOCKET_STATES,
1676
1638
  TEXTS_CACHE_FILE,
1677
- TEXTS_REFRESH_MS,
1678
- TEXTS_RETRY_MS,
1679
- TextsStore,
1680
1639
  VERSION,
1681
1640
  acquireLeaderLock,
1682
1641
  alwaysOnHealth,
@@ -1688,7 +1647,6 @@ export {
1688
1647
  atomicCopyFile,
1689
1648
  atomicWriteFile,
1690
1649
  beat,
1691
- buildRunPrompts,
1692
1650
  checkManual,
1693
1651
  clearAlwaysOnInstalledVersion,
1694
1652
  clearAlwaysOnOptOut,
@@ -1699,12 +1657,16 @@ export {
1699
1657
  clearPending,
1700
1658
  clientHeadersOf,
1701
1659
  clientIdentityOf,
1660
+ clientNameOf,
1702
1661
  createIdentityCommands,
1703
1662
  credentialsPath,
1704
1663
  describeManualSync,
1664
+ envApiKey,
1665
+ failedCyclesInARow,
1705
1666
  fetchIdentityLine,
1706
1667
  fetchServedTexts,
1707
1668
  formatIntegrationStatus,
1669
+ fromKitResult,
1708
1670
  hasAnchorAt,
1709
1671
  hostedMcpUrl,
1710
1672
  identityLineOf,
@@ -1715,6 +1677,7 @@ export {
1715
1677
  integrationStatusAge,
1716
1678
  integrationStatusPath,
1717
1679
  isRunProfile,
1680
+ isRunnerFactory,
1718
1681
  launchdPlist,
1719
1682
  loadTexts,
1720
1683
  log,
@@ -1762,12 +1725,10 @@ export {
1762
1725
  systemdQuote,
1763
1726
  systemdUnit,
1764
1727
  textsCachePath,
1765
- trayHasWaiting,
1766
1728
  traySummary,
1767
1729
  uninstallService,
1768
1730
  upsertAnchorBlock,
1769
1731
  writeAnchor,
1770
- writeCachedTexts,
1771
1732
  writeCredentials,
1772
1733
  writeIntegrationStatus,
1773
1734
  writePending,