@sayknow-cli/agent-core 0.7.1 → 0.7.3

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,7 +2,11 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
- ## [0.7.1] - 2026-09-29
5
+ ## [0.7.3] - 2026-09-30
6
+
7
+ ### Fixed
8
+
9
+ - Managed fallback now retains a lossless, owned UTF-16 forward-patch ledger instead of cumulative provisional assistant snapshots. Callback records are staged only for an actual observer, all retained owners count against the unchanged 10,000-record/16 MiB limits, and bounded replay validation precedes irreversible callback-before-update dispatch. Local staging/replay/observer failures do not authorize provider fallback.
6
10
 
7
11
  ## [0.6.7] - 2026-09-28
8
12
 
@@ -2,7 +2,7 @@
2
2
  * Agent loop that works with AgentMessage throughout.
3
3
  * Transforms to Message[] only at the LLM call boundary.
4
4
  */
5
- import { type AssistantMessage, type Context, EventStream, type TSchema } from "@sayknow-cli/ai";
5
+ import { type AssistantMessage, type AssistantMessageEvent, type Context, EventStream, type TSchema } from "@sayknow-cli/ai";
6
6
  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`. */
@@ -80,6 +80,44 @@ export declare const MANAGED_SNAPSHOT_MAX_NODES = 100000;
80
80
  * callers use the default budget via {@link managedAttemptSnapshot}.
81
81
  */
82
82
  export declare function sanitizedDetachedClone<T>(value: T, maxNodes?: number): T;
83
+ interface ManagedOwnedInventory {
84
+ totalBytes: number;
85
+ structuralBytes: number;
86
+ payloadBytes: number;
87
+ peakBytes: number;
88
+ recordCount: number;
89
+ strings: Array<{
90
+ ownerId: number;
91
+ codeUnits: number;
92
+ bytes: number;
93
+ }>;
94
+ buffers: Array<{
95
+ ownerId: number;
96
+ kind: "suffix" | "typed";
97
+ bytes: number;
98
+ }>;
99
+ }
100
+ /**
101
+ * @internal Unsupported transaction/test seam, not a public config or metrics API.
102
+ * Inventory measures retained provisional ownership, never process RSS or
103
+ * postcommit EventStream/consumer snapshots.
104
+ */
105
+ export declare class ManagedAttemptTransaction {
106
+ #private;
107
+ constructor(stream: EventStream<AgentEvent, AgentMessage[]>, observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined, model: AgentLoopConfig["model"]);
108
+ push(event: AgentEvent): void;
109
+ end(messages: AgentMessage[]): void;
110
+ stageAssistantMessageEvent(message: AssistantMessage, event: AssistantMessageEvent): void;
111
+ /** Inventory walks the actual retained ownership roots, not input lengths or
112
+ * an estimated snapshot savings counter. Canonical aliases share an ID;
113
+ * independently owned strings are charged even when JS values compare equal.
114
+ */
115
+ ownedInventory(): ManagedOwnedInventory;
116
+ flush(signal?: AbortSignal): boolean;
117
+ /** Consume the last exposed prefix only on a postcommit terminal exit. */
118
+ takePublishedAssistant(): AssistantMessage | undefined;
119
+ discard(): void;
120
+ }
83
121
  /**
84
122
  * Detailed-result handle returned by {@link agentLoopDetailed}. Adds the
85
123
  * run-level telemetry/coverage rollup to the existing `AgentMessage[]`
@@ -115,3 +153,4 @@ export declare function agentLoopContinueDetailed(context: AgentContext, config:
115
153
  export declare function normalizeMessagesForProvider(messages: Context["messages"], model: AgentLoopConfig["model"]): Context["messages"];
116
154
  export declare const INTENT_FIELD = "_i";
117
155
  export declare function normalizeTools(tools: AgentContext["tools"], injectIntent: boolean): Context["tools"];
156
+ export {};
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.1",
4
+ "version": "0.7.3",
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.1",
39
- "@sayknow-cli/natives": "0.7.1",
40
- "@sayknow-cli/utils": "0.7.1",
38
+ "@sayknow-cli/ai": "0.7.3",
39
+ "@sayknow-cli/natives": "0.7.3",
40
+ "@sayknow-cli/utils": "0.7.3",
41
41
  "@opentelemetry/api": "^1.9.0"
42
42
  },
43
43
  "devDependencies": {
package/src/agent-loop.ts CHANGED
@@ -757,154 +757,1092 @@ function isManagedPlainRecord(value: unknown): value is Record<string, unknown>
757
757
  return value !== null && typeof value === "object" && !Array.isArray(value) && !nodeUtilTypes.isProxy(value);
758
758
  }
759
759
 
760
+ /** An immutable ownership graph. Keys/tags are explicitly canonical; values are
761
+ * independently owned unless the ledger deliberately shares the same node ID.
762
+ * Atomic nodes preserve structured-clone graph topology (including cycles).
763
+ */
764
+ interface ManagedOwnedString {
765
+ kind: "string";
766
+ retainedRefs: number;
767
+ id: number;
768
+ value: string;
769
+ }
770
+ type ManagedValue =
771
+ | ManagedOwnedString
772
+ | ({ retainedRefs: number } & (
773
+ | { kind: "scalar"; id: number; value: undefined | null | boolean | number | bigint }
774
+ | { kind: "record" | "array"; id: number; fields: ManagedField[]; length: number; nullPrototype: boolean }
775
+ | { kind: "atomic"; id: number; value: object }
776
+ ));
777
+ interface ManagedField {
778
+ key: ManagedOwnedString;
779
+ value: ManagedValue;
780
+ }
781
+ interface ManagedPath {
782
+ id: number;
783
+ keys: Array<ManagedOwnedString | number>;
784
+ }
785
+ type ManagedPatch =
786
+ | { kind: "replace"; path: ManagedPath; value: ManagedValue }
787
+ | { kind: "delete"; path: ManagedPath }
788
+ | { kind: "truncate"; path: ManagedPath; length: number }
789
+ | { kind: "append"; path: ManagedPath; id: number; units: Uint16Array };
790
+ interface ManagedVersion {
791
+ id: number;
792
+ opStart: number;
793
+ opCount: number;
794
+ }
795
+ interface ManagedLedgerEntry {
796
+ kind: "event" | "callback";
797
+ type: ManagedOwnedString;
798
+ assistantType?: ManagedOwnedString;
799
+ shape: "plain" | "message" | "update" | "callback" | "messages";
800
+ nullPrototype: boolean;
801
+ assistantNullPrototype: boolean;
802
+ envelope: ManagedField[];
803
+ assistantEnvelope: ManagedField[];
804
+ refs: number[];
805
+ messageRef?: number;
806
+ partialRef?: number;
807
+ messageSlots?: ManagedValue;
808
+ opaque?: ManagedValue;
809
+ order: ManagedPath;
810
+ }
811
+ interface ManagedOwnedInventory {
812
+ totalBytes: number;
813
+ structuralBytes: number;
814
+ payloadBytes: number;
815
+ peakBytes: number;
816
+ recordCount: number;
817
+ strings: Array<{ ownerId: number; codeUnits: number; bytes: number }>;
818
+ buffers: Array<{ ownerId: number; kind: "suffix" | "typed"; bytes: number }>;
819
+ }
820
+
821
+ interface ManagedOpaqueEnvelope {
822
+ envelope: Record<string, unknown>;
823
+ assistantEnvelope: Record<string, unknown>;
824
+ messageSlots?: Array<number | AgentMessage>;
825
+ }
826
+
827
+ // Only opaque fields that share an object graph need a grouped owner. Ordinary
828
+ // scalar/delta envelopes retain the compact representation and its admission bound.
829
+ function managedFieldsShareGraph(fields: Array<[string, unknown]>): boolean {
830
+ const owners = new Map<object, number>();
831
+ let shared = false;
832
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
833
+ const visit = (value: unknown, owner: number, depth: number): void => {
834
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
835
+ if (value === null || typeof value !== "object") return;
836
+ const prior = owners.get(value);
837
+ if (prior !== undefined) {
838
+ if (prior !== owner) shared = true;
839
+ return;
840
+ }
841
+ owners.set(value, owner);
842
+ for (const [, child] of managedAtomicParts(value).fields) visit(child, owner, depth + 1);
843
+ };
844
+ for (let owner = 0; owner < fields.length; owner++) visit(fields[owner]![1], owner, 0);
845
+ return shared;
846
+ }
847
+
848
+ function managedOwnFields(value: object): Array<[string, unknown]> {
849
+ return Object.keys(value).map(key => {
850
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
851
+ if (!descriptor || !("value" in descriptor)) throw new ManagedAttemptSnapshotError();
852
+ return [key, descriptor.value];
853
+ });
854
+ }
855
+
856
+ // Raw atomic nodes are already detached by normalization. This walk is shared
857
+ // by equality and accounting, so an unsupported intrinsic cannot be accepted
858
+ // with an uncharged backing store. SharedArrayBuffer is intentionally rejected:
859
+ // structuredClone does not detach its backing memory from the provider.
860
+ function managedAtomicParts(value: object): {
861
+ tag: string;
862
+ fields: Array<[string, unknown]>;
863
+ buffer?: ArrayBuffer;
864
+ opaqueBytes?: number;
865
+ } {
866
+ if (nodeUtilTypes.isProxy(value) || nodeUtilTypes.isSharedArrayBuffer(value))
867
+ throw new ManagedAttemptSnapshotError();
868
+ if (nodeUtilTypes.isArrayBuffer(value)) return { tag: "ArrayBuffer", fields: [], buffer: value as ArrayBuffer };
869
+ if (ArrayBuffer.isView(value)) {
870
+ return {
871
+ tag: Object.getPrototypeOf(value).constructor.name,
872
+ fields: [
873
+ ["byteOffset", value.byteOffset],
874
+ ["byteLength", value.byteLength],
875
+ ["buffer", value.buffer],
876
+ ],
877
+ };
878
+ }
879
+ if (nodeUtilTypes.isDate(value)) return { tag: "Date", fields: [["time", Date.prototype.getTime.call(value)]] };
880
+ if (nodeUtilTypes.isRegExp(value)) {
881
+ const regexp = value as RegExp;
882
+ return {
883
+ tag: "RegExp",
884
+ fields: [
885
+ ["source", regexp.source],
886
+ ["flags", regexp.flags],
887
+ ["lastIndex", regexp.lastIndex],
888
+ ],
889
+ };
890
+ }
891
+ if (nodeUtilTypes.isMap(value)) {
892
+ const fields: Array<[string, unknown]> = [];
893
+ for (const [key, item] of Map.prototype.entries.call(value) as Iterable<[unknown, unknown]>) {
894
+ fields.push(["key", key], ["value", item]);
895
+ }
896
+ return { tag: "Map", fields };
897
+ }
898
+ if (nodeUtilTypes.isSet(value)) {
899
+ return {
900
+ tag: "Set",
901
+ fields: Array.from(Set.prototype.values.call(value) as Iterable<unknown>, item => ["value", item]),
902
+ };
903
+ }
904
+ if (nodeUtilTypes.isNativeError(value)) {
905
+ return {
906
+ tag: Object.getPrototypeOf(value).constructor.name,
907
+ fields: Object.getOwnPropertyNames(value).map(key => [
908
+ key,
909
+ Object.getOwnPropertyDescriptor(value, key)!.value,
910
+ ]),
911
+ };
912
+ }
913
+ if (nodeUtilTypes.isBoxedPrimitive(value)) {
914
+ const primitive = Object.getPrototypeOf(value).valueOf.call(value) as unknown;
915
+ return { tag: Object.getPrototypeOf(value).constructor.name, fields: [["value", primitive]] };
916
+ }
917
+ const prototype = Object.getPrototypeOf(value);
918
+ if (typeof Blob !== "undefined" && value instanceof Blob) {
919
+ const size = Object.getOwnPropertyDescriptor(Blob.prototype, "size")!.get!.call(value) as number;
920
+ const type = Object.getOwnPropertyDescriptor(Blob.prototype, "type")!.get!.call(value) as string;
921
+ // Blob backing data is immutable. Charge its full logical ownership and
922
+ // always replace it rather than guessing byte equality synchronously.
923
+ return { tag: "Blob", fields: [["type", type]], opaqueBytes: size };
924
+ }
925
+ if (Array.isArray(value)) return { tag: "Array", fields: [["length", value.length], ...managedOwnFields(value)] };
926
+ if (prototype === null || prototype === Object.prototype)
927
+ return { tag: prototype === null ? "NullRecord" : "Record", fields: managedOwnFields(value) };
928
+ throw new ManagedAttemptSnapshotError();
929
+ }
930
+
931
+ function managedGraphEqual(left: unknown, right: unknown): boolean {
932
+ const forward = new Map<object, object>();
933
+ const reverse = new Map<object, object>();
934
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
935
+ const equal = (a: unknown, b: unknown, depth: number): boolean => {
936
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
937
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return Object.is(a, b);
938
+ if (forward.has(a)) return forward.get(a) === b;
939
+ if (reverse.has(b)) return false;
940
+ forward.set(a, b);
941
+ reverse.set(b, a);
942
+ const ap = managedAtomicParts(a);
943
+ const bp = managedAtomicParts(b);
944
+ if (ap.tag !== bp.tag || ap.fields.length !== bp.fields.length || !!ap.buffer !== !!bp.buffer) return false;
945
+ if (ap.opaqueBytes !== undefined || bp.opaqueBytes !== undefined) return false;
946
+ if (ap.buffer && bp.buffer) {
947
+ if (ap.buffer.byteLength !== bp.buffer.byteLength) return false;
948
+ const aa = new Uint8Array(ap.buffer);
949
+ const bb = new Uint8Array(bp.buffer);
950
+ for (let i = 0; i < aa.length; i++) if (aa[i] !== bb[i]) return false;
951
+ }
952
+ return ap.fields.every(
953
+ ([key, item], index) => key === bp.fields[index]![0] && equal(item, bp.fields[index]![1], depth + 1),
954
+ );
955
+ };
956
+ return equal(left, right, 0);
957
+ }
958
+
959
+ function managedValueEqual(left: ManagedValue, right: ManagedValue): boolean {
960
+ if (left === right) return true;
961
+ if (left.kind !== right.kind) return false;
962
+ if (left.kind === "string" && right.kind === "string") return left.value === right.value;
963
+ if (left.kind === "scalar" && right.kind === "scalar") return Object.is(left.value, right.value);
964
+ if (left.kind === "atomic" && right.kind === "atomic") return managedGraphEqual(left.value, right.value);
965
+ if ((left.kind === "record" || left.kind === "array") && (right.kind === "record" || right.kind === "array")) {
966
+ return (
967
+ left.length === right.length &&
968
+ left.nullPrototype === right.nullPrototype &&
969
+ left.fields.length === right.fields.length &&
970
+ left.fields.every(
971
+ (field, index) =>
972
+ field.key.value === right.fields[index]!.key.value &&
973
+ managedValueEqual(field.value, right.fields[index]!.value),
974
+ )
975
+ );
976
+ }
977
+ return false;
978
+ }
979
+
980
+ function managedDecode(value: ManagedValue): unknown {
981
+ if (value.kind === "string" || value.kind === "scalar") return value.value;
982
+ if (value.kind === "atomic") return managedReplayClone(value.value);
983
+ const output: Record<string, unknown> | unknown[] =
984
+ value.kind === "array" ? new Array(value.length) : value.nullPrototype ? Object.create(null) : {};
985
+ for (const field of value.fields)
986
+ Object.defineProperty(output, field.key.value, {
987
+ value: managedDecode(field.value),
988
+ enumerable: true,
989
+ writable: true,
990
+ configurable: true,
991
+ });
992
+ return output;
993
+ }
994
+
995
+ // structuredClone detaches intrinsic graphs but intentionally erases null
996
+ // record prototypes. Replay must retain the sanitizer's normalized data shape.
997
+ function managedReplayClone<T>(value: T): T {
998
+ const clone = structuredClone(value);
999
+ const seen = new Map<object, object>();
1000
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1001
+ const restore = (source: unknown, target: unknown, depth: number): void => {
1002
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1003
+ if (source === null || typeof source !== "object") {
1004
+ if (!Object.is(source, target)) throw new ManagedAttemptSnapshotError();
1005
+ return;
1006
+ }
1007
+ if (target === null || typeof target !== "object") throw new ManagedAttemptSnapshotError();
1008
+ if (seen.has(source)) {
1009
+ if (seen.get(source) !== target) throw new ManagedAttemptSnapshotError();
1010
+ return;
1011
+ }
1012
+ seen.set(source, target);
1013
+ if (Object.getPrototypeOf(source) === null) Object.setPrototypeOf(target, null);
1014
+ const before = managedAtomicParts(source);
1015
+ const after = managedAtomicParts(target);
1016
+ if (before.tag !== after.tag || before.fields.length !== after.fields.length)
1017
+ throw new ManagedAttemptSnapshotError();
1018
+ for (let index = 0; index < before.fields.length; index++) {
1019
+ const [key, child] = before.fields[index]!;
1020
+ if (key !== after.fields[index]![0]) throw new ManagedAttemptSnapshotError();
1021
+ restore(child, after.fields[index]![1], depth + 1);
1022
+ }
1023
+ };
1024
+ restore(value, clone, 0);
1025
+ return clone;
1026
+ }
1027
+
1028
+ function managedReplaySuffix(units: Uint16Array): string {
1029
+ let result = "";
1030
+ for (let start = 0; start < units.length; start += 8_192) {
1031
+ // Only the bounded argument array is transient; the retained suffix owns
1032
+ // its backing buffer, not a view/substr of a cumulative provider string.
1033
+ result += String.fromCharCode(...units.subarray(start, Math.min(start + 8_192, units.length)));
1034
+ }
1035
+ return result;
1036
+ }
1037
+
1038
+ class ManagedAttemptObserverError extends Error {
1039
+ constructor(cause: unknown) {
1040
+ super(
1041
+ `Managed fallback committed output observer failed: ${cause instanceof Error ? cause.message : "observer exception"}`,
1042
+ { cause },
1043
+ );
1044
+ this.name = "ManagedAttemptObserverError";
1045
+ }
1046
+ }
1047
+
760
1048
  /**
761
- * Holds managed-attempt assistant output above the public event stream. A
762
- * cancelled provider attempt is therefore unobservable to sessions and their
763
- * side-effect consumers. Non-managed streams bypass this object entirely.
1049
+ * @internal Unsupported transaction/test seam, not a public config or metrics API.
1050
+ * Inventory measures retained provisional ownership, never process RSS or
1051
+ * postcommit EventStream/consumer snapshots.
764
1052
  */
765
- class ManagedAttemptTransaction {
766
- #batch: Array<
767
- | { type: "event"; event: AgentEvent }
768
- | { type: "assistant_event"; message: AssistantMessage; event: AssistantMessageEvent }
769
- > = [];
770
- #stagedEventCount = 0;
771
- #stagedBytes = 0;
1053
+ export class ManagedAttemptTransaction {
1054
+ #entries: Array<ManagedLedgerEntry | undefined> = [];
1055
+ #versions: Array<ManagedVersion | undefined> = [];
1056
+ #ops: Array<ManagedPatch | undefined> = [];
1057
+ #keys = new Map<string, ManagedOwnedString>();
1058
+ #paths: ManagedPath[] = [];
1059
+ #nextOwnerId = 0;
1060
+ #latest: ManagedValue | undefined;
1061
+ #peakBytes = 0;
1062
+ #retainedBytes = 64 * 5;
772
1063
  #discarded = false;
773
1064
  #committed = false;
1065
+ #publishedAssistant: AssistantMessage | undefined;
1066
+ #stream: EventStream<AgentEvent, AgentMessage[]>;
1067
+ #observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined;
1068
+ #model: AgentLoopConfig["model"];
774
1069
 
775
1070
  constructor(
776
- private readonly stream: EventStream<AgentEvent, AgentMessage[]>,
777
- private readonly onAssistantMessageEvent:
778
- | ((message: AssistantMessage, event: AssistantMessageEvent) => void)
779
- | undefined,
780
- private readonly model: AgentLoopConfig["model"],
781
- ) {}
1071
+ stream: EventStream<AgentEvent, AgentMessage[]>,
1072
+ observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined,
1073
+ model: AgentLoopConfig["model"],
1074
+ ) {
1075
+ this.#stream = stream;
1076
+ this.#observer = observer;
1077
+ this.#model = model;
1078
+ }
1079
+
1080
+ #string(value: string): ManagedOwnedString {
1081
+ // Construct by code units instead of retaining a provider substring.
1082
+ const units = new Uint16Array(value.length);
1083
+ for (let index = 0; index < value.length; index++) units[index] = value.charCodeAt(index);
1084
+ return { kind: "string", id: ++this.#nextOwnerId, retainedRefs: 0, value: managedReplaySuffix(units) };
1085
+ }
1086
+
1087
+ #key(value: string): ManagedOwnedString {
1088
+ let key = this.#keys.get(value);
1089
+ if (!key) {
1090
+ key = this.#string(value);
1091
+ this.#keys.set(key.value, key);
1092
+ this.#retainedBytes += 32;
1093
+ this.#retain(key);
1094
+ }
1095
+ return key;
1096
+ }
1097
+
1098
+ #encode(value: unknown): ManagedValue {
1099
+ // Shared/cyclic graphs are atomic rather than tree patches: splitting them
1100
+ // into independent replacements would lose aliases and cycle backrefs.
1101
+ const seen = new Set<object>();
1102
+ let shared = false;
1103
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1104
+ const inspect = (item: unknown, depth: number): void => {
1105
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1106
+ if (item === null || typeof item !== "object") return;
1107
+ if (seen.has(item)) {
1108
+ shared = true;
1109
+ return;
1110
+ }
1111
+ seen.add(item);
1112
+ for (const [, child] of managedAtomicParts(item).fields) inspect(child, depth + 1);
1113
+ };
1114
+ inspect(value, 0);
1115
+ const encode = (item: unknown): ManagedValue => {
1116
+ if (typeof item === "string") return this.#string(item);
1117
+ if (
1118
+ item === null ||
1119
+ item === undefined ||
1120
+ typeof item === "boolean" ||
1121
+ typeof item === "number" ||
1122
+ typeof item === "bigint"
1123
+ )
1124
+ return { kind: "scalar", id: ++this.#nextOwnerId, retainedRefs: 0, value: item };
1125
+ if (typeof item !== "object") throw new ManagedAttemptSnapshotError();
1126
+ const prototype = Object.getPrototypeOf(item);
1127
+ if (!Array.isArray(item) && prototype !== null && prototype !== Object.prototype)
1128
+ return { kind: "atomic", id: ++this.#nextOwnerId, retainedRefs: 0, value: managedReplayClone(item) };
1129
+ return {
1130
+ kind: Array.isArray(item) ? "array" : "record",
1131
+ id: ++this.#nextOwnerId,
1132
+ retainedRefs: 0,
1133
+ fields: managedOwnFields(item).map(([key, child]) => ({ key: this.#key(key), value: encode(child) })),
1134
+ length: Array.isArray(item) ? item.length : 0,
1135
+ nullPrototype: prototype === null,
1136
+ };
1137
+ };
1138
+ return shared && value !== null && typeof value === "object"
1139
+ ? { kind: "atomic", id: ++this.#nextOwnerId, retainedRefs: 0, value: managedReplayClone(value) }
1140
+ : encode(value);
1141
+ }
1142
+
1143
+ #path(keys: Array<ManagedOwnedString | number>): ManagedPath {
1144
+ const previous = this.#paths.find(
1145
+ path =>
1146
+ path.keys.length === keys.length &&
1147
+ path.keys.every((key, index) =>
1148
+ typeof key === "number" ? key === keys[index] : typeof keys[index] !== "number" && key === keys[index],
1149
+ ),
1150
+ );
1151
+ if (previous) return previous;
1152
+ const path = { id: ++this.#nextOwnerId, keys: [...keys] };
1153
+ this.#paths.push(path);
1154
+ this.#retainedBytes += 32 + 64 + keys.length * 32;
1155
+ for (const key of keys) {
1156
+ if (typeof key === "number") this.#retainedBytes += 8;
1157
+ else this.#retain(key);
1158
+ }
1159
+ return path;
1160
+ }
1161
+
1162
+ #transition(next: ManagedValue): number {
1163
+ if (this.#latest && managedValueEqual(this.#latest, next)) return this.#versions.length;
1164
+ const opStart = this.#ops.length;
1165
+ const diff = (
1166
+ previous: ManagedValue | undefined,
1167
+ value: ManagedValue,
1168
+ keys: Array<ManagedOwnedString | number>,
1169
+ ): ManagedValue => {
1170
+ if (previous && managedValueEqual(previous, value)) return previous;
1171
+ if (previous?.kind === "string" && value.kind === "string" && value.value.startsWith(previous.value)) {
1172
+ const units = new Uint16Array(value.value.length - previous.value.length);
1173
+ for (let i = 0; i < units.length; i++) units[i] = value.value.charCodeAt(previous.value.length + i);
1174
+ this.#ops.push({ kind: "append", path: this.#path(keys), id: ++this.#nextOwnerId, units });
1175
+ return value;
1176
+ }
1177
+ if (
1178
+ previous &&
1179
+ (previous.kind === "record" || previous.kind === "array") &&
1180
+ value.kind === previous.kind &&
1181
+ (value.kind === "record" || value.kind === "array") &&
1182
+ value.nullPrototype === previous.nullPrototype
1183
+ ) {
1184
+ const oldKeys = previous.fields.map(field => field.key.value);
1185
+ const newKeys = value.fields.map(field => field.key.value);
1186
+ const commonOld = oldKeys.filter(key => newKeys.includes(key));
1187
+ const commonNew = newKeys.filter(key => oldKeys.includes(key));
1188
+ const retainedThenAdded = [...commonOld, ...newKeys.filter(key => !oldKeys.includes(key))];
1189
+ const dense = (node: typeof value) =>
1190
+ node.kind !== "array" ||
1191
+ (node.fields.length === node.length &&
1192
+ node.fields.every((field, index) => field.key.value === String(index)));
1193
+ // Primitive array reorders/replacements are atomic. Positional record
1194
+ // updates (e.g. content/tool arguments) remain ordinary field patches.
1195
+ const stableArray =
1196
+ value.kind !== "array" ||
1197
+ (dense(value) &&
1198
+ dense(previous) &&
1199
+ previous.fields
1200
+ .slice(0, Math.min(previous.length, value.length))
1201
+ .every(
1202
+ (field, index) =>
1203
+ managedValueEqual(field.value, value.fields[index]!.value) ||
1204
+ (field.value.kind === "record" && value.fields[index]!.value.kind === "record"),
1205
+ ));
1206
+ if (
1207
+ stableArray &&
1208
+ commonOld.every((key, index) => key === commonNew[index]) &&
1209
+ retainedThenAdded.every((key, index) => key === newKeys[index])
1210
+ ) {
1211
+ for (const field of previous.fields)
1212
+ if (!newKeys.includes(field.key.value) && value.kind !== "array")
1213
+ this.#ops.push({ kind: "delete", path: this.#path([...keys, field.key]) });
1214
+ const fields = value.fields.map(field => {
1215
+ const old = previous.fields.find(candidate => candidate.key === field.key);
1216
+ return {
1217
+ key: field.key,
1218
+ value: diff(old?.value, field.value, [
1219
+ ...keys,
1220
+ value.kind === "array" ? Number(field.key.value) : field.key,
1221
+ ]),
1222
+ };
1223
+ });
1224
+ if (value.kind === "array" && value.length < previous.length)
1225
+ this.#ops.push({ kind: "truncate", path: this.#path(keys), length: value.length });
1226
+ return { ...value, fields };
1227
+ }
1228
+ }
1229
+ this.#ops.push({ kind: "replace", path: this.#path(keys), value });
1230
+ return value;
1231
+ };
1232
+ const previous = this.#latest;
1233
+ this.#latest = diff(previous, next, []);
1234
+ this.#retain(this.#latest);
1235
+ if (previous) this.#releaseNode(previous);
1236
+ for (let index = opStart; index < this.#ops.length; index++) {
1237
+ const op = this.#ops[index]!;
1238
+ this.#retainedBytes += 64 + 16;
1239
+ if (op.kind === "replace") this.#retain(op.value);
1240
+ else if (op.kind === "append") this.#retainedBytes += 64 + op.units.byteLength;
1241
+ else if (op.kind === "truncate") this.#retainedBytes += 8;
1242
+ }
1243
+ const id = this.#versions.length + 1;
1244
+ this.#versions.push({ id, opStart, opCount: this.#ops.length - opStart });
1245
+ this.#retainedBytes += 16;
1246
+ return id;
1247
+ }
782
1248
 
783
1249
  push(event: AgentEvent): void {
784
1250
  if (this.#committed) {
785
- this.stream.push(event);
1251
+ this.#stream.push(event);
786
1252
  return;
787
1253
  }
788
- this.#stage(event);
1254
+ this.#stage("event", event);
789
1255
  }
790
1256
 
791
1257
  end(messages: AgentMessage[]): void {
792
- this.stream.end(messages);
1258
+ this.#stream.end(messages);
793
1259
  }
794
1260
 
795
1261
  stageAssistantMessageEvent(message: AssistantMessage, event: AssistantMessageEvent): void {
796
- const partial = managedAssistantShell(message, this.model);
797
- this.#batch.push({
798
- type: "assistant_event",
799
- message: partial,
800
- event: managedAssistantEventSnapshot(event, partial),
801
- });
1262
+ if (!this.#observer) return;
1263
+ if (this.#committed) {
1264
+ this.#observer(message, event);
1265
+ return;
1266
+ }
1267
+ this.#stage("callback", { message, event });
1268
+ }
1269
+
1270
+ #preflight(input: unknown): boolean {
1271
+ if (this.#entries.length + 1 > MANAGED_ATTEMPT_MAX_STAGED_EVENTS) throw new ManagedAttemptBufferOverflowError();
1272
+ let serialized: string | undefined;
1273
+ try {
1274
+ serialized = JSON.stringify(input);
1275
+ } catch {
1276
+ return false;
1277
+ }
1278
+ if (serialized === undefined) throw new ManagedAttemptSnapshotError();
1279
+ if (managedAttemptTextEncoder.encode(serialized).byteLength > MANAGED_ATTEMPT_MAX_STAGED_BYTES)
1280
+ throw new ManagedAttemptBufferOverflowError();
1281
+ return true;
802
1282
  }
803
1283
 
804
- flush(): void {
805
- if (this.#discarded || this.#committed) return;
806
- for (const item of this.#batch) {
807
- if (item.type === "assistant_event") {
808
- this.onAssistantMessageEvent?.(item.message, item.event);
1284
+ #stage(
1285
+ kind: "event" | "callback",
1286
+ input: AgentEvent | { message: AssistantMessage; event: AssistantMessageEvent },
1287
+ ): void {
1288
+ if (this.#discarded) throw new ManagedAttemptSnapshotError();
1289
+ try {
1290
+ const measured = this.#preflight(input);
1291
+ let normalized: unknown;
1292
+ if (kind === "callback") {
1293
+ const callback = input as { message: AssistantMessage; event: AssistantMessageEvent };
1294
+ const message = managedAssistantShell(callback.message, this.#model);
1295
+ normalized = { message, event: managedAssistantEventSnapshot(callback.event, message) };
1296
+ } else {
1297
+ normalized = managedAttemptSnapshotDetailed(this.#repairAssistantEvent(input as AgentEvent)).snapshot;
1298
+ if (!measured) {
1299
+ try {
1300
+ JSON.stringify(normalized);
1301
+ } catch {
1302
+ normalized = sanitizedDetachedClone(normalized);
1303
+ }
1304
+ }
1305
+ }
1306
+ const record = normalized as Record<string, unknown>;
1307
+ const assistantEvent = (kind === "callback" ? record.event : record.assistantMessageEvent) as
1308
+ | Record<string, unknown>
1309
+ | undefined;
1310
+ const entry: ManagedLedgerEntry = {
1311
+ kind,
1312
+ type: this.#key(String(kind === "callback" ? assistantEvent?.type : record.type)),
1313
+ shape:
1314
+ kind === "callback"
1315
+ ? "callback"
1316
+ : record.type === "message_update"
1317
+ ? "update"
1318
+ : record.type === "agent_end"
1319
+ ? "messages"
1320
+ : "plain",
1321
+ nullPrototype: Object.getPrototypeOf(record) === null,
1322
+ assistantNullPrototype: assistantEvent !== undefined && Object.getPrototypeOf(assistantEvent) === null,
1323
+ envelope: [],
1324
+ assistantEnvelope: [],
1325
+ refs: [],
1326
+ order: this.#path([
1327
+ ...Object.keys(record).map(key => this.#key(key)),
1328
+ -1,
1329
+ ...Object.keys(assistantEvent ?? {}).map(key => this.#key(key)),
1330
+ ]),
1331
+ };
1332
+ const references = new Map<object, number>();
1333
+ const envelopeFields: Array<[string, unknown]> = [];
1334
+ const assistantFields: Array<[string, unknown]> = [];
1335
+ const observe = (message: unknown): number => {
1336
+ if (!message || typeof message !== "object" || (message as Record<string, unknown>).role !== "assistant")
1337
+ throw new ManagedAttemptSnapshotError();
1338
+ const existing = references.get(message);
1339
+ if (existing !== undefined) return existing;
1340
+ const slot = entry.refs.length;
1341
+ entry.refs.push(this.#transition(this.#encode(message)));
1342
+ references.set(message, slot);
1343
+ return slot;
1344
+ };
1345
+ if (record.message && (record.message as Record<string, unknown>).role === "assistant") {
1346
+ entry.messageRef = observe(record.message);
1347
+ if (entry.shape === "plain") entry.shape = "message";
1348
+ }
1349
+ if (assistantEvent) {
1350
+ entry.assistantType = this.#key(String(assistantEvent.type));
1351
+ for (const [key, value] of managedOwnFields(assistantEvent)) {
1352
+ if (key === "partial" || key === "message" || key === "error") entry.partialRef = observe(value);
1353
+ else if (key !== "type") assistantFields.push([key, value]);
1354
+ }
1355
+ }
1356
+ const messageSlots =
1357
+ entry.shape === "messages"
1358
+ ? ((record.messages as unknown[]).map(message =>
1359
+ message && typeof message === "object" && (message as Record<string, unknown>).role === "assistant"
1360
+ ? observe(message)
1361
+ : message,
1362
+ ) as Array<number | AgentMessage>)
1363
+ : undefined;
1364
+ for (const [key, value] of managedOwnFields(record)) {
1365
+ if (
1366
+ key === "type" ||
1367
+ (key === "message" && entry.messageRef !== undefined) ||
1368
+ (key === "messages" && entry.shape === "messages") ||
1369
+ (key === "event" && kind === "callback") ||
1370
+ (key === "assistantMessageEvent" && assistantEvent)
1371
+ )
1372
+ continue;
1373
+ envelopeFields.push([key, value]);
1374
+ }
1375
+ if (
1376
+ managedFieldsShareGraph([
1377
+ ...envelopeFields,
1378
+ ...assistantFields,
1379
+ ...(messageSlots ? [["messages", messageSlots] as [string, unknown]] : []),
1380
+ ])
1381
+ ) {
1382
+ const opaque: ManagedOpaqueEnvelope = {
1383
+ envelope: Object.create(null),
1384
+ assistantEnvelope: Object.create(null),
1385
+ };
1386
+ for (const [key, value] of envelopeFields)
1387
+ Object.defineProperty(opaque.envelope, key, { value, enumerable: true });
1388
+ for (const [key, value] of assistantFields)
1389
+ Object.defineProperty(opaque.assistantEnvelope, key, { value, enumerable: true });
1390
+ if (messageSlots) opaque.messageSlots = messageSlots;
1391
+ entry.opaque = this.#encode(opaque);
809
1392
  } else {
810
- this.stream.push(item.event);
1393
+ entry.envelope = envelopeFields.map(([key, value]) => ({
1394
+ key: this.#key(key),
1395
+ value: this.#encode(value),
1396
+ }));
1397
+ entry.assistantEnvelope = assistantFields.map(([key, value]) => ({
1398
+ key: this.#key(key),
1399
+ value: this.#encode(value),
1400
+ }));
1401
+ if (messageSlots) entry.messageSlots = this.#encode(messageSlots);
1402
+ }
1403
+ // A callback/event pair may canonicalize identical immutable delta
1404
+ // payloads, never their independently sampled state or record count.
1405
+ const previous = this.#entries.at(-1);
1406
+ if (kind === "event" && previous?.kind === "callback" && previous.assistantType === entry.assistantType) {
1407
+ for (const field of entry.assistantEnvelope) {
1408
+ const old = previous.assistantEnvelope.find(candidate => candidate.key === field.key);
1409
+ if (old && managedValueEqual(old.value, field.value) && field.value.kind === "string")
1410
+ field.value = old.value;
1411
+ }
811
1412
  }
1413
+ this.#entries.push(entry);
1414
+ this.#retainedBytes += 128 + 16 + (entry.refs.length + 1) * 16;
1415
+ this.#retain(entry.type);
1416
+ if (entry.assistantType) this.#retain(entry.assistantType);
1417
+ if (entry.opaque) {
1418
+ this.#retainedBytes += 16;
1419
+ this.#retain(entry.opaque);
1420
+ }
1421
+ for (const field of [...entry.envelope, ...entry.assistantEnvelope]) {
1422
+ this.#retainedBytes += 32;
1423
+ this.#retain(field.key);
1424
+ this.#retain(field.value);
1425
+ }
1426
+ if (entry.messageSlots) {
1427
+ this.#retainedBytes += 16;
1428
+ this.#retain(entry.messageSlots);
1429
+ }
1430
+ if (this.#retainedBytes > MANAGED_ATTEMPT_MAX_STAGED_BYTES) throw new ManagedAttemptBufferOverflowError();
1431
+ this.#peakBytes = Math.max(this.#peakBytes, this.#retainedBytes);
1432
+ } catch (error) {
1433
+ this.discard();
1434
+ if (error instanceof ManagedAttemptBufferOverflowError || error instanceof ManagedAttemptSnapshotError)
1435
+ throw error;
1436
+ throw new ManagedAttemptSnapshotError();
812
1437
  }
813
- this.#batch = [];
814
- this.#stagedBytes = 0;
815
- this.#stagedEventCount = 0;
816
- this.#committed = true;
817
1438
  }
818
1439
 
819
- discard(): void {
820
- this.#batch = [];
821
- this.#stagedBytes = 0;
822
- this.#stagedEventCount = 0;
823
- this.#discarded = true;
1440
+ // Admission visits only acquired/released owners, never the preceding log.
1441
+ // The full inventory below independently checks this counter in tests.
1442
+ #nodeBytes(value: ManagedValue): number {
1443
+ if (value.kind === "string") return 8 + 24 + 2 * value.value.length;
1444
+ if (value.kind === "scalar")
1445
+ return 8 + (typeof value.value === "bigint" ? 24 + 2 * String(value.value).length : 8);
1446
+ if (value.kind !== "atomic") return 8 + 64 + 8 + 32 * value.fields.length;
1447
+ const seen = new Set<object>();
1448
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1449
+ const raw = (item: unknown, depth: number): number => {
1450
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1451
+ if (typeof item === "string") return 24 + 2 * item.length;
1452
+ if (item === null || typeof item !== "object")
1453
+ return typeof item === "bigint" ? 24 + 2 * String(item).length : 8;
1454
+ if (seen.has(item)) return 16;
1455
+ seen.add(item);
1456
+ const parts = managedAtomicParts(item);
1457
+ let bytes = 64 + (parts.buffer?.byteLength ?? parts.opaqueBytes ?? 0);
1458
+ for (const [key, child] of parts.fields) bytes += 32 + 24 + 2 * key.length + raw(child, depth + 1);
1459
+ return bytes;
1460
+ };
1461
+ return 8 + 64 + raw(value.value, 0);
824
1462
  }
825
1463
 
826
- #wouldOverflow(bytes: number): boolean {
827
- return (
828
- this.#stagedEventCount + 1 > MANAGED_ATTEMPT_MAX_STAGED_EVENTS ||
829
- this.#stagedBytes + bytes > MANAGED_ATTEMPT_MAX_STAGED_BYTES
830
- );
1464
+ #retain(value: ManagedValue): void {
1465
+ if (value.retainedRefs++ !== 0) return;
1466
+ this.#retainedBytes += this.#nodeBytes(value);
1467
+ if (value.kind === "record" || value.kind === "array") {
1468
+ for (const field of value.fields) {
1469
+ this.#retain(field.key);
1470
+ this.#retain(field.value);
1471
+ }
1472
+ }
831
1473
  }
832
1474
 
833
- #stage(event: AgentEvent): void {
834
- // Measure the raw event FIRST so an oversized payload is rejected
835
- // before the snapshot duplicates it — the staged-byte cap exists to
836
- // bound memory, so cloning ahead of the check would defeat it.
837
- // Cyclic/JSON-hostile events cannot be pre-measured; only those fall
838
- // through to snapshot-then-measure, where the sanitized detached form
839
- // is the cycle-safe estimator.
840
- let bytes: number | undefined;
841
- try {
842
- bytes = managedAttemptTextEncoder.encode(JSON.stringify(event)).byteLength;
843
- } catch {
844
- bytes = undefined;
1475
+ #releaseNode(value: ManagedValue): void {
1476
+ if (--value.retainedRefs !== 0) return;
1477
+ this.#retainedBytes -= this.#nodeBytes(value);
1478
+ if (value.kind === "record" || value.kind === "array") {
1479
+ for (const field of value.fields) {
1480
+ this.#releaseNode(field.key);
1481
+ this.#releaseNode(field.value);
1482
+ }
845
1483
  }
846
- if (bytes !== undefined && this.#wouldOverflow(bytes)) {
847
- this.discard();
848
- throw new ManagedAttemptBufferOverflowError();
1484
+ }
1485
+
1486
+ /** Inventory walks the actual retained ownership roots, not input lengths or
1487
+ * an estimated snapshot savings counter. Canonical aliases share an ID;
1488
+ * independently owned strings are charged even when JS values compare equal.
1489
+ */
1490
+ ownedInventory(): ManagedOwnedInventory {
1491
+ const inventory: ManagedOwnedInventory = {
1492
+ totalBytes: 0,
1493
+ structuralBytes: 0,
1494
+ payloadBytes: 0,
1495
+ peakBytes: this.#peakBytes,
1496
+ recordCount: this.#entries.length,
1497
+ strings: [],
1498
+ buffers: [],
1499
+ };
1500
+ if (!this.#entries.length && !this.#latest) return inventory;
1501
+ const seen = new Set<number>();
1502
+ const rawSeen = new Map<object, number>();
1503
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1504
+ let rawOwner = this.#nextOwnerId;
1505
+ const string = (id: number, value: string) => {
1506
+ inventory.structuralBytes += 24;
1507
+ const bytes = value.length * 2;
1508
+ inventory.payloadBytes += bytes;
1509
+ inventory.strings.push({ ownerId: id, codeUnits: value.length, bytes });
1510
+ };
1511
+ const raw = (value: unknown, depth: number): void => {
1512
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1513
+ if (typeof value === "string") {
1514
+ string(++rawOwner, value);
1515
+ return;
1516
+ }
1517
+ if (value === null || typeof value !== "object") {
1518
+ if (typeof value === "bigint") string(++rawOwner, String(value));
1519
+ else inventory.structuralBytes += 8;
1520
+ return;
1521
+ }
1522
+ if (rawSeen.has(value)) {
1523
+ inventory.structuralBytes += 16;
1524
+ return;
1525
+ }
1526
+ const ownerId = ++rawOwner;
1527
+ rawSeen.set(value, ownerId);
1528
+ const parts = managedAtomicParts(value);
1529
+ inventory.structuralBytes += 64;
1530
+ const bytes = parts.buffer?.byteLength ?? parts.opaqueBytes;
1531
+ if (bytes !== undefined) {
1532
+ inventory.payloadBytes += bytes;
1533
+ inventory.buffers.push({ ownerId, kind: "typed", bytes });
1534
+ }
1535
+ for (const [key, child] of parts.fields) {
1536
+ inventory.structuralBytes += 32;
1537
+ string(++rawOwner, key);
1538
+ raw(child, depth + 1);
1539
+ }
1540
+ };
1541
+ const node = (value: ManagedValue): void => {
1542
+ if (seen.has(value.id)) return;
1543
+ seen.add(value.id);
1544
+ inventory.structuralBytes += 8; // Embedded ownership reference count.
1545
+ if (value.kind === "string") string(value.id, value.value);
1546
+ else if (value.kind === "scalar") {
1547
+ if (typeof value.value === "bigint") string(value.id, String(value.value));
1548
+ else inventory.structuralBytes += 8;
1549
+ } else if (value.kind === "atomic") {
1550
+ inventory.structuralBytes += 64;
1551
+ raw(value.value, 0);
1552
+ } else {
1553
+ inventory.structuralBytes += 64 + 8;
1554
+ fields(value.fields);
1555
+ }
1556
+ };
1557
+ const fields = (values: ManagedField[]): void => {
1558
+ for (const field of values) {
1559
+ inventory.structuralBytes += 32;
1560
+ node(field.key);
1561
+ node(field.value);
1562
+ }
1563
+ };
1564
+ // Container headers and every actual key-pool/path-pool member remain
1565
+ // charged even when no longer reachable from the latest state.
1566
+ inventory.structuralBytes += 64 * 5 + this.#keys.size * 32 + this.#paths.length * 32;
1567
+ for (const key of this.#keys.values()) node(key);
1568
+ for (const path of this.#paths) {
1569
+ inventory.structuralBytes += 64 + path.keys.length * 32;
1570
+ for (const key of path.keys) {
1571
+ if (typeof key === "number") inventory.structuralBytes += 8;
1572
+ else node(key);
1573
+ }
849
1574
  }
850
- const detailed = managedAttemptSnapshotDetailed(this.#repairAssistantEvent(event));
851
- let snapshot = detailed.snapshot;
852
- if (bytes === undefined || detailed.degraded) {
853
- // Account the bytes of what is actually retained: a degraded
854
- // snapshot replaces non-JSON leaves with placeholders, so the raw
855
- // pre-measure (which omits e.g. function-valued properties) can
856
- // undercount the staged form.
857
- try {
858
- bytes = managedAttemptTextEncoder.encode(JSON.stringify(snapshot)).byteLength;
859
- } catch {
860
- try {
861
- snapshot = sanitizedDetachedClone(snapshot);
862
- bytes = managedAttemptTextEncoder.encode(JSON.stringify(snapshot)).byteLength;
863
- } catch {
864
- bytes = undefined;
1575
+ for (const entry of this.#entries) {
1576
+ if (!entry) continue;
1577
+ inventory.structuralBytes += 128 + 16 + (entry.refs.length + 1) * 16;
1578
+ node(entry.type);
1579
+ if (entry.assistantType) node(entry.assistantType);
1580
+ if (entry.opaque) {
1581
+ inventory.structuralBytes += 16;
1582
+ node(entry.opaque);
1583
+ }
1584
+ fields(entry.envelope);
1585
+ fields(entry.assistantEnvelope);
1586
+ if (entry.messageSlots) {
1587
+ inventory.structuralBytes += 16;
1588
+ node(entry.messageSlots);
1589
+ }
1590
+ }
1591
+ for (const version of this.#versions) if (version) inventory.structuralBytes += 16;
1592
+ for (const op of this.#ops) {
1593
+ if (!op) continue;
1594
+ inventory.structuralBytes += 64 + 16;
1595
+ if (op.kind === "replace") node(op.value);
1596
+ else if (op.kind === "append") {
1597
+ inventory.structuralBytes += 64;
1598
+ inventory.payloadBytes += op.units.byteLength;
1599
+ inventory.buffers.push({ ownerId: op.id, kind: "suffix", bytes: op.units.byteLength });
1600
+ } else if (op.kind === "truncate") inventory.structuralBytes += 8;
1601
+ }
1602
+ if (this.#latest) node(this.#latest);
1603
+ inventory.totalBytes = inventory.structuralBytes + inventory.payloadBytes;
1604
+ if (!this.#committed && inventory.totalBytes !== this.#retainedBytes) throw new ManagedAttemptSnapshotError();
1605
+ inventory.peakBytes = Math.max(inventory.peakBytes, inventory.totalBytes);
1606
+ return inventory;
1607
+ }
1608
+
1609
+ #replay(consume: boolean, dispatch?: (entry: ManagedLedgerEntry, output: unknown) => boolean): boolean {
1610
+ let working: unknown;
1611
+ let versionIndex = 0;
1612
+ const advance = (id: number): void => {
1613
+ if (id < versionIndex) throw new ManagedAttemptSnapshotError();
1614
+ while (versionIndex < id) {
1615
+ const version = this.#versions[versionIndex];
1616
+ if (!version || version.id !== versionIndex + 1) throw new ManagedAttemptSnapshotError();
1617
+ for (let index = version.opStart; index < version.opStart + version.opCount; index++) {
1618
+ const op = this.#ops[index];
1619
+ if (!op) throw new ManagedAttemptSnapshotError();
1620
+ const keys = op.path.keys.map(key => (typeof key === "number" ? key : key.value));
1621
+ let parent = working as Record<string | number, unknown>;
1622
+ for (const key of keys.slice(0, -1)) {
1623
+ const descriptor = parent && Object.getOwnPropertyDescriptor(parent, key);
1624
+ if (!descriptor || !("value" in descriptor)) throw new ManagedAttemptSnapshotError();
1625
+ parent = descriptor.value;
1626
+ }
1627
+ const key = keys.at(-1);
1628
+ const current =
1629
+ key === undefined ? working : parent && Object.getOwnPropertyDescriptor(parent, key)?.value;
1630
+ if (op.kind === "delete") {
1631
+ if (key === undefined || !parent || !Object.hasOwn(parent, key))
1632
+ throw new ManagedAttemptSnapshotError();
1633
+ delete parent[key];
1634
+ } else if (op.kind === "truncate") {
1635
+ if (!Array.isArray(current) || op.length > current.length) throw new ManagedAttemptSnapshotError();
1636
+ current.length = op.length;
1637
+ } else {
1638
+ if (op.kind === "append" && typeof current !== "string") throw new ManagedAttemptSnapshotError();
1639
+ const value =
1640
+ op.kind === "replace"
1641
+ ? managedDecode(op.value)
1642
+ : (current as string) + managedReplaySuffix(op.units);
1643
+ if (key === undefined) working = value;
1644
+ else
1645
+ Object.defineProperty(parent, key, {
1646
+ value,
1647
+ enumerable: true,
1648
+ writable: true,
1649
+ configurable: true,
1650
+ });
1651
+ }
1652
+ if (consume) this.#ops[index] = undefined;
865
1653
  }
1654
+ if (consume) this.#versions[versionIndex] = undefined;
1655
+ versionIndex++;
866
1656
  }
867
- if (bytes === undefined) {
868
- // The sanitizer's output is total (detached, JSON-safe), so this
869
- // is unreachable unless the sanitizer itself regresses. Fail as a
870
- // dedicated local error: it carries no transport facts, so it is
871
- // non-retryable and can never be misattributed to the provider.
872
- this.discard();
873
- throw new ManagedAttemptSnapshotError();
1657
+ };
1658
+ const decodeFields = (fields: ManagedField[], output: Record<string, unknown>) => {
1659
+ for (const field of fields)
1660
+ Object.defineProperty(output, field.key.value, {
1661
+ value: managedDecode(field.value),
1662
+ enumerable: true,
1663
+ configurable: true,
1664
+ writable: true,
1665
+ });
1666
+ };
1667
+ const ordered = (
1668
+ output: Record<string, unknown>,
1669
+ order: ManagedPath,
1670
+ assistant: boolean,
1671
+ nullPrototype: boolean,
1672
+ ): Record<string, unknown> => {
1673
+ const result: Record<string, unknown> = nullPrototype ? Object.create(null) : {};
1674
+ let inAssistant = false;
1675
+ for (const key of order.keys) {
1676
+ if (typeof key === "number") {
1677
+ inAssistant = true;
1678
+ continue;
1679
+ }
1680
+ if (inAssistant !== assistant || !Object.hasOwn(output, key.value)) continue;
1681
+ Object.defineProperty(result, key.value, {
1682
+ value: output[key.value],
1683
+ enumerable: true,
1684
+ configurable: true,
1685
+ writable: true,
1686
+ });
874
1687
  }
875
- if (this.#wouldOverflow(bytes)) {
876
- this.discard();
877
- throw new ManagedAttemptBufferOverflowError();
1688
+ if (Object.keys(result).length !== Object.keys(output).length) throw new ManagedAttemptSnapshotError();
1689
+ return result;
1690
+ };
1691
+ for (let index = 0; index < this.#entries.length; index++) {
1692
+ const entry = this.#entries[index];
1693
+ if (!entry) throw new ManagedAttemptSnapshotError();
1694
+ const messages = entry.refs.map(id => {
1695
+ advance(id);
1696
+ return managedReplayClone(working) as AssistantMessage;
1697
+ });
1698
+ for (const message of messages)
1699
+ if (message?.role !== "assistant" || !Array.isArray(message.content))
1700
+ throw new ManagedAttemptSnapshotError();
1701
+ const output: Record<string, unknown> = {};
1702
+ const opaque = entry.opaque ? (managedDecode(entry.opaque) as ManagedOpaqueEnvelope) : undefined;
1703
+ if (opaque) {
1704
+ for (const [key, value] of managedOwnFields(opaque.envelope))
1705
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
1706
+ } else decodeFields(entry.envelope, output);
1707
+ if (entry.kind === "event") output.type = entry.type.value;
1708
+ if (entry.messageRef !== undefined) output.message = messages[entry.messageRef];
1709
+ if (entry.assistantType) {
1710
+ const event: Record<string, unknown> = { type: entry.assistantType.value };
1711
+ if (opaque) {
1712
+ for (const [key, value] of managedOwnFields(opaque.assistantEnvelope))
1713
+ Object.defineProperty(event, key, { value, enumerable: true, configurable: true, writable: true });
1714
+ } else decodeFields(entry.assistantEnvelope, event);
1715
+ if (entry.partialRef !== undefined)
1716
+ event[
1717
+ entry.assistantType.value === "done"
1718
+ ? "message"
1719
+ : entry.assistantType.value === "error"
1720
+ ? "error"
1721
+ : "partial"
1722
+ ] = messages[entry.partialRef];
1723
+ // Validation never calls observers and rejects malformed replay before
1724
+ // the irrevocable commit point, without materializing an output batch.
1725
+ managedAssistantEventSnapshot(
1726
+ event as unknown as AssistantMessageEvent,
1727
+ messages[entry.partialRef ?? entry.messageRef ?? 0]!,
1728
+ );
1729
+ output[entry.kind === "callback" ? "event" : "assistantMessageEvent"] = ordered(
1730
+ event,
1731
+ entry.order,
1732
+ true,
1733
+ entry.assistantNullPrototype,
1734
+ );
878
1735
  }
1736
+ const slots = entry.messageSlots
1737
+ ? (managedDecode(entry.messageSlots) as Array<number | AgentMessage>)
1738
+ : opaque?.messageSlots;
1739
+ if (slots) output.messages = slots.map(slot => (typeof slot === "number" ? messages[slot] : slot));
1740
+ if (!dispatch) ordered(output, entry.order, false, entry.nullPrototype);
1741
+ if (consume) this.#entries[index] = undefined;
1742
+ if (dispatch && !dispatch(entry, ordered(output, entry.order, false, entry.nullPrototype))) return false;
879
1743
  }
880
- this.#batch.push({ type: "event", event: snapshot });
881
- this.#stagedEventCount += 1;
1744
+ return true;
1745
+ }
882
1746
 
883
- this.#stagedBytes += bytes;
1747
+ flush(signal?: AbortSignal): boolean {
1748
+ if (this.#discarded) return false;
1749
+ if (this.#committed) return true;
1750
+ if (signal?.aborted) {
1751
+ this.discard();
1752
+ return false;
1753
+ }
1754
+ try {
1755
+ this.#replay(false);
1756
+ } catch {
1757
+ this.discard();
1758
+ throw new ManagedAttemptSnapshotError();
1759
+ }
1760
+ if (signal?.aborted) {
1761
+ this.discard();
1762
+ return false;
1763
+ }
1764
+ // No validation scratch or whole-output batch survives this point. The
1765
+ // queue and consumer-held detached snapshots are outside provisional L.
1766
+ this.#committed = true;
1767
+ this.#latest = undefined;
1768
+ try {
1769
+ const complete = this.#replay(true, (entry, output) => {
1770
+ if (signal?.aborted) return false;
1771
+ // One postcommit history snapshot, detached before an observer can
1772
+ // mutate its output. It is not retained provisional output or a batch.
1773
+ const message = (output as Record<string, unknown>).message;
1774
+ if (message && typeof message === "object" && (message as AssistantMessage).role === "assistant") {
1775
+ this.#publishedAssistant = managedReplayClone(message) as AssistantMessage;
1776
+ }
1777
+ if (entry.kind === "callback") {
1778
+ const callback = output as { message: AssistantMessage; event: AssistantMessageEvent };
1779
+ try {
1780
+ this.#observer?.(callback.message, callback.event);
1781
+ } catch (error) {
1782
+ throw new ManagedAttemptObserverError(error);
1783
+ }
1784
+ } else {
1785
+ try {
1786
+ this.#stream.push(output as AgentEvent);
1787
+ } catch (error) {
1788
+ throw new ManagedAttemptObserverError(error);
1789
+ }
1790
+ }
1791
+ return !signal?.aborted;
1792
+ });
1793
+ if (complete) this.#publishedAssistant = undefined;
1794
+ return complete;
1795
+ } catch (error) {
1796
+ if (error instanceof ManagedAttemptObserverError || error instanceof ManagedAttemptSnapshotError) throw error;
1797
+ throw new ManagedAttemptSnapshotError();
1798
+ } finally {
1799
+ this.#release();
1800
+ }
1801
+ }
1802
+
1803
+ /** Consume the last exposed prefix only on a postcommit terminal exit. */
1804
+ takePublishedAssistant(): AssistantMessage | undefined {
1805
+ const message = this.#publishedAssistant;
1806
+ this.#publishedAssistant = undefined;
1807
+ return message;
1808
+ }
1809
+
1810
+ #release(): void {
1811
+ this.#entries = [];
1812
+ this.#versions = [];
1813
+ this.#ops = [];
1814
+ this.#latest = undefined;
1815
+ this.#keys.clear();
1816
+ this.#paths = [];
1817
+ this.#retainedBytes = 0;
1818
+ }
1819
+
1820
+ discard(): void {
1821
+ this.#release();
1822
+ if (!this.#committed) this.#discarded = true;
884
1823
  }
885
1824
 
886
1825
  #repairAssistantEvent(event: AgentEvent): AgentEvent {
887
1826
  if (event.type === "message_start" || event.type === "message_end" || event.type === "turn_end") {
888
1827
  return event.message.role === "assistant"
889
- ? { ...event, message: managedAssistantShell(event.message, this.model) }
1828
+ ? { ...event, message: managedAssistantShell(event.message, this.#model) }
890
1829
  : event;
891
1830
  }
892
1831
  if (event.type === "message_update") {
893
- const message = managedAssistantShell(event.message, this.model);
1832
+ const message = managedAssistantShell(event.message, this.#model);
894
1833
  return {
895
1834
  ...event,
896
1835
  message,
897
1836
  assistantMessageEvent: managedAssistantEventSnapshot(event.assistantMessageEvent, message),
898
1837
  };
899
1838
  }
900
- if (event.type === "agent_end") {
1839
+ if (event.type === "agent_end")
901
1840
  return {
902
1841
  ...event,
903
1842
  messages: event.messages.map(message =>
904
- message.role === "assistant" ? managedAssistantShell(message, this.model) : message,
1843
+ message.role === "assistant" ? managedAssistantShell(message, this.#model) : message,
905
1844
  ),
906
1845
  };
907
- }
908
1846
  return event;
909
1847
  }
910
1848
  }
@@ -1411,8 +2349,10 @@ async function runLoopBody(
1411
2349
  const attemptConfig = attemptTransaction
1412
2350
  ? {
1413
2351
  ...config,
1414
- onAssistantMessageEvent: (partial: AssistantMessage, event: AssistantMessageEvent) =>
1415
- attemptTransaction.stageAssistantMessageEvent(partial, event),
2352
+ onAssistantMessageEvent: config.onAssistantMessageEvent
2353
+ ? (partial: AssistantMessage, event: AssistantMessageEvent) =>
2354
+ attemptTransaction.stageAssistantMessageEvent(partial, event)
2355
+ : undefined,
1416
2356
  }
1417
2357
  : config;
1418
2358
  if (recoveryState.pending && !recoveryState.inserted) {
@@ -1465,10 +2405,16 @@ async function runLoopBody(
1465
2405
  stream.end(newMessages);
1466
2406
  return;
1467
2407
  }
2408
+ transaction?.discard();
2409
+ if (transaction) {
2410
+ currentContext.messages.splice(contextMessageCount);
2411
+ newMessages.splice(newMessageCount);
2412
+ }
1468
2413
  throw err;
1469
2414
  }
1470
2415
  if (config.fallbackManaged) {
1471
2416
  await emitHarmonyAudit(config, err, "escalated", harmonyRetryAttempt);
2417
+ transaction?.discard();
1472
2418
  throw err;
1473
2419
  }
1474
2420
  if (err.recovered) {
@@ -1585,7 +2531,40 @@ async function runLoopBody(
1585
2531
  }
1586
2532
 
1587
2533
  // One provider invocation is committed before any tool can run.
1588
- transaction?.flush();
2534
+ if (transaction) {
2535
+ let complete: boolean;
2536
+ try {
2537
+ complete = transaction.flush(loopSignal);
2538
+ } catch (error) {
2539
+ const prefix = transaction.takePublishedAssistant();
2540
+ currentContext.messages.splice(contextMessageCount);
2541
+ newMessages.splice(newMessageCount);
2542
+ if (prefix) {
2543
+ prefix.stopReason = "error";
2544
+ prefix.errorMessage = error instanceof Error ? error.message : "Managed output failed";
2545
+ delete prefix.errorStatus;
2546
+ delete prefix.transportFailure;
2547
+ currentContext.messages.push(prefix);
2548
+ newMessages.push(prefix);
2549
+ }
2550
+ throw error;
2551
+ }
2552
+ if (!complete) {
2553
+ const prefix = transaction.takePublishedAssistant();
2554
+ currentContext.messages.splice(contextMessageCount);
2555
+ newMessages.splice(newMessageCount);
2556
+ await config.onManagedAttemptOutcome?.({ type: "run_terminal", reason: "cancelled" });
2557
+ if (!prefix) {
2558
+ stream.end(newMessages);
2559
+ return;
2560
+ }
2561
+ // Preserve the irreversible prefix, not the provider's unseen tail.
2562
+ currentContext.messages.push(prefix);
2563
+ message = emitAbortedAssistantMessage(prefix, true, currentContext, config, stream);
2564
+ currentContext.messages.push(message);
2565
+ newMessages.push(message);
2566
+ }
2567
+ }
1589
2568
  if (config.fallbackManaged && message.stopReason !== "error" && message.stopReason !== "aborted") {
1590
2569
  await config.onManagedAttemptAccepted?.();
1591
2570
  }