@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,164 @@
1
+ import type { CostSource, Usage } from "../events/types";
2
+ import type { ModelInfo } from "../providers/capabilities";
3
+
4
+ /**
5
+ * What a call cost, in micro-dollars.
6
+ *
7
+ * Two sources, and the label says which one answered: the provider's figure
8
+ * when it sends one, our own arithmetic when it does not. A total mixing the
9
+ * two is reported as an estimate.
10
+ *
11
+ * Everything here is integer micro-dollars. Prices are per million tokens, so
12
+ * `tokens × pricePerMillion` is already micro-dollars: nothing here divides.
13
+ */
14
+
15
+ /** USD per million tokens: the unit models.dev publishes and config copies. */
16
+ export interface ModelPrices {
17
+ input: number;
18
+ output: number;
19
+ /** Absent means "derive it from `input`" — the result is still an estimate. */
20
+ cacheRead?: number;
21
+ cacheWrite?: number;
22
+ }
23
+
24
+ /** Vendor-independent ratios, used only when a rate is missing. */
25
+ export const CACHE_READ_MULTIPLIER = 0.1;
26
+ export const CACHE_WRITE_MULTIPLIER = 1.25;
27
+
28
+ /**
29
+ * The part of the input billed at the full rate: `noCacheTokens` when the
30
+ * provider reports it, otherwise `inputTokens` minus the cache reads and
31
+ * writes. Never `inputTokens` alone: it includes the cache reads and writes,
32
+ * which are priced separately. Without the subtraction, a provider that
33
+ * reports cache counters but no `noCacheTokens` would be billed for its output
34
+ * alone.
35
+ */
36
+ export function billableInputTokens(usage: Usage): number {
37
+ if (usage.noCacheTokens !== undefined) return usage.noCacheTokens;
38
+ if (usage.inputTokens === undefined) return 0;
39
+ const cached = (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
40
+ return Math.max(0, usage.inputTokens - cached);
41
+ }
42
+
43
+ /** Micro-dollars for one call, priced field by field. */
44
+ export function estimateCost(usage: Usage, prices: ModelPrices): number {
45
+ const cacheRead = prices.cacheRead ?? prices.input * CACHE_READ_MULTIPLIER;
46
+ const cacheWrite = prices.cacheWrite ?? prices.input * CACHE_WRITE_MULTIPLIER;
47
+
48
+ return Math.round(
49
+ billableInputTokens(usage) * prices.input +
50
+ (usage.cacheReadTokens ?? 0) * cacheRead +
51
+ (usage.cacheWriteTokens ?? 0) * cacheWrite +
52
+ (usage.outputTokens ?? 0) * prices.output,
53
+ );
54
+ }
55
+
56
+ /**
57
+ * The cost fields for one call, or nothing at all: without a price there is no
58
+ * `costMicros`, and a front end prints `—`. Zero would be true for a local
59
+ * Ollama and a lie for a company gateway; only the price's author knows which.
60
+ */
61
+ export function costOf(usage: Usage, prices: ModelPrices | undefined): Usage {
62
+ if (prices === undefined) return {};
63
+ return { costMicros: estimateCost(usage, prices), costSource: "estimate" };
64
+ }
65
+
66
+ /**
67
+ * Prices for a model: the configured price when there is one, else the catalog
68
+ * price. The configured price is the bill this user receives; the catalog is a
69
+ * public list price for a model of that name. Reversing the order would leave
70
+ * the configured price unused.
71
+ */
72
+ export function resolvePrices(
73
+ info: ModelInfo | null | undefined,
74
+ // Written out rather than `ModelPrices`, because what a caller has in hand is
75
+ // a parsed config object, whose optional fields are `number | undefined`.
76
+ configured?: {
77
+ input: number;
78
+ output: number;
79
+ cacheRead?: number | undefined;
80
+ cacheWrite?: number | undefined;
81
+ },
82
+ ): ModelPrices | undefined {
83
+ if (configured !== undefined) {
84
+ const prices: ModelPrices = { input: configured.input, output: configured.output };
85
+ if (configured.cacheRead !== undefined) prices.cacheRead = configured.cacheRead;
86
+ if (configured.cacheWrite !== undefined) prices.cacheWrite = configured.cacheWrite;
87
+ return prices;
88
+ }
89
+ if (info?.inputPricePerMillion === undefined || info.outputPricePerMillion === undefined) {
90
+ return undefined;
91
+ }
92
+
93
+ const prices: ModelPrices = {
94
+ input: info.inputPricePerMillion,
95
+ output: info.outputPricePerMillion,
96
+ };
97
+ if (info.cacheReadPricePerMillion !== undefined) prices.cacheRead = info.cacheReadPricePerMillion;
98
+ if (info.cacheWritePricePerMillion !== undefined) {
99
+ prices.cacheWrite = info.cacheWritePricePerMillion;
100
+ }
101
+ return prices;
102
+ }
103
+
104
+ function asRecord(value: unknown): Record<string, unknown> | null {
105
+ return typeof value === "object" && value !== null && !Array.isArray(value)
106
+ ? (value as Record<string, unknown>)
107
+ : null;
108
+ }
109
+
110
+ function asNumber(value: unknown): number | undefined {
111
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
112
+ }
113
+
114
+ /**
115
+ * What OpenRouter says the call cost, in micro-dollars, or undefined.
116
+ *
117
+ * `upstream_inference_cost` is added to `cost` only when `is_byok` is true. On
118
+ * an ordinary account it equals `cost`, so adding it doubles the bill. Under
119
+ * BYOK `cost` is the OpenRouter routing fee and `upstream` is what the user's
120
+ * own key paid the vendor: only their sum is the real spend. The BYOK branch is
121
+ * not verified; the tests check only that it sums when the flag is set.
122
+ *
123
+ * `is_byok` is read from `usage.raw`, because the normalised `providerMetadata`
124
+ * copy drops it. That copy is a fallback and never adds `upstream`.
125
+ */
126
+ export function providerCostMicros(providerUsage: unknown, metadata?: unknown): number | undefined {
127
+ const raw = asRecord(providerUsage);
128
+ const cost = asNumber(raw?.cost);
129
+
130
+ if (raw !== null && cost !== undefined) {
131
+ const upstream = asNumber(asRecord(raw.cost_details)?.upstream_inference_cost) ?? 0;
132
+ return Math.round((cost + (raw.is_byok === true ? upstream : 0)) * 1_000_000);
133
+ }
134
+
135
+ // No raw block: `is_byok` is unknown, so the metadata figure is taken as
136
+ // the charge on its own.
137
+ const fromMetadata = asNumber(asRecord(asRecord(asRecord(metadata)?.openrouter)?.usage)?.cost);
138
+ return fromMetadata === undefined ? undefined : Math.round(fromMetadata * 1_000_000);
139
+ }
140
+
141
+ /** Which upstream provider OpenRouter routed to, when it says. */
142
+ export function routedProvider(metadata: unknown): string | undefined {
143
+ const provider = asRecord(asRecord(metadata)?.openrouter)?.provider;
144
+ return typeof provider === "string" && provider !== "" ? provider : undefined;
145
+ }
146
+
147
+ /**
148
+ * The provider's figure when there is one, our own when there is not.
149
+ *
150
+ * Shared by the loop, the compactor and the classifier, so all three decide the
151
+ * source the same way.
152
+ */
153
+ export function priceCall(
154
+ usage: Usage,
155
+ prices: ModelPrices | undefined,
156
+ source: { providerUsage?: unknown; metadata?: unknown } = {},
157
+ ): Usage {
158
+ const fromProvider = providerCostMicros(source.providerUsage, source.metadata);
159
+ if (fromProvider !== undefined) {
160
+ const costSource: CostSource = "provider";
161
+ return { ...usage, costMicros: fromProvider, costSource };
162
+ }
163
+ return { ...usage, ...costOf(usage, prices) };
164
+ }
@@ -0,0 +1,80 @@
1
+ import type { SessionRecordInput } from "../session/format";
2
+ import { type Prompt, type UserInput, toUserInput } from "./attachments";
3
+ import { userMessage, type UserMessage } from "./messages";
4
+
5
+ /**
6
+ * The one way anything from outside the model and its tools enters a
7
+ * conversation. The loop empties it before every model call.
8
+ */
9
+
10
+ /** What may enter: a line typed while the agent works, or a background task's record. */
11
+ export type InboxRecord =
12
+ | { type: "message"; message: UserMessage }
13
+ | Extract<SessionRecordInput, { type: "task" }>;
14
+
15
+ /** The port the loop sees. */
16
+ export interface Inbox {
17
+ /** Hands over what is waiting and forgets it. */
18
+ take(): InboxRecord[] | Promise<InboxRecord[]>;
19
+ }
20
+
21
+ /** The queue the core ships. */
22
+ export interface InboxQueue extends Inbox {
23
+ take(): InboxRecord[];
24
+ /**
25
+ * Something the user typed while the agent works. Always worth a run. Throws
26
+ * `attachment/*` for an attachment the vendors would refuse.
27
+ */
28
+ send(prompt: Prompt): void;
29
+ /** Anything else that may enter: a task record, a host notice. */
30
+ push(record: InboxRecord, options?: { wake?: boolean }): void;
31
+ /** Whether anything waiting is worth starting a run for. */
32
+ wakes(): boolean;
33
+ /** Takes back the prompts given to `send()` that nobody took yet. Everything else stays. */
34
+ recall(): UserInput[];
35
+ /** Called on every push. */
36
+ subscribe(listener: () => void): () => void;
37
+ }
38
+
39
+ interface Waiting {
40
+ record: InboxRecord;
41
+ wake: boolean;
42
+ /** The prompt as it was given, for what came through `send()`. */
43
+ typed?: UserInput;
44
+ }
45
+
46
+ export function createInbox(): InboxQueue {
47
+ let waiting: Waiting[] = [];
48
+ const listeners = new Set<() => void>();
49
+
50
+ const add = (entry: Waiting): void => {
51
+ waiting.push(entry);
52
+ for (const listener of listeners) listener();
53
+ };
54
+
55
+ return {
56
+ push: (record, options = {}) => add({ record, wake: options.wake === true }),
57
+ send: (prompt) => {
58
+ const typed = toUserInput(prompt);
59
+ add({ record: { type: "message", message: userMessage(typed) }, wake: true, typed });
60
+ },
61
+ take: () => {
62
+ const taken = waiting.map((entry) => entry.record);
63
+ waiting = [];
64
+ return taken;
65
+ },
66
+ wakes: () => waiting.some((entry) => entry.wake),
67
+ recall: () => {
68
+ const typed = waiting.flatMap((entry) => (entry.typed === undefined ? [] : [entry.typed]));
69
+ // A task ended whether or not somebody cancelled the turn, so its record stays.
70
+ waiting = waiting.filter((entry) => entry.typed === undefined);
71
+ return typed;
72
+ },
73
+ subscribe: (listener) => {
74
+ listeners.add(listener);
75
+ return () => {
76
+ listeners.delete(listener);
77
+ };
78
+ },
79
+ };
80
+ }
@@ -0,0 +1,62 @@
1
+ import type { ModelMessage } from "ai";
2
+ import { type UserMessage, hostMessage, isHostMessage } from "./messages";
3
+
4
+ /**
5
+ * How the user's and the project's instruction files reach the model: a host
6
+ * message in the conversation, never the system prompt, which opens every
7
+ * request and must not change. The last such message in the history is what
8
+ * the model was last told, so a change sends a new one and a compaction, which
9
+ * drops it, sends it again.
10
+ */
11
+
12
+ const OPEN = "<instruction_files>";
13
+ const CLOSE = "</instruction_files>";
14
+ // Without it the model reads a user turn, and answers it.
15
+ const SENDER =
16
+ "This message comes from the harness, not from the user: the instruction files of the user and of the project. Follow them unless the user says otherwise.";
17
+ const REPLACES = "These replace every instruction file given earlier in this conversation.";
18
+
19
+ const FILE_OPEN = /^<file path="(.*)">$/;
20
+
21
+ /** One file inside the message. A front end reads the paths back with `instructionFilesOf`. */
22
+ export function instructionFileBlock(path: string, text: string): string {
23
+ return `<file path="${path}">\n${text}\n</file>`;
24
+ }
25
+
26
+ export function instructionsMessage(text: string, replacing: boolean): UserMessage {
27
+ return hostMessage([OPEN, SENDER, ...(replacing ? [REPLACES] : []), text, CLOSE].join("\n"));
28
+ }
29
+
30
+ function bodyOf(message: ModelMessage): string | undefined {
31
+ if (!isHostMessage(message) || typeof message.content !== "string") return undefined;
32
+ const head = `${OPEN}\n${SENDER}\n`;
33
+ const tail = `\n${CLOSE}`;
34
+ const content = message.content;
35
+ if (!content.startsWith(head) || !content.endsWith(tail)) return undefined;
36
+ const body = content.slice(head.length, content.length - tail.length);
37
+ return body.startsWith(`${REPLACES}\n`) ? body.slice(REPLACES.length + 1) : body;
38
+ }
39
+
40
+ export function isInstructionsMessage(message: ModelMessage): boolean {
41
+ return bodyOf(message) !== undefined;
42
+ }
43
+
44
+ /** The text the history last gave the model, or nothing when it holds none. */
45
+ export function lastInstructions(messages: readonly ModelMessage[]): string | undefined {
46
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
47
+ const message = messages[index];
48
+ const body = message === undefined ? undefined : bodyOf(message);
49
+ if (body !== undefined) return body;
50
+ }
51
+ return undefined;
52
+ }
53
+
54
+ /** The files a message carried, for a front end that draws it as one line; nothing for another message. */
55
+ export function instructionFilesOf(message: ModelMessage): string[] | undefined {
56
+ const body = bodyOf(message);
57
+ if (body === undefined) return undefined;
58
+ return body.split("\n").flatMap((line) => {
59
+ const path = FILE_OPEN.exec(line)?.[1];
60
+ return path === undefined ? [] : [path];
61
+ });
62
+ }