@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,86 @@
1
+ // Exposes the built-in mcp__task__* tools as a streamable-HTTP MCP endpoint
2
+ // so claude-code agents can drive the task state machine. Token-guarded:
3
+ // the task heartbeat issues a per-run bearer token and revokes it after.
4
+ // Stateless MCP (no session): a fresh Server per request. The task tools
5
+ // are context-free (they take task_id as an argument), so no per-run
6
+ // injection is needed.
7
+ import { randomBytes } from 'node:crypto';
8
+ import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response';
9
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
10
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
11
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
12
+ import { tools as registry } from '../../harness/tools/instance.js';
13
+ const TASK_PREFIX = 'mcp__task__';
14
+ const activeTokens = new Set();
15
+ export function issueBridgeToken() {
16
+ const token = randomBytes(24).toString('hex');
17
+ activeTokens.add(token);
18
+ return token;
19
+ }
20
+ export function revokeBridgeToken(token) {
21
+ activeTokens.delete(token);
22
+ }
23
+ let bridgeUrl = null;
24
+ export function setTaskBridgeUrl(url) {
25
+ bridgeUrl = url;
26
+ }
27
+ export function getTaskBridgeUrl() {
28
+ return bridgeUrl;
29
+ }
30
+ function taskTools() {
31
+ return registry.list().filter((t) => t.name.startsWith(TASK_PREFIX));
32
+ }
33
+ function buildServer() {
34
+ const server = new Server({ name: 'caretaker-task', version: '0.0.0' }, { capabilities: { tools: {} } });
35
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
36
+ tools: taskTools().map((t) => ({
37
+ name: t.name.slice(TASK_PREFIX.length),
38
+ description: t.description,
39
+ inputSchema: t.parameters,
40
+ })),
41
+ }));
42
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
43
+ const tool = taskTools().find((t) => t.name === TASK_PREFIX + req.params.name);
44
+ if (!tool) {
45
+ return {
46
+ content: [{ type: 'text', text: `Error: unknown tool "${req.params.name}"` }],
47
+ isError: true,
48
+ };
49
+ }
50
+ // ponytail: task tools ignore ctx entirely; a stub keeps the types happy.
51
+ const ctx = {
52
+ workingDir: process.cwd(),
53
+ signal: new AbortController().signal,
54
+ readPaths: new Set(),
55
+ };
56
+ try {
57
+ const result = await tool.execute(req.params.arguments ?? {}, ctx);
58
+ return { content: [{ type: 'text', text: result.content }] };
59
+ }
60
+ catch (err) {
61
+ return {
62
+ content: [{ type: 'text', text: `Error: ${err?.message ?? String(err)}` }],
63
+ isError: true,
64
+ };
65
+ }
66
+ });
67
+ return server;
68
+ }
69
+ export function registerTaskBridge(app) {
70
+ app.post('/api/mcp/task', async (c) => {
71
+ const auth = c.req.header('authorization') ?? '';
72
+ const token = auth.replace(/^Bearer\s+/i, '');
73
+ if (!token || !activeTokens.has(token))
74
+ return c.json({ error: 'unauthorized' }, 401);
75
+ const body = await c.req.json().catch(() => null);
76
+ const server = buildServer();
77
+ const transport = new StreamableHTTPServerTransport({
78
+ sessionIdGenerator: undefined, // stateless
79
+ enableJsonResponse: true, // plain JSON responses, no SSE needed
80
+ });
81
+ await server.connect(transport);
82
+ const { incoming, outgoing } = c.env;
83
+ await transport.handleRequest(incoming, outgoing, body);
84
+ return RESPONSE_ALREADY_SENT;
85
+ });
86
+ }
@@ -0,0 +1,16 @@
1
+ import type { ScheduledTaskConfig } from '../../../types.js';
2
+ import type { SchedulerStrategy } from './strategy.js';
3
+ /**
4
+ * Parses and evaluates a cron expression string against a given Date.
5
+ * Supports standard syntax fields: minute, hour, day of month, month, day of week.
6
+ * Handles wildcards (*), step levels (e.g. *\/5), ranges (e.g. 1-5), and comma lists (e.g. 1,3,5).
7
+ */
8
+ export declare function matchesCron(cronStr: string, date: Date): boolean;
9
+ /**
10
+ * Headless runner execution of a single task prompt loop.
11
+ * Runs completely in background, automatically approving tool runs.
12
+ * Guards against concurrent execution: if the task is already running, skips.
13
+ */
14
+ export declare function executeTaskRun(task: ScheduledTaskConfig): Promise<void>;
15
+ export declare const HeartbeatStrategy: SchedulerStrategy;
16
+ //# sourceMappingURL=heartbeat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heartbeat.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/heartbeat.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAG7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,OAAO,CA2DhE;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgH7E;AAID,eAAO,MAAM,iBAAiB,EAAE,iBAgB/B,CAAC"}
@@ -0,0 +1,181 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import * as harness from '../../../harness/index.js';
3
+ import { loadAgents, loadConfig } from '../../../store/json.js';
4
+ import { userMessage } from '../../../session/store.js';
5
+ import { saveTaskRun } from './logs.js';
6
+ import { runningTasks } from './locks.js';
7
+ /**
8
+ * Parses and evaluates a cron expression string against a given Date.
9
+ * Supports standard syntax fields: minute, hour, day of month, month, day of week.
10
+ * Handles wildcards (*), step levels (e.g. *\/5), ranges (e.g. 1-5), and comma lists (e.g. 1,3,5).
11
+ */
12
+ export function matchesCron(cronStr, date) {
13
+ const fields = cronStr.trim().split(/\s+/);
14
+ if (fields.length !== 5)
15
+ return false;
16
+ const [min, hr, dom, mon, dow] = fields;
17
+ const m = date.getMinutes();
18
+ const h = date.getHours();
19
+ const d = date.getDate();
20
+ const mo = date.getMonth() + 1; // 0-indexed month
21
+ const w = date.getDay(); // 0 is Sunday
22
+ const matchField = (field, val, isDow = false) => {
23
+ if (field === '*')
24
+ return true;
25
+ // Handle list parsing (e.g., 1,3,5)
26
+ if (field.includes(',')) {
27
+ return field.split(',').some((p) => matchField(p, val, isDow));
28
+ }
29
+ // Handle step patterns (e.g., */5)
30
+ if (field.startsWith('*/')) {
31
+ const step = parseInt(field.slice(2), 10);
32
+ return val % step === 0;
33
+ }
34
+ // Handle range with step patterns (e.g., 1-5/2)
35
+ if (field.includes('/')) {
36
+ const [range, stepStr] = field.split('/');
37
+ const step = parseInt(stepStr || '1', 10);
38
+ if (range === '*') {
39
+ return val % step === 0;
40
+ }
41
+ if (range.includes('-')) {
42
+ const [start, end] = range.split('-').map(Number);
43
+ if (val >= start && val <= end) {
44
+ return (val - start) % step === 0;
45
+ }
46
+ return false;
47
+ }
48
+ }
49
+ // Handle range parsing (e.g., 1-5)
50
+ if (field.includes('-')) {
51
+ const [start, end] = field.split('-').map(Number);
52
+ return val >= start && val <= end;
53
+ }
54
+ // Exact number match
55
+ const num = parseInt(field, 10);
56
+ return num === val;
57
+ };
58
+ return (matchField(min, m) &&
59
+ matchField(hr, h) &&
60
+ matchField(dom, d) &&
61
+ matchField(mon, mo) &&
62
+ matchField(dow, w, true));
63
+ }
64
+ /**
65
+ * Headless runner execution of a single task prompt loop.
66
+ * Runs completely in background, automatically approving tool runs.
67
+ * Guards against concurrent execution: if the task is already running, skips.
68
+ */
69
+ export async function executeTaskRun(task) {
70
+ if (runningTasks.has(task.id)) {
71
+ console.log(`[scheduler] Task "${task.name}" is already running — skipping.`);
72
+ return;
73
+ }
74
+ runningTasks.add(task.id);
75
+ const runId = `run_${randomUUID().slice(0, 8)}`;
76
+ console.log(`[scheduler] Starting execution run ${runId} for task: "${task.name}"`);
77
+ const runMessages = [];
78
+ try {
79
+ const [agents, config] = await Promise.all([loadAgents(), loadConfig()]);
80
+ const agent = agents.find((a) => a.id === task.agentId);
81
+ if (!agent) {
82
+ throw new Error(`Agent with ID "${task.agentId}" not found for task "${task.name}"`);
83
+ }
84
+ const provider = config.providers.find((p) => p.name === agent.provider);
85
+ if (!provider) {
86
+ throw new Error(`Provider "${agent.provider}" not found for agent "${agent.name}"`);
87
+ }
88
+ const tools = await harness.resolveAgentTools(agent, harness.tools);
89
+ const workingDir = task.workingDir || agent.workingDir || process.cwd();
90
+ const unattendedNotice = `[UNATTENDED RUN] Note: You are running as an unattended scheduled task. No human is supervising this execution. Act autonomously and complete the task to the best of your ability.`;
91
+ const effectivePrompt = `${unattendedNotice}\n\n${task.prompt}`;
92
+ // Track the initial user prompt inside run history
93
+ const startMsg = userMessage(effectivePrompt);
94
+ runMessages.push(startMsg);
95
+ // Invoke headless loop run
96
+ await harness.run({
97
+ agent: { ...agent, permissionMode: 'bypassPermissions' }, // unattended: mirror the auto-approve confirm gate
98
+ provider,
99
+ tools,
100
+ prompt: effectivePrompt,
101
+ history: [],
102
+ workingDir,
103
+ }, {
104
+ onMessage: async (msg) => {
105
+ runMessages.push(msg);
106
+ },
107
+ confirmTool: async () => 'once', // Headless cron triggers auto-approve all tools
108
+ });
109
+ // Map captured MessageRecords to webview ChatMessage schema
110
+ const chatMessages = runMessages.map((m) => ({
111
+ id: m.id,
112
+ role: m.role,
113
+ content: m.content,
114
+ parts: m.parts,
115
+ toolCallId: m.toolCallId,
116
+ createdAt: m.createdAt,
117
+ }));
118
+ await saveTaskRun(task.id, {
119
+ runId,
120
+ timestamp: new Date().toISOString(),
121
+ status: 'success',
122
+ messages: chatMessages,
123
+ });
124
+ console.log(`[scheduler] Run ${runId} for task "${task.name}" finished successfully.`);
125
+ }
126
+ catch (err) {
127
+ const errorMsg = err instanceof Error ? err.message : String(err);
128
+ console.error(`[scheduler] Run ${runId} for task "${task.name}" failed:`, errorMsg);
129
+ const chatMessages = runMessages.map((m) => ({
130
+ id: m.id,
131
+ role: m.role,
132
+ content: m.content,
133
+ parts: m.parts,
134
+ toolCallId: m.toolCallId,
135
+ createdAt: m.createdAt,
136
+ }));
137
+ // Synthesize user prompt trigger if failed before loop initiation
138
+ if (chatMessages.length === 0) {
139
+ chatMessages.push({
140
+ id: randomUUID(),
141
+ role: 'user',
142
+ content: task.prompt,
143
+ createdAt: new Date().toISOString(),
144
+ });
145
+ }
146
+ // Append descriptive system assistant error to let the user review the failure details in UI
147
+ chatMessages.push({
148
+ id: randomUUID(),
149
+ role: 'assistant',
150
+ content: `⚠️ Task run failed:\n\n\`\`\`\n${errorMsg}\n\`\`\``,
151
+ createdAt: new Date().toISOString(),
152
+ });
153
+ await saveTaskRun(task.id, {
154
+ runId,
155
+ timestamp: new Date().toISOString(),
156
+ status: 'failure',
157
+ error: errorMsg,
158
+ messages: chatMessages,
159
+ });
160
+ }
161
+ finally {
162
+ // Always release the lock so future ticks can re-schedule this task
163
+ runningTasks.delete(task.id);
164
+ }
165
+ }
166
+ const lastCheckedMinutes = new Map();
167
+ export const HeartbeatStrategy = {
168
+ type: 'heartbeat',
169
+ async tick(task, now) {
170
+ const currentMinuteStr = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}`;
171
+ if (lastCheckedMinutes.get(task.id) === currentMinuteStr)
172
+ return;
173
+ if (matchesCron(task.cron, now)) {
174
+ lastCheckedMinutes.set(task.id, currentMinuteStr);
175
+ console.log(`[scheduler] Task "${task.name}" matches cron expression "${task.cron}". Launching run...`);
176
+ void executeTaskRun(task).catch((err) => {
177
+ console.error(`[scheduler] Background task run failed to execute:`, err);
178
+ });
179
+ }
180
+ },
181
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Shared in-process locks across scheduler strategies.
3
+ *
4
+ * Heartbeat uses plain task IDs as keys; Telegram uses compound `${taskId}:${chatId}`
5
+ * keys so concurrent chats can progress while serialising per-chat.
6
+ */
7
+ export declare const runningTasks: Set<string>;
8
+ //# sourceMappingURL=locks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/locks.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,YAAY,aAAoB,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Shared in-process locks across scheduler strategies.
3
+ *
4
+ * Heartbeat uses plain task IDs as keys; Telegram uses compound `${taskId}:${chatId}`
5
+ * keys so concurrent chats can progress while serialising per-chat.
6
+ */
7
+ export const runningTasks = new Set();
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Returns the folder where scheduler logs are cached under ~/.caretaker/scheduler-logs
3
+ */
4
+ export declare function schedulerLogsDir(): string;
5
+ /**
6
+ * Returns the path to a specific task's JSONL log file
7
+ */
8
+ export declare function schedulerLogPath(taskId: string): string;
9
+ /**
10
+ * Ensures the scheduler logs folder exists
11
+ */
12
+ export declare function ensureSchedulerLogsDir(): Promise<void>;
13
+ /**
14
+ * Parses and returns all execution runs for a given task ID, sorted by timestamp descending (newest first).
15
+ */
16
+ export declare function loadTaskRuns(taskId: string): Promise<any[]>;
17
+ /**
18
+ * Appends a task execution run record to the task's JSONL file.
19
+ */
20
+ export declare function saveTaskRun(taskId: string, run: any): Promise<void>;
21
+ //# sourceMappingURL=logs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/logs.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAEzC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED;;GAEG;AACH,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC,CAK5D;AAED;;GAEG;AACH,wBAAsB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAqBjE;AAED;;GAEG;AACH,wBAAsB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAIzE"}
@@ -0,0 +1,62 @@
1
+ import { join } from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readFile, appendFile } from 'node:fs/promises';
4
+ import { dataDir } from '../../../store/json.js';
5
+ /**
6
+ * Returns the folder where scheduler logs are cached under ~/.caretaker/scheduler-logs
7
+ */
8
+ export function schedulerLogsDir() {
9
+ return join(dataDir(), 'scheduler-logs');
10
+ }
11
+ /**
12
+ * Returns the path to a specific task's JSONL log file
13
+ */
14
+ export function schedulerLogPath(taskId) {
15
+ return join(schedulerLogsDir(), `${taskId}.jsonl`);
16
+ }
17
+ /**
18
+ * Ensures the scheduler logs folder exists
19
+ */
20
+ export async function ensureSchedulerLogsDir() {
21
+ const dir = schedulerLogsDir();
22
+ if (!existsSync(dir)) {
23
+ await mkdir(dir, { recursive: true, mode: 0o700 });
24
+ }
25
+ }
26
+ /**
27
+ * Parses and returns all execution runs for a given task ID, sorted by timestamp descending (newest first).
28
+ */
29
+ export async function loadTaskRuns(taskId) {
30
+ const path = schedulerLogPath(taskId);
31
+ if (!existsSync(path))
32
+ return [];
33
+ try {
34
+ const raw = await readFile(path, 'utf8');
35
+ const lines = raw.split('\n');
36
+ const runs = [];
37
+ for (const line of lines) {
38
+ const trimmed = line.trim();
39
+ if (!trimmed)
40
+ continue;
41
+ try {
42
+ runs.push(JSON.parse(trimmed));
43
+ }
44
+ catch (err) {
45
+ console.warn(`[scheduler/logs] failed to parse line: ${err}`);
46
+ }
47
+ }
48
+ return runs.reverse();
49
+ }
50
+ catch (err) {
51
+ console.error(`[scheduler/logs] failed to load runs for task ${taskId}:`, err);
52
+ return [];
53
+ }
54
+ }
55
+ /**
56
+ * Appends a task execution run record to the task's JSONL file.
57
+ */
58
+ export async function saveTaskRun(taskId, run) {
59
+ await ensureSchedulerLogsDir();
60
+ const path = schedulerLogPath(taskId);
61
+ await appendFile(path, JSON.stringify(run) + '\n', { mode: 0o600 });
62
+ }
@@ -0,0 +1,6 @@
1
+ import type { ScheduledTaskConfig } from '../../../types.js';
2
+ export interface SchedulerStrategy {
3
+ type: ScheduledTaskConfig['type'];
4
+ tick(task: ScheduledTaskConfig, now: Date): Promise<void>;
5
+ }
6
+ //# sourceMappingURL=strategy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/strategy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAE7D,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAClC,IAAI,CAAC,IAAI,EAAE,mBAAmB,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3D"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { AgentConfig, ProviderConfig } from '../../../types.js';
2
+ import type { Tool } from '../../../harness/tools/types.js';
3
+ export declare const MAX_REVIEW_ROUNDS = 3;
4
+ export declare function reviewPrompt(objective: string, branch: string, round: number): string;
5
+ export declare function parseReviewVerdict(text: string): 'pass' | 'changes';
6
+ export declare function runDoneReview(opts: {
7
+ agent: AgentConfig;
8
+ provider: ProviderConfig;
9
+ tools: Tool[];
10
+ objective: string;
11
+ branch: string;
12
+ workingDir: string;
13
+ round: number;
14
+ }): Promise<{
15
+ verdict: 'pass' | 'changes';
16
+ text: string;
17
+ }>;
18
+ //# sourceMappingURL=task_review.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task_review.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_review.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAG5D,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CA2BrF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMnE;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE;IACxC,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;CACf,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAsCzD"}
@@ -0,0 +1,77 @@
1
+ import * as harness from '../../../harness/index.js';
2
+ import { CLAUDE_CODE_MAX_RUN_MS } from './task_roles.js';
3
+ export const MAX_REVIEW_ROUNDS = 3;
4
+ export function reviewPrompt(objective, branch, round) {
5
+ return `You are an INDEPENDENT code reviewer. You did not write this code, and your job is to find real problems — not to be agreeable. Do not rubber-stamp.
6
+
7
+ The autonomous task you are reviewing had this objective:
8
+ """
9
+ ${objective}
10
+ """
11
+
12
+ All of the task's work is committed to the git branch \`${branch}\`, checked out in your current working directory. Inspect it:
13
+ - \`git log --oneline\` to see the commits made for this task.
14
+ - Review the full change with \`git show\` / \`git diff\` across those commits.
15
+ - Read the changed files where it matters.
16
+
17
+ Review for:
18
+ - Correctness: real bugs, broken logic, unhandled cases.
19
+ - Completeness: does it ACTUALLY achieve the objective, or only part of it?
20
+ - Regressions: does it break existing behavior?
21
+ - Tests: is the new behavior covered, if the repo expects tests?
22
+ Verify claims against the code — do not trust comments or commit messages.
23
+
24
+ Be concrete: cite files and lines. If the work is genuinely complete and correct, say so plainly.
25
+
26
+ This is review round ${round} of at most ${MAX_REVIEW_ROUNDS}.
27
+
28
+ End your response with EXACTLY ONE of these two lines, and nothing after it:
29
+ REVIEW_RESULT: PASS
30
+ REVIEW_RESULT: CHANGES_REQUESTED`;
31
+ }
32
+ export function parseReviewVerdict(text) {
33
+ // Fail-safe: anything that is not an explicit trailing PASS counts as changes-requested.
34
+ const matches = text.match(/REVIEW_RESULT:\s*(PASS|CHANGES_REQUESTED)/gi);
35
+ if (!matches || matches.length === 0)
36
+ return 'changes';
37
+ const last = matches[matches.length - 1].toUpperCase();
38
+ return /:\s*PASS/.test(last) ? 'pass' : 'changes';
39
+ }
40
+ export async function runDoneReview(opts) {
41
+ // Strip task-state tools: the reviewer must not mutate the task; the harness decides.
42
+ const reviewTools = opts.tools.filter((t) => !t.name.startsWith('mcp__task__'));
43
+ // claude-code reviewer: bypass permissions like the native path, but no task
44
+ // bridge — parity with the mcp__task__ strip above (the agent's own
45
+ // mcpServers still pass through inside the runner).
46
+ const isClaudeCode = opts.provider.type === 'claude-code';
47
+ const claudeCode = isClaudeCode ? { permissionMode: 'bypassPermissions' } : undefined;
48
+ // Same wall-clock backstop as the task heartbeat: the Claude Code CLI has
49
+ // no --max-turns equivalent, so a runaway review pass would otherwise stall
50
+ // the reviewing gate indefinitely.
51
+ let ccTimer;
52
+ let signal;
53
+ if (isClaudeCode) {
54
+ const ccController = new AbortController();
55
+ ccTimer = setTimeout(() => ccController.abort(), CLAUDE_CODE_MAX_RUN_MS);
56
+ signal = ccController.signal;
57
+ }
58
+ try {
59
+ const result = await harness.run({
60
+ agent: { ...opts.agent, permissionMode: 'bypassPermissions' }, // unattended: mirror the auto-approve confirm gate
61
+ provider: opts.provider,
62
+ tools: reviewTools,
63
+ prompt: reviewPrompt(opts.objective, opts.branch, opts.round),
64
+ history: [],
65
+ workingDir: opts.workingDir,
66
+ signal,
67
+ ...(claudeCode ? { claudeCode } : {}),
68
+ }, {
69
+ confirmTool: async () => 'once', // unattended
70
+ });
71
+ return { verdict: parseReviewVerdict(result.text), text: result.text };
72
+ }
73
+ finally {
74
+ if (ccTimer)
75
+ clearTimeout(ccTimer);
76
+ }
77
+ }
@@ -0,0 +1,22 @@
1
+ import { Task } from '../../../store/db.js';
2
+ import type { AgentConfig, ProjectConfig } from '../../../types.js';
3
+ import type { Tool } from '../../../harness/tools/types.js';
4
+ export type TaskRole = 'planner' | 'developer' | 'reviewer';
5
+ export declare const CLAUDE_CODE_MAX_RUN_MS: number;
6
+ export declare function resolveRoleAgent(role: TaskRole, task: Task, project: ProjectConfig | undefined, agents: AgentConfig[]): AgentConfig | undefined;
7
+ export declare function resolvePlanningEnabled(task: Pick<Task, 'planningEnabled'>, project?: Pick<ProjectConfig, 'planningEnabled'> | null): boolean;
8
+ export declare function resolveReviewEnabled(task: Pick<Task, 'reviewEnabled'>, project?: Pick<ProjectConfig, 'reviewEnabled'> | null): boolean;
9
+ export declare function resolveSddEnabled(task: Pick<Task, 'sddEnabled'>, project?: Pick<ProjectConfig, 'sddEnabled'> | null): boolean;
10
+ /**
11
+ * Where does an (re)activated task go? Planning, unless planning is disabled
12
+ * or a plan message is already on record. Deterministic and derived from the
13
+ * message stream, like review rounds — no stored phase counter.
14
+ */
15
+ export declare function activationStatus(task: Task, project: ProjectConfig | undefined): Promise<'planning' | 'active'>;
16
+ /** Builtins the planner must not have: everything that mutates the workspace.
17
+ * bash is stripped too — it cannot be made read-only, and the planner keeps
18
+ * read_file/glob/grep for exploration. Same post-filter mechanism as the
19
+ * reviewer's mcp__task__* strip in task_review.ts. */
20
+ export declare const PLANNER_TOOL_DENYLIST: Set<string>;
21
+ export declare function filterPlannerTools(tools: Tool[], sdd?: boolean): Tool[];
22
+ //# sourceMappingURL=task_roles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task_roles.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_roles.ts"],"names":[],"mappings":"AAGA,OAAO,EAAY,IAAI,EAAe,MAAM,sBAAsB,CAAC;AACnE,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iCAAiC,CAAC;AAE5D,MAAM,MAAM,QAAQ,GAAG,SAAS,GAAG,WAAW,GAAG,UAAU,CAAC;AAM5D,eAAO,MAAM,sBAAsB,QAAc,CAAC;AAElD,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,QAAQ,EACd,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,aAAa,GAAG,SAAS,EAClC,MAAM,EAAE,WAAW,EAAE,GACpB,WAAW,GAAG,SAAS,CAOzB;AAED,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,iBAAiB,CAAC,EACnC,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,iBAAiB,CAAC,GAAG,IAAI,GACtD,OAAO,CAET;AAED,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,EACjC,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,GAAG,IAAI,GACpD,OAAO,CAET;AAED,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,EAC9B,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,YAAY,CAAC,GAAG,IAAI,GACjD,OAAO,CAET;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,aAAa,GAAG,SAAS,GACjC,OAAO,CAAC,UAAU,GAAG,QAAQ,CAAC,CAIhC;AAED;;;uDAGuD;AACvD,eAAO,MAAM,qBAAqB,aAAkD,CAAC;AAsBrF,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,GAAG,UAAQ,GAAG,IAAI,EAAE,CAOrE"}
@@ -0,0 +1,70 @@
1
+ // Role and phase resolution for the autonomous task system.
2
+ // The existing task.agentId -> project.agentId -> agents[0] chain IS the
3
+ // developer role; planner/reviewer optionally override and degrade onto it.
4
+ import { runQuery } from '../../../store/db.js';
5
+ // ponytail: hard wall-clock cap; make configurable if real runs need more
6
+ // The Claude Code CLI has no --max-turns equivalent, so a claude-code run has
7
+ // no native turn cap. Without a wall-clock backstop a runaway run would stall
8
+ // the whole heartbeat (and, for reviews, the review gate) indefinitely.
9
+ export const CLAUDE_CODE_MAX_RUN_MS = 15 * 60_000;
10
+ export function resolveRoleAgent(role, task, project, agents) {
11
+ const pick = (id) => (id ? agents.find((a) => a.id === id) : undefined);
12
+ const developer = pick(task.agentId) || pick(project?.agentId) || agents[0];
13
+ if (role === 'developer')
14
+ return developer;
15
+ const taskRoleId = role === 'planner' ? task.plannerAgentId : task.reviewerAgentId;
16
+ const projectRoleId = role === 'planner' ? project?.plannerAgentId : project?.reviewerAgentId;
17
+ return pick(taskRoleId) || pick(projectRoleId) || developer;
18
+ }
19
+ export function resolvePlanningEnabled(task, project) {
20
+ return task.planningEnabled ?? project?.planningEnabled ?? true;
21
+ }
22
+ export function resolveReviewEnabled(task, project) {
23
+ return task.reviewEnabled ?? project?.reviewEnabled ?? true;
24
+ }
25
+ export function resolveSddEnabled(task, project) {
26
+ return task.sddEnabled ?? project?.sddEnabled ?? false;
27
+ }
28
+ /**
29
+ * Where does an (re)activated task go? Planning, unless planning is disabled
30
+ * or a plan message is already on record. Deterministic and derived from the
31
+ * message stream, like review rounds — no stored phase counter.
32
+ */
33
+ export async function activationStatus(task, project) {
34
+ if (!resolvePlanningEnabled(task, project))
35
+ return 'active';
36
+ const messages = (await runQuery(`SELECT * FROM task_messages WHERE taskId = ${task.id}`));
37
+ return messages.some((m) => m.messageType === 'plan') ? 'active' : 'planning';
38
+ }
39
+ /** Builtins the planner must not have: everything that mutates the workspace.
40
+ * bash is stripped too — it cannot be made read-only, and the planner keeps
41
+ * read_file/glob/grep for exploration. Same post-filter mechanism as the
42
+ * reviewer's mcp__task__* strip in task_review.ts. */
43
+ export const PLANNER_TOOL_DENYLIST = new Set(['write', 'edit', 'multiedit', 'bash']);
44
+ /** Tools the SDD wrapper applies to: workspace writers that take a `path` arg. */
45
+ const SDD_WRAPPED_TOOLS = new Set(['write', 'edit', 'multiedit']);
46
+ /** Wrap a writing tool so it only accepts markdown targets. Everything else
47
+ * about the tool (schema, sandbox, read-before-write guard) is unchanged —
48
+ * the guard runs before delegation. Guard-rail, not a security boundary. */
49
+ function markdownOnly(tool) {
50
+ return {
51
+ ...tool,
52
+ description: `${tool.description} In this planning phase, only markdown (.md) files are accepted.`,
53
+ execute: async (args, ctx) => {
54
+ const p = args.path;
55
+ if (typeof p !== 'string' || !p.toLowerCase().endsWith('.md')) {
56
+ return { content: 'Error: planning phase (SDD mode): only markdown (.md) files may be written.' };
57
+ }
58
+ return tool.execute(args, ctx);
59
+ },
60
+ };
61
+ }
62
+ export function filterPlannerTools(tools, sdd = false) {
63
+ if (!sdd)
64
+ return tools.filter((t) => !PLANNER_TOOL_DENYLIST.has(t.name));
65
+ // SDD mode: bash stays out (the actual implementation brake); the file
66
+ // writers survive but only for markdown targets.
67
+ return tools
68
+ .filter((t) => t.name !== 'bash')
69
+ .map((t) => (SDD_WRAPPED_TOOLS.has(t.name) ? markdownOnly(t) : t));
70
+ }
@@ -0,0 +1,2 @@
1
+ export declare function runTaskHeartbeatTick(now: Date): Promise<void>;
2
+ //# sourceMappingURL=task_strategy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task_strategy.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_strategy.ts"],"names":[],"mappings":"AAsHA,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAySnE"}