@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.
@@ -1,29 +1,32 @@
1
1
  import {
2
- ManualFollower,
3
- TextsStore,
2
+ MANUAL,
4
3
  acquireLeaderLock,
5
- atomicWriteFile,
6
4
  beat,
7
- buildRunPrompts,
8
- clientIdentityOf,
9
5
  credentialsPath,
10
- external_exports,
6
+ describeManualSync,
11
7
  idle,
12
8
  integrationDisabledBy,
13
- log,
14
- normalizeHandle,
15
- readJsonFile,
9
+ isRunnerFactory,
16
10
  resolveIdentity,
17
11
  resolveRunBudgetMs,
18
12
  resolveRunProfile,
19
- spawnCommand,
20
- spawnCommandSync,
21
- trayHasWaiting,
13
+ textsCachePath,
22
14
  writeIntegrationStatus
23
- } from "./chunk-KUZZ3MW2.js";
15
+ } from "./chunk-W3LYBKIV.js";
16
+ import {
17
+ WINDOWS_SWEEP_TIMEOUT_MS,
18
+ describeWindowsSweep,
19
+ redactDiagnostic,
20
+ spawnRun,
21
+ sweepWindowsDescendants
22
+ } from "./chunk-TH6XOVA3.js";
23
+ import {
24
+ clientIdentityOf,
25
+ log
26
+ } from "./chunk-NCSF3CCV.js";
24
27
 
25
28
  // src/integration/run.ts
26
- import * as path3 from "path";
29
+ import * as path2 from "path";
27
30
  import * as fs from "fs";
28
31
 
29
32
  // src/daemon/config.ts
@@ -37,7 +40,7 @@ function wsUrlFor(apiBase) {
37
40
  }
38
41
  async function resolveDaemonConfig(opts) {
39
42
  const home = path.resolve(opts.home);
40
- const id = resolveIdentity(home);
43
+ const id = resolveIdentity(home, { envKey: opts.envKey !== false });
41
44
  if (id === null) {
42
45
  throw new Error(`no AgentChat identity in ${home} \u2014 register this agent first`);
43
46
  }
@@ -68,11 +71,10 @@ async function resolveDaemonConfig(opts) {
68
71
  }
69
72
 
70
73
  // src/integration/integration.ts
71
- import { AgentChatClient as AgentChatClient2 } from "agentchatme";
74
+ import * as crypto from "crypto";
75
+ import { AgentChatClient as AgentChatClient2, RealtimeClient, integration as kit } from "agentchatme";
72
76
 
73
- // src/integration/connection.ts
74
- import { EventEmitter } from "events";
75
- import { RealtimeClient } from "agentchatme";
77
+ // src/integration/socket-state.ts
76
78
  function socketStateOf(next, previous) {
77
79
  switch (next) {
78
80
  case "idle":
@@ -93,755 +95,168 @@ function socketStateOf(next, previous) {
93
95
  function blockedDetail(info) {
94
96
  return `auth rejected (close ${info.code}${info.reason ? ` ${info.reason}` : ""}) \u2014 check the agent's API key; a fresh hello is tried every 10\u201315 min until one is accepted`;
95
97
  }
96
- function stringField(record, keys) {
97
- for (const key of keys) {
98
- const value = record[key];
99
- if (typeof value === "string" && value.length > 0) return value;
100
- }
101
- return null;
102
- }
103
- function asRecord(value) {
104
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
105
- }
106
- var IntegrationConnection = class extends EventEmitter {
107
- constructor(options) {
108
- super();
109
- this.options = options;
110
- this.selfHandle = normalizeHandle(options.selfHandle);
111
- }
112
- options;
113
- rt = null;
114
- _state = "idle";
115
- stopped = false;
116
- /** Rejected hellos since the last accepted one: the first is an error line, the rest are info. */
117
- refusals = 0;
118
- selfHandle;
119
- get state() {
120
- return this._state;
121
- }
122
- /** True only while the socket is live — `hello.ok` received, not merely open. */
123
- get connected() {
124
- return this._state === "ready";
125
- }
126
- on(event, listener) {
127
- return super.on(event, listener);
128
- }
129
- /** Open the SDK's client. Once: it lives until `stop()`, reconnecting on its own. */
130
- start() {
131
- if (this.rt !== null || this.stopped) return;
132
- const rt = new RealtimeClient({
133
- apiKey: this.options.apiKey,
134
- baseUrl: this.options.wsBase,
135
- clientIdentity: clientIdentityOf(this.options.client),
136
- // Delivered = this machine received it. Acked at parse time, before
137
- // anything here runs; read state is the agent's verdict, separately.
138
- ackOnReceipt: true,
139
- reconnect: true,
140
- ...this.options.reconnectIntervalMs !== void 0 ? { reconnectInterval: this.options.reconnectIntervalMs } : {},
141
- ...this.options.maxReconnectIntervalMs !== void 0 ? { maxReconnectInterval: this.options.maxReconnectIntervalMs } : {}
142
- });
143
- this.rt = rt;
144
- this.setState("connecting");
145
- rt.on("state", (next) => this.setState(socketStateOf(next, this._state)));
146
- rt.on("blocked", (info) => this.onBlocked(info));
147
- rt.onConnect(() => {
148
- this.refusals = 0;
149
- log.info(`socket ready (hello.ok) \u2014 acks ${rt.ackNegotiated ? "on receipt" : "not negotiated by this server"}`);
150
- this.emit("ready");
151
- });
152
- rt.onDisconnect(({ code, reason, initiator }) => {
153
- if (this.stopped) return;
154
- log.warn(`socket closed (${code}${reason ? ` ${reason}` : ""}${initiator === "client" ? ", by this client" : ""})`);
155
- });
156
- rt.onError((err) => {
157
- if (this.stopped) return;
158
- log.warn(`socket: ${err.message}`);
159
- });
160
- rt.on("message.new", (message) => {
161
- if (!this.stopped) this.onMessageFrame(message);
162
- });
163
- rt.on("wake", (frame) => {
164
- if (!this.stopped) this.onWakeFrame(frame);
165
- });
166
- rt.on("group.invite.received", (message) => {
167
- if (!this.stopped) this.onInviteFrame(message);
168
- });
169
- rt.connect().catch((err) => {
170
- if (this.stopped || rt.state !== "idle") return;
171
- log.error(`socket cannot be opened (${err instanceof Error ? err.message : String(err)}) \u2014 no WebSocket implementation; holding no socket`);
172
- });
173
- }
174
- /** End the SDK's client. Final: a stopped connection is not restarted. */
175
- stop() {
176
- if (this.stopped) return;
177
- this.stopped = true;
178
- const rt = this.rt;
179
- this.rt = null;
180
- try {
181
- rt?.disconnect();
182
- } catch {
183
- }
184
- this.setState("closed");
185
- }
186
- setState(next) {
187
- const prev = this._state;
188
- if (prev === next) return;
189
- this._state = next;
190
- if (next === "connecting") log.info("socket connecting");
191
- else if (next === "reconnecting") log.info("socket reconnecting \u2014 the SDK backs off and retries; it never gives up");
192
- else if (next === "closed") log.info("socket closed");
193
- this.emit("state", next, prev);
194
- }
195
- /** The SDK is `blocked`: the server refused the credential on the hello. Fires per rejected attempt. */
196
- onBlocked(info) {
197
- if (this.stopped) return;
198
- const detail = blockedDetail(info);
199
- this.refusals += 1;
200
- if (this.refusals === 1) {
201
- log.error(`socket blocked (auth): ${detail}`);
202
- } else {
203
- const next = info.retryInMs === null ? "no retry" : `next hello in about ${Math.max(1, Math.round(info.retryInMs / 6e4))} min`;
204
- log.info(`socket still blocked (auth): close ${info.code}${info.reason ? ` ${info.reason}` : ""} \u2014 ${next}`);
205
- }
206
- this.emit("blocked", detail, info);
207
- }
208
- /**
209
- * A `message.new` frame. Only the sender (echo filter) and the ids (log
210
- * line) are read. `content`, `metadata`, previews — never touched. The SDK
211
- * acked it before this ran.
212
- */
213
- onMessageFrame(message) {
214
- const payload = asRecord(message.payload);
215
- if (payload === null) {
216
- log.warn("socket: message.new without an object payload \u2014 dropped");
217
- return;
218
- }
219
- const senderRaw = stringField(payload, ["sender", "sender_handle", "from"]);
220
- const sender = senderRaw === null ? null : normalizeHandle(senderRaw);
221
- const messageId = stringField(payload, ["id"]);
222
- const conversationId = stringField(payload, ["conversation_id"]);
223
- if (sender !== null && sender === this.selfHandle) {
224
- log.debug(`socket: own echo in ${conversationId ?? "?"} \u2014 not a wake`);
225
- this.emit("echo");
226
- return;
227
- }
228
- log.info(`wake \u2014 message.new conv=${conversationId ?? "?"} msg=${messageId ?? "?"} from=@${sender ?? "?"}`);
229
- this.emit("wake", { source: "message", sender, conversationId, messageId });
230
- }
231
- /** A `wake` frame, validated by the SDK. No message, nothing to ack. */
232
- onWakeFrame(frame) {
233
- const { conversation_id, anchor_message_id, step, reason } = frame.payload;
234
- log.info(`wake \u2014 ${reason} conv=${conversation_id} anchor=${anchor_message_id} step=${step}`);
235
- this.emit("wake", {
236
- source: "reminder",
237
- conversationId: conversation_id,
238
- anchorMessageId: anchor_message_id,
239
- step
240
- });
241
- }
242
- onInviteFrame(message) {
243
- const payload = asRecord(message.payload);
244
- if (payload === null) {
245
- log.warn("socket: group.invite.received without an object payload \u2014 dropped");
246
- return;
247
- }
248
- const inviteId = stringField(payload, ["invite_id", "id"]);
249
- if (inviteId === null) {
250
- log.warn("socket: group invite without an invite id \u2014 dropped");
251
- return;
252
- }
253
- const invite = {
254
- inviteId,
255
- groupId: stringField(payload, ["group_id", "conversation_id"]),
256
- groupName: stringField(payload, ["group_name", "name"]),
257
- inviterHandle: stringField(payload, ["inviter_handle", "inviter", "from"])
258
- };
259
- log.info(`wake \u2014 group invite ${invite.inviteId} to ${invite.groupId ?? "?"} from=@${invite.inviterHandle ?? "?"}`);
260
- this.emit("invite", invite);
261
- }
262
- };
263
-
264
- // src/integration/invoker.ts
265
- import * as crypto from "crypto";
266
-
267
- // src/integration/wake.ts
268
- var DEFAULT_WAKE_DEBOUNCE_MS = 2e3;
269
- var WakeCoalescer = class {
270
- onFire;
271
- debounceMs;
272
- now;
273
- _setTimeout;
274
- _clearTimeout;
275
- timer = null;
276
- delayed = null;
277
- delayedDeadline = null;
278
- stopped = false;
279
- wakes = 0;
280
- absorbed = 0;
281
- fires = 0;
282
- constructor(options) {
283
- const debounce = options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS;
284
- if (!(debounce >= 0)) throw new RangeError("debounceMs must be >= 0");
285
- this.onFire = options.onFire;
286
- this.debounceMs = debounce;
287
- this.now = options.now ?? Date.now;
288
- this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
289
- this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
290
- }
291
- /** True while a debounce timer is armed. */
292
- get armed() {
293
- return this.timer !== null;
294
- }
295
- /** True while a retry wake is scheduled and has not fired. */
296
- get delayedPending() {
297
- return this.delayed !== null;
298
- }
299
- /** Epoch ms of the pending retry wake, or null. */
300
- get delayedDue() {
301
- return this.delayedDeadline;
302
- }
303
- /** A wake: arm the timer if none is armed; otherwise absorb. */
304
- wake() {
305
- if (this.stopped) return;
306
- this.wakes += 1;
307
- if (this.timer !== null) {
308
- this.absorbed += 1;
309
- return;
310
- }
311
- this.timer = this._setTimeout(() => this.fire(), this.debounceMs);
312
- }
313
- /** A delayed wake (retry ladder). The sooner pending deadline is kept. */
314
- wakeAfter(delayMs) {
315
- if (this.stopped) return;
316
- const delay = Math.max(0, delayMs);
317
- const deadline = this.now() + delay;
318
- if (this.delayed !== null) {
319
- if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {
320
- return;
321
- }
322
- this._clearTimeout(this.delayed);
323
- }
324
- this.delayedDeadline = deadline;
325
- this.delayed = this._setTimeout(() => {
326
- this.delayed = null;
327
- this.delayedDeadline = null;
328
- this.wake();
329
- }, delay);
330
- }
331
- /**
332
- * Drop a pending retry wake, if there is one; returns whether there was.
333
- * The debounce timer and later wakes are unaffected. For when nothing is
334
- * owed any more — a run read the whole tray, or the tray was found empty —
335
- * so the retry would only ring for a backlog that is already handled.
336
- */
337
- cancelDelayed() {
338
- if (this.delayed === null) return false;
339
- this._clearTimeout(this.delayed);
340
- this.delayed = null;
341
- this.delayedDeadline = null;
342
- return true;
343
- }
344
- /** Cancel everything; later wakes are ignored. */
345
- stop() {
346
- this.stopped = true;
347
- if (this.timer !== null) {
348
- this._clearTimeout(this.timer);
349
- this.timer = null;
350
- }
351
- this.cancelDelayed();
352
- }
353
- fire() {
354
- this.timer = null;
355
- if (this.stopped) return;
356
- this.fires += 1;
357
- try {
358
- this.onFire();
359
- } catch {
360
- }
361
- }
362
- };
363
-
364
- // src/integration/invites.ts
365
- import * as path2 from "path";
366
- var OFFERED_INVITES_FILE = "invites.offered.json";
367
- var MAX_REMEMBERED = 1e3;
368
- var Schema = external_exports.object({
369
- version: external_exports.literal(1),
370
- offered: external_exports.array(external_exports.object({ id: external_exports.string(), at: external_exports.string() }))
371
- });
372
- function offeredInvitesPath(home) {
373
- return path2.join(home, OFFERED_INVITES_FILE);
374
- }
375
- var OfferedInvites = class _OfferedInvites {
376
- /** `home === null` keeps the set in memory only (tests). */
377
- constructor(home, entries = [], now = () => /* @__PURE__ */ new Date()) {
378
- this.home = home;
379
- this.now = now;
380
- this.entries = entries.slice(-MAX_REMEMBERED);
381
- }
382
- home;
383
- now;
384
- entries;
385
- /** Read the set from the identity home; a missing or malformed file is an empty set. */
386
- static load(home, now) {
387
- const parsed = Schema.safeParse(readJsonFile(offeredInvitesPath(home)));
388
- return new _OfferedInvites(home, parsed.success ? parsed.data.offered : [], now);
389
- }
390
- get size() {
391
- return this.entries.length;
392
- }
393
- has(inviteId) {
394
- return this.entries.some((entry) => entry.id === inviteId);
395
- }
396
- add(inviteId) {
397
- if (this.has(inviteId)) return;
398
- this.entries.push({ id: inviteId, at: this.now().toISOString() });
399
- while (this.entries.length > MAX_REMEMBERED) this.entries.shift();
400
- this.persist();
401
- }
402
- remove(inviteId) {
403
- const index = this.entries.findIndex((entry) => entry.id === inviteId);
404
- if (index === -1) return;
405
- this.entries.splice(index, 1);
406
- this.persist();
407
- }
408
- persist() {
409
- if (this.home === null) return;
410
- try {
411
- atomicWriteFile(
412
- offeredInvitesPath(this.home),
413
- `${JSON.stringify({ version: 1, offered: this.entries }, null, 2)}
414
- `,
415
- 384
416
- );
417
- } catch (err) {
418
- log.debug(`offered-invites write failed: ${String(err)}`);
419
- }
420
- }
421
- };
422
-
423
- // src/integration/invoker.ts
424
- var RETRY_LADDER_MS = [6e4, 3e5, 18e5];
425
- var PREFLIGHT_WATCH_MS = 5 * 6e4;
426
- var MAX_TAKEN = 1e3;
427
- var IntegrationInvoker = class {
428
- runner;
429
- prompts;
430
- budgetMs;
431
- ladder;
432
- preflightWatchMs;
433
- now;
434
- _setTimeout;
435
- _clearTimeout;
436
- onChange;
437
- newRunId;
438
- trayHasWaiting;
439
- offered;
440
- coalescer;
441
- cycleDue = false;
442
- running = null;
443
- inFlight = null;
444
- stopped = false;
445
- /** Invites queued for a run, in arrival order. */
446
- invites = [];
447
- /** Invites whose run did not start; offered again on the next wake. */
448
- invitesAwaitingRetry = [];
449
- /**
450
- * Invite ids this process has taken, offered or not. The on-disk store says
451
- * what was OFFERED; this says what is already in hand here — queued, in
452
- * flight, or awaiting its retry — so the connect-time listing and a live
453
- * frame for the same invite cannot queue it twice.
454
- */
455
- taken = /* @__PURE__ */ new Set();
456
- retryRung = 0;
457
- preflightWatch = null;
458
- preflightWasDown = false;
459
- invitesSeen = 0;
460
- runsStarted = 0;
461
- runsOk = 0;
462
- runsFailed = 0;
463
- runsTimedOut = 0;
464
- runsNotStarted = 0;
465
- runsSkippedEmpty = 0;
466
- lastRun = null;
467
- constructor(options) {
468
- this.runner = options.runner;
469
- this.prompts = options.prompts;
470
- this.budgetMs = options.budgetMs;
471
- this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
472
- this.preflightWatchMs = options.preflightWatchMs ?? PREFLIGHT_WATCH_MS;
473
- this.now = options.now ?? Date.now;
474
- this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
475
- this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
476
- this.onChange = options.onChange ?? (() => void 0);
477
- this.newRunId = options.runId ?? (() => crypto.randomUUID());
478
- this.trayHasWaiting = options.trayHasWaiting ?? null;
479
- this.offered = options.offeredInvites ?? new OfferedInvites(null);
480
- this.coalescer = new WakeCoalescer({
481
- onFire: () => this.onWakeFired(),
482
- debounceMs: options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS,
483
- now: this.now,
484
- ...options.setTimeout ? { setTimeout: options.setTimeout } : {},
485
- ...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
486
- });
487
- }
488
- // ─── wakes ──────────────────────────────────────────────────────────────
489
- /** A wake from the socket (a frame), the connect-time catch-up, or any other source. Coalesced, then run. */
490
- wake(source) {
491
- if (this.stopped) return;
492
- log.debug(`wake (${source})`);
493
- this.coalescer.wake();
494
- this.onChange();
495
- }
496
- /**
497
- * The second wake kind. Offered once per machine: an invite already offered
498
- * to a run, already queued, or awaiting its retry is not queued again.
499
- * Returns true when newly queued.
500
- */
501
- invite(invite) {
502
- if (this.stopped) return false;
503
- if (this.offered.has(invite.inviteId) || this.taken.has(invite.inviteId)) return false;
504
- this.taken.add(invite.inviteId);
505
- if (this.taken.size > MAX_TAKEN) {
506
- const oldest = this.taken.values().next().value;
507
- if (oldest !== void 0) this.taken.delete(oldest);
508
- }
509
- this.invitesSeen += 1;
510
- this.invites.push(invite);
511
- this.onChange();
512
- this.schedule();
513
- return true;
514
- }
515
- /**
516
- * Cancel timers and interrupt a run in flight (its signal aborts; the
517
- * runner SIGTERMs the run's process group). `settled()` resolves when the
518
- * interrupted run has ended.
519
- */
520
- stop() {
521
- this.stopped = true;
522
- this.coalescer.stop();
523
- this.clearPreflightWatch();
524
- this.inFlight?.abort();
525
- }
526
- /** The promise of the work currently running, for tests and graceful stops. */
527
- settled() {
528
- return this.running ?? Promise.resolve();
529
- }
530
- counters() {
531
- return {
532
- wakes: this.coalescer.wakes,
533
- absorbed: this.coalescer.absorbed,
534
- invites: this.invitesSeen,
535
- runsStarted: this.runsStarted,
536
- runsOk: this.runsOk,
537
- runsFailed: this.runsFailed,
538
- runsTimedOut: this.runsTimedOut,
539
- runsNotStarted: this.runsNotStarted,
540
- runsSkippedEmpty: this.runsSkippedEmpty,
541
- retryRung: this.retryRung,
542
- retryDueAt: this.coalescer.delayedDue,
543
- lastRun: this.lastRun,
544
- running: this.running !== null
545
- };
546
- }
547
- // ─── worker ─────────────────────────────────────────────────────────────
548
- onWakeFired() {
549
- this.cycleDue = true;
550
- if (this.invitesAwaitingRetry.length > 0) {
551
- const retry = this.invitesAwaitingRetry.splice(0);
552
- log.info(`${retry.length} group invite(s) whose run did not start are offered again`);
553
- this.invites.push(...retry);
554
- }
555
- this.schedule();
556
- }
557
- /** Run the worker if idle. One run at a time; work that lands mid-run runs afterwards. */
558
- schedule() {
559
- if (this.running) return;
560
- this.running = this.drain().finally(() => {
561
- this.running = null;
562
- this.onChange();
563
- if (!this.stopped && (this.cycleDue || this.invites.length > 0)) this.schedule();
564
- });
565
- }
566
- async drain() {
567
- while (!this.stopped) {
568
- const invite = this.invites.shift();
569
- if (invite) {
570
- await this.run("invite", invite);
571
- continue;
572
- }
573
- if (this.cycleDue) {
574
- this.cycleDue = false;
575
- if (!await this.trayOwesRun()) continue;
576
- await this.run("wake");
577
- continue;
578
- }
579
- return;
580
- }
581
- }
582
- /**
583
- * The count before a wake run. True: start the run (something waits, or
584
- * the count could not be read). False: the tray is empty — no run, nothing
585
- * owed — or the invoker stopped while counting.
586
- */
587
- async trayOwesRun() {
588
- if (this.trayHasWaiting === null) return true;
589
- let waiting;
590
- try {
591
- waiting = await this.trayHasWaiting();
592
- } catch (err) {
593
- if (this.stopped) return false;
594
- log.warn(
595
- `tray count failed (${err instanceof Error ? err.message : String(err)}) \u2014 starting the run anyway: a failed count is not an empty tray`
596
- );
597
- return true;
598
- }
599
- if (this.stopped) return false;
600
- if (waiting) return true;
601
- this.runsSkippedEmpty += 1;
602
- log.info(`wake: the tray is empty \u2014 no run (nothing is owed; ${this.runsSkippedEmpty} skipped so far)`);
603
- this.settleLadder();
604
- this.onChange();
605
- return false;
606
- }
607
- /**
608
- * Nothing is owed any more — a wake run read the whole tray, or a count
609
- * found it empty: back to the first rung, drop a pending re-wake (it would
610
- * only ring for a backlog that is already handled), end the preflight watch.
611
- */
612
- settleLadder() {
613
- this.retryRung = 0;
614
- if (this.coalescer.cancelDelayed()) log.info("pending re-wake cancelled \u2014 nothing is owed any more");
615
- this.clearPreflightWatch();
616
- }
617
- async run(kind, invite) {
618
- const runId = this.newRunId();
619
- const startedAt = this.now();
620
- this.runsStarted += 1;
621
- this.onChange();
622
- log.info(`run start kind=${kind} id=${runId} budget=${Math.round(this.budgetMs / 1e3)}s`);
623
- const controller = new AbortController();
624
- this.inFlight = controller;
625
- let offerRecorded = false;
626
- const onStarted = () => {
627
- if (invite === void 0 || offerRecorded) return;
628
- offerRecorded = true;
629
- this.offered.add(invite.inviteId);
630
- };
631
- let outcome;
632
- try {
633
- const prompts = await this.prompts();
634
- if (prompts === null) {
635
- outcome = {
636
- state: "not_started",
637
- exitCode: null,
638
- durationMs: this.now() - startedAt,
639
- detail: "no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home"
640
- };
641
- } else if (this.stopped) {
642
- outcome = { state: "not_started", exitCode: null, durationMs: this.now() - startedAt, detail: "interrupted before the runtime was started" };
643
- } else {
644
- const prompt = kind === "invite" ? prompts.invite : prompts.wake;
645
- outcome = await this.runner.start({
646
- kind,
647
- prompt,
648
- runId,
649
- budgetMs: this.budgetMs,
650
- signal: controller.signal,
651
- ...invite !== void 0 ? { onStarted } : {}
652
- });
653
- }
654
- } catch (err) {
655
- outcome = {
656
- state: "not_started",
657
- exitCode: null,
658
- durationMs: this.now() - startedAt,
659
- detail: `runner threw: ${err instanceof Error ? err.message : String(err)}`
660
- };
661
- } finally {
662
- if (this.inFlight === controller) this.inFlight = null;
663
- }
664
- this.lastRun = {
665
- kind,
666
- started_at: new Date(startedAt).toISOString(),
667
- ended_at: new Date(this.now()).toISOString(),
668
- state: outcome.state,
669
- exit_code: outcome.exitCode,
670
- duration_ms: outcome.durationMs,
671
- detail: outcome.detail ?? null
672
- };
673
- switch (outcome.state) {
674
- case "ok":
675
- this.runsOk += 1;
676
- if (kind === "wake") this.settleLadder();
677
- log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1e3)}s (output discarded; any send was the agent's own hosted-tool call)`);
678
- break;
679
- case "failed":
680
- this.runsFailed += 1;
681
- break;
682
- case "timed_out":
683
- this.runsTimedOut += 1;
684
- break;
685
- case "not_started":
686
- this.runsNotStarted += 1;
687
- break;
688
- }
689
- if (invite !== void 0) this.settleInvite(invite, outcome, offerRecorded);
690
- if (outcome.state !== "ok") {
691
- log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""}`);
692
- if (this.stopped) {
693
- } else if (kind === "wake") {
694
- this.scheduleRetry(`run ${outcome.state}`);
695
- }
696
- }
697
- this.onChange();
698
- }
699
- /**
700
- * An invite counts as offered once its run has started (recorded at
701
- * `onStarted`; a runner that never signals it is recorded here, when the
702
- * run ends): the agent had its chance, and the invite stays reachable
703
- * through the hosted invite tools in any later run — including a run this
704
- * integration interrupted. A run that never got going is no offer: the
705
- * record is taken back and the invite is held for the next wake.
706
- */
707
- settleInvite(invite, outcome, offerRecorded) {
708
- if (outcome.state === "not_started") {
709
- if (offerRecorded) this.offered.remove(invite.inviteId);
710
- if (!this.invitesAwaitingRetry.some((i) => i.inviteId === invite.inviteId)) this.invitesAwaitingRetry.push(invite);
711
- log.info(`group-invite run did not start \u2014 invite ${invite.inviteId} is offered again on the next wake`);
712
- return;
713
- }
714
- if (!offerRecorded) this.offered.add(invite.inviteId);
715
- if (outcome.state !== "ok") log.info(`group-invite run ${outcome.state} \u2014 the invite stays pending server-side, reachable through the hosted tools`);
716
- }
717
- scheduleRetry(reason) {
718
- if (this.coalescer.delayedPending) {
719
- log.info(`${reason} \u2014 a re-wake is already scheduled; not climbing the ladder`);
720
- return;
721
- }
722
- if (this.retryRung >= this.ladder.length) {
723
- log.warn(
724
- `${reason} \u2014 retry ladder exhausted; the backlog stays unread. Watching the runtime's preflight every ${Math.round(this.preflightWatchMs / 1e3)}s: if it comes back, one re-wake; any wake also re-runs`
725
- );
726
- this.armPreflightWatch();
727
- return;
728
- }
729
- const delay = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 6e4;
730
- this.retryRung += 1;
731
- log.warn(`${reason} \u2014 re-waking in ${Math.round(delay / 1e3)}s (rung ${this.retryRung}/${this.ladder.length})`);
732
- this.coalescer.wakeAfter(delay);
733
- }
734
- // ─── preflight watch, after an exhausted ladder ─────────────────────────
735
- armPreflightWatch() {
736
- if (this.stopped || this.preflightWatch !== null) return;
737
- this.preflightWatch = this._setTimeout(() => {
738
- this.preflightWatch = null;
739
- void this.probePreflight();
740
- }, this.preflightWatchMs);
741
- this.onChange();
742
- }
743
- clearPreflightWatch() {
744
- if (this.preflightWatch !== null) {
745
- this._clearTimeout(this.preflightWatch);
746
- this.preflightWatch = null;
747
- }
748
- this.preflightWasDown = false;
749
- }
750
- async probePreflight() {
751
- if (this.stopped) return;
752
- let ok;
753
- try {
754
- ok = (await this.runner.preflight()).ok;
755
- } catch {
756
- ok = false;
757
- }
758
- if (this.stopped) return;
759
- if (!ok) {
760
- if (!this.preflightWasDown) log.info("runtime preflight is not ok \u2014 watching for it to come back");
761
- this.preflightWasDown = true;
762
- this.armPreflightWatch();
763
- return;
764
- }
765
- if (this.preflightWasDown) {
766
- this.preflightWasDown = false;
767
- log.info("runtime preflight is ok again after an exhausted ladder \u2014 waking once");
768
- this.wake("preflight");
769
- return;
770
- }
771
- log.info("runtime preflight was already ok \u2014 the failures are not its readiness; the backlog waits for the next wake");
772
- }
773
- };
774
98
 
775
99
  // src/integration/integration.ts
776
100
  var HEARTBEAT_MS = 3e4;
777
101
  var STATUS_MS = 3e4;
778
102
  var HTTP_TIMEOUT_MS = 1e4;
103
+ var RUNNER_DEADLINE_SLACK_MS = 6e4;
104
+ var PREFLIGHT_DEADLINE_MS = 6e4;
105
+ var CYCLE_FAILURE_CHARS = 240;
106
+ function reasonOf(source, frameReason) {
107
+ switch (source) {
108
+ case "message":
109
+ return "messages";
110
+ case "invite":
111
+ return "invite";
112
+ case "wake_frame":
113
+ return frameReason ?? "reminder";
114
+ default:
115
+ return null;
116
+ }
117
+ }
118
+ function withDeadline(work, ms, onTimeout) {
119
+ return new Promise((resolve3, reject) => {
120
+ let done = false;
121
+ const timer = setTimeout(() => {
122
+ if (done) return;
123
+ done = true;
124
+ try {
125
+ resolve3(onTimeout());
126
+ } catch (err) {
127
+ reject(err);
128
+ }
129
+ }, ms);
130
+ timer.unref?.();
131
+ work.then(
132
+ (value) => {
133
+ if (done) return;
134
+ done = true;
135
+ clearTimeout(timer);
136
+ resolve3(value);
137
+ },
138
+ (err) => {
139
+ if (done) return;
140
+ done = true;
141
+ clearTimeout(timer);
142
+ reject(err);
143
+ }
144
+ );
145
+ });
146
+ }
779
147
  var Integration = class {
780
148
  constructor(options) {
781
149
  this.options = options;
782
150
  const { cfg, client } = options;
783
- this.api = options.api ?? new AgentChatClient2({
784
- apiKey: cfg.apiKey,
785
- baseUrl: cfg.apiBase,
786
- clientIdentity: clientIdentityOf(client),
787
- timeoutMs: HTTP_TIMEOUT_MS,
788
- retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 }
151
+ const identity = clientIdentityOf(client);
152
+ this.api = options.api ?? new AgentChatClient2({ apiKey: cfg.apiKey, baseUrl: cfg.apiBase, clientIdentity: identity, timeoutMs: HTTP_TIMEOUT_MS, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
153
+ this.texts = new kit.TextsCache({
154
+ client: this.api,
155
+ runtime: client.runtime,
156
+ filePath: textsCachePath(cfg.home),
157
+ onError: (err) => log.warn(err.message)
789
158
  });
790
- this.manual = options.manualPath === void 0 ? null : new ManualFollower({ path: options.manualPath, apiBase: cfg.apiBase, ...options.manualFetch !== void 0 ? { fetch: options.manualFetch } : {} });
791
- this.texts = options.texts ?? new TextsStore({ home: cfg.home, runtime: client.runtime, client: this.api, onChange: () => this.textsChanged() });
792
- this.invoker = new IntegrationInvoker({
793
- runner: options.runner,
794
- prompts: () => this.runPrompts(),
795
- budgetMs: options.budgetMs,
796
- onChange: () => this.writeStatus(),
797
- trayHasWaiting: () => trayHasWaiting(this.api),
798
- offeredInvites: OfferedInvites.load(cfg.home)
159
+ this.texts.onChange((texts, source) => {
160
+ log.info(`texts ${source === "server" ? "fetched" : "read from the cache"} for ${client.runtime} (texts v${texts.version}, manual ${texts.manual.version})`);
161
+ this.writeStatus();
799
162
  });
800
- this.connection = options.connection ?? new IntegrationConnection({ apiKey: cfg.apiKey, wsBase: cfg.wsBase, selfHandle: cfg.handle, client });
801
- this.connection.on("wake", (wake) => this.invoker.wake(wake.source));
802
- this.connection.on("invite", (invite) => {
803
- this.invoker.invite(invite);
163
+ this.manual = options.manualPath === void 0 ? null : new kit.ManualSync({
164
+ texts: this.texts,
165
+ targetPath: options.manualPath,
166
+ fallback: MANUAL,
167
+ ...options.manualFetch !== void 0 ? { fetch: options.manualFetch } : {},
168
+ onResult: (result) => {
169
+ const line = `manual: ${describeManualSync({ ...result, source: result.source === "fallback" ? "bundled" : result.source })}`;
170
+ if (result.upToDate === false || result.state === "failed") log.warn(line);
171
+ else if (result.written) log.info(line);
172
+ }
804
173
  });
805
- this.connection.on("ready", () => {
806
- void this.catchUp();
174
+ this.realtime = options.realtime ?? new RealtimeClient({
175
+ apiKey: cfg.apiKey,
176
+ baseUrl: cfg.wsBase,
177
+ clientIdentity: identity,
178
+ ackOnReceipt: true,
179
+ reconnect: true,
180
+ capabilities: { heartbeat: true, rewake: true }
807
181
  });
808
- this.connection.on("state", (state) => {
809
- if (state === "ready") {
182
+ this.realtime.on("state", (next) => {
183
+ const word = socketStateOf(next, this.socket);
184
+ if (word === this.socket) return;
185
+ this.socket = word;
186
+ if (word === "ready") {
810
187
  beat(cfg.home);
811
188
  this.lastError = null;
189
+ 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"}`);
812
190
  } else {
813
191
  idle(cfg.home);
192
+ if (word === "reconnecting") log.info("socket reconnecting \u2014 the SDK backs off and retries; it never gives up");
814
193
  }
815
194
  this.writeStatus();
816
195
  });
817
- this.connection.on("blocked", (detail) => {
818
- this.lastError = detail;
196
+ this.realtime.on("blocked", (info) => {
197
+ this.lastError = blockedDetail(info);
198
+ log.error(`socket blocked (auth): ${this.lastError}`);
819
199
  this.writeStatus();
820
200
  });
201
+ this.realtime.on("wake", (frame) => {
202
+ const payload = frame.payload ?? {};
203
+ if (payload.reason === "unanswered" && typeof payload.step === "number") this.lastUnansweredStep = payload.step;
204
+ });
205
+ this.loop = new kit.ReceiveLoop({
206
+ client: this.api,
207
+ // The kit's own switch: off, no invite is dismissed on the agent's behalf.
208
+ ...options.dismissIgnoredInvites === false ? { dismissIgnoredInvites: false } : {},
209
+ texts: this.texts,
210
+ mode: "singleRun",
211
+ socket: this.realtime,
212
+ handle: cfg.handle,
213
+ startRun: (request) => this.startRun(request),
214
+ onEvent: (event) => this.onEvent(event),
215
+ ...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
216
+ ...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
217
+ ...options.cycleTimeoutMs !== void 0 ? { cycleTimeoutMs: options.cycleTimeoutMs } : {},
218
+ ...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {}
219
+ });
821
220
  }
822
221
  options;
823
222
  api;
824
- connection;
223
+ realtime;
825
224
  texts;
826
225
  manual;
827
- invoker;
226
+ loop;
828
227
  heartbeatTimer = null;
829
228
  statusTimer = null;
229
+ socket = "idle";
830
230
  lastError = null;
831
231
  stopping = false;
232
+ stopped = null;
233
+ invites = 0;
234
+ runsStarted = 0;
235
+ runsOk = 0;
236
+ runsFailed = 0;
237
+ runsTimedOut = 0;
238
+ runsNotStarted = 0;
239
+ runsSkippedEmpty = 0;
240
+ lastRun = null;
241
+ /** The newest wake since the last run started (for `RunRequest.wake`). */
242
+ pendingWake = null;
243
+ /** The rung of the newest `unanswered` wake frame (the kit's wake event does not carry it). */
244
+ lastUnansweredStep = null;
832
245
  async start() {
833
- const pre = await this.options.runner.preflight();
834
- if (!pre.ok) {
835
- throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? "unknown"}`);
836
- }
246
+ const pre = await withDeadline(this.options.runner.preflight(), PREFLIGHT_DEADLINE_MS, () => ({
247
+ ok: false,
248
+ detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1e3)} s`
249
+ }));
250
+ if (!pre.ok) throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? "unknown"}`);
837
251
  log.info(
838
252
  `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`
839
253
  );
840
254
  await this.texts.start();
841
255
  if (this.stopping) return;
842
- this.connection.start();
256
+ void this.manual?.start();
257
+ await this.loop.start();
843
258
  this.heartbeatTimer = setInterval(() => {
844
- if (this.connection.connected) beat(this.options.cfg.home);
259
+ if (this.socket === "ready") beat(this.options.cfg.home);
845
260
  }, HEARTBEAT_MS);
846
261
  this.heartbeatTimer.unref();
847
262
  this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS);
@@ -849,8 +264,8 @@ var Integration = class {
849
264
  this.writeStatus();
850
265
  }
851
266
  /**
852
- * Stop holding the socket and interrupt a run in flight (its process group
853
- * is SIGTERMed by the runner). Synchronous; `settled()` or `stopAndWait()`
267
+ * Stop holding the socket and interrupt a run in flight (its signal aborts;
268
+ * the runner SIGTERMs its process group). `idle()` / `stopAndWait()`
854
269
  * tell when the run has actually ended.
855
270
  */
856
271
  stop() {
@@ -858,25 +273,20 @@ var Integration = class {
858
273
  this.stopping = true;
859
274
  if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
860
275
  if (this.statusTimer) clearInterval(this.statusTimer);
861
- this.invoker.stop();
276
+ this.stopped = this.loop.stop();
862
277
  this.texts.stop();
863
278
  this.manual?.stop();
864
- this.connection.stop();
279
+ this.socket = "closed";
865
280
  idle(this.options.cfg.home);
866
281
  this.writeStatus();
867
282
  }
868
- /**
869
- * `stop()`, then wait up to `graceMs` for the interrupted run to end. What a
870
- * shutdown awaits before the process exits, so a launchd/systemd stop
871
- * reaches the child and the restarted daemon does not find a run still
872
- * going. Resolves true when nothing is running any more.
873
- */
283
+ /** `stop()`, then wait up to `graceMs` for the interrupted run to end. Resolves true when nothing runs any more. */
874
284
  async stopAndWait(graceMs) {
875
285
  this.stop();
876
286
  let timer = null;
877
287
  try {
878
288
  return await Promise.race([
879
- this.invoker.settled().then(() => true),
289
+ (this.stopped ?? Promise.resolve()).then(() => true),
880
290
  new Promise((resolve3) => {
881
291
  timer = setTimeout(() => resolve3(false), graceMs);
882
292
  })
@@ -885,13 +295,16 @@ var Integration = class {
885
295
  if (timer !== null) clearTimeout(timer);
886
296
  }
887
297
  }
888
- /** A run in flight finishes on its own; this resolves when it has. */
889
- settled() {
890
- return this.invoker.settled();
298
+ /** Resolves when no cycle (and so no run) is running: the kit's `ReceiveLoop.idle()`. */
299
+ idle() {
300
+ return this.loop.idle();
301
+ }
302
+ /** A wake heard outside the socket (a test, a webhook the integration received). */
303
+ wake() {
304
+ this.loop.wake();
891
305
  }
892
306
  snapshot() {
893
- const c = this.invoker.counters();
894
- const socket = this.stopping ? "closed" : this.connection.state;
307
+ const status = this.loop.status();
895
308
  const texts = this.texts.current();
896
309
  return {
897
310
  version: 2,
@@ -900,68 +313,147 @@ var Integration = class {
900
313
  runtime: this.options.runner.name,
901
314
  handle: this.options.cfg.handle,
902
315
  profile: this.options.profile,
903
- socket,
904
- wakes: c.wakes,
905
- wakes_absorbed: c.absorbed,
906
- invites: c.invites,
907
- runs_started: c.runsStarted,
908
- runs_ok: c.runsOk,
909
- runs_failed: c.runsFailed,
910
- runs_timed_out: c.runsTimedOut,
911
- runs_not_started: c.runsNotStarted,
912
- runs_skipped_empty: c.runsSkippedEmpty,
913
- last_run: c.lastRun,
914
- retry_rung: c.retryRung,
915
- retry_due_at: c.retryDueAt === null ? null : new Date(c.retryDueAt).toISOString(),
316
+ socket: this.stopping ? "closed" : this.socket,
317
+ wakes: status.coalescer.wakes,
318
+ wakes_absorbed: status.coalescer.absorbed,
319
+ invites: this.invites,
320
+ runs_started: this.runsStarted,
321
+ runs_ok: this.runsOk,
322
+ runs_failed: this.runsFailed,
323
+ runs_timed_out: this.runsTimedOut,
324
+ runs_not_started: this.runsNotStarted,
325
+ runs_skipped_empty: this.runsSkippedEmpty,
326
+ last_run: this.lastRun,
327
+ // No local retry ladder (the server re-wakes, D3); kept for older readers.
328
+ retry_rung: 0,
329
+ retry_due_at: null,
916
330
  last_error: this.lastError,
917
331
  texts: {
918
332
  source: this.texts.source,
919
333
  fetched_at: this.texts.fetchedAt,
920
334
  version: texts?.version ?? null,
921
335
  manual_version: texts?.manual.version ?? null
922
- }
336
+ },
337
+ capabilities: status.socket === null ? null : status.socket.capabilities,
338
+ intake_paused: status.socket === null ? null : status.socket.intakePaused,
339
+ recent_cycles: status.recentCycles.map((cycle) => ({
340
+ at: cycle.at,
341
+ outcome: cycle.outcome,
342
+ cards: cycle.cards,
343
+ invites: cycle.invites,
344
+ failure: cycle.failure === null ? null : cycle.failure.slice(0, CYCLE_FAILURE_CHARS)
345
+ }))
923
346
  };
924
347
  }
925
- /**
926
- * After every change in the texts in hand: the status file, and the skill
927
- * file brought to the manual they announce. Exposed for an injected store's
928
- * `onChange` (tests); the store this class builds calls it itself.
929
- */
930
- textsChanged() {
348
+ // ─── the one run ────────────────────────────────────────────────────────
349
+ async startRun(request) {
350
+ const kind = request.cards === 0 && (request.invites ?? 0) > 0 ? "invite" : "wake";
351
+ const wake = this.pendingWake ?? { reason: kind === "invite" ? "invite" : "messages" };
352
+ this.pendingWake = null;
353
+ const runId = crypto.randomUUID();
354
+ const startedAt = Date.now();
355
+ const budgetMs = this.options.budgetMs;
356
+ const slackMs = this.options.runnerDeadlineSlackMs ?? RUNNER_DEADLINE_SLACK_MS;
357
+ this.runsStarted += 1;
931
358
  this.writeStatus();
932
- if (this.manual !== null && !this.stopping) void this.manual.follow(this.texts.current()?.manual ?? null);
933
- }
934
- /** The served texts plus the pointer line, or null while no text is in hand. */
935
- async runPrompts() {
936
- const texts = await this.texts.ensure();
937
- return texts === null ? null : buildRunPrompts(texts, this.options.manualPointer);
938
- }
939
- /**
940
- * The connect-time catch-up: one wake (the invoker counts the tray before
941
- * any run, so an empty tray costs a count, not a run) and the pending invites.
942
- */
943
- async catchUp() {
944
- if (this.stopping) return;
945
- log.info("wake \u2014 connect (a run starts only if the tray has something unread)");
946
- this.invoker.wake("connect");
359
+ log.info(`run start kind=${kind} id=${runId} budget=${Math.round(budgetMs / 1e3)}s (tray: ${request.cards ?? "?"} card(s), ${request.invites ?? "?"} invite(s))`);
360
+ const controller = new AbortController();
361
+ const onAbort = () => controller.abort();
362
+ if (request.signal.aborted) controller.abort();
363
+ else request.signal.addEventListener("abort", onAbort, { once: true });
364
+ let outcome;
947
365
  try {
948
- const invites = await this.api.listGroupInvites();
949
- if (this.stopping) return;
950
- let surfaced = 0;
951
- for (const row of invites) {
952
- const invite = {
953
- inviteId: row.id,
954
- groupId: row.group_id ?? null,
955
- groupName: row.group_name ?? null,
956
- inviterHandle: row.inviter_handle ?? null
957
- };
958
- if (this.invoker.invite(invite)) surfaced += 1;
959
- }
960
- if (surfaced > 0) log.info(`wake \u2014 ${surfaced} pending group invite(s) surfaced on connect`);
366
+ outcome = await withDeadline(
367
+ this.options.runner.start({
368
+ kind,
369
+ wake,
370
+ prompt: `${request.prompt}
371
+
372
+ ${this.options.manualPointer}`,
373
+ runId,
374
+ budgetMs,
375
+ signal: controller.signal
376
+ }),
377
+ budgetMs + slackMs,
378
+ () => {
379
+ controller.abort();
380
+ return {
381
+ state: "timed_out",
382
+ exitCode: null,
383
+ durationMs: Date.now() - startedAt,
384
+ detail: `the runner did not return within ${Math.round((budgetMs + slackMs) / 1e3)} s (budget plus ${Math.round(slackMs / 1e3)} s) \u2014 abandoned so the next wake can run`
385
+ };
386
+ }
387
+ );
961
388
  } catch (err) {
962
- log.warn(`connect-time invite list failed (${err instanceof Error ? err.message : String(err)}) \u2014 live invite frames are unaffected`);
389
+ outcome = { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: `runner threw: ${err instanceof Error ? err.message : String(err)}` };
390
+ } finally {
391
+ request.signal.removeEventListener("abort", onAbort);
392
+ }
393
+ this.lastRun = {
394
+ kind,
395
+ started_at: new Date(startedAt).toISOString(),
396
+ ended_at: (/* @__PURE__ */ new Date()).toISOString(),
397
+ state: outcome.state,
398
+ exit_code: outcome.exitCode,
399
+ duration_ms: outcome.durationMs,
400
+ detail: outcome.detail ?? null
401
+ };
402
+ switch (outcome.state) {
403
+ case "ok":
404
+ this.runsOk += 1;
405
+ log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1e3)}s (output discarded; any send was the agent's own hosted-tool call)`);
406
+ break;
407
+ case "failed":
408
+ this.runsFailed += 1;
409
+ break;
410
+ case "timed_out":
411
+ this.runsTimedOut += 1;
412
+ break;
413
+ case "not_started":
414
+ this.runsNotStarted += 1;
415
+ break;
416
+ }
417
+ if (outcome.state !== "ok") {
418
+ log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""} \u2014 the cards stay on the tray; the next wake (or the server's re-wake) finds them`);
963
419
  }
964
420
  this.writeStatus();
421
+ return outcome.state === "ok" ? { status: "completed" } : { status: outcome.state === "not_started" ? "not_started" : "failed", ...outcome.detail !== void 0 ? { detail: outcome.detail } : {} };
422
+ }
423
+ onEvent(event) {
424
+ switch (event.type) {
425
+ case "wake": {
426
+ if (event.source === "invite") this.invites += 1;
427
+ const reason = reasonOf(event.source, event.reason);
428
+ if (reason !== null) {
429
+ this.pendingWake = reason === "unanswered" && this.lastUnansweredStep !== null ? { reason, step: this.lastUnansweredStep } : { reason };
430
+ }
431
+ log.info(`wake \u2014 ${event.source}${event.reason ? ` (${event.reason})` : ""}${event.conversationId ? ` conv=${event.conversationId}` : ""}`);
432
+ break;
433
+ }
434
+ case "echo":
435
+ log.debug(`own echo${event.conversationId ? ` in ${event.conversationId}` : ""} \u2014 not a wake`);
436
+ break;
437
+ case "cycle": {
438
+ const { outcome, cards, invites } = event.summary;
439
+ if (outcome === "empty" || outcome === "nothing_owed") {
440
+ this.runsSkippedEmpty += 1;
441
+ log.info(`wake: ${outcome === "empty" ? "the tray is empty" : "nothing owed (muted cards only)"} \u2014 no run (${cards} card(s), ${invites} invite(s))`);
442
+ } else if (outcome === "abandoned") {
443
+ log.warn(`wake cycle abandoned by the watchdog: ${event.summary.failure ?? "it ran past its deadline"} \u2014 the next wake starts a new one`);
444
+ } else if (outcome === "texts_missing") {
445
+ this.runsNotStarted += 1;
446
+ log.warn("no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home \u2014 no run this time");
447
+ }
448
+ this.writeStatus();
449
+ break;
450
+ }
451
+ case "error":
452
+ if (!this.stopping) log.warn(`receive loop: ${event.error.message}`);
453
+ break;
454
+ default:
455
+ break;
456
+ }
965
457
  }
966
458
  writeStatus() {
967
459
  writeIntegrationStatus(this.options.cfg.home, this.snapshot());
@@ -976,12 +468,12 @@ var SHUTDOWN_GRACE_MS = 1e4;
976
468
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
977
469
  var KEEP_LOG_BYTES = 1024 * 1024;
978
470
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
979
- function fingerprint(home) {
980
- const id = resolveIdentity(home);
471
+ function fingerprint(home, envKey) {
472
+ const id = resolveIdentity(home, { envKey });
981
473
  return id === null ? null : `${id.apiKey}:${id.handle ?? ""}`;
982
474
  }
983
475
  function boundDaemonLog(home) {
984
- const file = path3.join(home, "daemon.log");
476
+ const file = path2.join(home, "daemon.log");
985
477
  try {
986
478
  const size = fs.statSync(file).size;
987
479
  if (size <= MAX_LOG_BYTES) return;
@@ -1001,8 +493,8 @@ ${keep.toString("utf-8")}`
1001
493
  }
1002
494
  }
1003
495
  async function runIntegration(opts) {
1004
- const home = path3.resolve(opts.home);
1005
- const workdir = path3.resolve(opts.workdir);
496
+ const home = path2.resolve(opts.home);
497
+ const workdir = path2.resolve(opts.workdir);
1006
498
  const env = opts.env ?? process.env;
1007
499
  const profile = opts.profile ?? resolveRunProfile(env);
1008
500
  const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env);
@@ -1010,6 +502,8 @@ async function runIntegration(opts) {
1010
502
  if (process.env["AGENTCHAT_LOG_LEVEL"] === void 0) process.env["AGENTCHAT_LOG_LEVEL"] = "info";
1011
503
  const lock = acquireLeaderLock(home);
1012
504
  if (lock === null) return 1;
505
+ const envKey = opts.credentialsFromHomeOnly !== true;
506
+ const identityOf = () => resolveIdentity(home, { envKey });
1013
507
  const disabledBy = integrationDisabledBy(env);
1014
508
  const disabled = disabledBy !== null;
1015
509
  let live = null;
@@ -1082,28 +576,30 @@ async function runIntegration(opts) {
1082
576
  offStatus(null);
1083
577
  for (; ; ) {
1084
578
  if (shuttingDown || opts.signal?.aborted) break;
1085
- const fp = fingerprint(home);
579
+ const fp = fingerprint(home, envKey);
1086
580
  const identityChanged = fp !== observedFingerprint;
1087
581
  if (identityChanged) {
1088
582
  disconnect(fp === null ? "signed out" : "identity changed");
1089
583
  observedFingerprint = fp;
1090
584
  failures = 0;
1091
585
  lastFailure = null;
1092
- if (fp === null || disabled) offStatus(fp === null ? null : resolveIdentity(home)?.handle ?? null);
586
+ if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null);
1093
587
  }
1094
588
  if (fp === null) {
1095
589
  } else if (disabled) {
1096
590
  } else if (fp !== liveFingerprint) {
1097
591
  try {
1098
- const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client });
592
+ const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey });
593
+ const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner;
1099
594
  const candidate = new Integration({
1100
595
  cfg,
1101
- runner: opts.runner,
596
+ runner,
1102
597
  client: opts.client,
1103
598
  manualPointer: opts.manualPointer,
1104
599
  ...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
1105
600
  profile,
1106
- budgetMs
601
+ budgetMs,
602
+ ...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}
1107
603
  });
1108
604
  await candidate.start();
1109
605
  live = candidate;
@@ -1115,7 +611,7 @@ async function runIntegration(opts) {
1115
611
  if (msg !== lastFailure) {
1116
612
  log.warn(`not connecting yet: ${msg}`);
1117
613
  lastFailure = msg;
1118
- offStatus(resolveIdentity(home)?.handle ?? null);
614
+ offStatus(identityOf()?.handle ?? null);
1119
615
  }
1120
616
  failures += 1;
1121
617
  live = null;
@@ -1145,158 +641,19 @@ async function runIntegration(opts) {
1145
641
  }
1146
642
  return 0;
1147
643
  }
1148
-
1149
- // src/integration/spawn-run.ts
1150
- var DEFAULT_GRACE_MS = 5e3;
1151
- var STDERR_TAIL_CHARS = 400;
1152
- function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
1153
- return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\b(api[_ -]?key\s*[:=]\s*)\S+/gi, "$1[redacted]").replace(/\b(Bearer)\s+[A-Za-z0-9._~-]{8,}\b/gi, "$1 [redacted]").replace(/\bac_[A-Za-z0-9_-]{8,}\b/g, "[redacted AgentChat key]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "[redacted key]").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").replace(/\s+/g, " ").trim().slice(-max);
1154
- }
1155
- function killProcessTree(child, signal) {
1156
- if (child.pid === void 0) return;
1157
- try {
1158
- if (process.platform === "win32") {
1159
- spawnCommandSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
1160
- windowsHide: true,
1161
- stdio: "ignore"
1162
- });
1163
- } else {
1164
- process.kill(-child.pid, signal);
1165
- }
1166
- } catch {
1167
- try {
1168
- child.kill(signal);
1169
- } catch {
1170
- }
1171
- }
1172
- }
1173
- function spawnRun(spec) {
1174
- const started = Date.now();
1175
- return new Promise((resolve3) => {
1176
- let settled = false;
1177
- let stdoutBytes = 0;
1178
- let stderrTail = "";
1179
- let timedOut = false;
1180
- let interrupted = false;
1181
- let killTimer = null;
1182
- let graceTimer = null;
1183
- let onAbort = null;
1184
- const finish = (outcome) => {
1185
- if (settled) return;
1186
- settled = true;
1187
- if (killTimer) clearTimeout(killTimer);
1188
- if (graceTimer) clearTimeout(graceTimer);
1189
- if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
1190
- resolve3({ ...outcome, durationMs: Date.now() - started });
1191
- };
1192
- if (spec.signal?.aborted) {
1193
- finish({ state: "not_started", exitCode: null, detail: "interrupted before the runtime was started" });
1194
- return;
1195
- }
1196
- let child;
1197
- try {
1198
- child = spawnCommand(spec.command, [...spec.args], {
1199
- cwd: spec.cwd,
1200
- env: spec.env,
1201
- stdio: [spec.stdin === null ? "ignore" : "pipe", "pipe", "pipe"],
1202
- detached: process.platform !== "win32",
1203
- windowsHide: true
1204
- });
1205
- } catch (err) {
1206
- finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
1207
- return;
1208
- }
1209
- if (spec.onStarted) {
1210
- const onStarted = spec.onStarted;
1211
- child.once("spawn", () => {
1212
- try {
1213
- onStarted();
1214
- } catch {
1215
- }
1216
- });
1217
- }
1218
- child.stdout?.on("data", (chunk) => {
1219
- stdoutBytes += chunk.length;
1220
- });
1221
- child.stderr?.on("data", (chunk) => {
1222
- stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
1223
- });
1224
- if (spec.stdin !== null && child.stdin) {
1225
- child.stdin.on("error", () => {
1226
- });
1227
- try {
1228
- child.stdin.write(spec.stdin);
1229
- child.stdin.end();
1230
- } catch {
1231
- }
1232
- }
1233
- const terminate = () => {
1234
- killProcessTree(child, "SIGTERM");
1235
- if (graceTimer) clearTimeout(graceTimer);
1236
- graceTimer = setTimeout(() => killProcessTree(child, "SIGKILL"), spec.graceMs ?? DEFAULT_GRACE_MS);
1237
- };
1238
- killTimer = setTimeout(() => {
1239
- timedOut = true;
1240
- terminate();
1241
- }, spec.budgetMs);
1242
- if (spec.signal) {
1243
- onAbort = () => {
1244
- if (settled) return;
1245
- interrupted = true;
1246
- terminate();
1247
- };
1248
- spec.signal.addEventListener("abort", onAbort, { once: true });
1249
- }
1250
- child.on("error", (err) => {
1251
- finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
1252
- });
1253
- child.on("close", (code, signal) => {
1254
- const tail = redactDiagnostic(stderrTail);
1255
- if (timedOut) {
1256
- finish({
1257
- state: "timed_out",
1258
- exitCode: code,
1259
- detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget and was killed${tail ? `: ${tail}` : ""}`
1260
- });
1261
- return;
1262
- }
1263
- if (interrupted) {
1264
- finish({
1265
- state: "failed",
1266
- exitCode: code,
1267
- detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${tail ? `: ${tail}` : ""}`
1268
- });
1269
- return;
1270
- }
1271
- if (code === 0) {
1272
- finish({ state: "ok", exitCode: 0 });
1273
- return;
1274
- }
1275
- const exit = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
1276
- if (stdoutBytes === 0) {
1277
- finish({ state: "not_started", exitCode: code, detail: `${exit} with nothing on stdout${tail ? `: ${tail}` : ""}` });
1278
- return;
1279
- }
1280
- finish({ state: "failed", exitCode: code, detail: `${exit}${tail ? `: ${tail}` : ""}` });
1281
- });
1282
- });
1283
- }
1284
644
  export {
1285
- DEFAULT_WAKE_DEBOUNCE_MS,
1286
645
  Integration,
1287
- IntegrationConnection,
1288
- IntegrationInvoker,
1289
- OFFERED_INVITES_FILE,
1290
- OfferedInvites,
1291
- PREFLIGHT_WATCH_MS,
1292
- RETRY_LADDER_MS,
1293
- WakeCoalescer,
1294
- offeredInvitesPath,
646
+ PREFLIGHT_DEADLINE_MS,
647
+ RUNNER_DEADLINE_SLACK_MS,
648
+ WINDOWS_SWEEP_TIMEOUT_MS,
649
+ blockedDetail,
650
+ describeWindowsSweep,
1295
651
  redactDiagnostic,
1296
652
  resolveDaemonConfig,
1297
653
  runIntegration,
1298
654
  socketStateOf,
1299
655
  spawnRun,
656
+ sweepWindowsDescendants,
1300
657
  wsBaseFor,
1301
658
  wsUrlFor
1302
659
  };