@agentchatme/agent-core 0.1.0 → 0.3.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,30 +1,39 @@
1
1
  import {
2
- CODING_AGENTS_CLIENT_HEADERS,
2
+ ManualFollower,
3
+ TextsStore,
3
4
  acquireLeaderLock,
5
+ atomicWriteFile,
4
6
  beat,
7
+ buildRunPrompts,
8
+ clientIdentityOf,
5
9
  credentialsPath,
6
- doorbellDisabled,
7
- getMeLite,
10
+ external_exports,
8
11
  idle,
9
- listGroupInvites,
12
+ integrationDisabledBy,
10
13
  log,
14
+ normalizeHandle,
15
+ readJsonFile,
11
16
  resolveIdentity,
12
17
  resolveRunBudgetMs,
13
18
  resolveRunProfile,
14
19
  spawnCommand,
15
20
  spawnCommandSync,
16
21
  trayHasWaiting,
17
- writeDoorbellStatus
18
- } from "./chunk-I4U4A7HO.js";
22
+ writeIntegrationStatus
23
+ } from "./chunk-KUZZ3MW2.js";
19
24
 
20
- // src/doorbell/run.ts
21
- import * as path2 from "path";
25
+ // src/integration/run.ts
26
+ import * as path3 from "path";
22
27
  import * as fs from "fs";
23
28
 
24
29
  // src/daemon/config.ts
25
30
  import * as path from "path";
31
+ import { AgentChatClient } from "agentchatme";
32
+ function wsBaseFor(apiBase) {
33
+ return apiBase.replace(/^http/, "ws").replace(/\/+$/, "");
34
+ }
26
35
  function wsUrlFor(apiBase) {
27
- return apiBase.replace(/^http/, "ws").replace(/\/+$/, "") + "/v1/ws";
36
+ return `${wsBaseFor(apiBase)}/v1/ws`;
28
37
  }
29
38
  async function resolveDaemonConfig(opts) {
30
39
  const home = path.resolve(opts.home);
@@ -34,8 +43,14 @@ async function resolveDaemonConfig(opts) {
34
43
  }
35
44
  let handle = id.source === "file" ? id.handle : null;
36
45
  if (handle === null) {
37
- const me = await getMeLite({ apiKey: id.apiKey, apiBase: id.apiBase });
38
- if (me === null) {
46
+ const client = new AgentChatClient({
47
+ apiKey: id.apiKey,
48
+ baseUrl: id.apiBase,
49
+ clientIdentity: clientIdentityOf(opts.client),
50
+ timeoutMs: 1e4
51
+ });
52
+ const me = await client.getMe().catch(() => null);
53
+ if (me === null || typeof me.handle !== "string" || me.handle.length === 0) {
39
54
  throw new Error(
40
55
  "could not determine this agent\u2019s handle (no credentials file, and /v1/agents/me did not answer)"
41
56
  );
@@ -46,18 +61,212 @@ async function resolveDaemonConfig(opts) {
46
61
  apiKey: id.apiKey,
47
62
  handle,
48
63
  apiBase: id.apiBase,
49
- wsUrl: wsUrlFor(id.apiBase),
64
+ wsBase: wsBaseFor(id.apiBase),
50
65
  home,
51
- workdir: opts.workdir ?? path.join(home, "daemon-workdir")
66
+ workdir: path.resolve(opts.workdir)
52
67
  };
53
68
  }
54
69
 
55
- // src/doorbell/invoker.ts
70
+ // src/integration/integration.ts
71
+ import { AgentChatClient as AgentChatClient2 } from "agentchatme";
72
+
73
+ // src/integration/connection.ts
74
+ import { EventEmitter } from "events";
75
+ import { RealtimeClient } from "agentchatme";
76
+ function socketStateOf(next, previous) {
77
+ switch (next) {
78
+ case "idle":
79
+ return "idle";
80
+ case "connecting":
81
+ if (previous === "blocked") return "blocked";
82
+ return previous === "idle" || previous === "connecting" ? "connecting" : "reconnecting";
83
+ case "ready":
84
+ return "ready";
85
+ case "backoff":
86
+ return "reconnecting";
87
+ case "blocked":
88
+ return "blocked";
89
+ case "stopped":
90
+ return "closed";
91
+ }
92
+ }
93
+ function blockedDetail(info) {
94
+ 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
+ }
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
56
265
  import * as crypto from "crypto";
57
266
 
58
- // src/doorbell/knock.ts
59
- var DEFAULT_KNOCK_DEBOUNCE_MS = 2e3;
60
- var KnockCoalescer = class {
267
+ // src/integration/wake.ts
268
+ var DEFAULT_WAKE_DEBOUNCE_MS = 2e3;
269
+ var WakeCoalescer = class {
61
270
  onFire;
62
271
  debounceMs;
63
272
  now;
@@ -67,11 +276,11 @@ var KnockCoalescer = class {
67
276
  delayed = null;
68
277
  delayedDeadline = null;
69
278
  stopped = false;
70
- knocks = 0;
279
+ wakes = 0;
71
280
  absorbed = 0;
72
281
  fires = 0;
73
282
  constructor(options) {
74
- const debounce = options.debounceMs ?? DEFAULT_KNOCK_DEBOUNCE_MS;
283
+ const debounce = options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS;
75
284
  if (!(debounce >= 0)) throw new RangeError("debounceMs must be >= 0");
76
285
  this.onFire = options.onFire;
77
286
  this.debounceMs = debounce;
@@ -83,26 +292,26 @@ var KnockCoalescer = class {
83
292
  get armed() {
84
293
  return this.timer !== null;
85
294
  }
86
- /** True while a retry knock is scheduled and has not fired. */
295
+ /** True while a retry wake is scheduled and has not fired. */
87
296
  get delayedPending() {
88
297
  return this.delayed !== null;
89
298
  }
90
- /** Epoch ms of the pending retry knock, or null. */
299
+ /** Epoch ms of the pending retry wake, or null. */
91
300
  get delayedDue() {
92
301
  return this.delayedDeadline;
93
302
  }
94
- /** A knock: arm the timer if none is armed; otherwise absorb. */
95
- knock() {
303
+ /** A wake: arm the timer if none is armed; otherwise absorb. */
304
+ wake() {
96
305
  if (this.stopped) return;
97
- this.knocks += 1;
306
+ this.wakes += 1;
98
307
  if (this.timer !== null) {
99
308
  this.absorbed += 1;
100
309
  return;
101
310
  }
102
311
  this.timer = this._setTimeout(() => this.fire(), this.debounceMs);
103
312
  }
104
- /** A delayed knock (retry ladder). The sooner pending deadline is kept. */
105
- knockAfter(delayMs) {
313
+ /** A delayed wake (retry ladder). The sooner pending deadline is kept. */
314
+ wakeAfter(delayMs) {
106
315
  if (this.stopped) return;
107
316
  const delay = Math.max(0, delayMs);
108
317
  const deadline = this.now() + delay;
@@ -116,12 +325,12 @@ var KnockCoalescer = class {
116
325
  this.delayed = this._setTimeout(() => {
117
326
  this.delayed = null;
118
327
  this.delayedDeadline = null;
119
- this.knock();
328
+ this.wake();
120
329
  }, delay);
121
330
  }
122
331
  /**
123
- * Drop a pending retry knock, if there is one; returns whether there was.
124
- * The debounce timer and later knocks are unaffected. For when nothing is
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
125
334
  * owed any more — a run read the whole tray, or the tray was found empty —
126
335
  * so the retry would only ring for a backlog that is already handled.
127
336
  */
@@ -132,7 +341,7 @@ var KnockCoalescer = class {
132
341
  this.delayedDeadline = null;
133
342
  return true;
134
343
  }
135
- /** Cancel everything; later knocks are ignored. */
344
+ /** Cancel everything; later wakes are ignored. */
136
345
  stop() {
137
346
  this.stopped = true;
138
347
  if (this.timer !== null) {
@@ -152,11 +361,70 @@ var KnockCoalescer = class {
152
361
  }
153
362
  };
154
363
 
155
- // src/doorbell/invoker.ts
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
156
424
  var RETRY_LADDER_MS = [6e4, 3e5, 18e5];
157
425
  var PREFLIGHT_WATCH_MS = 5 * 6e4;
158
- var MAX_SEEN_INVITES = 1e3;
159
- var DoorbellInvoker = class {
426
+ var MAX_TAKEN = 1e3;
427
+ var IntegrationInvoker = class {
160
428
  runner;
161
429
  prompts;
162
430
  budgetMs;
@@ -168,13 +436,23 @@ var DoorbellInvoker = class {
168
436
  onChange;
169
437
  newRunId;
170
438
  trayHasWaiting;
439
+ offered;
171
440
  coalescer;
172
441
  cycleDue = false;
173
442
  running = null;
174
443
  inFlight = null;
175
444
  stopped = false;
445
+ /** Invites queued for a run, in arrival order. */
176
446
  invites = [];
177
- seenInvites = [];
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();
178
456
  retryRung = 0;
179
457
  preflightWatch = null;
180
458
  preflightWasDown = false;
@@ -198,31 +476,36 @@ var DoorbellInvoker = class {
198
476
  this.onChange = options.onChange ?? (() => void 0);
199
477
  this.newRunId = options.runId ?? (() => crypto.randomUUID());
200
478
  this.trayHasWaiting = options.trayHasWaiting ?? null;
201
- this.coalescer = new KnockCoalescer({
202
- onFire: () => this.onKnockFired(),
203
- debounceMs: options.debounceMs ?? DEFAULT_KNOCK_DEBOUNCE_MS,
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,
204
483
  now: this.now,
205
484
  ...options.setTimeout ? { setTimeout: options.setTimeout } : {},
206
485
  ...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
207
486
  });
208
487
  }
209
- // ─── knocks ─────────────────────────────────────────────────────────────
210
- /** A knock from the socket (a frame), the connect-time catch-up, or any other source. Coalesced, then run. */
211
- knock(source) {
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) {
212
491
  if (this.stopped) return;
213
- log.debug(`knock (${source})`);
214
- this.coalescer.knock();
492
+ log.debug(`wake (${source})`);
493
+ this.coalescer.wake();
215
494
  this.onChange();
216
495
  }
217
496
  /**
218
- * The second knock kind. Deduplicated by invite id for the life of the
219
- * process. Returns true when newly queued.
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.
220
500
  */
221
501
  invite(invite) {
222
502
  if (this.stopped) return false;
223
- if (this.seenInvites.includes(invite.inviteId)) return false;
224
- this.seenInvites.push(invite.inviteId);
225
- if (this.seenInvites.length > MAX_SEEN_INVITES) this.seenInvites.shift();
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
+ }
226
509
  this.invitesSeen += 1;
227
510
  this.invites.push(invite);
228
511
  this.onChange();
@@ -246,7 +529,7 @@ var DoorbellInvoker = class {
246
529
  }
247
530
  counters() {
248
531
  return {
249
- knocks: this.coalescer.knocks,
532
+ wakes: this.coalescer.wakes,
250
533
  absorbed: this.coalescer.absorbed,
251
534
  invites: this.invitesSeen,
252
535
  runsStarted: this.runsStarted,
@@ -262,8 +545,13 @@ var DoorbellInvoker = class {
262
545
  };
263
546
  }
264
547
  // ─── worker ─────────────────────────────────────────────────────────────
265
- onKnockFired() {
548
+ onWakeFired() {
266
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
+ }
267
555
  this.schedule();
268
556
  }
269
557
  /** Run the worker if idle. One run at a time; work that lands mid-run runs afterwards. */
@@ -279,20 +567,20 @@ var DoorbellInvoker = class {
279
567
  while (!this.stopped) {
280
568
  const invite = this.invites.shift();
281
569
  if (invite) {
282
- await this.run("invite", this.prompts.invite);
570
+ await this.run("invite", invite);
283
571
  continue;
284
572
  }
285
573
  if (this.cycleDue) {
286
574
  this.cycleDue = false;
287
575
  if (!await this.trayOwesRun()) continue;
288
- await this.run("knock", this.prompts.knock);
576
+ await this.run("wake");
289
577
  continue;
290
578
  }
291
579
  return;
292
580
  }
293
581
  }
294
582
  /**
295
- * The count before a knock run. True: start the run (something waits, or
583
+ * The count before a wake run. True: start the run (something waits, or
296
584
  * the count could not be read). False: the tray is empty — no run, nothing
297
585
  * owed — or the invoker stopped while counting.
298
586
  */
@@ -311,22 +599,22 @@ var DoorbellInvoker = class {
311
599
  if (this.stopped) return false;
312
600
  if (waiting) return true;
313
601
  this.runsSkippedEmpty += 1;
314
- log.info(`knock: the tray is empty \u2014 no run (nothing is owed; ${this.runsSkippedEmpty} skipped so far)`);
602
+ log.info(`wake: the tray is empty \u2014 no run (nothing is owed; ${this.runsSkippedEmpty} skipped so far)`);
315
603
  this.settleLadder();
316
604
  this.onChange();
317
605
  return false;
318
606
  }
319
607
  /**
320
- * Nothing is owed any more — a knock run read the whole tray, or a count
321
- * found it empty: back to the first rung, drop a pending re-knock (it would
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
322
610
  * only ring for a backlog that is already handled), end the preflight watch.
323
611
  */
324
612
  settleLadder() {
325
613
  this.retryRung = 0;
326
- if (this.coalescer.cancelDelayed()) log.info("pending re-knock cancelled \u2014 nothing is owed any more");
614
+ if (this.coalescer.cancelDelayed()) log.info("pending re-wake cancelled \u2014 nothing is owed any more");
327
615
  this.clearPreflightWatch();
328
616
  }
329
- async run(kind, prompt) {
617
+ async run(kind, invite) {
330
618
  const runId = this.newRunId();
331
619
  const startedAt = this.now();
332
620
  this.runsStarted += 1;
@@ -334,9 +622,35 @@ var DoorbellInvoker = class {
334
622
  log.info(`run start kind=${kind} id=${runId} budget=${Math.round(this.budgetMs / 1e3)}s`);
335
623
  const controller = new AbortController();
336
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
+ };
337
631
  let outcome;
338
632
  try {
339
- outcome = await this.runner.start({ kind, prompt, runId, budgetMs: this.budgetMs, signal: controller.signal });
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
+ }
340
654
  } catch (err) {
341
655
  outcome = {
342
656
  state: "not_started",
@@ -359,7 +673,7 @@ var DoorbellInvoker = class {
359
673
  switch (outcome.state) {
360
674
  case "ok":
361
675
  this.runsOk += 1;
362
- if (kind === "knock") this.settleLadder();
676
+ if (kind === "wake") this.settleLadder();
363
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)`);
364
678
  break;
365
679
  case "failed":
@@ -372,33 +686,50 @@ var DoorbellInvoker = class {
372
686
  this.runsNotStarted += 1;
373
687
  break;
374
688
  }
689
+ if (invite !== void 0) this.settleInvite(invite, outcome, offerRecorded);
375
690
  if (outcome.state !== "ok") {
376
691
  log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""}`);
377
692
  if (this.stopped) {
378
- } else if (kind === "knock") {
693
+ } else if (kind === "wake") {
379
694
  this.scheduleRetry(`run ${outcome.state}`);
380
- } else {
381
- log.info(`group-invite run ${outcome.state} \u2014 the invite stays pending server-side`);
382
695
  }
383
696
  }
384
697
  this.onChange();
385
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
+ }
386
717
  scheduleRetry(reason) {
387
718
  if (this.coalescer.delayedPending) {
388
- log.info(`${reason} \u2014 a re-knock is already scheduled; not climbing the ladder`);
719
+ log.info(`${reason} \u2014 a re-wake is already scheduled; not climbing the ladder`);
389
720
  return;
390
721
  }
391
722
  if (this.retryRung >= this.ladder.length) {
392
723
  log.warn(
393
- `${reason} \u2014 retry ladder exhausted; the backlog stays stored. Watching the runtime's preflight every ${Math.round(this.preflightWatchMs / 1e3)}s: if it comes back, one re-knock; any knock also re-runs`
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`
394
725
  );
395
726
  this.armPreflightWatch();
396
727
  return;
397
728
  }
398
729
  const delay = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 6e4;
399
730
  this.retryRung += 1;
400
- log.warn(`${reason} \u2014 re-knocking in ${Math.round(delay / 1e3)}s (rung ${this.retryRung}/${this.ladder.length})`);
401
- this.coalescer.knockAfter(delay);
731
+ log.warn(`${reason} \u2014 re-waking in ${Math.round(delay / 1e3)}s (rung ${this.retryRung}/${this.ladder.length})`);
732
+ this.coalescer.wakeAfter(delay);
402
733
  }
403
734
  // ─── preflight watch, after an exhausted ladder ─────────────────────────
404
735
  armPreflightWatch() {
@@ -433,310 +764,66 @@ var DoorbellInvoker = class {
433
764
  }
434
765
  if (this.preflightWasDown) {
435
766
  this.preflightWasDown = false;
436
- log.info("runtime preflight is ok again after an exhausted ladder \u2014 re-knocking once");
437
- this.knock("preflight");
767
+ log.info("runtime preflight is ok again after an exhausted ladder \u2014 waking once");
768
+ this.wake("preflight");
438
769
  return;
439
770
  }
440
- log.info("runtime preflight was already ok \u2014 the failures are not its readiness; the backlog waits for the next knock");
771
+ log.info("runtime preflight was already ok \u2014 the failures are not its readiness; the backlog waits for the next wake");
441
772
  }
442
773
  };
443
774
 
444
- // src/doorbell/socket.ts
445
- import { WebSocket } from "ws";
446
- import { EventEmitter } from "events";
447
- var BASE_BACKOFF_MS = 1e3;
448
- var MAX_BACKOFF_MS = 6e4;
449
- var LIVENESS_MS = 1e5;
450
- var RECONNECT_HARD_CAP_ATTEMPTS = 500;
451
- var HANDSHAKE_TIMEOUT_MS = 15e3;
452
- var AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401, 4403]);
453
- function stringField(record, keys) {
454
- for (const key of keys) {
455
- const value = record[key];
456
- if (typeof value === "string" && value.length > 0) return value;
457
- }
458
- return null;
459
- }
460
- function asRecord(value) {
461
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
462
- }
463
- var DoorbellSocket = class extends EventEmitter {
464
- constructor(options) {
465
- super();
466
- this.options = options;
467
- this.selfHandle = options.selfHandle.trim().replace(/^@/, "").toLowerCase();
468
- }
469
- options;
470
- ws = null;
471
- _state = "idle";
472
- attempt = 0;
473
- reconnectTimer = null;
474
- livenessTimer = null;
475
- stopped = false;
476
- _ackNegotiated = null;
477
- /** `hello.ok` seen on the CURRENT connection. Reset on every open. */
478
- helloOk = false;
479
- selfHandle;
480
- get state() {
481
- return this._state;
482
- }
483
- /** True only while the socket is live — `hello.ok` received, not merely open. */
484
- get connected() {
485
- return this._state === "ready";
486
- }
487
- /** null until the server answered; then whether `ack` was echoed. */
488
- get ackNegotiated() {
489
- return this._ackNegotiated;
490
- }
491
- on(event, listener) {
492
- return super.on(event, listener);
493
- }
494
- start() {
495
- this.stopped = false;
496
- this.open();
497
- }
498
- stop() {
499
- this.stopped = true;
500
- this.clearTimers();
501
- if (this._state !== "terminal") this.setState("closed");
502
- const ws = this.ws;
503
- this.ws = null;
504
- if (ws) {
505
- try {
506
- ws.close(1e3, "doorbell shutdown");
507
- } catch {
508
- }
509
- }
510
- }
511
- setState(next) {
512
- const prev = this._state;
513
- if (prev === next) return;
514
- this._state = next;
515
- this.emit("state", next, prev);
516
- }
517
- open() {
518
- if (this.stopped) return;
519
- this.setState(this.attempt === 0 ? "connecting" : "reconnecting");
520
- log.info(`doorbell socket ${this._state} (attempt ${this.attempt + 1})`);
521
- const ws = new WebSocket(this.options.url, {
522
- headers: {
523
- ...CODING_AGENTS_CLIENT_HEADERS,
524
- authorization: `Bearer ${this.options.apiKey}`,
525
- // Opt into the delivery-ack protocol: the server then leaves each
526
- // envelope `stored` until an ack — which this socket never sends.
527
- "x-agentchat-capabilities": "ack"
528
- },
529
- handshakeTimeout: HANDSHAKE_TIMEOUT_MS
530
- });
531
- this.ws = ws;
532
- this.helloOk = false;
533
- this._ackNegotiated = null;
534
- const current = () => this.ws === ws;
535
- ws.on("open", () => {
536
- if (!current()) return;
537
- this.armLiveness();
538
- log.info("doorbell socket open \u2014 waiting for hello.ok");
539
- });
540
- ws.on("message", (data) => {
541
- if (!current()) return;
542
- this.armLiveness();
543
- let frame;
544
- try {
545
- frame = JSON.parse(data.toString());
546
- } catch {
547
- return;
548
- }
549
- const record = asRecord(frame);
550
- if (record === null) return;
551
- const type = record["type"];
552
- if (type === "hello.ok") {
553
- this.onHelloOk(record);
554
- } else if (type === "message.new") {
555
- this.onMessageFrame(asRecord(record["payload"]));
556
- } else if (type === "group.invite.received") {
557
- this.onInviteFrame(asRecord(record["payload"]));
558
- } else {
559
- log.debug(`doorbell socket frame ${String(type)} \u2014 not a knock`);
560
- }
561
- });
562
- ws.on("ping", () => {
563
- if (current()) this.armLiveness();
564
- });
565
- ws.on("unexpected-response", (req, res) => {
566
- if (!current()) return;
567
- const status = res.statusCode ?? 0;
568
- try {
569
- res.resume();
570
- req.destroy();
571
- } catch {
572
- }
573
- this.ws = null;
574
- if (this.stopped) return;
575
- if (status === 401 || status === 403) {
576
- this.enterTerminal("auth", `auth rejected (HTTP ${status}) \u2014 check the agent's API key`);
577
- return;
578
- }
579
- log.warn(`doorbell socket unexpected response ${status} \u2014 scheduling reconnect`);
580
- this.scheduleReconnect();
581
- });
582
- ws.on("error", (err) => {
583
- if (!current()) return;
584
- log.warn(`doorbell socket error: ${String(err)}`);
585
- });
586
- ws.on("close", (code, reasonBuffer) => {
587
- if (!current()) return;
588
- this.ws = null;
589
- if (this._state === "terminal" || this.stopped) return;
590
- const reason = reasonBuffer.toString();
591
- if (!this.helloOk && AUTH_CLOSE_CODES.has(code)) {
592
- this.enterTerminal("auth", `auth rejected (close ${code}${reason ? ` ${reason}` : ""}) \u2014 check the agent's API key`);
593
- return;
594
- }
595
- log.warn(`doorbell socket closed (${code}${reason ? ` ${reason}` : ""}) \u2014 scheduling reconnect`);
596
- this.scheduleReconnect();
597
- });
598
- }
599
- /** The server accepted the credential and echoed the capability set. */
600
- onHelloOk(record) {
601
- const caps = Array.isArray(record["capabilities"]) ? record["capabilities"] : [];
602
- this._ackNegotiated = caps.includes("ack");
603
- const first = !this.helloOk;
604
- this.helloOk = true;
605
- this.attempt = 0;
606
- this.setState("ready");
607
- log.info(`doorbell socket hello.ok \u2014 ack capability ${this._ackNegotiated ? "negotiated" : "NOT echoed (legacy server)"}`);
608
- this.emit("ack", this._ackNegotiated);
609
- if (first) this.emit("ready");
610
- }
611
- /**
612
- * A `message.new` frame. Only the sender (echo filter) and the ids (log
613
- * line) are read. `content`, `metadata`, previews — never touched.
614
- */
615
- onMessageFrame(payload) {
616
- if (payload === null) {
617
- log.warn("doorbell socket: message.new without an object payload \u2014 dropped");
618
- return;
619
- }
620
- const senderRaw = stringField(payload, ["sender", "sender_handle", "from"]);
621
- const sender = senderRaw === null ? null : senderRaw.replace(/^@/, "").toLowerCase();
622
- const messageId = stringField(payload, ["id"]);
623
- const conversationId = stringField(payload, ["conversation_id"]);
624
- if (sender !== null && sender === this.selfHandle) {
625
- log.debug(`doorbell socket: own echo in ${conversationId ?? "?"} \u2014 not a knock`);
626
- this.emit("echo");
627
- return;
628
- }
629
- log.info(`knock \u2014 message.new conv=${conversationId ?? "?"} msg=${messageId ?? "?"} from=@${sender ?? "?"}`);
630
- this.emit("knock", { source: "message", sender, conversationId, messageId });
631
- }
632
- onInviteFrame(payload) {
633
- if (payload === null) {
634
- log.warn("doorbell socket: group.invite.received without an object payload \u2014 dropped");
635
- return;
636
- }
637
- const inviteId = stringField(payload, ["invite_id", "id"]);
638
- if (inviteId === null) {
639
- log.warn("doorbell socket: group invite without an invite id \u2014 dropped");
640
- return;
641
- }
642
- const invite = {
643
- inviteId,
644
- groupId: stringField(payload, ["group_id", "conversation_id"]),
645
- groupName: stringField(payload, ["group_name", "name"]),
646
- inviterHandle: stringField(payload, ["inviter_handle", "inviter", "from"])
647
- };
648
- log.info(`knock \u2014 group invite ${invite.inviteId} to ${invite.groupId ?? "?"} from=@${invite.inviterHandle ?? "?"}`);
649
- this.emit("invite", invite);
650
- }
651
- /** Give up. The socket stays stopped; the holder decides what happens next. */
652
- enterTerminal(reason, detail) {
653
- this.clearTimers();
654
- this.ws = null;
655
- this.setState("terminal");
656
- log.error(`doorbell socket terminal (${reason}): ${detail}`);
657
- this.emit("terminal", reason, detail);
658
- }
659
- scheduleReconnect() {
660
- if (this.stopped || this._state === "terminal") return;
661
- if (this.reconnectTimer) return;
662
- this.setState("reconnecting");
663
- this.clearTimers();
664
- const nextAttempt = this.attempt + 1;
665
- if (nextAttempt > RECONNECT_HARD_CAP_ATTEMPTS) {
666
- this.enterTerminal("cap", `reconnect hard cap (${RECONNECT_HARD_CAP_ATTEMPTS} attempts) reached \u2014 the control plane is unreachable from here`);
667
- return;
668
- }
669
- const backoff = Math.min(BASE_BACKOFF_MS * 2 ** Math.min(this.attempt, 20), MAX_BACKOFF_MS);
670
- const jitter = backoff * (0.5 + Math.random() * 0.5);
671
- this.attempt = nextAttempt;
672
- this.reconnectTimer = setTimeout(() => {
673
- this.reconnectTimer = null;
674
- this.open();
675
- }, jitter);
676
- }
677
- armLiveness() {
678
- if (this.livenessTimer) clearTimeout(this.livenessTimer);
679
- this.livenessTimer = setTimeout(() => {
680
- log.warn("doorbell socket liveness timeout \u2014 forcing reconnect");
681
- const ws = this.ws;
682
- this.ws = null;
683
- try {
684
- ws?.terminate();
685
- } catch {
686
- }
687
- this.scheduleReconnect();
688
- }, LIVENESS_MS);
689
- }
690
- clearTimers() {
691
- if (this.reconnectTimer) {
692
- clearTimeout(this.reconnectTimer);
693
- this.reconnectTimer = null;
694
- }
695
- if (this.livenessTimer) {
696
- clearTimeout(this.livenessTimer);
697
- this.livenessTimer = null;
698
- }
699
- }
700
- };
701
-
702
- // src/doorbell/doorbell.ts
775
+ // src/integration/integration.ts
703
776
  var HEARTBEAT_MS = 3e4;
704
777
  var STATUS_MS = 3e4;
705
- var Doorbell = class {
778
+ var HTTP_TIMEOUT_MS = 1e4;
779
+ var Integration = class {
706
780
  constructor(options) {
707
781
  this.options = options;
708
- const { cfg } = options;
709
- const wire = { apiKey: cfg.apiKey, apiBase: cfg.apiBase };
710
- this.invoker = new DoorbellInvoker({
782
+ 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 }
789
+ });
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({
711
793
  runner: options.runner,
712
- prompts: options.prompts,
794
+ prompts: () => this.runPrompts(),
713
795
  budgetMs: options.budgetMs,
714
796
  onChange: () => this.writeStatus(),
715
- trayHasWaiting: () => trayHasWaiting(wire)
797
+ trayHasWaiting: () => trayHasWaiting(this.api),
798
+ offeredInvites: OfferedInvites.load(cfg.home)
716
799
  });
717
- this.socket = options.socket ?? new DoorbellSocket({ url: cfg.wsUrl, apiKey: cfg.apiKey, selfHandle: cfg.handle });
718
- this.socket.on("knock", (knock) => this.invoker.knock(knock.source));
719
- this.socket.on("invite", (invite) => {
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) => {
720
803
  this.invoker.invite(invite);
721
804
  });
722
- this.socket.on("ready", () => {
805
+ this.connection.on("ready", () => {
723
806
  void this.catchUp();
724
807
  });
725
- this.socket.on("state", (state) => {
726
- if (state === "ready") beat(cfg.home);
727
- else idle(cfg.home);
808
+ this.connection.on("state", (state) => {
809
+ if (state === "ready") {
810
+ beat(cfg.home);
811
+ this.lastError = null;
812
+ } else {
813
+ idle(cfg.home);
814
+ }
728
815
  this.writeStatus();
729
816
  });
730
- this.socket.on("ack", () => this.writeStatus());
731
- this.socket.on("terminal", (reason, detail) => {
817
+ this.connection.on("blocked", (detail) => {
732
818
  this.lastError = detail;
733
- log.error(`doorbell terminal (${reason}): ${detail}`);
734
- this.stop();
735
- options.onTerminal?.(reason, detail);
819
+ this.writeStatus();
736
820
  });
737
821
  }
738
822
  options;
739
- socket;
823
+ api;
824
+ connection;
825
+ texts;
826
+ manual;
740
827
  invoker;
741
828
  heartbeatTimer = null;
742
829
  statusTimer = null;
@@ -748,11 +835,13 @@ var Doorbell = class {
748
835
  throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? "unknown"}`);
749
836
  }
750
837
  log.info(
751
- `doorbell up as @${this.options.cfg.handle} via ${this.options.runner.name}, profile ${this.options.profile}; holding the socket`
838
+ `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`
752
839
  );
753
- this.socket.start();
840
+ await this.texts.start();
841
+ if (this.stopping) return;
842
+ this.connection.start();
754
843
  this.heartbeatTimer = setInterval(() => {
755
- if (this.socket.connected) beat(this.options.cfg.home);
844
+ if (this.connection.connected) beat(this.options.cfg.home);
756
845
  }, HEARTBEAT_MS);
757
846
  this.heartbeatTimer.unref();
758
847
  this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS);
@@ -770,7 +859,9 @@ var Doorbell = class {
770
859
  if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
771
860
  if (this.statusTimer) clearInterval(this.statusTimer);
772
861
  this.invoker.stop();
773
- this.socket.stop();
862
+ this.texts.stop();
863
+ this.manual?.stop();
864
+ this.connection.stop();
774
865
  idle(this.options.cfg.home);
775
866
  this.writeStatus();
776
867
  }
@@ -800,18 +891,18 @@ var Doorbell = class {
800
891
  }
801
892
  snapshot() {
802
893
  const c = this.invoker.counters();
803
- const socket = this.socket.state === "terminal" ? "terminal" : this.stopping ? "closed" : this.socket.state;
894
+ const socket = this.stopping ? "closed" : this.connection.state;
895
+ const texts = this.texts.current();
804
896
  return {
805
- version: 1,
897
+ version: 2,
806
898
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
807
899
  pid: process.pid,
808
900
  runtime: this.options.runner.name,
809
901
  handle: this.options.cfg.handle,
810
902
  profile: this.options.profile,
811
903
  socket,
812
- ack_negotiated: this.socket.ackNegotiated,
813
- knocks: c.knocks,
814
- knocks_absorbed: c.absorbed,
904
+ wakes: c.wakes,
905
+ wakes_absorbed: c.absorbed,
815
906
  invites: c.invites,
816
907
  runs_started: c.runsStarted,
817
908
  runs_ok: c.runsOk,
@@ -822,41 +913,65 @@ var Doorbell = class {
822
913
  last_run: c.lastRun,
823
914
  retry_rung: c.retryRung,
824
915
  retry_due_at: c.retryDueAt === null ? null : new Date(c.retryDueAt).toISOString(),
825
- last_error: this.lastError
916
+ last_error: this.lastError,
917
+ texts: {
918
+ source: this.texts.source,
919
+ fetched_at: this.texts.fetchedAt,
920
+ version: texts?.version ?? null,
921
+ manual_version: texts?.manual.version ?? null
922
+ }
826
923
  };
827
924
  }
828
925
  /**
829
- * The connect-time catch-up: one knock (the invoker counts the tray before
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() {
931
+ 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
830
941
  * any run, so an empty tray costs a count, not a run) and the pending invites.
831
942
  */
832
943
  async catchUp() {
833
- const { cfg } = this.options;
834
- const wire = { apiKey: cfg.apiKey, apiBase: cfg.apiBase };
835
944
  if (this.stopping) return;
836
- log.info("knock \u2014 connect (a run starts only if the tray has something waiting)");
837
- this.invoker.knock("connect");
945
+ log.info("wake \u2014 connect (a run starts only if the tray has something unread)");
946
+ this.invoker.wake("connect");
838
947
  try {
839
- const invites = await listGroupInvites(wire);
948
+ const invites = await this.api.listGroupInvites();
840
949
  if (this.stopping) return;
841
950
  let surfaced = 0;
842
- for (const invite of invites) if (this.invoker.invite(invite)) surfaced += 1;
843
- if (surfaced > 0) log.info(`knock \u2014 ${surfaced} pending group invite(s) surfaced on connect`);
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`);
844
961
  } catch (err) {
845
962
  log.warn(`connect-time invite list failed (${err instanceof Error ? err.message : String(err)}) \u2014 live invite frames are unaffected`);
846
963
  }
847
964
  this.writeStatus();
848
965
  }
849
966
  writeStatus() {
850
- writeDoorbellStatus(this.options.cfg.home, this.snapshot());
967
+ writeIntegrationStatus(this.options.cfg.home, this.snapshot());
851
968
  }
852
969
  };
853
970
 
854
- // src/doorbell/run.ts
971
+ // src/integration/run.ts
855
972
  var POLL_MS = 5e3;
856
973
  var TICK_MS = 250;
857
- var MAX_BACKOFF_MS2 = 5 * 6e4;
858
- var SOCKET_GIVEUP_HOLD_BASE_MS = 6e4;
859
- var SOCKET_GIVEUP_HOLD_MAX_MS = 10 * 6e4;
974
+ var MAX_BACKOFF_MS = 5 * 6e4;
860
975
  var SHUTDOWN_GRACE_MS = 1e4;
861
976
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
862
977
  var KEEP_LOG_BYTES = 1024 * 1024;
@@ -866,7 +981,7 @@ function fingerprint(home) {
866
981
  return id === null ? null : `${id.apiKey}:${id.handle ?? ""}`;
867
982
  }
868
983
  function boundDaemonLog(home) {
869
- const file = path2.join(home, "daemon.log");
984
+ const file = path3.join(home, "daemon.log");
870
985
  try {
871
986
  const size = fs.statSync(file).size;
872
987
  if (size <= MAX_LOG_BYTES) return;
@@ -885,9 +1000,9 @@ ${keep.toString("utf-8")}`
885
1000
  } catch {
886
1001
  }
887
1002
  }
888
- async function runDoorbell(opts) {
889
- const home = path2.resolve(opts.home);
890
- const workdir = opts.workdir ?? path2.join(home, "daemon-workdir");
1003
+ async function runIntegration(opts) {
1004
+ const home = path3.resolve(opts.home);
1005
+ const workdir = path3.resolve(opts.workdir);
891
1006
  const env = opts.env ?? process.env;
892
1007
  const profile = opts.profile ?? resolveRunProfile(env);
893
1008
  const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env);
@@ -895,27 +1010,24 @@ async function runDoorbell(opts) {
895
1010
  if (process.env["AGENTCHAT_LOG_LEVEL"] === void 0) process.env["AGENTCHAT_LOG_LEVEL"] = "info";
896
1011
  const lock = acquireLeaderLock(home);
897
1012
  if (lock === null) return 1;
898
- const disabled = doorbellDisabled(env);
1013
+ const disabledBy = integrationDisabledBy(env);
1014
+ const disabled = disabledBy !== null;
899
1015
  let live = null;
900
1016
  let liveFingerprint = null;
901
1017
  let observedFingerprint = null;
902
- let refused = null;
903
1018
  let failures = 0;
904
- let socketGiveUps = 0;
905
- let holdUntil = 0;
906
1019
  let lastFailure = null;
907
1020
  let shuttingDown = false;
908
- const offStatus = (handle) => writeDoorbellStatus(home, {
909
- version: 1,
1021
+ const offStatus = (handle) => writeIntegrationStatus(home, {
1022
+ version: 2,
910
1023
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
911
1024
  pid: process.pid,
912
1025
  runtime: opts.runner.name,
913
1026
  handle,
914
1027
  profile,
915
1028
  socket: disabled ? "off" : "idle",
916
- ack_negotiated: null,
917
- knocks: 0,
918
- knocks_absorbed: 0,
1029
+ wakes: 0,
1030
+ wakes_absorbed: 0,
919
1031
  invites: 0,
920
1032
  runs_started: 0,
921
1033
  runs_ok: 0,
@@ -926,7 +1038,8 @@ async function runDoorbell(opts) {
926
1038
  last_run: null,
927
1039
  retry_rung: 0,
928
1040
  retry_due_at: null,
929
- last_error: lastFailure
1041
+ last_error: lastFailure,
1042
+ texts: null
930
1043
  });
931
1044
  const disconnect = (why) => {
932
1045
  if (live === null) return;
@@ -961,9 +1074,9 @@ async function runDoorbell(opts) {
961
1074
  watcher.unref();
962
1075
  } catch {
963
1076
  }
964
- log.info(`doorbell resident for ${home} (${credentialsPath(home)})`);
1077
+ log.info(`integration resident for ${home} (${credentialsPath(home)}) \u2014 ${opts.client.runtime} ${opts.client.version}`);
965
1078
  if (disabled) {
966
- log.info("AGENTCHAT_DOORBELL=off \u2014 holding no socket and starting no run; the hosted tools and the manual still work in every session");
1079
+ log.info(`${disabledBy}=off \u2014 holding no socket and starting no run; the hosted tools and the manual still work in every session`);
967
1080
  }
968
1081
  idle(home);
969
1082
  offStatus(null);
@@ -975,63 +1088,42 @@ async function runDoorbell(opts) {
975
1088
  disconnect(fp === null ? "signed out" : "identity changed");
976
1089
  observedFingerprint = fp;
977
1090
  failures = 0;
978
- socketGiveUps = 0;
979
- holdUntil = 0;
980
1091
  lastFailure = null;
981
- if (fp !== refused) refused = null;
982
1092
  if (fp === null || disabled) offStatus(fp === null ? null : resolveIdentity(home)?.handle ?? null);
983
1093
  }
984
1094
  if (fp === null) {
985
- if (refused !== null) refused = null;
986
1095
  } else if (disabled) {
987
1096
  } else if (fp !== liveFingerprint) {
988
- if (fp === refused) {
989
- } else if (Date.now() < holdUntil) {
990
- } else {
991
- try {
992
- const cfg = await resolveDaemonConfig({ home, workdir });
993
- const candidate = new Doorbell({
994
- cfg,
995
- runner: opts.runner,
996
- prompts: opts.prompts,
997
- profile,
998
- budgetMs,
999
- onTerminal: (reason, detail) => {
1000
- live = null;
1001
- liveFingerprint = null;
1002
- lastFailure = detail;
1003
- idle(home);
1004
- if (reason === "auth") {
1005
- log.warn(`credential refused (${detail}) \u2014 idling until it changes`);
1006
- refused = fp;
1007
- return;
1008
- }
1009
- socketGiveUps += 1;
1010
- const hold = Math.min(SOCKET_GIVEUP_HOLD_BASE_MS * 2 ** (socketGiveUps - 1), SOCKET_GIVEUP_HOLD_MAX_MS);
1011
- holdUntil = Date.now() + hold;
1012
- log.warn(`socket gave up (${detail}) \u2014 opening a fresh socket in ${Math.round(hold / 1e3)}s`);
1013
- }
1014
- });
1015
- await candidate.start();
1016
- live = candidate;
1017
- liveFingerprint = fp;
1018
- failures = 0;
1019
- lastFailure = null;
1020
- } catch (err) {
1021
- const msg = String(err instanceof Error ? err.message : err);
1022
- if (msg !== lastFailure) {
1023
- log.warn(`not connecting yet: ${msg}`);
1024
- lastFailure = msg;
1025
- offStatus(resolveIdentity(home)?.handle ?? null);
1026
- }
1027
- failures += 1;
1028
- live = null;
1029
- liveFingerprint = null;
1030
- idle(home);
1097
+ try {
1098
+ const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client });
1099
+ const candidate = new Integration({
1100
+ cfg,
1101
+ runner: opts.runner,
1102
+ client: opts.client,
1103
+ manualPointer: opts.manualPointer,
1104
+ ...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
1105
+ profile,
1106
+ budgetMs
1107
+ });
1108
+ await candidate.start();
1109
+ live = candidate;
1110
+ liveFingerprint = fp;
1111
+ failures = 0;
1112
+ lastFailure = null;
1113
+ } catch (err) {
1114
+ const msg = String(err instanceof Error ? err.message : err);
1115
+ if (msg !== lastFailure) {
1116
+ log.warn(`not connecting yet: ${msg}`);
1117
+ lastFailure = msg;
1118
+ offStatus(resolveIdentity(home)?.handle ?? null);
1031
1119
  }
1120
+ failures += 1;
1121
+ live = null;
1122
+ liveFingerprint = null;
1123
+ idle(home);
1032
1124
  }
1033
1125
  }
1034
- const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS2);
1126
+ const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS);
1035
1127
  nudged = false;
1036
1128
  const deadline = Date.now() + waitMs;
1037
1129
  while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {
@@ -1054,7 +1146,7 @@ async function runDoorbell(opts) {
1054
1146
  return 0;
1055
1147
  }
1056
1148
 
1057
- // src/doorbell/spawn-run.ts
1149
+ // src/integration/spawn-run.ts
1058
1150
  var DEFAULT_GRACE_MS = 5e3;
1059
1151
  var STDERR_TAIL_CHARS = 400;
1060
1152
  function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
@@ -1114,6 +1206,15 @@ function spawnRun(spec) {
1114
1206
  finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
1115
1207
  return;
1116
1208
  }
1209
+ if (spec.onStarted) {
1210
+ const onStarted = spec.onStarted;
1211
+ child.once("spawn", () => {
1212
+ try {
1213
+ onStarted();
1214
+ } catch {
1215
+ }
1216
+ });
1217
+ }
1117
1218
  child.stdout?.on("data", (chunk) => {
1118
1219
  stdoutBytes += chunk.length;
1119
1220
  });
@@ -1163,7 +1264,7 @@ function spawnRun(spec) {
1163
1264
  finish({
1164
1265
  state: "failed",
1165
1266
  exitCode: code,
1166
- detail: `interrupted \u2014 the doorbell was stopping; the tray stays stored for the next run${tail ? `: ${tail}` : ""}`
1267
+ detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${tail ? `: ${tail}` : ""}`
1167
1268
  });
1168
1269
  return;
1169
1270
  }
@@ -1181,17 +1282,22 @@ function spawnRun(spec) {
1181
1282
  });
1182
1283
  }
1183
1284
  export {
1184
- DEFAULT_KNOCK_DEBOUNCE_MS,
1185
- Doorbell,
1186
- DoorbellInvoker,
1187
- DoorbellSocket,
1188
- KnockCoalescer,
1285
+ DEFAULT_WAKE_DEBOUNCE_MS,
1286
+ Integration,
1287
+ IntegrationConnection,
1288
+ IntegrationInvoker,
1289
+ OFFERED_INVITES_FILE,
1290
+ OfferedInvites,
1189
1291
  PREFLIGHT_WATCH_MS,
1190
1292
  RETRY_LADDER_MS,
1293
+ WakeCoalescer,
1294
+ offeredInvitesPath,
1191
1295
  redactDiagnostic,
1192
1296
  resolveDaemonConfig,
1193
- runDoorbell,
1297
+ runIntegration,
1298
+ socketStateOf,
1194
1299
  spawnRun,
1300
+ wsBaseFor,
1195
1301
  wsUrlFor
1196
1302
  };
1197
1303
  //# sourceMappingURL=daemon-entry.js.map