@sayknow-cli/agent-core 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.7.4] - 2026-10-03
6
+
7
+ ### Fixed
8
+
9
+ - Managed fallback no longer kills healthy long responses. Exceeding the provisional caps (100,000 records / 16 MiB) now publishes the attempt and streams the rest live instead of failing with "exceeded the provisional event buffer limit"; `ManagedAttemptBufferOverflowError` is removed. Streamed content is also published once it has been held for `MANAGED_ATTEMPT_MAX_VISIBLE_HOLD_MS` (2 s), so long and parallel work stays visible while it streams. A published attempt is never silently discarded: a later provider failure surfaces through the ordinary session retry path with the visible output preserved.
10
+ - A provider invocation that exits by throwing (e.g. a local staging failure) now aborts its provider request. Previously the stream kept running unobserved, and the immediate retry on a Codex websocket failed with "websocket request already in progress".
11
+
5
12
  ## [0.7.3] - 2026-09-30
6
13
 
7
14
  ### Fixed
@@ -7,12 +7,22 @@ import { type AgentRunCoverage, type AgentRunSummary } from "./run-collector";
7
7
  import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool, StreamFn } from "./types";
8
8
  /** Sentinel returned by the abort race in `streamAssistantResponse`. */
9
9
  /**
10
- * Defensive caps for a provisional managed attempt. These are intentionally
11
- * well above ordinary streamed responses; they only bound memory when an
12
- * upstream emits an unbounded event stream before the attempt can commit.
10
+ * Defensive caps for a provisional managed attempt. They only bound memory when
11
+ * an upstream emits an unbounded event stream before the attempt can commit.
12
+ * Every streamed delta stages two records (the `message_update` event and the
13
+ * observer callback), so the record cap must sit well above the byte cap's
14
+ * effective delta count (~22k ordinary deltas at 16 MiB); a 10,000-record cap
15
+ * killed healthy ~5,000-delta responses with a non-retryable local error.
13
16
  */
14
- export declare const MANAGED_ATTEMPT_MAX_STAGED_EVENTS = 10000;
17
+ export declare const MANAGED_ATTEMPT_MAX_STAGED_EVENTS = 100000;
15
18
  export declare const MANAGED_ATTEMPT_MAX_STAGED_BYTES: number;
19
+ /**
20
+ * Longest a managed attempt may hold streamed content invisible. Failures that
21
+ * warrant a silent model fallback arrive before or at the first content; after
22
+ * this window the attempt is published so long or parallel work stays visible.
23
+ * Reaching either staging cap also publishes instead of killing the attempt.
24
+ */
25
+ export declare const MANAGED_ATTEMPT_MAX_VISIBLE_HOLD_MS = 2000;
16
26
  /**
17
27
  * Validate provider-observed escaped arguments before permitting the only
18
28
  * exception to the fail-closed tool boundary. The raw JSON must decode to the
@@ -105,6 +115,8 @@ interface ManagedOwnedInventory {
105
115
  export declare class ManagedAttemptTransaction {
106
116
  #private;
107
117
  constructor(stream: EventStream<AgentEvent, AgentMessage[]>, observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined, model: AgentLoopConfig["model"]);
118
+ /** Whether staged output has been published; later failures cannot be hidden. */
119
+ get committed(): boolean;
108
120
  push(event: AgentEvent): void;
109
121
  end(messages: AgentMessage[]): void;
110
122
  stageAssistantMessageEvent(message: AssistantMessage, event: AssistantMessageEvent): void;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/agent-core",
4
- "version": "0.7.3",
4
+ "version": "0.7.4",
5
5
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -35,9 +35,9 @@
35
35
  "fmt": "biome format --write ."
36
36
  },
37
37
  "dependencies": {
38
- "@sayknow-cli/ai": "0.7.3",
39
- "@sayknow-cli/natives": "0.7.3",
40
- "@sayknow-cli/utils": "0.7.3",
38
+ "@sayknow-cli/ai": "0.7.4",
39
+ "@sayknow-cli/natives": "0.7.4",
40
+ "@sayknow-cli/utils": "0.7.4",
41
41
  "@opentelemetry/api": "^1.9.0"
42
42
  },
43
43
  "devDependencies": {
package/src/agent-loop.ts CHANGED
@@ -64,26 +64,30 @@ import type {
64
64
 
65
65
  /** Sentinel returned by the abort race in `streamAssistantResponse`. */
66
66
  /**
67
- * Defensive caps for a provisional managed attempt. These are intentionally
68
- * well above ordinary streamed responses; they only bound memory when an
69
- * upstream emits an unbounded event stream before the attempt can commit.
67
+ * Defensive caps for a provisional managed attempt. They only bound memory when
68
+ * an upstream emits an unbounded event stream before the attempt can commit.
69
+ * Every streamed delta stages two records (the `message_update` event and the
70
+ * observer callback), so the record cap must sit well above the byte cap's
71
+ * effective delta count (~22k ordinary deltas at 16 MiB); a 10,000-record cap
72
+ * killed healthy ~5,000-delta responses with a non-retryable local error.
70
73
  */
71
- export const MANAGED_ATTEMPT_MAX_STAGED_EVENTS = 10_000;
74
+ export const MANAGED_ATTEMPT_MAX_STAGED_EVENTS = 100_000;
72
75
  export const MANAGED_ATTEMPT_MAX_STAGED_BYTES = 16 * 1024 * 1024;
73
76
 
74
77
  /**
75
- * Local staging failure: the provisional buffer limit was exceeded. Carries
76
- * NO transport facts or status by design — only original typed provider
77
- * transport facts may authorize provider fallback, so local buffer machinery
78
- * must never masquerade as provider evidence or consume the fallback chain.
79
- * It is therefore non-retryable and surfaces as an explicit local error.
78
+ * Longest a managed attempt may hold streamed content invisible. Failures that
79
+ * warrant a silent model fallback arrive before or at the first content; after
80
+ * this window the attempt is published so long or parallel work stays visible.
81
+ * Reaching either staging cap also publishes instead of killing the attempt.
80
82
  */
81
- class ManagedAttemptBufferOverflowError extends Error {
82
- constructor() {
83
- super("Managed fallback attempt exceeded the provisional event buffer limit");
84
- this.name = "ManagedAttemptBufferOverflowError";
85
- }
86
- }
83
+ export const MANAGED_ATTEMPT_MAX_VISIBLE_HOLD_MS = 2_000;
84
+
85
+ const MANAGED_VISIBLE_CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([
86
+ "text_delta",
87
+ "thinking_delta",
88
+ "reasoning_summary_delta",
89
+ "toolcall_delta",
90
+ ]);
87
91
 
88
92
  /**
89
93
  * Local snapshot-machinery failure. Deliberately carries no transport facts
@@ -1067,6 +1071,8 @@ export class ManagedAttemptTransaction {
1067
1071
  #observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined;
1068
1072
  #model: AgentLoopConfig["model"];
1069
1073
 
1074
+ #visibleSince: number | undefined;
1075
+
1070
1076
  constructor(
1071
1077
  stream: EventStream<AgentEvent, AgentMessage[]>,
1072
1078
  observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined,
@@ -1246,6 +1252,11 @@ export class ManagedAttemptTransaction {
1246
1252
  return id;
1247
1253
  }
1248
1254
 
1255
+ /** Whether staged output has been published; later failures cannot be hidden. */
1256
+ get committed(): boolean {
1257
+ return this.#committed;
1258
+ }
1259
+
1249
1260
  push(event: AgentEvent): void {
1250
1261
  if (this.#committed) {
1251
1262
  this.#stream.push(event);
@@ -1267,8 +1278,22 @@ export class ManagedAttemptTransaction {
1267
1278
  this.#stage("callback", { message, event });
1268
1279
  }
1269
1280
 
1270
- #preflight(input: unknown): boolean {
1271
- if (this.#entries.length + 1 > MANAGED_ATTEMPT_MAX_STAGED_EVENTS) throw new ManagedAttemptBufferOverflowError();
1281
+ /**
1282
+ * Hold streamed content back only briefly. Transport failures that justify a
1283
+ * silent model fallback (429/5xx/auth/first-event timeout) happen before or
1284
+ * right at the first content; past this window the user must see progress.
1285
+ */
1286
+ #visibleHoldExpired(entry: ManagedLedgerEntry): boolean {
1287
+ const type = entry.assistantType?.value;
1288
+ if (!type || !MANAGED_VISIBLE_CONTENT_EVENT_TYPES.has(type)) return false;
1289
+ const now = Date.now();
1290
+ this.#visibleSince ??= now;
1291
+ return now - this.#visibleSince >= MANAGED_ATTEMPT_MAX_VISIBLE_HOLD_MS;
1292
+ }
1293
+
1294
+ /** Returns whether the input is JSON-serializable, or "overflow" when it cannot be staged within the caps. */
1295
+ #preflight(input: unknown): boolean | "overflow" {
1296
+ if (this.#entries.length + 1 > MANAGED_ATTEMPT_MAX_STAGED_EVENTS) return "overflow";
1272
1297
  let serialized: string | undefined;
1273
1298
  try {
1274
1299
  serialized = JSON.stringify(input);
@@ -1276,11 +1301,31 @@ export class ManagedAttemptTransaction {
1276
1301
  return false;
1277
1302
  }
1278
1303
  if (serialized === undefined) throw new ManagedAttemptSnapshotError();
1279
- if (managedAttemptTextEncoder.encode(serialized).byteLength > MANAGED_ATTEMPT_MAX_STAGED_BYTES)
1280
- throw new ManagedAttemptBufferOverflowError();
1304
+ if (managedAttemptTextEncoder.encode(serialized).byteLength > MANAGED_ATTEMPT_MAX_STAGED_BYTES) return "overflow";
1281
1305
  return true;
1282
1306
  }
1283
1307
 
1308
+ /**
1309
+ * Publish everything staged so far and pass later output straight through.
1310
+ * Used when holding more output would exceed the memory caps or delay
1311
+ * visible progress too long. A spilled attempt is no longer discardable:
1312
+ * a later failure surfaces as an ordinary (same-run) error instead of a
1313
+ * silent model fallback, and a long healthy response is never killed.
1314
+ */
1315
+ #spill(): void {
1316
+ this.#visibleSince = undefined;
1317
+ this.flush();
1318
+ }
1319
+
1320
+ #forward(kind: "event" | "callback", input: unknown): void {
1321
+ if (kind === "event") {
1322
+ this.#stream.push(input as AgentEvent);
1323
+ return;
1324
+ }
1325
+ const callback = input as { message: AssistantMessage; event: AssistantMessageEvent };
1326
+ this.#observer?.(callback.message, callback.event);
1327
+ }
1328
+
1284
1329
  #stage(
1285
1330
  kind: "event" | "callback",
1286
1331
  input: AgentEvent | { message: AssistantMessage; event: AssistantMessageEvent },
@@ -1288,6 +1333,14 @@ export class ManagedAttemptTransaction {
1288
1333
  if (this.#discarded) throw new ManagedAttemptSnapshotError();
1289
1334
  try {
1290
1335
  const measured = this.#preflight(input);
1336
+ if (measured === "overflow") {
1337
+ // Holding this frame would exceed the caps: publish instead of killing
1338
+ // a healthy attempt. The frame itself is forwarded live, exactly as a
1339
+ // committed transaction forwards every later frame.
1340
+ this.#spill();
1341
+ this.#forward(kind, input);
1342
+ return;
1343
+ }
1291
1344
  let normalized: unknown;
1292
1345
  if (kind === "callback") {
1293
1346
  const callback = input as { message: AssistantMessage; event: AssistantMessageEvent };
@@ -1427,12 +1480,17 @@ export class ManagedAttemptTransaction {
1427
1480
  this.#retainedBytes += 16;
1428
1481
  this.#retain(entry.messageSlots);
1429
1482
  }
1430
- if (this.#retainedBytes > MANAGED_ATTEMPT_MAX_STAGED_BYTES) throw new ManagedAttemptBufferOverflowError();
1431
1483
  this.#peakBytes = Math.max(this.#peakBytes, this.#retainedBytes);
1484
+ if (this.#retainedBytes > MANAGED_ATTEMPT_MAX_STAGED_BYTES || this.#visibleHoldExpired(entry)) {
1485
+ // The entry is already ledgered, so the flush publishes it too.
1486
+ this.#spill();
1487
+ }
1432
1488
  } catch (error) {
1489
+ // Once published, failures are ordinary run errors (observer/replay), not
1490
+ // discardable staging failures.
1491
+ if (this.#committed) throw error;
1433
1492
  this.discard();
1434
- if (error instanceof ManagedAttemptBufferOverflowError || error instanceof ManagedAttemptSnapshotError)
1435
- throw error;
1493
+ if (error instanceof ManagedAttemptSnapshotError) throw error;
1436
1494
  throw new ManagedAttemptSnapshotError();
1437
1495
  }
1438
1496
  }
@@ -2389,7 +2447,12 @@ async function runLoopBody(
2389
2447
  } catch (err) {
2390
2448
  if (!(err instanceof HarmonyLeakInterruption)) {
2391
2449
  const failureMessage = managedFailureMessage(err, config);
2392
- if (config.fallbackManaged && transaction && managedContextOverflow(failureMessage, config)) {
2450
+ if (
2451
+ config.fallbackManaged &&
2452
+ transaction &&
2453
+ !transaction.committed &&
2454
+ managedContextOverflow(failureMessage, config)
2455
+ ) {
2393
2456
  transaction.discard();
2394
2457
  currentContext.messages.splice(contextMessageCount);
2395
2458
  newMessages.splice(newMessageCount);
@@ -2397,7 +2460,7 @@ async function runLoopBody(
2397
2460
  stream.end(newMessages);
2398
2461
  return;
2399
2462
  }
2400
- if (config.fallbackManaged && transaction && managedRetryableFailure(err)) {
2463
+ if (config.fallbackManaged && transaction && !transaction.committed && managedRetryableFailure(err)) {
2401
2464
  transaction.discard();
2402
2465
  currentContext.messages.splice(contextMessageCount);
2403
2466
  newMessages.splice(newMessageCount);
@@ -2405,8 +2468,9 @@ async function runLoopBody(
2405
2468
  stream.end(newMessages);
2406
2469
  return;
2407
2470
  }
2471
+ const published = transaction?.committed === true;
2408
2472
  transaction?.discard();
2409
- if (transaction) {
2473
+ if (transaction && !published) {
2410
2474
  currentContext.messages.splice(contextMessageCount);
2411
2475
  newMessages.splice(newMessageCount);
2412
2476
  }
@@ -2482,8 +2546,11 @@ async function runLoopBody(
2482
2546
  }
2483
2547
  }
2484
2548
 
2549
+ // A published attempt cannot be silently discarded: its failure surfaces
2550
+ // through the ordinary error path (session retry) with output preserved.
2551
+ const discardable = transaction ? !transaction.committed : true;
2485
2552
  const overflow = managedContextOverflow(message, config);
2486
- if (config.fallbackManaged && overflow) {
2553
+ if (config.fallbackManaged && discardable && overflow) {
2487
2554
  transaction?.discard();
2488
2555
  currentContext.messages.splice(contextMessageCount);
2489
2556
  newMessages.splice(newMessageCount);
@@ -2504,7 +2571,12 @@ async function runLoopBody(
2504
2571
  : "Provider returned an empty response with anomalously low token usage (possible context overflow via proxy)";
2505
2572
  }
2506
2573
 
2507
- if (config.fallbackManaged && message.stopReason === "error" && managedRetryableFailure(message)) {
2574
+ if (
2575
+ config.fallbackManaged &&
2576
+ discardable &&
2577
+ message.stopReason === "error" &&
2578
+ managedRetryableFailure(message)
2579
+ ) {
2508
2580
  transaction?.discard();
2509
2581
  currentContext.messages.splice(contextMessageCount);
2510
2582
  newMessages.splice(newMessageCount);
@@ -2513,7 +2585,7 @@ async function runLoopBody(
2513
2585
  return;
2514
2586
  }
2515
2587
 
2516
- if (config.fallbackManaged && message.stopReason === "aborted") {
2588
+ if (config.fallbackManaged && discardable && message.stopReason === "aborted") {
2517
2589
  transaction?.discard();
2518
2590
  currentContext.messages.splice(contextMessageCount);
2519
2591
  newMessages.splice(newMessageCount);
@@ -2816,11 +2888,16 @@ async function streamAssistantResponse(
2816
2888
  const dynamicReasoning = config.getReasoning?.();
2817
2889
  const harmonyMitigationEnabled = isHarmonyLeakMitigationTarget(config.model);
2818
2890
  const harmonyAbortController = harmonyMitigationEnabled ? new AbortController() : undefined;
2819
- const requestSignal = harmonyAbortController
2820
- ? signal
2821
- ? AbortSignal.any([signal, harmonyAbortController.signal])
2822
- : harmonyAbortController.signal
2823
- : signal;
2891
+ // Cancels the provider request when this invocation exits by throwing (e.g.
2892
+ // a local managed-staging failure). Without it the provider stream keeps
2893
+ // running unobserved and a stateful transport (Codex websocket) rejects the
2894
+ // immediate retry with "websocket request already in progress".
2895
+ const attemptAbortController = new AbortController();
2896
+ const requestSignal = AbortSignal.any([
2897
+ ...(signal ? [signal] : []),
2898
+ ...(harmonyAbortController ? [harmonyAbortController.signal] : []),
2899
+ attemptAbortController.signal,
2900
+ ]);
2824
2901
  const effectiveTemperature =
2825
2902
  harmonyRetryAttempt > 0 && config.temperature !== undefined ? config.temperature + 0.05 : config.temperature;
2826
2903
  const effectiveToolChoice = recoveryMode ? "none" : (dynamicToolChoice ?? config.toolChoice);
@@ -3001,6 +3078,7 @@ async function streamAssistantResponse(
3001
3078
  return trailing;
3002
3079
  });
3003
3080
  } catch (err) {
3081
+ attemptAbortController.abort(err);
3004
3082
  failChatSpan(telemetry, chatSpan, {
3005
3083
  errorObject: err,
3006
3084
  responseHeaders: capturedHeaders,