@agentchatme/agent-core 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,17 +7,24 @@ import {
7
7
  agentLockRefusal,
8
8
  beat,
9
9
  clearStandby,
10
+ createListenerReporter,
10
11
  credentialsPath,
11
12
  describeManualSync,
13
+ ensureListenerInstanceId,
12
14
  envKeyConflict,
15
+ followIdentityAnchor,
13
16
  idle,
14
17
  isRunnerFactory,
18
+ listenerReasonKindOf,
19
+ listenerReportStatusOf,
15
20
  markStandby,
16
21
  resolveIdentity,
22
+ resolveManualPointer,
17
23
  standbyWaiting,
24
+ tellListener,
18
25
  textsCachePath,
19
26
  writeIntegrationStatus
20
- } from "./chunk-AQTRC7G4.js";
27
+ } from "./chunk-6GMYBMID.js";
21
28
  import {
22
29
  INTEGRATION_ENV,
23
30
  INTEGRATION_ENV_LEGACY,
@@ -32,7 +39,7 @@ import {
32
39
  resolveRunProfile,
33
40
  spawnRun,
34
41
  sweepWindowsDescendants
35
- } from "./chunk-5KMQ23O6.js";
42
+ } from "./chunk-LPTOKVEE.js";
36
43
 
37
44
  // src/integration/run.ts
38
45
  import * as path2 from "path";
@@ -180,10 +187,12 @@ var Integration = class {
180
187
  client: this.api,
181
188
  runtime: client.runtime,
182
189
  filePath: textsCachePath(cfg.home),
183
- onError: (err) => log.warn(err.message)
190
+ onError: (err) => log.warn(err.message),
191
+ ...options.textsRefreshMs !== void 0 ? { refreshMs: options.textsRefreshMs } : {}
184
192
  });
185
193
  this.texts.onChange((texts, source) => {
186
194
  log.info(`texts ${source === "server" ? "fetched" : "read from the cache"} for ${client.runtime} (texts v${texts.version}, manual ${texts.manual.version})`);
195
+ this.follows = this.follows.then(() => this.followIdentityLine(texts));
187
196
  this.writeStatus();
188
197
  });
189
198
  this.manual = options.manualPath === void 0 ? null : new kit.ManualSync({
@@ -213,6 +222,8 @@ var Integration = class {
213
222
  beat(cfg.home);
214
223
  this.lastError = null;
215
224
  log.info(`socket ready (hello.ok) \u2014 acks ${this.realtime.ackNegotiated ? "on receipt" : "not negotiated by this server"}; ${this.realtime.capabilities.has("rewake") ? "the server re-wakes unanswered cards" : "this server does not re-wake unanswered cards"}`);
225
+ this.connected = true;
226
+ this.reportListener();
216
227
  } else {
217
228
  idle(cfg.home);
218
229
  if (word === "reconnecting") log.info("socket reconnecting \u2014 the SDK backs off and retries; it never gives up");
@@ -290,16 +301,31 @@ var Integration = class {
290
301
  paused;
291
302
  /** The runner's runtime check in flight: concurrent asks share it. */
292
303
  runtimeCheckInFlight = null;
304
+ /** What the identity block's last follow did (status `identity_line`); null without `anchorPath`, or before the first texts. */
305
+ identityLine = null;
306
+ /** The follows of the identity line, one after another (each texts change queues one; a stop waits for the one in flight). */
307
+ follows = Promise.resolve();
308
+ /** The socket's hello has been accepted since this integration started (a reconnect after it changes nothing). */
309
+ connected = false;
310
+ /** The recheck after a failed run failed, and the reason it gives (`runs_failing`); null when it passed or a run completed since. */
311
+ recheckFailing = null;
312
+ /** The runtime check after a failed run failed, and nothing has passed or completed since. */
313
+ runtimeCheckFailing = false;
293
314
  async start() {
294
315
  const pre = await withDeadline(this.options.runner.preflight(), PREFLIGHT_DEADLINE_MS, () => ({
295
316
  ok: false,
296
317
  detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1e3)} s`
297
318
  }));
298
- if (!pre.ok) throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? "unknown"}`);
319
+ if (!pre.ok) {
320
+ if (!this.stopping) tellListener(this.options.listenerReport, "not_ready", listenerReasonKindOf(pre.detail ?? ""));
321
+ throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? "unknown"}`);
322
+ }
323
+ if (!this.stopping && this.options.listenerReport?.status().state === "not_ready") tellListener(this.options.listenerReport, "ok");
299
324
  log.info(
300
325
  `integration up as @${this.options.cfg.handle} via ${this.options.runner.name} (${this.options.client.runtime} ${this.options.client.version}), profile ${this.options.profile}; fetching the served texts, then holding the socket`
301
326
  );
302
327
  await this.texts.start();
328
+ await this.follows;
303
329
  if (this.stopping) return;
304
330
  void this.manual?.start();
305
331
  await this.loop.start();
@@ -322,7 +348,7 @@ var Integration = class {
322
348
  if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
323
349
  if (this.statusTimer) clearInterval(this.statusTimer);
324
350
  this.recheckAbort.abort();
325
- this.stopped = Promise.all([this.loop.stop(), this.recheckInFlight ?? Promise.resolve()]).then(() => void 0);
351
+ this.stopped = Promise.all([this.loop.stop(), this.recheckInFlight ?? Promise.resolve(), this.follows]).then(() => void 0);
326
352
  this.texts.stop();
327
353
  this.manual?.stop();
328
354
  this.socket = "closed";
@@ -392,6 +418,8 @@ var Integration = class {
392
418
  version: texts?.version ?? null,
393
419
  manual_version: texts?.manual.version ?? null
394
420
  },
421
+ identity_line: this.identityLine,
422
+ listener_report: listenerReportStatusOf(this.options.listenerReport),
395
423
  capabilities: status.socket === null ? null : status.socket.capabilities,
396
424
  intake_paused: status.socket === null ? null : status.socket.intakePaused,
397
425
  recent_cycles: status.recentCycles.map((cycle) => ({
@@ -423,7 +451,14 @@ var Integration = class {
423
451
  const onAbort = () => controller.abort();
424
452
  if (request.signal.aborted) controller.abort();
425
453
  else request.signal.addEventListener("abort", onAbort, { once: true });
426
- const identityLine = this.texts.current()?.identity_line;
454
+ const texts = this.texts.current();
455
+ const identityLine = texts?.identity_line;
456
+ let pointer = "";
457
+ try {
458
+ pointer = resolveManualPointer(this.options.manualPointer, texts);
459
+ } catch (err) {
460
+ log.warn(`run pointer: the integration's pointer function threw (${err instanceof Error ? err.message : String(err)}); the run starts without the line`);
461
+ }
427
462
  let outcome;
428
463
  try {
429
464
  outcome = await withDeadline(
@@ -432,9 +467,9 @@ var Integration = class {
432
467
  ...conversationId !== void 0 ? { conversationId } : {},
433
468
  wake,
434
469
  // No pointer, no trailing blank lines.
435
- prompt: this.options.manualPointer.trim().length > 0 ? `${request.prompt}
470
+ prompt: pointer.trim().length > 0 ? `${request.prompt}
436
471
 
437
- ${this.options.manualPointer}` : request.prompt,
472
+ ${pointer}` : request.prompt,
438
473
  runId,
439
474
  ...identityLine !== void 0 && identityLine.trim().length > 0 ? { identityLine } : {},
440
475
  budgetMs,
@@ -528,6 +563,11 @@ ${this.options.manualPointer}` : request.prompt,
528
563
  const took = `${Math.round((Date.now() - startedAt) / 1e3)} s`;
529
564
  if (answer.ok) log.info(`runtime check ok (${this.options.runner.name}: the model answered, ${took}; output discarded)`);
530
565
  else if (!this.stopping) log.warn(`runtime check failed (${this.options.runner.name}, ${took}): ${answer.detail ?? "no detail"} \u2014 a failed run is not reported as this conversation's`);
566
+ const overtaken = !answer.ok && this.lastOkRunAt !== null && Date.parse(this.lastOkRunAt) >= startedAt;
567
+ if (!this.stopping && !overtaken) {
568
+ this.runtimeCheckFailing = !answer.ok;
569
+ this.reportListener();
570
+ }
531
571
  return answer.ok ? { ok: true } : { ok: false, ...answer.detail !== void 0 ? { detail: answer.detail } : {} };
532
572
  } finally {
533
573
  this.recheckAbort.signal.removeEventListener("abort", onStop);
@@ -566,6 +606,9 @@ ${this.options.manualPointer}` : request.prompt,
566
606
  this.failingRuns = 0;
567
607
  this.runsFailing = null;
568
608
  this.lastRecheckAt = 0;
609
+ this.recheckFailing = null;
610
+ this.runtimeCheckFailing = false;
611
+ this.reportListener();
569
612
  return;
570
613
  }
571
614
  this.failingSince ??= endedAt;
@@ -590,15 +633,34 @@ ${this.options.manualPointer}` : request.prompt,
590
633
  const reason = `${this.options.runner.name}: ${pre.detail ?? "its check failed"}`;
591
634
  if (this.runsFailing?.reason !== reason) log.warn(`runs failing \u2014 ${reason} (since ${this.failingSince}, ${this.failingRuns} run(s) missed); status says so until a run succeeds`);
592
635
  this.runsFailing = { reason, since: this.failingSince, runs_missed: this.failingRuns, checked_at: checkedAt };
593
- } else if (this.runsFailing !== null) {
594
- this.runsFailing = {
595
- ...this.runsFailing,
596
- reason: `${this.options.runner.name} checks out now, but runs still fail${this.lastRun?.detail ? ` (last: ${this.lastRun.detail})` : ""}`,
597
- checked_at: checkedAt
598
- };
636
+ this.recheckFailing = listenerReasonKindOf(pre.detail ?? "");
637
+ } else {
638
+ if (this.runsFailing !== null) {
639
+ this.runsFailing = {
640
+ ...this.runsFailing,
641
+ reason: `${this.options.runner.name} checks out now, but runs still fail${this.lastRun?.detail ? ` (last: ${this.lastRun.detail})` : ""}`,
642
+ checked_at: checkedAt
643
+ };
644
+ }
645
+ this.recheckFailing = null;
599
646
  }
647
+ this.reportListener();
600
648
  this.writeStatus();
601
649
  }
650
+ /**
651
+ * What the listener report says now, from what this integration knows:
652
+ * `runs_failing` while the recheck after a failed run fails (its reason)
653
+ * or the runtime check after one fails (`runtime_check_failed`), else
654
+ * `ok` once connected; before the first hello nothing new is said. Nothing
655
+ * once stopping: a stop is the supervisor's to report, or not.
656
+ */
657
+ reportListener() {
658
+ const sink = this.options.listenerReport;
659
+ if (sink === void 0 || this.stopping) return;
660
+ if (this.recheckFailing !== null) tellListener(sink, "runs_failing", this.recheckFailing);
661
+ else if (this.runtimeCheckFailing) tellListener(sink, "runs_failing", "runtime_check_failed");
662
+ else if (this.connected) tellListener(sink, "ok");
663
+ }
602
664
  /**
603
665
  * Whether this integration can serve its agent: not while the server refuses
604
666
  * its key (socket `blocked`: rotated by `recover` elsewhere, revoked), nor
@@ -681,6 +743,57 @@ ${this.options.manualPointer}` : request.prompt,
681
743
  }
682
744
  this.writeStatus();
683
745
  }
746
+ /**
747
+ * The identity block follows the served identity line: on each texts
748
+ * change, this agent's own block in the host's instruction file is brought
749
+ * to the line served now (`followIdentityAnchor`, under its rules). Said in
750
+ * the log and the status file (`identity_line`); never throws.
751
+ */
752
+ async followIdentityLine(texts) {
753
+ const filePath = this.options.anchorPath;
754
+ if (filePath === void 0 || this.stopping) return;
755
+ let result;
756
+ try {
757
+ result = await followIdentityAnchor({
758
+ filePath,
759
+ handle: this.options.cfg.handle,
760
+ identityLine: texts.identity_line,
761
+ template: texts.identity_line_template
762
+ });
763
+ } catch (err) {
764
+ result = { outcome: "failed", path: filePath, claimed: null, detail: `could not follow the identity line in ${filePath}: ${err instanceof Error ? err.message : String(err)}` };
765
+ }
766
+ let loadNote = null;
767
+ try {
768
+ loadNote = this.options.anchorLoadNote?.(this.options.cfg.handle, { identityLine: texts.identity_line, template: texts.identity_line_template }) ?? null;
769
+ } catch {
770
+ loadNote = null;
771
+ }
772
+ const notLoaded = loadNote !== null && !loadNote.ok ? loadNote.note : null;
773
+ const detail = loadNote === null ? result.detail : `${result.detail}; ${loadNote.note}`;
774
+ this.identityLine = { outcome: result.outcome, path: result.path, at: (/* @__PURE__ */ new Date()).toISOString(), texts_version: texts.version, detail, not_loaded: notLoaded };
775
+ const line = `identity line: ${result.outcome} \u2014 ${detail}`;
776
+ this.writeStatus();
777
+ if (notLoaded !== null && result.outcome !== "other_agent") {
778
+ log.warn(line);
779
+ return;
780
+ }
781
+ switch (result.outcome) {
782
+ case "updated":
783
+ case "absent":
784
+ case "hand_edited":
785
+ log.info(line);
786
+ break;
787
+ case "unchanged":
788
+ log.debug(line);
789
+ break;
790
+ case "other_agent":
791
+ log.error(line);
792
+ break;
793
+ default:
794
+ log.warn(line);
795
+ }
796
+ }
684
797
  writeStatus() {
685
798
  writeIntegrationStatus(this.options.cfg.home, this.snapshot());
686
799
  }
@@ -693,6 +806,7 @@ var MAX_BACKOFF_MS = 5 * 6e4;
693
806
  var STANDBY_POLL_MS = 3e4;
694
807
  var UNSERVABLE_RECHECK_MS = 6e4;
695
808
  var BLOCKED_RETRY_MS = 5 * 6e4;
809
+ var OFF_STATUS_REFRESH_MS = 3e4;
696
810
  var SHUTDOWN_GRACE_MS = 1e4;
697
811
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
698
812
  var KEEP_LOG_BYTES = 1024 * 1024;
@@ -746,6 +860,27 @@ async function runIntegration(opts) {
746
860
  const stopChecks = new AbortController();
747
861
  if (opts.signal?.aborted === true) stopChecks.abort();
748
862
  else opts.signal?.addEventListener("abort", () => stopChecks.abort(), { once: true });
863
+ let listener = null;
864
+ let instanceId;
865
+ const dropListener = () => {
866
+ listener?.reporter.stop();
867
+ listener = null;
868
+ };
869
+ const listenerFor = async (cfg, fp) => {
870
+ if (listener !== null && listener.fp === fp) return listener.reporter;
871
+ dropListener();
872
+ if (instanceId === void 0) instanceId = await ensureListenerInstanceId(home);
873
+ if (instanceId === null) return null;
874
+ const reporter = createListenerReporter({
875
+ apiKey: cfg.apiKey,
876
+ apiBase: cfg.apiBase,
877
+ client: opts.client,
878
+ instanceId,
879
+ ...opts.listenerReportTiming !== void 0 ? { timing: opts.listenerReportTiming } : {}
880
+ });
881
+ listener = { fp, reporter };
882
+ return reporter;
883
+ };
749
884
  const lock = await acquireLeaderLock(home, { ...opts.lease ?? {}, signal: stopChecks.signal });
750
885
  if (lock === null) return 1;
751
886
  let homeLost = null;
@@ -753,6 +888,7 @@ async function runIntegration(opts) {
753
888
  lock.onLost((why) => {
754
889
  homeLost = why;
755
890
  nudged = true;
891
+ dropListener();
756
892
  starting?.stop();
757
893
  live?.stop();
758
894
  log.error(`lost this home's daemon lock (${why}) \u2014 another daemon serves ${home} now; this one exits`);
@@ -800,36 +936,42 @@ async function runIntegration(opts) {
800
936
  const count = lock.renewErrors + (agentLock?.renewErrors ?? 0);
801
937
  return count === 0 ? null : { count, last: agentLock?.lastRenewError ?? lock.lastRenewError };
802
938
  };
803
- const offStatus = (handle) => writeIntegrationStatus(home, {
804
- version: 2,
805
- updated_at: (/* @__PURE__ */ new Date()).toISOString(),
806
- pid: process.pid,
807
- runtime: opts.runner.name,
808
- runtime_label: opts.runner.label ?? null,
809
- handle,
810
- profile,
811
- workdir,
812
- socket: disabled ? "off" : "idle",
813
- wakes: 0,
814
- wakes_absorbed: 0,
815
- invites: 0,
816
- runs_started: 0,
817
- runs_ok: 0,
818
- runs_failed: 0,
819
- runs_timed_out: 0,
820
- runs_not_started: 0,
821
- runs_skipped_empty: 0,
822
- last_run: null,
823
- retry_rung: 0,
824
- retry_due_at: null,
825
- last_error: lastFailure,
826
- texts: null,
827
- standby,
828
- runs_failing: unservable?.runsFailing ?? null,
829
- unservable: unservable === null ? null : { reason: unservable.kind, detail: unservable.detail, since: unservable.since, retry_at: new Date(unservable.retryAt).toISOString() },
830
- lease_errors: leaseErrors()
831
- });
939
+ let offStatusAt = 0;
940
+ const offStatus = (handle) => {
941
+ offStatusAt = Date.now();
942
+ writeIntegrationStatus(home, {
943
+ version: 2,
944
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
945
+ pid: process.pid,
946
+ runtime: opts.runner.name,
947
+ runtime_label: opts.runner.label ?? null,
948
+ handle,
949
+ profile,
950
+ workdir,
951
+ socket: disabled ? "off" : "idle",
952
+ wakes: 0,
953
+ wakes_absorbed: 0,
954
+ invites: 0,
955
+ runs_started: 0,
956
+ runs_ok: 0,
957
+ runs_failed: 0,
958
+ runs_timed_out: 0,
959
+ runs_not_started: 0,
960
+ runs_skipped_empty: 0,
961
+ last_run: null,
962
+ retry_rung: 0,
963
+ retry_due_at: null,
964
+ last_error: lastFailure,
965
+ texts: null,
966
+ standby,
967
+ runs_failing: unservable?.runsFailing ?? null,
968
+ unservable: unservable === null ? null : { reason: unservable.kind, detail: unservable.detail, since: unservable.since, retry_at: new Date(unservable.retryAt).toISOString() },
969
+ lease_errors: leaseErrors(),
970
+ listener_report: listenerReportStatusOf(listener?.reporter)
971
+ });
972
+ };
832
973
  const disconnect = (why) => {
974
+ dropListener();
833
975
  if (live === null) return;
834
976
  log.info(`${why} \u2014 disconnecting (a run in flight is interrupted), staying resident`);
835
977
  live.stop();
@@ -963,9 +1105,11 @@ async function runIntegration(opts) {
963
1105
  if (agentLock !== lease) return;
964
1106
  agentLost = why;
965
1107
  nudged = true;
1108
+ dropListener();
966
1109
  starting?.stop();
967
1110
  live?.stop();
968
1111
  });
1112
+ const listenerReport = await listenerFor(cfg, fp);
969
1113
  const runner = runnerFor(cfg, fp);
970
1114
  lastRunner = runner;
971
1115
  const candidate = new Integration({
@@ -974,6 +1118,8 @@ async function runIntegration(opts) {
974
1118
  client: opts.client,
975
1119
  manualPointer: opts.manualPointer,
976
1120
  ...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
1121
+ ...opts.anchorPath !== void 0 ? { anchorPath: opts.anchorPath } : {},
1122
+ ...opts.anchorLoadNote !== void 0 ? { anchorLoadNote: opts.anchorLoadNote } : {},
977
1123
  profile,
978
1124
  budgetMs,
979
1125
  ...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {},
@@ -982,6 +1128,7 @@ async function runIntegration(opts) {
982
1128
  ...opts.quietMs !== void 0 ? { quietMs: opts.quietMs } : {},
983
1129
  ...opts.maxMs !== void 0 ? { maxMs: opts.maxMs } : {},
984
1130
  ...opts.paceMs !== void 0 ? { paceMs: opts.paceMs } : {},
1131
+ ...listenerReport !== null ? { listenerReport } : {},
985
1132
  statusExtra: () => ({ lease_errors: leaseErrors() })
986
1133
  });
987
1134
  starting = candidate;
@@ -1003,14 +1150,15 @@ async function runIntegration(opts) {
1003
1150
  live = null;
1004
1151
  liveFingerprint = null;
1005
1152
  if (err instanceof StandbyError) {
1153
+ dropListener();
1006
1154
  offStatus(cachedCfg?.cfg.handle ?? identityOf()?.handle ?? null);
1007
1155
  } else {
1008
1156
  const msg = String(err instanceof Error ? err.message : err);
1009
1157
  if (msg !== lastFailure) {
1010
1158
  log.warn(`not connecting yet: ${msg}`);
1011
1159
  lastFailure = msg;
1012
- offStatus(identityOf()?.handle ?? null);
1013
1160
  }
1161
+ offStatus(identityOf()?.handle ?? null);
1014
1162
  failures += 1;
1015
1163
  }
1016
1164
  idle(home);
@@ -1022,10 +1170,12 @@ async function runIntegration(opts) {
1022
1170
  const deadline = Date.now() + waitMs;
1023
1171
  while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {
1024
1172
  await sleepUnless(opts.tickMs ?? TICK_MS, opts.signal);
1173
+ if (live === null && Date.now() - offStatusAt >= (opts.offStatusRefreshMs ?? OFF_STATUS_REFRESH_MS)) offStatus(observedFingerprint === null ? null : cachedCfg?.cfg.handle ?? identityOf()?.handle ?? null);
1025
1174
  }
1026
1175
  }
1027
1176
  process.off("SIGINT", onSigint);
1028
1177
  process.off("SIGTERM", onSigterm);
1178
+ dropListener();
1029
1179
  if (live !== null) {
1030
1180
  const ended = await live.stopAndWait(SHUTDOWN_GRACE_MS);
1031
1181
  if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1e3)}s of being interrupted \u2014 exiting anyway`);
@@ -1049,7 +1199,9 @@ export {
1049
1199
  RUNTIME_CHECK_DEADLINE_MS,
1050
1200
  WINDOWS_SWEEP_TIMEOUT_MS,
1051
1201
  blockedDetail,
1202
+ createListenerReporter,
1052
1203
  describeWindowsSweep,
1204
+ ensureListenerInstanceId,
1053
1205
  redactDiagnostic,
1054
1206
  resolveDaemonConfig,
1055
1207
  runIntegration,