@sayknow-cli/agent-core 0.7.2 → 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/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
@@ -757,154 +761,1146 @@ function isManagedPlainRecord(value: unknown): value is Record<string, unknown>
757
761
  return value !== null && typeof value === "object" && !Array.isArray(value) && !nodeUtilTypes.isProxy(value);
758
762
  }
759
763
 
764
+ /** An immutable ownership graph. Keys/tags are explicitly canonical; values are
765
+ * independently owned unless the ledger deliberately shares the same node ID.
766
+ * Atomic nodes preserve structured-clone graph topology (including cycles).
767
+ */
768
+ interface ManagedOwnedString {
769
+ kind: "string";
770
+ retainedRefs: number;
771
+ id: number;
772
+ value: string;
773
+ }
774
+ type ManagedValue =
775
+ | ManagedOwnedString
776
+ | ({ retainedRefs: number } & (
777
+ | { kind: "scalar"; id: number; value: undefined | null | boolean | number | bigint }
778
+ | { kind: "record" | "array"; id: number; fields: ManagedField[]; length: number; nullPrototype: boolean }
779
+ | { kind: "atomic"; id: number; value: object }
780
+ ));
781
+ interface ManagedField {
782
+ key: ManagedOwnedString;
783
+ value: ManagedValue;
784
+ }
785
+ interface ManagedPath {
786
+ id: number;
787
+ keys: Array<ManagedOwnedString | number>;
788
+ }
789
+ type ManagedPatch =
790
+ | { kind: "replace"; path: ManagedPath; value: ManagedValue }
791
+ | { kind: "delete"; path: ManagedPath }
792
+ | { kind: "truncate"; path: ManagedPath; length: number }
793
+ | { kind: "append"; path: ManagedPath; id: number; units: Uint16Array };
794
+ interface ManagedVersion {
795
+ id: number;
796
+ opStart: number;
797
+ opCount: number;
798
+ }
799
+ interface ManagedLedgerEntry {
800
+ kind: "event" | "callback";
801
+ type: ManagedOwnedString;
802
+ assistantType?: ManagedOwnedString;
803
+ shape: "plain" | "message" | "update" | "callback" | "messages";
804
+ nullPrototype: boolean;
805
+ assistantNullPrototype: boolean;
806
+ envelope: ManagedField[];
807
+ assistantEnvelope: ManagedField[];
808
+ refs: number[];
809
+ messageRef?: number;
810
+ partialRef?: number;
811
+ messageSlots?: ManagedValue;
812
+ opaque?: ManagedValue;
813
+ order: ManagedPath;
814
+ }
815
+ interface ManagedOwnedInventory {
816
+ totalBytes: number;
817
+ structuralBytes: number;
818
+ payloadBytes: number;
819
+ peakBytes: number;
820
+ recordCount: number;
821
+ strings: Array<{ ownerId: number; codeUnits: number; bytes: number }>;
822
+ buffers: Array<{ ownerId: number; kind: "suffix" | "typed"; bytes: number }>;
823
+ }
824
+
825
+ interface ManagedOpaqueEnvelope {
826
+ envelope: Record<string, unknown>;
827
+ assistantEnvelope: Record<string, unknown>;
828
+ messageSlots?: Array<number | AgentMessage>;
829
+ }
830
+
831
+ // Only opaque fields that share an object graph need a grouped owner. Ordinary
832
+ // scalar/delta envelopes retain the compact representation and its admission bound.
833
+ function managedFieldsShareGraph(fields: Array<[string, unknown]>): boolean {
834
+ const owners = new Map<object, number>();
835
+ let shared = false;
836
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
837
+ const visit = (value: unknown, owner: number, depth: number): void => {
838
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
839
+ if (value === null || typeof value !== "object") return;
840
+ const prior = owners.get(value);
841
+ if (prior !== undefined) {
842
+ if (prior !== owner) shared = true;
843
+ return;
844
+ }
845
+ owners.set(value, owner);
846
+ for (const [, child] of managedAtomicParts(value).fields) visit(child, owner, depth + 1);
847
+ };
848
+ for (let owner = 0; owner < fields.length; owner++) visit(fields[owner]![1], owner, 0);
849
+ return shared;
850
+ }
851
+
852
+ function managedOwnFields(value: object): Array<[string, unknown]> {
853
+ return Object.keys(value).map(key => {
854
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
855
+ if (!descriptor || !("value" in descriptor)) throw new ManagedAttemptSnapshotError();
856
+ return [key, descriptor.value];
857
+ });
858
+ }
859
+
860
+ // Raw atomic nodes are already detached by normalization. This walk is shared
861
+ // by equality and accounting, so an unsupported intrinsic cannot be accepted
862
+ // with an uncharged backing store. SharedArrayBuffer is intentionally rejected:
863
+ // structuredClone does not detach its backing memory from the provider.
864
+ function managedAtomicParts(value: object): {
865
+ tag: string;
866
+ fields: Array<[string, unknown]>;
867
+ buffer?: ArrayBuffer;
868
+ opaqueBytes?: number;
869
+ } {
870
+ if (nodeUtilTypes.isProxy(value) || nodeUtilTypes.isSharedArrayBuffer(value))
871
+ throw new ManagedAttemptSnapshotError();
872
+ if (nodeUtilTypes.isArrayBuffer(value)) return { tag: "ArrayBuffer", fields: [], buffer: value as ArrayBuffer };
873
+ if (ArrayBuffer.isView(value)) {
874
+ return {
875
+ tag: Object.getPrototypeOf(value).constructor.name,
876
+ fields: [
877
+ ["byteOffset", value.byteOffset],
878
+ ["byteLength", value.byteLength],
879
+ ["buffer", value.buffer],
880
+ ],
881
+ };
882
+ }
883
+ if (nodeUtilTypes.isDate(value)) return { tag: "Date", fields: [["time", Date.prototype.getTime.call(value)]] };
884
+ if (nodeUtilTypes.isRegExp(value)) {
885
+ const regexp = value as RegExp;
886
+ return {
887
+ tag: "RegExp",
888
+ fields: [
889
+ ["source", regexp.source],
890
+ ["flags", regexp.flags],
891
+ ["lastIndex", regexp.lastIndex],
892
+ ],
893
+ };
894
+ }
895
+ if (nodeUtilTypes.isMap(value)) {
896
+ const fields: Array<[string, unknown]> = [];
897
+ for (const [key, item] of Map.prototype.entries.call(value) as Iterable<[unknown, unknown]>) {
898
+ fields.push(["key", key], ["value", item]);
899
+ }
900
+ return { tag: "Map", fields };
901
+ }
902
+ if (nodeUtilTypes.isSet(value)) {
903
+ return {
904
+ tag: "Set",
905
+ fields: Array.from(Set.prototype.values.call(value) as Iterable<unknown>, item => ["value", item]),
906
+ };
907
+ }
908
+ if (nodeUtilTypes.isNativeError(value)) {
909
+ return {
910
+ tag: Object.getPrototypeOf(value).constructor.name,
911
+ fields: Object.getOwnPropertyNames(value).map(key => [
912
+ key,
913
+ Object.getOwnPropertyDescriptor(value, key)!.value,
914
+ ]),
915
+ };
916
+ }
917
+ if (nodeUtilTypes.isBoxedPrimitive(value)) {
918
+ const primitive = Object.getPrototypeOf(value).valueOf.call(value) as unknown;
919
+ return { tag: Object.getPrototypeOf(value).constructor.name, fields: [["value", primitive]] };
920
+ }
921
+ const prototype = Object.getPrototypeOf(value);
922
+ if (typeof Blob !== "undefined" && value instanceof Blob) {
923
+ const size = Object.getOwnPropertyDescriptor(Blob.prototype, "size")!.get!.call(value) as number;
924
+ const type = Object.getOwnPropertyDescriptor(Blob.prototype, "type")!.get!.call(value) as string;
925
+ // Blob backing data is immutable. Charge its full logical ownership and
926
+ // always replace it rather than guessing byte equality synchronously.
927
+ return { tag: "Blob", fields: [["type", type]], opaqueBytes: size };
928
+ }
929
+ if (Array.isArray(value)) return { tag: "Array", fields: [["length", value.length], ...managedOwnFields(value)] };
930
+ if (prototype === null || prototype === Object.prototype)
931
+ return { tag: prototype === null ? "NullRecord" : "Record", fields: managedOwnFields(value) };
932
+ throw new ManagedAttemptSnapshotError();
933
+ }
934
+
935
+ function managedGraphEqual(left: unknown, right: unknown): boolean {
936
+ const forward = new Map<object, object>();
937
+ const reverse = new Map<object, object>();
938
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
939
+ const equal = (a: unknown, b: unknown, depth: number): boolean => {
940
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
941
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return Object.is(a, b);
942
+ if (forward.has(a)) return forward.get(a) === b;
943
+ if (reverse.has(b)) return false;
944
+ forward.set(a, b);
945
+ reverse.set(b, a);
946
+ const ap = managedAtomicParts(a);
947
+ const bp = managedAtomicParts(b);
948
+ if (ap.tag !== bp.tag || ap.fields.length !== bp.fields.length || !!ap.buffer !== !!bp.buffer) return false;
949
+ if (ap.opaqueBytes !== undefined || bp.opaqueBytes !== undefined) return false;
950
+ if (ap.buffer && bp.buffer) {
951
+ if (ap.buffer.byteLength !== bp.buffer.byteLength) return false;
952
+ const aa = new Uint8Array(ap.buffer);
953
+ const bb = new Uint8Array(bp.buffer);
954
+ for (let i = 0; i < aa.length; i++) if (aa[i] !== bb[i]) return false;
955
+ }
956
+ return ap.fields.every(
957
+ ([key, item], index) => key === bp.fields[index]![0] && equal(item, bp.fields[index]![1], depth + 1),
958
+ );
959
+ };
960
+ return equal(left, right, 0);
961
+ }
962
+
963
+ function managedValueEqual(left: ManagedValue, right: ManagedValue): boolean {
964
+ if (left === right) return true;
965
+ if (left.kind !== right.kind) return false;
966
+ if (left.kind === "string" && right.kind === "string") return left.value === right.value;
967
+ if (left.kind === "scalar" && right.kind === "scalar") return Object.is(left.value, right.value);
968
+ if (left.kind === "atomic" && right.kind === "atomic") return managedGraphEqual(left.value, right.value);
969
+ if ((left.kind === "record" || left.kind === "array") && (right.kind === "record" || right.kind === "array")) {
970
+ return (
971
+ left.length === right.length &&
972
+ left.nullPrototype === right.nullPrototype &&
973
+ left.fields.length === right.fields.length &&
974
+ left.fields.every(
975
+ (field, index) =>
976
+ field.key.value === right.fields[index]!.key.value &&
977
+ managedValueEqual(field.value, right.fields[index]!.value),
978
+ )
979
+ );
980
+ }
981
+ return false;
982
+ }
983
+
984
+ function managedDecode(value: ManagedValue): unknown {
985
+ if (value.kind === "string" || value.kind === "scalar") return value.value;
986
+ if (value.kind === "atomic") return managedReplayClone(value.value);
987
+ const output: Record<string, unknown> | unknown[] =
988
+ value.kind === "array" ? new Array(value.length) : value.nullPrototype ? Object.create(null) : {};
989
+ for (const field of value.fields)
990
+ Object.defineProperty(output, field.key.value, {
991
+ value: managedDecode(field.value),
992
+ enumerable: true,
993
+ writable: true,
994
+ configurable: true,
995
+ });
996
+ return output;
997
+ }
998
+
999
+ // structuredClone detaches intrinsic graphs but intentionally erases null
1000
+ // record prototypes. Replay must retain the sanitizer's normalized data shape.
1001
+ function managedReplayClone<T>(value: T): T {
1002
+ const clone = structuredClone(value);
1003
+ const seen = new Map<object, object>();
1004
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1005
+ const restore = (source: unknown, target: unknown, depth: number): void => {
1006
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1007
+ if (source === null || typeof source !== "object") {
1008
+ if (!Object.is(source, target)) throw new ManagedAttemptSnapshotError();
1009
+ return;
1010
+ }
1011
+ if (target === null || typeof target !== "object") throw new ManagedAttemptSnapshotError();
1012
+ if (seen.has(source)) {
1013
+ if (seen.get(source) !== target) throw new ManagedAttemptSnapshotError();
1014
+ return;
1015
+ }
1016
+ seen.set(source, target);
1017
+ if (Object.getPrototypeOf(source) === null) Object.setPrototypeOf(target, null);
1018
+ const before = managedAtomicParts(source);
1019
+ const after = managedAtomicParts(target);
1020
+ if (before.tag !== after.tag || before.fields.length !== after.fields.length)
1021
+ throw new ManagedAttemptSnapshotError();
1022
+ for (let index = 0; index < before.fields.length; index++) {
1023
+ const [key, child] = before.fields[index]!;
1024
+ if (key !== after.fields[index]![0]) throw new ManagedAttemptSnapshotError();
1025
+ restore(child, after.fields[index]![1], depth + 1);
1026
+ }
1027
+ };
1028
+ restore(value, clone, 0);
1029
+ return clone;
1030
+ }
1031
+
1032
+ function managedReplaySuffix(units: Uint16Array): string {
1033
+ let result = "";
1034
+ for (let start = 0; start < units.length; start += 8_192) {
1035
+ // Only the bounded argument array is transient; the retained suffix owns
1036
+ // its backing buffer, not a view/substr of a cumulative provider string.
1037
+ result += String.fromCharCode(...units.subarray(start, Math.min(start + 8_192, units.length)));
1038
+ }
1039
+ return result;
1040
+ }
1041
+
1042
+ class ManagedAttemptObserverError extends Error {
1043
+ constructor(cause: unknown) {
1044
+ super(
1045
+ `Managed fallback committed output observer failed: ${cause instanceof Error ? cause.message : "observer exception"}`,
1046
+ { cause },
1047
+ );
1048
+ this.name = "ManagedAttemptObserverError";
1049
+ }
1050
+ }
1051
+
760
1052
  /**
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.
1053
+ * @internal Unsupported transaction/test seam, not a public config or metrics API.
1054
+ * Inventory measures retained provisional ownership, never process RSS or
1055
+ * postcommit EventStream/consumer snapshots.
764
1056
  */
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;
1057
+ export class ManagedAttemptTransaction {
1058
+ #entries: Array<ManagedLedgerEntry | undefined> = [];
1059
+ #versions: Array<ManagedVersion | undefined> = [];
1060
+ #ops: Array<ManagedPatch | undefined> = [];
1061
+ #keys = new Map<string, ManagedOwnedString>();
1062
+ #paths: ManagedPath[] = [];
1063
+ #nextOwnerId = 0;
1064
+ #latest: ManagedValue | undefined;
1065
+ #peakBytes = 0;
1066
+ #retainedBytes = 64 * 5;
772
1067
  #discarded = false;
773
1068
  #committed = false;
1069
+ #publishedAssistant: AssistantMessage | undefined;
1070
+ #stream: EventStream<AgentEvent, AgentMessage[]>;
1071
+ #observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined;
1072
+ #model: AgentLoopConfig["model"];
1073
+
1074
+ #visibleSince: number | undefined;
774
1075
 
775
1076
  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
- ) {}
1077
+ stream: EventStream<AgentEvent, AgentMessage[]>,
1078
+ observer: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined,
1079
+ model: AgentLoopConfig["model"],
1080
+ ) {
1081
+ this.#stream = stream;
1082
+ this.#observer = observer;
1083
+ this.#model = model;
1084
+ }
1085
+
1086
+ #string(value: string): ManagedOwnedString {
1087
+ // Construct by code units instead of retaining a provider substring.
1088
+ const units = new Uint16Array(value.length);
1089
+ for (let index = 0; index < value.length; index++) units[index] = value.charCodeAt(index);
1090
+ return { kind: "string", id: ++this.#nextOwnerId, retainedRefs: 0, value: managedReplaySuffix(units) };
1091
+ }
1092
+
1093
+ #key(value: string): ManagedOwnedString {
1094
+ let key = this.#keys.get(value);
1095
+ if (!key) {
1096
+ key = this.#string(value);
1097
+ this.#keys.set(key.value, key);
1098
+ this.#retainedBytes += 32;
1099
+ this.#retain(key);
1100
+ }
1101
+ return key;
1102
+ }
1103
+
1104
+ #encode(value: unknown): ManagedValue {
1105
+ // Shared/cyclic graphs are atomic rather than tree patches: splitting them
1106
+ // into independent replacements would lose aliases and cycle backrefs.
1107
+ const seen = new Set<object>();
1108
+ let shared = false;
1109
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1110
+ const inspect = (item: unknown, depth: number): void => {
1111
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1112
+ if (item === null || typeof item !== "object") return;
1113
+ if (seen.has(item)) {
1114
+ shared = true;
1115
+ return;
1116
+ }
1117
+ seen.add(item);
1118
+ for (const [, child] of managedAtomicParts(item).fields) inspect(child, depth + 1);
1119
+ };
1120
+ inspect(value, 0);
1121
+ const encode = (item: unknown): ManagedValue => {
1122
+ if (typeof item === "string") return this.#string(item);
1123
+ if (
1124
+ item === null ||
1125
+ item === undefined ||
1126
+ typeof item === "boolean" ||
1127
+ typeof item === "number" ||
1128
+ typeof item === "bigint"
1129
+ )
1130
+ return { kind: "scalar", id: ++this.#nextOwnerId, retainedRefs: 0, value: item };
1131
+ if (typeof item !== "object") throw new ManagedAttemptSnapshotError();
1132
+ const prototype = Object.getPrototypeOf(item);
1133
+ if (!Array.isArray(item) && prototype !== null && prototype !== Object.prototype)
1134
+ return { kind: "atomic", id: ++this.#nextOwnerId, retainedRefs: 0, value: managedReplayClone(item) };
1135
+ return {
1136
+ kind: Array.isArray(item) ? "array" : "record",
1137
+ id: ++this.#nextOwnerId,
1138
+ retainedRefs: 0,
1139
+ fields: managedOwnFields(item).map(([key, child]) => ({ key: this.#key(key), value: encode(child) })),
1140
+ length: Array.isArray(item) ? item.length : 0,
1141
+ nullPrototype: prototype === null,
1142
+ };
1143
+ };
1144
+ return shared && value !== null && typeof value === "object"
1145
+ ? { kind: "atomic", id: ++this.#nextOwnerId, retainedRefs: 0, value: managedReplayClone(value) }
1146
+ : encode(value);
1147
+ }
1148
+
1149
+ #path(keys: Array<ManagedOwnedString | number>): ManagedPath {
1150
+ const previous = this.#paths.find(
1151
+ path =>
1152
+ path.keys.length === keys.length &&
1153
+ path.keys.every((key, index) =>
1154
+ typeof key === "number" ? key === keys[index] : typeof keys[index] !== "number" && key === keys[index],
1155
+ ),
1156
+ );
1157
+ if (previous) return previous;
1158
+ const path = { id: ++this.#nextOwnerId, keys: [...keys] };
1159
+ this.#paths.push(path);
1160
+ this.#retainedBytes += 32 + 64 + keys.length * 32;
1161
+ for (const key of keys) {
1162
+ if (typeof key === "number") this.#retainedBytes += 8;
1163
+ else this.#retain(key);
1164
+ }
1165
+ return path;
1166
+ }
1167
+
1168
+ #transition(next: ManagedValue): number {
1169
+ if (this.#latest && managedValueEqual(this.#latest, next)) return this.#versions.length;
1170
+ const opStart = this.#ops.length;
1171
+ const diff = (
1172
+ previous: ManagedValue | undefined,
1173
+ value: ManagedValue,
1174
+ keys: Array<ManagedOwnedString | number>,
1175
+ ): ManagedValue => {
1176
+ if (previous && managedValueEqual(previous, value)) return previous;
1177
+ if (previous?.kind === "string" && value.kind === "string" && value.value.startsWith(previous.value)) {
1178
+ const units = new Uint16Array(value.value.length - previous.value.length);
1179
+ for (let i = 0; i < units.length; i++) units[i] = value.value.charCodeAt(previous.value.length + i);
1180
+ this.#ops.push({ kind: "append", path: this.#path(keys), id: ++this.#nextOwnerId, units });
1181
+ return value;
1182
+ }
1183
+ if (
1184
+ previous &&
1185
+ (previous.kind === "record" || previous.kind === "array") &&
1186
+ value.kind === previous.kind &&
1187
+ (value.kind === "record" || value.kind === "array") &&
1188
+ value.nullPrototype === previous.nullPrototype
1189
+ ) {
1190
+ const oldKeys = previous.fields.map(field => field.key.value);
1191
+ const newKeys = value.fields.map(field => field.key.value);
1192
+ const commonOld = oldKeys.filter(key => newKeys.includes(key));
1193
+ const commonNew = newKeys.filter(key => oldKeys.includes(key));
1194
+ const retainedThenAdded = [...commonOld, ...newKeys.filter(key => !oldKeys.includes(key))];
1195
+ const dense = (node: typeof value) =>
1196
+ node.kind !== "array" ||
1197
+ (node.fields.length === node.length &&
1198
+ node.fields.every((field, index) => field.key.value === String(index)));
1199
+ // Primitive array reorders/replacements are atomic. Positional record
1200
+ // updates (e.g. content/tool arguments) remain ordinary field patches.
1201
+ const stableArray =
1202
+ value.kind !== "array" ||
1203
+ (dense(value) &&
1204
+ dense(previous) &&
1205
+ previous.fields
1206
+ .slice(0, Math.min(previous.length, value.length))
1207
+ .every(
1208
+ (field, index) =>
1209
+ managedValueEqual(field.value, value.fields[index]!.value) ||
1210
+ (field.value.kind === "record" && value.fields[index]!.value.kind === "record"),
1211
+ ));
1212
+ if (
1213
+ stableArray &&
1214
+ commonOld.every((key, index) => key === commonNew[index]) &&
1215
+ retainedThenAdded.every((key, index) => key === newKeys[index])
1216
+ ) {
1217
+ for (const field of previous.fields)
1218
+ if (!newKeys.includes(field.key.value) && value.kind !== "array")
1219
+ this.#ops.push({ kind: "delete", path: this.#path([...keys, field.key]) });
1220
+ const fields = value.fields.map(field => {
1221
+ const old = previous.fields.find(candidate => candidate.key === field.key);
1222
+ return {
1223
+ key: field.key,
1224
+ value: diff(old?.value, field.value, [
1225
+ ...keys,
1226
+ value.kind === "array" ? Number(field.key.value) : field.key,
1227
+ ]),
1228
+ };
1229
+ });
1230
+ if (value.kind === "array" && value.length < previous.length)
1231
+ this.#ops.push({ kind: "truncate", path: this.#path(keys), length: value.length });
1232
+ return { ...value, fields };
1233
+ }
1234
+ }
1235
+ this.#ops.push({ kind: "replace", path: this.#path(keys), value });
1236
+ return value;
1237
+ };
1238
+ const previous = this.#latest;
1239
+ this.#latest = diff(previous, next, []);
1240
+ this.#retain(this.#latest);
1241
+ if (previous) this.#releaseNode(previous);
1242
+ for (let index = opStart; index < this.#ops.length; index++) {
1243
+ const op = this.#ops[index]!;
1244
+ this.#retainedBytes += 64 + 16;
1245
+ if (op.kind === "replace") this.#retain(op.value);
1246
+ else if (op.kind === "append") this.#retainedBytes += 64 + op.units.byteLength;
1247
+ else if (op.kind === "truncate") this.#retainedBytes += 8;
1248
+ }
1249
+ const id = this.#versions.length + 1;
1250
+ this.#versions.push({ id, opStart, opCount: this.#ops.length - opStart });
1251
+ this.#retainedBytes += 16;
1252
+ return id;
1253
+ }
1254
+
1255
+ /** Whether staged output has been published; later failures cannot be hidden. */
1256
+ get committed(): boolean {
1257
+ return this.#committed;
1258
+ }
782
1259
 
783
1260
  push(event: AgentEvent): void {
784
1261
  if (this.#committed) {
785
- this.stream.push(event);
1262
+ this.#stream.push(event);
786
1263
  return;
787
1264
  }
788
- this.#stage(event);
1265
+ this.#stage("event", event);
789
1266
  }
790
1267
 
791
1268
  end(messages: AgentMessage[]): void {
792
- this.stream.end(messages);
1269
+ this.#stream.end(messages);
793
1270
  }
794
1271
 
795
1272
  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
- });
1273
+ if (!this.#observer) return;
1274
+ if (this.#committed) {
1275
+ this.#observer(message, event);
1276
+ return;
1277
+ }
1278
+ this.#stage("callback", { message, event });
1279
+ }
1280
+
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;
802
1292
  }
803
1293
 
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);
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";
1297
+ let serialized: string | undefined;
1298
+ try {
1299
+ serialized = JSON.stringify(input);
1300
+ } catch {
1301
+ return false;
1302
+ }
1303
+ if (serialized === undefined) throw new ManagedAttemptSnapshotError();
1304
+ if (managedAttemptTextEncoder.encode(serialized).byteLength > MANAGED_ATTEMPT_MAX_STAGED_BYTES) return "overflow";
1305
+ return true;
1306
+ }
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
+
1329
+ #stage(
1330
+ kind: "event" | "callback",
1331
+ input: AgentEvent | { message: AssistantMessage; event: AssistantMessageEvent },
1332
+ ): void {
1333
+ if (this.#discarded) throw new ManagedAttemptSnapshotError();
1334
+ try {
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
+ }
1344
+ let normalized: unknown;
1345
+ if (kind === "callback") {
1346
+ const callback = input as { message: AssistantMessage; event: AssistantMessageEvent };
1347
+ const message = managedAssistantShell(callback.message, this.#model);
1348
+ normalized = { message, event: managedAssistantEventSnapshot(callback.event, message) };
809
1349
  } else {
810
- this.stream.push(item.event);
1350
+ normalized = managedAttemptSnapshotDetailed(this.#repairAssistantEvent(input as AgentEvent)).snapshot;
1351
+ if (!measured) {
1352
+ try {
1353
+ JSON.stringify(normalized);
1354
+ } catch {
1355
+ normalized = sanitizedDetachedClone(normalized);
1356
+ }
1357
+ }
1358
+ }
1359
+ const record = normalized as Record<string, unknown>;
1360
+ const assistantEvent = (kind === "callback" ? record.event : record.assistantMessageEvent) as
1361
+ | Record<string, unknown>
1362
+ | undefined;
1363
+ const entry: ManagedLedgerEntry = {
1364
+ kind,
1365
+ type: this.#key(String(kind === "callback" ? assistantEvent?.type : record.type)),
1366
+ shape:
1367
+ kind === "callback"
1368
+ ? "callback"
1369
+ : record.type === "message_update"
1370
+ ? "update"
1371
+ : record.type === "agent_end"
1372
+ ? "messages"
1373
+ : "plain",
1374
+ nullPrototype: Object.getPrototypeOf(record) === null,
1375
+ assistantNullPrototype: assistantEvent !== undefined && Object.getPrototypeOf(assistantEvent) === null,
1376
+ envelope: [],
1377
+ assistantEnvelope: [],
1378
+ refs: [],
1379
+ order: this.#path([
1380
+ ...Object.keys(record).map(key => this.#key(key)),
1381
+ -1,
1382
+ ...Object.keys(assistantEvent ?? {}).map(key => this.#key(key)),
1383
+ ]),
1384
+ };
1385
+ const references = new Map<object, number>();
1386
+ const envelopeFields: Array<[string, unknown]> = [];
1387
+ const assistantFields: Array<[string, unknown]> = [];
1388
+ const observe = (message: unknown): number => {
1389
+ if (!message || typeof message !== "object" || (message as Record<string, unknown>).role !== "assistant")
1390
+ throw new ManagedAttemptSnapshotError();
1391
+ const existing = references.get(message);
1392
+ if (existing !== undefined) return existing;
1393
+ const slot = entry.refs.length;
1394
+ entry.refs.push(this.#transition(this.#encode(message)));
1395
+ references.set(message, slot);
1396
+ return slot;
1397
+ };
1398
+ if (record.message && (record.message as Record<string, unknown>).role === "assistant") {
1399
+ entry.messageRef = observe(record.message);
1400
+ if (entry.shape === "plain") entry.shape = "message";
1401
+ }
1402
+ if (assistantEvent) {
1403
+ entry.assistantType = this.#key(String(assistantEvent.type));
1404
+ for (const [key, value] of managedOwnFields(assistantEvent)) {
1405
+ if (key === "partial" || key === "message" || key === "error") entry.partialRef = observe(value);
1406
+ else if (key !== "type") assistantFields.push([key, value]);
1407
+ }
1408
+ }
1409
+ const messageSlots =
1410
+ entry.shape === "messages"
1411
+ ? ((record.messages as unknown[]).map(message =>
1412
+ message && typeof message === "object" && (message as Record<string, unknown>).role === "assistant"
1413
+ ? observe(message)
1414
+ : message,
1415
+ ) as Array<number | AgentMessage>)
1416
+ : undefined;
1417
+ for (const [key, value] of managedOwnFields(record)) {
1418
+ if (
1419
+ key === "type" ||
1420
+ (key === "message" && entry.messageRef !== undefined) ||
1421
+ (key === "messages" && entry.shape === "messages") ||
1422
+ (key === "event" && kind === "callback") ||
1423
+ (key === "assistantMessageEvent" && assistantEvent)
1424
+ )
1425
+ continue;
1426
+ envelopeFields.push([key, value]);
811
1427
  }
1428
+ if (
1429
+ managedFieldsShareGraph([
1430
+ ...envelopeFields,
1431
+ ...assistantFields,
1432
+ ...(messageSlots ? [["messages", messageSlots] as [string, unknown]] : []),
1433
+ ])
1434
+ ) {
1435
+ const opaque: ManagedOpaqueEnvelope = {
1436
+ envelope: Object.create(null),
1437
+ assistantEnvelope: Object.create(null),
1438
+ };
1439
+ for (const [key, value] of envelopeFields)
1440
+ Object.defineProperty(opaque.envelope, key, { value, enumerable: true });
1441
+ for (const [key, value] of assistantFields)
1442
+ Object.defineProperty(opaque.assistantEnvelope, key, { value, enumerable: true });
1443
+ if (messageSlots) opaque.messageSlots = messageSlots;
1444
+ entry.opaque = this.#encode(opaque);
1445
+ } else {
1446
+ entry.envelope = envelopeFields.map(([key, value]) => ({
1447
+ key: this.#key(key),
1448
+ value: this.#encode(value),
1449
+ }));
1450
+ entry.assistantEnvelope = assistantFields.map(([key, value]) => ({
1451
+ key: this.#key(key),
1452
+ value: this.#encode(value),
1453
+ }));
1454
+ if (messageSlots) entry.messageSlots = this.#encode(messageSlots);
1455
+ }
1456
+ // A callback/event pair may canonicalize identical immutable delta
1457
+ // payloads, never their independently sampled state or record count.
1458
+ const previous = this.#entries.at(-1);
1459
+ if (kind === "event" && previous?.kind === "callback" && previous.assistantType === entry.assistantType) {
1460
+ for (const field of entry.assistantEnvelope) {
1461
+ const old = previous.assistantEnvelope.find(candidate => candidate.key === field.key);
1462
+ if (old && managedValueEqual(old.value, field.value) && field.value.kind === "string")
1463
+ field.value = old.value;
1464
+ }
1465
+ }
1466
+ this.#entries.push(entry);
1467
+ this.#retainedBytes += 128 + 16 + (entry.refs.length + 1) * 16;
1468
+ this.#retain(entry.type);
1469
+ if (entry.assistantType) this.#retain(entry.assistantType);
1470
+ if (entry.opaque) {
1471
+ this.#retainedBytes += 16;
1472
+ this.#retain(entry.opaque);
1473
+ }
1474
+ for (const field of [...entry.envelope, ...entry.assistantEnvelope]) {
1475
+ this.#retainedBytes += 32;
1476
+ this.#retain(field.key);
1477
+ this.#retain(field.value);
1478
+ }
1479
+ if (entry.messageSlots) {
1480
+ this.#retainedBytes += 16;
1481
+ this.#retain(entry.messageSlots);
1482
+ }
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
+ }
1488
+ } catch (error) {
1489
+ // Once published, failures are ordinary run errors (observer/replay), not
1490
+ // discardable staging failures.
1491
+ if (this.#committed) throw error;
1492
+ this.discard();
1493
+ if (error instanceof ManagedAttemptSnapshotError) throw error;
1494
+ throw new ManagedAttemptSnapshotError();
812
1495
  }
813
- this.#batch = [];
814
- this.#stagedBytes = 0;
815
- this.#stagedEventCount = 0;
816
- this.#committed = true;
817
1496
  }
818
1497
 
819
- discard(): void {
820
- this.#batch = [];
821
- this.#stagedBytes = 0;
822
- this.#stagedEventCount = 0;
823
- this.#discarded = true;
1498
+ // Admission visits only acquired/released owners, never the preceding log.
1499
+ // The full inventory below independently checks this counter in tests.
1500
+ #nodeBytes(value: ManagedValue): number {
1501
+ if (value.kind === "string") return 8 + 24 + 2 * value.value.length;
1502
+ if (value.kind === "scalar")
1503
+ return 8 + (typeof value.value === "bigint" ? 24 + 2 * String(value.value).length : 8);
1504
+ if (value.kind !== "atomic") return 8 + 64 + 8 + 32 * value.fields.length;
1505
+ const seen = new Set<object>();
1506
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1507
+ const raw = (item: unknown, depth: number): number => {
1508
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1509
+ if (typeof item === "string") return 24 + 2 * item.length;
1510
+ if (item === null || typeof item !== "object")
1511
+ return typeof item === "bigint" ? 24 + 2 * String(item).length : 8;
1512
+ if (seen.has(item)) return 16;
1513
+ seen.add(item);
1514
+ const parts = managedAtomicParts(item);
1515
+ let bytes = 64 + (parts.buffer?.byteLength ?? parts.opaqueBytes ?? 0);
1516
+ for (const [key, child] of parts.fields) bytes += 32 + 24 + 2 * key.length + raw(child, depth + 1);
1517
+ return bytes;
1518
+ };
1519
+ return 8 + 64 + raw(value.value, 0);
824
1520
  }
825
1521
 
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
- );
1522
+ #retain(value: ManagedValue): void {
1523
+ if (value.retainedRefs++ !== 0) return;
1524
+ this.#retainedBytes += this.#nodeBytes(value);
1525
+ if (value.kind === "record" || value.kind === "array") {
1526
+ for (const field of value.fields) {
1527
+ this.#retain(field.key);
1528
+ this.#retain(field.value);
1529
+ }
1530
+ }
831
1531
  }
832
1532
 
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;
1533
+ #releaseNode(value: ManagedValue): void {
1534
+ if (--value.retainedRefs !== 0) return;
1535
+ this.#retainedBytes -= this.#nodeBytes(value);
1536
+ if (value.kind === "record" || value.kind === "array") {
1537
+ for (const field of value.fields) {
1538
+ this.#releaseNode(field.key);
1539
+ this.#releaseNode(field.value);
1540
+ }
845
1541
  }
846
- if (bytes !== undefined && this.#wouldOverflow(bytes)) {
847
- this.discard();
848
- throw new ManagedAttemptBufferOverflowError();
1542
+ }
1543
+
1544
+ /** Inventory walks the actual retained ownership roots, not input lengths or
1545
+ * an estimated snapshot savings counter. Canonical aliases share an ID;
1546
+ * independently owned strings are charged even when JS values compare equal.
1547
+ */
1548
+ ownedInventory(): ManagedOwnedInventory {
1549
+ const inventory: ManagedOwnedInventory = {
1550
+ totalBytes: 0,
1551
+ structuralBytes: 0,
1552
+ payloadBytes: 0,
1553
+ peakBytes: this.#peakBytes,
1554
+ recordCount: this.#entries.length,
1555
+ strings: [],
1556
+ buffers: [],
1557
+ };
1558
+ if (!this.#entries.length && !this.#latest) return inventory;
1559
+ const seen = new Set<number>();
1560
+ const rawSeen = new Map<object, number>();
1561
+ let budget = MANAGED_SNAPSHOT_MAX_NODES;
1562
+ let rawOwner = this.#nextOwnerId;
1563
+ const string = (id: number, value: string) => {
1564
+ inventory.structuralBytes += 24;
1565
+ const bytes = value.length * 2;
1566
+ inventory.payloadBytes += bytes;
1567
+ inventory.strings.push({ ownerId: id, codeUnits: value.length, bytes });
1568
+ };
1569
+ const raw = (value: unknown, depth: number): void => {
1570
+ if (--budget < 0 || depth > 512) throw new ManagedAttemptSnapshotError();
1571
+ if (typeof value === "string") {
1572
+ string(++rawOwner, value);
1573
+ return;
1574
+ }
1575
+ if (value === null || typeof value !== "object") {
1576
+ if (typeof value === "bigint") string(++rawOwner, String(value));
1577
+ else inventory.structuralBytes += 8;
1578
+ return;
1579
+ }
1580
+ if (rawSeen.has(value)) {
1581
+ inventory.structuralBytes += 16;
1582
+ return;
1583
+ }
1584
+ const ownerId = ++rawOwner;
1585
+ rawSeen.set(value, ownerId);
1586
+ const parts = managedAtomicParts(value);
1587
+ inventory.structuralBytes += 64;
1588
+ const bytes = parts.buffer?.byteLength ?? parts.opaqueBytes;
1589
+ if (bytes !== undefined) {
1590
+ inventory.payloadBytes += bytes;
1591
+ inventory.buffers.push({ ownerId, kind: "typed", bytes });
1592
+ }
1593
+ for (const [key, child] of parts.fields) {
1594
+ inventory.structuralBytes += 32;
1595
+ string(++rawOwner, key);
1596
+ raw(child, depth + 1);
1597
+ }
1598
+ };
1599
+ const node = (value: ManagedValue): void => {
1600
+ if (seen.has(value.id)) return;
1601
+ seen.add(value.id);
1602
+ inventory.structuralBytes += 8; // Embedded ownership reference count.
1603
+ if (value.kind === "string") string(value.id, value.value);
1604
+ else if (value.kind === "scalar") {
1605
+ if (typeof value.value === "bigint") string(value.id, String(value.value));
1606
+ else inventory.structuralBytes += 8;
1607
+ } else if (value.kind === "atomic") {
1608
+ inventory.structuralBytes += 64;
1609
+ raw(value.value, 0);
1610
+ } else {
1611
+ inventory.structuralBytes += 64 + 8;
1612
+ fields(value.fields);
1613
+ }
1614
+ };
1615
+ const fields = (values: ManagedField[]): void => {
1616
+ for (const field of values) {
1617
+ inventory.structuralBytes += 32;
1618
+ node(field.key);
1619
+ node(field.value);
1620
+ }
1621
+ };
1622
+ // Container headers and every actual key-pool/path-pool member remain
1623
+ // charged even when no longer reachable from the latest state.
1624
+ inventory.structuralBytes += 64 * 5 + this.#keys.size * 32 + this.#paths.length * 32;
1625
+ for (const key of this.#keys.values()) node(key);
1626
+ for (const path of this.#paths) {
1627
+ inventory.structuralBytes += 64 + path.keys.length * 32;
1628
+ for (const key of path.keys) {
1629
+ if (typeof key === "number") inventory.structuralBytes += 8;
1630
+ else node(key);
1631
+ }
849
1632
  }
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;
1633
+ for (const entry of this.#entries) {
1634
+ if (!entry) continue;
1635
+ inventory.structuralBytes += 128 + 16 + (entry.refs.length + 1) * 16;
1636
+ node(entry.type);
1637
+ if (entry.assistantType) node(entry.assistantType);
1638
+ if (entry.opaque) {
1639
+ inventory.structuralBytes += 16;
1640
+ node(entry.opaque);
1641
+ }
1642
+ fields(entry.envelope);
1643
+ fields(entry.assistantEnvelope);
1644
+ if (entry.messageSlots) {
1645
+ inventory.structuralBytes += 16;
1646
+ node(entry.messageSlots);
1647
+ }
1648
+ }
1649
+ for (const version of this.#versions) if (version) inventory.structuralBytes += 16;
1650
+ for (const op of this.#ops) {
1651
+ if (!op) continue;
1652
+ inventory.structuralBytes += 64 + 16;
1653
+ if (op.kind === "replace") node(op.value);
1654
+ else if (op.kind === "append") {
1655
+ inventory.structuralBytes += 64;
1656
+ inventory.payloadBytes += op.units.byteLength;
1657
+ inventory.buffers.push({ ownerId: op.id, kind: "suffix", bytes: op.units.byteLength });
1658
+ } else if (op.kind === "truncate") inventory.structuralBytes += 8;
1659
+ }
1660
+ if (this.#latest) node(this.#latest);
1661
+ inventory.totalBytes = inventory.structuralBytes + inventory.payloadBytes;
1662
+ if (!this.#committed && inventory.totalBytes !== this.#retainedBytes) throw new ManagedAttemptSnapshotError();
1663
+ inventory.peakBytes = Math.max(inventory.peakBytes, inventory.totalBytes);
1664
+ return inventory;
1665
+ }
1666
+
1667
+ #replay(consume: boolean, dispatch?: (entry: ManagedLedgerEntry, output: unknown) => boolean): boolean {
1668
+ let working: unknown;
1669
+ let versionIndex = 0;
1670
+ const advance = (id: number): void => {
1671
+ if (id < versionIndex) throw new ManagedAttemptSnapshotError();
1672
+ while (versionIndex < id) {
1673
+ const version = this.#versions[versionIndex];
1674
+ if (!version || version.id !== versionIndex + 1) throw new ManagedAttemptSnapshotError();
1675
+ for (let index = version.opStart; index < version.opStart + version.opCount; index++) {
1676
+ const op = this.#ops[index];
1677
+ if (!op) throw new ManagedAttemptSnapshotError();
1678
+ const keys = op.path.keys.map(key => (typeof key === "number" ? key : key.value));
1679
+ let parent = working as Record<string | number, unknown>;
1680
+ for (const key of keys.slice(0, -1)) {
1681
+ const descriptor = parent && Object.getOwnPropertyDescriptor(parent, key);
1682
+ if (!descriptor || !("value" in descriptor)) throw new ManagedAttemptSnapshotError();
1683
+ parent = descriptor.value;
1684
+ }
1685
+ const key = keys.at(-1);
1686
+ const current =
1687
+ key === undefined ? working : parent && Object.getOwnPropertyDescriptor(parent, key)?.value;
1688
+ if (op.kind === "delete") {
1689
+ if (key === undefined || !parent || !Object.hasOwn(parent, key))
1690
+ throw new ManagedAttemptSnapshotError();
1691
+ delete parent[key];
1692
+ } else if (op.kind === "truncate") {
1693
+ if (!Array.isArray(current) || op.length > current.length) throw new ManagedAttemptSnapshotError();
1694
+ current.length = op.length;
1695
+ } else {
1696
+ if (op.kind === "append" && typeof current !== "string") throw new ManagedAttemptSnapshotError();
1697
+ const value =
1698
+ op.kind === "replace"
1699
+ ? managedDecode(op.value)
1700
+ : (current as string) + managedReplaySuffix(op.units);
1701
+ if (key === undefined) working = value;
1702
+ else
1703
+ Object.defineProperty(parent, key, {
1704
+ value,
1705
+ enumerable: true,
1706
+ writable: true,
1707
+ configurable: true,
1708
+ });
1709
+ }
1710
+ if (consume) this.#ops[index] = undefined;
865
1711
  }
1712
+ if (consume) this.#versions[versionIndex] = undefined;
1713
+ versionIndex++;
866
1714
  }
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();
1715
+ };
1716
+ const decodeFields = (fields: ManagedField[], output: Record<string, unknown>) => {
1717
+ for (const field of fields)
1718
+ Object.defineProperty(output, field.key.value, {
1719
+ value: managedDecode(field.value),
1720
+ enumerable: true,
1721
+ configurable: true,
1722
+ writable: true,
1723
+ });
1724
+ };
1725
+ const ordered = (
1726
+ output: Record<string, unknown>,
1727
+ order: ManagedPath,
1728
+ assistant: boolean,
1729
+ nullPrototype: boolean,
1730
+ ): Record<string, unknown> => {
1731
+ const result: Record<string, unknown> = nullPrototype ? Object.create(null) : {};
1732
+ let inAssistant = false;
1733
+ for (const key of order.keys) {
1734
+ if (typeof key === "number") {
1735
+ inAssistant = true;
1736
+ continue;
1737
+ }
1738
+ if (inAssistant !== assistant || !Object.hasOwn(output, key.value)) continue;
1739
+ Object.defineProperty(result, key.value, {
1740
+ value: output[key.value],
1741
+ enumerable: true,
1742
+ configurable: true,
1743
+ writable: true,
1744
+ });
874
1745
  }
875
- if (this.#wouldOverflow(bytes)) {
876
- this.discard();
877
- throw new ManagedAttemptBufferOverflowError();
1746
+ if (Object.keys(result).length !== Object.keys(output).length) throw new ManagedAttemptSnapshotError();
1747
+ return result;
1748
+ };
1749
+ for (let index = 0; index < this.#entries.length; index++) {
1750
+ const entry = this.#entries[index];
1751
+ if (!entry) throw new ManagedAttemptSnapshotError();
1752
+ const messages = entry.refs.map(id => {
1753
+ advance(id);
1754
+ return managedReplayClone(working) as AssistantMessage;
1755
+ });
1756
+ for (const message of messages)
1757
+ if (message?.role !== "assistant" || !Array.isArray(message.content))
1758
+ throw new ManagedAttemptSnapshotError();
1759
+ const output: Record<string, unknown> = {};
1760
+ const opaque = entry.opaque ? (managedDecode(entry.opaque) as ManagedOpaqueEnvelope) : undefined;
1761
+ if (opaque) {
1762
+ for (const [key, value] of managedOwnFields(opaque.envelope))
1763
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
1764
+ } else decodeFields(entry.envelope, output);
1765
+ if (entry.kind === "event") output.type = entry.type.value;
1766
+ if (entry.messageRef !== undefined) output.message = messages[entry.messageRef];
1767
+ if (entry.assistantType) {
1768
+ const event: Record<string, unknown> = { type: entry.assistantType.value };
1769
+ if (opaque) {
1770
+ for (const [key, value] of managedOwnFields(opaque.assistantEnvelope))
1771
+ Object.defineProperty(event, key, { value, enumerable: true, configurable: true, writable: true });
1772
+ } else decodeFields(entry.assistantEnvelope, event);
1773
+ if (entry.partialRef !== undefined)
1774
+ event[
1775
+ entry.assistantType.value === "done"
1776
+ ? "message"
1777
+ : entry.assistantType.value === "error"
1778
+ ? "error"
1779
+ : "partial"
1780
+ ] = messages[entry.partialRef];
1781
+ // Validation never calls observers and rejects malformed replay before
1782
+ // the irrevocable commit point, without materializing an output batch.
1783
+ managedAssistantEventSnapshot(
1784
+ event as unknown as AssistantMessageEvent,
1785
+ messages[entry.partialRef ?? entry.messageRef ?? 0]!,
1786
+ );
1787
+ output[entry.kind === "callback" ? "event" : "assistantMessageEvent"] = ordered(
1788
+ event,
1789
+ entry.order,
1790
+ true,
1791
+ entry.assistantNullPrototype,
1792
+ );
878
1793
  }
1794
+ const slots = entry.messageSlots
1795
+ ? (managedDecode(entry.messageSlots) as Array<number | AgentMessage>)
1796
+ : opaque?.messageSlots;
1797
+ if (slots) output.messages = slots.map(slot => (typeof slot === "number" ? messages[slot] : slot));
1798
+ if (!dispatch) ordered(output, entry.order, false, entry.nullPrototype);
1799
+ if (consume) this.#entries[index] = undefined;
1800
+ if (dispatch && !dispatch(entry, ordered(output, entry.order, false, entry.nullPrototype))) return false;
879
1801
  }
880
- this.#batch.push({ type: "event", event: snapshot });
881
- this.#stagedEventCount += 1;
1802
+ return true;
1803
+ }
882
1804
 
883
- this.#stagedBytes += bytes;
1805
+ flush(signal?: AbortSignal): boolean {
1806
+ if (this.#discarded) return false;
1807
+ if (this.#committed) return true;
1808
+ if (signal?.aborted) {
1809
+ this.discard();
1810
+ return false;
1811
+ }
1812
+ try {
1813
+ this.#replay(false);
1814
+ } catch {
1815
+ this.discard();
1816
+ throw new ManagedAttemptSnapshotError();
1817
+ }
1818
+ if (signal?.aborted) {
1819
+ this.discard();
1820
+ return false;
1821
+ }
1822
+ // No validation scratch or whole-output batch survives this point. The
1823
+ // queue and consumer-held detached snapshots are outside provisional L.
1824
+ this.#committed = true;
1825
+ this.#latest = undefined;
1826
+ try {
1827
+ const complete = this.#replay(true, (entry, output) => {
1828
+ if (signal?.aborted) return false;
1829
+ // One postcommit history snapshot, detached before an observer can
1830
+ // mutate its output. It is not retained provisional output or a batch.
1831
+ const message = (output as Record<string, unknown>).message;
1832
+ if (message && typeof message === "object" && (message as AssistantMessage).role === "assistant") {
1833
+ this.#publishedAssistant = managedReplayClone(message) as AssistantMessage;
1834
+ }
1835
+ if (entry.kind === "callback") {
1836
+ const callback = output as { message: AssistantMessage; event: AssistantMessageEvent };
1837
+ try {
1838
+ this.#observer?.(callback.message, callback.event);
1839
+ } catch (error) {
1840
+ throw new ManagedAttemptObserverError(error);
1841
+ }
1842
+ } else {
1843
+ try {
1844
+ this.#stream.push(output as AgentEvent);
1845
+ } catch (error) {
1846
+ throw new ManagedAttemptObserverError(error);
1847
+ }
1848
+ }
1849
+ return !signal?.aborted;
1850
+ });
1851
+ if (complete) this.#publishedAssistant = undefined;
1852
+ return complete;
1853
+ } catch (error) {
1854
+ if (error instanceof ManagedAttemptObserverError || error instanceof ManagedAttemptSnapshotError) throw error;
1855
+ throw new ManagedAttemptSnapshotError();
1856
+ } finally {
1857
+ this.#release();
1858
+ }
1859
+ }
1860
+
1861
+ /** Consume the last exposed prefix only on a postcommit terminal exit. */
1862
+ takePublishedAssistant(): AssistantMessage | undefined {
1863
+ const message = this.#publishedAssistant;
1864
+ this.#publishedAssistant = undefined;
1865
+ return message;
1866
+ }
1867
+
1868
+ #release(): void {
1869
+ this.#entries = [];
1870
+ this.#versions = [];
1871
+ this.#ops = [];
1872
+ this.#latest = undefined;
1873
+ this.#keys.clear();
1874
+ this.#paths = [];
1875
+ this.#retainedBytes = 0;
1876
+ }
1877
+
1878
+ discard(): void {
1879
+ this.#release();
1880
+ if (!this.#committed) this.#discarded = true;
884
1881
  }
885
1882
 
886
1883
  #repairAssistantEvent(event: AgentEvent): AgentEvent {
887
1884
  if (event.type === "message_start" || event.type === "message_end" || event.type === "turn_end") {
888
1885
  return event.message.role === "assistant"
889
- ? { ...event, message: managedAssistantShell(event.message, this.model) }
1886
+ ? { ...event, message: managedAssistantShell(event.message, this.#model) }
890
1887
  : event;
891
1888
  }
892
1889
  if (event.type === "message_update") {
893
- const message = managedAssistantShell(event.message, this.model);
1890
+ const message = managedAssistantShell(event.message, this.#model);
894
1891
  return {
895
1892
  ...event,
896
1893
  message,
897
1894
  assistantMessageEvent: managedAssistantEventSnapshot(event.assistantMessageEvent, message),
898
1895
  };
899
1896
  }
900
- if (event.type === "agent_end") {
1897
+ if (event.type === "agent_end")
901
1898
  return {
902
1899
  ...event,
903
1900
  messages: event.messages.map(message =>
904
- message.role === "assistant" ? managedAssistantShell(message, this.model) : message,
1901
+ message.role === "assistant" ? managedAssistantShell(message, this.#model) : message,
905
1902
  ),
906
1903
  };
907
- }
908
1904
  return event;
909
1905
  }
910
1906
  }
@@ -1411,8 +2407,10 @@ async function runLoopBody(
1411
2407
  const attemptConfig = attemptTransaction
1412
2408
  ? {
1413
2409
  ...config,
1414
- onAssistantMessageEvent: (partial: AssistantMessage, event: AssistantMessageEvent) =>
1415
- attemptTransaction.stageAssistantMessageEvent(partial, event),
2410
+ onAssistantMessageEvent: config.onAssistantMessageEvent
2411
+ ? (partial: AssistantMessage, event: AssistantMessageEvent) =>
2412
+ attemptTransaction.stageAssistantMessageEvent(partial, event)
2413
+ : undefined,
1416
2414
  }
1417
2415
  : config;
1418
2416
  if (recoveryState.pending && !recoveryState.inserted) {
@@ -1449,7 +2447,12 @@ async function runLoopBody(
1449
2447
  } catch (err) {
1450
2448
  if (!(err instanceof HarmonyLeakInterruption)) {
1451
2449
  const failureMessage = managedFailureMessage(err, config);
1452
- if (config.fallbackManaged && transaction && managedContextOverflow(failureMessage, config)) {
2450
+ if (
2451
+ config.fallbackManaged &&
2452
+ transaction &&
2453
+ !transaction.committed &&
2454
+ managedContextOverflow(failureMessage, config)
2455
+ ) {
1453
2456
  transaction.discard();
1454
2457
  currentContext.messages.splice(contextMessageCount);
1455
2458
  newMessages.splice(newMessageCount);
@@ -1457,7 +2460,7 @@ async function runLoopBody(
1457
2460
  stream.end(newMessages);
1458
2461
  return;
1459
2462
  }
1460
- if (config.fallbackManaged && transaction && managedRetryableFailure(err)) {
2463
+ if (config.fallbackManaged && transaction && !transaction.committed && managedRetryableFailure(err)) {
1461
2464
  transaction.discard();
1462
2465
  currentContext.messages.splice(contextMessageCount);
1463
2466
  newMessages.splice(newMessageCount);
@@ -1465,10 +2468,17 @@ async function runLoopBody(
1465
2468
  stream.end(newMessages);
1466
2469
  return;
1467
2470
  }
2471
+ const published = transaction?.committed === true;
2472
+ transaction?.discard();
2473
+ if (transaction && !published) {
2474
+ currentContext.messages.splice(contextMessageCount);
2475
+ newMessages.splice(newMessageCount);
2476
+ }
1468
2477
  throw err;
1469
2478
  }
1470
2479
  if (config.fallbackManaged) {
1471
2480
  await emitHarmonyAudit(config, err, "escalated", harmonyRetryAttempt);
2481
+ transaction?.discard();
1472
2482
  throw err;
1473
2483
  }
1474
2484
  if (err.recovered) {
@@ -1536,8 +2546,11 @@ async function runLoopBody(
1536
2546
  }
1537
2547
  }
1538
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;
1539
2552
  const overflow = managedContextOverflow(message, config);
1540
- if (config.fallbackManaged && overflow) {
2553
+ if (config.fallbackManaged && discardable && overflow) {
1541
2554
  transaction?.discard();
1542
2555
  currentContext.messages.splice(contextMessageCount);
1543
2556
  newMessages.splice(newMessageCount);
@@ -1558,7 +2571,12 @@ async function runLoopBody(
1558
2571
  : "Provider returned an empty response with anomalously low token usage (possible context overflow via proxy)";
1559
2572
  }
1560
2573
 
1561
- if (config.fallbackManaged && message.stopReason === "error" && managedRetryableFailure(message)) {
2574
+ if (
2575
+ config.fallbackManaged &&
2576
+ discardable &&
2577
+ message.stopReason === "error" &&
2578
+ managedRetryableFailure(message)
2579
+ ) {
1562
2580
  transaction?.discard();
1563
2581
  currentContext.messages.splice(contextMessageCount);
1564
2582
  newMessages.splice(newMessageCount);
@@ -1567,7 +2585,7 @@ async function runLoopBody(
1567
2585
  return;
1568
2586
  }
1569
2587
 
1570
- if (config.fallbackManaged && message.stopReason === "aborted") {
2588
+ if (config.fallbackManaged && discardable && message.stopReason === "aborted") {
1571
2589
  transaction?.discard();
1572
2590
  currentContext.messages.splice(contextMessageCount);
1573
2591
  newMessages.splice(newMessageCount);
@@ -1585,7 +2603,40 @@ async function runLoopBody(
1585
2603
  }
1586
2604
 
1587
2605
  // One provider invocation is committed before any tool can run.
1588
- transaction?.flush();
2606
+ if (transaction) {
2607
+ let complete: boolean;
2608
+ try {
2609
+ complete = transaction.flush(loopSignal);
2610
+ } catch (error) {
2611
+ const prefix = transaction.takePublishedAssistant();
2612
+ currentContext.messages.splice(contextMessageCount);
2613
+ newMessages.splice(newMessageCount);
2614
+ if (prefix) {
2615
+ prefix.stopReason = "error";
2616
+ prefix.errorMessage = error instanceof Error ? error.message : "Managed output failed";
2617
+ delete prefix.errorStatus;
2618
+ delete prefix.transportFailure;
2619
+ currentContext.messages.push(prefix);
2620
+ newMessages.push(prefix);
2621
+ }
2622
+ throw error;
2623
+ }
2624
+ if (!complete) {
2625
+ const prefix = transaction.takePublishedAssistant();
2626
+ currentContext.messages.splice(contextMessageCount);
2627
+ newMessages.splice(newMessageCount);
2628
+ await config.onManagedAttemptOutcome?.({ type: "run_terminal", reason: "cancelled" });
2629
+ if (!prefix) {
2630
+ stream.end(newMessages);
2631
+ return;
2632
+ }
2633
+ // Preserve the irreversible prefix, not the provider's unseen tail.
2634
+ currentContext.messages.push(prefix);
2635
+ message = emitAbortedAssistantMessage(prefix, true, currentContext, config, stream);
2636
+ currentContext.messages.push(message);
2637
+ newMessages.push(message);
2638
+ }
2639
+ }
1589
2640
  if (config.fallbackManaged && message.stopReason !== "error" && message.stopReason !== "aborted") {
1590
2641
  await config.onManagedAttemptAccepted?.();
1591
2642
  }
@@ -1837,11 +2888,16 @@ async function streamAssistantResponse(
1837
2888
  const dynamicReasoning = config.getReasoning?.();
1838
2889
  const harmonyMitigationEnabled = isHarmonyLeakMitigationTarget(config.model);
1839
2890
  const harmonyAbortController = harmonyMitigationEnabled ? new AbortController() : undefined;
1840
- const requestSignal = harmonyAbortController
1841
- ? signal
1842
- ? AbortSignal.any([signal, harmonyAbortController.signal])
1843
- : harmonyAbortController.signal
1844
- : 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
+ ]);
1845
2901
  const effectiveTemperature =
1846
2902
  harmonyRetryAttempt > 0 && config.temperature !== undefined ? config.temperature + 0.05 : config.temperature;
1847
2903
  const effectiveToolChoice = recoveryMode ? "none" : (dynamicToolChoice ?? config.toolChoice);
@@ -2022,6 +3078,7 @@ async function streamAssistantResponse(
2022
3078
  return trailing;
2023
3079
  });
2024
3080
  } catch (err) {
3081
+ attemptAbortController.abort(err);
2025
3082
  failChatSpan(telemetry, chatSpan, {
2026
3083
  errorObject: err,
2027
3084
  responseHeaders: capturedHeaders,