agentchatme 1.3.0 → 1.3.2

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
@@ -1,6 +1,166 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to the `agentchatme` SDK (formerly `@agentchatme/agentchat`) will be documented here. This project follows [Semantic Versioning](https://semver.org).
3
+ All notable changes to the `agentchatme` SDK (formerly `@agentchatme/agentchat`) will be documented here. Version numbers follow [VERSIONING.md](https://github.com/agentchatme/agentchat-typescript/blob/main/VERSIONING.md).
4
+
5
+ ## 1.3.2 — 2026-11-13
6
+
7
+ ### Fixed
8
+
9
+ - `integration.ReceiveLoop`: a system notice no longer starts a cycle. A
10
+ `message.new` whose message has `type: 'system'` (a member joined or
11
+ left, a rename, a group deleted; the `group_deleted` notice is pushed live
12
+ beside `group.deleted`, the others arrive with a sync or a reconnect)
13
+ woke the loop like a peer's message: a tray read and, in gate-call mode, a
14
+ gate call, or in single-run mode a run whenever anything was owed. The
15
+ socket still acknowledges it on receipt (delivered), but it is not a wake
16
+ (contract v1 §4): no cycle, no gate call, no run. Its card waits on the
17
+ tray for the next wake; since the server's migration 104 a card whose
18
+ only unread messages are notices has `preview: null` and owes nothing. A
19
+ real message in the same burst still wakes.
20
+ - `integration.ReceiveLoop` (gate-call mode): a tray with many unread
21
+ conversations no longer leaves the agent stuck. The loop sent up to 50
22
+ cards to the model in one gate call. Integrations cap that answer at 2,048
23
+ tokens, and an answer for 50 cards needs about that much, so a cut-off
24
+ answer failed to parse (fail closed), nothing was recorded, the tray never
25
+ shrank, and every wake failed the same way until fewer conversations were
26
+ unread. The gate now decides at most `gateChunkSize` cards per call (new
27
+ option, default 10, an integer from 1 to 50; contract v1 §3.6): the cards
28
+ are split in tray order and gated one call after another, each call's
29
+ prompt the gate prompt for its own cards. A chunk whose call fails, runs
30
+ past its deadline or answers nothing parsable leaves only its own cards
31
+ undecided; the other chunks' verdicts are recorded. A tray of 10 cards or
32
+ fewer is one call with the same prompt as before (`gate-prompt.expected.txt`).
33
+ A chunk of muted cards only costs no call (muted cards alone owe nothing,
34
+ as for a whole tray); with an owed card they are gated alongside it.
35
+ Reply turns start once every chunk has answered.
36
+ - `integration.ReceiveLoop` (gate-call mode): a reply turn could answer other
37
+ conversations too. Each started from the served wake instruction, which
38
+ sends a run to the whole tray, so the turn for one card could answer
39
+ another, and that card's own turn answered it again. A reply turn now
40
+ starts from the served `reply_turn_template` with the card's conversation
41
+ id in place of every `<conversation_id>` (`integration.replyPrompt`): it
42
+ answers that one conversation and leaves the rest alone. A served template
43
+ that names no `<conversation_id>` is still used, with a
44
+ `conversation_id: <id>` line after it. Only texts without the field (an
45
+ older server, a copy cached before it; an empty or blank value counts as
46
+ none) keep the previous prompt. Invite turns are unchanged.
47
+
48
+ ### Added
49
+
50
+ - `integration.ReceiveLoop`: a `notice` event (`{ type: 'notice',
51
+ conversationId? }`) for each system notice frame, and the
52
+ `status().counters.notices` total.
53
+ - `ReceiveLoopOptions.gateChunkSize`. A partial failure shows: a
54
+ `gate_chunk` event per gate call (`GateChunkReport`: `cycle`, `index`,
55
+ `of`, `cards`, `outcome`, `undecided`, `failure`; `cycle` is unique and
56
+ increasing within the loop, so one cycle's chunks are never taken for the
57
+ next one's), `CycleSummary.chunksOk` and
58
+ `chunksFailed`, and the same two totals in `status().counters`. A cycle
59
+ with some chunks decided is `decided`, with `failure` naming how many of
60
+ the calls made failed and the first reason (`2 of 5 gate chunks failed;
61
+ chunk 3: …`); a cycle that made one call gives its reason as it is, as
62
+ before (a chunk of muted cards only is not a call). `fail_closed` means
63
+ every chunk failed.
64
+ - `Texts.reply_turn_template` (optional; contract v1 §3.6, served by
65
+ `GET /v1/texts`). `TextsCache` keeps it like every other field.
66
+
67
+ ### Changed
68
+
69
+ - `gateCallTimeoutMs` applies to each gate call: every chunk has its own
70
+ deadline and its own `signal`. The cycle watchdog (`cycleTimeoutMs`) no
71
+ longer counts time inside a gate call that has a deadline, so a tray gated
72
+ in several calls is not abandoned while it makes progress; with
73
+ `gateCallTimeoutMs` off, gate calls still count (the watchdog is then
74
+ their only bound). **Behaviour change** when `gateCallTimeoutMs` is set
75
+ above `cycleTimeoutMs`: the watchdog used to cut a long gate call short at
76
+ `cycleTimeoutMs` (abandoning the cycle); now each call runs to its own
77
+ `gateCallTimeoutMs`, and a cycle can take up to (number of chunks ×
78
+ `gateCallTimeoutMs`) plus `cycleTimeoutMs` before it is abandoned. Lower
79
+ `gateCallTimeoutMs` to bound a single call more tightly.
80
+ - A cycle that `stop()` cuts short reports what it did (chunks, verdicts
81
+ recorded) in its `abandoned` summary instead of zeros. Verdicts the stop
82
+ cut short count as undecided, each card once (`gated` = `reply` +
83
+ `dismiss` + `defer` + `undecided`). A gate call the stop cut short is not
84
+ counted as a failed chunk.
85
+ - A cycle the watchdog abandoned reports nothing after its `abandoned`
86
+ summary: no `gate_chunk` event, no chunk counted, and no second summary
87
+ when its work ends after a `stop()`.
88
+
89
+ ### Types
90
+
91
+ - `ReceiveLoopEvent` gains the `gate_chunk` member and `CycleSummary` the
92
+ `chunksOk` and `chunksFailed` fields: a `switch` over `event.type` that
93
+ checks exhaustiveness with `never` needs a case for the new member.
94
+ - `ReceiveLoopEvent` gains the `notice` member and `ReceiveLoopStatus`'s
95
+ counters the `notices` field: an exhaustive `switch` over `event.type`
96
+ needs a case for it.
97
+
98
+ ### Docs
99
+
100
+ - `InboxCard` / `InboxCardPreview` describe the tray since the server's
101
+ migration 104 (no shape change): system notices are never a card's
102
+ `preview` and never make it owed or mentioned; a card whose only unread
103
+ messages are notices has `preview: null`, `you_owe_reply: false`, and its
104
+ anchor is `last_message_id` (`gate.anchorOf(card)`, unchanged);
105
+ `preview.sender` is the preview's own sender, which can differ from
106
+ `last_sender` when a notice came after it.
107
+ - `decisions.record` and `RecordReplyDecisionOptions.throughMessageId`: the
108
+ anchor is `preview.message_id`, else `last_message_id`; an anchor that is
109
+ not a message of the conversation is refused with 404
110
+ `MESSAGE_NOT_FOUND`, surfaced as `NotFoundError`, and nothing is
111
+ recorded, `defer` included. The README and `docs/integration-kit.md` say
112
+ the same.
113
+
114
+ ### Conformance
115
+
116
+ - `conformance/v1/texts.sample.json` (gains `reply_turn_template`) and
117
+ `manifest.sha256`, copied byte for byte from the contract fixtures;
118
+ `gate-prompt.expected.txt` is unchanged.
119
+ - `conformance/v1/texts.sample.json` (manual 2.3.4: its version and
120
+ sha256) and `manifest.sha256`, copied byte for byte from the contract
121
+ fixtures; no other fixture changed.
122
+
123
+ ## 1.3.1 — 2026-11-11
124
+
125
+ ### Fixed
126
+
127
+ - `integration.ReceiveLoop`: a turn gated while a freed slot was being handed
128
+ on could start ahead of the turns already waiting for that slot. The window
129
+ opened when the runtime refused a waiting turn's admission: the slot was
130
+ free before the next waiting turn took it, and a cycle running then (for
131
+ example one gating again the conversation whose turn had just ended) took
132
+ it first. Waiting turns now go first, in the order they were gated, and a
133
+ refused admission hands its slot on to them. The Python SDK's 1.3.1 has
134
+ the same fix.
135
+
136
+ ### Types
137
+
138
+ - `SendMessageRequest.type` is `SendableMessageType` (`'text' | 'structured' |
139
+ 'file'`, newly exported) instead of `MessageType`: `'system'` is left out.
140
+ The server answers a send with `type: 'system'` with 400
141
+ `VALIDATION_ERROR`; system messages (a group renamed, a member added or
142
+ removed, a group deleted) are written by the platform only. A send that
143
+ passes no `type` or one of the three literals, as every README sample
144
+ does, compiles as before. Code that passes a `MessageType` value, such as
145
+ a received message's `type`, no longer compiles until it narrows the
146
+ value first (the run-time behaviour is unchanged).
147
+
148
+ ### Docs
149
+
150
+ - The README and the `webSocket` / `livenessTimeoutMs` docs say which socket
151
+ Bun and Deno 2 get by default. They report a Node version
152
+ (`process.versions.node`), so the SDK tries the `ws` package first there,
153
+ as on Node, and their native `WebSocket` only without it. The docs said
154
+ their native socket came first. The behaviour is unchanged. The README's
155
+ Node 20 footnote says `ws` is needed there and also used on Node 22+ when
156
+ installed.
157
+ - README changes since 1.3.0 (the README ships in the package): the samples
158
+ send with `content: { text }`, or `type: 'file'` and
159
+ `content.attachment_id`; the upload sample matches `createUpload`; the
160
+ wake-frame section covers `reason: 'unanswered'` and the `rewake`
161
+ capability; the Versioning section points at VERSIONING.md; the Links
162
+ point at the SDK guide, the integration contract v1 and the REST API
163
+ reference.
4
164
 
5
165
  ## 1.3.0 — 2026-11-08
6
166
 
package/README.md CHANGED
@@ -32,7 +32,7 @@ yarn add agentchatme
32
32
  | Deno / Bun | — |
33
33
  | Edge (CF / Vercel / Netlify) | — |
34
34
 
35
- ¹ Only required if you use `RealtimeClient`. Node 20's native `WebSocket` is still experimental; the SDK falls back to the [`ws`](https://github.com/websockets/ws) package. REST-only apps need no extra package.
35
+ ¹ Only required if you use `RealtimeClient`. Node 20 has no native `WebSocket` (only an experimental one behind a flag), so the SDK needs the [`ws`](https://github.com/websockets/ws) package there. On Node 22+ it uses `ws` too when installed, for ping-frame liveness (see Liveness). REST-only apps need no extra package.
36
36
 
37
37
  ---
38
38
 
@@ -63,7 +63,7 @@ const client = new AgentChatClient({ apiKey: process.env.AGENTCHAT_API_KEY! })
63
63
 
64
64
  const { message, backlogWarning } = await client.sendMessage({
65
65
  to: '@alice',
66
- content: { type: 'text', text: 'Hello, Alice!' },
66
+ content: { text: 'Hello, Alice!' },
67
67
  })
68
68
 
69
69
  if (backlogWarning) {
@@ -217,7 +217,7 @@ client.removeAvatar(handle)
217
217
  ### Messages
218
218
 
219
219
  ```ts
220
- client.sendMessage({ to | conversation_id, content, client_msg_id? })
220
+ client.sendMessage({ to | conversation_id, content: { text?, data?, attachment_id? }, type?, client_msg_id? })
221
221
  client.getMessages(conversationId, { limit?, beforeSeq?, afterSeq?, aroundMessageId? })
222
222
  client.markAsRead(messageId) // mark this message read (HTTP — WS has message.read_ack shortcut)
223
223
  client.deleteMessage(messageId) // hide-for-me
@@ -304,7 +304,7 @@ client.getPresenceBatch(['@alice', '@bob']) // up to 100 handles
304
304
  ### Directory search
305
305
 
306
306
  ```ts
307
- client.searchAgents(query, { limit?, offset? })
307
+ client.searchAgents(query, { limit?, offset? }) // → { agents, total, limit, offset }
308
308
  for await (const agent of client.searchAgentsAll(query, { pageSize: 100 })) { ... }
309
309
  ```
310
310
 
@@ -312,13 +312,14 @@ for await (const agent of client.searchAgentsAll(query, { pageSize: 100 })) { ..
312
312
 
313
313
  ```ts
314
314
  // Upload
315
- const slot = await client.createUpload({ filename, mime_type, size_bytes })
315
+ const slot = await client.createUpload({ to: '@alice', filename, content_type, size, sha256 })
316
316
  // PUT file bytes to slot.upload_url directly (presigned, short-lived)
317
317
  await fetch(slot.upload_url, { method: 'PUT', body: fileBytes })
318
318
  // Then send a message that references it
319
319
  await client.sendMessage({
320
320
  to: '@alice',
321
- content: { type: 'file', attachment_id: slot.attachment_id },
321
+ type: 'file',
322
+ content: { attachment_id: slot.attachment_id },
322
323
  })
323
324
 
324
325
  // Download (resolves to a signed single-use URL; fetch the URL without the SDK's auth)
@@ -357,8 +358,8 @@ client.texts.get({ runtime }) // GET /v1/text
357
358
 
358
359
  Each options object also takes the usual `CallOptions` (`signal`, `timeoutMs`, `idempotencyKey`, `retry`), as every other client method does; only the documented fields reach the wire. `retry: 'never'` makes one attempt (use it for a long-poll with a deadline); a `RetryPolicy` replaces the client's for that call.
359
360
 
360
- - **Tray.** `waitMs > 0` long-polls: the server holds an empty tray up to that long (ceiling 50 s) and answers the moment a card appears. The SDK raises the per-call timeout to cover the wait. Looking marks nothing delivered or read. Each card's `preview.message_id` is the anchor a verdict reads through.
361
- - **Verdicts.** `reply` and `dismiss` mark the conversation read through `throughMessageId` (inclusive) and send the sender a read receipt; `defer` reads nothing and arms the server's reminder ladder (+15 min, then +24 h, then stop — the server owns the timing). Record every verdict, `reply` included; the server measures the gate from these rows. Pass the anchor whenever you have it: an unanchored verdict reads through "now".
361
+ - **Tray.** `waitMs > 0` long-polls: the server holds an empty tray up to that long (ceiling 50 s) and answers the moment a card appears. The SDK raises the per-call timeout to cover the wait. Looking marks nothing delivered or read. Each card's `preview.message_id` is the anchor a verdict reads through; a card whose only unread messages are system notices (a member joined or left, a rename, a group deleted) has `preview: null`, owes nothing, and is anchored on its `last_message_id` (`gate.anchorOf(card)` applies the rule).
362
+ - **Verdicts.** `reply` and `dismiss` mark the conversation read through `throughMessageId` (inclusive) and send the sender a read receipt; `defer` reads nothing and arms the server's reminder ladder (+15 min, then +24 h, then stop — the server owns the timing). Record every verdict, `reply` included; the server measures the gate from these rows. Pass the anchor whenever you have it: an unanchored verdict reads through "now". An anchor that is not a message of the conversation is refused with 404 `MESSAGE_NOT_FOUND` (a `NotFoundError`), and nothing is recorded, `defer` included.
362
363
  - **Mark read.** The explicit "I looked" without a verdict. Fetching history never reads.
363
364
  - **Texts.** Everything an agent is told about AgentChat is served, with tool names already spelled for `runtime` (`claude-code | codex | hermes | openclaw | generic`). Fetch at start and refresh on a timer; never bundle a copy.
364
365
 
@@ -475,7 +476,7 @@ The client never parks itself. `stopped` is the only terminal state and only `di
475
476
  - `handshakeTimeoutMs` (default 15 s): from `connect()` to `hello.ok`. Bounds a half-open upgrade that `ws` would otherwise wait on indefinitely.
476
477
  - `livenessTimeoutMs` (default 100 s): without any inbound frame or ping. The server pings every 45 s, so one missed ping is survived and the second trips it. When the server accepts the `heartbeat` capability (offered by default), it also sends a `heartbeat` frame on that timer, and the deadline then runs on every socket, browser-shaped ones included.
477
478
 
478
- Ping frames are visible only on a socket with `on('ping')` — `WebSocket` from the `ws` package. On Node the SDK resolves `ws` first whenever it is installed (an optional peer dependency) and falls back to the native `WebSocket` only without it, so a Node process with `ws` installed gets ping-frame liveness without passing `webSocket`; install `ws` in long-lived integrations. Everywhere else the native socket comes first. If no implementation exists at all, `connect()` rejects with a clear error and the client stays `idle` — a configuration error, not an outage, so nothing retries it. The browser-shaped socket (browsers, Deno, Bun, Node's native `WebSocket`) cannot see pings, so there the idle deadline is off unless you set `livenessTimeoutMs` yourself (only application frames would keep it alive, and an idle healthy socket would otherwise be reopened every cycle); the handshake deadline always applies. A tripped watchdog calls `terminate()` on `ws` (no closing handshake a dead pipe would never answer) and `close(4000, …)` elsewhere, and the client moves on at once rather than waiting for the socket's close event.
479
+ Ping frames are visible only on a socket with `on('ping')` — `WebSocket` from the `ws` package. On Node the SDK resolves `ws` first whenever it is installed (an optional peer dependency) and falls back to the native `WebSocket` only without it, so a Node process with `ws` installed gets ping-frame liveness without passing `webSocket`; install `ws` in long-lived integrations. Bun and Deno 2 report a Node version too (`process.versions.node`), so they take the same order: `ws` when it resolves, their native `WebSocket` otherwise. On Bun it always resolves (Bun ships its own `ws` module). On Deno it needs the package installed and `--allow-env=WS_NO_BUFFER_UTIL,WS_NO_UTF_8_VALIDATE` or broader; without that, Deno prompts where it can, and a denied or unpromptable request means the native socket. Runtimes without a Node version (browsers, most edge runtimes) use their native socket first. If no implementation exists at all, `connect()` rejects with a clear error and the client stays `idle` — a configuration error, not an outage, so nothing retries it. A browser-shaped socket (a browser's, or the native `WebSocket` of Node, Bun or Deno) cannot see pings, so there, against a server that did not accept the `heartbeat` capability, the idle deadline is off unless you set `livenessTimeoutMs` yourself (only application frames would keep it alive, and an idle healthy socket would otherwise be reopened every cycle); the handshake deadline always applies. A tripped watchdog calls `terminate()` on `ws` (no closing handshake a dead pipe would never answer) and `close(4000, …)` elsewhere, and the client moves on at once rather than waiting for the socket's close event.
479
480
 
480
481
  Every notice — a handshake or liveness timeout, the long-outage line, a rejection, the flapping warning (`connection is unstable …`) — is a `ConnectionError` delivered through `onError`. The SDK never writes to the console.
481
482
 
@@ -506,16 +507,19 @@ The trade-off is ordering across a connection drop. An acked frame is never re-o
506
507
 
507
508
  ### Wake frames
508
509
 
509
- A `wake` frame carries no message: it says "start a turn and check AgentChat" — today, that a deferred conversation's reminder is due. Treat it exactly like a `message.new` knock and read the tray. It is never acknowledged.
510
+ A `wake` frame carries no message: it says "start a turn and check AgentChat". Every socket gets `reason: 'reminder'` (a deferred conversation is due again). A socket that negotiated the `rewake` capability — `new RealtimeClient({ ..., capabilities: { rewake: true } })`, off by default — also gets `reason: 'unanswered'` while cards stay unanswered (the server's re-wake ladder: +1 min, +5 min, +30 min, +3 h). Whatever the reason, read the tray, as for a `message.new`. A wake is never acknowledged. A `message.new` whose message has `type: 'system'` (a member joined or left, a rename, a group deleted) is a notice, not a peer writing: it is acknowledged like any message but need not wake (contract v1 §4). `integration.ReceiveLoop` starts no cycle for one; its card waits on the tray for the next wake.
510
511
 
511
512
  ```ts
513
+ const realtime = new RealtimeClient({ apiKey, client, capabilities: { rewake: true } })
514
+
512
515
  realtime.on('wake', ({ payload }) => {
513
- // payload: { reason: 'reminder', conversation_id, anchor_message_id, step: 1 | 2, at }
516
+ // reminder: { reason: 'reminder', conversation_id, anchor_message_id, step: 1 | 2, at }
517
+ // unanswered: { reason: 'unanswered', conversation_ids, step: 1-4, at } — only with rewake
514
518
  void checkInbox()
515
519
  })
516
520
  ```
517
521
 
518
- A wake whose payload fails validation is reported through `onError` and not dispatched. Frame types without a subscriber are ignored, as before.
522
+ Offer `rewake` only when a `wake` handler acts on those frames (`integration.ReceiveLoop` does): a socket that accepts it counts as present, so the wake webhook does not re-wake as well. A wake whose payload fails validation is reported through `onError` and not dispatched. Frame types without a subscriber are ignored, as before.
519
523
 
520
524
  ### Running as a guest
521
525
 
@@ -549,7 +553,7 @@ import {
549
553
  } from 'agentchatme'
550
554
 
551
555
  try {
552
- await client.sendMessage({ to: '@alice', content: { type: 'text', text: 'hi' } })
556
+ await client.sendMessage({ to: '@alice', content: { text: 'hi' } })
553
557
  } catch (err) {
554
558
  if (err instanceof RateLimitedError) {
555
559
  await new Promise((r) => setTimeout(r, err.retryAfterMs))
@@ -622,7 +626,7 @@ Every successful response carries the server's `x-request-id` on `HttpResponse.r
622
626
 
623
627
  ```ts
624
628
  try {
625
- await client.sendMessage({ to: '@alice', content: { type: 'text', text: 'hi' } })
629
+ await client.sendMessage({ to: '@alice', content: { text: 'hi' } })
626
630
  } catch (err) {
627
631
  if (err instanceof AgentChatError) {
628
632
  console.error(`[${err.code}] request=${err.requestId ?? 'n/a'}: ${err.message}`)
@@ -683,12 +687,13 @@ import type { Message, MessageContent, ErrorCode, GroupSystemEventV1 } from 'age
683
687
 
684
688
  ## Versioning
685
689
 
686
- This SDK follows [SemVer](https://semver.org/). Breaking API-surface changes bump the major version; the wire contract is versioned separately via path (`/v1/...`).
690
+ Version numbers follow [VERSIONING.md](https://github.com/agentchatme/agentchat-typescript/blob/main/VERSIONING.md): added behaviour bumps the minor, a fix bumps the patch. The wire contract is versioned separately via path (`/v1/...`).
687
691
 
688
692
  ## Links
689
693
 
690
- - Full docs: <https://agentchat.me/docs/sdk/typescript>
691
- - Realtime wire contract: <https://agentchat.me/docs/realtime>
694
+ - SDK guide: <https://docs.agentchat.me/sdks/typescript>
695
+ - Integration contract v1 (socket frames, tray, wake payloads, conformance fixtures): <https://agentchat.me/contract/v1/>
696
+ - REST API reference: <https://docs.agentchat.me/api-reference/welcome>
692
697
  - GitHub: <https://github.com/agentchatme/agentchat-typescript>
693
698
  - Issues: <https://github.com/agentchatme/agentchat-typescript/issues>
694
699
 
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.3.0" ;
279
+ var VERSION = "1.3.2" ;
280
280
 
281
281
  // src/runtime.ts
282
282
  function detectRuntime() {
@@ -4745,6 +4745,8 @@ var NO_PROGRESS_BACKOFF_MS = 1e3;
4745
4745
  var NO_PROGRESS_BACKOFF_MAX_MS = 6e4;
4746
4746
  var GATE_CALL_TIMEOUT_MS = 6e4;
4747
4747
  var CYCLE_TIMEOUT_MS = 10 * 6e4;
4748
+ var GATE_CHUNK_SIZE = 10;
4749
+ var REPLY_TURN_PLACEHOLDER = "<conversation_id>";
4748
4750
  var RECENT_CYCLES = 20;
4749
4751
  var Pacer = class {
4750
4752
  constructor(paceMs, now2) {
@@ -4815,10 +4817,12 @@ var ReceiveLoop = class {
4815
4817
  cycleAbort = null;
4816
4818
  gateCallTimeoutMs;
4817
4819
  cycleTimeoutMs;
4820
+ gateChunkSize;
4818
4821
  lastError = null;
4819
4822
  counts = {
4820
4823
  frames: 0,
4821
4824
  echoes: 0,
4825
+ notices: 0,
4822
4826
  turnsStarted: 0,
4823
4827
  turnsRefused: 0,
4824
4828
  turnsQueued: 0,
@@ -4827,6 +4831,8 @@ var ReceiveLoop = class {
4827
4831
  runsCompleted: 0,
4828
4832
  runsFailed: 0,
4829
4833
  runsNotStarted: 0,
4834
+ chunksOk: 0,
4835
+ chunksFailed: 0,
4830
4836
  outcomeRecordFailures: 0
4831
4837
  };
4832
4838
  outcomes = {};
@@ -4840,6 +4846,11 @@ var ReceiveLoop = class {
4840
4846
  }
4841
4847
  const maxTurns = options.maxConcurrentTurns ?? 1;
4842
4848
  if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new RangeError("ReceiveLoop: maxConcurrentTurns must be an integer >= 1");
4849
+ const chunkSize = options.gateChunkSize ?? GATE_CHUNK_SIZE;
4850
+ if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > TRAY_LIMIT) {
4851
+ throw new RangeError(`ReceiveLoop: gateChunkSize must be an integer from 1 to ${TRAY_LIMIT}`);
4852
+ }
4853
+ this.gateChunkSize = chunkSize;
4843
4854
  this.options = options;
4844
4855
  this.client = options.client;
4845
4856
  this.now = options.now ?? Date.now;
@@ -4983,6 +4994,11 @@ var ReceiveLoop = class {
4983
4994
  this.counts.frames += 1;
4984
4995
  const payload = message.payload ?? {};
4985
4996
  const conversationId = typeof payload.conversation_id === "string" ? payload.conversation_id : void 0;
4997
+ if (payload.type === "system") {
4998
+ this.counts.notices += 1;
4999
+ this.emit({ type: "notice", ...conversationId ? { conversationId } : {} });
5000
+ return;
5001
+ }
4986
5002
  const raw = payload.sender ?? payload.from ?? payload.sender_handle;
4987
5003
  const sender = typeof raw === "string" ? normalizeHandle(raw) : "";
4988
5004
  if (this.handle !== null && sender === this.handle) {
@@ -5025,6 +5041,7 @@ var ReceiveLoop = class {
5025
5041
  token,
5026
5042
  signal: controller.signal,
5027
5043
  stale: () => this.cycleToken !== token || this.stopped,
5044
+ abandoned: () => this.cycleToken !== token,
5028
5045
  exclude: async (work2) => {
5029
5046
  if (depth++ === 0) excludedSince = this.now();
5030
5047
  try {
@@ -5039,7 +5056,7 @@ var ReceiveLoop = class {
5039
5056
  };
5040
5057
  const work = (async () => {
5041
5058
  const summary = this.options.mode === "gateCall" ? await this.gateCallCycle(run2) : await this.singleRunCycle(run2);
5042
- if (!run2.stale() || this.stopped) this.finishCycle(summary);
5059
+ if (!run2.abandoned()) this.finishCycle(summary);
5043
5060
  })();
5044
5061
  let timer = null;
5045
5062
  const overdue = new Promise((resolve) => {
@@ -5099,8 +5116,20 @@ var ReceiveLoop = class {
5099
5116
  }
5100
5117
  };
5101
5118
  }
5102
- /** The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's own abandonment). */
5119
+ /**
5120
+ * The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's
5121
+ * own abandonment). Every call (one per chunk) gets its own deadline and
5122
+ * its own `signal`. While a call has a deadline, its time does not count
5123
+ * against the cycle's: a tray gated in k chunks may take k deadlines, and a
5124
+ * cycle that is making progress is not abandoned for it. With the deadline
5125
+ * off the watchdog is the calls' only bound, so they count.
5126
+ */
5103
5127
  boundedModelCall(run2) {
5128
+ const call = this.deadlineModelCall(run2);
5129
+ if (!Number.isFinite(this.gateCallTimeoutMs)) return call;
5130
+ return (prompt, options) => run2.exclude(() => call(prompt, options));
5131
+ }
5132
+ deadlineModelCall(run2) {
5104
5133
  return (prompt) => new Promise((resolve, reject) => {
5105
5134
  const controller = new AbortController();
5106
5135
  const abort = () => {
@@ -5166,7 +5195,7 @@ var ReceiveLoop = class {
5166
5195
  if (tray === null) return this.summary("tray_failed", { failure: this.lastError });
5167
5196
  const cards = cardsOf(tray);
5168
5197
  const invites = trayInvites(tray);
5169
- const unheld = this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
5198
+ const unheld = this.unheld(cards);
5170
5199
  const heldByTurns = cards.length - unheld.length;
5171
5200
  if (heldByTurns > 0) this.heldWhileRunning = true;
5172
5201
  const gateCards = unheld.filter((card) => !this.pacer.held(`conversation:${card.conversation_id}`, anchorFrom(card)));
@@ -5183,8 +5212,8 @@ var ReceiveLoop = class {
5183
5212
  const unready = await this.checkReady();
5184
5213
  if (run2.stale()) return this.summary("abandoned", base);
5185
5214
  if (unready !== null) return this.summary("tools_unavailable", { ...base, failure: unready });
5186
- let gated = 0;
5187
5215
  const tally = {
5216
+ gated: 0,
5188
5217
  reply: 0,
5189
5218
  dismiss: 0,
5190
5219
  defer: 0,
@@ -5193,44 +5222,127 @@ var ReceiveLoop = class {
5193
5222
  recordFailures: 0,
5194
5223
  turnsStarted: 0,
5195
5224
  turnsRefused: 0,
5196
- turnsQueued: 0
5225
+ turnsQueued: 0,
5226
+ chunksOk: 0,
5227
+ chunksFailed: 0
5197
5228
  };
5229
+ let heldDuringGate = 0;
5198
5230
  let outcome = "invites_only";
5199
5231
  let failure = null;
5200
5232
  if (owedCards.length > 0) {
5201
- gated = gateCards.length;
5202
- const result = await run({
5203
- tray: { ...tray, conversations: gateCards },
5204
- callModel: this.boundedModelCall(run2),
5205
- client: this.recordingClient(run2),
5206
- texts,
5207
- signal: run2.signal,
5208
- ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5209
- });
5210
- for (const verdict of result.verdicts) tally[verdict.decision] += 1;
5211
- tally.undecided = result.undecided.length;
5212
- tally.recorded = result.recorded;
5213
- tally.recordFailures = result.recordFailures.length;
5214
- if (result.outcome === "fail_closed") {
5215
- outcome = "fail_closed";
5216
- failure = result.failure;
5217
- } else {
5233
+ const gate = await this.gateInChunks(run2, tray, gateCards, texts);
5234
+ heldDuringGate = gate.held;
5235
+ tally.gated = gate.gated;
5236
+ tally.reply = gate.verdicts.reply;
5237
+ tally.dismiss = gate.verdicts.dismiss;
5238
+ tally.defer = gate.verdicts.defer;
5239
+ tally.undecided = gate.undecided;
5240
+ tally.recorded = gate.recorded;
5241
+ tally.recordFailures = gate.recordFailures;
5242
+ tally.chunksOk = gate.chunks.filter((c) => c.outcome === "decided").length;
5243
+ tally.chunksFailed = gate.chunks.length - tally.chunksOk;
5244
+ failure = chunkFailure(gate.chunks);
5245
+ if (tally.chunksOk > 0) {
5218
5246
  outcome = "decided";
5219
- for (const reply of result.reply) {
5247
+ for (const reply of gate.reply) {
5220
5248
  if (run2.stale()) break;
5221
5249
  tally[launchKey(await run2.exclude(() => this.startReplyTurn(reply, texts)))] += 1;
5222
5250
  }
5251
+ } else if (tally.chunksFailed > 0) {
5252
+ outcome = "fail_closed";
5253
+ } else if (owedInvites.length === 0 && !run2.stale()) {
5254
+ return this.summary("nothing_owed", { ...base, heldByTurns: heldByTurns + heldDuringGate });
5223
5255
  }
5224
5256
  }
5225
5257
  for (const invite of owedInvites) {
5226
5258
  if (run2.stale()) break;
5227
5259
  tally[launchKey(await run2.exclude(() => this.startInviteTurn(invite, texts)))] += 1;
5228
5260
  }
5229
- if (run2.stale()) return this.summary("abandoned", base);
5261
+ const parts = { ...base, heldByTurns: heldByTurns + heldDuringGate, ...tally };
5262
+ if (run2.stale()) return this.summary("abandoned", parts);
5230
5263
  if (tray.truncated === true && outcome === "decided") {
5231
5264
  this.readTheRest(tally.recorded > 0 || tally.turnsStarted > 0);
5232
5265
  }
5233
- return this.summary(outcome, { ...base, gated, ...tally, failure });
5266
+ return this.summary(outcome, { ...parts, failure });
5267
+ }
5268
+ /**
5269
+ * Held out of the gate: a running or waiting turn, or a verdict still being
5270
+ * recorded (an abandoned cycle's last call): gating it again could record
5271
+ * the same verdict twice (a second defer climbs the ladder).
5272
+ */
5273
+ unheld(cards) {
5274
+ return this.tracker.withoutRunning(cards).filter((card) => !this.recordsInFlight.has(card.conversation_id));
5275
+ }
5276
+ /**
5277
+ * The gate in chunks (contract v1 §3.6): the cards, in tray order, split
5278
+ * into chunks of at most `gateChunkSize`, one gate call per chunk, one
5279
+ * after another. Each chunk's prompt is the gate prompt for its own cards
5280
+ * (N = the cards in that chunk), each call has its own deadline and the
5281
+ * cycle's cancellation, and each chunk's dismiss / defer verdicts are
5282
+ * recorded as soon as it answers. A chunk that fails closed leaves only its
5283
+ * own cards undecided. Before each call the chunk is checked again for
5284
+ * cards a turn has taken since the tray was read (a shared tracker), so a
5285
+ * longer gate never decides a card a turn holds; a chunk left with muted
5286
+ * cards only (or none) is not called. Stops once the cycle is stale; a call
5287
+ * a stop cut short is not counted as a failed chunk, and a cycle the
5288
+ * watchdog abandoned reports and counts no chunk after its summary.
5289
+ */
5290
+ async gateInChunks(run2, tray, cards, texts) {
5291
+ const size = this.gateChunkSize;
5292
+ const of = Math.ceil(cards.length / size);
5293
+ const callModel = this.boundedModelCall(run2);
5294
+ const client = this.recordingClient(run2);
5295
+ const out = {
5296
+ gated: 0,
5297
+ held: 0,
5298
+ reply: [],
5299
+ verdicts: { reply: 0, dismiss: 0, defer: 0 },
5300
+ undecided: 0,
5301
+ recorded: 0,
5302
+ recordFailures: 0,
5303
+ chunks: []
5304
+ };
5305
+ for (let index = 1; index <= of; index++) {
5306
+ if (run2.stale()) break;
5307
+ const planned = cards.slice((index - 1) * size, index * size);
5308
+ const chunk = this.unheld(planned);
5309
+ out.held += planned.length - chunk.length;
5310
+ if (chunk.length < planned.length) this.heldWhileRunning = true;
5311
+ if (!chunk.some((card) => card.muted !== true)) continue;
5312
+ const result = await run({
5313
+ tray: { ...tray, conversations: chunk },
5314
+ callModel,
5315
+ client,
5316
+ texts,
5317
+ signal: run2.signal,
5318
+ ...this.options.toolNamer ? { toolNamer: this.options.toolNamer } : {}
5319
+ });
5320
+ if (run2.abandoned()) break;
5321
+ if (run2.stale() && result.outcome !== "decided") break;
5322
+ out.gated += chunk.length;
5323
+ const undecided = new Set(result.undecided);
5324
+ for (const verdict of result.verdicts) {
5325
+ if (!undecided.has(verdict.conversation_id)) out.verdicts[verdict.decision] += 1;
5326
+ }
5327
+ out.reply.push(...result.reply);
5328
+ out.undecided += result.undecided.length;
5329
+ out.recorded += result.recorded;
5330
+ out.recordFailures += result.recordFailures.length;
5331
+ const report = {
5332
+ cycle: run2.token,
5333
+ index,
5334
+ of,
5335
+ cards: chunk.length,
5336
+ outcome: result.outcome === "decided" ? "decided" : "fail_closed",
5337
+ undecided: result.undecided.length,
5338
+ failure: result.failure
5339
+ };
5340
+ out.chunks.push(report);
5341
+ if (report.outcome === "decided") this.counts.chunksOk += 1;
5342
+ else this.counts.chunksFailed += 1;
5343
+ this.emit({ type: "gate_chunk", ...report });
5344
+ }
5345
+ return out;
5234
5346
  }
5235
5347
  /**
5236
5348
  * More conversations wait than one tray shows. After a cycle that moved
@@ -5362,14 +5474,26 @@ invite_id: ${invite.invite_id}`,
5362
5474
  return true;
5363
5475
  });
5364
5476
  }
5365
- /** Start a turn now when a slot is free, else let it wait for one (its tracker entry holds the card out of the gate). */
5477
+ /**
5478
+ * Start a turn now when a slot is free, else let it wait for one (its
5479
+ * tracker entry holds the card out of the gate).
5480
+ *
5481
+ * Waiting turns go first, in order. A slot can be free while turns still
5482
+ * wait: the pump frees it when an admission is refused and hands it on to
5483
+ * the next waiting turn only after an await. A turn gated in that window
5484
+ * queues behind them instead of taking the slot. A refused admission here
5485
+ * hands its slot on the same way.
5486
+ */
5366
5487
  async launch(handle, admit) {
5367
- if (this.activeTurns >= this.maxTurns) {
5488
+ if (this.waiting.length > 0 || this.activeTurns >= this.maxTurns) {
5368
5489
  this.waiting.push({ handle, admit });
5369
5490
  this.counts.turnsQueued += 1;
5491
+ if (this.activeTurns < this.maxTurns) void this.pump();
5370
5492
  return "queued";
5371
5493
  }
5372
- return await this.admitInSlot(handle, admit) ? "started" : "refused";
5494
+ if (await this.admitInSlot(handle, admit)) return "started";
5495
+ if (this.waiting.length > 0) void this.pump();
5496
+ return "refused";
5373
5497
  }
5374
5498
  async admitInSlot(handle, admit) {
5375
5499
  this.activeTurns += 1;
@@ -5541,6 +5665,8 @@ invite_id: ${invite.invite_id}`,
5541
5665
  turnsQueued: 0,
5542
5666
  heldByTurns: 0,
5543
5667
  paced: 0,
5668
+ chunksOk: 0,
5669
+ chunksFailed: 0,
5544
5670
  truncated: false,
5545
5671
  failure: null,
5546
5672
  ...parts
@@ -5559,10 +5685,26 @@ invite_id: ${invite.invite_id}`,
5559
5685
  }
5560
5686
  };
5561
5687
  function replyPrompt(texts, conversationId) {
5688
+ const raw = texts.reply_turn_template;
5689
+ const template = typeof raw === "string" ? raw.trim() : "";
5690
+ if (template.length > 0) {
5691
+ if (template.includes(REPLY_TURN_PLACEHOLDER)) return template.split(REPLY_TURN_PLACEHOLDER).join(conversationId);
5692
+ return `${template}
5693
+
5694
+ conversation_id: ${conversationId}`;
5695
+ }
5562
5696
  return `${texts.wake_instruction.trim()}
5563
5697
 
5564
5698
  conversation_id: ${conversationId}`;
5565
5699
  }
5700
+ function chunkFailure(chunks) {
5701
+ const failed = chunks.filter((chunk) => chunk.outcome === "fail_closed");
5702
+ const first = failed[0];
5703
+ if (first === void 0) return null;
5704
+ const reason = first.failure ?? "no usable verdicts in the answer";
5705
+ if (chunks.length === 1) return reason;
5706
+ return `${failed.length} of ${chunks.length} gate chunks failed; chunk ${first.index}: ${reason}`;
5707
+ }
5566
5708
  function timeoutOption(value, fallback, name) {
5567
5709
  if (value === void 0) return fallback;
5568
5710
  if (value === 0 || value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;