@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,186 @@
1
+ import { AgentError, serializeError } from "../errors";
2
+ import type { AgentEvent, AgentEventPayload } from "../events/types";
3
+ import type { Preflight, ToolCall, ToolOutcome, ToolRunner } from "./tools";
4
+
5
+ // How one step's tool calls run: in groups.
6
+
7
+ /** A model rarely sends more than six at once. */
8
+ export const MAX_PARALLEL_TOOLS = 10;
9
+
10
+ /** Consecutive "parallel" calls share a group; any other call stands alone and is a barrier. */
11
+ export function planGroups(calls: readonly ToolCall[], runner: ToolRunner): ToolCall[][] {
12
+ const groups: ToolCall[][] = [];
13
+ let open: ToolCall[] | undefined;
14
+
15
+ for (const call of calls) {
16
+ if (schedule(runner, call) === "parallel") {
17
+ if (open === undefined) {
18
+ open = [];
19
+ groups.push(open);
20
+ }
21
+ open.push(call);
22
+ } else {
23
+ open = undefined;
24
+ groups.push([call]);
25
+ }
26
+ }
27
+ return groups;
28
+ }
29
+
30
+ // Anything but "parallel" runs alone, a throwing preflight included; so does
31
+ // every call when the runner has no preflight.
32
+ function schedule(runner: ToolRunner, call: ToolCall): Preflight {
33
+ if (runner.preflight === undefined) return "serial";
34
+ try {
35
+ return runner.preflight(call) === "parallel" ? "parallel" : "serial";
36
+ } catch {
37
+ return "serial";
38
+ }
39
+ }
40
+
41
+ export interface GroupHooks {
42
+ /** Starts one call. `emit` publishes while it runs. */
43
+ start: (call: ToolCall, emit: (payload: AgentEventPayload) => void) => Promise<ToolOutcome>;
44
+ event: (payload: AgentEventPayload) => AgentEvent;
45
+ /** Sees every payload with the call it came from; the loop records approvals here. */
46
+ note: (call: ToolCall, payload: AgentEventPayload) => void;
47
+ signal: AbortSignal;
48
+ limit?: number;
49
+ }
50
+
51
+ /**
52
+ * Runs a group, yielding what its calls publish while they run.
53
+ * Outcomes come back by position, never by completion: the log must say what
54
+ * was asked, in order.
55
+ */
56
+ export async function* drainAll(
57
+ group: readonly ToolCall[],
58
+ hooks: GroupHooks,
59
+ ): AsyncGenerator<AgentEvent, ToolOutcome[]> {
60
+ const limit = hooks.limit ?? MAX_PARALLEL_TOOLS;
61
+ const outcomes: (ToolOutcome | undefined)[] = group.map(() => undefined);
62
+ const queue: { index: number; payload: AgentEventPayload }[] = [];
63
+ const settled: number[] = [];
64
+
65
+ let wake: (() => void) | undefined;
66
+ const rouse = (): void => {
67
+ wake?.();
68
+ wake = undefined;
69
+ };
70
+
71
+ let next = 0;
72
+ let running = 0;
73
+ let failure: { error: unknown } | undefined;
74
+
75
+ const launch = (index: number, call: ToolCall): void => {
76
+ running += 1;
77
+ queue.push({
78
+ index,
79
+ payload: { type: "tool-start", toolCallId: call.toolCallId, toolName: call.toolName },
80
+ });
81
+
82
+ let work: Promise<ToolOutcome>;
83
+ try {
84
+ work = hooks.start(call, (payload) => {
85
+ queue.push({ index, payload });
86
+ rouse();
87
+ });
88
+ } catch (error) {
89
+ work = Promise.reject(error);
90
+ }
91
+
92
+ work.then(
93
+ (outcome) => {
94
+ outcomes[index] = outcome;
95
+ settled.push(index);
96
+ running -= 1;
97
+ rouse();
98
+ },
99
+ (error: unknown) => {
100
+ failure ??= { error };
101
+ running -= 1;
102
+ rouse();
103
+ },
104
+ );
105
+ };
106
+
107
+ for (;;) {
108
+ // After a runner throws, nothing new starts; what runs is still awaited so no promise outlives us.
109
+ while (failure === undefined && running < limit && next < group.length) {
110
+ const index = next;
111
+ next += 1;
112
+ const call = group[index] as ToolCall;
113
+
114
+ // Nothing starts after Esc, but every call still gets a result or the provider rejects the history.
115
+ if (hooks.signal.aborted) {
116
+ outcomes[index] = cancelled(call);
117
+ settled.push(index);
118
+ continue;
119
+ }
120
+ launch(index, call);
121
+ }
122
+
123
+ // The queue empties before any result goes out, so a call's approval never lands after its answer.
124
+ for (;;) {
125
+ const item = queue.shift();
126
+ if (item !== undefined) {
127
+ const call = group[item.index] as ToolCall;
128
+ hooks.note(call, item.payload);
129
+ yield hooks.event(item.payload);
130
+ continue;
131
+ }
132
+
133
+ const index = settled.shift();
134
+ if (index === undefined) break;
135
+ const call = group[index] as ToolCall;
136
+ const outcome = outcomes[index] as ToolOutcome;
137
+
138
+ // For a runner that predates `emit` and hands its events over with the outcome.
139
+ for (const payload of outcome.events ?? []) {
140
+ hooks.note(call, payload);
141
+ yield hooks.event(payload);
142
+ }
143
+
144
+ yield hooks.event(
145
+ outcome.error === undefined
146
+ ? {
147
+ type: "tool-result",
148
+ toolCallId: outcome.toolCallId,
149
+ toolName: outcome.toolName,
150
+ output: outcome.output,
151
+ ...(outcome.change === undefined ? {} : { change: outcome.change }),
152
+ }
153
+ : {
154
+ type: "tool-error",
155
+ toolCallId: outcome.toolCallId,
156
+ toolName: outcome.toolName,
157
+ error: outcome.error,
158
+ },
159
+ );
160
+ }
161
+
162
+ const nothingLeftToStart = next >= group.length || failure !== undefined;
163
+ if (running === 0 && nothingLeftToStart) break;
164
+ if (running === 0) continue;
165
+
166
+ // Nothing runs between the last look at both queues and here, so no publication slips past.
167
+ await new Promise<void>((resolve) => {
168
+ wake = resolve;
169
+ });
170
+ }
171
+
172
+ if (failure !== undefined) throw failure.error;
173
+ return outcomes as ToolOutcome[];
174
+ }
175
+
176
+ function cancelled(call: ToolCall): ToolOutcome {
177
+ return {
178
+ toolCallId: call.toolCallId,
179
+ toolName: call.toolName,
180
+ error: serializeError(
181
+ new AgentError("run/aborted", `${call.toolName} was cancelled.`, {
182
+ details: { toolName: call.toolName },
183
+ }),
184
+ ),
185
+ };
186
+ }
@@ -0,0 +1,106 @@
1
+ import type { SerializedError } from "../errors";
2
+ import type { AgentEventPayload, Usage } from "../events/types";
3
+ import type { FileChange } from "../tools/change";
4
+ import type { Attachment } from "./attachments";
5
+ import type { ModelMessage } from "./messages";
6
+
7
+ /**
8
+ * The seam between the loop and tool execution.
9
+ *
10
+ * The loop owns *when* a tool runs; a `ToolRunner` owns *what* running means:
11
+ * lookup, permission policy, approval, timeouts. Swapping the implementation
12
+ * never touches the loop.
13
+ *
14
+ * `modelTools` goes to the provider as schemas without `execute`, so the SDK
15
+ * validates the arguments and hands each call back instead of running it.
16
+ */
17
+
18
+ export interface ToolCall {
19
+ toolCallId: string;
20
+ toolName: string;
21
+ input: unknown;
22
+ }
23
+
24
+ /** What the run can tell a tool about itself. Not the tool's own context. */
25
+ export interface ToolRunContext {
26
+ signal: AbortSignal;
27
+ sessionId: string;
28
+ runId: string;
29
+ /**
30
+ * Publishes an event while the call is still in flight.
31
+ *
32
+ * An approval request has to reach an observer *before* the answer does, or a
33
+ * remote handler announces the question only after it is answered.
34
+ * Optional so an existing implementation of this port keeps compiling.
35
+ */
36
+ emit?: (payload: AgentEventPayload) => void;
37
+ /**
38
+ * The conversation so far, for approval handlers that judge intent rather
39
+ * than syntax. Optional: an older implementation of this port keeps
40
+ * compiling and gets an empty transcript.
41
+ *
42
+ * Includes the turn in progress, so the assistant message carrying the call
43
+ * being approved is already in it.
44
+ */
45
+ messages?: readonly ModelMessage[];
46
+ }
47
+
48
+ export interface ToolOutcome {
49
+ toolCallId: string;
50
+ toolName: string;
51
+ /** Present on success. */
52
+ output?: unknown;
53
+ /** Present on failure; the model is told, the run continues. */
54
+ error?: SerializedError;
55
+ /** What a write did, for the screen and the log — not for the model. */
56
+ change?: FileChange;
57
+ /** Images the call returns to the model beside `output`. */
58
+ attachments?: readonly Attachment[];
59
+ /**
60
+ * What the call spent on models of its own, as a tool that runs an agent
61
+ * does. The loop writes it to the session's bill; the model never sees it.
62
+ */
63
+ usage?: Usage;
64
+ /**
65
+ * What happened on the way, for runners that do not call `emit`.
66
+ *
67
+ * Kept so an implementation written against the older contract still has its
68
+ * approvals recorded: the loop emits these after the call settles. A runner
69
+ * that calls `emit` leaves this empty.
70
+ */
71
+ events?: readonly AgentEventPayload[];
72
+ }
73
+
74
+ /** Whether a call may run beside others in its step. */
75
+ export type Preflight = "parallel" | "serial";
76
+
77
+ export interface ToolRunner {
78
+ /** Tool definitions handed to the model, never carrying an execute function. */
79
+ readonly modelTools: Record<string, unknown>;
80
+ execute(call: ToolCall, context: ToolRunContext): Promise<ToolOutcome>;
81
+ /**
82
+ * A scheduling hint, never a permission: `execute` still asks the policy
83
+ * itself. Must not ask, run or emit. Absent means every call runs alone.
84
+ */
85
+ preflight?(call: ToolCall): Preflight;
86
+ /**
87
+ * Names of the tools the model reaches only through `call_tool`, sorted.
88
+ * Asked before every model call, so the model hears of a tool that appeared
89
+ * mid-turn at its next step. Absent: there are none.
90
+ */
91
+ onDemandTools?(): Promise<readonly string[]>;
92
+ }
93
+
94
+ /** A model with no tools available. */
95
+ export const emptyToolRunner: ToolRunner = {
96
+ modelTools: {},
97
+ execute: async (call) => ({
98
+ toolCallId: call.toolCallId,
99
+ toolName: call.toolName,
100
+ error: {
101
+ code: "tool/not-found",
102
+ message: `No tool named "${call.toolName}" is available.`,
103
+ details: { toolName: call.toolName },
104
+ },
105
+ }),
106
+ };
package/src/app.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The one place the product name lives.
3
+ *
4
+ * Everything a user sees while working — the command, the directories, the
5
+ * environment prefix — derives from here. The npm scope (@wraith-ai) is a
6
+ * separate concern that belongs to distribution and appears only in
7
+ * package.json files, so renaming one never drags the other along.
8
+ */
9
+
10
+ export const APP_NAME = "wraith";
11
+
12
+ /** Prefix for this app's own environment variables. Provider keys use theirs. */
13
+ export const ENV_PREFIX = "WRAITH";
14
+
15
+ /** Per-project directory, checked in the working directory. */
16
+ export const PROJECT_DIR_NAME = `.${APP_NAME}`;
17
+
18
+ export const CONFIG_FILE_NAME = "config.json";
19
+ /** Personal overrides, expected to be git-ignored. */
20
+ export const LOCAL_CONFIG_FILE_NAME = "config.local.json";
21
+ /**
22
+ * Provider API keys, in the user's directory only.
23
+ *
24
+ * A file of its own rather than a field in `config.json`, which is committed,
25
+ * shared with the team and printed by `config show`.
26
+ */
27
+ export const CREDENTIALS_FILE_NAME = "credentials.json";
28
+ /** Optional override for the system prompt compiled into the binary. */
29
+ export const PROMPT_FILE_NAME = "prompt.md";
30
+
31
+ /**
32
+ * The name an application built on this core wears on disk. Everything here is
33
+ * branding, not behaviour: the project directory, the environment prefix, and
34
+ * what error messages call the command. The file names inside the directory
35
+ * stay fixed.
36
+ */
37
+ export interface AppIdentity {
38
+ /** What messages call the application. Its commands are never named here. */
39
+ name: string;
40
+ /** Per-project directory, looked for from the working directory upwards. */
41
+ projectDirName: string;
42
+ /** Prefix for the app's own variables. Provider keys use their own names. */
43
+ envPrefix: string;
44
+ }
45
+
46
+ /**
47
+ * Everything derives from the name, so the common case is one argument:
48
+ * `defineApp({ name: "forge" })` gives `.forge` and `FORGE_*`.
49
+ */
50
+ export function defineApp(identity: { name: string } & Partial<AppIdentity>): AppIdentity {
51
+ return {
52
+ projectDirName: `.${identity.name}`,
53
+ envPrefix: identity.name.toUpperCase(),
54
+ ...identity,
55
+ };
56
+ }
57
+
58
+ /** This product. Every function taking an `AppIdentity` defaults to it. */
59
+ export const WRAITH: AppIdentity = {
60
+ name: APP_NAME,
61
+ projectDirName: PROJECT_DIR_NAME,
62
+ envPrefix: ENV_PREFIX,
63
+ };
64
+
65
+ export function envVar(name: string, app: AppIdentity = WRAITH): string {
66
+ return `${app.envPrefix}_${name}`;
67
+ }
@@ -0,0 +1,66 @@
1
+ import { mkdir, rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { AgentError } from "../errors";
4
+ import type { CredentialStore, OAuthCredential } from "../providers/oauth";
5
+ import { readTextFile, withFileLock, writeFileAtomically } from "./locked-file";
6
+
7
+ /**
8
+ * Sign-ins on disk, one file per provider.
9
+ *
10
+ * Not in `credentials.json`: a token changes while the process runs, and that
11
+ * file is read once into `Config` and written without a lock. Either would
12
+ * sooner or later write a spent refresh token back over a live one.
13
+ * One file per provider, so a refresh of one never rewrites another's entry.
14
+ */
15
+
16
+ function fileFor(dir: string, provider: string): string {
17
+ // Provider names come from config; one with a separator must not pick its own path.
18
+ if (!/^[A-Za-z0-9._-]+$/.test(provider)) {
19
+ throw new AgentError("config/invalid", `Provider name "${provider}" cannot be used as a file name.`, {
20
+ details: { provider },
21
+ });
22
+ }
23
+ return join(dir, `${provider}.json`);
24
+ }
25
+
26
+ function parseCredential(text: string | undefined): OAuthCredential | undefined {
27
+ if (text === undefined) return undefined;
28
+ try {
29
+ const value = JSON.parse(text) as Partial<OAuthCredential> | null;
30
+ if (typeof value?.access === "string" && typeof value.refresh === "string" && typeof value.expires === "number") {
31
+ return { access: value.access, refresh: value.refresh, expires: value.expires };
32
+ }
33
+ } catch {
34
+ // Unreadable is the same as absent: the answer is to sign in again.
35
+ }
36
+ return undefined;
37
+ }
38
+
39
+ export function fileCredentialStore(dir: string): CredentialStore {
40
+ const locked = async <T>(provider: string, work: (file: string) => Promise<T>): Promise<T> => {
41
+ const file = fileFor(dir, provider);
42
+ await mkdir(dir, { recursive: true, mode: 0o700 });
43
+ return withFileLock(
44
+ `${file}.lock`,
45
+ () => work(file),
46
+ () =>
47
+ new AgentError("provider/request-failed", `Timed out waiting for ${file}.lock. Delete it if no other process is running.`),
48
+ );
49
+ };
50
+
51
+ return {
52
+ read: async (provider) => parseCredential(await readTextFile(fileFor(dir, provider))),
53
+
54
+ modify: (provider, fn) =>
55
+ locked(provider, async (file) => {
56
+ // Read under the lock: the copy from before waiting may already be spent.
57
+ const current = parseCredential(await readTextFile(file));
58
+ const next = await fn(current);
59
+ if (next === undefined) return current;
60
+ await writeFileAtomically(file, `${JSON.stringify(next, null, 2)}\n`);
61
+ return next;
62
+ }),
63
+
64
+ delete: (provider) => locked(provider, (file) => rm(file, { force: true })),
65
+ };
66
+ }
@@ -0,0 +1,105 @@
1
+ import { readFile, readdir } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import type { AppPaths } from "./paths";
4
+
5
+ /**
6
+ * The facts an agent would otherwise spend its first steps discovering, as a
7
+ * fragment of its system prompt. Every line replaces at least one round trip.
8
+ *
9
+ * Here, not in `agent/`, because it reads the disk.
10
+ */
11
+
12
+ /** Enough to recognise the project, short enough not to crowd the prompt. */
13
+ const MAX_LISTED_ENTRIES = 40;
14
+
15
+ export interface EnvironmentOptions {
16
+ /** The workspace root: where the shell starts and relative paths resolve. */
17
+ cwd: string;
18
+ paths: Pick<AppPaths, "projectDir" | "projectRoot" | "repoRoot" | "checkoutRoot" | "gitDir">;
19
+ /** Stated when given: a model told what it is hedges less and answers at its own length. */
20
+ model?: string;
21
+ /**
22
+ * Lines that name the session, such as its scratch directory. They go last:
23
+ * everything above is the same for every session of a project, and stays one
24
+ * cached prefix.
25
+ */
26
+ session?: readonly string[];
27
+ }
28
+
29
+ export async function environmentBlock(options: EnvironmentOptions): Promise<string> {
30
+ const { cwd, paths, model } = options;
31
+ const checkout = await describeCheckout(paths);
32
+ // The application's own directory is hidden with the two that crowd out everything else.
33
+ const own = paths.projectDir === undefined ? [] : [basename(paths.projectDir)];
34
+ const entries = await topLevel(cwd, new Set([".git", "node_modules", ...own]));
35
+
36
+ const lines = [
37
+ "## Environment",
38
+ "",
39
+ `Working directory: ${cwd}`,
40
+ `Project root: ${paths.projectRoot}`,
41
+ ...(model === undefined ? [] : [`Model: ${model}`]),
42
+ `Platform: ${process.platform}`,
43
+ "Shell for the bash tool: bash (POSIX syntax on every platform, Windows included)",
44
+ `Today: ${new Date().toISOString().slice(0, 10)}`,
45
+ `Git repository: ${checkout === undefined ? "no" : `yes, ${checkout}`}`,
46
+ ];
47
+
48
+ if (entries.length > 0) {
49
+ lines.push("", `Top level of the working directory: ${entries.join(", ")}`);
50
+ }
51
+
52
+ lines.push(
53
+ "",
54
+ "Trust these facts instead of rediscovering them. In particular, do not run",
55
+ "commands to find out which operating system or shell you are on.",
56
+ );
57
+
58
+ if (options.session !== undefined && options.session.length > 0) {
59
+ lines.push("", ...options.session);
60
+ }
61
+
62
+ return lines.join("\n");
63
+ }
64
+
65
+ /**
66
+ * "on branch x", and whose worktree this is when it is one. Undefined outside a
67
+ * repository.
68
+ */
69
+ export async function describeCheckout(
70
+ paths: Pick<AppPaths, "repoRoot" | "checkoutRoot" | "gitDir">,
71
+ ): Promise<string | undefined> {
72
+ const branch = await gitBranch(paths.gitDir);
73
+ if (branch === undefined) return undefined;
74
+ const linked = paths.repoRoot === paths.checkoutRoot ? "" : `, in a worktree of ${paths.repoRoot}`;
75
+ return `on branch ${branch}${linked}`;
76
+ }
77
+
78
+ /**
79
+ * Read from the checkout's own `HEAD`, because spawning git costs a process.
80
+ * The git directory comes resolved: in a worktree `.git` is a file, and the
81
+ * main checkout's `HEAD` names somebody else's branch.
82
+ */
83
+ async function gitBranch(gitDir: string | undefined): Promise<string | undefined> {
84
+ if (gitDir === undefined) return undefined;
85
+ let head: string;
86
+ try {
87
+ head = await readFile(join(gitDir, "HEAD"), "utf8");
88
+ } catch {
89
+ return undefined;
90
+ }
91
+ const match = /^ref: refs\/heads\/(.+)$/m.exec(head.trim());
92
+ return match?.[1] ?? "(detached)";
93
+ }
94
+
95
+ async function topLevel(root: string, hidden: ReadonlySet<string>): Promise<string[]> {
96
+ try {
97
+ const found = await readdir(root, { withFileTypes: true });
98
+ return found
99
+ .filter((entry) => !hidden.has(entry.name))
100
+ .slice(0, MAX_LISTED_ENTRIES)
101
+ .map((entry) => (entry.isDirectory() ? `${entry.name}/` : entry.name));
102
+ } catch {
103
+ return [];
104
+ }
105
+ }
@@ -0,0 +1,157 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { instructionFileBlock } from "../agent/instructions";
4
+ import type { ProjectTrust } from "./load";
5
+ import type { AppPaths } from "./paths";
6
+ import type { Config } from "./schema";
7
+
8
+ /**
9
+ * AGENTS.md and the files like it: what the user and a project's authors tell
10
+ * the agent. Read here, by the host; the loop puts the text into the history
11
+ * as a message, never into the system prompt, where a repository's words
12
+ * would speak with the application's authority.
13
+ */
14
+
15
+ export interface InstructionFile {
16
+ path: string;
17
+ /** The user's own file, or one of the project's. */
18
+ scope: "user" | "project";
19
+ /** As read, before any cut. */
20
+ bytes: number;
21
+ /** Cut at `instructions.maxBytes`; the text says so to the model too. */
22
+ truncated: boolean;
23
+ }
24
+
25
+ export interface Instructions {
26
+ /** For `createAgent({ instructions })`: every file in a block naming its path. */
27
+ text: string;
28
+ files: InstructionFile[];
29
+ }
30
+
31
+ /**
32
+ * What decides what may be read: the settings, the paths, and the trust
33
+ * decision they were loaded under. A `LoadedConfig` is one; taking the three
34
+ * together keeps a project's files from being read on a decision made elsewhere.
35
+ */
36
+ export interface InstructionSource {
37
+ config: Pick<Config, "instructions">;
38
+ paths: Pick<AppPaths, "userDir" | "checkoutRoot">;
39
+ project: ProjectTrust;
40
+ }
41
+
42
+ export interface LoadInstructionsOptions {
43
+ /** The workspace: files are looked for from the checkout's root down to here. */
44
+ cwd: string;
45
+ /** For tests. Null when the file cannot be read. */
46
+ readFile?: (path: string) => Promise<string | null>;
47
+ }
48
+
49
+ /**
50
+ * The directories a project's files are looked for in, outermost first: the
51
+ * checkout's root down to `cwd`. A worktree is its own checkout, so the main
52
+ * one's copy of a file is never read beside the worktree's.
53
+ */
54
+ export function instructionDirs(
55
+ checkoutRoot: string,
56
+ cwd: string,
57
+ pathModule: Pick<typeof path, "relative" | "isAbsolute" | "join" | "sep"> = path,
58
+ ): string[] {
59
+ const relative = pathModule.relative(checkoutRoot, cwd);
60
+ if (relative === "") return [checkoutRoot];
61
+ if (relative.startsWith("..") || pathModule.isAbsolute(relative)) return [cwd];
62
+ const dirs = [checkoutRoot];
63
+ let current = checkoutRoot;
64
+ for (const part of relative.split(pathModule.sep)) {
65
+ current = pathModule.join(current, part);
66
+ dirs.push(current);
67
+ }
68
+ return dirs;
69
+ }
70
+
71
+ async function defaultRead(file: string): Promise<string | null> {
72
+ try {
73
+ return await readFile(file, "utf8");
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** The first of `names` that can be read in `dir`. */
80
+ async function firstIn(
81
+ dir: string,
82
+ names: readonly string[],
83
+ read: (file: string) => Promise<string | null>,
84
+ ): Promise<{ path: string; text: string } | undefined> {
85
+ for (const name of names) {
86
+ const file = path.join(dir, name);
87
+ const text = await read(file);
88
+ if (text !== null) return { path: file, text: text.replace(/^\uFEFF/u, "") };
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ /** Cut to at most `limit` bytes of UTF-8, without leaving half a character. */
94
+ function cutToBytes(text: string, limit: number): string {
95
+ return Buffer.from(text, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/u, "");
96
+ }
97
+
98
+ /**
99
+ * The user's file, then the project's from the checkout's root down to `cwd`,
100
+ * the project's only when it is trusted. Undefined when there is nothing.
101
+ */
102
+ export async function loadInstructions(
103
+ source: InstructionSource,
104
+ options: LoadInstructionsOptions,
105
+ ): Promise<Instructions | undefined> {
106
+ const { files: names, maxBytes } = source.config.instructions;
107
+ if (names.length === 0 || maxBytes === 0) return undefined;
108
+ const read = options.readFile ?? defaultRead;
109
+
110
+ const found: { path: string; text: string; scope: InstructionFile["scope"] }[] = [];
111
+ const own = await firstIn(source.paths.userDir, names, read);
112
+ if (own !== undefined) found.push({ ...own, scope: "user" });
113
+ if (source.project === "trusted") {
114
+ for (const dir of instructionDirs(source.paths.checkoutRoot, options.cwd)) {
115
+ const file = await firstIn(dir, names, read);
116
+ if (file !== undefined) found.push({ ...file, scope: "project" });
117
+ }
118
+ }
119
+ if (found.length === 0) return undefined;
120
+
121
+ let left = maxBytes;
122
+ const files: InstructionFile[] = [];
123
+ const blocks: string[] = [];
124
+ for (const file of found) {
125
+ const bytes = Buffer.byteLength(file.text, "utf8");
126
+ const truncated = bytes > left;
127
+ const text = truncated ? cutToBytes(file.text, left) : file.text;
128
+ left = Math.max(0, left - bytes);
129
+ files.push({ path: file.path, scope: file.scope, bytes, truncated });
130
+ const note = truncated ? "\n[The rest of this file was cut: it is over the size limit for instructions.]" : "";
131
+ blocks.push(instructionFileBlock(file.path, `${text.trimEnd()}${note}`));
132
+ }
133
+
134
+ const text = [
135
+ `The working directory is ${options.cwd}. The user's own file comes first, then the project's from its root down; where two disagree, the later one wins.`,
136
+ ...blocks,
137
+ ].join("\n\n");
138
+ return { text, files };
139
+ }
140
+
141
+ /**
142
+ * The project's files that would be read if it were trusted, for the trust
143
+ * question and for what an untrusted load reports. The user's own file is not
144
+ * the project's and is never in it.
145
+ */
146
+ export function projectInstructionFiles(
147
+ checkoutRoot: string,
148
+ cwd: string,
149
+ names: readonly string[],
150
+ exists: (file: string) => boolean,
151
+ pathModule: Pick<typeof path, "relative" | "isAbsolute" | "join" | "sep"> = path,
152
+ ): string[] {
153
+ return instructionDirs(checkoutRoot, cwd, pathModule).flatMap((dir) => {
154
+ const name = names.find((candidate) => exists(pathModule.join(dir, candidate)));
155
+ return name === undefined ? [] : [pathModule.join(dir, name)];
156
+ });
157
+ }