@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,156 @@
1
+ import type { LanguageModelMiddleware, ModelMessage } from "ai";
2
+ import type { ReasoningEffort } from "../config/schema";
3
+
4
+ /**
5
+ * Which effort each turn of a conversation ran at. The loop stamps each
6
+ * assistant message under `providerOptions[TURN_OPTIONS_KEY]`; vendors read
7
+ * only their own namespace, so the stamp changes nothing for them. A factory
8
+ * that can change effort mid-conversation without restarting the prompt cache
9
+ * reads the stamps and renders the changes in its own dialect; the rest never
10
+ * look. The key is a fixed format name, so renaming the product does not make
11
+ * old logs unreadable.
12
+ */
13
+ export const TURN_OPTIONS_KEY = "turn";
14
+
15
+ /**
16
+ * Models documented as taking an effort change mid-conversation without
17
+ * restarting the prompt cache (OpenRouter, 2026-11), in OpenRouter's ids; Codex
18
+ * looks its models up as `openai/<id>`. No catalog says which do, so this list
19
+ * is kept by hand. It is here so a host can read it without a vendor's SDK.
20
+ */
21
+ export const TURN_EFFORT_MODELS: ReadonlySet<string> = new Set([
22
+ "anthropic/claude-fable-5.1",
23
+ "anthropic/claude-fable-5.2",
24
+ "anthropic/claude-opus-5",
25
+ "openai/gpt-6-astra",
26
+ "openai/gpt-6-luna",
27
+ "openai/gpt-6-sol",
28
+ "openai/gpt-6.1-sol",
29
+ "openai/gpt-6.1-terra",
30
+ ]);
31
+
32
+ type CallParams = Parameters<NonNullable<LanguageModelMiddleware["transformParams"]>>[0]["params"];
33
+ export type Prompt = CallParams["prompt"];
34
+ export type PromptMessage = Prompt[number];
35
+
36
+ /** An effort someone chose. `provider-default` is the absence of a choice. */
37
+ export type ExplicitEffort = Exclude<ReasoningEffort, "provider-default">;
38
+
39
+ const EXPLICIT: ReadonlySet<string> = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
40
+
41
+ /** Levels the per-turn form carries. `none` is refused by Claude, so it goes by request. */
42
+ const PER_TURN: ReadonlySet<string> = new Set(["minimal", "low", "medium", "high", "xhigh", "max"]);
43
+
44
+ export function explicitEffort(level: unknown): ExplicitEffort | undefined {
45
+ return typeof level === "string" && EXPLICIT.has(level) ? (level as ExplicitEffort) : undefined;
46
+ }
47
+
48
+ const LEAST_FIRST: readonly ExplicitEffort[] = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
49
+
50
+ /**
51
+ * The least thinking a model takes for a quick side question, such as the
52
+ * classifier's first stage. `none` only where the model lists it (a catalog
53
+ * toggle counts); a hard-coded `none` gets every first stage refused.
54
+ * Otherwise the lowest level it lists; `low` when the catalog does not know
55
+ * the model; nothing when it says the model does not reason.
56
+ */
57
+ export function quickestEffort(
58
+ info: { reasoningEfforts?: readonly string[]; reasoning?: boolean } | null | undefined,
59
+ ): ExplicitEffort | undefined {
60
+ if (info?.reasoning === false) return undefined;
61
+ return LEAST_FIRST.find((level) => info?.reasoningEfforts?.includes(level) === true) ?? "low";
62
+ }
63
+
64
+ /** Only assistant messages carry a stamp: they are what a level produced. */
65
+ export function stampEffort(message: ModelMessage, effort: ExplicitEffort | undefined): ModelMessage {
66
+ if (effort === undefined || message.role !== "assistant") return message;
67
+ return {
68
+ ...message,
69
+ providerOptions: { ...message.providerOptions, [TURN_OPTIONS_KEY]: { effort } },
70
+ };
71
+ }
72
+
73
+ export function effortOf(message: { providerOptions?: unknown }): ExplicitEffort | undefined {
74
+ const options = message.providerOptions as Record<string, Record<string, unknown> | undefined> | undefined;
75
+ return explicitEffort(options?.[TURN_OPTIONS_KEY]?.["effort"]);
76
+ }
77
+
78
+ export interface TurnEffortPlan {
79
+ prompt: Prompt;
80
+ /** The request-level effort, fixed for the session: its first explicit level. */
81
+ base: ExplicitEffort | undefined;
82
+ }
83
+
84
+ /**
85
+ * The effort changes of a conversation, placed before the user turns they
86
+ * apply to. Returns `undefined` when the per-turn form cannot express them,
87
+ * and the whole request then goes by request-level effort.
88
+ *
89
+ * A pure function of the history, so the prefix is identical on every request
90
+ * and after a resume: a change is rendered from the stamps of the turns before
91
+ * it. Two shapes fall back: a return to the default after an explicit level
92
+ * (no per-turn value means "the model's default"), and `none`. A fallback
93
+ * lasts for the rest of the session, since it stays in the history.
94
+ */
95
+ export function planTurnEfforts(
96
+ prompt: Prompt,
97
+ current: ExplicitEffort | undefined,
98
+ render: (level: ExplicitEffort) => PromptMessage,
99
+ ): TurnEffortPlan | undefined {
100
+ const starts: number[] = [];
101
+ const levels: (ExplicitEffort | undefined)[] = [];
102
+ const settled: boolean[] = [];
103
+
104
+ prompt.forEach((message, index) => {
105
+ if (message.role === "user") {
106
+ starts.push(index);
107
+ levels.push(undefined);
108
+ settled.push(false);
109
+ return;
110
+ }
111
+ const turn = starts.length - 1;
112
+ if (message.role === "assistant" && turn >= 0 && settled[turn] !== true) {
113
+ levels[turn] = effortOf(message);
114
+ settled[turn] = true;
115
+ }
116
+ });
117
+
118
+ // The turn being answered runs at the level asked for now. A turn in the
119
+ // middle that never got an answer (a cancelled one) changes nothing.
120
+ for (let turn = 0; turn < levels.length; turn += 1) {
121
+ if (settled[turn] === true) continue;
122
+ levels[turn] = turn === levels.length - 1 ? current : levels[turn - 1];
123
+ }
124
+
125
+ let first: number | undefined;
126
+ for (let turn = 0; turn < levels.length; turn += 1) {
127
+ const level = levels[turn];
128
+ if (level === undefined) {
129
+ if (first !== undefined) return undefined;
130
+ continue;
131
+ }
132
+ if (!PER_TURN.has(level)) return undefined;
133
+ first ??= turn;
134
+ }
135
+
136
+ if (first === undefined) return { prompt, base: undefined };
137
+
138
+ const base = levels[first];
139
+ const changes = new Map<number, ExplicitEffort>();
140
+ for (let turn = first + 1; turn < levels.length; turn += 1) {
141
+ const level = levels[turn];
142
+ const start = starts[turn];
143
+ if (level !== undefined && start !== undefined && level !== levels[turn - 1]) {
144
+ changes.set(start, level);
145
+ }
146
+ }
147
+
148
+ const rendered: PromptMessage[] = [];
149
+ prompt.forEach((message, index) => {
150
+ const change = changes.get(index);
151
+ if (change !== undefined) rendered.push(render(change));
152
+ rendered.push(message);
153
+ });
154
+
155
+ return { prompt: rendered, base };
156
+ }
@@ -0,0 +1,83 @@
1
+ import type { LanguageModel } from "ai";
2
+ import type { AppIdentity } from "../app";
3
+ import type { ModelProfile, ProviderConfig, ReasoningEffort } from "../config/schema";
4
+ import type { CacheOptions, CacheSupport, RequestFields } from "./cache";
5
+ import type { OAuthCredential } from "./oauth";
6
+
7
+ /**
8
+ * AI SDK 7 accepts either a model object or a bare id string. Factories always
9
+ * build the object, and narrowing here keeps `modelId` available to callers.
10
+ */
11
+ export type AgentLanguageModel = Exclude<LanguageModel, string>;
12
+
13
+ /**
14
+ * A provider factory turns one config entry into something that can hand out
15
+ * language models. Registering a new vendor means adding a factory — nothing
16
+ * above this file changes.
17
+ */
18
+
19
+ export interface ProviderFactoryContext {
20
+ /** Provider name as written in config, e.g. "openrouter". */
21
+ name: string;
22
+ /** Key already resolved from `apiKey` or `apiKeyEnv`; empty when unset. */
23
+ apiKey: string;
24
+ config: ProviderConfig;
25
+ /**
26
+ * For a provider that signs in: a valid credential on every call, refreshed
27
+ * under the host's lock when due. Absent when the host keeps no sign-ins.
28
+ */
29
+ credential?: () => Promise<OAuthCredential>;
30
+ /** Whose name to send where a vendor asks who is calling. */
31
+ app?: AppIdentity;
32
+ }
33
+
34
+ export interface ProviderInstance {
35
+ /**
36
+ * Knows no session: a routing key on the model object would tie the object
37
+ * to one conversation, so it travels with each request instead.
38
+ */
39
+ languageModel(modelId: string): AgentLanguageModel;
40
+ /** Endpoint used to list available models, when the vendor exposes one. */
41
+ readonly modelsEndpoint?: string;
42
+ /** What this vendor can do about caching. Diagnostics, never gating. */
43
+ readonly cacheSupport?: CacheSupport;
44
+ /**
45
+ * One request's cache fields in this vendor's dialect. Optional: a factory
46
+ * that knows nothing about caching still compiles and works.
47
+ */
48
+ requestFields?(cache: CacheOptions): RequestFields;
49
+ /**
50
+ * False when the adapter sends a tool result as text only: Chat Completions
51
+ * allows nothing else in a `tool` message, and the SDK would put an image's
52
+ * base64 there as text. Check the adapter before leaving it out.
53
+ */
54
+ readonly imagesInToolResults?: boolean;
55
+ }
56
+
57
+ export type ProviderFactory = (context: ProviderFactoryContext) => ProviderInstance;
58
+
59
+ /**
60
+ * Factories are reached through a loader so a vendor SDK is imported only when
61
+ * its provider is used, keeping unused SDKs out of the binary and out of
62
+ * startup. This is why resolving a model is asynchronous.
63
+ */
64
+ export type ProviderFactoryLoader = () => Promise<ProviderFactory>;
65
+
66
+ /** What a profile sets on every call to its model. */
67
+ export interface ModelCallSettings {
68
+ reasoning?: ReasoningEffort;
69
+ temperature?: number;
70
+ topP?: number;
71
+ maxOutputTokens?: number;
72
+ providerOptions?: Record<string, Record<string, unknown>>;
73
+ }
74
+
75
+ export function settingsFromProfile(profile: ModelProfile): ModelCallSettings {
76
+ const settings: ModelCallSettings = {};
77
+ if (profile.reasoning !== undefined) settings.reasoning = profile.reasoning;
78
+ if (profile.temperature !== undefined) settings.temperature = profile.temperature;
79
+ if (profile.topP !== undefined) settings.topP = profile.topP;
80
+ if (profile.maxOutputTokens !== undefined) settings.maxOutputTokens = profile.maxOutputTokens;
81
+ if (profile.providerOptions !== undefined) settings.providerOptions = profile.providerOptions;
82
+ return settings;
83
+ }
@@ -0,0 +1,44 @@
1
+ import { AgentError } from "../errors";
2
+ import type { SessionRecord } from "./format";
3
+
4
+ /** A session's opening and closing record: all a listing or the next append needs. */
5
+ export interface SessionEnds {
6
+ first: SessionRecord;
7
+ last: SessionRecord;
8
+ }
9
+
10
+ /**
11
+ * A place to keep sessions: it holds records in the order given and hands them
12
+ * back unchanged. It never reads what a record says. Numbering, dating,
13
+ * checkpoints and the projection belong to `createSessionStore`.
14
+ */
15
+ export interface SessionBackend {
16
+ /** A new session with its opening records. Throws `session/exists` when the id is taken. */
17
+ create(id: string, records: readonly SessionRecord[]): Promise<void>;
18
+ /**
19
+ * All of `records` after everything already kept, or none of them. Throws
20
+ * `session/not-found` for an unknown id, and may throw
21
+ * `session/concurrent-write` when someone else wrote since its last look.
22
+ */
23
+ append(id: string, records: readonly SessionRecord[]): Promise<void>;
24
+ /** Every record in the order it was written, or null for an unknown id. */
25
+ read(id: string): Promise<SessionRecord[] | null>;
26
+ ends(id: string): Promise<SessionEnds | null>;
27
+ /**
28
+ * The ends of every session. `limit` is a hint: a backend may return only
29
+ * the sessions written to most recently, or ignore it.
30
+ */
31
+ list(limit?: number): Promise<SessionEnds[]>;
32
+ /** True when there was something to remove. */
33
+ delete(id: string): Promise<boolean>;
34
+ }
35
+
36
+ export function sessionExists(id: string): AgentError {
37
+ return new AgentError("session/exists", `A session with id "${id}" already exists.`, {
38
+ details: { id },
39
+ });
40
+ }
41
+
42
+ export function sessionNotFound(id: string): AgentError {
43
+ return new AgentError("session/not-found", `No session with id "${id}".`, { details: { id } });
44
+ }
@@ -0,0 +1,278 @@
1
+ import { open, mkdir, readdir, readFile, rm, stat, truncate } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { AgentError } from "../errors";
4
+ import { type SessionBackend, type SessionEnds, sessionExists, sessionNotFound } from "./backend";
5
+ import { type SessionRecord, decodeLog, parseRecord } from "./format";
6
+ import { type SessionStore, createSessionStore } from "./store";
7
+
8
+ /**
9
+ * Sessions as append-only JSONL, one file per session. Only this module outside
10
+ * `tools/` and `config/` may use `node:fs`; portable code must not import it.
11
+ *
12
+ * `append` throws `session/concurrent-write` when the file grew behind this
13
+ * process's back. No lock: a second writer is detected, not prevented.
14
+ */
15
+
16
+ export interface FileSessionBackendOptions {
17
+ /** Directory holding this project's session files; created on first write. */
18
+ dir: string;
19
+ }
20
+
21
+ export interface FileSessionStoreOptions extends FileSessionBackendOptions {
22
+ newId?: () => string;
23
+ now?: () => number;
24
+ }
25
+
26
+ const SUFFIX = ".jsonl";
27
+
28
+ /** Enough to hold the closing checkpoint of any sane append. */
29
+ const TAIL_WINDOW = 64 * 1024;
30
+
31
+ function isMissing(error: unknown): boolean {
32
+ return (error as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
33
+ }
34
+
35
+ /** Ids become file names, so anything that could climb the tree is refused. */
36
+ function assertSafeId(id: string): void {
37
+ if (id === "" || /[\\/]/.test(id) || id === "." || id === "..") {
38
+ throw new AgentError("session/not-found", `"${id}" is not a usable session id.`, {
39
+ details: { id },
40
+ });
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Where a session keeps files beside its log, such as saved tool results. A
46
+ * host and `delete` both use this path, so they cannot disagree about it.
47
+ */
48
+ export function sessionSideDir(dir: string, id: string): string {
49
+ assertSafeId(id);
50
+ return join(dir, id);
51
+ }
52
+
53
+ interface TailScan {
54
+ size: number;
55
+ /** Byte offset just past the last complete line. */
56
+ completeBytes: number;
57
+ lastRecord: SessionRecord | null;
58
+ }
59
+
60
+ /**
61
+ * Reads the end of the log instead of all of it. A listing calls this once per
62
+ * session, so it does not parse whole logs.
63
+ */
64
+ async function scanTail(path: string): Promise<TailScan | null> {
65
+ let handle;
66
+ try {
67
+ handle = await open(path, "r");
68
+ } catch (error) {
69
+ if (isMissing(error)) return null;
70
+ throw error;
71
+ }
72
+
73
+ try {
74
+ const { size } = await handle.stat();
75
+ const start = Math.max(0, size - TAIL_WINDOW);
76
+ const buffer = Buffer.alloc(size - start);
77
+ if (buffer.length > 0) await handle.read(buffer, 0, buffer.length, start);
78
+
79
+ // A window that does not start at the file start opens mid-record; the
80
+ // first newline is where usable data begins.
81
+ const text = buffer.toString("utf8");
82
+ const usable = start === 0 ? text : text.slice(text.indexOf("\n") + 1);
83
+ const usableStart = size - Buffer.byteLength(usable, "utf8");
84
+
85
+ let completeBytes = usableStart;
86
+ let lastRecord: SessionRecord | null = null;
87
+
88
+ for (const line of usable.split("\n")) {
89
+ const lineBytes = Buffer.byteLength(line, "utf8");
90
+ const terminated = completeBytes + lineBytes < size;
91
+ if (!terminated) break;
92
+ completeBytes += lineBytes + 1;
93
+
94
+ if (line.trim() === "") continue;
95
+ lastRecord = parseRecord(JSON.parse(line), "in the log tail");
96
+ }
97
+
98
+ return { size, completeBytes, lastRecord };
99
+ } finally {
100
+ await handle.close();
101
+ }
102
+ }
103
+
104
+ /** The header from the front of the file, the last complete record from the back. */
105
+ async function readEnds(path: string): Promise<SessionEnds | null> {
106
+ const tail = await scanTail(path);
107
+ // No complete line at all: a file cut off inside its header holds no session.
108
+ if (tail === null || tail.lastRecord === null) return null;
109
+
110
+ const handle = await open(path, "r");
111
+ let head: string;
112
+ try {
113
+ const buffer = Buffer.alloc(Math.min(tail.size, TAIL_WINDOW));
114
+ if (buffer.length > 0) await handle.read(buffer, 0, buffer.length, 0);
115
+ head = buffer.toString("utf8");
116
+ } finally {
117
+ await handle.close();
118
+ }
119
+
120
+ const firstLine = head.split("\n")[0] ?? "";
121
+ if (firstLine.trim() === "") return null;
122
+ return { first: parseRecord(JSON.parse(firstLine), "in the log header"), last: tail.lastRecord };
123
+ }
124
+
125
+ export function createFileSessionBackend(options: FileSessionBackendOptions): SessionBackend {
126
+ // File size as of the last write this process made or the scan before its first.
127
+ const sizes = new Map<string, number>();
128
+
129
+ const pathFor = (id: string): string => {
130
+ assertSafeId(id);
131
+ return join(options.dir, `${id}${SUFFIX}`);
132
+ };
133
+
134
+ /**
135
+ * Truncates a partial last line, which a killed append leaves, before any
136
+ * write: appending after it would bury the damage mid-log, where nothing
137
+ * tolerates it.
138
+ */
139
+ const sizeFor = async (id: string): Promise<number> => {
140
+ const cached = sizes.get(id);
141
+ if (cached !== undefined) return cached;
142
+
143
+ const path = pathFor(id);
144
+ const tail = await scanTail(path);
145
+ if (tail === null || tail.lastRecord === null) throw sessionNotFound(id);
146
+ if (tail.completeBytes < tail.size) await truncate(path, tail.completeBytes);
147
+
148
+ // After the repair above, the complete prefix is the whole file.
149
+ sizes.set(id, tail.completeBytes);
150
+ return tail.completeBytes;
151
+ };
152
+
153
+ /** Returns the bytes written, so the next append can tell our own growth apart. */
154
+ const write = async (
155
+ path: string,
156
+ records: readonly SessionRecord[],
157
+ create: boolean,
158
+ ): Promise<number> => {
159
+ const payload = `${records.map((record) => JSON.stringify(record)).join("\n")}\n`;
160
+ const handle = await open(path, create ? "wx" : "a");
161
+ try {
162
+ await handle.write(payload);
163
+ return Buffer.byteLength(payload, "utf8");
164
+ } finally {
165
+ await handle.close();
166
+ }
167
+ };
168
+
169
+ /**
170
+ * Throws `session/concurrent-write` when the file is not the size it had
171
+ * after this process's last write or scan.
172
+ */
173
+ const assertSoleWriter = async (id: string, expected: number): Promise<void> => {
174
+ let size: number;
175
+ try {
176
+ size = (await stat(pathFor(id))).size;
177
+ } catch (error) {
178
+ if (isMissing(error)) return;
179
+ throw error;
180
+ }
181
+ if (size === expected) return;
182
+
183
+ sizes.delete(id);
184
+ throw new AgentError(
185
+ "session/concurrent-write",
186
+ `Session "${id}" was written by another process. Appending now would interleave two conversations; re-read the session and retry.`,
187
+ { details: { id, expectedBytes: expected, actualBytes: size } },
188
+ );
189
+ };
190
+
191
+ return {
192
+ async create(id: string, records: readonly SessionRecord[]): Promise<void> {
193
+ await mkdir(options.dir, { recursive: true });
194
+ try {
195
+ sizes.set(id, await write(pathFor(id), records, true));
196
+ } catch (error) {
197
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") throw sessionExists(id);
198
+ throw error;
199
+ }
200
+ },
201
+
202
+ async append(id: string, records: readonly SessionRecord[]): Promise<void> {
203
+ const expected = await sizeFor(id);
204
+ await assertSoleWriter(id, expected);
205
+ sizes.set(id, expected + (await write(pathFor(id), records, false)));
206
+ },
207
+
208
+ async read(id: string): Promise<SessionRecord[] | null> {
209
+ let text: string;
210
+ try {
211
+ text = await readFile(pathFor(id), "utf8");
212
+ } catch (error) {
213
+ if (isMissing(error)) return null;
214
+ throw error;
215
+ }
216
+ return decodeLog(text).records;
217
+ },
218
+
219
+ async ends(id: string): Promise<SessionEnds | null> {
220
+ return readEnds(pathFor(id));
221
+ },
222
+
223
+ async list(): Promise<SessionEnds[]> {
224
+ let names: string[];
225
+ try {
226
+ names = await readdir(options.dir);
227
+ } catch (error) {
228
+ if (isMissing(error)) return [];
229
+ throw error;
230
+ }
231
+
232
+ const all: SessionEnds[] = [];
233
+ for (const name of names) {
234
+ if (!name.endsWith(SUFFIX)) continue;
235
+ const ends = await readEnds(pathFor(name.slice(0, -SUFFIX.length)));
236
+ if (ends !== null) all.push(ends);
237
+ }
238
+ return all;
239
+ },
240
+
241
+ async delete(id: string): Promise<boolean> {
242
+ try {
243
+ await rm(pathFor(id));
244
+ sizes.delete(id);
245
+ // What the log points at goes with it; left behind, nothing would ever find it.
246
+ await rm(sessionSideDir(options.dir, id), { recursive: true, force: true });
247
+ return true;
248
+ } catch (error) {
249
+ if (isMissing(error)) return false;
250
+ throw error;
251
+ }
252
+ },
253
+ };
254
+ }
255
+
256
+ /**
257
+ * Where the agents a session started keep their own logs: a folder beside its
258
+ * log. Listing a store reads only the top of its directory, so they never
259
+ * appear among sessions, and deleting the session takes them along.
260
+ */
261
+ export function subagentSessionStore(
262
+ options: FileSessionStoreOptions & { parentId: string },
263
+ ): SessionStore {
264
+ const { parentId, ...rest } = options;
265
+ return createFileSessionStore({ ...rest, dir: join(sessionSideDir(options.dir, parentId), "subagents") });
266
+ }
267
+
268
+ /**
269
+ * A file is created with a session's first message, not by `create()`, so a
270
+ * chat left without a word leaves no empty log for `--continue` to pick.
271
+ */
272
+ export function createFileSessionStore(options: FileSessionStoreOptions): SessionStore {
273
+ return createSessionStore(createFileSessionBackend({ dir: options.dir }), {
274
+ ...(options.newId === undefined ? {} : { newId: options.newId }),
275
+ ...(options.now === undefined ? {} : { now: options.now }),
276
+ deferUntilFirstMessage: true,
277
+ });
278
+ }