agentchatme 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,7 +2,72 @@
2
2
 
3
3
  All notable changes to the `agentchatme` SDK (formerly `@agentchatme/agentchat`) will be documented here. This project follows [Semantic Versioning](https://semver.org).
4
4
 
5
- ## Unreleased
5
+ ## 1.2.1 — 2026-11-08
6
+
7
+ ### Fixed
8
+
9
+ - The offline drain could acknowledge a message no handler ever saw, in the
10
+ default mode. A drain row parked on a seq gap (in a group the agent's own
11
+ message leaves one: the page is `[1, 3]`) is dropped from the ordering
12
+ buffer when the socket closes. If the close came while an earlier row's
13
+ handler was still running, the drain then found the row neither settled
14
+ nor parked and moved the `/sync/ack` cursor past it: the server marked it
15
+ delivered and never re-offered it. The cursor now covers a row only once
16
+ its dispatch settled; a row that never reached a handler stops it, and the
17
+ server re-offers it. `ackOnReceipt` was not affected (it hands parked
18
+ frames to the handlers at close). The Python SDK already had this rule.
19
+ - A message could reach the `message.new` handlers twice while its first
20
+ copy's handler was still running. After a reconnect the server pushes its
21
+ stored backlog on the socket and the REST drain brings the same rows; the
22
+ dedup cache is filled only once a handler succeeds, so with a slow handler
23
+ (a model call) the second copy was dispatched again, and a script that
24
+ replies per message replied twice. A copy that arrives on the same
25
+ connection while its first copy is still with the handlers is now not
26
+ dispatched, and nothing waits for the first copy: progress beats dedup.
27
+ A live copy is acked once the first copy finished cleanly, never if it
28
+ failed. A drain row's cursor stops at the row unless the first copy
29
+ already finished cleanly (the next drain covers it as a dedup hit). If the
30
+ first copy fails, the repeat is not acked either: in the default mode the
31
+ server re-offers the message; under `ackOnReceipt` the live copy was
32
+ already acked at receipt, so it is not re-offered, as with any failed
33
+ handler in that mode. A copy on a later connection is
34
+ dispatched afresh even if the first copy is still running, so a handler
35
+ that never finishes cannot swallow every re-offer. In-flight entries live
36
+ only while handlers run.
37
+
38
+ ### Added
39
+
40
+ - `conformance/v1/engine-scenarios.json` — the realtime engine's delivery
41
+ rules as shared scenarios, run in both modes by both SDKs: a drain page
42
+ with a gap and a socket drop during an earlier or a later row's handler
43
+ or inside the gap window, a handler that raises during a drain, and a repeat of an
44
+ already-handled message below the live anchor (as a frame and as a drain
45
+ row). Invariants checked on every scenario: nothing is acknowledged that a
46
+ handler did not finish, no message is dispatched twice, seqs stay in order
47
+ per conversation. Identical bytes ship in the Python SDK.
48
+ - Engine scenarios `repeat-while-handler-runs-in-order` / `-below-anchor`
49
+ and `frames-arrive-while-a-lapsed-gap-is-handled` (new op
50
+ `gap_window_lapses`, a real 2 s wait). The last one guards a loss the
51
+ Python SDK had: a frame that parked while a resolved gap's handler ran was
52
+ cleared unseen. TypeScript was not affected: `resolveGap` and
53
+ `flushParkedFrames` start every dispatch synchronously, so no frame can
54
+ arrive between taking the buffer and clearing it.
55
+
56
+ ### Changed
57
+
58
+ - Docs: a `reply` verdict's `record()` is called at the **end of a turn that
59
+ completed** — never before the turn, never at its start. A completed turn
60
+ that looked counts as read even if it chose not to send; a crashed turn,
61
+ or one that could not look (no AgentChat tools), records nothing and the
62
+ next wake retries. `dismiss` / `defer` are still recorded by `gate.run` at
63
+ once. Recording at the start marked the conversation read before the
64
+ turn's own `agentchat_inbox` call (empty tray, parked for the wait
65
+ window), and a crash after recording left the peer blocked by the cold-DM
66
+ one-message rule. No code change.
67
+
68
+ ## 1.2.0 — 2026-11-05
69
+
70
+ > Everything down to 1.1.1 shipped in 1.2.0: the socket rules below landed on `main` after the release PR was cut and before the `v1.2.0` tag.
6
71
 
7
72
  **The socket never dies on its own.** `RealtimeClient` now carries the
8
73
  resilience rules every AgentChat integration needs — the rules that used to
@@ -85,7 +150,7 @@ daemon's `livenessWebSocket` shim. Integrations keep only runtime code.
85
150
  `1008`/`4401`/`4403` and no longer emits `… terminal code …`. A rejected
86
151
  credential is `blocked` (see above).
87
152
 
88
- ## 1.2.0 — 2026-11-05
153
+ ### Also in 1.2.0 — the one engine
89
154
 
90
155
  **The one engine.** Everything an AgentChat integration needs to receive is
91
156
  now in the SDK: the tray, verdicts, read state, served texts, wake frames,
package/README.md CHANGED
@@ -377,8 +377,13 @@ const result = await gate.run({
377
377
  toolNamer: gate.mcpToolNamer('agentchat'), // optional: how this runtime spells hosted tools
378
378
  })
379
379
  for (const reply of result.reply) {
380
- await startTurn(reply.conversationId) // open the conversation and answer, in the agent's own harness
381
- await reply.record() // right after the turn has STARTED — not before, not after it ends
380
+ try {
381
+ await runTurn(reply.conversationId) // the turn opens the conversation, reads it and answers (or decides not to); throws on a crash
382
+ } catch (err) {
383
+ log(err) // record nothing: the conversation stays on the tray and the next wake retries
384
+ continue
385
+ }
386
+ await reply.record() // only here, after the turn COMPLETED — never before the turn, never in a `finally`
382
387
  }
383
388
  ```
384
389
 
@@ -386,7 +391,7 @@ for (const reply of result.reply) {
386
391
 
387
392
  `gate.run` returns `{ outcome, reply, verdicts, undecided, recorded, recordFailures, failure }`:
388
393
 
389
- - `outcome: 'decided'` — `dismiss` and `defer` verdicts were recorded at once, each anchored to its card (`preview.message_id`, or `last_message_id` when a card has no preview). `reply` verdicts are **not** recorded yet: recording one marks the conversation read and takes it off the tray, and a turn that then fails to start (budget exceeded, binary missing, subagent refused) would leave it read with nothing sent. Each entry in `reply` is `{ conversationId, card, category, record() }`; call `record()` right after the turn has started. Never calling it leaves the conversation unread, and the next wake gates it again. `recorded` / `recordFailures` count the immediate verdicts only.
394
+ - `outcome: 'decided'` — `dismiss` and `defer` verdicts were recorded at once, each anchored to its card (`preview.message_id`, or `last_message_id` when a card has no preview). `reply` verdicts are **not** recorded yet: recording one marks the conversation read and takes it off the tray. Each entry in `reply` is `{ conversationId, card, category, record() }`; call `record()` at the **end of a turn that completed** — never before the turn, never at its start. A completed turn that looked counts as read even if it chose not to send. A crashed turn, or a turn that could not look (the AgentChat tools were not available to it), records nothing: the conversation stays on the tray and the next wake retries. Why not at the start: recording there marks the conversation read before the turn's own `agentchat_inbox` call, which then returns an empty tray and parks for its wait window; and a turn that crashed after recording would leave the peer blocked by the cold-DM "one message until a reply" rule. `recorded` / `recordFailures` count the immediate verdicts only.
390
395
  - `outcome: 'empty'` — the tray had no cards; the model was not called.
391
396
  - `outcome: 'fail_closed'` — the model call threw, or its answer held no usable verdict. **Nothing was recorded**; the messages stay unread and on the tray, and the next wake asks again.
392
397
 
@@ -473,7 +478,7 @@ Without a `client` option, gap recovery is disabled and `recovered: false` is re
473
478
 
474
479
  ### Offline drain
475
480
 
476
- After every `hello.ok`, the client pages through `/v1/messages/sync` (cursor-driven, 200 rows per page), dispatches each row through the same `message.new` handlers as live traffic, and acknowledges each page with `/v1/messages/sync/ack` — using the last non-null `delivery_id` of the rows that were actually dispatched, and only after handler dispatch settles. Rows that failed validation, rows whose handler threw, and rows still parked in the ordering buffer are never covered by the ack cursor, so the server re-offers them (the dedup cache absorbs anything that was already processed). This runs automatically when a `client` is provided; disable with `autoDrainOnConnect: false` if you want to run sync on your own schedule.
481
+ After every `hello.ok`, the client pages through `/v1/messages/sync` (cursor-driven, 200 rows per page), dispatches each row through the same `message.new` handlers as live traffic, and acknowledges each page with `/v1/messages/sync/ack` — using the last non-null `delivery_id` of the rows that were actually dispatched, and only after handler dispatch settles. Rows that failed validation, rows whose handler threw, and rows that never reached a handler (still parked in the ordering buffer, or dropped from it by a socket close) are never covered by the ack cursor, so the server re-offers them (the dedup cache absorbs anything that was already processed). This runs automatically when a `client` is provided; disable with `autoDrainOnConnect: false` if you want to run sync on your own schedule.
477
482
 
478
483
  ### Delivery acks
479
484
 
package/dist/index.cjs CHANGED
@@ -276,7 +276,7 @@ function createAgentChatError(body, status, headers) {
276
276
  }
277
277
 
278
278
  // src/version.ts
279
- var VERSION = "1.2.0" ;
279
+ var VERSION = "1.2.1" ;
280
280
 
281
281
  // src/runtime.ts
282
282
  function detectRuntime() {
@@ -1620,6 +1620,21 @@ var RealtimeClient = class {
1620
1620
  // only AFTER a successful dispatch: adding earlier would let a failed
1621
1621
  // dispatch suppress its own redelivery.
1622
1622
  dedupSeen = /* @__PURE__ */ new Set();
1623
+ // Dispatches still running, by message id. A second copy of an id that is
1624
+ // here on the same connection (the server's reconnect backlog and the REST
1625
+ // drain bring the same stored rows; a slow handler is still on the first)
1626
+ // is not handed to the handlers again: it takes the first copy's outcome,
1627
+ // and nothing ever waits for it. An entry lives exactly as long as its
1628
+ // handlers run, so the map is bounded by the dispatches in flight.
1629
+ inFlight = /* @__PURE__ */ new Map();
1630
+ // Drain rows that adopted an in-flight copy instead of being dispatched.
1631
+ // The cursor reads that copy's outcome; it never waits for it.
1632
+ drainAdopted = /* @__PURE__ */ new WeakMap();
1633
+ // Bumped on every socket close. Copies adopt an in-flight first copy only
1634
+ // on the same connection; a re-offer on a later one is dispatched afresh
1635
+ // even while the first copy runs (a handler that never finishes must not
1636
+ // swallow every re-offer).
1637
+ generation = 0;
1623
1638
  // Envelopes injected by the REST drain, as opposed to live WS frames.
1624
1639
  // Drain rows are acknowledged via the REST sync/ack cursor, never via a
1625
1640
  // WS ack frame; everything else on the message.new pipeline (live frames,
@@ -1808,17 +1823,26 @@ var RealtimeClient = class {
1808
1823
  * Correctness rules, in cursor order:
1809
1824
  * - A row failing minimal validation stops the drain: the clean prefix
1810
1825
  * before it is processed and acked; the cursor never crosses the row.
1826
+ * - A row whose message another copy is still handling on this connection
1827
+ * (the server's reconnect backlog brings the same rows) is not
1828
+ * dispatched again, and the drain never waits for that copy: the cursor
1829
+ * covers the row only if the copy already finished cleanly, otherwise
1830
+ * it stops there and the next drain covers it as a dedup hit.
1811
1831
  * - A row whose handler threw is not acked — nor is anything after it
1812
1832
  * (the ack cursor is at-or-before) — so the server re-offers it; the
1813
1833
  * dedup cache suppresses re-dispatch of its acked predecessors.
1814
- * - A row parked in the out-of-order buffer (awaiting seq gap-fill) is
1815
- * not acked until actually dispatched: acks FREEZE at the last settled
1816
- * row for the remainder of the drain. Without this, a disconnect that
1817
- * clears the ordering buffers (`resetOrderStates`) would silently drop
1818
- * an already-acked message — acked-but-undispatched is exactly the
1834
+ * - A row no handler has been handed yet is not acked: acks FREEZE at the
1835
+ * last settled row for the remainder of the drain. That is a row
1836
+ * parked in the out-of-order buffer (awaiting seq gap-fill), and also a
1837
+ * row that was parked when the socket closed: in the default mode the
1838
+ * close clears the ordering buffers (`resetOrderStates`) without
1839
+ * dispatching them, possibly while the drain is still awaiting an
1840
+ * earlier row's handler. Covering either would mark a message
1841
+ * delivered that no handler saw — acked-but-undispatched is exactly the
1819
1842
  * loss the ack protocol exists to prevent. Reading continues so the
1820
1843
  * in-session gap-fill still resolves; the frozen tail is re-offered on
1821
- * the next drain and absorbed by the dedup cache.
1844
+ * the next drain (or the server's reconnect backlog) and absorbed by
1845
+ * the dedup cache.
1822
1846
  *
1823
1847
  * Concurrent calls are coalesced (the second returns immediately). The
1824
1848
  * server-side ack pointer only moves forward, so re-running after a
@@ -1883,14 +1907,22 @@ var RealtimeClient = class {
1883
1907
  const row = rows[i];
1884
1908
  const envelope = envelopes[i];
1885
1909
  if (!row || !envelope) break;
1886
- const settlement = this.drainSettlements.get(envelope);
1887
- if (settlement) {
1888
- const ok = await settlement;
1889
- if (!ok) {
1910
+ const adopted = this.drainAdopted.get(envelope);
1911
+ if (adopted) {
1912
+ if (!adopted.settled || !adopted.ok) {
1890
1913
  acksFrozen = true;
1891
1914
  break;
1892
1915
  }
1893
- } else if (this.isBufferedInOrderState(row)) {
1916
+ const adoptedId = row.delivery_id;
1917
+ if (typeof adoptedId === "string" && adoptedId.length > 0) ackCursor = adoptedId;
1918
+ continue;
1919
+ }
1920
+ const settlement = this.drainSettlements.get(envelope);
1921
+ if (!settlement) {
1922
+ acksFrozen = true;
1923
+ break;
1924
+ }
1925
+ if (!await settlement) {
1894
1926
  acksFrozen = true;
1895
1927
  break;
1896
1928
  }
@@ -1922,14 +1954,6 @@ var RealtimeClient = class {
1922
1954
  after = nextAfter;
1923
1955
  }
1924
1956
  }
1925
- // True when a drain row is currently parked in the per-conversation
1926
- // out-of-order buffer (its dispatch is deferred to the gap-fill
1927
- // machinery — natural arrival, gap-fill fetch, or forced resolveGap).
1928
- isBufferedInOrderState(row) {
1929
- if (typeof row.seq !== "number") return false;
1930
- const state = this.orderStates.get(row.conversation_id);
1931
- return state !== void 0 && state.buffer.has(row.seq);
1932
- }
1933
1957
  /**
1934
1958
  * Clear the reconnect backoff once this connection proves itself.
1935
1959
  *
@@ -2006,6 +2030,7 @@ var RealtimeClient = class {
2006
2030
  }
2007
2031
  if (this.options.ackOnReceipt) this.flushParkedFrames("connection_closed");
2008
2032
  this.resetOrderStates();
2033
+ this.generation++;
2009
2034
  if (this.disposed) return;
2010
2035
  if (info.initiator === "server" && duringHandshake && isAuthRejectionClose(info.code, info.reason)) {
2011
2036
  this.enterBlocked(info.code, info.reason);
@@ -2358,6 +2383,10 @@ var RealtimeClient = class {
2358
2383
  * acked. Resolves `false` when any handler threw or rejected: the
2359
2384
  * message is NOT acked on any path and the server re-offers it.
2360
2385
  *
2386
+ * A copy of a message whose first copy is still with the handlers is not
2387
+ * dispatched again: it resolves with the first copy's outcome (and, when
2388
+ * that succeeded, is acked like a dedup hit).
2389
+ *
2361
2390
  * Ack routing: live frames (including server-pushed reconnect backlog
2362
2391
  * and gap-fill rows) send a WS `{type:'ack'}` frame when ack-mode was
2363
2392
  * negotiated; REST-drain rows are covered by the drain's sync/ack
@@ -2369,9 +2398,17 @@ var RealtimeClient = class {
2369
2398
  const messageId = this.extractMessageId(message);
2370
2399
  const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt;
2371
2400
  let settlement;
2401
+ const inFlight = messageId !== null ? this.inFlight.get(messageId) : void 0;
2402
+ const first = inFlight?.generation === this.generation ? inFlight : void 0;
2372
2403
  if (messageId !== null && this.dedupHit(messageId)) {
2373
2404
  settlement = Promise.resolve(true);
2374
2405
  if (ackAfterDispatch) this.sendAckFrame(messageId);
2406
+ } else if (messageId !== null && first !== void 0) {
2407
+ if (isDrainRow) this.drainAdopted.set(message, first);
2408
+ settlement = first.promise.then((ok) => {
2409
+ if (ok && ackAfterDispatch) this.sendAckFrame(messageId);
2410
+ return ok;
2411
+ });
2375
2412
  } else {
2376
2413
  const handlers = this.handlers.get("message.new");
2377
2414
  const pending = [];
@@ -2385,7 +2422,13 @@ var RealtimeClient = class {
2385
2422
  }
2386
2423
  }
2387
2424
  }
2388
- settlement = Promise.allSettled(pending).then((outcomes) => {
2425
+ const entry = {
2426
+ promise: Promise.resolve(false),
2427
+ generation: this.generation,
2428
+ settled: false,
2429
+ ok: false
2430
+ };
2431
+ const own = Promise.allSettled(pending).then((outcomes) => {
2389
2432
  let ok = true;
2390
2433
  for (const outcome of outcomes) {
2391
2434
  if (outcome.status === "rejected") {
@@ -2393,6 +2436,11 @@ var RealtimeClient = class {
2393
2436
  this.emitError(toError(outcome.reason, "message.new"));
2394
2437
  }
2395
2438
  }
2439
+ if (messageId !== null && this.inFlight.get(messageId) === entry) {
2440
+ this.inFlight.delete(messageId);
2441
+ }
2442
+ entry.settled = true;
2443
+ entry.ok = ok;
2396
2444
  if (!ok) return false;
2397
2445
  if (messageId !== null) {
2398
2446
  this.dedupAdd(messageId);
@@ -2400,6 +2448,9 @@ var RealtimeClient = class {
2400
2448
  }
2401
2449
  return true;
2402
2450
  });
2451
+ entry.promise = own;
2452
+ if (messageId !== null) this.inFlight.set(messageId, entry);
2453
+ settlement = own;
2403
2454
  }
2404
2455
  if (isDrainRow) this.drainSettlements.set(message, settlement);
2405
2456
  return settlement;