@demicodes/agent 0.25.1 → 0.25.2

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/dist/index.d.mts CHANGED
@@ -40,6 +40,7 @@ type ActiveTurnPhase = 'provider_streaming' | 'tool_executing' | 'compacting' |
40
40
  declare class AgentSession<State> {
41
41
  private provider;
42
42
  private model;
43
+ private modelNeedsCompaction;
43
44
  private pendingModelSwitch;
44
45
  private readonly cwd;
45
46
  private readonly runtime;
@@ -132,8 +133,8 @@ declare class AgentSession<State> {
132
133
  * start of the next queued action, so a running turn finishes entirely on the old model;
133
134
  * 'immediate' also applies mid-turn at the next sampling/tool continuation, so the very
134
135
  * next request already runs on the new model (the same "as soon as possible" semantics
135
- * steering has). Either way, if the new model can't hold the history, compaction runs
136
- * first with the current (pre-switch) model, then the swap happens. Recording is cheap
136
+ * steering has). The selection is applied before compaction, so recovery never
137
+ * depends on the previous provider remaining available. Recording is cheap
137
138
  * and non-blocking so it never holds up an in-flight turn or other frames.
138
139
  */
139
140
  updateModel(provider: AgentProvider | null, model: ModelSelection, apply?: ModelSwitchApply): void;
@@ -180,14 +181,8 @@ declare class AgentSession<State> {
180
181
  private kickWorker;
181
182
  private runWorker;
182
183
  private executeAction;
183
- /**
184
- * Applies a queued model/provider switch at an action boundary (turn preflight). If the
185
- * new model's context window can't hold the current history, compaction runs FIRST with
186
- * the current (pre-switch) model + provider — which can still load it to summarize — and
187
- * only then do we swap. Doing it the other way would ask the smaller model to summarize
188
- * a history it may not be able to load. Returns whether that compaction actually ran
189
- * (false when no switch was pending).
190
- */
184
+ /** Apply selection independently of whether the selected model can summarize. */
185
+ private applyModelSelection;
191
186
  private applyPendingModelSwitch;
192
187
  /**
193
188
  * Turn-loop variant for mid-turn continuation boundaries: only switches recorded with
package/dist/index.mjs CHANGED
@@ -833,25 +833,31 @@ const COMPACTION_SUMMARY_INSTRUCTION = "Summarize the conversation above into a
833
833
  */
834
834
  var CompactionController = class {
835
835
  host;
836
+ revision = 0;
837
+ summaryAbort = null;
836
838
  constructor(host) {
837
839
  this.host = host;
838
840
  }
839
- /**
840
- * Compacts (up to 8 passes) until the history fits `targetModel`'s context, if over
841
- * threshold. Returns whether anything was compacted.
842
- */
843
- async compactToFit(targetModel) {
844
- const contextWindow = targetModel.model.contextWindow;
845
- if (contextWindow <= 0) return false;
846
- const threshold = resolveCompactionThreshold(contextWindow, this.host.thresholdRatio, this.host.thresholdTokens);
847
- if (this.host.transcript.estimateContextTokens(contextWindow) < threshold) return false;
841
+ interrupt() {
842
+ this.revision += 1;
843
+ this.summaryAbort?.abort();
844
+ }
845
+ /** Compact against the live selection, retaining it even if summarization fails. */
846
+ async compactToFit() {
848
847
  return this.host.runWithCompactingPhase(async () => {
849
848
  let compacted = false;
850
- for (let attempt = 0; attempt < 8 && this.host.transcript.estimateContextTokens(contextWindow) >= threshold; attempt += 1) {
851
- if (!await this.run()) break;
849
+ for (let attempt = 0; attempt < 8; attempt += 1) {
850
+ await this.host.applyModelSwitch();
851
+ const contextWindow = this.host.model.model.contextWindow;
852
+ if (contextWindow <= 0) return compacted;
853
+ const threshold = resolveCompactionThreshold(contextWindow, this.host.thresholdRatio, this.host.thresholdTokens);
854
+ const before = this.host.transcript.estimateContextTokens(contextWindow);
855
+ if (before < threshold) return compacted;
856
+ if (!await this.run()) throw new Error("Compaction cannot fit the selected model: no reducible history remains");
852
857
  compacted = true;
858
+ if (this.host.model.model.contextWindow === contextWindow && this.host.transcript.estimateContextTokens(contextWindow) >= before) throw new Error("Compaction cannot fit the selected model: summary made no progress");
853
859
  }
854
- return compacted;
860
+ throw new Error("Compaction exceeded its pass limit; retry with the selected model or select a larger context window");
855
861
  });
856
862
  }
857
863
  /** Runs one compaction pass before a turn when the current model is over threshold. */
@@ -864,9 +870,20 @@ var CompactionController = class {
864
870
  }
865
871
  /** Runs one compaction pass; returns whether it compacted anything. */
866
872
  async run() {
873
+ while (true) {
874
+ throwIfAborted(this.host.currentSignal());
875
+ await this.host.applyModelSwitch();
876
+ try {
877
+ return await this.runPass();
878
+ } catch (error) {
879
+ if (!(error instanceof SummarySuperseded)) throw error;
880
+ }
881
+ }
882
+ }
883
+ async runPass() {
867
884
  const transcript = this.host.transcript;
868
885
  if (transcript.pendingToolCalls().length > 0) return false;
869
- const window = transcript.findCompactionWindow(this.host.keepRecentTokens);
886
+ const window = transcript.findCompactionWindow(Math.min(this.host.keepRecentTokens, Math.max(1, Math.floor(this.host.model.model.contextWindow / 4))));
870
887
  if (window === null) return false;
871
888
  let minCutPoint = window.startIndex;
872
889
  while (minCutPoint < window.cutPoint) {
@@ -880,7 +897,10 @@ var CompactionController = class {
880
897
  const compactedBlocks = transcript.blocks.slice(window.startIndex, cutPoint);
881
898
  const compactedTokens = compactedBlocks.reduce((total, block) => total + estimateTranscriptBlockTokens(block), 0);
882
899
  try {
900
+ const revision = this.revision;
883
901
  const summary = await this.generateSummary(compactedBlocks);
902
+ throwIfAborted(this.host.currentSignal());
903
+ if (revision !== this.revision) throw new SummarySuperseded();
884
904
  if (!summary) return false;
885
905
  const boundary = transcript.insertCompactionBoundary(cutPoint, this.host.model, summary, estimateTokens(summary));
886
906
  transcript.appendCompactionMarker(this.host.model, boundary.id, compactedTokens);
@@ -888,7 +908,12 @@ var CompactionController = class {
888
908
  return true;
889
909
  } catch (error) {
890
910
  if (!isContextLengthExceeded(error)) throw error;
891
- const nextCutPoint = nextSmallerCompactionCutPoint(window.startIndex, cutPoint);
911
+ const midpoint = nextSmallerCompactionCutPoint(window.startIndex, cutPoint);
912
+ let nextCutPoint = null;
913
+ for (let index = minCutPoint + 1; index < cutPoint; index += 1) {
914
+ if (transcript.blocks[index - 1]?.type !== "response") continue;
915
+ if (nextCutPoint === null || midpoint !== null && index <= midpoint) nextCutPoint = index;
916
+ }
892
917
  if (nextCutPoint === null) throw error;
893
918
  cutPoint = nextCutPoint;
894
919
  }
@@ -896,6 +921,8 @@ var CompactionController = class {
896
921
  return false;
897
922
  }
898
923
  async generateSummary(blocks) {
924
+ const controller = new AbortController();
925
+ this.summaryAbort = controller;
899
926
  const clone = this.host.clone({ blocks });
900
927
  const baseBlockCount = clone.transcript().blocks.length;
901
928
  const parentSignal = this.host.currentSignal();
@@ -906,21 +933,30 @@ var CompactionController = class {
906
933
  if (event.type === "retry_scheduled") this.host.emit(event);
907
934
  });
908
935
  parentSignal.addEventListener("abort", abortClone, { once: true });
936
+ controller.signal.addEventListener("abort", abortClone, { once: true });
909
937
  try {
910
938
  throwIfAborted(parentSignal);
911
- await clone.send([{
939
+ await abortable(clone.send([{
912
940
  type: "text",
913
941
  text: COMPACTION_SUMMARY_INSTRUCTION
914
- }]);
942
+ }]), controller.signal);
915
943
  throwIfAborted(parentSignal);
944
+ if (controller.signal.aborted) throw new SummarySuperseded();
916
945
  return lastAssistantText$1(clone.transcript(), baseBlockCount).trim();
946
+ } catch (error) {
947
+ throwIfAborted(parentSignal);
948
+ if (controller.signal.aborted) throw new SummarySuperseded();
949
+ throw error;
917
950
  } finally {
951
+ this.summaryAbort = null;
952
+ controller.signal.removeEventListener("abort", abortClone);
918
953
  parentSignal.removeEventListener("abort", abortClone);
919
954
  unsubscribe();
920
955
  await clone.dispose();
921
956
  }
922
957
  }
923
958
  };
959
+ var SummarySuperseded = class extends Error {};
924
960
  function lastAssistantText$1(transcript, startIndex) {
925
961
  for (let index = transcript.blocks.length - 1; index >= startIndex; index -= 1) {
926
962
  const block = transcript.blocks[index];
@@ -1191,6 +1227,7 @@ const DEFAULT_PERSIST_INTERVAL_MS = 1e3;
1191
1227
  var AgentSession = class AgentSession {
1192
1228
  provider;
1193
1229
  model;
1230
+ modelNeedsCompaction = false;
1194
1231
  pendingModelSwitch = null;
1195
1232
  cwd;
1196
1233
  runtime;
@@ -1290,6 +1327,7 @@ var AgentSession = class AgentSession {
1290
1327
  return self.compactionThresholdTokens;
1291
1328
  },
1292
1329
  currentSignal: () => self.currentSignal(),
1330
+ applyModelSwitch: () => self.applyModelSelection(true),
1293
1331
  clone: (transcript) => self.clone({
1294
1332
  transcript,
1295
1333
  options: {
@@ -1494,16 +1532,23 @@ var AgentSession = class AgentSession {
1494
1532
  * start of the next queued action, so a running turn finishes entirely on the old model;
1495
1533
  * 'immediate' also applies mid-turn at the next sampling/tool continuation, so the very
1496
1534
  * next request already runs on the new model (the same "as soon as possible" semantics
1497
- * steering has). Either way, if the new model can't hold the history, compaction runs
1498
- * first with the current (pre-switch) model, then the swap happens. Recording is cheap
1535
+ * steering has). The selection is applied before compaction, so recovery never
1536
+ * depends on the previous provider remaining available. Recording is cheap
1499
1537
  * and non-blocking so it never holds up an in-flight turn or other frames.
1500
1538
  */
1501
1539
  updateModel(provider, model, apply = "next_turn") {
1540
+ const previous = this.pendingModelSwitch?.provider;
1541
+ const next = provider ?? previous ?? null;
1502
1542
  this.pendingModelSwitch = {
1503
- provider,
1543
+ provider: next,
1504
1544
  model,
1505
1545
  apply
1506
1546
  };
1547
+ if (previous && previous !== next && previous !== this.provider) Promise.resolve().then(() => previous.dispose?.()).catch((error) => this.emit({
1548
+ type: "error",
1549
+ error: asError(error)
1550
+ }));
1551
+ if (apply === "immediate") this.compaction.interrupt();
1507
1552
  }
1508
1553
  async abort() {
1509
1554
  if (this.currentAbortController && !this.currentAbortController.signal.aborted) {
@@ -1892,25 +1937,23 @@ var AgentSession = class AgentSession {
1892
1937
  return;
1893
1938
  }
1894
1939
  }
1895
- /**
1896
- * Applies a queued model/provider switch at an action boundary (turn preflight). If the
1897
- * new model's context window can't hold the current history, compaction runs FIRST with
1898
- * the current (pre-switch) model + provider — which can still load it to summarize — and
1899
- * only then do we swap. Doing it the other way would ask the smaller model to summarize
1900
- * a history it may not be able to load. Returns whether that compaction actually ran
1901
- * (false when no switch was pending).
1902
- */
1903
- async applyPendingModelSwitch() {
1940
+ /** Apply selection independently of whether the selected model can summarize. */
1941
+ async applyModelSelection(immediateOnly = false) {
1904
1942
  const pending = this.pendingModelSwitch;
1905
- if (!pending) return false;
1943
+ if (!pending || immediateOnly && pending.apply !== "immediate") return false;
1906
1944
  this.pendingModelSwitch = null;
1907
- const compacted = await this.compaction.compactToFit(pending.model);
1908
- if (pending.provider && pending.provider !== this.provider) {
1909
- const previous = this.provider;
1910
- this.provider = pending.provider;
1911
- await previous.dispose?.();
1912
- }
1945
+ const previous = this.provider;
1946
+ this.provider = pending.provider ?? previous;
1913
1947
  this.model = pending.model;
1948
+ this.modelNeedsCompaction = true;
1949
+ if (previous !== this.provider) await previous.dispose?.();
1950
+ return true;
1951
+ }
1952
+ async applyPendingModelSwitch(immediateOnly = false) {
1953
+ await this.applyModelSelection(immediateOnly);
1954
+ if (!this.modelNeedsCompaction) return false;
1955
+ const compacted = await this.compaction.compactToFit();
1956
+ this.modelNeedsCompaction = false;
1914
1957
  return compacted;
1915
1958
  }
1916
1959
  /**
@@ -1919,8 +1962,7 @@ var AgentSession = class AgentSession {
1919
1962
  * finishes and the next action starts.
1920
1963
  */
1921
1964
  async applyImmediateModelSwitch() {
1922
- if (this.pendingModelSwitch?.apply !== "immediate") return false;
1923
- return this.applyPendingModelSwitch();
1965
+ return this.applyPendingModelSwitch(true);
1924
1966
  }
1925
1967
  async runWithCompactingPhase(fn) {
1926
1968
  const previousPhase = this.currentPhase;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@demicodes/agent",
3
3
  "description": "Session runtime and transport-neutral client and server protocol for Demi.",
4
- "version": "0.25.1",
4
+ "version": "0.25.2",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "exports": {
@@ -19,10 +19,10 @@
19
19
  }
20
20
  },
21
21
  "dependencies": {
22
- "@demicodes/core": "^0.25.1",
23
- "@demicodes/provider": "^0.25.1",
24
- "@demicodes/shell": "^0.25.1",
25
- "@demicodes/utils": "^0.25.1",
22
+ "@demicodes/core": "^0.25.2",
23
+ "@demicodes/provider": "^0.25.2",
24
+ "@demicodes/shell": "^0.25.2",
25
+ "@demicodes/utils": "^0.25.2",
26
26
  "zod": "^4.0.0"
27
27
  },
28
28
  "license": "Apache-2.0",