akanjs 3.2.0-rc.6 → 3.2.0-rc.7

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
@@ -4,16 +4,24 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - 31f7039: The agent relay's hooks share one turn, and every turn the quota passes is billed, including one that fails.
7
+ - bd198af: A turn its caller stops is billed at what the provider plausibly charged, never at zero.
8
8
 
9
- - **One turn from the policy to the usage report.** `setAgentRequestPolicy`, `setAgentQuota` and `setAgentUsage` receive the same `AgentTurnContext`: `{ id, headers, account, ip }`. `id` is new for every turn, so an app can match a quota hold with the usage report that settles it, and `headers` lets it read an org header to pick the account to bill, once it has checked that the caller belongs to that org. The quota check also carries the `request` the policy returned. `AgentRequestContext` is now a deprecated alias.
9
+ - A streamed turn whose reader leaves stops its provider call, and a stream cut short carries no counts of the provider's own: an OpenAI-compatible stream sends them only in its last chunk, and an Anthropic one only the prompt. Its usage report keeps every count the provider did send, estimates the rest from the request and the text and tool arguments streamed, and says so with `estimated: true` on `AgentUsageReport` and `LlmSpent`. The estimate takes three UTF-8 bytes a token and 1,600 tokens a picture, which errs high.
10
+ - A plain turn's answer shows nothing before its end to estimate from, so its provider call runs on after the client leaves. The client still gets a 499 at once, and the turn is reported `aborted` with the provider's own counts when the call ends. Until then it holds the caller's next turn, as any turn not yet reported does.
11
+ - `AgentRelayPolicy.apply` takes the old `{ account, ip }` context again and fills in a fresh `id` and empty `headers`. `AgentRequestContext` is that old shape again, and stays deprecated.
12
+
13
+ **Upgrading.** A usage hook receives failed and aborted turns. Before, a streamed turn whose reader left ran to its end and was billed as finished; it now stops early and is billed at its estimate. To bill as before, bill every report except `outcome === "failed"`. Billing only `ok` would leave a stopped turn unbilled while the provider charged for it. Read `estimated` to treat estimated counts differently.
14
+
15
+ - 31f7039: The agent relay's hooks share one turn, and every turn the quota passes is billed, including one that fails or whose caller goes away.
16
+
17
+ - **One turn from the policy to the usage report.** `setAgentRequestPolicy`, `setAgentQuota` and `setAgentUsage` receive the same `AgentTurnContext`: `{ id, headers, account, ip }`. `id` is new for every turn, so an app can match a quota hold with the usage report that settles it, and `headers` lets it read an org header to pick the account to bill, once it has checked that the caller belongs to that org. The quota check also carries the `request` the policy returned. `AgentRequestContext` is deprecated.
10
18
  - **Usage for every turn the quota passed.** The usage report carries an `outcome`.
11
19
  - `ok`: the turn finished.
12
- - `failed`: the provider or the network ended it. The report holds what the provider counted before then, such as the prompt of an Anthropic stream that broke after `message_start`, and the model.
20
+ - `failed`: the provider or the network ended it. The report holds what the provider spent before then, such as the prompt of an Anthropic stream that broke after `message_start`, and the model.
13
21
  - `aborted`: the caller went away first.
14
- - A turn whose provider reported no counts is reported with zero usage. Before, a failed turn and a turn without counts were not reported at all.
15
- - A failed turn holds the caller's next turn until its report settles, as a finished one does.
16
- - **A caller that goes away stops the provider call.** When the reader of a streamed turn disconnects, or the client of a plain one does, the provider call is aborted, so the turn stops spending tokens on an answer nobody will read. `LlmAdaptor.chat` takes an optional third argument, `signal`, and both built-in adaptors pass it to `fetch`. A plain turn whose client left answers 499 rather than logging a server error.
22
+ - A turn that spent nothing, such as one the provider refused, is reported with zero usage. Before, a failed turn and a turn without counts were not reported at all.
23
+ - A failed or aborted turn holds the caller's next turn until its report settles, as a finished one does.
24
+ - **A streamed turn whose reader goes away stops the provider call**, so the turn stops spending tokens on an answer nobody will read. `LlmAdaptor.chat` takes an optional third argument, `signal`, which the relay sends with `onDelta`, and both built-in adaptors pass it to `fetch`. A plain turn whose client left answers 499 rather than logging a server error.
17
25
  - **Cache writes reported separately.** `LlmUsage.cacheWriteTokens` is the part of `inputTokens` the provider wrote to its cache, which Anthropic bills above its input rate. `inputTokens` still counts the whole prompt.
18
26
  - **`AgentService.runTurn(request, { onDelta, preamble, signal })`.** `preamble` replaces the in-page preamble, and `false` sends none, for a turn with no screen behind it. Passing `onDelta` alone as the second argument still works.
19
27
 
@@ -318,19 +326,18 @@
318
326
 
319
327
  The `infra/app` chart's readiness probe calls a new `readinessPath` value, `/_akan/app/health` unless set, because an image built with an earlier akanjs answers `/_akan/app/ready` with 404 and its pod would never become Ready. Set `readinessPath: /_akan/app/ready` once every image the chart deploys carries this release. The repository's own values set it, since its pipeline builds the image from the same commit as the chart. The startup and liveness probes stay on `/_akan/app/health`.
320
328
 
321
- - 7f0de74: On the Redis WebSocket adaptor, Redis now hands a server only the events of the rooms it holds and the changes of the models it holds live rooms for. Both used to go to every server of the app on one channel, `<prefix>ws:broadcast`.
329
+ - 7f0de74: On the Redis WebSocket adaptor, each room's events and each live-synced model's changes now go out on channels of their own, and a server subscribes only to those of the rooms and models it holds. Both used to go to every server of the app on one channel, `<prefix>ws:broadcast`, which servers keep using for one more release so that a rolling deploy loses nothing (see the note on rolling deploys).
322
330
 
323
331
  - **A room's events** go out on one of 16,384 channels, picked by a hash of the room id (`<prefix>ws:room:<shard>`). A server subscribes to a shard while it holds a room on it.
324
- - **A change to a live-synced model** goes out on `<prefix>ws:change:<model>`. A server subscribes to it while it holds a live room for that model, so a server with none, a batch server included, receives no change for it.
332
+ - **A change to a live-synced model** goes out on `<prefix>ws:change:<model>`. A server subscribes to it while it holds a live room for that model.
325
333
  - **A subscribe is acknowledged once Redis has confirmed the SUBSCRIBE** for its channel, so an event another server publishes after the ack still arrives. While the subscriber is disconnected, the ack does not wait.
326
334
  - **`WebsocketAdaptor.joinRoom`** takes an optional third argument, `{ live: refName }`, for a live room.
327
335
 
328
- Servers of this release and of earlier ones do not hear each other until the last old server is gone:
329
-
330
- - A pubsub event published on one side never reaches clients on the other.
331
- - A live list misses the writes made on the other side. A client on an old server resynchronizes when it reconnects to a new one. A client already on a new server stays stale until a later write reaches it or the page reloads, as nothing tells it to resynchronize.
336
+ - c0b84d0: A rolling deploy of an app on the Redis WebSocket adaptor loses no event while servers of this release and of an earlier one run side by side.
332
337
 
333
- Replacing every server at once, rather than rolling, avoids that window. A Redis ACL that names the old channel must allow `<prefix>ws:*` instead.
338
+ - **Servers of this release also publish every room event and live change on `<prefix>ws:broadcast`**, in the format earlier releases read, and listen there for theirs. They skip a copy another server of this release put there, since they heard it on its own channel. Servers of 3.2.0-rc.6, which use only the new channels, hear and are heard on those.
339
+ - **This lasts one release** (#458). Until then Redis still sends every event to every server on `<prefix>ws:broadcast`, plus once more to the servers holding its room, so the traffic saving of the per-room channels arrives with the next release. Deploy this release before that one rather than skipping it.
340
+ - **A Redis ACL** that names `<prefix>ws:broadcast` must allow `<prefix>ws:*` before this release goes out, since its servers publish on both.
334
341
 
335
342
  - 1f93507: On the Redis WebSocket adaptor, events buffered while the publisher was disconnected now go out in the order they were sent. Before, an event published while the buffer drained after a reconnect went straight out, ahead of older buffered ones, and the drain started on `connect`, ahead of the commands ioredis resends on `ready`. So another server's subscribers could see a room's events out of order. A message now waits behind a non-empty buffer, and the buffer drains once the publisher is `ready`. A publish that fails goes back into the buffer in the order it was sent, where it used to go to the back. When Redis refuses a publish with an error reply, the buffer is retried on a timer, starting at 200 ms and backing off to 5 s, instead of not until the next reconnect. Shutting down waits for a drain that is still running, unless the publisher drops meanwhile.
336
343
  - 5d3cb3e: In production, an error thrown while a page renders no longer reaches the browser as its message. The RSC worker returned the message as the error's digest, and React writes the digest into the Flight payload that the HTML inlines and that client navigations fetch, so a database driver's message, a file path or a value read from a record was on the page. Under `NODE_ENV=production` the digest is now a random 8-character id, and the worker's `[rsc] render failed` log line carries the same `digest=<id>` beside the full error, so the id a page shows finds its log line.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.6",
3
+ "version": "3.2.0-rc.7",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -5,9 +5,11 @@ import {
5
5
  type AgentWireReference,
6
6
  type AgentWireToolResult,
7
7
  type LlmAccepts,
8
+ type LlmAdaptor,
8
9
  type LlmTurnRequest,
9
10
  pageContentInstruction,
10
11
  } from "./predefinedAdaptor/llm.adaptor";
12
+ import { LlmSpend } from "./predefinedAdaptor/llmSpend";
11
13
  import { LlmAdaptorRole } from "./predefinedAdaptor/role.adaptor";
12
14
  import { serve } from "./serve";
13
15
  import { ToolNames } from "./toolNames";
@@ -23,6 +25,7 @@ export class AgentService extends serve("agent" as const, ({ plug }) => ({
23
25
  })) {
24
26
  async runTurn(request: LlmTurnRequest, options: AgentTurnOptions | ((delta: string) => void) = {}) {
25
27
  const { onDelta, preamble, signal } = typeof options === "function" ? { onDelta: options } : options;
28
+ signal?.throwIfAborted();
26
29
  const names = ToolNames.of(request);
27
30
  const prepared = names.encode(
28
31
  AgentService.instructed(
@@ -30,7 +33,7 @@ export class AgentService extends serve("agent" as const, ({ plug }) => ({
30
33
  preamble,
31
34
  ),
32
35
  );
33
- const answer = await this.llm.chat(prepared, onDelta, signal);
36
+ const answer = await AgentService.answered(this.llm, prepared, onDelta, signal);
34
37
  if (!answer) throw new Err("agent.error.llmUnavailable");
35
38
  return {
36
39
  text: answer.text ?? "",
@@ -57,6 +60,34 @@ export class AgentService extends serve("agent" as const, ({ plug }) => ({
57
60
  pageContentInstruction,
58
61
  ].join(" ");
59
62
 
63
+ private static async answered(
64
+ llm: LlmAdaptor,
65
+ prepared: LlmTurnRequest,
66
+ onDelta: ((delta: string) => void) | undefined,
67
+ signal: AbortSignal | undefined,
68
+ ) {
69
+ if (signal && !onDelta)
70
+ return await LlmSpend.outlast(llm.chat(prepared), signal, (answer) => ({
71
+ ...(answer?.usage ? { usage: answer.usage } : {}),
72
+ ...(answer?.model ? { model: answer.model } : {}),
73
+ }));
74
+ let streamed = "";
75
+ const forward =
76
+ onDelta &&
77
+ ((delta: string) => {
78
+ streamed += delta;
79
+ onDelta(delta);
80
+ });
81
+ try {
82
+ return await llm.chat(prepared, forward, signal);
83
+ } catch (error) {
84
+ const spent = LlmSpend.of(error);
85
+ if (!signal?.aborted && !spent?.usage) throw error;
86
+ const own = spent?.usage ? "" : streamed;
87
+ throw LlmSpend.attach(error, LlmSpend.estimate(spent?.usage, { prompt: prepared, streamed: own }));
88
+ }
89
+ }
90
+
60
91
  static instructed(request: LlmTurnRequest, preamble: string | false = AgentService.preamble): LlmTurnRequest {
61
92
  const instructions = [preamble, request.instructions].filter(Boolean).join("\n\n");
62
93
  if (instructions) return { ...request, instructions };
@@ -356,6 +356,7 @@ export class AnthropicLlm
356
356
  let text = "";
357
357
  let stopReason: string | null = null;
358
358
  let usage: AnthropicUsage = {};
359
+ let finalCount = false;
359
360
  const read = eachSseData(body, (payload) => {
360
361
  const event = JSON.parse(payload) as AnthropicStreamEvent;
361
362
  const index = event.index ?? 0;
@@ -375,10 +376,18 @@ export class AnthropicLlm
375
376
  if (event.type === "message_delta" && event.delta?.stop_reason) stopReason = event.delta.stop_reason;
376
377
 
377
378
  if (event.type === "message_start" && event.message?.usage) usage = { ...usage, ...event.message.usage };
378
- if (event.type === "message_delta" && event.usage) usage = { ...usage, ...event.usage };
379
+ if (event.type === "message_delta" && event.usage) {
380
+ usage = { ...usage, ...event.usage };
381
+ finalCount = true;
382
+ }
379
383
  });
380
384
  await read.catch((error: unknown) => {
381
- throw Object.keys(usage).length ? LlmSpend.attach(error, { usage: AnthropicLlm.usageOf(usage) }) : error;
385
+ const partial = Object.keys(usage).length ? AnthropicLlm.usageOf(usage) : undefined;
386
+ const streamed = text + [...calls.values()].map(({ args }) => args).join("");
387
+ throw LlmSpend.attach(
388
+ error,
389
+ partial && finalCount ? { usage: partial } : LlmSpend.estimate(partial, { streamed }),
390
+ );
382
391
  });
383
392
  const toolCalls = [...calls.entries()]
384
393
  .sort(([a], [b]) => a - b)
@@ -104,7 +104,8 @@ export interface LlmUsage {
104
104
  export interface LlmAdaptor {
105
105
  /**
106
106
  * `onDelta` opts into streaming and the full answer still resolves; an adaptor may ignore it. `signal` is aborted
107
- * once nobody waits for the answer, so the provider call should take it.
107
+ * once nobody reads the answer, so the provider call should take it. The relay sends it with `onDelta` only: a
108
+ * plain call runs to its end, where the provider's counts arrive.
108
109
  */
109
110
  chat(request: LlmTurnRequest, onDelta?: (delta: string) => void, signal?: AbortSignal): Promise<LlmTurnAnswer | null>;
110
111
  /** Omitted means text only. */
@@ -3,10 +3,17 @@ import type { LlmUsage } from "./llm.adaptor";
3
3
  export interface LlmSpent {
4
4
  usage?: LlmUsage;
5
5
  model?: string;
6
+ /** Some of `usage` is the framework's estimate: the call ended before the provider sent counts of its own. */
7
+ estimated?: boolean;
6
8
  }
7
9
 
8
10
  export class LlmSpend {
11
+
12
+ static readonly bytesPerToken = 3;
13
+
14
+ static readonly imageTokens = 1_600;
9
15
  static readonly #spent = new WeakMap<object, LlmSpent>();
16
+ static readonly #settling = new WeakMap<object, Promise<LlmSpent | null>>();
10
17
 
11
18
  static attach<E>(error: E, spent: LlmSpent): E {
12
19
  if (error && typeof error === "object") LlmSpend.#spent.set(error, { ...LlmSpend.of(error), ...spent });
@@ -16,4 +23,58 @@ export class LlmSpend {
16
23
  static of(error: unknown): LlmSpent | null {
17
24
  return error && typeof error === "object" ? (LlmSpend.#spent.get(error) ?? null) : null;
18
25
  }
26
+
27
+ static async settled(error: unknown): Promise<LlmSpent | null> {
28
+ const settling = error && typeof error === "object" ? LlmSpend.#settling.get(error) : undefined;
29
+ return settling ? { ...LlmSpend.of(error), ...(await settling) } : LlmSpend.of(error);
30
+ }
31
+
32
+ static outlast<T>(call: Promise<T>, signal: AbortSignal, spentOf: (answer: T) => LlmSpent): Promise<T> {
33
+ return new Promise<T>((resolve, reject) => {
34
+ const abandon = () => {
35
+ const error = new DOMException("Nobody waits for this answer any more.", "AbortError");
36
+ LlmSpend.#settling.set(
37
+ error,
38
+ call.then(spentOf, (failure: unknown) => LlmSpend.of(failure)).catch(() => null),
39
+ );
40
+ reject(error);
41
+ };
42
+ if (signal.aborted) abandon();
43
+ else signal.addEventListener("abort", abandon, { once: true });
44
+ void call.then(resolve, reject).finally(() => signal.removeEventListener("abort", abandon));
45
+ });
46
+ }
47
+
48
+ static estimate(
49
+ counted: LlmUsage | undefined,
50
+ { prompt, streamed = "" }: { prompt?: unknown; streamed?: string },
51
+ ): LlmSpent {
52
+ const inputTokens = counted?.inputTokens || (prompt === undefined ? 0 : LlmSpend.promptOf(prompt));
53
+ const outputTokens = Math.max(counted?.outputTokens ?? 0, LlmSpend.tokensOf(streamed));
54
+ const estimated = inputTokens !== (counted?.inputTokens ?? 0) || outputTokens !== (counted?.outputTokens ?? 0);
55
+ return {
56
+ usage: { ...counted, inputTokens, outputTokens, cachedTokens: counted?.cachedTokens ?? 0 },
57
+ ...(estimated ? { estimated } : {}),
58
+ };
59
+ }
60
+
61
+ static tokensOf(text: string): number {
62
+ return Math.ceil(Buffer.byteLength(text, "utf8") / LlmSpend.bytesPerToken);
63
+ }
64
+
65
+ static promptOf(request: unknown): number {
66
+ let images = 0;
67
+ const text = JSON.stringify(request, (_key, value: unknown) => {
68
+ if (!LlmSpend.#isImage(value)) return value;
69
+ images += 1;
70
+ return undefined;
71
+ });
72
+ return LlmSpend.tokensOf(text ?? "") + images * LlmSpend.imageTokens;
73
+ }
74
+
75
+ static #isImage(value: unknown): boolean {
76
+ if (!value || typeof value !== "object") return false;
77
+ const { mimeType, text } = value as { mimeType?: unknown; text?: unknown };
78
+ return typeof mimeType === "string" && mimeType.toLowerCase().startsWith("image/") && !text;
79
+ }
19
80
  }
@@ -7,6 +7,7 @@ import {
7
7
  type LlmUsage,
8
8
  pageContentInstruction,
9
9
  } from "./llm.adaptor";
10
+ import { LlmSpend } from "./llmSpend";
10
11
  import { eachSseData } from "./sseData";
11
12
 
12
13
  export interface OpenaiToolCall {
@@ -190,7 +191,7 @@ export class OpenaiDialect {
190
191
  let text = "";
191
192
  let finish: string | null = null;
192
193
  let usage: LlmUsage | undefined;
193
- await eachSseData(body, (payload) => {
194
+ const read = eachSseData(body, (payload) => {
194
195
  if (payload === "[DONE]") return;
195
196
  const chunk = JSON.parse(payload) as OpenaiStreamChunk;
196
197
  if (chunk.usage) usage = OpenaiDialect.usageOf(chunk.usage);
@@ -210,6 +211,10 @@ export class OpenaiDialect {
210
211
  }
211
212
  if (choice.finish_reason) finish = choice.finish_reason;
212
213
  });
214
+ await read.catch((error: unknown) => {
215
+ const streamed = text + [...calls.values()].map(({ args }) => args).join("");
216
+ throw LlmSpend.attach(error, usage ? { usage } : LlmSpend.estimate(undefined, { streamed }));
217
+ });
213
218
  const toolCalls = [...calls.entries()]
214
219
  .sort(([a], [b]) => a - b)
215
220
  .flatMap(([, call]) =>
@@ -91,6 +91,8 @@ export class WebSocketRedisAdaptor
91
91
  static readonly #shards = 16_384;
92
92
 
93
93
  static readonly #subscribeTimeoutMs = 3_000;
94
+
95
+ static readonly #legacyMark = "\0sharded";
94
96
  readonly #buffer: BufferedMessage[] = [];
95
97
  readonly #maxBufferSize = 10000;
96
98
  readonly #rooms = new Map<string, HeldRoom>();
@@ -111,6 +113,10 @@ export class WebSocketRedisAdaptor
111
113
  readonly #lossWaiters = new Set<() => void>();
112
114
  #warnedVersion = false;
113
115
 
116
+ get #legacyChannel() {
117
+ return `${this.channelPrefix}ws:broadcast`;
118
+ }
119
+
114
120
  #roomChannel(roomId: string) {
115
121
  return `${this.channelPrefix}ws:room:${Bun.hash.crc32(roomId) % WebSocketRedisAdaptor.#shards}`;
116
122
  }
@@ -147,6 +153,7 @@ export class WebSocketRedisAdaptor
147
153
  this.logger.warn("Subscriber disconnected; cross-server events are being missed until it returns");
148
154
  });
149
155
  this.subscriber.on("ready", () => {
156
+ this.#listenToLegacy();
150
157
 
151
158
  for (const [channel, hold] of this.#channels) this.#subscribe(channel, hold);
152
159
  const recovering = !this.#subscriberReady && this.#subscriberStarted;
@@ -191,23 +198,39 @@ export class WebSocketRedisAdaptor
191
198
  this.logger.warn(`Nothing to publish to ${roomId}: the payload has no JSON form`);
192
199
  return;
193
200
  }
201
+ const kind = bytes ? "bytes" : "json";
194
202
  this.#send({
195
203
  channel: this.#roomChannel(roomId),
196
204
  roomId,
197
- message: this.#pack(bytes ? "bytes" : "json", roomId, payload),
205
+ message: this.#pack(kind, roomId, payload),
198
206
  coalesce,
199
207
  seq: this.#sent++,
200
208
  });
209
+ this.#sendLegacy(kind, roomId, payload, coalesce);
201
210
  }
202
211
 
203
212
  publishChange(change: LiveChange): void {
213
+ const payload = JSON.stringify(change);
204
214
  this.#send({
205
215
  channel: this.#changeChannel(change.refName),
206
216
  roomId: "",
207
- message: this.#pack("change", "", JSON.stringify(change)),
217
+ message: this.#pack("change", "", payload),
208
218
  coalesce: false,
209
219
  seq: this.#sent++,
210
220
  });
221
+ this.#sendLegacy("change", "", payload, false);
222
+ }
223
+
224
+ #sendLegacy(kind: "json" | "bytes" | "change", roomId: string, payload: string | Uint8Array, coalesce: boolean) {
225
+ const origin = `${this.serverId}${WebSocketRedisAdaptor.#legacyMark}`;
226
+ const message = this.#pack(kind, roomId, payload, origin);
227
+ this.#send({ channel: this.#legacyChannel, roomId, message, coalesce, seq: this.#sent++ });
228
+ }
229
+
230
+ #listenToLegacy() {
231
+ this.subscriber.subscribe(this.#legacyChannel).catch((err: Error) => {
232
+ this.logger.warn(`Subscribe to ${this.#legacyChannel} failed: ${err.message}`);
233
+ });
211
234
  }
212
235
 
213
236
  onChange(handler: LiveChangeHandler): void {
@@ -351,6 +374,7 @@ export class WebSocketRedisAdaptor
351
374
  try {
352
375
  const unpacked = this.#unpack(message);
353
376
  if (!unpacked || unpacked.origin === this.serverId) return;
377
+ if (unpacked.origin.endsWith(WebSocketRedisAdaptor.#legacyMark)) return;
354
378
  if (unpacked.kind === WebSocketRedisAdaptor.#kind.change) {
355
379
  this.#changeHandler?.(JSON.parse(unpacked.payload.toString()) as LiveChange);
356
380
  return;
@@ -367,8 +391,8 @@ export class WebSocketRedisAdaptor
367
391
  }
368
392
  }
369
393
 
370
- #pack(kind: "json" | "bytes" | "change", roomId: string, payload: string | Uint8Array): Buffer {
371
- const origin = Buffer.from(this.serverId, "utf-8");
394
+ #pack(kind: "json" | "bytes" | "change", roomId: string, payload: string | Uint8Array, from = this.serverId): Buffer {
395
+ const origin = Buffer.from(from, "utf-8");
372
396
  const room = Buffer.from(roomId, "utf-8");
373
397
  const header = Buffer.alloc(2 + 2 + origin.length + 2 + room.length);
374
398
  let offset = header.writeUInt8(WebSocketRedisAdaptor.#version, 0);
@@ -408,7 +432,9 @@ export class WebSocketRedisAdaptor
408
432
 
409
433
  #addToBuffer(buffered: BufferedMessage): void {
410
434
  if (buffered.coalesce) {
411
- const stale = this.#buffer.findIndex((item) => item.coalesce && item.roomId === buffered.roomId);
435
+ const stale = this.#buffer.findIndex(
436
+ (item) => item.coalesce && item.roomId === buffered.roomId && item.channel === buffered.channel,
437
+ );
412
438
  if (stale >= 0) this.#buffer.splice(stale, 1);
413
439
  }
414
440
  if (this.#buffer.length >= this.#maxBufferSize) {
@@ -422,8 +448,11 @@ export class WebSocketRedisAdaptor
422
448
  this.#buffer.push(...failed);
423
449
  this.#buffer.sort((a, b) => a.seq - b.seq);
424
450
  const newest = new Map<string, number>();
425
- for (const { coalesce, roomId, seq } of this.#buffer) if (coalesce) newest.set(roomId, seq);
426
- const kept = this.#buffer.filter(({ coalesce, roomId, seq }) => !coalesce || newest.get(roomId) === seq);
451
+ for (const { coalesce, channel, roomId, seq } of this.#buffer)
452
+ if (coalesce) newest.set(`${channel}\0${roomId}`, seq);
453
+ const kept = this.#buffer.filter(
454
+ ({ coalesce, channel, roomId, seq }) => !coalesce || newest.get(`${channel}\0${roomId}`) === seq,
455
+ );
427
456
  const over = Math.max(0, kept.length - this.#maxBufferSize);
428
457
  this.#buffer.splice(0, this.#buffer.length, ...kept.slice(over));
429
458
  if (over) this.logger.warn(`Buffer full, dropping the oldest ${over} messages`);
@@ -10,8 +10,13 @@ export interface AgentUsageReport {
10
10
  account: unknown;
11
11
  turn: AgentTurnContext;
12
12
  model: string | null;
13
- /** On a failed or aborted turn, what the provider counted before it ended; zero where it counted nothing. */
13
+ /** On a failed or aborted turn, what the provider spent before it ended; zero where it spent nothing. */
14
14
  usage: LlmUsage;
15
+ /**
16
+ * Some of `usage` is the framework's estimate, not the provider's count: a stream cut short sends no counts of its
17
+ * own, so what was sent and streamed stands in for them, erring high.
18
+ */
19
+ estimated?: boolean;
15
20
  /** `aborted` is a turn whose caller went away before the answer, `failed` one the provider or the network ended. */
16
21
  outcome: AgentTurnOutcome;
17
22
  }
@@ -108,16 +113,19 @@ export class AgentMeter {
108
113
  try {
109
114
  result = await turn();
110
115
  } catch (error) {
111
- const spent = LlmSpend.of(error);
112
- AgentMeter.#report(
113
- {
114
- account,
115
- turn: context,
116
- model: spent?.model ?? null,
117
- usage: spent?.usage ?? AgentMeter.#unspent(),
118
- outcome: signal?.aborted ? "aborted" : "failed",
119
- },
120
- settled,
116
+ const outcome = signal?.aborted ? "aborted" : "failed";
117
+ void LlmSpend.settled(error).then((spent) =>
118
+ AgentMeter.#report(
119
+ {
120
+ account,
121
+ turn: context,
122
+ model: spent?.model ?? null,
123
+ usage: spent?.usage ?? AgentMeter.#unspent(),
124
+ ...(spent?.estimated ? { estimated: true } : {}),
125
+ outcome,
126
+ },
127
+ settled,
128
+ ),
121
129
  );
122
130
  throw error;
123
131
  }
@@ -1,6 +1,7 @@
1
1
  import type { PromiseOrObject } from "akanjs/base";
2
2
  import { Err } from "akanjs/dictionary";
3
3
  import type { LlmTurnRequest } from "akanjs/service";
4
+ import { AgentMeter } from "./agentMeter";
4
5
 
5
6
  /** One relayed turn, the same object from the request policy through the quota to the usage report. */
6
7
  export interface AgentTurnContext {
@@ -13,8 +14,11 @@ export interface AgentTurnContext {
13
14
  ip: string | null;
14
15
  }
15
16
 
16
- /** @deprecated Use `AgentTurnContext`, which also carries the turn's `id` and `headers`. */
17
- export type AgentRequestContext = AgentTurnContext;
17
+ /** @deprecated Use `AgentTurnContext`; `apply` still takes this shape and gives it a fresh `id` and empty `headers`. */
18
+ export interface AgentRequestContext {
19
+ account: unknown;
20
+ ip: string | null;
21
+ }
18
22
 
19
23
  export type AgentRequestPolicy = (
20
24
  request: LlmTurnRequest,
@@ -47,9 +51,12 @@ export class AgentRelayPolicy {
47
51
  AgentRelayPolicy.#policy = policy;
48
52
  }
49
53
 
50
- static async apply(request: LlmTurnRequest, context: AgentTurnContext): Promise<LlmTurnRequest> {
54
+ static async apply(
55
+ request: LlmTurnRequest,
56
+ context: AgentTurnContext | AgentRequestContext,
57
+ ): Promise<LlmTurnRequest> {
51
58
  const policy = AgentRelayPolicy.#policy ?? AgentRelayPolicy.#defaultPolicy;
52
- return await policy(request, context);
59
+ return await policy(request, "id" in context ? context : AgentMeter.turnOf(context.account, { ip: context.ip }));
53
60
  }
54
61
 
55
62
  static readonly #defaultPolicy: AgentRequestPolicy = (request) => AgentRelayPolicy.capped(request);
@@ -41,7 +41,6 @@ export class AgentTurnStream {
41
41
  return { message, ...(data ? { data } : {}), ...(overflow ? { overflow } : {}) };
42
42
  }
43
43
 
44
- /** A reader that goes away aborts `run`'s signal, so the provider stops spending on an answer nobody will read. */
45
44
  static response(run: RunTurn): Response {
46
45
  const abort = new AbortController();
47
46
  const stream = new EventStream(() => abort.abort());
@@ -1,11 +1,11 @@
1
- import { type LlmAccepts, type LlmTurnRequest } from "./predefinedAdaptor/llm.adaptor";
1
+ import { type LlmAccepts, type LlmAdaptor, type LlmTurnRequest } from "./predefinedAdaptor/llm.adaptor";
2
2
  export interface AgentTurnOptions {
3
3
  onDelta?: (delta: string) => void;
4
4
  preamble?: string | false;
5
5
  signal?: AbortSignal;
6
6
  }
7
7
  declare const AgentService_base: import("./serve.d.ts").ServiceCls<"agent", {}, {
8
- llm: import("./injectInfo.d.ts").InjectInfo<"plug", import("./predefinedAdaptor.d.ts").LlmAdaptor, never, never>;
8
+ llm: import("./injectInfo.d.ts").InjectInfo<"plug", LlmAdaptor, never, never>;
9
9
  }>;
10
10
  export declare class AgentService extends AgentService_base {
11
11
  runTurn(request: LlmTurnRequest, options?: AgentTurnOptions | ((delta: string) => void)): Promise<{
@@ -22,6 +22,7 @@ export declare class AgentService extends AgentService_base {
22
22
  * carves the batching rule: a call batched behind `navigate` was written against the screen being left.
23
23
  */
24
24
  static readonly preamble: string;
25
+ private static answered;
25
26
  static instructed(request: LlmTurnRequest, preamble?: string | false): LlmTurnRequest;
26
27
  /** Provider mappings read `text` and drop `error`, so a failed turn is folded into its text or retried blind. */
27
28
  static explained(request: LlmTurnRequest): LlmTurnRequest;
@@ -94,7 +94,8 @@ export interface LlmUsage {
94
94
  export interface LlmAdaptor {
95
95
  /**
96
96
  * `onDelta` opts into streaming and the full answer still resolves; an adaptor may ignore it. `signal` is aborted
97
- * once nobody waits for the answer, so the provider call should take it.
97
+ * once nobody reads the answer, so the provider call should take it. The relay sends it with `onDelta` only: a
98
+ * plain call runs to its end, where the provider's counts arrive.
98
99
  */
99
100
  chat(request: LlmTurnRequest, onDelta?: (delta: string) => void, signal?: AbortSignal): Promise<LlmTurnAnswer | null>;
100
101
  /** Omitted means text only. */
@@ -2,9 +2,21 @@ import type { LlmUsage } from "./llm.adaptor";
2
2
  export interface LlmSpent {
3
3
  usage?: LlmUsage;
4
4
  model?: string;
5
+ /** Some of `usage` is the framework's estimate: the call ended before the provider sent counts of its own. */
6
+ estimated?: boolean;
5
7
  }
6
8
  export declare class LlmSpend {
7
9
  #private;
10
+ static readonly bytesPerToken = 3;
11
+ static readonly imageTokens = 1600;
8
12
  static attach<E>(error: E, spent: LlmSpent): E;
9
13
  static of(error: unknown): LlmSpent | null;
14
+ static settled(error: unknown): Promise<LlmSpent | null>;
15
+ static outlast<T>(call: Promise<T>, signal: AbortSignal, spentOf: (answer: T) => LlmSpent): Promise<T>;
16
+ static estimate(counted: LlmUsage | undefined, { prompt, streamed }: {
17
+ prompt?: unknown;
18
+ streamed?: string;
19
+ }): LlmSpent;
20
+ static tokensOf(text: string): number;
21
+ static promptOf(request: unknown): number;
10
22
  }
@@ -6,8 +6,13 @@ export interface AgentUsageReport {
6
6
  account: unknown;
7
7
  turn: AgentTurnContext;
8
8
  model: string | null;
9
- /** On a failed or aborted turn, what the provider counted before it ended; zero where it counted nothing. */
9
+ /** On a failed or aborted turn, what the provider spent before it ended; zero where it spent nothing. */
10
10
  usage: LlmUsage;
11
+ /**
12
+ * Some of `usage` is the framework's estimate, not the provider's count: a stream cut short sends no counts of its
13
+ * own, so what was sent and streamed stands in for them, erring high.
14
+ */
15
+ estimated?: boolean;
11
16
  /** `aborted` is a turn whose caller went away before the answer, `failed` one the provider or the network ended. */
12
17
  outcome: AgentTurnOutcome;
13
18
  }
@@ -10,8 +10,11 @@ export interface AgentTurnContext {
10
10
  account: unknown;
11
11
  ip: string | null;
12
12
  }
13
- /** @deprecated Use `AgentTurnContext`, which also carries the turn's `id` and `headers`. */
14
- export type AgentRequestContext = AgentTurnContext;
13
+ /** @deprecated Use `AgentTurnContext`; `apply` still takes this shape and gives it a fresh `id` and empty `headers`. */
14
+ export interface AgentRequestContext {
15
+ account: unknown;
16
+ ip: string | null;
17
+ }
15
18
  export type AgentRequestPolicy = (request: LlmTurnRequest, context: AgentTurnContext) => PromiseOrObject<LlmTurnRequest>;
16
19
  export interface AgentRequestLimits {
17
20
  messages: number;
@@ -27,6 +30,6 @@ export declare class AgentRelayPolicy {
27
30
  static readonly defaultLimits: Readonly<AgentRequestLimits>;
28
31
  /** `null` restores the default, `capped(defaultLimits)`; `(request) => request` relays every request untouched. */
29
32
  static use(policy: AgentRequestPolicy | null): void;
30
- static apply(request: LlmTurnRequest, context: AgentTurnContext): Promise<LlmTurnRequest>;
33
+ static apply(request: LlmTurnRequest, context: AgentTurnContext | AgentRequestContext): Promise<LlmTurnRequest>;
31
34
  static capped(request: LlmTurnRequest, limits?: Partial<AgentRequestLimits>): LlmTurnRequest;
32
35
  }
@@ -18,7 +18,6 @@ export declare class AgentTurnStream {
18
18
  limit?: number;
19
19
  };
20
20
  };
21
- /** A reader that goes away aborts `run`'s signal, so the provider stops spending on an answer nobody will read. */
22
21
  static response(run: RunTurn): Response;
23
22
  }
24
23
  export {};