@wraith-ai/agents 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.
package/README.md CHANGED
@@ -31,6 +31,6 @@ await agent.close();
31
31
  `grep` needs [ripgrep](https://github.com/BurntSushi/ripgrep) on `PATH`.
32
32
 
33
33
  What each option does, and what is read from disk when:
34
- [USING-WRAITH.md](https://github.com/xFroty/wraith/blob/main/USING-WRAITH.md#a-coding-agent-in-one-call).
34
+ the [using-wraith skill](https://github.com/xFroty/wraith/blob/main/wraith-skills/using-wraith/SKILL.md#a-coding-agent-in-one-call).
35
35
 
36
36
  MIT
package/dist/index.d.mts CHANGED
@@ -51,9 +51,15 @@ interface CodingAgentOptions {
51
51
  overrides?: ConfigInput | undefined;
52
52
  /** Sources beside the built-in tools. `tools.deny` takes a built-in one away. */
53
53
  tools?: readonly ToolSource[] | undefined;
54
- /** A directory to keep sessions in, or a store. Absent: in memory, gone at `close()`. */
54
+ /**
55
+ * A directory to keep sessions in, or a store. Absent: nothing is written;
56
+ * the conversation holds its session, which is gone at `close()`.
57
+ */
55
58
  sessions?: string | SessionStore | undefined;
56
- /** A session to carry on, by id. One the store does not have fails with `session/not-found`. */
59
+ /**
60
+ * A session to carry on, by id, from `sessions`. Without `sessions` it fails
61
+ * with `config/invalid`; one the store does not have, with `session/not-found`.
62
+ */
57
63
  session?: string | undefined;
58
64
  /** The agent's role. The environment and the permission guidance are always added. */
59
65
  system?: string | undefined;
@@ -90,4 +96,5 @@ interface CodingAgent {
90
96
  close(): Promise<void>;
91
97
  }
92
98
  export declare function createCodingAgent(options: CodingAgentOptions): Promise<CodingAgent>;
93
- export type { CodingAgent, CodingAgentOptions, ProjectConfig, SkippedSetting };
99
+ export type { CodingAgent, CodingAgentOptions, ProjectConfig, SkippedSetting };
100
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/coding-agent.ts"],"mappings":";;;;;;;;;;;qBA2Ea;;;;;;;;;;KAWD,gBACR,gCAEE,SAAS,gCAAgC;UAE9B;;EAEf;;;;;;;EAOA,QAAQ;;;;;;EAMR,OAAO;;;;;EAKP,UAAU;;;;;;EAMV,SAAS;;EAET,YAAY;;EAEZ,iBAAiB;;;;;EAKjB,oBAAoB;;;;;EAKpB;;EAEA;;EAEA,MAAM,SAAS;;;UAIA;EACf;EACA;EACA;;UAGe;;EAEf,cAAc;EACd,OAAO;;EAEP,MAAM;EACN,OAAO;EACP,WAAW;;EAEX,MAAM;;EAEN,WAAW;;;;;;EAMX,eAAe;;EAEf,SAAS;;EAET,SAAS;;wBAqBW,kBAAkB,SAAS,qBAAqB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { mkdir, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
- import { APP_NAME, AgentError, INHERIT_MODEL, SERVICE_KEY_ENV, TOOL_POLICY_GUIDANCE, approvalModes, builtinSubagents, builtinToolSource, catalogTables, chainApproval, composeSystemPrompt, createAgent, createClassifierApproval, createCompactor, createConversation, createFileSessionStore, createInbox, createMcpServers, createMemorySessionStore, createModelsDevCapabilities, createPermissionPolicy, createSubagents, createTaskRegistry, createToolRegistry, defaultCompactionPolicy, environmentBlock, fileCredentialStore, fileMcpAuthStore, inspectProject, loadConfig, loadInstructions, loadSubagents, parseConfig, permissiveCapabilities, readTrust, registryFromConfig, sessionSideDir, subagentSessionStore, toPosix, webToolSource } from "@wraith-ai/core";
4
+ import { APP_NAME, AgentError, INHERIT_MODEL, SERVICE_KEY_ENV, TOOL_POLICY_GUIDANCE, approvalModes, builtinSubagents, builtinToolSource, catalogTables, chainApproval, composeSystemPrompt, createAgent, createClassifierApproval, createCompactor, createConversation, createFileSessionStore, createInbox, createMcpServers, createModelsDevCapabilities, createPermissionPolicy, createSession, createSubagents, createTaskRegistry, createToolRegistry, defaultCompactionPolicy, environmentBlock, fileCredentialStore, fileMcpAuthStore, inspectProject, loadConfig, loadInstructions, loadSubagents, parseConfig, permissiveCapabilities, readTrust, registryFromConfig, sessionSideDir, subagentSessionStore, toPosix, webToolSource } from "@wraith-ai/core";
5
5
  import { capabilitySnapshot } from "@wraith-ai/core/snapshot";
6
6
  // src/coding-agent.ts
7
7
  /**
@@ -181,8 +181,8 @@ async function createCodingAgent(options) {
181
181
  const conversation = createConversation({
182
182
  agent,
183
183
  session,
184
- store,
185
- inbox
184
+ inbox,
185
+ ...store === void 0 ? {} : { store }
186
186
  });
187
187
  return {
188
188
  conversation,
@@ -277,11 +277,19 @@ function capabilitiesFor(config) {
277
277
  ...snapshot === void 0 ? {} : { snapshot }
278
278
  });
279
279
  }
280
+ /**
281
+ * No store without `sessions`: the conversation already holds its session, and
282
+ * a store in memory would keep every record a second time for nobody to read.
283
+ */
280
284
  function sessionStore(sessions) {
281
- if (sessions === void 0) return createMemorySessionStore({ newId: () => `session-${crypto.randomUUID()}` });
285
+ if (sessions === void 0) return void 0;
282
286
  return typeof sessions === "string" ? createFileSessionStore({ dir: sessions }) : sessions;
283
287
  }
284
288
  async function openSession(store, id) {
289
+ if (store === void 0) {
290
+ if (id !== void 0) throw new AgentError("config/invalid", `Session "${id}" cannot be resumed without the sessions option.`, { details: { id } });
291
+ return createSession(`session-${crypto.randomUUID()}`);
292
+ }
285
293
  if (id === void 0) return store.create();
286
294
  const found = await store.get(id);
287
295
  if (found === null) throw new AgentError("session/not-found", `No session with id "${id}" in this store.`, { details: { id } });
@@ -312,3 +320,5 @@ async function subagentKinds(read) {
312
320
  };
313
321
  }
314
322
  export { CODING_AGENT_MAX_STEPS, createCodingAgent };
323
+
324
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/coding-agent.ts"],"mappings":";;;;;;;;;;;;AA2EA,MAAa,yBAAyB;AA8FtC,MAAM,eACJ;;AAIF,MAAM,WAAwD;CAC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AG,iBAAiB;EAAG,SAAS,CAAC;CAAE;CACrF,MAAM,EAAE,UAAU,KAAK;CAEvB,MAAM,OAAO,CAAC,MAAM,eAAe,GAAI,MAAM,qBAAqB,KAAA,IAAY,CAAC,IAAI,CAAC,MAAM,gBAAgB,CAAE;CAC5G,MAAM,EAAE,QAAQ,YAAY,MAAM,cAAc,IAAI;CACpD,OAAO;EACL,QAAQ;GAAE,GAAG;GAAkB,GAAG;EAAO;EACzC,SAAS,QAAQ,KAAK,UAAU;GAAE,SAAS;GAAS,QAAQ,KAAK;GAAM,QAAQ,KAAK;EAAO,EAAE;CAC/F;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wraith-ai/agents",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Ready-made agents built on @wraith-ai/core, starting with createCodingAgent.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -18,12 +18,13 @@
18
18
  }
19
19
  },
20
20
  "files": [
21
- "dist"
21
+ "dist",
22
+ "src"
22
23
  ],
23
24
  "engines": {
24
25
  "node": ">=22"
25
26
  },
26
27
  "dependencies": {
27
- "@wraith-ai/core": "0.1.0"
28
+ "@wraith-ai/core": "0.1.1"
28
29
  }
29
30
  }
@@ -0,0 +1,518 @@
1
+ import { mkdir, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import {
5
+ AgentError,
6
+ APP_NAME,
7
+ INHERIT_MODEL,
8
+ SERVICE_KEY_ENV,
9
+ TOOL_POLICY_GUIDANCE,
10
+ approvalModes,
11
+ builtinSubagents,
12
+ builtinToolSource,
13
+ catalogTables,
14
+ chainApproval,
15
+ composeSystemPrompt,
16
+ createAgent,
17
+ createClassifierApproval,
18
+ createCompactor,
19
+ createConversation,
20
+ createFileSessionStore,
21
+ createInbox,
22
+ createMcpServers,
23
+ createModelsDevCapabilities,
24
+ createPermissionPolicy,
25
+ createSession,
26
+ createSubagents,
27
+ createTaskRegistry,
28
+ createToolRegistry,
29
+ defaultCompactionPolicy,
30
+ environmentBlock,
31
+ fileCredentialStore,
32
+ fileMcpAuthStore,
33
+ inspectProject,
34
+ loadConfig,
35
+ loadInstructions,
36
+ loadSubagents,
37
+ parseConfig,
38
+ permissiveCapabilities,
39
+ readTrust,
40
+ registryFromConfig,
41
+ sessionSideDir,
42
+ subagentSessionStore,
43
+ toPosix,
44
+ webToolSource,
45
+ type AppPaths,
46
+ type ApprovalHandler,
47
+ type ApprovalMode,
48
+ type Config,
49
+ type ConfigInput,
50
+ type ConfiguredRegistry,
51
+ type Conversation,
52
+ type ExtraRoot,
53
+ type Instructions,
54
+ type LoadedConfig,
55
+ type McpServers,
56
+ type Model,
57
+ type ModelCapabilities,
58
+ type ProjectInspection,
59
+ type ProjectTrust,
60
+ type Session,
61
+ type SessionStore,
62
+ type SubagentType,
63
+ type Subagents,
64
+ type ToolRegistry,
65
+ type ToolSource,
66
+ } from "@wraith-ai/core";
67
+ import { capabilitySnapshot } from "@wraith-ai/core/snapshot";
68
+
69
+ /**
70
+ * An agent that works on code in one directory, from the blocks `wraith`
71
+ * itself is built from: the file and shell tools, the web tools, background
72
+ * tasks, agents it can start, MCP servers and compaction.
73
+ */
74
+
75
+ /** Higher than `createAgent`'s: a coding task takes more steps than an answer. */
76
+ export const CODING_AGENT_MAX_STEPS = 200;
77
+
78
+ /**
79
+ * Whether the project's own `.wraith/` files, `.env` settings and AGENTS.md
80
+ * files may configure the agent. The user's own config and AGENTS.md are read
81
+ * in every case but `undefined`.
82
+ *
83
+ * - `"trusted"`, `"untrusted"`: decided by the host.
84
+ * - `"remembered"`: what `wraith trust` stored for this repository; nothing stored is untrusted.
85
+ * - a function: asked with what the project brings, only when it brings something.
86
+ */
87
+ export type ProjectConfig =
88
+ | ProjectTrust
89
+ | "remembered"
90
+ | ((project: ProjectInspection) => boolean | Promise<boolean>);
91
+
92
+ export interface CodingAgentOptions {
93
+ /** The workspace. The file tools act inside it, and the shell starts there. */
94
+ cwd: string;
95
+ /**
96
+ * A model, or a name to look up: a profile or `"provider:model"`. Absent:
97
+ * the config's `defaultModel`. With none anywhere, creation fails with
98
+ * `model/not-configured`. A resumed session runs on this one too, not on the
99
+ * model it was started with.
100
+ */
101
+ model?: Model | string | undefined;
102
+ /**
103
+ * `"ask"`: what the policy does not allow goes to `approve`. `"auto"`: a model
104
+ * answers first, and passes what it is unsure of to `approve`. `"yolo"`: no
105
+ * questions; `deny` rules still hold. Absent: what the config says, else ask.
106
+ */
107
+ mode?: ApprovalMode | undefined;
108
+ /**
109
+ * Answers what the policy and the classifier left open. Absent: nobody is
110
+ * asked, and the call goes back to the model refused, saying so.
111
+ */
112
+ approve?: ApprovalHandler | undefined;
113
+ /**
114
+ * Absent: no file and no `WRAITH_*` variable is read; the config is the
115
+ * defaults with `overrides` on top. Given: the user's files and variables
116
+ * are read, and the project's as this says.
117
+ */
118
+ config?: ProjectConfig | undefined;
119
+ /** Anything a config file can set, over every other layer. */
120
+ overrides?: ConfigInput | undefined;
121
+ /** Sources beside the built-in tools. `tools.deny` takes a built-in one away. */
122
+ tools?: readonly ToolSource[] | undefined;
123
+ /**
124
+ * A directory to keep sessions in, or a store. Absent: nothing is written;
125
+ * the conversation holds its session, which is gone at `close()`.
126
+ */
127
+ sessions?: string | SessionStore | undefined;
128
+ /**
129
+ * A session to carry on, by id, from `sessions`. Without `sessions` it fails
130
+ * with `config/invalid`; one the store does not have, with `session/not-found`.
131
+ */
132
+ session?: string | undefined;
133
+ /** The agent's role. The environment and the permission guidance are always added. */
134
+ system?: string | undefined;
135
+ /** Where provider keys and MCP servers' variables come from. Absent: `process.env`. */
136
+ env?: Readonly<Record<string, string | undefined>> | undefined;
137
+ }
138
+
139
+ /** A setting that was written and not used, and why. */
140
+ export interface SkippedSetting {
141
+ setting: string;
142
+ source: string;
143
+ reason: string;
144
+ }
145
+
146
+ export interface CodingAgent {
147
+ /** Send prompts here, and subscribe to what happens. */
148
+ conversation: Conversation;
149
+ model: Model;
150
+ /** The mode it runs in, after the config had its say. */
151
+ mode: ApprovalMode;
152
+ tools: ToolRegistry;
153
+ subagents: Subagents;
154
+ /** Present when the config names MCP servers. */
155
+ mcp?: McpServers;
156
+ /** The config's providers: what a name in `model` was looked up in. */
157
+ providers: ConfiguredRegistry;
158
+ /**
159
+ * The AGENTS.md files the model is given: the user's, and a trusted
160
+ * project's from its root down to `cwd`. Absent when there were none, or
161
+ * when `config` was not given and no file was read at all.
162
+ */
163
+ instructions?: Instructions;
164
+ /** What the config said and this agent does not do. */
165
+ skipped: SkippedSetting[];
166
+ /** Stops the turn, the tasks, the agents and the servers, and removes the session's temp files. */
167
+ close(): Promise<void>;
168
+ }
169
+
170
+ const DEFAULT_ROLE =
171
+ "You are a coding agent working in the user's workspace. Read the code before you change it, " +
172
+ "make the change the task asks for, check it where you can, and say plainly what you did and what is left.";
173
+
174
+ /** Settings of `wraith` the preset has nothing for, with the reason it gives. */
175
+ const NOT_USED: Record<string, (config: Config) => unknown> = {
176
+ "session.store": (config) => config.session.store,
177
+ "session.dir": (config) => config.session.dir,
178
+ "session.autoTitle": (config) => config.session.autoTitle,
179
+ "session.titleModel": (config) => config.session.titleModel,
180
+ logLevel: (config) => config.logLevel,
181
+ };
182
+
183
+ const NOT_USED_REASON: Record<string, string> = {
184
+ "session.store": "sessions come from the sessions option",
185
+ "session.dir": "sessions come from the sessions option",
186
+ };
187
+
188
+ export async function createCodingAgent(options: CodingAgentOptions): Promise<CodingAgent> {
189
+ const { cwd } = options;
190
+ const env = options.env ?? process.env;
191
+ const read = await readConfig(options, env);
192
+ const { config, paths } = read;
193
+ const skipped = [...read.skipped, ...notUsed(config)];
194
+ const instructions = read.loaded === undefined ? undefined : await loadInstructions(read.loaded, { cwd });
195
+ for (const file of instructions?.files ?? []) {
196
+ if (!file.truncated) continue;
197
+ skipped.push({
198
+ setting: "instructions.maxBytes",
199
+ source: file.path,
200
+ reason: `the file was cut: the instruction files together may hold ${String(config.instructions.maxBytes)} bytes`,
201
+ });
202
+ }
203
+
204
+ const capabilities = capabilitiesFor(config);
205
+ const providers = registryFromConfig(config, {
206
+ env: (variable) => env[variable],
207
+ capabilities,
208
+ credentials: fileCredentialStore(paths.userOAuthDir),
209
+ });
210
+
211
+ // Resolved before anything is started: a missing model leaves nothing to close.
212
+ const model =
213
+ typeof options.model === "object" ? options.model : await providers.resolve(options.model);
214
+ const auxiliary = (ref: string): Promise<Model> =>
215
+ ref === INHERIT_MODEL ? Promise.resolve(model) : providers.resolve(ref);
216
+
217
+ const store = sessionStore(options.sessions);
218
+ const session = await openSession(store, options.session);
219
+
220
+ const mode = options.mode ?? approvalModes(config, { yolo: false, auto: false, switchable: false }).initial;
221
+ const classifier = config.permissions.classifier;
222
+ const approval =
223
+ mode === "auto"
224
+ ? chainApproval(
225
+ createClassifierApproval({
226
+ model: await auxiliary(classifier.model),
227
+ cacheKey: `classifier:${session.id}`,
228
+ decides: classifier.decides,
229
+ onUnsure: classifier.onUnsure,
230
+ escalateAfter: classifier.escalateAfter,
231
+ ...(classifier.environment.trim() === "" ? {} : { environment: classifier.environment }),
232
+ blockRules: classifier.blockRules,
233
+ allowExceptions: classifier.allowExceptions,
234
+ }),
235
+ options.approve,
236
+ )
237
+ : options.approve;
238
+
239
+ const compactionModel =
240
+ config.compaction.enabled && model.contextLimit !== undefined
241
+ ? await auxiliary(config.compaction.model)
242
+ : undefined;
243
+
244
+ // Per session, not per agent: a resumed session sends the system prompt it
245
+ // was started with, and that names these directories.
246
+ const temp = sessionSideDir(join(tmpdir(), APP_NAME, "agents"), session.id);
247
+ await mkdir(temp, { recursive: true });
248
+ const scratchpad = join(temp, "scratchpad");
249
+ const tasksDir = join(temp, "tasks");
250
+ const resultsDir =
251
+ typeof options.sessions === "string"
252
+ ? join(sessionSideDir(options.sessions, session.id), "tool-results")
253
+ : undefined;
254
+ const roots: ExtraRoot[] = [
255
+ { path: scratchpad, access: "write" },
256
+ { path: tasksDir, access: "read" },
257
+ ...(resultsDir === undefined ? [] : [{ path: resultsDir, access: "read" as const }]),
258
+ ];
259
+ const sessionLines = [
260
+ `Scratch directory: ${toPosix(scratchpad)}`,
261
+ "Put temporary files there — clones, downloads, throwaway scripts — not in the project.",
262
+ `Background task logs: ${toPosix(tasksDir)}`,
263
+ "Read them with read_file or grep, without asking. A log stays after its task ends.",
264
+ ];
265
+ const environment = (of: Model): Promise<string> =>
266
+ environmentBlock({ cwd, paths, model: of.modelId, session: sessionLines });
267
+
268
+ const opened: { close(): unknown }[] = [];
269
+ try {
270
+ const inbox = createInbox();
271
+ const tasks = createTaskRegistry({ dir: tasksDir, inbox });
272
+ opened.push(tasks);
273
+
274
+ const kinds = await subagentKinds(read);
275
+ skipped.push(...kinds.skipped);
276
+ const maxSteps = config.limits.maxSteps ?? CODING_AGENT_MAX_STEPS;
277
+ const subagents = createSubagents({
278
+ agents: kinds.agents,
279
+ model,
280
+ models: providers,
281
+ ...(typeof options.sessions === "string"
282
+ ? { store: subagentSessionStore({ dir: options.sessions, parentId: session.id }) }
283
+ : {}),
284
+ // Given, not left out: absent, they would get `createAgent`'s limit.
285
+ maxSteps,
286
+ compaction: config.compaction.enabled ? { model: config.compaction.model } : false,
287
+ environment,
288
+ instructions: () => instructions?.text,
289
+ });
290
+ opened.push(subagents);
291
+
292
+ const mcp =
293
+ Object.keys(config.mcpServers).length === 0
294
+ ? undefined
295
+ : createMcpServers(config.mcpServers, {
296
+ cwd,
297
+ env,
298
+ jobDir: paths.cacheDir,
299
+ auth: fileMcpAuthStore(join(paths.userOAuthDir, "mcp")),
300
+ });
301
+ if (mcp !== undefined) opened.push(mcp);
302
+
303
+ const searchKey = env[SERVICE_KEY_ENV.exa] ?? read.serviceKeys.exa;
304
+ const tools = await createToolRegistry({
305
+ sources: [
306
+ builtinToolSource({
307
+ ...(config.tools.bashPath === undefined ? {} : { bashPath: config.tools.bashPath }),
308
+ cacheDir: paths.cacheDir,
309
+ ripgrep: {
310
+ ...(config.tools.ripgrepPath === undefined ? {} : { configured: config.tools.ripgrepPath }),
311
+ cacheDir: paths.cacheDir,
312
+ },
313
+ }),
314
+ webToolSource(
315
+ !config.web.search.enabled
316
+ ? { search: false }
317
+ : searchKey === undefined || searchKey === ""
318
+ ? {}
319
+ : { exaApiKey: searchKey },
320
+ ),
321
+ subagents.toolSource(),
322
+ ...(mcp === undefined ? [] : [mcp.toolSource()]),
323
+ ...(options.tools ?? []),
324
+ ],
325
+ cwd,
326
+ roots,
327
+ ...(resultsDir === undefined ? {} : { resultsDir }),
328
+ policy: createPermissionPolicy(
329
+ {
330
+ ...config.permissions,
331
+ // A `deny` written down stays one in every mode; so does a deny rule.
332
+ mode: mode === "yolo" ? "yolo" : config.permissions.mode === "deny" ? "deny" : "ask",
333
+ },
334
+ { cwd, roots },
335
+ ),
336
+ ...(approval === undefined ? {} : { approval }),
337
+ tasks,
338
+ ...(config.tools.allow === undefined ? {} : { allow: config.tools.allow }),
339
+ deny: config.tools.deny,
340
+ });
341
+ opened.push(tools);
342
+
343
+ // No window known, no compactor: one that cannot tell when to fire only looks present.
344
+ const compactor =
345
+ compactionModel === undefined || model.contextLimit === undefined
346
+ ? undefined
347
+ : createCompactor({
348
+ model: compactionModel,
349
+ contextLimit: model.contextLimit,
350
+ policy: {
351
+ ...defaultCompactionPolicy,
352
+ keepLastTurns: config.compaction.keepLastTurns,
353
+ bufferTokens: config.compaction.bufferTokens,
354
+ },
355
+ });
356
+
357
+ const agent = createAgent({
358
+ model,
359
+ system: composeSystemPrompt(options.system ?? DEFAULT_ROLE, await environment(model), TOOL_POLICY_GUIDANCE),
360
+ instructions: instructions?.text,
361
+ tools,
362
+ maxSteps,
363
+ ...(compactor === undefined ? {} : { compactor }),
364
+ });
365
+
366
+ const conversation = createConversation({ agent, session, inbox, ...(store === undefined ? {} : { store }) });
367
+
368
+ return {
369
+ conversation,
370
+ model,
371
+ mode,
372
+ tools,
373
+ subagents,
374
+ ...(mcp === undefined ? {} : { mcp }),
375
+ providers,
376
+ ...(instructions === undefined ? {} : { instructions }),
377
+ skipped,
378
+ close: async () => {
379
+ await conversation.close();
380
+ // Agents first: what their logs gain is a note that they were stopped.
381
+ await subagents.close();
382
+ tasks.close();
383
+ await tools.close();
384
+ await mcp?.close();
385
+ await rm(temp, { recursive: true, force: true });
386
+ },
387
+ };
388
+ } catch (error) {
389
+ for (const resource of opened.reverse()) await Promise.resolve(resource.close()).catch(() => undefined);
390
+ await rm(temp, { recursive: true, force: true });
391
+ throw error;
392
+ }
393
+ }
394
+
395
+ interface ReadConfig {
396
+ config: Config;
397
+ paths: AppPaths;
398
+ /** Absent when no file was read: then no directory of agent files is either. */
399
+ loaded?: LoadedConfig;
400
+ serviceKeys: LoadedConfig["serviceKeys"];
401
+ skipped: SkippedSetting[];
402
+ }
403
+
404
+ async function readConfig(
405
+ options: CodingAgentOptions,
406
+ env: Readonly<Record<string, string | undefined>>,
407
+ ): Promise<ReadConfig> {
408
+ const { cwd } = options;
409
+ const overrides = options.overrides ?? {};
410
+
411
+ if (options.config === undefined) {
412
+ // Paths still: the environment block names the project, and sign-ins live there.
413
+ const { paths } = inspectProject({ cwd, env: { ...env } });
414
+ return { config: parseConfig(overrides), paths, serviceKeys: {}, skipped: [] };
415
+ }
416
+
417
+ const project = await projectTrust(options.config, cwd, env, overrides);
418
+ const loaded = loadConfig({ project, cwd, env: { ...env }, overrides });
419
+ return {
420
+ config: loaded.config,
421
+ paths: loaded.paths,
422
+ loaded,
423
+ serviceKeys: loaded.serviceKeys,
424
+ skipped: loaded.ignored.map((item) => ({ ...item })),
425
+ };
426
+ }
427
+
428
+ async function projectTrust(
429
+ decision: ProjectConfig,
430
+ cwd: string,
431
+ env: Readonly<Record<string, string | undefined>>,
432
+ overrides: ConfigInput,
433
+ ): Promise<ProjectTrust> {
434
+ if (decision === "trusted" || decision === "untrusted") return decision;
435
+
436
+ // With the overrides: one that names more instruction files makes more to ask about.
437
+ const inspection = inspectProject({ cwd, env: { ...env }, overrides });
438
+ // Nothing of the project's own to load, so nothing to decide.
439
+ if (inspection.files.length === 0 && inspection.variables.length === 0) return "trusted";
440
+
441
+ if (decision === "remembered") {
442
+ // The repository, not the checkout: a worktree of a trusted repository is not a stranger.
443
+ return readTrust(inspection.paths.userDir, inspection.paths.repoRoot) ?? "untrusted";
444
+ }
445
+ return (await decision(inspection)) ? "trusted" : "untrusted";
446
+ }
447
+
448
+ /** Written and not used: told, not dropped. A default nobody wrote is not news. */
449
+ function notUsed(config: Config): SkippedSetting[] {
450
+ const defaults = parseConfig({});
451
+ return Object.entries(NOT_USED)
452
+ .filter(([, value]) => value(config) !== value(defaults))
453
+ .map(([setting]) => ({
454
+ setting,
455
+ source: "config",
456
+ reason: NOT_USED_REASON[setting] ?? "createCodingAgent does not use it",
457
+ }));
458
+ }
459
+
460
+ /**
461
+ * The catalog the build carries, in memory: windows and prices without a
462
+ * request at start. `wraith models --refresh` is what updates the cache on disk.
463
+ */
464
+ function capabilitiesFor(config: Config): ModelCapabilities {
465
+ if (config.capabilities.source === "off") return permissiveCapabilities;
466
+ const snapshot = capabilitySnapshot();
467
+ return createModelsDevCapabilities({
468
+ tables: catalogTables(config.providers),
469
+ ...(snapshot === undefined ? {} : { snapshot }),
470
+ });
471
+ }
472
+
473
+ /**
474
+ * No store without `sessions`: the conversation already holds its session, and
475
+ * a store in memory would keep every record a second time for nobody to read.
476
+ */
477
+ function sessionStore(sessions: CodingAgentOptions["sessions"]): SessionStore | undefined {
478
+ if (sessions === undefined) return undefined;
479
+ return typeof sessions === "string" ? createFileSessionStore({ dir: sessions }) : sessions;
480
+ }
481
+
482
+ async function openSession(store: SessionStore | undefined, id: string | undefined): Promise<Session> {
483
+ if (store === undefined) {
484
+ if (id !== undefined) {
485
+ throw new AgentError("config/invalid", `Session "${id}" cannot be resumed without the sessions option.`, {
486
+ details: { id },
487
+ });
488
+ }
489
+ // Unique: the temp directory is named after the session.
490
+ return createSession(`session-${crypto.randomUUID()}`);
491
+ }
492
+ if (id === undefined) return store.create();
493
+ const found = await store.get(id);
494
+ if (found === null) {
495
+ throw new AgentError("session/not-found", `No session with id "${id}" in this store.`, {
496
+ details: { id },
497
+ });
498
+ }
499
+ return found;
500
+ }
501
+
502
+ /**
503
+ * The two built in, then the user's files, then a trusted project's. With no
504
+ * config read, the built-in ones only.
505
+ */
506
+ async function subagentKinds(
507
+ read: ReadConfig,
508
+ ): Promise<{ agents: Record<string, SubagentType>; skipped: SkippedSetting[] }> {
509
+ if (read.loaded === undefined) return { agents: { ...builtinSubagents }, skipped: [] };
510
+ const { paths } = read.loaded;
511
+ // Untrusted, `loadConfig` leaves the project's directory out of the paths.
512
+ const dirs = [paths.userAgentsDir, ...(paths.projectAgentsDir === undefined ? [] : [paths.projectAgentsDir])];
513
+ const { agents, skipped } = await loadSubagents(dirs);
514
+ return {
515
+ agents: { ...builtinSubagents, ...agents },
516
+ skipped: skipped.map((file) => ({ setting: "agent", source: file.path, reason: file.reason })),
517
+ };
518
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Ready-made agents: the core's blocks, put together for one kind of work.
3
+ * Each preset only composes; behaviour it needs lands in the core first.
4
+ */
5
+
6
+ export {
7
+ CODING_AGENT_MAX_STEPS,
8
+ createCodingAgent,
9
+ type CodingAgent,
10
+ type CodingAgentOptions,
11
+ type ProjectConfig,
12
+ type SkippedSetting,
13
+ } from "./coding-agent";