akanjs 3.2.0-rc.23 → 3.2.0-rc.24

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
@@ -45,6 +45,17 @@
45
45
 
46
46
  Both are new and optional, so no upgrade step is needed.
47
47
 
48
+ - 3ebf990: `agentService.loop` now recovers from a model call refused for length, the way the in-page chat does, instead of ending the run. Both now read a refusal's `limit` in the refusal's own unit when it also gives `requested`.
49
+
50
+ - With `compact` set, a round whose call fails as `agent.error.contextOverflow` compacts at once, whatever `at` says, emits `compacted` as usual, and asks again.
51
+ - The retry is part of the same round. A second refusal, a transcript with nothing to cut, or a summary that fails ends the run with the original error, as before.
52
+ - The refused attempt is metered as a `failed` turn with what the provider counted, which is nothing for a refusal an adaptor makes before any network call.
53
+ - When the refusal's data carries `limit` and `requested`, the run lowers `at` for its remaining rounds to where that request would have fit, so the next one compacts ahead instead of being refused.
54
+ - The relay now forwards `requested` beside `limit` on the wire's `overflow` (`TurnOverflow`). Given both, the chat scales its own estimate of the refused prompt by `limit / requested` to get the window it adopts. Given `limit` alone, the chat still takes it as the window in tokens.
55
+ - The two numbers may be in any unit, as long as it is the same one. An adaptor that caps the request body in bytes can throw `new Err("agent.error.contextOverflow", { limit, requested })` with its own byte counts, and neither the loop nor the chat mistakes them for tokens.
56
+
57
+ A run without `compact` ends on the refusal as before. With `compact` set, a refused round now costs up to two more model calls (the summary and the retry) before the run ends. `AgentTurnStream.failure(...).overflow` and `RunnerEvent`'s error `overflow` gain an optional `requested`; code reading only `limit` needs no change.
58
+
48
59
  - 2da2adc: `agentService.loop` takes `toolkits`, so a run over a large catalogue no longer sends every tool definition every round.
49
60
 
50
61
  - **Shape.** `toolkits: { calendar: { description: "Read and edit the org calendar", tools: ["eventListInOrg", "updateEvent"] } }` groups names of `allow`. A tool in no toolkit is the core and is listed every round. `allow` still caps every toolkit.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.23",
3
+ "version": "3.2.0-rc.24",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -70,6 +70,7 @@ export class AgentLoop {
70
70
  #toolCalls = 0;
71
71
  #tainted: boolean = false;
72
72
  #compactFloor = 0;
73
+ #overflowAt = Number.POSITIVE_INFINITY;
73
74
 
74
75
  constructor(port: AgentLoopPort, request: AgentLoopRequest) {
75
76
  this.#port = port;
@@ -178,16 +179,37 @@ export class AgentLoop {
178
179
  }
179
180
 
180
181
  async *#ask(tools: AgentTool[]): Events<AgentLoopAnswer> {
182
+ const preamble = this.#request.preamble ?? false;
183
+ const request = this.#turnOf(tools);
184
+ try {
185
+ return yield* this.#metered(request, preamble, true);
186
+ } catch (error) {
187
+ if (!this.#request.compact || !Err.is(error, "agent.error.contextOverflow")) throw error;
188
+ this.#learnOverflow(error.data, request);
189
+
190
+ if (!(yield* this.#compact(true))) throw error;
191
+ }
192
+ return yield* this.#metered(this.#turnOf(tools), preamble, true);
193
+ }
194
+
195
+ #turnOf(tools: AgentTool[]): LlmTurnRequest {
181
196
  const { context = [], model, preamble } = this.#request;
182
197
  const instructions = this.#request.instructions || (preamble ? "" : AgentLoop.noInstructions);
183
- const request: LlmTurnRequest = {
198
+ return {
184
199
  messages: LoopTranscript.wire(this.#messages),
185
200
  tools: tools.map(({ readOnly: _readOnly, ...tool }) => tool),
186
201
  context,
187
202
  ...(instructions ? { instructions } : {}),
188
203
  ...(model ? { model } : {}),
189
204
  };
190
- return yield* this.#metered(request, preamble ?? false, true);
205
+ }
206
+
207
+ #learnOverflow(data: Record<string, unknown> | undefined, request: LlmTurnRequest) {
208
+ const { limit, requested } = data ?? {};
209
+ if (typeof limit !== "number" || typeof requested !== "number" || !(limit > 0 && requested > limit)) return;
210
+ const frame = LoopCompaction.frameTokensOf(request);
211
+ const fits = Math.floor(((LoopCompaction.tokensOf(this.#messages) + frame) * limit) / requested) - frame;
212
+ if (fits > 0) this.#overflowAt = Math.min(this.#overflowAt, fits);
191
213
  }
192
214
 
193
215
  async *#metered(request: LlmTurnRequest, preamble: string | false, streamed: boolean): Events<AgentLoopAnswer> {
@@ -221,12 +243,13 @@ export class AgentLoop {
221
243
  return answer;
222
244
  }
223
245
 
224
- async *#compact(): Events<void> {
246
+ async *#compact(forced = false): Events<boolean> {
225
247
  const { compact, model, untrusted } = this.#request;
226
- if (!compact) return;
227
- if (LoopCompaction.tokensOf(this.#messages) < Math.max(compact.at, this.#compactFloor)) return;
248
+ if (!compact) return false;
249
+ const threshold = Math.min(compact.at, this.#overflowAt);
250
+ if (!forced && LoopCompaction.tokensOf(this.#messages) < Math.max(threshold, this.#compactFloor)) return false;
228
251
  const at = LoopCompaction.cutAt(this.#messages, compact.keep ?? LoopCompaction.keep);
229
- if (at <= 0) return;
252
+ if (at <= 0) return false;
230
253
  const digest = LoopCompaction.digest(this.#messages.slice(0, at));
231
254
  let text = "";
232
255
  try {
@@ -242,9 +265,9 @@ export class AgentLoop {
242
265
  if (this.#haltedBy(error)) throw error;
243
266
 
244
267
  AgentLoop.#logger.warn(`agent loop compaction failed: ${error instanceof Error ? error.message : String(error)}`);
245
- return;
268
+ return false;
246
269
  }
247
- if (!text) return;
270
+ if (!text) return false;
248
271
  const summary = LoopCompaction.message(
249
272
  text,
250
273
  this.#tainted || untrusted ? this.#tainted : undefined,
@@ -253,8 +276,9 @@ export class AgentLoop {
253
276
  this.#messages.splice(0, at, summary);
254
277
  const after = LoopCompaction.tokensOf(this.#messages);
255
278
 
256
- this.#compactFloor = after >= compact.at ? after + compact.at : 0;
279
+ this.#compactFloor = after >= threshold ? after + threshold : 0;
257
280
  yield { type: "compacted", replaced: at, summary };
281
+ return true;
258
282
  }
259
283
 
260
284
  async *#runCalls(calls: AgentWireToolCall[], tools: AgentTool[]): Events<AgentLoopStop | null> {
@@ -81,7 +81,11 @@ export interface AgentLoopOptions {
81
81
  * no question is answered with an error instead. A `clientTools` entry by that name is dropped.
82
82
  */
83
83
  ask?: boolean;
84
- /** Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens. */
84
+ /**
85
+ * Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens, and also when a
86
+ * round's call fails as `agent.error.contextOverflow`, which is then asked again once. A refusal whose data carries
87
+ * `limit` and `requested`, in any one unit, lowers `at` for the rest of the run to where the request would fit.
88
+ */
85
89
  compact?: { at: number; keep?: number };
86
90
  /** Asked before every call; without it a `needsConfirm` tool is refused, and so is any write once tainted. */
87
91
  approve?: AgentLoopApprove;
@@ -1,4 +1,4 @@
1
- import type { AgentWireAttachment, AgentWireMessage } from "../predefinedAdaptor/llm.adaptor";
1
+ import type { AgentWireAttachment, AgentWireMessage, LlmTurnRequest } from "../predefinedAdaptor/llm.adaptor";
2
2
  import { LoopTranscript } from "./loopTranscript";
3
3
 
4
4
  export class LoopCompaction {
@@ -20,6 +20,10 @@ export class LoopCompaction {
20
20
  return Math.ceil(chars / 4);
21
21
  }
22
22
 
23
+ static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number {
24
+ return Math.ceil(JSON.stringify(frame).length / 4);
25
+ }
26
+
23
27
  static #charsOf(message: AgentWireMessage): number {
24
28
  const own = LoopCompaction.#blanked(message.attachments);
25
29
  let images = own.images;
@@ -25,7 +25,7 @@ export class AgentTurnStream {
25
25
  message: string;
26
26
  code: string;
27
27
  data?: Record<string, string | number>;
28
- overflow?: { limit?: number };
28
+ overflow?: { limit?: number; requested?: number };
29
29
  } {
30
30
  const status = isExceptionLike(error) ? error.statusCode : SignalFailure.generalized(error).statusCode;
31
31
  const code = SignalFailure.codeOf(error, status);
@@ -40,7 +40,12 @@ export class AgentTurnStream {
40
40
  raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, string | number>) : null;
41
41
 
42
42
  const overflow =
43
- message === "agent.error.contextOverflow" ? (typeof data?.limit === "number" ? { limit: data.limit } : {}) : null;
43
+ message === "agent.error.contextOverflow"
44
+ ? {
45
+ ...(typeof data?.limit === "number" ? { limit: data.limit } : {}),
46
+ ...(typeof data?.requested === "number" ? { requested: data.requested } : {}),
47
+ }
48
+ : null;
44
49
  return { message, code, ...(data ? { data } : {}), ...(overflow ? { overflow } : {}) };
45
50
  }
46
51
 
@@ -63,7 +63,11 @@ export interface AgentLoopOptions {
63
63
  * no question is answered with an error instead. A `clientTools` entry by that name is dropped.
64
64
  */
65
65
  ask?: boolean;
66
- /** Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens. */
66
+ /**
67
+ * Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens, and also when a
68
+ * round's call fails as `agent.error.contextOverflow`, which is then asked again once. A refusal whose data carries
69
+ * `limit` and `requested`, in any one unit, lowers `at` for the rest of the run to where the request would fit.
70
+ */
67
71
  compact?: {
68
72
  at: number;
69
73
  keep?: number;
@@ -1,10 +1,11 @@
1
- import type { AgentWireMessage } from "../predefinedAdaptor/llm.adaptor";
1
+ import type { AgentWireMessage, LlmTurnRequest } from "../predefinedAdaptor/llm.adaptor";
2
2
  export declare class LoopCompaction {
3
3
  #private;
4
4
  static readonly keep = 6;
5
5
  static readonly imageTokens = 1600;
6
6
  static readonly instruction: string;
7
7
  static tokensOf(messages: readonly AgentWireMessage[]): number;
8
+ static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number;
8
9
  static cutAt(messages: readonly AgentWireMessage[], keep: number): number;
9
10
  static digest(messages: readonly AgentWireMessage[], budget?: number): string;
10
11
  static message(summary: string, tainted?: boolean, toolkits?: string[]): AgentWireMessage;
@@ -17,6 +17,7 @@ export declare class AgentTurnStream {
17
17
  data?: Record<string, string | number>;
18
18
  overflow?: {
19
19
  limit?: number;
20
+ requested?: number;
20
21
  };
21
22
  };
22
23
  static response(run: RunTurn): Response;
@@ -1,4 +1,4 @@
1
- import type { ChatMessage, ToolCallResult, TurnLimits } from "./types.d.ts";
1
+ import type { ChatMessage, RunnerRequest, ToolCallResult, TurnLimits, TurnOverflow } from "./types.d.ts";
2
2
  export interface CompactOptions {
3
3
  /**
4
4
  * Estimated transcript tokens above which a turn summarizes its own history first — a ceiling on what each turn
@@ -52,6 +52,7 @@ export declare class Compaction {
52
52
  static tokensOf(messages: readonly ChatMessage[]): number;
53
53
  /** One tool result as it rides the wire, by the same rule. */
54
54
  static resultTokensOf(result: ToolCallResult): number;
55
+ static frameTokensOf(frame: Omit<RunnerRequest, "messages" | "signal">): number;
55
56
  /**
56
57
  * What the next request is estimated to cost, prompt and all: the provider's own count for the last turn that
57
58
  * reported one, plus four characters a token for what the transcript gained since. The provider's number is the
@@ -60,6 +61,7 @@ export declare class Compaction {
60
61
  * transcript: the tools, the screen context and the instructions.
61
62
  */
62
63
  static promptTokensOf(messages: readonly ChatMessage[], overhead: () => number): number;
64
+ static windowOf({ limit, requested }: TurnOverflow, messages: readonly ChatMessage[], overhead: number): number | undefined;
63
65
  /**
64
66
  * The prompt size past which a turn compacts first, or `Infinity` while the window is unknown. The answer shares
65
67
  * the window with the prompt, so its ceiling is held back along with `buffer`.
@@ -300,10 +300,13 @@ export type RunnerEvent = {
300
300
  message: string;
301
301
  code?: string;
302
302
  data?: Record<string, string | number>;
303
- overflow?: {
304
- limit?: number;
305
- };
303
+ overflow?: TurnOverflow;
306
304
  };
305
+ /** `limit` alone is a window in tokens; with `requested` beside it, both are in the refusal's own unit, bytes included. */
306
+ export interface TurnOverflow {
307
+ limit?: number;
308
+ requested?: number;
309
+ }
307
310
  export interface RunnerRequest {
308
311
  messages: ChatMessage[];
309
312
  tools: PublishedTool[];
@@ -19,6 +19,7 @@ import type {
19
19
  ToolCallResult,
20
20
  ToolCard,
21
21
  TurnLimits,
22
+ TurnOverflow,
22
23
  TurnStop,
23
24
  TurnUsage,
24
25
  } from "./types";
@@ -669,7 +670,7 @@ export class AgentSession {
669
670
  const guard = Compaction.thresholdOf(this.#limits, buffer);
670
671
  const measure = () => ({
671
672
  transcript: Compaction.tokensOf(this.#messages),
672
- prompt: Compaction.promptTokensOf(this.#messages, () => AgentSession.#tokensOfFrame(this.#frame())),
673
+ prompt: Compaction.promptTokensOf(this.#messages, () => Compaction.frameTokensOf(this.#frame())),
673
674
  });
674
675
  const before = measure();
675
676
  const floor = this.#compactFloor;
@@ -695,8 +696,9 @@ export class AgentSession {
695
696
  * refused again after its own summary is not one another summary will fit — and never where the host turned
696
697
  * automatic compaction off, since that host keeps the window itself.
697
698
  */
698
- async #recover(overflow: { limit?: number }, signal: AbortSignal): Promise<boolean> {
699
- if (overflow.limit) this.#limits = { ...this.#limits, window: overflow.limit };
699
+ async #recover(overflow: TurnOverflow, signal: AbortSignal): Promise<boolean> {
700
+ const window = Compaction.windowOf(overflow, this.#messages, this.#overhead);
701
+ if (window) this.#limits = { ...this.#limits, window };
700
702
  const { at, keep } = this.#compactOptions;
701
703
  if (!at) return false;
702
704
  const draft = this.#messages[this.#messages.length - 1];
@@ -731,10 +733,6 @@ export class AgentSession {
731
733
  };
732
734
  }
733
735
 
734
- static #tokensOfFrame(frame: Omit<RunnerRequest, "messages" | "signal">): number {
735
- return Math.ceil(JSON.stringify(frame).length / 4);
736
- }
737
-
738
736
  /** No tools and no screen context: this turn summarizes the conversation, and must not act on it. */
739
737
  async #summarize(digest: string, signal: AbortSignal): Promise<string> {
740
738
  const custom = this.#options.compact?.summarize;
@@ -757,7 +755,7 @@ export class AgentSession {
757
755
  signal: AbortSignal,
758
756
  ): Promise<{ toolCalls: ToolCallRequest[]; stop: TurnStop; failure?: Extract<RunnerEvent, { type: "error" }> }> {
759
757
  const frame = this.#frame();
760
- this.#overhead = AgentSession.#tokensOfFrame(frame);
758
+ this.#overhead = Compaction.frameTokensOf(frame);
761
759
  this.#listed = frame.tools.map((tool) => tool.name);
762
760
  const request: RunnerRequest = { messages: Transcript.wire(this.#messages), ...frame, signal };
763
761
  this.#append({ role: "assistant" });
@@ -17,6 +17,17 @@
17
17
 
18
18
  Both are new and optional, so no upgrade step is needed.
19
19
 
20
+ - 3ebf990: `agentService.loop` now recovers from a model call refused for length, the way the in-page chat does, instead of ending the run. Both now read a refusal's `limit` in the refusal's own unit when it also gives `requested`.
21
+
22
+ - With `compact` set, a round whose call fails as `agent.error.contextOverflow` compacts at once, whatever `at` says, emits `compacted` as usual, and asks again.
23
+ - The retry is part of the same round. A second refusal, a transcript with nothing to cut, or a summary that fails ends the run with the original error, as before.
24
+ - The refused attempt is metered as a `failed` turn with what the provider counted, which is nothing for a refusal an adaptor makes before any network call.
25
+ - When the refusal's data carries `limit` and `requested`, the run lowers `at` for its remaining rounds to where that request would have fit, so the next one compacts ahead instead of being refused.
26
+ - The relay now forwards `requested` beside `limit` on the wire's `overflow` (`TurnOverflow`). Given both, the chat scales its own estimate of the refused prompt by `limit / requested` to get the window it adopts. Given `limit` alone, the chat still takes it as the window in tokens.
27
+ - The two numbers may be in any unit, as long as it is the same one. An adaptor that caps the request body in bytes can throw `new Err("agent.error.contextOverflow", { limit, requested })` with its own byte counts, and neither the loop nor the chat mistakes them for tokens.
28
+
29
+ A run without `compact` ends on the refusal as before. With `compact` set, a refused round now costs up to two more model calls (the summary and the retry) before the run ends. `AgentTurnStream.failure(...).overflow` and `RunnerEvent`'s error `overflow` gain an optional `requested`; code reading only `limit` needs no change.
30
+
20
31
  - f5d1e63: A restored chat transcript that ends on an unanswered `askUser` call now opens on that question instead of closing it. This covers a server run that parked on a question while no chat was open, and a page reloaded mid-question.
21
32
 
22
33
  - The session's `pendingQuestion` holds the question, so `Agent.Chat` draws its card and the composer answers it as usual.
@@ -1,5 +1,5 @@
1
1
  import { Transcript } from "./Transcript";
2
- import type { ChatMessage, MessageAttachment, ToolCallResult, TurnLimits } from "./types";
2
+ import type { ChatMessage, MessageAttachment, RunnerRequest, ToolCallResult, TurnLimits, TurnOverflow } from "./types";
3
3
 
4
4
  export interface CompactOptions {
5
5
  /**
@@ -70,6 +70,10 @@ export class Compaction {
70
70
  return Math.ceil(chars / 4) + images * Compaction.imageTokens;
71
71
  }
72
72
 
73
+ static frameTokensOf(frame: Omit<RunnerRequest, "messages" | "signal">): number {
74
+ return Math.ceil(JSON.stringify(frame).length / 4);
75
+ }
76
+
73
77
  /**
74
78
  * What the next request is estimated to cost, prompt and all: the provider's own count for the last turn that
75
79
  * reported one, plus four characters a token for what the transcript gained since. The provider's number is the
@@ -85,6 +89,11 @@ export class Compaction {
85
89
  return Compaction.tokensOf(messages) + overhead();
86
90
  }
87
91
 
92
+ static windowOf({ limit, requested }: TurnOverflow, messages: readonly ChatMessage[], overhead: number) {
93
+ if (!limit || !requested || requested <= limit) return limit;
94
+ return Math.floor((Compaction.promptTokensOf(messages, () => overhead) * limit) / requested);
95
+ }
96
+
88
97
  /**
89
98
  * The prompt size past which a turn compacts first, or `Infinity` while the window is unknown. The answer shares
90
99
  * the window with the prompt, so its ceiling is held back along with `buffer`.
@@ -133,8 +133,10 @@ errors is such a refusal. The code is what a host branches on, since the message
133
133
  The session keeps it on the failed assistant message as `errorCode`, which is never sent back.
134
134
 
135
135
  **A refusal because the prompt no longer fits the window carries `"overflow": { "limit": 128000 }`** (`limit` only
136
- when the provider named it). It is the one refusal a session can answer by itself: it summarizes the transcript and
137
- asks again, once, and remembers the window for the rest of the conversation. Flag nothing else with it — a rate
136
+ when the refusal named it). With `requested` beside it, both are in the refusal's own unit — a byte cap included —
137
+ and the session scales its own estimate of the refused prompt by their ratio; `limit` alone is a window in tokens. It
138
+ is the one refusal a session can answer by itself: it summarizes the transcript and asks again, once, and remembers
139
+ the window for the rest of the conversation. Flag nothing else with it — a rate
138
140
  limit flagged as overflow compacts a conversation that fit.
139
141
 
140
142
  ## Streaming
@@ -1,5 +1,5 @@
1
1
  import { codeOfAnswer, codeOfStatus, isFailureCode } from "./failureCode";
2
- import type { AgentRunner, RunnerEvent, ToolCallRequest, TurnLimits, TurnUsage } from "./types";
2
+ import type { AgentRunner, RunnerEvent, ToolCallRequest, TurnLimits, TurnOverflow, TurnUsage } from "./types";
3
3
 
4
4
  export interface HttpRunnerOptions {
5
5
  url: string;
@@ -79,11 +79,14 @@ const interpolations = (value: unknown): Record<string, string | number> | undef
79
79
  return entries.length ? Object.fromEntries(entries) : undefined;
80
80
  };
81
81
 
82
- const overflowOf = (value: unknown): { limit?: number } | undefined => {
82
+ const overflowOf = (value: unknown): TurnOverflow | undefined => {
83
83
  if (!value) return undefined;
84
84
  if (typeof value !== "object") return {};
85
- const { limit } = value as { limit?: unknown };
86
- return typeof limit === "number" ? { limit } : {};
85
+ const { limit, requested } = value as { limit?: unknown; requested?: unknown };
86
+ return {
87
+ ...(typeof limit === "number" ? { limit } : {}),
88
+ ...(typeof requested === "number" ? { requested } : {}),
89
+ };
87
90
  };
88
91
 
89
92
  /**
@@ -321,9 +321,15 @@ export type RunnerEvent =
321
321
  message: string;
322
322
  code?: string;
323
323
  data?: Record<string, string | number>;
324
- overflow?: { limit?: number };
324
+ overflow?: TurnOverflow;
325
325
  };
326
326
 
327
+ /** `limit` alone is a window in tokens; with `requested` beside it, both are in the refusal's own unit, bytes included. */
328
+ export interface TurnOverflow {
329
+ limit?: number;
330
+ requested?: number;
331
+ }
332
+
327
333
  export interface RunnerRequest {
328
334
  messages: ChatMessage[];
329
335
  tools: PublishedTool[];