@hyperwindmill/caretaker-cli 0.11.0

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 (275) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +25 -0
  3. package/dist/agents/dispatch.d.ts +35 -0
  4. package/dist/agents/dispatch.d.ts.map +1 -0
  5. package/dist/agents/dispatch.js +108 -0
  6. package/dist/agents/sync.d.ts +10 -0
  7. package/dist/agents/sync.d.ts.map +1 -0
  8. package/dist/agents/sync.js +95 -0
  9. package/dist/cli/index.d.ts +2 -0
  10. package/dist/cli/index.d.ts.map +1 -0
  11. package/dist/cli/index.js +50 -0
  12. package/dist/cli/run.d.ts +11 -0
  13. package/dist/cli/run.d.ts.map +1 -0
  14. package/dist/cli/run.js +89 -0
  15. package/dist/cli/web/fs.d.ts +3 -0
  16. package/dist/cli/web/fs.d.ts.map +1 -0
  17. package/dist/cli/web/fs.js +35 -0
  18. package/dist/cli/web/mcp_bridge.d.ts +7 -0
  19. package/dist/cli/web/mcp_bridge.d.ts.map +1 -0
  20. package/dist/cli/web/mcp_bridge.js +86 -0
  21. package/dist/cli/web/scheduler/heartbeat.d.ts +16 -0
  22. package/dist/cli/web/scheduler/heartbeat.d.ts.map +1 -0
  23. package/dist/cli/web/scheduler/heartbeat.js +181 -0
  24. package/dist/cli/web/scheduler/locks.d.ts +8 -0
  25. package/dist/cli/web/scheduler/locks.d.ts.map +1 -0
  26. package/dist/cli/web/scheduler/locks.js +7 -0
  27. package/dist/cli/web/scheduler/logs.d.ts +21 -0
  28. package/dist/cli/web/scheduler/logs.d.ts.map +1 -0
  29. package/dist/cli/web/scheduler/logs.js +62 -0
  30. package/dist/cli/web/scheduler/strategy.d.ts +6 -0
  31. package/dist/cli/web/scheduler/strategy.d.ts.map +1 -0
  32. package/dist/cli/web/scheduler/strategy.js +1 -0
  33. package/dist/cli/web/scheduler/task_review.d.ts +18 -0
  34. package/dist/cli/web/scheduler/task_review.d.ts.map +1 -0
  35. package/dist/cli/web/scheduler/task_review.js +77 -0
  36. package/dist/cli/web/scheduler/task_roles.d.ts +22 -0
  37. package/dist/cli/web/scheduler/task_roles.d.ts.map +1 -0
  38. package/dist/cli/web/scheduler/task_roles.js +70 -0
  39. package/dist/cli/web/scheduler/task_strategy.d.ts +2 -0
  40. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -0
  41. package/dist/cli/web/scheduler/task_strategy.js +437 -0
  42. package/dist/cli/web/scheduler/telegram.d.ts +7 -0
  43. package/dist/cli/web/scheduler/telegram.d.ts.map +1 -0
  44. package/dist/cli/web/scheduler/telegram.js +393 -0
  45. package/dist/cli/web/scheduler.d.ts +15 -0
  46. package/dist/cli/web/scheduler.d.ts.map +1 -0
  47. package/dist/cli/web/scheduler.js +60 -0
  48. package/dist/cli/web/server.d.ts +38 -0
  49. package/dist/cli/web/server.d.ts.map +1 -0
  50. package/dist/cli/web/server.js +970 -0
  51. package/dist/commands/loader.d.ts +37 -0
  52. package/dist/commands/loader.d.ts.map +1 -0
  53. package/dist/commands/loader.js +110 -0
  54. package/dist/harness/claude_code_runner.d.ts +47 -0
  55. package/dist/harness/claude_code_runner.d.ts.map +1 -0
  56. package/dist/harness/claude_code_runner.js +325 -0
  57. package/dist/harness/claude_code_stream.d.ts +32 -0
  58. package/dist/harness/claude_code_stream.d.ts.map +1 -0
  59. package/dist/harness/claude_code_stream.js +121 -0
  60. package/dist/harness/context_files.d.ts +23 -0
  61. package/dist/harness/context_files.d.ts.map +1 -0
  62. package/dist/harness/context_files.js +126 -0
  63. package/dist/harness/history.d.ts +4 -0
  64. package/dist/harness/history.d.ts.map +1 -0
  65. package/dist/harness/history.js +120 -0
  66. package/dist/harness/index.d.ts +8 -0
  67. package/dist/harness/index.d.ts.map +1 -0
  68. package/dist/harness/index.js +8 -0
  69. package/dist/harness/loop.d.ts +73 -0
  70. package/dist/harness/loop.d.ts.map +1 -0
  71. package/dist/harness/loop.js +373 -0
  72. package/dist/harness/model_limits.d.ts +25 -0
  73. package/dist/harness/model_limits.d.ts.map +1 -0
  74. package/dist/harness/model_limits.js +67 -0
  75. package/dist/harness/models.d.ts +9 -0
  76. package/dist/harness/models.d.ts.map +1 -0
  77. package/dist/harness/models.js +38 -0
  78. package/dist/harness/prelude.d.ts +21 -0
  79. package/dist/harness/prelude.d.ts.map +1 -0
  80. package/dist/harness/prelude.js +41 -0
  81. package/dist/harness/provider.d.ts +87 -0
  82. package/dist/harness/provider.d.ts.map +1 -0
  83. package/dist/harness/provider.js +140 -0
  84. package/dist/harness/runtime_info.d.ts +7 -0
  85. package/dist/harness/runtime_info.d.ts.map +1 -0
  86. package/dist/harness/runtime_info.js +15 -0
  87. package/dist/harness/think_tag_splitter.d.ts +33 -0
  88. package/dist/harness/think_tag_splitter.d.ts.map +1 -0
  89. package/dist/harness/think_tag_splitter.js +70 -0
  90. package/dist/harness/title.d.ts +17 -0
  91. package/dist/harness/title.d.ts.map +1 -0
  92. package/dist/harness/title.js +75 -0
  93. package/dist/harness/tools/builtin/bash.d.ts +3 -0
  94. package/dist/harness/tools/builtin/bash.d.ts.map +1 -0
  95. package/dist/harness/tools/builtin/bash.js +137 -0
  96. package/dist/harness/tools/builtin/edit.d.ts +6 -0
  97. package/dist/harness/tools/builtin/edit.d.ts.map +1 -0
  98. package/dist/harness/tools/builtin/edit.js +85 -0
  99. package/dist/harness/tools/builtin/fetch.d.ts +3 -0
  100. package/dist/harness/tools/builtin/fetch.d.ts.map +1 -0
  101. package/dist/harness/tools/builtin/fetch.js +75 -0
  102. package/dist/harness/tools/builtin/get_agent_context.d.ts +3 -0
  103. package/dist/harness/tools/builtin/get_agent_context.d.ts.map +1 -0
  104. package/dist/harness/tools/builtin/get_agent_context.js +76 -0
  105. package/dist/harness/tools/builtin/glob.d.ts +3 -0
  106. package/dist/harness/tools/builtin/glob.d.ts.map +1 -0
  107. package/dist/harness/tools/builtin/glob.js +52 -0
  108. package/dist/harness/tools/builtin/grep.d.ts +3 -0
  109. package/dist/harness/tools/builtin/grep.d.ts.map +1 -0
  110. package/dist/harness/tools/builtin/grep.js +126 -0
  111. package/dist/harness/tools/builtin/index.d.ts +23 -0
  112. package/dist/harness/tools/builtin/index.d.ts.map +1 -0
  113. package/dist/harness/tools/builtin/index.js +74 -0
  114. package/dist/harness/tools/builtin/invoke_agent.d.ts +3 -0
  115. package/dist/harness/tools/builtin/invoke_agent.d.ts.map +1 -0
  116. package/dist/harness/tools/builtin/invoke_agent.js +106 -0
  117. package/dist/harness/tools/builtin/invoke_command.d.ts +3 -0
  118. package/dist/harness/tools/builtin/invoke_command.d.ts.map +1 -0
  119. package/dist/harness/tools/builtin/invoke_command.js +42 -0
  120. package/dist/harness/tools/builtin/list_agents.d.ts +3 -0
  121. package/dist/harness/tools/builtin/list_agents.d.ts.map +1 -0
  122. package/dist/harness/tools/builtin/list_agents.js +32 -0
  123. package/dist/harness/tools/builtin/list_commands.d.ts +3 -0
  124. package/dist/harness/tools/builtin/list_commands.d.ts.map +1 -0
  125. package/dist/harness/tools/builtin/list_commands.js +27 -0
  126. package/dist/harness/tools/builtin/list_skills.d.ts +3 -0
  127. package/dist/harness/tools/builtin/list_skills.d.ts.map +1 -0
  128. package/dist/harness/tools/builtin/list_skills.js +24 -0
  129. package/dist/harness/tools/builtin/multiedit.d.ts +3 -0
  130. package/dist/harness/tools/builtin/multiedit.d.ts.map +1 -0
  131. package/dist/harness/tools/builtin/multiedit.js +88 -0
  132. package/dist/harness/tools/builtin/read_attachment.d.ts +3 -0
  133. package/dist/harness/tools/builtin/read_attachment.d.ts.map +1 -0
  134. package/dist/harness/tools/builtin/read_attachment.js +128 -0
  135. package/dist/harness/tools/builtin/read_document.d.ts +37 -0
  136. package/dist/harness/tools/builtin/read_document.d.ts.map +1 -0
  137. package/dist/harness/tools/builtin/read_document.js +238 -0
  138. package/dist/harness/tools/builtin/read_file.d.ts +3 -0
  139. package/dist/harness/tools/builtin/read_file.d.ts.map +1 -0
  140. package/dist/harness/tools/builtin/read_file.js +141 -0
  141. package/dist/harness/tools/builtin/read_image.d.ts +3 -0
  142. package/dist/harness/tools/builtin/read_image.d.ts.map +1 -0
  143. package/dist/harness/tools/builtin/read_image.js +80 -0
  144. package/dist/harness/tools/builtin/read_skill.d.ts +3 -0
  145. package/dist/harness/tools/builtin/read_skill.d.ts.map +1 -0
  146. package/dist/harness/tools/builtin/read_skill.js +30 -0
  147. package/dist/harness/tools/builtin/shell-env.d.ts +55 -0
  148. package/dist/harness/tools/builtin/shell-env.d.ts.map +1 -0
  149. package/dist/harness/tools/builtin/shell-env.js +181 -0
  150. package/dist/harness/tools/builtin/task_tools.d.ts +21 -0
  151. package/dist/harness/tools/builtin/task_tools.d.ts.map +1 -0
  152. package/dist/harness/tools/builtin/task_tools.js +708 -0
  153. package/dist/harness/tools/builtin/write.d.ts +3 -0
  154. package/dist/harness/tools/builtin/write.d.ts.map +1 -0
  155. package/dist/harness/tools/builtin/write.js +56 -0
  156. package/dist/harness/tools/index.d.ts +6 -0
  157. package/dist/harness/tools/index.d.ts.map +1 -0
  158. package/dist/harness/tools/index.js +7 -0
  159. package/dist/harness/tools/instance.d.ts +3 -0
  160. package/dist/harness/tools/instance.d.ts.map +1 -0
  161. package/dist/harness/tools/instance.js +19 -0
  162. package/dist/harness/tools/registry.d.ts +21 -0
  163. package/dist/harness/tools/registry.d.ts.map +1 -0
  164. package/dist/harness/tools/registry.js +33 -0
  165. package/dist/harness/tools/resolve.d.ts +5 -0
  166. package/dist/harness/tools/resolve.d.ts.map +1 -0
  167. package/dist/harness/tools/resolve.js +60 -0
  168. package/dist/harness/tools/sandbox.d.ts +6 -0
  169. package/dist/harness/tools/sandbox.d.ts.map +1 -0
  170. package/dist/harness/tools/sandbox.js +23 -0
  171. package/dist/harness/tools/types.d.ts +80 -0
  172. package/dist/harness/tools/types.d.ts.map +1 -0
  173. package/dist/harness/tools/types.js +16 -0
  174. package/dist/index.d.ts +3 -0
  175. package/dist/index.d.ts.map +1 -0
  176. package/dist/index.js +46 -0
  177. package/dist/lib/encryption.d.ts +24 -0
  178. package/dist/lib/encryption.d.ts.map +1 -0
  179. package/dist/lib/encryption.js +163 -0
  180. package/dist/lib/open_url.d.ts +9 -0
  181. package/dist/lib/open_url.d.ts.map +1 -0
  182. package/dist/lib/open_url.js +23 -0
  183. package/dist/lib/task_git.d.ts +11 -0
  184. package/dist/lib/task_git.d.ts.map +1 -0
  185. package/dist/lib/task_git.js +100 -0
  186. package/dist/mcp/adapter.d.ts +9 -0
  187. package/dist/mcp/adapter.d.ts.map +1 -0
  188. package/dist/mcp/adapter.js +74 -0
  189. package/dist/mcp/client.d.ts +50 -0
  190. package/dist/mcp/client.d.ts.map +1 -0
  191. package/dist/mcp/client.js +243 -0
  192. package/dist/mcp/oauth.d.ts +30 -0
  193. package/dist/mcp/oauth.d.ts.map +1 -0
  194. package/dist/mcp/oauth.js +171 -0
  195. package/dist/mcp/oauth_callback.d.ts +9 -0
  196. package/dist/mcp/oauth_callback.d.ts.map +1 -0
  197. package/dist/mcp/oauth_callback.js +51 -0
  198. package/dist/mcp/oauth_store.d.ts +22 -0
  199. package/dist/mcp/oauth_store.d.ts.map +1 -0
  200. package/dist/mcp/oauth_store.js +40 -0
  201. package/dist/mcp/server_manager.d.ts +49 -0
  202. package/dist/mcp/server_manager.d.ts.map +1 -0
  203. package/dist/mcp/server_manager.js +271 -0
  204. package/dist/plugins/fetchers/git.d.ts +67 -0
  205. package/dist/plugins/fetchers/git.d.ts.map +1 -0
  206. package/dist/plugins/fetchers/git.js +130 -0
  207. package/dist/plugins/fetchers/path.d.ts +4 -0
  208. package/dist/plugins/fetchers/path.d.ts.map +1 -0
  209. package/dist/plugins/fetchers/path.js +22 -0
  210. package/dist/plugins/loader.d.ts +31 -0
  211. package/dist/plugins/loader.d.ts.map +1 -0
  212. package/dist/plugins/loader.js +146 -0
  213. package/dist/plugins/manifest.d.ts +56 -0
  214. package/dist/plugins/manifest.d.ts.map +1 -0
  215. package/dist/plugins/manifest.js +389 -0
  216. package/dist/plugins/refresh_on_start.d.ts +7 -0
  217. package/dist/plugins/refresh_on_start.d.ts.map +1 -0
  218. package/dist/plugins/refresh_on_start.js +35 -0
  219. package/dist/plugins/source_manager.d.ts +27 -0
  220. package/dist/plugins/source_manager.d.ts.map +1 -0
  221. package/dist/plugins/source_manager.js +211 -0
  222. package/dist/plugins/types.d.ts +41 -0
  223. package/dist/plugins/types.d.ts.map +1 -0
  224. package/dist/plugins/types.js +11 -0
  225. package/dist/session/context_usage.d.ts +13 -0
  226. package/dist/session/context_usage.d.ts.map +1 -0
  227. package/dist/session/context_usage.js +25 -0
  228. package/dist/session/index.d.ts +7 -0
  229. package/dist/session/index.d.ts.map +1 -0
  230. package/dist/session/index.js +5 -0
  231. package/dist/session/store.d.ts +68 -0
  232. package/dist/session/store.d.ts.map +1 -0
  233. package/dist/session/store.js +268 -0
  234. package/dist/session/types.d.ts +60 -0
  235. package/dist/session/types.d.ts.map +1 -0
  236. package/dist/session/types.js +11 -0
  237. package/dist/store/db.d.ts +64 -0
  238. package/dist/store/db.d.ts.map +1 -0
  239. package/dist/store/db.js +91 -0
  240. package/dist/store/json.d.ts +21 -0
  241. package/dist/store/json.d.ts.map +1 -0
  242. package/dist/store/json.js +135 -0
  243. package/dist/tui/agents.d.ts +4 -0
  244. package/dist/tui/agents.d.ts.map +1 -0
  245. package/dist/tui/agents.js +616 -0
  246. package/dist/tui/app.d.ts +2 -0
  247. package/dist/tui/app.d.ts.map +1 -0
  248. package/dist/tui/app.js +32 -0
  249. package/dist/tui/chat.d.ts +10 -0
  250. package/dist/tui/chat.d.ts.map +1 -0
  251. package/dist/tui/chat.js +258 -0
  252. package/dist/tui/logo.d.ts +2 -0
  253. package/dist/tui/logo.d.ts.map +1 -0
  254. package/dist/tui/logo.js +10 -0
  255. package/dist/tui/mcp_servers.d.ts +4 -0
  256. package/dist/tui/mcp_servers.d.ts.map +1 -0
  257. package/dist/tui/mcp_servers.js +287 -0
  258. package/dist/tui/plugins.d.ts +4 -0
  259. package/dist/tui/plugins.d.ts.map +1 -0
  260. package/dist/tui/plugins.js +234 -0
  261. package/dist/tui/providers.d.ts +4 -0
  262. package/dist/tui/providers.d.ts.map +1 -0
  263. package/dist/tui/providers.js +178 -0
  264. package/dist/tui/tool_picker_state.d.ts +9 -0
  265. package/dist/tui/tool_picker_state.d.ts.map +1 -0
  266. package/dist/tui/tool_picker_state.js +37 -0
  267. package/dist/types.d.ts +2 -0
  268. package/dist/types.d.ts.map +1 -0
  269. package/dist/types.js +1 -0
  270. package/dist/webview/index.html +22 -0
  271. package/dist/webview/standalone.css +2732 -0
  272. package/dist/webview/standalone.css.map +7 -0
  273. package/dist/webview/standalone.js +20641 -0
  274. package/dist/webview/standalone.js.map +7 -0
  275. package/package.json +120 -0
@@ -0,0 +1,373 @@
1
+ // Agent loop, ported from caretaker server's src/runner/openai_style.ts.
2
+ // Stripped of: DB persistence layer (replaced by a callback-based hand-off
3
+ // to the session store), MCP dispatch (in-process tools instead), permission
4
+ // gate, plugin skills, context files, harness prelude, self-introspection
5
+ // tool, image-attachment tool results.
6
+ //
7
+ // Now supports multi-turn replay: pass `opts.history` (prior persisted
8
+ // MessageRecords from the session store) and the loop will reconstruct the
9
+ // chat-completions message array via mapMessagesToChat. The new user prompt
10
+ // is appended after the replayed history. The caller is responsible for
11
+ // persisting the user prompt before calling run(); the loop emits assistant
12
+ // and tool messages via `cb.onMessage` as they are produced.
13
+ import { readFileSync } from 'node:fs';
14
+ import { join } from 'node:path';
15
+ import { assistantMessage, toolMessage, saveAttachment, attachmentsDir } from '../session/store.js';
16
+ import { buildRequestBody, readStream } from './provider.js';
17
+ import { mapMessagesToChat } from './history.js';
18
+ import { toOpenAiTool, } from './tools/index.js';
19
+ import { withHarnessPrelude } from './prelude.js';
20
+ import { formatRuntimeInfoBlock } from './runtime_info.js';
21
+ import { loadContextFiles, formatContextBlock, resolveFileReferences } from './context_files.js';
22
+ let fetchImpl = globalThis.fetch.bind(globalThis);
23
+ /** Testing hook — override the fetch used by the runner. */
24
+ export function __setFetch(f) {
25
+ fetchImpl = f;
26
+ }
27
+ export function __resetFetch() {
28
+ fetchImpl = globalThis.fetch.bind(globalThis);
29
+ }
30
+ export async function run(opts, cb = {}) {
31
+ if (opts.provider.type === 'claude-code') {
32
+ // Single dispatch point: claude-code providers get the whole loop
33
+ // replaced by the Claude Code CLI (see claude_code_runner.ts).
34
+ const { runClaudeCode } = await import('./claude_code_runner.js');
35
+ return runClaudeCode(opts, cb);
36
+ }
37
+ const { agent, provider, tools, prompt } = opts;
38
+ const baseUrl = provider.endpoint.replace(/\/+$/, '');
39
+ const endpoint = `${baseUrl}/v1/chat/completions`;
40
+ // 0 → unlimited; >0 → that cap; anything else (negative / NaN) → 30 fallback.
41
+ const maxTurns = agent.maxTurns === 0 ? Infinity : agent.maxTurns > 0 ? agent.maxTurns : 30;
42
+ const openAiTools = tools.map(toOpenAiTool);
43
+ const toolByName = new Map(tools.map((t) => [t.name, t]));
44
+ // Tool execution context: signal defaults to a never-aborting one so tools
45
+ // that always check `ctx.signal.aborted` work even when the caller passed
46
+ // no signal.
47
+ const toolCtx = {
48
+ signal: opts.signal ?? new AbortController().signal,
49
+ workingDir: opts.workingDir ?? process.cwd(),
50
+ readPaths: new Set(),
51
+ activePlugins: agent.plugins ?? [],
52
+ callerAgent: agent,
53
+ dispatchDepth: opts.dispatchDepth ?? 0,
54
+ confirmTool: cb.confirmTool,
55
+ sessionId: opts.sessionId,
56
+ };
57
+ // System prompt assembly, applied unconditionally (the prelude and
58
+ // context-files block are harness-level concerns, not tied to which tools
59
+ // the agent has active right now):
60
+ // 1. Resolve @<file> refs in the agent's prompt
61
+ // 2. Prepend AGENTS.md / CLAUDE.md / GEMINI.md walk-up + globals
62
+ // 3. Prepend the harness prelude
63
+ let effectiveSystemPrompt = await resolveFileReferences(agent.systemPrompt ?? '', toolCtx.workingDir);
64
+ const ctxEntries = await loadContextFiles(toolCtx.workingDir);
65
+ const ctxBlock = formatContextBlock(ctxEntries);
66
+ const withCtx = ctxBlock
67
+ ? `${ctxBlock}\n\n${effectiveSystemPrompt}`.trim()
68
+ : effectiveSystemPrompt;
69
+ effectiveSystemPrompt = withHarnessPrelude(withCtx);
70
+ // Per-run identity block — static facts (name, model, provider,
71
+ // working_dir) the agent should know without spending a tool call.
72
+ // Live token usage / context-window % stays in `get_agent_context`.
73
+ const runtimeBlock = formatRuntimeInfoBlock({
74
+ agentName: agent.name,
75
+ model: agent.model,
76
+ provider: agent.provider,
77
+ workingDir: toolCtx.workingDir,
78
+ });
79
+ effectiveSystemPrompt = `${effectiveSystemPrompt}\n\n${runtimeBlock}`.trim();
80
+ // Plugin skills are no longer injected here. Agents with active plugins
81
+ // get the `list_skills` / `read_skill` tools (added by resolveAgentTools
82
+ // at the call site) and pull the SKILL.md content on demand.
83
+ const chat = [];
84
+ if (effectiveSystemPrompt)
85
+ chat.push({ role: 'system', content: effectiveSystemPrompt });
86
+ if (opts.history && opts.history.length > 0) {
87
+ for (const m of mapMessagesToChat(opts.history, opts.sessionId))
88
+ chat.push(m);
89
+ }
90
+ if (opts.promptAttachments && opts.promptAttachments.length > 0) {
91
+ let textContent = prompt;
92
+ const imageParts = [];
93
+ for (const att of opts.promptAttachments) {
94
+ const displayName = att.name || att.id;
95
+ textContent += `\n\n[Allegato: ${displayName} (ID: ${att.id})]`;
96
+ if (att.mime.startsWith('image/')) {
97
+ try {
98
+ const filePath = join(attachmentsDir(opts.sessionId || 'default'), att.id);
99
+ const data = readFileSync(filePath);
100
+ const base64 = data.toString('base64');
101
+ imageParts.push({
102
+ type: 'image_url',
103
+ image_url: {
104
+ url: `data:${att.mime};base64,${base64}`,
105
+ },
106
+ });
107
+ }
108
+ catch (err) {
109
+ console.error(`[loop] failed to read prompt image attachment ${att.id}:`, err);
110
+ }
111
+ }
112
+ }
113
+ if (imageParts.length > 0) {
114
+ chat.push({
115
+ role: 'user',
116
+ content: [
117
+ { type: 'text', text: textContent },
118
+ ...imageParts,
119
+ ],
120
+ });
121
+ }
122
+ else {
123
+ chat.push({ role: 'user', content: textContent });
124
+ }
125
+ }
126
+ else {
127
+ chat.push({ role: 'user', content: prompt });
128
+ }
129
+ let fullText = '';
130
+ let totalToolCalls = 0;
131
+ const cumulative = {
132
+ input: 0,
133
+ output: 0,
134
+ cacheRead: 0,
135
+ cacheWrite: 0,
136
+ reasoning: 0,
137
+ };
138
+ // Shared object — the loop mutates `lastTurn` and `cumulative` in place
139
+ // each turn, and `get_agent_context` reads from this same reference at
140
+ // tool execution time so it always sees the latest values.
141
+ const liveUsage = {
142
+ lastTurn: undefined,
143
+ cumulative,
144
+ };
145
+ toolCtx.liveUsage = liveUsage;
146
+ const safeEmit = async (msg) => {
147
+ try {
148
+ await cb.onMessage?.(msg);
149
+ }
150
+ catch (err) {
151
+ // Persistence is best-effort within a turn. The model has already
152
+ // produced output and tools have already run; aborting now would
153
+ // diverge model state from on-disk state worse than logging and
154
+ // continuing.
155
+ console.error('[loop] onMessage handler threw:', err);
156
+ }
157
+ };
158
+ for (let turn = 0; turn < maxTurns; turn++) {
159
+ if (opts.signal?.aborted)
160
+ return { text: fullText, toolCalls: totalToolCalls, usage: cumulative, stop: 'aborted' };
161
+ const body = buildRequestBody({ messages: chat, tools: openAiTools, model: agent.model });
162
+ const headers = { 'Content-Type': 'application/json' };
163
+ if (provider.apiKey)
164
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
165
+ const response = await fetchImpl(endpoint, {
166
+ method: 'POST',
167
+ headers,
168
+ body: JSON.stringify(body),
169
+ signal: opts.signal,
170
+ });
171
+ if (!response.ok) {
172
+ const errText = (await response.text().catch(() => '')).slice(0, 8192);
173
+ throw new Error(`provider ${provider.name} returned ${response.status}: ${errText}`);
174
+ }
175
+ let assistantText = '';
176
+ const assistantParts = [];
177
+ let turnUsage;
178
+ const pending = new Map();
179
+ // Merge consecutive same-kind streamed deltas into a single part. This
180
+ // keeps the persisted shape compact and round-trips cleanly through
181
+ // mapMessagesToChat.
182
+ const pushTextPart = (text) => {
183
+ if (text.length === 0)
184
+ return;
185
+ const last = assistantParts[assistantParts.length - 1];
186
+ if (last && last.type === 'text')
187
+ last.text += text;
188
+ else
189
+ assistantParts.push({ type: 'text', text });
190
+ };
191
+ const pushThinkingPart = (text) => {
192
+ if (text.length === 0)
193
+ return;
194
+ const last = assistantParts[assistantParts.length - 1];
195
+ if (last && last.type === 'thinking')
196
+ last.text += text;
197
+ else
198
+ assistantParts.push({ type: 'thinking', text });
199
+ };
200
+ await readStream(response, (evt) => {
201
+ switch (evt.kind) {
202
+ case 'content':
203
+ assistantText += evt.text;
204
+ fullText += evt.text;
205
+ cb.onChunk?.(evt.text);
206
+ pushTextPart(evt.text);
207
+ break;
208
+ case 'thinking':
209
+ cb.onThinking?.(evt.text);
210
+ pushThinkingPart(evt.text);
211
+ break;
212
+ case 'tool_call_delta': {
213
+ const rec = pending.get(evt.index) ?? { id: '', name: '', args: '' };
214
+ if (evt.id)
215
+ rec.id = evt.id;
216
+ if (evt.name)
217
+ rec.name = evt.name;
218
+ if (evt.argumentsDelta)
219
+ rec.args += evt.argumentsDelta;
220
+ pending.set(evt.index, rec);
221
+ break;
222
+ }
223
+ case 'usage':
224
+ turnUsage = evt.usage;
225
+ liveUsage.lastTurn = evt.usage;
226
+ cb.onUsage?.(evt.usage);
227
+ cumulative.input += evt.usage.input;
228
+ cumulative.output += evt.usage.output;
229
+ cumulative.cacheRead = (cumulative.cacheRead ?? 0) + (evt.usage.cacheRead ?? 0);
230
+ cumulative.cacheWrite = (cumulative.cacheWrite ?? 0) + (evt.usage.cacheWrite ?? 0);
231
+ cumulative.reasoning = (cumulative.reasoning ?? 0) + (evt.usage.reasoning ?? 0);
232
+ break;
233
+ case 'finish':
234
+ case 'done':
235
+ break;
236
+ }
237
+ });
238
+ if (opts.signal?.aborted)
239
+ return { text: fullText, toolCalls: totalToolCalls, usage: cumulative, stop: 'aborted' };
240
+ // Build the model-facing assistant ChatMessage and the persistable
241
+ // assistant MessageRecord in one pass: tool_use parts mirror the
242
+ // tool_calls array on the chat-completions payload.
243
+ const toolCalls = pending.size > 0
244
+ ? [...pending.entries()]
245
+ .sort(([a], [b]) => a - b)
246
+ .map(([, rec]) => ({
247
+ id: rec.id,
248
+ type: 'function',
249
+ function: { name: rec.name, arguments: rec.args },
250
+ }))
251
+ : [];
252
+ for (const tc of toolCalls) {
253
+ let parsedArgs = {};
254
+ try {
255
+ parsedArgs = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
256
+ }
257
+ catch {
258
+ parsedArgs = {};
259
+ }
260
+ assistantParts.push({
261
+ type: 'tool_use',
262
+ id: tc.id,
263
+ name: tc.function.name,
264
+ args: parsedArgs,
265
+ });
266
+ }
267
+ // Persist the assistant turn (parts + usage). Caller serializes via the
268
+ // session store; we await so writes are ordered.
269
+ const assistantMsg = assistantMessage(assistantParts, turnUsage);
270
+ await safeEmit(assistantMsg);
271
+ // Mirror the assistant turn into the chat-completions array for the next iteration.
272
+ chat.push({
273
+ role: 'assistant',
274
+ content: assistantText.length > 0 ? assistantText : null,
275
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
276
+ });
277
+ if (toolCalls.length === 0) {
278
+ return { text: fullText, toolCalls: totalToolCalls, usage: cumulative, stop: 'done' };
279
+ }
280
+ for (const tc of toolCalls) {
281
+ let parsedArgs = {};
282
+ try {
283
+ parsedArgs = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
284
+ }
285
+ catch {
286
+ parsedArgs = {};
287
+ }
288
+ cb.onToolCall?.(tc.id, tc.function.name, parsedArgs);
289
+ totalToolCalls++;
290
+ let content = '';
291
+ let attRecords;
292
+ let attachmentsToPass;
293
+ const t = toolByName.get(tc.function.name);
294
+ if (!t) {
295
+ content = `Error: unknown tool "${tc.function.name}"`;
296
+ }
297
+ else {
298
+ let gateOutcome = 'proceed';
299
+ if (cb.confirmTool) {
300
+ try {
301
+ const decision = await cb.confirmTool(tc.id, tc.function.name, parsedArgs);
302
+ gateOutcome = decision === 'reject' ? 'reject' : 'proceed';
303
+ }
304
+ catch (err) {
305
+ // Treat a thrown gate as a rejection so a buggy UI can never
306
+ // silently auto-approve. The tool message records why.
307
+ gateOutcome = `Error: confirm gate threw: ${err instanceof Error ? err.message : String(err)}`;
308
+ }
309
+ }
310
+ if (gateOutcome === 'proceed') {
311
+ try {
312
+ const result = await t.execute(parsedArgs, toolCtx);
313
+ content = result.content;
314
+ if (result.attachments && result.attachments.length > 0) {
315
+ attRecords = [];
316
+ attachmentsToPass = [];
317
+ const sId = opts.sessionId || 'default';
318
+ for (const att of result.attachments) {
319
+ const ext = mimeToExt(att.mime);
320
+ const id = await saveAttachment(sId, att.data, ext);
321
+ attRecords.push({ mime: att.mime, id });
322
+ attachmentsToPass.push({ mime: att.mime, base64: att.data.toString('base64') });
323
+ }
324
+ }
325
+ }
326
+ catch (err) {
327
+ content = `Error: ${err instanceof Error ? err.message : String(err)}`;
328
+ }
329
+ }
330
+ else if (gateOutcome === 'reject') {
331
+ content = 'Error: rejected by user';
332
+ }
333
+ else {
334
+ content = gateOutcome;
335
+ }
336
+ }
337
+ // Persist the tool turn.
338
+ const toolMsg = toolMessage(tc.id, content, attRecords);
339
+ await safeEmit(toolMsg);
340
+ chat.push({ role: 'tool', tool_call_id: tc.id, content });
341
+ if (attachmentsToPass && attachmentsToPass.length > 0) {
342
+ const parts = [{ type: 'text', text: 'Attachment from tool:' }];
343
+ for (const att of attachmentsToPass) {
344
+ parts.push({
345
+ type: 'image_url',
346
+ image_url: {
347
+ url: `data:${att.mime};base64,${att.base64}`,
348
+ },
349
+ });
350
+ }
351
+ chat.push({ role: 'user', content: parts });
352
+ }
353
+ cb.onToolResult?.(tc.id, content);
354
+ }
355
+ }
356
+ return { text: fullText, toolCalls: totalToolCalls, usage: cumulative, stop: 'max_turns' };
357
+ }
358
+ function mimeToExt(mime) {
359
+ const map = {
360
+ 'image/png': '.png',
361
+ 'image/jpeg': '.jpg',
362
+ 'image/webp': '.webp',
363
+ 'image/gif': '.gif',
364
+ 'application/pdf': '.pdf',
365
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
366
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
367
+ 'application/vnd.ms-excel': '.xls',
368
+ 'text/plain': '.txt',
369
+ 'text/markdown': '.md',
370
+ 'application/json': '.json',
371
+ };
372
+ return map[mime.toLowerCase()] || '';
373
+ }
@@ -0,0 +1,25 @@
1
+ type ModelsDevModel = {
2
+ id?: string;
3
+ limit?: {
4
+ context?: number;
5
+ output?: number;
6
+ };
7
+ };
8
+ type ModelsDevProvider = {
9
+ id?: string;
10
+ models?: Record<string, ModelsDevModel>;
11
+ };
12
+ type ModelsDevApi = Record<string, ModelsDevProvider>;
13
+ /** Flatten the models.dev API JSON into a flat `model_id → context_tokens` map. */
14
+ export declare function parseModelsDevApi(api: ModelsDevApi): Map<string, number>;
15
+ /** Populate the registry from models.dev. Idempotent; safe to call multiple times.
16
+ * On failure, the existing cache (possibly empty) is retained. */
17
+ export declare function refreshModelLimits(): Promise<void>;
18
+ /** Boot-time hook: kicks off a background refresh and schedules a periodic one.
19
+ * Awaits nothing; the meter degrades gracefully until the first fetch lands. */
20
+ export declare function initModelLimits(): void;
21
+ export declare function resolveContextWindow(model: string): number | null;
22
+ /** Test hook — replace the in-memory registry directly. */
23
+ export declare function __setRegistryForTesting(map: Map<string, number>): void;
24
+ export {};
25
+ //# sourceMappingURL=model_limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model_limits.d.ts","sourceRoot":"","sources":["../../src/harness/model_limits.ts"],"names":[],"mappings":"AAMA,KAAK,cAAc,GAAG;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAAC;AACrF,KAAK,iBAAiB,GAAG;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;CAAE,CAAC;AAClF,KAAK,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;AAEtD,mFAAmF;AACnF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,YAAY,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAUxE;AAgBD;mEACmE;AACnE,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC,CAGxD;AAED;iFACiF;AACjF,wBAAgB,eAAe,IAAI,IAAI,CAOtC;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CASjE;AAED,2DAA2D;AAC3D,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAEtE"}
@@ -0,0 +1,67 @@
1
+ const MODELS_DEV_URL = 'https://models.dev/api.json';
2
+ const REFRESH_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24h
3
+ let registry = new Map();
4
+ let refreshTimer = null;
5
+ /** Flatten the models.dev API JSON into a flat `model_id → context_tokens` map. */
6
+ export function parseModelsDevApi(api) {
7
+ const out = new Map();
8
+ for (const provider of Object.values(api ?? {})) {
9
+ const models = provider?.models ?? {};
10
+ for (const [id, m] of Object.entries(models)) {
11
+ const ctx = m?.limit?.context;
12
+ if (typeof ctx === 'number' && ctx > 0)
13
+ out.set(id, ctx);
14
+ }
15
+ }
16
+ return out;
17
+ }
18
+ async function fetchOnce() {
19
+ try {
20
+ const ctrl = new AbortController();
21
+ const t = setTimeout(() => ctrl.abort(), 10_000);
22
+ const res = await fetch(MODELS_DEV_URL, { signal: ctrl.signal });
23
+ clearTimeout(t);
24
+ if (!res.ok)
25
+ return null;
26
+ const json = (await res.json());
27
+ return parseModelsDevApi(json);
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /** Populate the registry from models.dev. Idempotent; safe to call multiple times.
34
+ * On failure, the existing cache (possibly empty) is retained. */
35
+ export async function refreshModelLimits() {
36
+ const fresh = await fetchOnce();
37
+ if (fresh && fresh.size > 0)
38
+ registry = fresh;
39
+ }
40
+ /** Boot-time hook: kicks off a background refresh and schedules a periodic one.
41
+ * Awaits nothing; the meter degrades gracefully until the first fetch lands. */
42
+ export function initModelLimits() {
43
+ void refreshModelLimits();
44
+ if (refreshTimer)
45
+ return;
46
+ refreshTimer = setInterval(() => {
47
+ void refreshModelLimits();
48
+ }, REFRESH_INTERVAL_MS);
49
+ if (typeof refreshTimer.unref === 'function')
50
+ refreshTimer.unref();
51
+ }
52
+ export function resolveContextWindow(model) {
53
+ const direct = registry.get(model);
54
+ if (typeof direct === 'number' && direct > 0)
55
+ return direct;
56
+ const stripped = model.replace(/[-:]cloud$/, '');
57
+ if (stripped !== model) {
58
+ const fallback = registry.get(stripped);
59
+ if (typeof fallback === 'number' && fallback > 0)
60
+ return fallback;
61
+ }
62
+ return null;
63
+ }
64
+ /** Test hook — replace the in-memory registry directly. */
65
+ export function __setRegistryForTesting(map) {
66
+ registry = map;
67
+ }
@@ -0,0 +1,9 @@
1
+ export type ModelsResult = {
2
+ ok: true;
3
+ ids: string[];
4
+ } | {
5
+ ok: false;
6
+ error: string;
7
+ };
8
+ export declare function fetchOpenAiStyleModels(baseUrl: string, apiKey: string | null, signal?: AbortSignal): Promise<ModelsResult>;
9
+ //# sourceMappingURL=models.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../../src/harness/models.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,YAAY,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,GAAG,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtF,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,YAAY,CAAC,CA+BvB"}
@@ -0,0 +1,38 @@
1
+ // Ported from caretaker server's src/api/models.ts (fetchOpenAiStyleModels).
2
+ // Queries /v1/models on an OpenAI-compatible provider; returns the list of ids
3
+ // or a structured error. 5s timeout.
4
+ export async function fetchOpenAiStyleModels(baseUrl, apiKey, signal) {
5
+ const normalized = baseUrl.replace(/\/+$/, '');
6
+ const ac = new AbortController();
7
+ const timer = setTimeout(() => ac.abort(), 5_000);
8
+ if (signal)
9
+ signal.addEventListener('abort', () => ac.abort(), { once: true });
10
+ try {
11
+ const headers = {};
12
+ if (apiKey)
13
+ headers.Authorization = `Bearer ${apiKey}`;
14
+ const res = await fetch(`${normalized}/v1/models`, { headers, signal: ac.signal });
15
+ if (!res.ok) {
16
+ const text = (await res.text().catch(() => '')).slice(0, 512);
17
+ return { ok: false, error: `Provider returned ${res.status}: ${text}` };
18
+ }
19
+ const contentType = res.headers.get('content-type') ?? '';
20
+ if (!contentType.toLowerCase().includes('json')) {
21
+ const text = (await res.text().catch(() => '')).slice(0, 200);
22
+ return {
23
+ ok: false,
24
+ error: `Provider at ${normalized}/v1/models did not return JSON (content-type: ${contentType || 'unknown'}). First bytes: ${text.replace(/\s+/g, ' ')}`,
25
+ };
26
+ }
27
+ const payload = (await res.json());
28
+ const ids = (payload.data ?? []).map((m) => m.id).filter(Boolean);
29
+ return { ok: true, ids };
30
+ }
31
+ catch (err) {
32
+ const message = err instanceof Error ? err.message : String(err);
33
+ return { ok: false, error: `Failed to fetch models: ${message}` };
34
+ }
35
+ finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * System-prompt prelude prepended to every agent's system prompt by the loop.
3
+ *
4
+ * Two parts:
5
+ * 1. A short "what kind of agent you are" identity statement built around
6
+ * the CARE acronym (caretaker → care).
7
+ * 2. Harness-level conventions that aren't tied to any specific tool —
8
+ * function-calling protocol, message-text discipline, sandbox rules,
9
+ * output caps.
10
+ *
11
+ * Applied unconditionally: chat-only agents get it too, with no harm. The
12
+ * text is intended to grow as harness-wide conventions emerge — add new
13
+ * bullets to the "harness conventions" section.
14
+ */
15
+ export declare const HARNESS_PRELUDE: string;
16
+ /**
17
+ * Combine the agent system prompt with the harness prelude.
18
+ * If the agent prompt is empty, return the prelude alone.
19
+ */
20
+ export declare function withHarnessPrelude(agentSystemPrompt: string | undefined): string;
21
+ //# sourceMappingURL=prelude.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prelude.d.ts","sourceRoot":"","sources":["../../src/harness/prelude.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,eAAe,QAgBhB,CAAC;AAEb;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,iBAAiB,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAIhF"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * System-prompt prelude prepended to every agent's system prompt by the loop.
3
+ *
4
+ * Two parts:
5
+ * 1. A short "what kind of agent you are" identity statement built around
6
+ * the CARE acronym (caretaker → care).
7
+ * 2. Harness-level conventions that aren't tied to any specific tool —
8
+ * function-calling protocol, message-text discipline, sandbox rules,
9
+ * output caps.
10
+ *
11
+ * Applied unconditionally: chat-only agents get it too, with no harm. The
12
+ * text is intended to grow as harness-wide conventions emerge — add new
13
+ * bullets to the "harness conventions" section.
14
+ */
15
+ export const HARNESS_PRELUDE = [
16
+ 'You are a caretaker agent. This means you:',
17
+ '',
18
+ '- CARE about your goal: tasks are successful when the user is satisfied.',
19
+ '- CARE about your environment: always check your actions are never harmful in any way.',
20
+ "- CARE about your project: every change should leave it better than you found it. When the requested path won't, push back and propose a better one.",
21
+ '',
22
+ 'A few harness conventions:',
23
+ '',
24
+ "- Tool invocations go through your provider's function-calling protocol. Never paste tool-call JSON, code fences, or pseudo-XML into your assistant text — that text is shown to the user; only structured tool calls execute.",
25
+ '',
26
+ '- Do not output JSON-encoded message envelopes (e.g. arrays of {"type":"text",...} or {"type":"thinking",...} blocks) in your replies. The harness serializes messages for you; your text reply is plain user-facing content (markdown is fine), nothing more.',
27
+ '',
28
+ "- File-system tools are sandboxed to the agent's working directory; paths outside that directory are rejected. Resolve relative paths against that root.",
29
+ '',
30
+ '- Tool outputs (file reads, shell commands, web fetches) are automatically capped. Paginate large reads with offset/limit, and prefer targeted queries over broad ones.',
31
+ ].join('\n');
32
+ /**
33
+ * Combine the agent system prompt with the harness prelude.
34
+ * If the agent prompt is empty, return the prelude alone.
35
+ */
36
+ export function withHarnessPrelude(agentSystemPrompt) {
37
+ const base = agentSystemPrompt?.trim() ?? '';
38
+ if (!base)
39
+ return HARNESS_PRELUDE;
40
+ return `${HARNESS_PRELUDE}\n\n${base}`;
41
+ }
@@ -0,0 +1,87 @@
1
+ export type AssistantUsage = {
2
+ input: number;
3
+ output: number;
4
+ cacheRead?: number;
5
+ cacheWrite?: number;
6
+ reasoning?: number;
7
+ };
8
+ export interface OpenAiFunctionTool {
9
+ type: 'function';
10
+ function: {
11
+ name: string;
12
+ description: string;
13
+ parameters: Record<string, unknown>;
14
+ };
15
+ }
16
+ export type TextContentPart = {
17
+ type: 'text';
18
+ text: string;
19
+ };
20
+ export type ImageContentPart = {
21
+ type: 'image_url';
22
+ image_url: {
23
+ url: string;
24
+ };
25
+ };
26
+ export type UserContentPart = TextContentPart | ImageContentPart;
27
+ export type ChatMessage = {
28
+ role: 'system';
29
+ content: string;
30
+ } | {
31
+ role: 'user';
32
+ content: string | UserContentPart[];
33
+ } | {
34
+ role: 'assistant';
35
+ content: string | null;
36
+ tool_calls?: Array<{
37
+ id: string;
38
+ type: 'function';
39
+ function: {
40
+ name: string;
41
+ arguments: string;
42
+ };
43
+ }>;
44
+ } | {
45
+ role: 'tool';
46
+ tool_call_id: string;
47
+ content: string;
48
+ };
49
+ export interface ChatCompletionsRequest {
50
+ model: string;
51
+ messages: ChatMessage[];
52
+ stream: true;
53
+ stream_options: {
54
+ include_usage: true;
55
+ };
56
+ tools?: OpenAiFunctionTool[];
57
+ }
58
+ export declare function buildRequestBody(params: {
59
+ messages: ChatMessage[];
60
+ tools: OpenAiFunctionTool[];
61
+ model: string;
62
+ }): ChatCompletionsRequest;
63
+ export type SseEvent = {
64
+ kind: 'content';
65
+ text: string;
66
+ } | {
67
+ kind: 'thinking';
68
+ text: string;
69
+ } | {
70
+ kind: 'tool_call_delta';
71
+ index: number;
72
+ id?: string;
73
+ name?: string;
74
+ argumentsDelta?: string;
75
+ } | {
76
+ kind: 'finish';
77
+ reason: string;
78
+ } | {
79
+ kind: 'usage';
80
+ usage: AssistantUsage;
81
+ } | {
82
+ kind: 'done';
83
+ };
84
+ /** Parse a single SSE line from an OpenAI-compatible chat completions stream. */
85
+ export declare function parseSseChunk(rawLine: string): SseEvent[];
86
+ export declare function readStream(response: Response, onEvent: (e: SseEvent) => void): Promise<void>;
87
+ //# sourceMappingURL=provider.d.ts.map