akanjs 3.2.0-rc.4 → 3.2.0-rc.6

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/CONTRIBUTING.md +23 -0
  3. package/client/makePageProto.tsx +26 -2
  4. package/package.json +1 -1
  5. package/server/akanOption.ts +1 -1
  6. package/server/resolver/signal.resolver.ts +48 -50
  7. package/server/resolver/websocketOf.ts +22 -0
  8. package/service/agent.service.ts +15 -4
  9. package/service/predefinedAdaptor/anthropicLlm.ts +23 -10
  10. package/service/predefinedAdaptor/index.ts +1 -0
  11. package/service/predefinedAdaptor/llm.adaptor.ts +12 -2
  12. package/service/predefinedAdaptor/llmSpend.ts +19 -0
  13. package/service/predefinedAdaptor/openaiLlm.ts +16 -8
  14. package/service/predefinedAdaptor/websocket.adaptor.ts +122 -25
  15. package/signal/agent.signal.ts +22 -5
  16. package/signal/agentMeter.ts +74 -15
  17. package/signal/agentRelayPolicy.ts +11 -3
  18. package/signal/agentTurnStream.ts +8 -6
  19. package/signal/endpointErrorContract.ts +11 -0
  20. package/signal/middleware.ts +6 -2
  21. package/signal/signalContext.ts +2 -7
  22. package/types/client/makePageProto.d.ts +27 -26082
  23. package/types/server/akanOption.d.ts +1 -1
  24. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  25. package/types/server/resolver/signal.resolver.d.ts +1 -1
  26. package/types/server/resolver/websocketOf.d.ts +2 -0
  27. package/types/service/agent.service.d.ts +7 -2
  28. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +1 -1
  29. package/types/service/predefinedAdaptor/index.d.ts +1 -0
  30. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +8 -2
  31. package/types/service/predefinedAdaptor/llmSpend.d.ts +10 -0
  32. package/types/service/predefinedAdaptor/openaiLlm.d.ts +1 -1
  33. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +7 -2
  34. package/types/signal/agentMeter.d.ts +20 -2
  35. package/types/signal/agentRelayPolicy.d.ts +10 -3
  36. package/types/signal/agentTurnStream.d.ts +2 -1
  37. package/types/signal/endpointErrorContract.d.ts +3 -0
@@ -6,9 +6,11 @@ import {
6
6
  type LlmOption,
7
7
  type LlmTurnAnswer,
8
8
  type LlmTurnRequest,
9
+ llmCallSignal,
9
10
  llmProviderOf,
10
11
  } from "./llm.adaptor";
11
12
  import { LlmOverflow } from "./llmOverflow";
13
+ import { LlmSpend } from "./llmSpend";
12
14
  import { type OpenaiAnswer, OpenaiDialect } from "./openaiDialect";
13
15
 
14
16
  /**
@@ -46,7 +48,11 @@ export class OpenaiLlm
46
48
  return !host || llmProviderOf(host) === llmProviderOf(OpenaiLlm.defaultHost) ? { image: true } : undefined;
47
49
  }
48
50
 
49
- async chat(request: LlmTurnRequest, onDelta?: (delta: string) => void): Promise<LlmTurnAnswer | null> {
51
+ async chat(
52
+ request: LlmTurnRequest,
53
+ onDelta?: (delta: string) => void,
54
+ signal?: AbortSignal,
55
+ ): Promise<LlmTurnAnswer | null> {
50
56
  const model = request.model || this.llmOption.model;
51
57
  if (!this.llmOption.apiKey || !model) {
52
58
  this.logger.warn(
@@ -60,39 +66,41 @@ export class OpenaiLlm
60
66
  const answer = await this.#api<OpenaiAnswer>(
61
67
  "/chat/completions",
62
68
  OpenaiDialect.requestBody(model, request, { accepts }),
69
+ signal,
63
70
  );
64
71
  return { ...OpenaiDialect.turnAnswer(answer), model };
65
72
  }
66
73
  const body = await this.#apiStream(
67
74
  "/chat/completions",
68
75
  OpenaiDialect.requestBody(model, request, { accepts, stream: true }),
76
+ signal,
69
77
  );
70
78
  return { ...(await OpenaiDialect.consumeStream(body, onDelta)), model };
71
79
  } catch (error) {
72
80
 
73
- this.logger.error(`LLM turn failed: ${error instanceof Error ? error.message : String(error)}`);
74
- throw error;
81
+ if (!signal?.aborted)
82
+ this.logger.error(`LLM turn failed: ${error instanceof Error ? error.message : String(error)}`);
83
+ throw LlmSpend.attach(error, { model });
75
84
  }
76
85
  }
77
86
 
78
- async #api<T>(path: string, body: object): Promise<T> {
87
+ async #api<T>(path: string, body: object, signal?: AbortSignal): Promise<T> {
79
88
  const response = await fetch(`${this.#host}${path}`, {
80
89
  method: "POST",
81
90
  headers: { "content-type": "application/json", authorization: `Bearer ${this.llmOption.apiKey}` },
82
91
  body: JSON.stringify(body),
83
-
84
- signal: AbortSignal.timeout(120_000),
92
+ signal: llmCallSignal(signal),
85
93
  });
86
94
  if (!response.ok) throw await OpenaiLlm.refusal(this.#host, response);
87
95
  return (await response.json()) as T;
88
96
  }
89
97
 
90
- async #apiStream(path: string, body: object): Promise<ReadableStream<Uint8Array>> {
98
+ async #apiStream(path: string, body: object, signal?: AbortSignal): Promise<ReadableStream<Uint8Array>> {
91
99
  const response = await fetch(`${this.#host}${path}`, {
92
100
  method: "POST",
93
101
  headers: { "content-type": "application/json", authorization: `Bearer ${this.llmOption.apiKey}` },
94
102
  body: JSON.stringify(body),
95
- signal: AbortSignal.timeout(120_000),
103
+ signal: llmCallSignal(signal),
96
104
  });
97
105
  if (!response.ok || !response.body) throw await OpenaiLlm.refusal(this.#host, response);
98
106
  return response.body;
@@ -23,6 +23,11 @@ export interface WebsocketPublishOption {
23
23
  coalesce?: boolean;
24
24
  }
25
25
 
26
+ export interface WebsocketJoinOption {
27
+ /** The model a live room is routed by: its events come from that model's changes, never from a `publish`. */
28
+ live?: string;
29
+ }
30
+
26
31
  export interface WebsocketAdaptor {
27
32
  /** Across every server instance. */
28
33
  publish(roomId: string, data: unknown, option?: WebsocketPublishOption): void;
@@ -35,7 +40,8 @@ export interface WebsocketAdaptor {
35
40
  onChange?(handler: LiveChangeHandler): void;
36
41
  /** The models this server holds live rooms for, each time that changes, so changes to the rest pass it by. */
37
42
  reportLiveModels?(models: string[]): void;
38
- joinRoom(ws: Bun.ServerWebSocket<unknown>, room: string): Promise<void>;
43
+ /** Resolves once what another server publishes to the room reaches this one, or sooner if that link is down or stalls. */
44
+ joinRoom(ws: Bun.ServerWebSocket<unknown>, room: string, option?: WebsocketJoinOption): Promise<void>;
39
45
  leaveRoom(ws: Bun.ServerWebSocket<unknown>, room: string): Promise<void>;
40
46
  leaveAllRooms(ws: Bun.ServerWebSocket<unknown>): Promise<void>;
41
47
  registerSocket(ws: Bun.ServerWebSocket<unknown>, meta?: Record<string, string>): Promise<void>;
@@ -43,12 +49,24 @@ export interface WebsocketAdaptor {
43
49
  }
44
50
 
45
51
  interface BufferedMessage {
52
+ channel: string;
46
53
  roomId: string;
47
54
  message: Buffer;
48
55
  coalesce: boolean;
49
56
  seq: number;
50
57
  }
51
58
 
59
+ interface HeldRoom {
60
+ sockets: Set<string>;
61
+ channel: string;
62
+ }
63
+
64
+ interface ChannelHold {
65
+ rooms: number;
66
+ reply?: Promise<void>;
67
+ confirmed: boolean;
68
+ }
69
+
52
70
  export class WebSocketRedisAdaptor
53
71
  extends adapt("wsRedis", ({ plug, env }) => ({
54
72
  channelPrefix: plug(RedisCache, (cache) => cache.keyPrefix),
@@ -69,10 +87,15 @@ export class WebSocketRedisAdaptor
69
87
 
70
88
  static readonly #version = 1;
71
89
  static readonly #kind = { json: 0x6a, bytes: 0x62, change: 0x63 } as const;
90
+
91
+ static readonly #shards = 16_384;
92
+
93
+ static readonly #subscribeTimeoutMs = 3_000;
72
94
  readonly #buffer: BufferedMessage[] = [];
73
95
  readonly #maxBufferSize = 10000;
74
- readonly #roomSockets = new Map<string, Set<string>>();
96
+ readonly #rooms = new Map<string, HeldRoom>();
75
97
  readonly #socketRooms = new Map<string, Set<string>>();
98
+ readonly #channels = new Map<string, ChannelHold>();
76
99
  #eventHandler: WsRedisEventHandler | null = null;
77
100
  #changeHandler: LiveChangeHandler | null = null;
78
101
  #recoveryHandler: (() => void) | null = null;
@@ -85,10 +108,15 @@ export class WebSocketRedisAdaptor
85
108
  #subscriberReady = false;
86
109
  /** Whether the subscriber has ever been up, so the first `ready` is a start rather than a recovery. */
87
110
  #subscriberStarted = false;
111
+ readonly #lossWaiters = new Set<() => void>();
88
112
  #warnedVersion = false;
89
113
 
90
- get #channel() {
91
- return `${this.channelPrefix}ws:broadcast`;
114
+ #roomChannel(roomId: string) {
115
+ return `${this.channelPrefix}ws:room:${Bun.hash.crc32(roomId) % WebSocketRedisAdaptor.#shards}`;
116
+ }
117
+
118
+ #changeChannel(refName: string) {
119
+ return `${this.channelPrefix}ws:change:${refName}`;
92
120
  }
93
121
 
94
122
  override async onInit() {
@@ -107,15 +135,20 @@ export class WebSocketRedisAdaptor
107
135
  this.logger.warn(`Publisher error: ${err.message}`);
108
136
  });
109
137
 
138
+ this.subscriber.options.autoResubscribe = false;
139
+
110
140
  this.subscriber.on("error", (err: Error) => {
111
141
  this.logger.warn(`Subscriber error: ${err.message}`);
112
142
  });
113
143
  this.subscriber.on("close", () => {
144
+ this.#loseSubscriber();
114
145
  if (!this.#subscriberReady) return;
115
146
  this.#subscriberReady = false;
116
147
  this.logger.warn("Subscriber disconnected; cross-server events are being missed until it returns");
117
148
  });
118
149
  this.subscriber.on("ready", () => {
150
+
151
+ for (const [channel, hold] of this.#channels) this.#subscribe(channel, hold);
119
152
  const recovering = !this.#subscriberReady && this.#subscriberStarted;
120
153
  this.#subscriberReady = true;
121
154
  this.#subscriberStarted = true;
@@ -126,20 +159,13 @@ export class WebSocketRedisAdaptor
126
159
 
127
160
  await this.publisher.connect();
128
161
  await this.subscriber.connect();
129
- await this.subscriber.subscribe(this.#channel, (err?: Error | null) => {
130
- if (err) this.logger.warn(`Subscribe error: ${err.message}`);
131
- });
132
162
  this.subscriber.on("messageBuffer", (_channel: Buffer, message: Buffer) => this.#receive(message));
133
163
  this.logger.verbose(`WebSocket Redis adaptor initialized (serverId: ${this.serverId})`);
134
164
  }
135
165
 
136
166
  override async onDestroy() {
137
- if (this.subscriber) {
138
- try {
139
- await this.subscriber.unsubscribe(this.#channel);
140
- } catch {}
141
- this.subscriber.disconnect();
142
- }
167
+ this.#loseSubscriber();
168
+ this.subscriber.disconnect();
143
169
  if (this.publisher) {
144
170
  this.#cancelRetry();
145
171
 
@@ -152,8 +178,9 @@ export class WebSocketRedisAdaptor
152
178
  this.#recoveryHandler = null;
153
179
  this.#publisherReady = false;
154
180
  this.#subscriberReady = false;
155
- this.#roomSockets.clear();
181
+ this.#rooms.clear();
156
182
  this.#socketRooms.clear();
183
+ this.#channels.clear();
157
184
  this.logger.verbose("WebSocket Redis adaptor destroyed");
158
185
  }
159
186
 
@@ -164,11 +191,18 @@ export class WebSocketRedisAdaptor
164
191
  this.logger.warn(`Nothing to publish to ${roomId}: the payload has no JSON form`);
165
192
  return;
166
193
  }
167
- this.#send({ roomId, message: this.#pack(bytes ? "bytes" : "json", roomId, payload), coalesce, seq: this.#sent++ });
194
+ this.#send({
195
+ channel: this.#roomChannel(roomId),
196
+ roomId,
197
+ message: this.#pack(bytes ? "bytes" : "json", roomId, payload),
198
+ coalesce,
199
+ seq: this.#sent++,
200
+ });
168
201
  }
169
202
 
170
203
  publishChange(change: LiveChange): void {
171
204
  this.#send({
205
+ channel: this.#changeChannel(change.refName),
172
206
  roomId: "",
173
207
  message: this.#pack("change", "", JSON.stringify(change)),
174
208
  coalesce: false,
@@ -186,7 +220,7 @@ export class WebSocketRedisAdaptor
186
220
  void this.#flushBuffer();
187
221
  return;
188
222
  }
189
- this.publisher.publish(this.#channel, buffered.message).catch((err: Error) => {
223
+ this.publisher.publish(buffered.channel, buffered.message).catch((err: Error) => {
190
224
  this.logger.warn(`Publish failed, buffering: ${err.message}`);
191
225
  this.#requeue([buffered]);
192
226
  void this.#flushBuffer();
@@ -205,14 +239,19 @@ export class WebSocketRedisAdaptor
205
239
  this.#recoveryHandler = handler;
206
240
  }
207
241
 
208
- async joinRoom(ws: Bun.ServerWebSocket<unknown>, room: string): Promise<void> {
242
+ async joinRoom(ws: Bun.ServerWebSocket<unknown>, room: string, { live }: WebsocketJoinOption = {}): Promise<void> {
209
243
  const socketId = this.#getSocketId(ws);
210
- const sockets = this.#roomSockets.get(room) ?? new Set<string>();
211
- sockets.add(socketId);
212
- this.#roomSockets.set(room, sockets);
244
+ let held = this.#rooms.get(room);
245
+ if (!held) {
246
+ held = { sockets: new Set(), channel: live ? this.#changeChannel(live) : this.#roomChannel(room) };
247
+ this.#rooms.set(room, held);
248
+ this.#hold(held.channel);
249
+ }
250
+ held.sockets.add(socketId);
213
251
  const rooms = this.#socketRooms.get(socketId) ?? new Set<string>();
214
252
  rooms.add(room);
215
253
  this.#socketRooms.set(socketId, rooms);
254
+ await this.#awaitChannel(held.channel);
216
255
  }
217
256
 
218
257
  async leaveRoom(ws: Bun.ServerWebSocket<unknown>, room: string): Promise<void> {
@@ -245,9 +284,67 @@ export class WebSocketRedisAdaptor
245
284
  }
246
285
 
247
286
  #forget(socketId: string, room: string) {
248
- const sockets = this.#roomSockets.get(room);
249
- sockets?.delete(socketId);
250
- if (sockets?.size === 0) this.#roomSockets.delete(room);
287
+ const held = this.#rooms.get(room);
288
+ if (!held?.sockets.delete(socketId) || held.sockets.size) return;
289
+ this.#rooms.delete(room);
290
+ this.#release(held.channel);
291
+ }
292
+
293
+ #hold(channel: string) {
294
+ const hold = this.#channels.get(channel) ?? { rooms: 0, confirmed: false };
295
+ hold.rooms += 1;
296
+ this.#channels.set(channel, hold);
297
+ }
298
+
299
+ #release(channel: string) {
300
+ const hold = this.#channels.get(channel);
301
+ if (!hold) return;
302
+ hold.rooms -= 1;
303
+ if (hold.rooms > 0) return;
304
+ this.#channels.delete(channel);
305
+ this.subscriber.unsubscribe(channel).catch((err: Error) => {
306
+ this.logger.warn(`Unsubscribe from ${channel} failed: ${err.message}`);
307
+ });
308
+ }
309
+
310
+ async #awaitChannel(channel: string) {
311
+ const hold = this.#channels.get(channel);
312
+ if (!hold || hold.confirmed) return;
313
+ const reply = hold.reply ?? this.#subscribe(channel, hold);
314
+ if (!this.#subscriberReady) return;
315
+
316
+ let wake = () => {};
317
+ const woken = new Promise<void>((resolve) => {
318
+ wake = resolve;
319
+ });
320
+ this.#lossWaiters.add(wake);
321
+ const timer = setTimeout(wake, WebSocketRedisAdaptor.#subscribeTimeoutMs);
322
+ try {
323
+ await Promise.race([reply, woken]);
324
+ } finally {
325
+ clearTimeout(timer);
326
+ this.#lossWaiters.delete(wake);
327
+ }
328
+ }
329
+
330
+ #loseSubscriber() {
331
+ for (const wake of this.#lossWaiters) wake();
332
+ this.#lossWaiters.clear();
333
+ }
334
+
335
+ #subscribe(channel: string, hold: ChannelHold): Promise<void> {
336
+ const reply: Promise<void> = this.subscriber.subscribe(channel).then(
337
+ () => {
338
+ if (hold.reply === reply) hold.confirmed = true;
339
+ },
340
+ (err: Error) => {
341
+ this.logger.warn(`Subscribe to ${channel} failed: ${err.message}`);
342
+ if (hold.reply === reply) hold.reply = undefined;
343
+ },
344
+ );
345
+ hold.reply = reply;
346
+ hold.confirmed = false;
347
+ return reply;
251
348
  }
252
349
 
253
350
  #receive(message: Buffer) {
@@ -259,7 +356,7 @@ export class WebSocketRedisAdaptor
259
356
  return;
260
357
  }
261
358
 
262
- if (!this.#eventHandler || !this.#roomSockets.has(unpacked.roomId)) return;
359
+ if (!this.#eventHandler || !this.#rooms.has(unpacked.roomId)) return;
263
360
  const data =
264
361
  unpacked.kind === WebSocketRedisAdaptor.#kind.bytes
265
362
  ? new Uint8Array(unpacked.payload)
@@ -346,7 +443,7 @@ export class WebSocketRedisAdaptor
346
443
  this.logger.verbose(`Flushing ${this.#buffer.length} buffered messages`);
347
444
  const batch = this.#buffer.splice(0);
348
445
  const results = await Promise.allSettled(
349
- batch.map((buffered) => this.publisher.publish(this.#channel, buffered.message)),
446
+ batch.map((buffered) => this.publisher.publish(buffered.channel, buffered.message)),
350
447
  );
351
448
  const failed = batch.filter((_, idx) => results[idx].status === "rejected");
352
449
  if (!failed.length) {
@@ -25,6 +25,8 @@ export class AgentEndpoint extends endpoint(srv.agent, ({ mutation }) => ({
25
25
  .with(CallerAccount, { nullable: true })
26
26
  .with(Ip, { nullable: true })
27
27
  .exec(async function (messages, tools, context, instructions, request, account, ip) {
28
+ const http = request as Bun.BunRequest;
29
+ const scope = AgentMeter.turnOf(account, { headers: http.headers, ip });
28
30
 
29
31
  const turn = await AgentRelayPolicy.apply(
30
32
  {
@@ -33,13 +35,28 @@ export class AgentEndpoint extends endpoint(srv.agent, ({ mutation }) => ({
33
35
  context: context as unknown as AgentWireContext[],
34
36
  ...(instructions ? { instructions } : {}),
35
37
  },
36
- { account, ip },
38
+ scope,
37
39
  );
38
- if (AgentTurnStream.wants(request as Bun.BunRequest))
39
- return AgentTurnStream.response((onDelta) =>
40
- AgentMeter.run(account, () => this.agentService.runTurn(turn, onDelta)),
40
+ if (AgentTurnStream.wants(http))
41
+ return AgentTurnStream.response((onDelta, signal) =>
42
+ AgentMeter.run(account, () => this.agentService.runTurn(turn, { onDelta, signal }), {
43
+ turn: scope,
44
+ request: turn,
45
+ signal,
46
+ }),
41
47
  ) as unknown as AgentTurn;
42
- return await AgentMeter.run(account, () => this.agentService.runTurn(turn));
48
+ try {
49
+ return await AgentMeter.run(account, () => this.agentService.runTurn(turn, { signal: http.signal }), {
50
+ turn: scope,
51
+ request: turn,
52
+ signal: http.signal,
53
+ });
54
+ } catch (error) {
55
+
56
+ if (http.signal.aborted)
57
+ return new Response(null, { status: 499, headers: { "cache-control": "no-store" } }) as unknown as AgentTurn;
58
+ throw error;
59
+ }
43
60
  }),
44
61
  })) {}
45
62
 
@@ -1,16 +1,32 @@
1
1
  import type { PromiseOrObject } from "akanjs/base";
2
2
  import { Logger } from "akanjs/common";
3
3
  import { Err } from "akanjs/dictionary";
4
- import type { LlmUsage } from "akanjs/service";
4
+ import { LlmSpend, type LlmTurnRequest, type LlmUsage } from "akanjs/service";
5
+ import type { AgentTurnContext } from "./agentRelayPolicy";
6
+
7
+ export type AgentTurnOutcome = "ok" | "failed" | "aborted";
5
8
 
6
9
  export interface AgentUsageReport {
7
10
  account: unknown;
11
+ turn: AgentTurnContext;
8
12
  model: string | null;
13
+ /** On a failed or aborted turn, what the provider counted before it ended; zero where it counted nothing. */
9
14
  usage: LlmUsage;
15
+ /** `aborted` is a turn whose caller went away before the answer, `failed` one the provider or the network ended. */
16
+ outcome: AgentTurnOutcome;
10
17
  }
11
18
 
12
19
  export interface AgentQuotaCheck {
13
20
  account: unknown;
21
+ turn: AgentTurnContext;
22
+ /** What the request policy returned; absent when server code meters a turn without naming it. */
23
+ request?: LlmTurnRequest;
24
+ }
25
+
26
+ export interface AgentMeterScope {
27
+ turn?: AgentTurnContext;
28
+ request?: LlmTurnRequest;
29
+ signal?: AbortSignal;
14
30
  }
15
31
 
16
32
  export type AgentUsageHook = (report: AgentUsageReport) => PromiseOrObject<void>;
@@ -40,13 +56,23 @@ export class AgentMeter {
40
56
  if (serial !== undefined) AgentMeter.#serial = serial;
41
57
  }
42
58
 
43
- static async run<T extends { usage?: LlmUsage; model?: string }>(account: unknown, turn: () => Promise<T>) {
59
+ static turnOf(account: unknown, { headers, ip }: { headers?: Headers; ip?: string | null } = {}): AgentTurnContext {
60
+ return { id: crypto.randomUUID(), headers: headers ?? new Headers(), account, ip: ip ?? null };
61
+ }
62
+
63
+ static async run<T extends { usage?: LlmUsage; model?: string } | null>(
64
+ account: unknown,
65
+ turn: () => Promise<T>,
66
+ scope: AgentMeterScope = {},
67
+ ) {
68
+ const context = scope.turn ?? AgentMeter.turnOf(account);
69
+ const check: AgentQuotaCheck = { account, turn: context, ...(scope.request ? { request: scope.request } : {}) };
44
70
  const quota = AgentMeter.#quota;
45
- if (!quota) return await AgentMeter.#spend(account, turn, () => undefined);
71
+ if (!quota) return await AgentMeter.#spend(check, turn, scope.signal, () => undefined);
46
72
  const key = AgentMeter.#serial ? AgentMeter.#keyOf(account) : null;
47
73
  if (key === null) {
48
- if (!(await quota({ account }))) throw new Err("agent.error.quotaExceeded");
49
- return await AgentMeter.#spend(account, turn, () => undefined);
74
+ if (!(await quota(check))) throw new Err("agent.error.quotaExceeded");
75
+ return await AgentMeter.#spend(check, turn, scope.signal, () => undefined);
50
76
  }
51
77
 
52
78
  const ahead = AgentMeter.#lanes.get(key);
@@ -64,29 +90,63 @@ export class AgentMeter {
64
90
  };
65
91
  try {
66
92
  await ahead;
67
- if (!(await quota({ account }))) throw new Err("agent.error.quotaExceeded");
68
- return await AgentMeter.#spend(account, turn, release);
93
+ if (!(await quota(check))) throw new Err("agent.error.quotaExceeded");
69
94
  } catch (error) {
70
95
  release();
71
96
  throw error;
72
97
  }
98
+ return await AgentMeter.#spend(check, turn, scope.signal, release);
73
99
  }
74
100
 
75
- static async #spend<T extends { usage?: LlmUsage; model?: string }>(
76
- account: unknown,
101
+ static async #spend<T extends { usage?: LlmUsage; model?: string } | null>(
102
+ { account, turn: context }: AgentQuotaCheck,
77
103
  turn: () => Promise<T>,
104
+ signal: AbortSignal | undefined,
78
105
  settled: () => void,
79
106
  ) {
80
- const result = await turn();
107
+ let result: T;
108
+ try {
109
+ result = await turn();
110
+ } 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,
121
+ );
122
+ throw error;
123
+ }
124
+ AgentMeter.#report(
125
+ {
126
+ account,
127
+ turn: context,
128
+ model: result?.model ?? null,
129
+ usage: result?.usage ?? AgentMeter.#unspent(),
130
+ outcome: "ok",
131
+ },
132
+ settled,
133
+ );
134
+ return result;
135
+ }
136
+
137
+ static #unspent(): LlmUsage {
138
+ return { inputTokens: 0, outputTokens: 0, cachedTokens: 0 };
139
+ }
140
+
141
+ static #report(report: AgentUsageReport, settled: () => void) {
81
142
  const hook = AgentMeter.#usage;
82
- const usage = result.usage;
83
- if (!hook || !usage) {
143
+ if (!hook) {
84
144
  settled();
85
- return result;
145
+ return;
86
146
  }
87
147
 
88
148
  const reported = Promise.resolve()
89
- .then(() => hook({ account, model: result.model ?? null, usage }))
149
+ .then(() => hook(report))
90
150
  .catch((error: unknown) =>
91
151
  AgentMeter.#logger.error(`agent usage hook failed: ${error instanceof Error ? error.message : String(error)}`),
92
152
  );
@@ -105,7 +165,6 @@ export class AgentMeter {
105
165
  clearTimeout(timer);
106
166
  settled();
107
167
  });
108
- return result;
109
168
  }
110
169
 
111
170
  static #keyOf(account: unknown): string | null {
@@ -2,15 +2,23 @@ import type { PromiseOrObject } from "akanjs/base";
2
2
  import { Err } from "akanjs/dictionary";
3
3
  import type { LlmTurnRequest } from "akanjs/service";
4
4
 
5
- export interface AgentRequestContext {
5
+ /** One relayed turn, the same object from the request policy through the quota to the usage report. */
6
+ export interface AgentTurnContext {
7
+ /** Fresh per turn, so a quota hold and the usage that settles it pair up without guessing. */
8
+ id: string;
9
+ /** The turn's HTTP request headers, Authorization and Cookie included; empty for a turn no request carried. */
10
+ headers: Headers;
6
11
  /** What the account middleware resolved for this call, as the access guard saw it; `null` for an anonymous one. */
7
12
  account: unknown;
8
13
  ip: string | null;
9
14
  }
10
15
 
16
+ /** @deprecated Use `AgentTurnContext`, which also carries the turn's `id` and `headers`. */
17
+ export type AgentRequestContext = AgentTurnContext;
18
+
11
19
  export type AgentRequestPolicy = (
12
20
  request: LlmTurnRequest,
13
- context: AgentRequestContext,
21
+ context: AgentTurnContext,
14
22
  ) => PromiseOrObject<LlmTurnRequest>;
15
23
 
16
24
  export interface AgentRequestLimits {
@@ -39,7 +47,7 @@ export class AgentRelayPolicy {
39
47
  AgentRelayPolicy.#policy = policy;
40
48
  }
41
49
 
42
- static async apply(request: LlmTurnRequest, context: AgentRequestContext): Promise<LlmTurnRequest> {
50
+ static async apply(request: LlmTurnRequest, context: AgentTurnContext): Promise<LlmTurnRequest> {
43
51
  const policy = AgentRelayPolicy.#policy ?? AgentRelayPolicy.#defaultPolicy;
44
52
  return await policy(request, context);
45
53
  }
@@ -11,7 +11,7 @@ interface StreamedTurn {
11
11
  limits?: LlmLimits;
12
12
  }
13
13
 
14
- type RunTurn = (onDelta: (delta: string) => void) => Promise<StreamedTurn>;
14
+ type RunTurn = (onDelta: (delta: string) => void, signal: AbortSignal) => Promise<StreamedTurn>;
15
15
 
16
16
  export class AgentTurnStream {
17
17
  static #logger = new Logger("AgentTurnStream");
@@ -41,21 +41,22 @@ 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. */
44
45
  static response(run: RunTurn): Response {
45
-
46
- const stream = new EventStream(() => undefined);
47
- void AgentTurnStream.#deliver(stream, run);
46
+ const abort = new AbortController();
47
+ const stream = new EventStream(() => abort.abort());
48
+ void AgentTurnStream.#deliver(stream, run, abort.signal);
48
49
  return stream.response();
49
50
  }
50
51
 
51
- static async #deliver(stream: EventStream, run: RunTurn) {
52
+ static async #deliver(stream: EventStream, run: RunTurn, signal: AbortSignal) {
52
53
  try {
53
54
  let streamed = 0;
54
55
  const turn = await run((delta) => {
55
56
  if (!delta) return;
56
57
  streamed += delta.length;
57
58
  stream.write({ type: "text", delta });
58
- });
59
+ }, signal);
59
60
 
60
61
  if (!streamed && turn.text) stream.write({ type: "text", delta: turn.text });
61
62
  const toolCalls = turn.toolCalls ?? [];
@@ -65,6 +66,7 @@ export class AgentTurnStream {
65
66
  const limits = turn.limits && (turn.limits.window || turn.limits.output) ? turn.limits : null;
66
67
  stream.write({ type: "done", stop, ...(usage ? { usage } : {}), ...(limits ? { limits } : {}) });
67
68
  } catch (error) {
69
+ if (signal.aborted) return;
68
70
  if (!isExceptionLike(error))
69
71
  AgentTurnStream.#logger.error(`agent turn failed after its stream opened: ${String(error)}`);
70
72
 
@@ -1,6 +1,7 @@
1
1
  import type { Adaptor } from "akanjs/service";
2
2
 
3
3
  import type { EndpointInfo } from "./endpointInfo";
4
+ import type { ExceptionLike } from "./exception";
4
5
  import type { EndpointErrors } from "./types";
5
6
 
6
7
  export class EndpointErrorContract {
@@ -34,4 +35,14 @@ export class EndpointErrorContract {
34
35
  `"${key}" threw ${thrownKey}, which its \`errors\` declaration leaves out: OpenAPI and the MCP catalogue do not publish it.`,
35
36
  );
36
37
  }
38
+
39
+ static promised(endpointInfo: EndpointInfo, error: ExceptionLike) {
40
+ const keys: readonly string[] | undefined = endpointInfo.signalOption.errors?.[error.statusCode];
41
+ return error.statusCode < 500 && keys?.includes(EndpointErrorContract.wireKey(error)) === true;
42
+ }
43
+
44
+ static wireKey(error: ExceptionLike): string {
45
+ const wire = (error.toJSON() as { error?: unknown }).error;
46
+ return typeof wire === "string" ? wire : (error as unknown as Error).message;
47
+ }
37
48
  }
@@ -1,5 +1,6 @@
1
1
  import type { BackendEnv, Cls, PromiseOrObject } from "akanjs/base";
2
2
  import { Logger } from "akanjs/common";
3
+ import { EndpointErrorContract } from "./endpointErrorContract";
3
4
  import { Exception, isExceptionLike } from "./exception";
4
5
  import type { SignalContext } from "./signalContext";
5
6
 
@@ -37,8 +38,11 @@ export class Logging extends middleware("logging") {
37
38
 
38
39
  if (context.isBodyReadFailure(error)) throw error;
39
40
  const line = `Error ${context.endpointInfo.type}-${context.key} / ${Date.now() - start}ms: ${String(error)}`;
40
-
41
- if (isExceptionLike(error) && error.statusCode === 429) {
41
+
42
+ if (
43
+ isExceptionLike(error) &&
44
+ (error.statusCode === 429 || EndpointErrorContract.promised(context.endpointInfo, error))
45
+ ) {
42
46
  if (debug) context.adaptor.logger.debug(line);
43
47
  } else context.adaptor.logger.error(line);
44
48
  throw error;