@autumnsgrove/lyra 0.1.0 → 0.3.0

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.
Files changed (173) hide show
  1. package/dist/adapters/cloudflare/index.d.ts +1 -0
  2. package/dist/adapters/cloudflare/index.d.ts.map +1 -1
  3. package/dist/adapters/cloudflare/index.js +1 -0
  4. package/dist/adapters/cloudflare/index.js.map +1 -1
  5. package/dist/adapters/cloudflare/session.d.ts +102 -0
  6. package/dist/adapters/cloudflare/session.d.ts.map +1 -0
  7. package/dist/adapters/cloudflare/session.js +595 -0
  8. package/dist/adapters/cloudflare/session.js.map +1 -0
  9. package/dist/adapters/openai/errors.d.ts +36 -0
  10. package/dist/adapters/openai/errors.d.ts.map +1 -0
  11. package/dist/adapters/openai/errors.js +117 -0
  12. package/dist/adapters/openai/errors.js.map +1 -0
  13. package/dist/adapters/openai/index.d.ts +18 -0
  14. package/dist/adapters/openai/index.d.ts.map +1 -0
  15. package/dist/adapters/openai/index.js +18 -0
  16. package/dist/adapters/openai/index.js.map +1 -0
  17. package/dist/adapters/openai/model.d.ts +50 -0
  18. package/dist/adapters/openai/model.d.ts.map +1 -0
  19. package/dist/adapters/openai/model.js +169 -0
  20. package/dist/adapters/openai/model.js.map +1 -0
  21. package/dist/adapters/openai/presets.d.ts +36 -0
  22. package/dist/adapters/openai/presets.d.ts.map +1 -0
  23. package/dist/adapters/openai/presets.js +43 -0
  24. package/dist/adapters/openai/presets.js.map +1 -0
  25. package/dist/adapters/openai/request.d.ts +47 -0
  26. package/dist/adapters/openai/request.d.ts.map +1 -0
  27. package/dist/adapters/openai/request.js +93 -0
  28. package/dist/adapters/openai/request.js.map +1 -0
  29. package/dist/adapters/openai/sse.d.ts +44 -0
  30. package/dist/adapters/openai/sse.d.ts.map +1 -0
  31. package/dist/adapters/openai/sse.js +410 -0
  32. package/dist/adapters/openai/sse.js.map +1 -0
  33. package/dist/core/approval.d.ts +38 -0
  34. package/dist/core/approval.d.ts.map +1 -0
  35. package/dist/core/approval.js +47 -0
  36. package/dist/core/approval.js.map +1 -0
  37. package/dist/core/compaction.d.ts +193 -0
  38. package/dist/core/compaction.d.ts.map +1 -0
  39. package/dist/core/compaction.js +460 -0
  40. package/dist/core/compaction.js.map +1 -0
  41. package/dist/core/define-recipe.d.ts +8 -1
  42. package/dist/core/define-recipe.d.ts.map +1 -1
  43. package/dist/core/define-recipe.js +13 -0
  44. package/dist/core/define-recipe.js.map +1 -1
  45. package/dist/core/events.d.ts +32 -2
  46. package/dist/core/events.d.ts.map +1 -1
  47. package/dist/core/events.js +16 -1
  48. package/dist/core/events.js.map +1 -1
  49. package/dist/core/execute-tools.d.ts +7 -0
  50. package/dist/core/execute-tools.d.ts.map +1 -1
  51. package/dist/core/execute-tools.js +6 -0
  52. package/dist/core/execute-tools.js.map +1 -1
  53. package/dist/core/hash.d.ts +10 -0
  54. package/dist/core/hash.d.ts.map +1 -0
  55. package/dist/core/hash.js +14 -0
  56. package/dist/core/hash.js.map +1 -0
  57. package/dist/core/model.d.ts +12 -0
  58. package/dist/core/model.d.ts.map +1 -1
  59. package/dist/core/propose.d.ts +29 -0
  60. package/dist/core/propose.d.ts.map +1 -0
  61. package/dist/core/propose.js +75 -0
  62. package/dist/core/propose.js.map +1 -0
  63. package/dist/core/recipe.d.ts +2 -0
  64. package/dist/core/recipe.d.ts.map +1 -1
  65. package/dist/core/recipe.js +5 -8
  66. package/dist/core/recipe.js.map +1 -1
  67. package/dist/core/resume.d.ts +19 -1
  68. package/dist/core/resume.d.ts.map +1 -1
  69. package/dist/core/resume.js +64 -6
  70. package/dist/core/resume.js.map +1 -1
  71. package/dist/core/retry.d.ts +9 -0
  72. package/dist/core/retry.d.ts.map +1 -0
  73. package/dist/core/retry.js +9 -0
  74. package/dist/core/retry.js.map +1 -0
  75. package/dist/core/run-handle.d.ts +5 -0
  76. package/dist/core/run-handle.d.ts.map +1 -1
  77. package/dist/core/run-handle.js +1 -0
  78. package/dist/core/run-handle.js.map +1 -1
  79. package/dist/core/run.d.ts +29 -2
  80. package/dist/core/run.d.ts.map +1 -1
  81. package/dist/core/run.js +526 -132
  82. package/dist/core/run.js.map +1 -1
  83. package/dist/core/runtime.d.ts +12 -0
  84. package/dist/core/runtime.d.ts.map +1 -1
  85. package/dist/core/runtime.js +34 -2
  86. package/dist/core/runtime.js.map +1 -1
  87. package/dist/core/system-clock.d.ts.map +1 -1
  88. package/dist/core/system-clock.js +5 -1
  89. package/dist/core/system-clock.js.map +1 -1
  90. package/dist/core/tool.d.ts +55 -0
  91. package/dist/core/tool.d.ts.map +1 -1
  92. package/dist/core/tool.js +16 -0
  93. package/dist/core/tool.js.map +1 -1
  94. package/dist/core/usage.d.ts +27 -0
  95. package/dist/core/usage.d.ts.map +1 -0
  96. package/dist/core/usage.js +67 -0
  97. package/dist/core/usage.js.map +1 -0
  98. package/dist/index.d.ts +7 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +7 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/protocol/answers.d.ts +33 -0
  103. package/dist/protocol/answers.d.ts.map +1 -0
  104. package/dist/protocol/answers.js +86 -0
  105. package/dist/protocol/answers.js.map +1 -0
  106. package/dist/protocol/commands.d.ts +84 -0
  107. package/dist/protocol/commands.d.ts.map +1 -0
  108. package/dist/protocol/commands.js +232 -0
  109. package/dist/protocol/commands.js.map +1 -0
  110. package/dist/protocol/events.d.ts +145 -0
  111. package/dist/protocol/events.d.ts.map +1 -0
  112. package/dist/protocol/events.js +195 -0
  113. package/dist/protocol/events.js.map +1 -0
  114. package/dist/protocol/frames.d.ts +72 -0
  115. package/dist/protocol/frames.d.ts.map +1 -0
  116. package/dist/protocol/frames.js +134 -0
  117. package/dist/protocol/frames.js.map +1 -0
  118. package/dist/protocol/http.d.ts +52 -0
  119. package/dist/protocol/http.d.ts.map +1 -0
  120. package/dist/protocol/http.js +357 -0
  121. package/dist/protocol/http.js.map +1 -0
  122. package/dist/protocol/reader.d.ts +35 -0
  123. package/dist/protocol/reader.d.ts.map +1 -0
  124. package/dist/protocol/reader.js +71 -0
  125. package/dist/protocol/reader.js.map +1 -0
  126. package/dist/protocol/session.d.ts +85 -0
  127. package/dist/protocol/session.d.ts.map +1 -0
  128. package/dist/protocol/session.js +801 -0
  129. package/dist/protocol/session.js.map +1 -0
  130. package/dist/record/entries.d.ts +110 -2
  131. package/dist/record/entries.d.ts.map +1 -1
  132. package/dist/record/entries.js +337 -10
  133. package/dist/record/entries.js.map +1 -1
  134. package/dist/record/replay.d.ts +6 -0
  135. package/dist/record/replay.d.ts.map +1 -1
  136. package/dist/record/replay.js +11 -3
  137. package/dist/record/replay.js.map +1 -1
  138. package/dist/record/truncate.d.ts +12 -0
  139. package/dist/record/truncate.d.ts.map +1 -1
  140. package/dist/record/truncate.js +72 -1
  141. package/dist/record/truncate.js.map +1 -1
  142. package/dist/testkit/cassette.d.ts +91 -0
  143. package/dist/testkit/cassette.d.ts.map +1 -0
  144. package/dist/testkit/cassette.js +250 -0
  145. package/dist/testkit/cassette.js.map +1 -0
  146. package/dist/testkit/fake-model-server.d.ts +104 -0
  147. package/dist/testkit/fake-model-server.d.ts.map +1 -0
  148. package/dist/testkit/fake-model-server.js +251 -0
  149. package/dist/testkit/fake-model-server.js.map +1 -0
  150. package/dist/testkit/index.d.ts +5 -2
  151. package/dist/testkit/index.d.ts.map +1 -1
  152. package/dist/testkit/index.js +5 -2
  153. package/dist/testkit/index.js.map +1 -1
  154. package/dist/testkit/misbehaving-model.d.ts +40 -0
  155. package/dist/testkit/misbehaving-model.d.ts.map +1 -0
  156. package/dist/testkit/misbehaving-model.js +134 -0
  157. package/dist/testkit/misbehaving-model.js.map +1 -0
  158. package/dist/testkit/model.d.ts +20 -0
  159. package/dist/testkit/model.d.ts.map +1 -1
  160. package/dist/testkit/model.js +50 -3
  161. package/dist/testkit/model.js.map +1 -1
  162. package/dist/testkit/scenario.d.ts +36 -2
  163. package/dist/testkit/scenario.d.ts.map +1 -1
  164. package/dist/testkit/scenario.js +98 -13
  165. package/dist/testkit/scenario.js.map +1 -1
  166. package/dist/testkit/timeline-recipe.d.ts.map +1 -1
  167. package/dist/testkit/timeline-recipe.js +3 -0
  168. package/dist/testkit/timeline-recipe.js.map +1 -1
  169. package/dist/testkit/tools.d.ts +15 -1
  170. package/dist/testkit/tools.d.ts.map +1 -1
  171. package/dist/testkit/tools.js +19 -0
  172. package/dist/testkit/tools.js.map +1 -1
  173. package/package.json +5 -1
@@ -0,0 +1,193 @@
1
+ /**
2
+ * The cut, and what a history is guessed to cost (docs/context-size.md, decisions
3
+ * 39 to 41).
4
+ *
5
+ * Compaction never deletes from the record. It writes a `compaction` entry naming
6
+ * the first entry the model still sees, and the view is built from that pointer,
7
+ * so replay and the record keep everything (decision 39). This module is the pure
8
+ * half of that: how many tokens a piece of text is guessed to cost, and where the
9
+ * cut may fall.
10
+ *
11
+ * The estimate is four characters to a token. It is a smoke alarm rather than
12
+ * billing: the trigger adds it to the input tokens the provider reported for the
13
+ * last request, so it only has to be roughly right about what arrived since.
14
+ *
15
+ * A cut is only allowed to start a step, never to land on a tool result: a result
16
+ * whose call was summarized away would leave the model with an answer to a
17
+ * question it cannot see, and a provider refuses that (CMP02).
18
+ */
19
+ import type { Clock, Ids } from "./clock.js";
20
+ import type { ConversationMessage } from "./conversation.js";
21
+ import type { ModelError, ModelSlot, Usage } from "./model.js";
22
+ import { type Result } from "./result.js";
23
+ import type { CompactionEntry, RecordEntry } from "../record/entries.js";
24
+ import type { Tool } from "./tool.js";
25
+ /** How many tokens a piece of text is guessed to cost, rounded up. */
26
+ export declare function estimateTokens(text: string): number;
27
+ /**
28
+ * What one entry costs the model. A status, a note, a pin and a compaction are in
29
+ * the record but never in the conversation, so they are free here too.
30
+ */
31
+ export declare function entryTokens(entry: RecordEntry): number;
32
+ /** Where a compaction cuts: the first entry kept, its position, and how many it replaces. */
33
+ export interface Cut {
34
+ /** The id of the first entry the model still sees, which the entry stores. */
35
+ firstKept: string;
36
+ /** That entry's position in the list the cut was chosen from. */
37
+ index: number;
38
+ /** How many entries before the cut the summary stands in for. */
39
+ replaces: number;
40
+ }
41
+ /**
42
+ * Where to cut a history so the model keeps at most `keepTokens` of it.
43
+ *
44
+ * Nothing is cut when the whole history already fits, which is the common case
45
+ * and also what an empty history and one that is a single step return: cutting
46
+ * a history down to itself would only spend a summary call.
47
+ */
48
+ export declare function chooseCut(entries: readonly RecordEntry[], keepTokens: number): Cut | undefined;
49
+ /**
50
+ * What the model sees of a record: the latest summary, what each tool says its
51
+ * state is, and the entries from the compaction's pointer on (decision 39).
52
+ */
53
+ export interface ModelView {
54
+ /** The entries kept verbatim, oldest first: where a later cut is chosen from. */
55
+ entries: RecordEntry[];
56
+ /** The latest summary, when the record has a compaction in it. */
57
+ summary: string | undefined;
58
+ /** What each tool rendered as its current state, in the order given. */
59
+ stateTexts: readonly string[];
60
+ /** The conversation to send, in order. The system text is the caller's. */
61
+ messages: ConversationMessage[];
62
+ }
63
+ /**
64
+ * Build the view of a record. Everything before the latest `compaction`'s pointer
65
+ * is left out of the conversation but stays in the record, so replay still
66
+ * rebuilds tool state from every saved result (CMP07).
67
+ *
68
+ * A pointer that names no entry in the path is treated as the end of the
69
+ * compaction entry itself rather than as an error: a record whose chain is
70
+ * damaged is already noted by the loader, and showing the model too much is
71
+ * safer than showing it nothing.
72
+ */
73
+ export declare function buildView(path: readonly RecordEntry[], stateTexts?: readonly string[]): ModelView;
74
+ /** The default cap on what the model reads from one tool result (decision 40). */
75
+ export declare const DEFAULT_RESULT_CAP_BYTES = 51200;
76
+ /**
77
+ * What each tool says the recipe's state is, already labelled for the model
78
+ * (decision 40).
79
+ *
80
+ * A tool that throws here loses its state text and not the run: this runs while a
81
+ * view is being built, and a view is not worth failing a run over.
82
+ */
83
+ export declare function currentStateTexts(tools: readonly Tool[], state: unknown): string[];
84
+ /** The most one old entry may take in a summary request, in estimated tokens. */
85
+ export declare const SUMMARY_ENTRY_TOKENS = 8000;
86
+ /**
87
+ * What a summary call is given: the previous summary, which it updates rather
88
+ * than restarts, and the steps since it, oldest first (decision 40).
89
+ *
90
+ * An old tool result is cut to a per-entry cap so the summary call itself fits in
91
+ * the window it is trying to save. That loses detail, and the record keeps it:
92
+ * `notes.md` says why the tradeoff was taken.
93
+ */
94
+ export declare function summaryMaterial(view: ModelView, cut: Cut): string;
95
+ /**
96
+ * How a recipe shapes compaction. Every field is optional: the defaults are
97
+ * Nova's numbers, chosen at step 7 and recorded in `decisions.md`.
98
+ */
99
+ export interface CompactionSettings {
100
+ /** The model's context window, when the recipe knows it and the slot does not. */
101
+ contextWindow?: number;
102
+ /** How close to the window a run may come before it compacts. */
103
+ reserveTokens?: number;
104
+ /** How much of the most recent history to keep verbatim, in estimated tokens. */
105
+ keepTokens?: number;
106
+ /** The model that writes the summary, when it is not the run's own. */
107
+ model?: string;
108
+ /** The recipe's own summarizer instructions, replacing the default. */
109
+ instructions?: string;
110
+ }
111
+ /** `max(16384, 10% of the window)`, which is Nova's reserve (decision 41). */
112
+ export declare function defaultReserveTokens(window: number): number;
113
+ /** What the run keeps if a recipe says nothing: Nova's 20000 tokens (decision 41). */
114
+ export declare const DEFAULT_KEEP_TOKENS = 20000;
115
+ /** A recipe's compaction settings, checked once so a bad one fails fast (LIM03's rule). */
116
+ export declare function validateCompactionSettings(settings: CompactionSettings): Result<CompactionSettings>;
117
+ /**
118
+ * The instructions the summarizer is given when a recipe does not replace them.
119
+ *
120
+ * Shaped for a Lyra run rather than a coding chat: the goal is pinned in the system
121
+ * text and never summarized, the tools can hand back their own exact state, and
122
+ * what is left is progress, decisions and what is open (decision 40).
123
+ */
124
+ export declare const DEFAULT_SUMMARY_INSTRUCTIONS: string;
125
+ /** What the model is asked for when the run compacts itself. */
126
+ export interface Summarizer {
127
+ model: ModelSlot;
128
+ /** The model to ask, when the recipe names one. */
129
+ modelName?: string;
130
+ instructions: string;
131
+ }
132
+ export interface Summary {
133
+ summary: string;
134
+ /** The model that answered, which the entry records. */
135
+ model: string;
136
+ usage: Usage;
137
+ }
138
+ /**
139
+ * Ask the model for a summary, retrying a retryable failure the way the loop's own
140
+ * requests are retried (decision 26).
141
+ *
142
+ * An answer that is empty or only whitespace is a failure rather than a summary: a
143
+ * run that continued on it would have thrown away the history it meant to keep,
144
+ * and there is no smaller answer to fall back on.
145
+ */
146
+ export declare function summarize(options: {
147
+ summarizer: Summarizer;
148
+ material: string;
149
+ clock: Clock;
150
+ signal: AbortSignal;
151
+ /** Told about each wait, so a host can show it the way it shows a turn's retry. */
152
+ onRetry?: (attempt: number, delayMs: number, error: ModelError) => void;
153
+ }): Promise<Result<Summary, ModelError>>;
154
+ /** Whether the conversation is close enough to the window to compact (decision 41). */
155
+ export declare function shouldCompact(estimate: number, window: number, reserveTokens: number): boolean;
156
+ /** The tokens a conversation is guessed to cost. */
157
+ export declare function estimateConversation(messages: readonly ConversationMessage[]): number;
158
+ /**
159
+ * What was added since the last request: the reply it produced, and every message
160
+ * after it. A provider's reported input tokens only cover that request, so this is
161
+ * the part it could not know about (decision 41).
162
+ */
163
+ export declare function estimateSinceLastReply(messages: readonly ConversationMessage[]): number;
164
+ /** What a manual compaction was asked to do, over a record that is not running. */
165
+ export interface ManualCompaction {
166
+ /** The record's active path, oldest first. */
167
+ path: readonly RecordEntry[];
168
+ /** The id the new entry links to, which is the record's last entry. */
169
+ parent: string | null;
170
+ model: ModelSlot;
171
+ /** The model a host runs, when the recipe does not name its own summarizer. */
172
+ modelName?: string;
173
+ clock: Clock;
174
+ ids: Ids;
175
+ /** The summarizer's instructions: the recipe's own, or the default. */
176
+ instructions: string;
177
+ /** How much of the most recent history to keep verbatim. */
178
+ keepTokens: number;
179
+ /** A person's own words for this one summary, added to the instructions. */
180
+ extraInstructions?: string;
181
+ }
182
+ /**
183
+ * Summarize a record now, because a person asked (decision 42).
184
+ *
185
+ * It answers `undefined` when there is nothing to cut, which is not a failure: a
186
+ * short history is already the view. The entry it makes is not appended here, so
187
+ * the caller decides what a write failure means; it is `trigger: "manual"`, and a
188
+ * person's extra instructions are recorded by their hash like any other.
189
+ */
190
+ export declare function compactRecord(options: ManualCompaction): Promise<Result<{
191
+ entry: CompactionEntry;
192
+ } | undefined, ModelError>>;
193
+ //# sourceMappingURL=compaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../src/core/compaction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAA4B,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGzF,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAMtC,sEAAsE;AACtE,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAmBtD;AAOD,6FAA6F;AAC7F,MAAM,WAAW,GAAG;IACnB,8EAA8E;IAC9E,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,KAAK,EAAE,MAAM,CAAC;IACd,iEAAiE;IACjE,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,EAAE,UAAU,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS,CA6C9F;AAKD;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,iFAAiF;IACjF,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB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,KAAK,EAAE,KAAK,CAAC;IACb,GAAG,EAAE,GAAG,CAAC;IACT,uEAAuE;IACvE,YAAY,EAAE,MAAM,CAAC;IACrB,4DAA4D;IAC5D,UAAU,EAAE,MAAM,CAAC;IACnB,4EAA4E;IAC5E,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,wBAAsB,aAAa,CAClC,OAAO,EAAE,gBAAgB,GACvB,OAAO,CAAC,MAAM,CAAC;IAAE,KAAK,EAAE,eAAe,CAAA;CAAE,GAAG,SAAS,EAAE,UAAU,CAAC,CAAC,CAwCrE"}
@@ -0,0 +1,460 @@
1
+ /**
2
+ * The cut, and what a history is guessed to cost (docs/context-size.md, decisions
3
+ * 39 to 41).
4
+ *
5
+ * Compaction never deletes from the record. It writes a `compaction` entry naming
6
+ * the first entry the model still sees, and the view is built from that pointer,
7
+ * so replay and the record keep everything (decision 39). This module is the pure
8
+ * half of that: how many tokens a piece of text is guessed to cost, and where the
9
+ * cut may fall.
10
+ *
11
+ * The estimate is four characters to a token. It is a smoke alarm rather than
12
+ * billing: the trigger adds it to the input tokens the provider reported for the
13
+ * last request, so it only has to be roughly right about what arrived since.
14
+ *
15
+ * A cut is only allowed to start a step, never to land on a tool result: a result
16
+ * whose call was summarized away would leave the model with an answer to a
17
+ * question it cannot see, and a provider refuses that (CMP02).
18
+ */
19
+ import { hashText } from "./hash.js";
20
+ import { RETRY_DELAYS_MS } from "./retry.js";
21
+ import { err, fail, ok } from "./result.js";
22
+ import { entryMessage } from "../record/replay.js";
23
+ /** Four characters to a token, the estimate decision 41 settled on. */
24
+ const CHARACTERS_PER_TOKEN = 4;
25
+ /** How many tokens a piece of text is guessed to cost, rounded up. */
26
+ export function estimateTokens(text) {
27
+ return Math.ceil(text.length / CHARACTERS_PER_TOKEN);
28
+ }
29
+ /**
30
+ * What one entry costs the model. A status, a note, a pin and a compaction are in
31
+ * the record but never in the conversation, so they are free here too.
32
+ */
33
+ export function entryTokens(entry) {
34
+ switch (entry.type) {
35
+ case "user_message":
36
+ return estimateTokens(entry.text);
37
+ case "assistant_message": {
38
+ let tokens = estimateTokens(entry.text);
39
+ if (entry.reasoning !== undefined) {
40
+ tokens += estimateTokens(entry.reasoning);
41
+ }
42
+ for (const call of entry.toolCalls) {
43
+ tokens += estimateTokens(call.name) + estimateTokens(call.arguments);
44
+ }
45
+ return tokens;
46
+ }
47
+ case "tool_message":
48
+ return estimateTokens(entry.content);
49
+ default:
50
+ return 0;
51
+ }
52
+ }
53
+ /** The entries that carry a message, which are the only ones a cut may start on. */
54
+ function startsStep(entry) {
55
+ return entry.type === "user_message" || entry.type === "assistant_message";
56
+ }
57
+ /**
58
+ * Where to cut a history so the model keeps at most `keepTokens` of it.
59
+ *
60
+ * Nothing is cut when the whole history already fits, which is the common case
61
+ * and also what an empty history and one that is a single step return: cutting
62
+ * a history down to itself would only spend a summary call.
63
+ */
64
+ export function chooseCut(entries, keepTokens) {
65
+ if (entries.length === 0) {
66
+ return undefined;
67
+ }
68
+ // What the suffix starting at each entry would cost, walked once from the end.
69
+ const suffixTokens = new Array(entries.length);
70
+ let running = 0;
71
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
72
+ running += entryTokens(entries[index]);
73
+ suffixTokens[index] = running;
74
+ }
75
+ if (suffixTokens[0] <= keepTokens) {
76
+ return undefined;
77
+ }
78
+ const last = entries.length - 1;
79
+ let index = -1;
80
+ // The smallest suffix that fits the budget and starts a step: the most recent
81
+ // work the budget allows, with nothing cut in the middle of it.
82
+ for (let candidate = 1; candidate <= last; candidate += 1) {
83
+ const entry = entries[candidate];
84
+ if (startsStep(entry) && suffixTokens[candidate] <= keepTokens) {
85
+ index = candidate;
86
+ break;
87
+ }
88
+ }
89
+ if (index < 0) {
90
+ // Not even the last step fits. Keeping it anyway is the smallest suffix that
91
+ // is still a whole step, which is better than an empty view.
92
+ for (let candidate = 1; candidate <= last; candidate += 1) {
93
+ if (startsStep(entries[candidate])) {
94
+ index = candidate;
95
+ }
96
+ }
97
+ }
98
+ if (index < 0) {
99
+ return undefined;
100
+ }
101
+ return {
102
+ firstKept: entries[index].id,
103
+ index,
104
+ replaces: index,
105
+ };
106
+ }
107
+ /** How a compaction summary is introduced to the model. */
108
+ const SUMMARY_LABEL = "Summary of the run so far. Older steps were compacted away:";
109
+ /**
110
+ * Build the view of a record. Everything before the latest `compaction`'s pointer
111
+ * is left out of the conversation but stays in the record, so replay still
112
+ * rebuilds tool state from every saved result (CMP07).
113
+ *
114
+ * A pointer that names no entry in the path is treated as the end of the
115
+ * compaction entry itself rather than as an error: a record whose chain is
116
+ * damaged is already noted by the loader, and showing the model too much is
117
+ * safer than showing it nothing.
118
+ */
119
+ export function buildView(path, stateTexts = []) {
120
+ let last;
121
+ for (const [index, entry] of path.entries()) {
122
+ if (entry.type === "compaction") {
123
+ last = { entry, index };
124
+ }
125
+ }
126
+ let start = 0;
127
+ if (last !== undefined) {
128
+ const pointer = path.findIndex((entry) => entry.id === last.entry.firstKept);
129
+ start = pointer >= 0 ? pointer : last.index + 1;
130
+ }
131
+ // Only what carries a message is part of the view: a status is progress, a note
132
+ // is for a person, and a compaction is how the view is built rather than
133
+ // something in it. A later cut is chosen from these, so a live view and a
134
+ // resumed one count the same entries.
135
+ const entries = path.slice(start).filter((entry) => entryMessage(entry) !== undefined);
136
+ const messages = [];
137
+ if (last !== undefined) {
138
+ messages.push({ role: "user", text: `${SUMMARY_LABEL}\n${last.entry.summary}` });
139
+ }
140
+ for (const text of stateTexts) {
141
+ messages.push({ role: "user", text });
142
+ }
143
+ for (const entry of entries) {
144
+ const message = entryMessage(entry);
145
+ if (message !== undefined) {
146
+ messages.push(message);
147
+ }
148
+ }
149
+ return {
150
+ entries,
151
+ summary: last?.entry.summary,
152
+ stateTexts,
153
+ messages,
154
+ };
155
+ }
156
+ /** The default cap on what the model reads from one tool result (decision 40). */
157
+ export const DEFAULT_RESULT_CAP_BYTES = 51_200;
158
+ /**
159
+ * What each tool says the recipe's state is, already labelled for the model
160
+ * (decision 40).
161
+ *
162
+ * A tool that throws here loses its state text and not the run: this runs while a
163
+ * view is being built, and a view is not worth failing a run over.
164
+ */
165
+ export function currentStateTexts(tools, state) {
166
+ if (state === undefined) {
167
+ return [];
168
+ }
169
+ const texts = [];
170
+ for (const tool of tools) {
171
+ if (tool.currentState === undefined) {
172
+ continue;
173
+ }
174
+ let text;
175
+ try {
176
+ text = tool.currentState(state);
177
+ }
178
+ catch {
179
+ text = undefined;
180
+ }
181
+ if (typeof text === "string" && text.trim() !== "") {
182
+ texts.push(`Current state of ${tool.spec.name}:\n${text}`);
183
+ }
184
+ }
185
+ return texts;
186
+ }
187
+ /** The most one old entry may take in a summary request, in estimated tokens. */
188
+ export const SUMMARY_ENTRY_TOKENS = 8_000;
189
+ function cappedForSummary(text) {
190
+ const limit = SUMMARY_ENTRY_TOKENS * CHARACTERS_PER_TOKEN;
191
+ if (text.length <= limit) {
192
+ return text;
193
+ }
194
+ return `${text.slice(0, limit)}\n…[cut for the summary: ${text.length - limit} characters dropped]`;
195
+ }
196
+ /** One entry as a line of the material a summary is written from. */
197
+ function describeForSummary(entry) {
198
+ switch (entry.type) {
199
+ case "user_message":
200
+ return `User: ${entry.text}`;
201
+ case "assistant_message": {
202
+ const calls = entry.toolCalls.map((call) => `${call.name}(${call.arguments})`);
203
+ const said = entry.text === "" ? "" : ` ${entry.text}`;
204
+ const asked = calls.length === 0 ? "" : ` → ${calls.join(", ")}`;
205
+ return `Assistant:${said}${asked}`;
206
+ }
207
+ case "tool_message":
208
+ return `Tool result: ${cappedForSummary(entry.content)}`;
209
+ default:
210
+ return undefined;
211
+ }
212
+ }
213
+ /**
214
+ * What a summary call is given: the previous summary, which it updates rather
215
+ * than restarts, and the steps since it, oldest first (decision 40).
216
+ *
217
+ * An old tool result is cut to a per-entry cap so the summary call itself fits in
218
+ * the window it is trying to save. That loses detail, and the record keeps it:
219
+ * `notes.md` says why the tradeoff was taken.
220
+ */
221
+ export function summaryMaterial(view, cut) {
222
+ const parts = [];
223
+ if (view.summary !== undefined) {
224
+ parts.push(`The previous summary, which you are updating rather than replacing:\n${view.summary}`);
225
+ }
226
+ const steps = [];
227
+ for (const entry of view.entries.slice(0, cut.index)) {
228
+ const line = describeForSummary(entry);
229
+ if (line !== undefined) {
230
+ steps.push(line);
231
+ }
232
+ }
233
+ parts.push(`The steps since then, oldest first:\n${steps.join("\n")}`);
234
+ return parts.join("\n\n");
235
+ }
236
+ /** `max(16384, 10% of the window)`, which is Nova's reserve (decision 41). */
237
+ export function defaultReserveTokens(window) {
238
+ return Math.max(16_384, Math.floor(window / 10));
239
+ }
240
+ /** What the run keeps if a recipe says nothing: Nova's 20000 tokens (decision 41). */
241
+ export const DEFAULT_KEEP_TOKENS = 20_000;
242
+ /** A recipe's compaction settings, checked once so a bad one fails fast (LIM03's rule). */
243
+ export function validateCompactionSettings(settings) {
244
+ const checked = {};
245
+ const positive = (value, field) => {
246
+ if (value === undefined) {
247
+ return ok(undefined);
248
+ }
249
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
250
+ return fail("bad_request", `compaction's ${field} must be a whole number of tokens`);
251
+ }
252
+ return ok(value);
253
+ };
254
+ const window = positive(settings.contextWindow, "contextWindow");
255
+ if (!window.ok) {
256
+ return window;
257
+ }
258
+ if (window.value === 0) {
259
+ return fail("bad_request", "compaction's contextWindow must be more than zero");
260
+ }
261
+ const reserve = positive(settings.reserveTokens, "reserveTokens");
262
+ if (!reserve.ok) {
263
+ return reserve;
264
+ }
265
+ const keep = positive(settings.keepTokens, "keepTokens");
266
+ if (!keep.ok) {
267
+ return keep;
268
+ }
269
+ if (window.value !== undefined) {
270
+ checked.contextWindow = window.value;
271
+ }
272
+ if (reserve.value !== undefined) {
273
+ checked.reserveTokens = reserve.value;
274
+ }
275
+ if (keep.value !== undefined) {
276
+ checked.keepTokens = keep.value;
277
+ }
278
+ if (settings.model !== undefined) {
279
+ if (typeof settings.model !== "string" || settings.model === "") {
280
+ return fail("bad_request", "compaction's model must be a non-empty name");
281
+ }
282
+ checked.model = settings.model;
283
+ }
284
+ if (settings.instructions !== undefined) {
285
+ if (typeof settings.instructions !== "string" || settings.instructions.trim() === "") {
286
+ return fail("bad_request", "compaction's instructions must be text");
287
+ }
288
+ checked.instructions = settings.instructions;
289
+ }
290
+ return ok(checked);
291
+ }
292
+ /**
293
+ * The instructions the summarizer is given when a recipe does not replace them.
294
+ *
295
+ * Shaped for a Lyra run rather than a coding chat: the goal is pinned in the system
296
+ * text and never summarized, the tools can hand back their own exact state, and
297
+ * what is left is progress, decisions and what is open (decision 40).
298
+ */
299
+ export const DEFAULT_SUMMARY_INSTRUCTIONS = [
300
+ "You are compacting the history of a run so it can go on with less context.",
301
+ "Write a summary of the work so far, under these headings:",
302
+ "- Goal: what the run is trying to do, in one sentence.",
303
+ "- Progress: what has been done, in order, including any result that changed something.",
304
+ "- Decisions: what was decided and why, where the record shows it.",
305
+ "- Open items: what is still to do, and anything that failed and needs another try.",
306
+ "- Exact identifiers: every handle, id, path, URL and name you copy must be copied exactly, never paraphrased.",
307
+ "If a previous summary is given, update it: keep what is still true, correct what moved, and do not start again.",
308
+ "Answer with the summary alone, with no preamble and no commentary.",
309
+ ].join("\n");
310
+ /**
311
+ * Ask the model for a summary, retrying a retryable failure the way the loop's own
312
+ * requests are retried (decision 26).
313
+ *
314
+ * An answer that is empty or only whitespace is a failure rather than a summary: a
315
+ * run that continued on it would have thrown away the history it meant to keep,
316
+ * and there is no smaller answer to fall back on.
317
+ */
318
+ export async function summarize(options) {
319
+ const request = {
320
+ system: options.summarizer.instructions,
321
+ messages: [{ role: "user", text: options.material }],
322
+ tools: [],
323
+ purpose: "compaction",
324
+ signal: options.signal,
325
+ };
326
+ if (options.summarizer.modelName !== undefined) {
327
+ request.model = options.summarizer.modelName;
328
+ }
329
+ let retries = 0;
330
+ for (;;) {
331
+ let answered;
332
+ try {
333
+ answered = await options.summarizer.model.complete(request);
334
+ }
335
+ catch (error) {
336
+ const text = error instanceof Error ? error.message : String(error);
337
+ return err({
338
+ code: "internal",
339
+ message: `the summarizer threw: ${text.slice(0, 300)}`,
340
+ retryable: false,
341
+ });
342
+ }
343
+ if (answered.ok) {
344
+ if (answered.value.text.trim() === "") {
345
+ return err({
346
+ code: "provider_error",
347
+ message: "the summarizer answered with nothing",
348
+ retryable: false,
349
+ });
350
+ }
351
+ return ok({
352
+ summary: answered.value.text,
353
+ model: answered.value.model,
354
+ usage: answered.value.usage,
355
+ });
356
+ }
357
+ const delay = RETRY_DELAYS_MS[retries];
358
+ if (!answered.error.retryable || delay === undefined) {
359
+ return answered;
360
+ }
361
+ const waitMs = Math.max(delay, answered.error.retryAfterMs ?? 0);
362
+ options.onRetry?.(retries + 1, waitMs, answered.error);
363
+ retries += 1;
364
+ try {
365
+ await options.clock.sleep(waitMs, options.signal);
366
+ }
367
+ catch {
368
+ // Stopped while waiting: the caller checks the signal before believing
369
+ // this error, so the run parks `stopped` rather than failing.
370
+ return answered;
371
+ }
372
+ }
373
+ }
374
+ /** Whether the conversation is close enough to the window to compact (decision 41). */
375
+ export function shouldCompact(estimate, window, reserveTokens) {
376
+ return estimate > window - reserveTokens;
377
+ }
378
+ /** The tokens a conversation is guessed to cost. */
379
+ export function estimateConversation(messages) {
380
+ let tokens = 0;
381
+ for (const message of messages) {
382
+ if (message.role === "assistant") {
383
+ tokens += estimateTokens(message.text);
384
+ if (message.reasoning !== undefined) {
385
+ tokens += estimateTokens(message.reasoning);
386
+ }
387
+ for (const call of message.toolCalls) {
388
+ tokens += estimateTokens(call.name) + estimateTokens(call.arguments);
389
+ }
390
+ }
391
+ else if (message.role === "user") {
392
+ tokens += estimateTokens(message.text);
393
+ }
394
+ else {
395
+ tokens += estimateTokens(message.content);
396
+ }
397
+ }
398
+ return tokens;
399
+ }
400
+ /**
401
+ * What was added since the last request: the reply it produced, and every message
402
+ * after it. A provider's reported input tokens only cover that request, so this is
403
+ * the part it could not know about (decision 41).
404
+ */
405
+ export function estimateSinceLastReply(messages) {
406
+ let last = -1;
407
+ for (const [index, message] of messages.entries()) {
408
+ if (message.role === "assistant") {
409
+ last = index;
410
+ }
411
+ }
412
+ return last < 0 ? estimateConversation(messages) : estimateConversation(messages.slice(last));
413
+ }
414
+ /**
415
+ * Summarize a record now, because a person asked (decision 42).
416
+ *
417
+ * It answers `undefined` when there is nothing to cut, which is not a failure: a
418
+ * short history is already the view. The entry it makes is not appended here, so
419
+ * the caller decides what a write failure means; it is `trigger: "manual"`, and a
420
+ * person's extra instructions are recorded by their hash like any other.
421
+ */
422
+ export async function compactRecord(options) {
423
+ const view = buildView(options.path);
424
+ const cut = chooseCut(view.entries, options.keepTokens);
425
+ if (cut === undefined) {
426
+ return ok(undefined);
427
+ }
428
+ const instructions = options.extraInstructions === undefined
429
+ ? options.instructions
430
+ : `${options.instructions}\n\nAdditional instructions for this summary:\n${options.extraInstructions}`;
431
+ const summarized = await summarize({
432
+ summarizer: {
433
+ model: options.model,
434
+ instructions,
435
+ ...(options.modelName === undefined ? {} : { modelName: options.modelName }),
436
+ },
437
+ material: summaryMaterial(view, cut),
438
+ clock: options.clock,
439
+ signal: new AbortController().signal,
440
+ });
441
+ if (!summarized.ok) {
442
+ return summarized;
443
+ }
444
+ return ok({
445
+ entry: {
446
+ type: "compaction",
447
+ id: options.ids.next("e"),
448
+ parent: options.parent,
449
+ ts: options.clock.now(),
450
+ summary: summarized.value.summary,
451
+ firstKept: cut.firstKept,
452
+ replaces: cut.replaces,
453
+ usage: summarized.value.usage,
454
+ model: summarized.value.model,
455
+ trigger: "manual",
456
+ instructionsHash: await hashText(instructions),
457
+ },
458
+ });
459
+ }
460
+ //# sourceMappingURL=compaction.js.map