neuralbrain 0.0.0-stage → 0.0.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 (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +106 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
@@ -0,0 +1,292 @@
1
+ /**
2
+ * The generative adapters: three cloud vendors plus the OpenAI-compatible
3
+ * `remote` tier, all behind one interface.
4
+ *
5
+ * Every adapter speaks raw `fetch` rather than a vendor SDK, for three
6
+ * reasons: the request and response shapes are the thing being adapted and are
7
+ * clearer written out; there is exactly one timeout and one error path to
8
+ * audit; and tests mock `fetch` instead of a client object.
9
+ *
10
+ * An adapter's job stops at returning the text. It never parses the model's
11
+ * JSON, never repairs it and never decides whether it is acceptable — that is
12
+ * the verification gate's job, and the gate runs on every producer, vendor
13
+ * included (docs/CONTRACTS.md).
14
+ */
15
+
16
+ import { VENDOR_API_KEY_ENV } from './config';
17
+ import type { VendorName } from '../learning/types';
18
+
19
+ export interface ChatRequest {
20
+ system: string;
21
+ user: string;
22
+ model: string;
23
+ maxTokens: number;
24
+ signal?: AbortSignal;
25
+ }
26
+
27
+ export interface ChatReply {
28
+ /** The model's text. '' when the provider returned no content at all. */
29
+ content: string;
30
+ /**
31
+ * Normalised across vendors: 'length' whenever the response was cut off by
32
+ * the token budget, whatever each vendor calls it. The gate keys its
33
+ * `truncated` rejection off exactly this value.
34
+ */
35
+ finish_reason: string | null;
36
+ /** The model id the provider says answered, when it reports one. */
37
+ model: string | null;
38
+ /** Reasoning/thinking tokens the provider reports, 0 when it reports none. */
39
+ reasoning_tokens: number;
40
+ }
41
+
42
+ export interface GenerativeAdapter {
43
+ readonly name: string;
44
+ complete(req: ChatRequest): Promise<ChatReply>;
45
+ }
46
+
47
+ export class ChatTransportError extends Error {
48
+ readonly code = 'chat_transport_error';
49
+ readonly status: number | null;
50
+
51
+ constructor(message: string, status: number | null = null) {
52
+ super(message);
53
+ this.name = 'ChatTransportError';
54
+ this.status = status;
55
+ }
56
+ }
57
+
58
+ export function isChatTransportError(error: unknown): error is ChatTransportError {
59
+ return error instanceof ChatTransportError;
60
+ }
61
+
62
+ function requireKey(vendor: VendorName): string {
63
+ const envName = VENDOR_API_KEY_ENV[vendor];
64
+ const key = process.env[envName]?.trim();
65
+ if (!key) {
66
+ throw new ChatTransportError(`${envName} is required for BRAIN_VENDOR=${vendor}`);
67
+ }
68
+ return key;
69
+ }
70
+
71
+ /**
72
+ * Strips/redacts sensitive query parameters (e.g., key, api_key, token, auth, secret)
73
+ * from a URL so credentials cannot leak into error messages, logs, or HTTP responses.
74
+ */
75
+ export function redactUrl(url: string): string {
76
+ try {
77
+ const parsed = new URL(url);
78
+ const sensitive = ['key', 'api_key', 'token', 'auth', 'secret'];
79
+ for (const param of sensitive) {
80
+ if (parsed.searchParams.has(param)) {
81
+ parsed.searchParams.set(param, '[REDACTED]');
82
+ }
83
+ }
84
+ return parsed.toString();
85
+ } catch {
86
+ return url.replace(/([?&](?:key|api_key|token|auth|secret)=)[^&]*/gi, '$1[REDACTED]');
87
+ }
88
+ }
89
+
90
+ async function postJson(
91
+ url: string,
92
+ headers: Record<string, string>,
93
+ body: unknown,
94
+ signal?: AbortSignal
95
+ ): Promise<any> {
96
+ const safeUrl = redactUrl(url);
97
+ let response: Response;
98
+ try {
99
+ response = await fetch(url, {
100
+ method: 'POST',
101
+ headers: { 'Content-Type': 'application/json', ...headers },
102
+ body: JSON.stringify(body),
103
+ signal,
104
+ });
105
+ } catch (err) {
106
+ if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError')) {
107
+ throw new ChatTransportError(`request to ${safeUrl} aborted (timeout)`);
108
+ }
109
+ throw new ChatTransportError(
110
+ `request to ${safeUrl} failed: ${err instanceof Error ? err.message : String(err)}`
111
+ );
112
+ }
113
+
114
+ if (!response.ok) {
115
+ let detail = '';
116
+ try {
117
+ detail = (await response.text()).slice(0, 500);
118
+ } catch {
119
+ detail = '';
120
+ }
121
+ throw new ChatTransportError(
122
+ `${safeUrl} returned ${response.status} ${response.statusText}${detail ? `: ${detail}` : ''}`,
123
+ response.status
124
+ );
125
+ }
126
+
127
+ try {
128
+ return await response.json();
129
+ } catch (err) {
130
+ // A 200 whose body is not JSON at all is a transport fault, not a model
131
+ // producing bad output: there is no model text to attribute it to.
132
+ throw new ChatTransportError(
133
+ `${safeUrl} returned a non-JSON body: ${err instanceof Error ? err.message : String(err)}`
134
+ );
135
+ }
136
+ }
137
+
138
+ /** Shared by the `openai` vendor and by the `remote` tier. */
139
+ function readOpenAiCompatibleReply(json: any): ChatReply {
140
+ const choice = json?.choices?.[0];
141
+ const message = choice?.message ?? {};
142
+ const content = typeof message.content === 'string' ? message.content : '';
143
+ const reasoning =
144
+ json?.usage?.completion_tokens_details?.reasoning_tokens ??
145
+ json?.usage?.reasoning_tokens ??
146
+ (typeof message.reasoning_content === 'string' && message.reasoning_content.length > 0 ? 1 : 0);
147
+
148
+ return {
149
+ content,
150
+ finish_reason: typeof choice?.finish_reason === 'string' ? choice.finish_reason : null,
151
+ model: typeof json?.model === 'string' ? json.model : null,
152
+ reasoning_tokens: Number(reasoning) || 0,
153
+ };
154
+ }
155
+
156
+ /** OpenAI-compatible chat completions: the `remote` tier (LM Studio, Ollama, vLLM). */
157
+ export function createRemoteAdapter(endpoint: string): GenerativeAdapter {
158
+ const base = endpoint.replace(/\/$/, '');
159
+ return {
160
+ name: `remote:${base}`,
161
+ async complete(req: ChatRequest): Promise<ChatReply> {
162
+ const apiKey = process.env.BRAIN_ENDPOINT_API_KEY?.trim() || 'no-key';
163
+ const json = await postJson(
164
+ `${base}/chat/completions`,
165
+ { Authorization: `Bearer ${apiKey}` },
166
+ {
167
+ model: req.model,
168
+ messages: [
169
+ { role: 'system', content: req.system },
170
+ { role: 'user', content: req.user },
171
+ ],
172
+ max_tokens: req.maxTokens,
173
+ temperature: 0,
174
+ },
175
+ req.signal
176
+ );
177
+ return readOpenAiCompatibleReply(json);
178
+ },
179
+ };
180
+ }
181
+
182
+ export function createOpenAiAdapter(): GenerativeAdapter {
183
+ return {
184
+ name: 'vendor:openai',
185
+ async complete(req: ChatRequest): Promise<ChatReply> {
186
+ const json = await postJson(
187
+ 'https://api.openai.com/v1/chat/completions',
188
+ { Authorization: `Bearer ${requireKey('openai')}` },
189
+ {
190
+ model: req.model,
191
+ messages: [
192
+ { role: 'system', content: req.system },
193
+ { role: 'user', content: req.user },
194
+ ],
195
+ max_tokens: req.maxTokens,
196
+ temperature: 0,
197
+ },
198
+ req.signal
199
+ );
200
+ return readOpenAiCompatibleReply(json);
201
+ },
202
+ };
203
+ }
204
+
205
+ export function createAnthropicAdapter(): GenerativeAdapter {
206
+ return {
207
+ name: 'vendor:anthropic',
208
+ async complete(req: ChatRequest): Promise<ChatReply> {
209
+ // Anthropic's shape differs from OpenAI's in two ways that matter here:
210
+ // the system prompt is a top-level field rather than a message, and the
211
+ // reply is a content block array.
212
+ const json = await postJson(
213
+ 'https://api.anthropic.com/v1/messages',
214
+ {
215
+ 'x-api-key': requireKey('anthropic'),
216
+ 'anthropic-version': '2023-06-01',
217
+ },
218
+ {
219
+ model: req.model,
220
+ system: req.system,
221
+ messages: [{ role: 'user', content: req.user }],
222
+ max_tokens: req.maxTokens,
223
+ temperature: 0,
224
+ },
225
+ req.signal
226
+ );
227
+
228
+ const blocks = Array.isArray(json?.content) ? json.content : [];
229
+ const firstText = blocks.find((b: any) => b?.type === 'text' && typeof b.text === 'string');
230
+ const content = typeof firstText?.text === 'string' ? firstText.text : '';
231
+
232
+ const stopReason = typeof json?.stop_reason === 'string' ? json.stop_reason : null;
233
+ return {
234
+ content,
235
+ // 'max_tokens' is Anthropic's name for OpenAI's 'length'.
236
+ finish_reason: stopReason === 'max_tokens' ? 'length' : stopReason,
237
+ model: typeof json?.model === 'string' ? json.model : null,
238
+ reasoning_tokens: blocks.some((b: any) => b?.type === 'thinking') ? 1 : 0,
239
+ };
240
+ },
241
+ };
242
+ }
243
+
244
+ export function createGoogleAdapter(): GenerativeAdapter {
245
+ return {
246
+ name: 'vendor:google',
247
+ async complete(req: ChatRequest): Promise<ChatReply> {
248
+ const key = requireKey('google');
249
+ const url =
250
+ `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(req.model)}` +
251
+ `:generateContent?key=${encodeURIComponent(key)}`;
252
+
253
+ const json = await postJson(
254
+ url,
255
+ { 'x-goog-api-key': key },
256
+ {
257
+ systemInstruction: { parts: [{ text: req.system }] },
258
+ contents: [{ role: 'user', parts: [{ text: req.user }] }],
259
+ generationConfig: { maxOutputTokens: req.maxTokens, temperature: 0 },
260
+ },
261
+ req.signal
262
+ );
263
+
264
+ const candidate = json?.candidates?.[0];
265
+ const parts = Array.isArray(candidate?.content?.parts) ? candidate.content.parts : [];
266
+ const content = parts
267
+ .map((p: any) => (typeof p?.text === 'string' ? p.text : ''))
268
+ .join('');
269
+
270
+ const finishReason =
271
+ typeof candidate?.finishReason === 'string' ? candidate.finishReason : null;
272
+ return {
273
+ content,
274
+ // 'MAX_TOKENS' is Google's name for OpenAI's 'length'.
275
+ finish_reason: finishReason === 'MAX_TOKENS' ? 'length' : finishReason,
276
+ model: typeof json?.modelVersion === 'string' ? json.modelVersion : null,
277
+ reasoning_tokens: Number(json?.usageMetadata?.thoughtsTokenCount) || 0,
278
+ };
279
+ },
280
+ };
281
+ }
282
+
283
+ export function createVendorAdapter(vendor: VendorName): GenerativeAdapter {
284
+ switch (vendor) {
285
+ case 'openai':
286
+ return createOpenAiAdapter();
287
+ case 'anthropic':
288
+ return createAnthropicAdapter();
289
+ case 'google':
290
+ return createGoogleAdapter();
291
+ }
292
+ }