@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,3 @@
1
+ import type { Tool } from '../types.js';
2
+ export declare const writeTool: Tool;
3
+ //# sourceMappingURL=write.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../../src/harness/tools/builtin/write.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAGxC,eAAO,MAAM,SAAS,EAAE,IAiDvB,CAAC"}
@@ -0,0 +1,56 @@
1
+ // Ported from caretaker server's src/mcp/fs.ts (write).
2
+ // Read-before-write guard: existing files cannot be overwritten unless they
3
+ // were read in this run (ctx.readPaths). New files can always be created.
4
+ import { mkdir, stat, writeFile } from 'node:fs/promises';
5
+ import * as path from 'node:path';
6
+ import { assertWithinRoot, OutsideRootError } from '../sandbox.js';
7
+ export const writeTool = {
8
+ name: 'write',
9
+ description: 'Create a new file or overwrite an existing one. To overwrite, you must ' +
10
+ 'have read the file in this run (read_file).',
11
+ parameters: {
12
+ type: 'object',
13
+ properties: {
14
+ path: { type: 'string', description: 'Path within the working directory.' },
15
+ content: { type: 'string', description: 'Full file contents (UTF-8).' },
16
+ },
17
+ required: ['path', 'content'],
18
+ additionalProperties: false,
19
+ },
20
+ dangerous: true,
21
+ async execute(args, ctx) {
22
+ const a = args;
23
+ if (typeof a.path !== 'string' || !a.path.trim()) {
24
+ return { content: 'Error: path must be a non-empty string' };
25
+ }
26
+ if (typeof a.content !== 'string') {
27
+ return { content: 'Error: content must be a string' };
28
+ }
29
+ let abs;
30
+ try {
31
+ abs = assertWithinRoot(ctx.workingDir, a.path);
32
+ }
33
+ catch (err) {
34
+ if (err instanceof OutsideRootError)
35
+ return { content: `Error: ${err.message}` };
36
+ throw err;
37
+ }
38
+ const exists = await stat(abs)
39
+ .then(() => true)
40
+ .catch(() => false);
41
+ if (exists && !ctx.readPaths.has(abs)) {
42
+ return {
43
+ content: `Error: file ${a.path} exists and was not read in this run. Use read_file first.`,
44
+ };
45
+ }
46
+ try {
47
+ await mkdir(path.dirname(abs), { recursive: true });
48
+ await writeFile(abs, a.content, 'utf-8');
49
+ }
50
+ catch (err) {
51
+ return { content: `Error: ${err instanceof Error ? err.message : String(err)}` };
52
+ }
53
+ ctx.readPaths.add(abs);
54
+ return { content: `Wrote ${Buffer.byteLength(a.content, 'utf-8')} bytes to ${a.path}` };
55
+ },
56
+ };
@@ -0,0 +1,6 @@
1
+ export type { Tool, ToolContext, ToolResult, OpenAiFunctionTool, ConfirmDecision, ConfirmGate, } from './types.js';
2
+ export { toOpenAiTool } from './types.js';
3
+ export { ToolRegistry } from './registry.js';
4
+ export { registerBuiltins } from './builtin/index.js';
5
+ export { resolveAgentTools } from './resolve.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/index.ts"],"names":[],"mappings":"AAIA,YAAY,EACV,IAAI,EACJ,WAAW,EACX,UAAU,EACV,kBAAkB,EAClB,eAAe,EACf,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,7 @@
1
+ // Barrel export. Imports throughout the app go through this module so the
2
+ // internal layout (types / registry / builtin / future mcp adapter) can be
3
+ // reorganized without touching consumers.
4
+ export { toOpenAiTool } from './types.js';
5
+ export { ToolRegistry } from './registry.js';
6
+ export { registerBuiltins } from './builtin/index.js';
7
+ export { resolveAgentTools } from './resolve.js';
@@ -0,0 +1,3 @@
1
+ import { ToolRegistry } from './registry.js';
2
+ export declare const tools: ToolRegistry;
3
+ //# sourceMappingURL=instance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/instance.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAG7C,eAAO,MAAM,KAAK,cAAqB,CAAC"}
@@ -0,0 +1,19 @@
1
+ // Process-wide ToolRegistry singleton. Built-ins are registered at module
2
+ // load. Future MCP-adapted tools will be registered here too (likely via
3
+ // an async init driven by caretaker.json's mcpServers list).
4
+ //
5
+ // Importing this from anywhere in the app yields the same registry — the
6
+ // agent form uses it to render the tool picker, and the chat screen uses
7
+ // it to filter per agent. ToolRegistry tests don't depend on this
8
+ // singleton; they instantiate their own.
9
+ //
10
+ // Note: this module registers builtins as a one-time side effect at load.
11
+ // If a future test cache-busts this module and re-imports it (e.g. via a
12
+ // `?cb=…` query string), the registry will throw "tool already registered".
13
+ // Tests should import individual tool files (e.g. ./builtin/bash.js)
14
+ // directly or instantiate their own ToolRegistry rather than depend on
15
+ // this singleton.
16
+ import { ToolRegistry } from './registry.js';
17
+ import { registerBuiltins } from './builtin/index.js';
18
+ export const tools = new ToolRegistry();
19
+ registerBuiltins(tools);
@@ -0,0 +1,21 @@
1
+ import type { Tool } from './types.js';
2
+ /**
3
+ * In-process tool registry. Tools are registered once at startup
4
+ * (registerBuiltins + future registerMcpServers) and filtered per-run by
5
+ * the agent's allowedTools list.
6
+ */
7
+ export declare class ToolRegistry {
8
+ private tools;
9
+ /** Register a tool. Throws if a tool with the same name is already
10
+ * registered — registration is meant to be deterministic, and silent
11
+ * overwrites would mask bugs. */
12
+ register(tool: Tool): void;
13
+ has(name: string): boolean;
14
+ get(name: string): Tool | undefined;
15
+ list(): Tool[];
16
+ /** Filter the registry by an explicit allowlist of tool names. Names
17
+ * not present in the registry are silently dropped — the agent may
18
+ * reference tools that are unmounted on this install. */
19
+ filtered(allowed: string[]): Tool[];
20
+ }
21
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC;;;;GAIG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,KAAK,CAA2B;IAExC;;sCAEkC;IAClC,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI;IAO1B,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI1B,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAInC,IAAI,IAAI,IAAI,EAAE;IAId;;8DAE0D;IAC1D,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE;CAIpC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * In-process tool registry. Tools are registered once at startup
3
+ * (registerBuiltins + future registerMcpServers) and filtered per-run by
4
+ * the agent's allowedTools list.
5
+ */
6
+ export class ToolRegistry {
7
+ tools = new Map();
8
+ /** Register a tool. Throws if a tool with the same name is already
9
+ * registered — registration is meant to be deterministic, and silent
10
+ * overwrites would mask bugs. */
11
+ register(tool) {
12
+ if (this.tools.has(tool.name)) {
13
+ throw new Error(`tool already registered: ${tool.name}`);
14
+ }
15
+ this.tools.set(tool.name, tool);
16
+ }
17
+ has(name) {
18
+ return this.tools.has(name);
19
+ }
20
+ get(name) {
21
+ return this.tools.get(name);
22
+ }
23
+ list() {
24
+ return [...this.tools.values()];
25
+ }
26
+ /** Filter the registry by an explicit allowlist of tool names. Names
27
+ * not present in the registry are silently dropped — the agent may
28
+ * reference tools that are unmounted on this install. */
29
+ filtered(allowed) {
30
+ const set = new Set(allowed);
31
+ return this.list().filter((t) => set.has(t.name));
32
+ }
33
+ }
@@ -0,0 +1,5 @@
1
+ import type { AgentConfig } from '../../types.js';
2
+ import type { ToolRegistry } from './registry.js';
3
+ import type { Tool } from './types.js';
4
+ export declare function resolveAgentTools(agent: AgentConfig, registry: ToolRegistry): Promise<Tool[]>;
5
+ //# sourceMappingURL=resolve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/resolve.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAgBvC,wBAAsB,iBAAiB,CACrC,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,YAAY,GACrB,OAAO,CAAC,IAAI,EAAE,CAAC,CA2BjB"}
@@ -0,0 +1,60 @@
1
+ // Resolve the Tool[] visible to a single run, given the agent config and
2
+ // the process-wide registry. Layers on top of allowedTools:
3
+ // - Always-on builtin: `get_agent_context`. Pure introspection (live
4
+ // token usage / context-window %); read-only, no side effects, no
5
+ // reason to ever hide it from the model.
6
+ // - Plugin-gated builtins: when the agent has at least one active
7
+ // plugin, the skill (`list_skills`/`read_skill`) and command
8
+ // (`list_commands`/`invoke_command`) access tools are added even if
9
+ // the user did not list them in allowedTools — they are useless
10
+ // without an active plugin and noisy if shown without one.
11
+ // - MCP tools: when the agent references MCP servers, their tools/list
12
+ // output is fetched via the adapter and appended (names already
13
+ // namespaced as `mcp__<id>__<toolName>`).
14
+ //
15
+ // Every other builtin — including `list_agents` and `invoke_agent` — is
16
+ // gated by the user's `allowedTools` selection. The agents UI exposes
17
+ // the same tri-state for them as for any other tool; the runtime
18
+ // honours the chosen state instead of silently re-enabling capabilities
19
+ // the user disabled.
20
+ //
21
+ // MCP tools are NOT registered into the process-wide registry: we resolve
22
+ // them per-run because the remote tool list can change between runs and we
23
+ // don't want stale entries cluttering autocomplete or test fixtures.
24
+ import { mcpToolsForServers } from '../../mcp/adapter.js';
25
+ const SKILL_TOOL_NAMES = ['list_skills', 'read_skill'];
26
+ const COMMAND_TOOL_NAMES = ['list_commands', 'invoke_command'];
27
+ const ALWAYS_ON_TOOL_NAMES = ['get_agent_context'];
28
+ function autoInclude(tools, registry, names) {
29
+ const have = new Set(tools.map((t) => t.name));
30
+ for (const name of names) {
31
+ if (have.has(name))
32
+ continue;
33
+ const t = registry.get(name);
34
+ if (t)
35
+ tools.push(t);
36
+ }
37
+ }
38
+ export async function resolveAgentTools(agent, registry) {
39
+ const tools = registry.filtered(agent.allowedTools);
40
+ if (agent.allowedTools.includes('mcp__task__*')) {
41
+ const taskTools = registry.list().filter((t) => t.name.startsWith('mcp__task__'));
42
+ const have = new Set(tools.map((t) => t.name));
43
+ for (const t of taskTools) {
44
+ if (!have.has(t.name)) {
45
+ tools.push(t);
46
+ }
47
+ }
48
+ }
49
+ autoInclude(tools, registry, ALWAYS_ON_TOOL_NAMES);
50
+ if ((agent.plugins ?? []).length > 0) {
51
+ autoInclude(tools, registry, SKILL_TOOL_NAMES);
52
+ autoInclude(tools, registry, COMMAND_TOOL_NAMES);
53
+ }
54
+ const mcpIds = agent.mcpServers ?? [];
55
+ if (mcpIds.length > 0) {
56
+ const mcp = await mcpToolsForServers(mcpIds);
57
+ tools.push(...mcp);
58
+ }
59
+ return tools;
60
+ }
@@ -0,0 +1,6 @@
1
+ export declare class OutsideRootError extends Error {
2
+ code: string;
3
+ constructor(root: string, candidate: string);
4
+ }
5
+ export declare function assertWithinRoot(root: string, candidate: string): string;
6
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/sandbox.ts"],"names":[],"mappings":"AAQA,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,IAAI,SAAmB;gBACX,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;CAG5C;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAUxE"}
@@ -0,0 +1,23 @@
1
+ // Path sandbox for fs tools. Ported from caretaker server's
2
+ // src/mcp/fs_sandbox.ts. Symlinks are intentionally NOT followed for the
3
+ // check — this is a "soft jail" that protects against accidental escapes
4
+ // (`..` traversal, absolute paths outside the working dir), not a security
5
+ // boundary against an adversarial filesystem.
6
+ import * as path from 'node:path';
7
+ export class OutsideRootError extends Error {
8
+ code = 'EOUTSIDE_ROOT';
9
+ constructor(root, candidate) {
10
+ super(`Path "${candidate}" is outside the working directory "${root}"`);
11
+ }
12
+ }
13
+ export function assertWithinRoot(root, candidate) {
14
+ const absRoot = path.resolve(root);
15
+ const absCandidate = path.isAbsolute(candidate)
16
+ ? path.resolve(candidate)
17
+ : path.resolve(absRoot, candidate);
18
+ const rel = path.relative(absRoot, absCandidate);
19
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
20
+ throw new OutsideRootError(absRoot, candidate);
21
+ }
22
+ return absCandidate;
23
+ }
@@ -0,0 +1,80 @@
1
+ import type { AgentConfig } from '../../types.js';
2
+ import type { AssistantUsage } from '../provider.js';
3
+ export type ConfirmDecision = 'once' | 'always' | 'reject';
4
+ export type ConfirmGate = (id: string, name: string, args: unknown) => Promise<ConfirmDecision>;
5
+ export interface ToolContext {
6
+ /** Aborted when the run is cancelled (Esc) or the chat unmounts. Tools
7
+ * that spawn subprocesses or open network connections MUST honor it. */
8
+ signal: AbortSignal;
9
+ /** Working directory for fs/bash tools. Defaults to process.cwd(). */
10
+ workingDir: string;
11
+ /** Set of absolute paths read in this run. fs.read populates it; fs.write
12
+ * consults it for the read-before-write guard so the model cannot blind-
13
+ * overwrite a file it never inspected. The loop creates a fresh Set per
14
+ * run; tools mutate it in place. */
15
+ readPaths: Set<string>;
16
+ /** Plugin names active for this run (mirrors AgentConfig.plugins). The
17
+ * list_skills / read_skill tools consult this to scope what the model can
18
+ * enumerate or fetch. Optional because most tools never read it; tests
19
+ * for non-skill tools can omit it. The skill tools treat undefined as []. */
20
+ activePlugins?: string[];
21
+ /** The agent currently executing this tool. `invoke_agent` reads this to
22
+ * resolve inheritance for the invoked sub-agent (empty fields fall back
23
+ * to the caller). At the top-level run this is the user's chat agent;
24
+ * inside a dispatched child it is the child's already-effective config. */
25
+ callerAgent?: AgentConfig;
26
+ /** How many `invoke_agent` frames deep this run is. Top-level = 0; a
27
+ * dispatched child = 1; etc. The dispatch helper rejects calls past a
28
+ * small cap to prevent runaway recursion. */
29
+ dispatchDepth?: number;
30
+ /** The chat-side confirm callback. The dispatch helper passes it through
31
+ * to the child run so the user keeps the gate authority for tool calls
32
+ * inside the sub-agent too. */
33
+ confirmTool?: ConfirmGate;
34
+ /** Live token-usage handles updated by the loop in place each turn. The
35
+ * `get_agent_context` builtin reads this at exec time so it reflects
36
+ * the latest values (not a snapshot from when the run started). */
37
+ liveUsage?: {
38
+ lastTurn?: AssistantUsage;
39
+ cumulative: AssistantUsage;
40
+ };
41
+ /** The session ID of the current conversation run. Useful for attachment directories. */
42
+ sessionId?: string;
43
+ }
44
+ export interface ToolAttachment {
45
+ mime: string;
46
+ data: Buffer;
47
+ }
48
+ export interface ToolResult {
49
+ /** Textual content returned to the model as the tool result. */
50
+ content: string;
51
+ attachments?: ToolAttachment[];
52
+ }
53
+ export interface Tool {
54
+ /** Unique key. Flat for native tools (e.g. "read_file"), namespaced for
55
+ * adapter-wrapped tools (e.g. "mcp__kb__search"). The name appears in
56
+ * the agent's allowedTools list and in the model's tool_call payload. */
57
+ name: string;
58
+ description: string;
59
+ /** JSON Schema for the args (OpenAI function-calling shape). */
60
+ parameters: Record<string, unknown>;
61
+ /** Resolves the tool. Throws are caught by the loop and surfaced as
62
+ * "Error: <msg>" tool results. */
63
+ execute: (args: unknown, ctx: ToolContext) => Promise<ToolResult>;
64
+ /** Marks tools whose action mutates the system or has side effects
65
+ * (file write, command exec, network mutation). The harness may surface
66
+ * a confirm prompt for these in a future iteration; today purely
67
+ * informational. */
68
+ dangerous?: boolean;
69
+ }
70
+ export interface OpenAiFunctionTool {
71
+ type: 'function';
72
+ function: {
73
+ name: string;
74
+ description: string;
75
+ parameters: Record<string, unknown>;
76
+ };
77
+ }
78
+ /** Convert a Tool to the OpenAI function-tool entry sent in chat-completions. */
79
+ export declare function toOpenAiTool(tool: Tool): OpenAiFunctionTool;
80
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/types.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAErD,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC3D,MAAM,MAAM,WAAW,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC,eAAe,CAAC,CAAC;AAoBhG,MAAM,WAAW,WAAW;IAC1B;6EACyE;IACzE,MAAM,EAAE,WAAW,CAAC;IACpB,sEAAsE;IACtE,UAAU,EAAE,MAAM,CAAC;IACnB;;;yCAGqC;IACrC,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACvB;;;kFAG8E;IAC9E,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB;;;gFAG4E;IAC5E,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B;;kDAE8C;IAC9C,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;oCAEgC;IAChC,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B;;wEAEoE;IACpE,SAAS,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,cAAc,CAAC;QAAC,UAAU,EAAE,cAAc,CAAA;KAAE,CAAC;IACtE,yFAAyF;IACzF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,UAAU;IACzB,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,cAAc,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,IAAI;IACnB;;8EAE0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC;uCACmC;IACnC,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;IAClE;;;yBAGqB;IACrB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,MAAM,CAAC;QACpB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACrC,CAAC;CACH;AAED,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,kBAAkB,CAS3D"}
@@ -0,0 +1,16 @@
1
+ // Tool registry types. The `Tool` shape is provider-agnostic and the loop
2
+ // dispatches against it without distinguishing native (in-process) tools
3
+ // from adapter-wrapped tools (e.g. an MCP adapter, future). A `Tool` only
4
+ // has to declare its OpenAI-function-calling parameters and an `execute`
5
+ // that takes parsed args + a runtime context and returns a structured result.
6
+ /** Convert a Tool to the OpenAI function-tool entry sent in chat-completions. */
7
+ export function toOpenAiTool(tool) {
8
+ return {
9
+ type: 'function',
10
+ function: {
11
+ name: tool.name,
12
+ description: tool.description,
13
+ parameters: tool.parameters,
14
+ },
15
+ };
16
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ // Process entrypoint: boot side-effects (plugin refresh, model-limits
3
+ // fetch, MCP shutdown hooks) + dispatch to the CLI layer in src/cli/.
4
+ // Subcommand routing lives in src/cli/index.ts; this file stays thin.
5
+ import { refreshSourcesOnStart } from './plugins/refresh_on_start.js';
6
+ import { closeAll as closeAllMcp } from './mcp/client.js';
7
+ import { initModelLimits } from './harness/model_limits.js';
8
+ import { probeShellEnv } from './harness/tools/builtin/shell-env.js';
9
+ import { runCli } from './cli/index.js';
10
+ // Fire refresh-on-start in the background — startup must not block on a
11
+ // slow git fetch. The next agent run reads plugins.json fresh so it picks
12
+ // up newly-discovered plugins automatically.
13
+ void refreshSourcesOnStart().catch((err) => {
14
+ console.error('[boot] refresh-on-start failed:', err);
15
+ });
16
+ // Probe the interactive shell environment on Linux to capture PATH and
17
+ // version manager variables (NVM, volta, fnm, etc.) that .bashrc sets.
18
+ // This runs in the background and the result is cached for bash tool use.
19
+ void probeShellEnv().catch((err) => {
20
+ console.error('[boot] shell-env probe failed:', err);
21
+ });
22
+ // Populate the model-context registry from models.dev in the background.
23
+ // Degrades gracefully (percent stays null) until the first fetch lands.
24
+ initModelLimits();
25
+ // Tear pooled MCP connections down on shutdown so child stdio processes are
26
+ // not orphaned and HTTP sessions get a chance to send DELETE. Best-effort:
27
+ // SIGINT/SIGTERM may not yield enough time for the close handshake.
28
+ const shutdownMcp = async () => {
29
+ try {
30
+ await closeAllMcp();
31
+ }
32
+ catch {
33
+ /* swallow — we are exiting regardless */
34
+ }
35
+ };
36
+ process.on('exit', () => {
37
+ // exit is sync — fire-and-forget; close handlers may not complete.
38
+ void shutdownMcp();
39
+ });
40
+ for (const sig of ['SIGINT', 'SIGTERM']) {
41
+ process.on(sig, async () => {
42
+ await shutdownMcp();
43
+ process.exit(0);
44
+ });
45
+ }
46
+ await runCli(process.argv);
@@ -0,0 +1,24 @@
1
+ /** Resolve the on-disk path of the encryption key. Exported for diagnostics
2
+ * and tests; runtime code should not need it. */
3
+ export declare function encryptionKeyPath(): string;
4
+ /**
5
+ * Build the `icacls` invocation that restricts a file to the current user
6
+ * only — the Windows equivalent of chmod 0600. `/inheritance:r` drops the
7
+ * ACEs inherited from the parent directory (which would otherwise let other
8
+ * principals read the key); `/grant:r <user>:F` replaces them with a single
9
+ * Full-control grant to the owner. Exported so the argument construction can
10
+ * be unit-tested on any platform.
11
+ */
12
+ export declare function windowsLockCommand(path: string, username: string): {
13
+ cmd: string;
14
+ args: string[];
15
+ };
16
+ /** Encrypt plaintext, return a hex-encoded blob `iv:tag:ciphertext`. */
17
+ export declare function encrypt(plaintext: string): string;
18
+ /** Decrypt a blob produced by encrypt(). Throws on tampered input. */
19
+ export declare function decrypt(blob: string): string;
20
+ /** Heuristic: does this string look like an encrypt() blob? */
21
+ export declare function isEncrypted(value: string): boolean;
22
+ /** Mask a token in user-facing UI: keep only the last 4 characters. */
23
+ export declare function maskToken(token: string): string;
24
+ //# sourceMappingURL=encryption.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption.d.ts","sourceRoot":"","sources":["../../src/lib/encryption.ts"],"names":[],"mappings":"AAoCA;kDACkD;AAClD,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAElG;AA8FD,wEAAwE;AACxE,wBAAgB,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAOjD;AAED,sEAAsE;AACtE,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAW5C;AAED,+DAA+D;AAC/D,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAKlD;AAED,uEAAuE;AACvE,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAG/C"}
@@ -0,0 +1,163 @@
1
+ // AES-256-GCM symmetric encryption for sensitive values stored on disk
2
+ // (today: git auth tokens in plugins.json; soon: MCP HTTP auth headers).
3
+ // Mirrors the server implementation at src/lib/encryption.ts so blobs are
4
+ // wire-compatible if you ever copy state between the two.
5
+ //
6
+ // Key resolution (first match wins):
7
+ // 1. process.env.ENCRYPTION_KEY — 64-char hex string (32 bytes).
8
+ // Useful in CI and for forcing a known key across hosts.
9
+ // 2. <dataDir>/encryption.key — 32 raw bytes, chmod 0600. Auto-generated
10
+ // atomically the first time a key is needed.
11
+ //
12
+ // dataDir() honors CARETAKER_HOME so tests can isolate the keystore.
13
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
14
+ import { execFileSync } from 'node:child_process';
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, renameSync, unlinkSync, } from 'node:fs';
16
+ import { homedir, userInfo } from 'node:os';
17
+ import { join } from 'node:path';
18
+ const ALGORITHM = 'aes-256-gcm';
19
+ const IV_LENGTH = 12;
20
+ const TAG_LENGTH = 16;
21
+ const KEY_BYTES = 32;
22
+ function dataDir() {
23
+ return process.env.CARETAKER_HOME ?? join(homedir(), '.caretaker');
24
+ }
25
+ /** Resolve the on-disk path of the encryption key. Exported for diagnostics
26
+ * and tests; runtime code should not need it. */
27
+ export function encryptionKeyPath() {
28
+ return join(dataDir(), 'encryption.key');
29
+ }
30
+ /**
31
+ * Build the `icacls` invocation that restricts a file to the current user
32
+ * only — the Windows equivalent of chmod 0600. `/inheritance:r` drops the
33
+ * ACEs inherited from the parent directory (which would otherwise let other
34
+ * principals read the key); `/grant:r <user>:F` replaces them with a single
35
+ * Full-control grant to the owner. Exported so the argument construction can
36
+ * be unit-tested on any platform.
37
+ */
38
+ export function windowsLockCommand(path, username) {
39
+ return { cmd: 'icacls', args: [path, '/inheritance:r', '/grant:r', `${username}:F`] };
40
+ }
41
+ /**
42
+ * Tighten on-disk permissions for the key file so only the current user can
43
+ * read it. On POSIX the 0600 applied at write time already does this; on
44
+ * Windows `chmod 0600` only toggles the read-only bit and leaves the ACL
45
+ * inherited (other local users can read it), so we apply an explicit ACL via
46
+ * `icacls`. Best-effort: a failed tightening must not break key creation — the
47
+ * file still lives under the per-user profile directory, which denies other
48
+ * standard users by default.
49
+ */
50
+ function restrictToCurrentUser(path) {
51
+ if (process.platform !== 'win32')
52
+ return;
53
+ try {
54
+ const { cmd, args } = windowsLockCommand(path, userInfo().username);
55
+ execFileSync(cmd, args, { stdio: 'ignore' });
56
+ }
57
+ catch {
58
+ /* best-effort — see doc comment */
59
+ }
60
+ }
61
+ // Guards the one-shot ACL heal below so `icacls` runs at most once per process
62
+ // rather than on every encrypt/decrypt (getKey re-reads the key each call).
63
+ let keyAclEnsured = false;
64
+ function loadOrCreateOnDiskKey() {
65
+ const dir = dataDir();
66
+ const path = encryptionKeyPath();
67
+ if (existsSync(path)) {
68
+ const buf = readFileSync(path);
69
+ if (buf.length !== KEY_BYTES) {
70
+ throw new Error(`encryption.key at ${path} must be exactly ${KEY_BYTES} bytes (found ${buf.length})`);
71
+ }
72
+ // Heal Windows keys created before owner-only ACLs existed: re-apply the
73
+ // ACL once per process (idempotent, no-op on POSIX). Regenerating the key
74
+ // is NOT an option — it would orphan every existing ciphertext blob.
75
+ if (!keyAclEnsured) {
76
+ keyAclEnsured = true;
77
+ restrictToCurrentUser(path);
78
+ }
79
+ return buf;
80
+ }
81
+ // First-boot generation: produce a fresh 32-byte key and persist it
82
+ // atomically under restrictive permissions. The data dir is created with
83
+ // 0700 (mirrors store/json.ts ensureDataDir) and the key file with 0600.
84
+ // Tmp + rename keeps a partial write from leaving an empty file in place.
85
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ try {
87
+ chmodSync(dir, 0o700);
88
+ }
89
+ catch {
90
+ /* best-effort — directory already exists with looser perms on some setups */
91
+ }
92
+ const key = randomBytes(KEY_BYTES);
93
+ const tmp = `${path}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
94
+ try {
95
+ writeFileSync(tmp, key, { mode: 0o600 });
96
+ try {
97
+ chmodSync(tmp, 0o600);
98
+ }
99
+ catch {
100
+ /* same caveat as the dir chmod */
101
+ }
102
+ renameSync(tmp, path);
103
+ // Windows: chmod 0600 above is a no-op for confidentiality; apply a real
104
+ // owner-only ACL. POSIX no-ops here.
105
+ keyAclEnsured = true;
106
+ restrictToCurrentUser(path);
107
+ }
108
+ catch (err) {
109
+ try {
110
+ unlinkSync(tmp);
111
+ }
112
+ catch {
113
+ /* nothing to clean up */
114
+ }
115
+ throw err;
116
+ }
117
+ return key;
118
+ }
119
+ function getKey() {
120
+ const raw = process.env.ENCRYPTION_KEY;
121
+ if (raw) {
122
+ const buf = Buffer.from(raw, 'hex');
123
+ if (buf.length !== KEY_BYTES) {
124
+ throw new Error('ENCRYPTION_KEY must be a 64-char hex string (32 bytes)');
125
+ }
126
+ return buf;
127
+ }
128
+ return loadOrCreateOnDiskKey();
129
+ }
130
+ /** Encrypt plaintext, return a hex-encoded blob `iv:tag:ciphertext`. */
131
+ export function encrypt(plaintext) {
132
+ const key = getKey();
133
+ const iv = randomBytes(IV_LENGTH);
134
+ const cipher = createCipheriv(ALGORITHM, key, iv);
135
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
136
+ const tag = cipher.getAuthTag();
137
+ return `${iv.toString('hex')}:${tag.toString('hex')}:${encrypted.toString('hex')}`;
138
+ }
139
+ /** Decrypt a blob produced by encrypt(). Throws on tampered input. */
140
+ export function decrypt(blob) {
141
+ const key = getKey();
142
+ const parts = blob.split(':');
143
+ if (parts.length !== 3)
144
+ throw new Error('Invalid encrypted token format');
145
+ const [ivHex, tagHex, ctHex] = parts;
146
+ const iv = Buffer.from(ivHex, 'hex');
147
+ const tag = Buffer.from(tagHex, 'hex');
148
+ const ct = Buffer.from(ctHex, 'hex');
149
+ const decipher = createDecipheriv(ALGORITHM, key, iv);
150
+ decipher.setAuthTag(tag);
151
+ return decipher.update(ct).toString('utf8') + decipher.final('utf8');
152
+ }
153
+ /** Heuristic: does this string look like an encrypt() blob? */
154
+ export function isEncrypted(value) {
155
+ const parts = value.split(':');
156
+ return (parts.length === 3 && parts[0].length === IV_LENGTH * 2 && parts[1].length === TAG_LENGTH * 2);
157
+ }
158
+ /** Mask a token in user-facing UI: keep only the last 4 characters. */
159
+ export function maskToken(token) {
160
+ if (token.length <= 4)
161
+ return '****';
162
+ return `****${token.slice(-4)}`;
163
+ }
@@ -0,0 +1,9 @@
1
+ export declare function openCommandFor(platform: NodeJS.Platform, url: string): {
2
+ cmd: string;
3
+ args: string[];
4
+ };
5
+ /** Open a URL in the user's default browser. Fire-and-forget: a missing
6
+ * opener must not crash the flow — the URL is still surfaced to the user by
7
+ * the caller. */
8
+ export declare function openUrl(url: string): void;
9
+ //# sourceMappingURL=open_url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"open_url.d.ts","sourceRoot":"","sources":["../../src/lib/open_url.ts"],"names":[],"mappings":"AAGA,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAItG;AAED;;kBAEkB;AAClB,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CASzC"}