@wraith-ai/core 0.1.0 → 0.1.1

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 (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,384 @@
1
+ import { generateText } from "ai";
2
+ import { type Usage, normaliseUsage } from "../events/types";
3
+ import { withRequestFields } from "../providers/cache";
4
+ import { type Model, toModel } from "../providers/model";
5
+ import type { AgentLanguageModel, ModelCallSettings } from "../providers/types";
6
+ import { summaryMessage } from "../session/format";
7
+ import { type ModelPrices, priceCall } from "./cost";
8
+ import { attachmentOf, type ModelMessage } from "./messages";
9
+
10
+ /**
11
+ * Compaction: history summarized by a model when the context window runs out.
12
+ *
13
+ * The threshold is checked before a request goes out, never after one fails:
14
+ * a context-length error costs a full round trip and arrives when the run is
15
+ * already too long to recover cheaply.
16
+ */
17
+
18
+ export interface CompactionPolicy {
19
+ /** Turns kept verbatim at the end. Fresh context is what a summary cannot rebuild. */
20
+ keepLastTurns: number;
21
+ /** Head-room for the system prompt and tool declarations, which we do not measure. */
22
+ bufferTokens: number;
23
+ summaryMaxTokens: number;
24
+ reserveOutputTokens: number;
25
+ }
26
+
27
+ export const defaultCompactionPolicy: CompactionPolicy = {
28
+ keepLastTurns: 2,
29
+ bufferTokens: 20_000,
30
+ summaryMaxTokens: 4_096,
31
+ reserveOutputTokens: 4_096,
32
+ };
33
+
34
+ /**
35
+ * What compaction decided, not the resulting history.
36
+ *
37
+ * The loop rebuilds the messages from these numbers with the same rule the
38
+ * session log replays on resume. A compactor that returned its own array could
39
+ * return history a reload would not reproduce, and a session would then behave
40
+ * differently across a restart.
41
+ */
42
+ export interface CompactionResult {
43
+ summary: string;
44
+ /** How many trailing messages survive verbatim. */
45
+ keptMessages: number;
46
+ droppedMessages: number;
47
+ tokensBefore: number;
48
+ tokensAfter: number;
49
+ /**
50
+ * What the summarizing call itself cost. It is counted in the session total.
51
+ */
52
+ usage: Usage;
53
+ }
54
+
55
+ /** The one way to turn a compaction decision into history, used everywhere. */
56
+ export function applyCompaction(
57
+ messages: readonly ModelMessage[],
58
+ result: Pick<CompactionResult, "summary" | "keptMessages">,
59
+ ): ModelMessage[] {
60
+ return [
61
+ summaryMessage(result.summary),
62
+ ...messages.slice(messages.length - result.keptMessages),
63
+ ];
64
+ }
65
+
66
+ export interface CompactionInput {
67
+ messages: readonly ModelMessage[];
68
+ /** Input tokens the provider reported for the previous request, when it did. */
69
+ lastInputTokens?: number;
70
+ signal?: AbortSignal;
71
+ /** Called just before the summarizing model is, so a front end can say it is waiting. */
72
+ onStart?: () => void;
73
+ /** The session's id, as the routing key: the run passes it, so must a host. */
74
+ cacheKey?: string;
75
+ }
76
+
77
+ export interface Compactor {
78
+ maybeCompact(input: CompactionInput): Promise<CompactionResult | null>;
79
+ /**
80
+ * Compacts because somebody asked, whatever the threshold says. Optional: a
81
+ * compactor without it cannot do this, and a host has to say so, not pretend.
82
+ */
83
+ compactNow?(input: CompactionInput, note?: string): Promise<CompactionResult | null>;
84
+ }
85
+
86
+ export interface CompactorOptions {
87
+ /**
88
+ * The summarising model, which may be cheaper than the run's: its own prices
89
+ * come with it, and its requests are keyed by the session the run passes.
90
+ */
91
+ model: Model | AgentLanguageModel;
92
+ /**
93
+ * The window of the **run's** model, not the summariser's: it decides when
94
+ * the conversation is full. Required.
95
+ *
96
+ * A host with no window size must decide not to build a compactor at all,
97
+ * and say so in its own code. Missing data never blocks a run.
98
+ */
99
+ contextLimit: number;
100
+ policy?: Partial<CompactionPolicy>;
101
+ /** Overrides the built-in summarization template. */
102
+ template?: string;
103
+ settings?: ModelCallSettings;
104
+ /** Prices over the summarising model's own. */
105
+ pricing?: ModelPrices;
106
+ }
107
+
108
+ /**
109
+ * A briefing for whoever picks the work up, not a recap of a chat; the fixed
110
+ * headings carry the state an agent needs to keep working.
111
+ *
112
+ * A constant, not a `.md` file: `node:fs` is banned in `agent/`.
113
+ * Prompts owned by an application live in that application.
114
+ */
115
+ export const COMPACTION_TEMPLATE = `You are compacting the transcript of an AI agent's working session so the agent can keep going with a smaller context.
116
+
117
+ Write a briefing in Markdown under exactly these headings:
118
+
119
+ ## Goal
120
+ What the user asked for, in their terms.
121
+
122
+ ## Constraints
123
+ Rules, preferences and limits stated so far, including anything the user rejected.
124
+
125
+ ## Progress
126
+ What has actually been done: files created or changed, commands run, results observed.
127
+
128
+ ## Key decisions
129
+ Choices made and the reason for each.
130
+
131
+ ## Next steps
132
+ What remains, in the order it should happen.
133
+
134
+ ## Critical context
135
+ Facts the agent would get wrong from memory: exact names, paths, ids, versions, error text.
136
+
137
+ Rules:
138
+ - Preserve exact identifiers, paths and error messages; never paraphrase them.
139
+ - Record failures and dead ends — they stop the work being repeated.
140
+ - Omit pleasantries, reasoning that led nowhere, and anything already superseded.
141
+ - Write it for the agent that continues the work, not for a reader of the chat.`;
142
+
143
+ /**
144
+ * How full the context is, for the compactor and for a status bar, from one
145
+ * function: two copies of this sum would drift on the next policy change.
146
+ *
147
+ * The percentage is measured against the compaction threshold, not the bare
148
+ * window: against the window, the bar would read roomy exactly when compaction
149
+ * is about to run.
150
+ */
151
+ export interface ContextUsage {
152
+ /** Input tokens the last request reported, or an estimate before the first. */
153
+ used: number;
154
+ /** `contextLimit − reserveOutputTokens − bufferTokens`. */
155
+ threshold: number;
156
+ limit: number;
157
+ /** `used / threshold`, capped at 1. Zero when the window leaves no room. */
158
+ fraction: number;
159
+ }
160
+
161
+ export function contextUsage(
162
+ policy: CompactionPolicy,
163
+ contextLimit: number,
164
+ lastInputTokens?: number,
165
+ ): ContextUsage {
166
+ const threshold = contextLimit - policy.reserveOutputTokens - policy.bufferTokens;
167
+ const used = lastInputTokens ?? 0;
168
+ // A window with no room past its reserve and buffer reads as empty, not
169
+ // full, so the compactor leaves it alone.
170
+ const fraction = threshold <= 0 ? 0 : Math.min(1, used / threshold);
171
+ return { used, threshold, limit: contextLimit, fraction };
172
+ }
173
+
174
+ /**
175
+ * What one image costs, roughly: Anthropic scales a large one to about 1,600
176
+ * tokens. Its base64 counted as text would be a hundred times that, and would
177
+ * start a compaction on the first screenshot.
178
+ */
179
+ export const IMAGE_TOKEN_ESTIMATE = 1_600;
180
+
181
+ /** Cheap and rough; the provider's own count corrects it. */
182
+ export function estimateTokens(messages: readonly ModelMessage[]): number {
183
+ let characters = 0;
184
+ let images = 0;
185
+ for (const message of messages) {
186
+ if (typeof message.content === "string") {
187
+ characters += message.content.length;
188
+ continue;
189
+ }
190
+ for (const part of message.content as readonly unknown[]) {
191
+ const counted = withoutImageData(part);
192
+ images += counted.images;
193
+ characters += JSON.stringify(counted.part).length;
194
+ }
195
+ }
196
+ return Math.ceil(characters / 4) + images * IMAGE_TOKEN_ESTIMATE;
197
+ }
198
+
199
+ /** A part with its images taken out and counted, in a prompt or in a tool result. */
200
+ function withoutImageData(part: unknown): { part: unknown; images: number } {
201
+ if (attachmentOf(part) !== undefined) return { part: "", images: 1 };
202
+ const record = part as { type?: unknown; output?: { type?: unknown; value?: unknown } };
203
+ if (record.type !== "tool-result" || record.output?.type !== "content" || !Array.isArray(record.output.value)) {
204
+ return { part, images: 0 };
205
+ }
206
+ const items = record.output.value as readonly unknown[];
207
+ const kept = items.filter((item) => attachmentOf(item) === undefined);
208
+ return { part: { ...record, output: { ...record.output, value: kept } }, images: items.length - kept.length };
209
+ }
210
+
211
+ const TOOL_OUTPUT_LIMIT = 2_000;
212
+
213
+ function renderPart(part: unknown): string {
214
+ if (typeof part === "string") return part;
215
+ const record = part as Record<string, unknown>;
216
+ switch (record.type) {
217
+ case "text":
218
+ return String(record.text ?? "");
219
+ case "reasoning":
220
+ return "";
221
+ case "tool-call":
222
+ return `[calls ${String(record.toolName)} with ${JSON.stringify(record.input)}]`;
223
+ case "tool-result": {
224
+ const output = JSON.stringify(imagesNamed(record.output ?? ""));
225
+ return `[result of ${String(record.toolName)}: ${truncate(output, TOOL_OUTPUT_LIMIT)}]`;
226
+ }
227
+ case "image":
228
+ case "file":
229
+ // Attachments are dropped rather than described: re-sending megabytes of
230
+ // base64 to *save* context would defeat the exercise.
231
+ return "[attachment omitted]";
232
+ default:
233
+ return "";
234
+ }
235
+ }
236
+
237
+ /** A result's images named, not kept: a cut through base64 is noise the summariser pays for. */
238
+ function imagesNamed(output: unknown): unknown {
239
+ const result = output as { type?: unknown; value?: unknown };
240
+ if (result.type !== "content" || !Array.isArray(result.value)) return output;
241
+ return {
242
+ ...result,
243
+ value: (result.value as readonly unknown[]).map((item) =>
244
+ attachmentOf(item) === undefined ? item : "[attachment omitted]",
245
+ ),
246
+ };
247
+ }
248
+
249
+ function truncate(value: string, limit: number): string {
250
+ return value.length <= limit ? value : `${value.slice(0, limit)}… (truncated)`;
251
+ }
252
+
253
+ /**
254
+ * The transcript goes to the summarizer as plain text, not as a message array.
255
+ * Some providers reject a tool result whose declaration is missing, and text
256
+ * works everywhere and costs less.
257
+ */
258
+ export function renderTranscript(messages: readonly ModelMessage[]): string {
259
+ const lines: string[] = [];
260
+ for (const message of messages) {
261
+ const body = Array.isArray(message.content)
262
+ ? message.content.map(renderPart).filter((part) => part !== "").join("\n")
263
+ : String(message.content);
264
+ if (body.trim() === "") continue;
265
+ lines.push(`### ${message.role}\n${body}`);
266
+ }
267
+ return lines.join("\n\n");
268
+ }
269
+
270
+ /**
271
+ * Where to cut so the tail stays intact.
272
+ *
273
+ * Turns start at user messages, so cutting there keeps every assistant message
274
+ * with the tool results that answer it. An orphaned tool result is a 400 from
275
+ * the provider.
276
+ */
277
+ export function findCut(
278
+ messages: readonly ModelMessage[],
279
+ keepLastTurns: number,
280
+ tailBudget = Number.POSITIVE_INFINITY,
281
+ ): number {
282
+ const starts: number[] = [];
283
+ for (let index = 0; index < messages.length; index += 1) {
284
+ if (messages[index]?.role === "user") starts.push(index);
285
+ }
286
+
287
+ let cut = starts.length <= keepLastTurns ? 0 : (starts[starts.length - keepLastTurns] ?? 0);
288
+
289
+ // Turns that alone outgrow the budget are cut inside, or compaction keeps
290
+ // re-summarizing its own summary and shrinks nothing.
291
+ let size = estimateTokens(messages.slice(cut));
292
+ while (cut < messages.length && size > tailBudget) {
293
+ size -= estimateTokens(messages.slice(cut, cut + 1));
294
+ cut += 1;
295
+ }
296
+
297
+ // Never begin the kept tail with a result whose call was dropped.
298
+ while (cut < messages.length && messages[cut]?.role === "tool") cut += 1;
299
+ return cut;
300
+ }
301
+
302
+ /** Share of the threshold the verbatim tail may take. */
303
+ const TAIL_SHARE = 0.25;
304
+
305
+ export function createCompactor(options: CompactorOptions): Compactor {
306
+ const policy = { ...defaultCompactionPolicy, ...options.policy };
307
+ const template = options.template ?? COMPACTION_TEMPLATE;
308
+ const model = toModel(options.model);
309
+ const pricing = options.pricing ?? model.pricing;
310
+
311
+ /** Everything after the decision to compact, shared so both roads bill alike. */
312
+ const summarize = async (
313
+ input: CompactionInput,
314
+ cut: number,
315
+ tokensBefore: number,
316
+ note?: string,
317
+ ): Promise<CompactionResult | null> => {
318
+ const dropped = input.messages.slice(0, cut);
319
+ const kept = input.messages.slice(cut);
320
+
321
+ // Ahead of the transcript, where nothing a tool printed can pass for it.
322
+ const guidance = note?.trim() ?? "";
323
+ const heading = guidance === "" ? "" : `The user asked this of the summary: ${guidance}\n\n`;
324
+
325
+ // Same boundary cast as the loop: the SDK's option types are keyed on the
326
+ // shape of the call, so one cast here keeps the rest of the file plain.
327
+ const callOptions = {
328
+ model: model.languageModel,
329
+ system: template,
330
+ prompt: `${heading}Here is the transcript to compact:\n\n${renderTranscript(dropped)}`,
331
+ ...withRequestFields(options.settings ?? {}, model.requestFields(input.cacheKey)),
332
+ maxOutputTokens: policy.summaryMaxTokens,
333
+ ...(input.signal === undefined ? {} : { abortSignal: input.signal }),
334
+ } as Parameters<typeof generateText>[0];
335
+
336
+ input.onStart?.();
337
+ const generated = await generateText(callOptions);
338
+
339
+ const summary = generated.text.trim();
340
+ if (summary === "") return null;
341
+
342
+ const compacted = applyCompaction(input.messages, {
343
+ summary,
344
+ keptMessages: kept.length,
345
+ });
346
+ return {
347
+ summary,
348
+ keptMessages: kept.length,
349
+ droppedMessages: dropped.length,
350
+ tokensBefore,
351
+ tokensAfter: estimateTokens(compacted),
352
+ // Priced here, where the model that ran is known. The loop folds this
353
+ // into the session total through the one door every spend goes through.
354
+ usage: priceCall(normaliseUsage(generated.usage), pricing, {
355
+ providerUsage: (generated.usage as { raw?: unknown }).raw,
356
+ metadata: generated.providerMetadata,
357
+ }),
358
+ };
359
+ };
360
+
361
+ return {
362
+ async maybeCompact(input: CompactionInput): Promise<CompactionResult | null> {
363
+ // The provider's count measured a prefix of what we are about to send, so
364
+ // it is a floor; the estimate covers everything added since.
365
+ const tokensBefore = Math.max(estimateTokens(input.messages), input.lastInputTokens ?? 0);
366
+ // The same sum a status bar draws. Taking it from `contextUsage` keeps
367
+ // the two from disagreeing.
368
+ const usage = contextUsage(policy, options.contextLimit, tokensBefore);
369
+ if (usage.fraction < 1) return null;
370
+
371
+ const cut = findCut(input.messages, policy.keepLastTurns, usage.threshold * TAIL_SHARE);
372
+ return cut === 0 ? null : summarize(input, cut, tokensBefore);
373
+ },
374
+
375
+ async compactNow(input: CompactionInput, note?: string): Promise<CompactionResult | null> {
376
+ const tokensBefore = Math.max(estimateTokens(input.messages), input.lastInputTokens ?? 0);
377
+ const usage = contextUsage(policy, options.contextLimit, tokensBefore);
378
+
379
+ // Asked for, so the threshold is not consulted; the tail is kept all the same.
380
+ const cut = findCut(input.messages, policy.keepLastTurns, usage.threshold * TAIL_SHARE);
381
+ return cut === 0 ? null : summarize(input, cut, tokensBefore, note);
382
+ },
383
+ };
384
+ }
@@ -0,0 +1,300 @@
1
+ import { AgentError, serializeError, type SerializedError } from "../errors";
2
+ import type { AgentEvent } from "../events/types";
3
+ import { applyRecords, messageOf, usageOwed, type SessionRecordInput } from "../session/format";
4
+ import { createSession, type Session } from "../session/session";
5
+ import type { SessionStore } from "../session/store";
6
+ import type { Agent } from "./agent";
7
+ import { type Prompt, type UserInput, toUserInput } from "./attachments";
8
+ import { createInbox, type InboxQueue } from "./inbox";
9
+ import { run, type RunResult } from "./loop";
10
+
11
+ /**
12
+ * Turns, one after another, on one session: what every front end has to do
13
+ * the same way, and nothing a host could want done differently. Built only from
14
+ * what the core exports, so a host can write its own instead.
15
+ */
16
+
17
+ export interface ConversationOptions {
18
+ /**
19
+ * Absent: nothing can run until `use()` gives one. A front end opens its
20
+ * session before it knows which model the user will pick.
21
+ */
22
+ agent?: Agent;
23
+ /** Absent: a fresh session held in memory. */
24
+ session?: Session;
25
+ /** Absent: nothing is written anywhere. */
26
+ store?: SessionStore;
27
+ /**
28
+ * Absent: a queue of its own, so `steer()` works with nothing configured.
29
+ * A task registry must be given this same one, or its tasks end unheard.
30
+ */
31
+ inbox?: InboxQueue;
32
+ /**
33
+ * Absent or true: a record that asks for a run — a task that ended — starts
34
+ * one, also while nobody types. False for a host that answers and leaves, as
35
+ * `wraith run` does: a run woken just before `close()` would be paid for and
36
+ * cut short.
37
+ */
38
+ wake?: boolean;
39
+ /**
40
+ * The run this conversation works for, when another agent's tool started it:
41
+ * its events then carry that id as `parentRunId`. A function, because each
42
+ * turn may be asked for by a different run.
43
+ */
44
+ parentRunId?: string | (() => string | undefined);
45
+ }
46
+
47
+ export type ConversationEvent =
48
+ | AgentEvent
49
+ /** A run is about to start. `prompt` is absent for a run the inbox started. */
50
+ | { type: "turn-start"; prompt?: UserInput }
51
+ /** A run ended, the session moved on and, with a store, the log grew. */
52
+ | { type: "turn-end"; result: RunResult }
53
+ /** A run or its write failed. The conversation stays usable. */
54
+ | { type: "turn-error"; error: SerializedError };
55
+
56
+ export interface Conversation {
57
+ readonly session: Session;
58
+ readonly busy: boolean;
59
+ /** The agent the next run uses, if one was given yet. */
60
+ readonly agent: Agent | undefined;
61
+ /**
62
+ * A new turn: now when idle, after the current run when busy. Settles when
63
+ * the conversation is idle again. Refused with `conversation/no-agent`
64
+ * before an agent is given, and with `attachment/*` for an image the vendors
65
+ * would refuse.
66
+ */
67
+ send(prompt: Prompt): Promise<void>;
68
+ /** Into the run in flight, before its next model call. The same as `send()` when idle. */
69
+ steer(prompt: Prompt): Promise<void>;
70
+ /**
71
+ * Starts a run for what is waiting in the inbox, if anything asks for one and
72
+ * an agent is there. Called on every push unless `wake: false` was given.
73
+ */
74
+ wake(): void;
75
+ subscribe(listener: (event: ConversationEvent) => void): () => void;
76
+ /** The agent the next run uses. */
77
+ use(agent: Agent): void;
78
+ /**
79
+ * Records written outside a run: a title, usage, a compaction on demand.
80
+ * While a run is in flight, records that change the history — a message,
81
+ * a task, a compaction, a system prompt — are refused with
82
+ * `conversation/busy`; the rest are written at once.
83
+ */
84
+ append(records: readonly SessionRecordInput[]): Promise<void>;
85
+ /** Prompts sent while busy that have not started yet. */
86
+ readonly queued: readonly UserInput[];
87
+ clearQueue(): void;
88
+ /** Cancels the run in flight; queued prompts still run. True when there was a run to cancel. */
89
+ abort(): boolean;
90
+ /**
91
+ * Takes back what was typed and has not entered the conversation: steered
92
+ * lines still waiting and queued prompts. Nothing starts afterwards until
93
+ * the next send or wake.
94
+ */
95
+ recall(): UserInput[];
96
+ /** Stops waking, cancels the run in flight, waits for it, and writes what is left in the inbox. */
97
+ close(): Promise<void>;
98
+ }
99
+
100
+ export function createConversation(options: ConversationOptions): Conversation {
101
+ const { store } = options;
102
+ const inbox = options.inbox ?? createInbox();
103
+ let agent = options.agent;
104
+ let session =
105
+ options.session ?? createSession(agent?.newId("session") ?? `session-${crypto.randomUUID()}`);
106
+ let driving: Promise<void> | undefined;
107
+ let abort: AbortController | undefined;
108
+ // Something asked for a run while one was in flight.
109
+ let rung = false;
110
+ const queued: UserInput[] = [];
111
+ const listeners = new Set<(event: ConversationEvent) => void>();
112
+
113
+ const emit = (event: ConversationEvent): void => {
114
+ for (const listener of listeners) listener(event);
115
+ };
116
+
117
+ // Every write of this conversation queues behind the one before, so records
118
+ // enter `session` in the order they were written, whatever the store does.
119
+ let lastWrite: Promise<void> = Promise.resolve();
120
+ const write = (records: readonly SessionRecordInput[]): Promise<void> => {
121
+ if (store === undefined) return Promise.resolve();
122
+ const id = session.id;
123
+ const next = lastWrite.then(() => store.append(id, records));
124
+ // A failed write still frees the queue; its caller gets the error from `next`.
125
+ lastWrite = next.then(
126
+ () => undefined,
127
+ () => undefined,
128
+ );
129
+ return next;
130
+ };
131
+
132
+ const noAgent = (): AgentError =>
133
+ new AgentError("conversation/no-agent", "No agent to run with yet.");
134
+
135
+ const turn = async (prompt?: UserInput): Promise<void> => {
136
+ abort = new AbortController();
137
+ emit(prompt === undefined ? { type: "turn-start" } : { type: "turn-start", prompt });
138
+ try {
139
+ if (agent === undefined) throw noAgent();
140
+ const input = prompt === undefined ? { session } : { session, prompt };
141
+ const parentRunId =
142
+ typeof options.parentRunId === "function" ? options.parentRunId() : options.parentRunId;
143
+ const stream = run(agent, input, {
144
+ signal: abort.signal,
145
+ inbox,
146
+ ...(parentRunId === undefined ? {} : { parentRunId }),
147
+ });
148
+ try {
149
+ let next = await stream.next();
150
+ while (next.done !== true) {
151
+ const event = next.value;
152
+ // Written before the run goes on, and kept in memory only once written,
153
+ // so the session a resume reads is the one this conversation continues.
154
+ if (event.type === "record") {
155
+ await write([event.record]);
156
+ session = applyRecords(session, [event.record]);
157
+ }
158
+ emit(event);
159
+ next = await stream.next();
160
+ }
161
+ emit({ type: "turn-end", result: next.value });
162
+ } catch (error) {
163
+ // A write that failed ends the run, as any host that stops reading does:
164
+ // what it did next would be missing from the log.
165
+ await stream.return(undefined as never);
166
+ throw error;
167
+ }
168
+ } catch (error) {
169
+ // A run the inbox started has nobody awaiting it, so a rejection alone would vanish.
170
+ emit({ type: "turn-error", error: serializeError(error) });
171
+ } finally {
172
+ abort = undefined;
173
+ }
174
+ };
175
+
176
+ const drive = (first?: UserInput): Promise<void> => {
177
+ driving ??= (async () => {
178
+ let prompt = first;
179
+ for (;;) {
180
+ await turn(prompt);
181
+ prompt = queued.shift();
182
+ if (prompt !== undefined) continue;
183
+ if (!rung) break;
184
+ rung = false;
185
+ // The run in flight may already have taken what rang.
186
+ if (!inbox.wakes()) break;
187
+ }
188
+ })().finally(() => {
189
+ driving = undefined;
190
+ });
191
+ return driving;
192
+ };
193
+
194
+ const wake = (): void => {
195
+ if (driving !== undefined) {
196
+ rung = true;
197
+ return;
198
+ }
199
+ // What rang stays in the inbox; the first `send()` takes it in.
200
+ if (agent !== undefined && inbox.wakes()) void drive();
201
+ };
202
+ // On unless the host says otherwise: a host that forgets the line gets tasks
203
+ // that end unheard, and nothing fails to say so.
204
+ const unsubscribe = options.wake === false ? undefined : inbox.subscribe(wake);
205
+
206
+ return {
207
+ get session() {
208
+ return session;
209
+ },
210
+ get busy() {
211
+ return driving !== undefined;
212
+ },
213
+ get agent() {
214
+ return agent;
215
+ },
216
+ get queued() {
217
+ return queued;
218
+ },
219
+ clearQueue: () => {
220
+ queued.length = 0;
221
+ },
222
+ subscribe: (listener) => {
223
+ listeners.add(listener);
224
+ return () => {
225
+ listeners.delete(listener);
226
+ };
227
+ },
228
+
229
+ send: (prompt) => {
230
+ if (agent === undefined) return Promise.reject(noAgent());
231
+ let input: UserInput;
232
+ try {
233
+ input = toUserInput(prompt);
234
+ } catch (error) {
235
+ return Promise.reject(error);
236
+ }
237
+ if (driving === undefined) return drive(input);
238
+ queued.push(input);
239
+ return driving;
240
+ },
241
+ steer: (prompt) => {
242
+ if (agent === undefined) return Promise.reject(noAgent());
243
+ let input: UserInput;
244
+ try {
245
+ input = toUserInput(prompt);
246
+ } catch (error) {
247
+ return Promise.reject(error);
248
+ }
249
+ if (driving === undefined) return drive(input);
250
+ inbox.send(input);
251
+ rung = true;
252
+ return driving;
253
+ },
254
+ wake,
255
+
256
+ use: (next) => {
257
+ agent = next;
258
+ },
259
+ append: async (records) => {
260
+ // The run builds its history from the session it started with, so a
261
+ // message slipped in now would sit in the log where the model never saw it.
262
+ if (driving !== undefined && records.some(shapesHistory)) {
263
+ throw new AgentError(
264
+ "conversation/busy",
265
+ "Records that change the history cannot be appended while a run is in flight.",
266
+ );
267
+ }
268
+ session = applyRecords(session, records);
269
+ await write(records);
270
+ },
271
+ abort: () => {
272
+ if (abort === undefined || abort.signal.aborted) return false;
273
+ abort.abort();
274
+ return true;
275
+ },
276
+ recall: () => {
277
+ const typed = [...inbox.recall(), ...queued];
278
+ queued.length = 0;
279
+ rung = false;
280
+ return typed;
281
+ },
282
+ close: async () => {
283
+ // First, so what the stopped tasks push on the way out starts nothing.
284
+ unsubscribe?.();
285
+ queued.length = 0;
286
+ abort?.abort();
287
+ await driving;
288
+ const taken = inbox.take();
289
+ if (taken.length === 0) return;
290
+ // No run will deliver these, so what a task spent is written here with its ending.
291
+ const left = [...taken, ...usageOwed(taken)];
292
+ session = applyRecords(session, left);
293
+ await write(left);
294
+ },
295
+ };
296
+ }
297
+
298
+ function shapesHistory(record: SessionRecordInput): boolean {
299
+ return messageOf(record) !== undefined || record.type === "compaction" || record.type === "system";
300
+ }