@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,437 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import * as harness from '../../../harness/index.js';
3
+ import { loadAgents, loadConfig } from '../../../store/json.js';
4
+ import { getTaskById, saveTask, addTaskMessage, updateTaskMessageContent, runQuery } from '../../../store/db.js';
5
+ import { runningTasks } from './locks.js';
6
+ import { isGitRepo, ensureWorktree, agentDirIn, commitWip, finalizeDone } from '../../../lib/task_git.js';
7
+ import { runDoneReview, MAX_REVIEW_ROUNDS } from './task_review.js';
8
+ import { claudeCodeTaskExtras } from '../../../harness/claude_code_runner.js';
9
+ import { issueBridgeToken, revokeBridgeToken, getTaskBridgeUrl } from '../mcp_bridge.js';
10
+ import { resolveRoleAgent, resolveReviewEnabled, resolveSddEnabled, filterPlannerTools, CLAUDE_CODE_MAX_RUN_MS, } from './task_roles.js';
11
+ function buildPrompt(systemPrompt, taskId, taskTitle, maxRunSeconds, maxTurns, workingDir) {
12
+ const workspaceLine = workingDir
13
+ ? `\n**Your workspace is: \`${workingDir}\`** — operate exclusively inside this directory. Do NOT reference or modify any other path on the filesystem.\n`
14
+ : '';
15
+ return `${systemPrompt}
16
+ ${workspaceLine}
17
+ ---
18
+
19
+ You are running in **autonomous task mode**. Your job is to advance one step toward the objective.
20
+
21
+ You have no memory of previous invocations. Your only memory is in the task messages.
22
+ It is therefore **mandatory** that you always leave a detailed record of what you did,
23
+ so the next invocation can pick up exactly where you left off.
24
+
25
+ You have **${maxRunSeconds} seconds** for this invocation. Plan accordingly — do not start
26
+ work you cannot finish and document within that time.
27
+
28
+ Your agent runtime allows a maximum of **${maxTurns} turns** per invocation. Use them wisely.
29
+
30
+ On each invocation:
31
+ 1. Read the current state with \`task_get_state\` (objective, checklist, recent messages)
32
+ 2. From the recent messages, understand what has already been done and what remains
33
+ 3. Identify the next step in the checklist
34
+ 4. Do the necessary work using the other tools available to you
35
+ 5. Update the checklist with \`task_update_checklist_item\`
36
+ 6. **Mandatory:** call \`task_add_message\` with a detailed summary of:
37
+ - what you did in this session
38
+ - which tools you used and what the results were
39
+ - what the recommended next step is
40
+ - any issues encountered or decisions made
41
+ 7. If the objective is complete, close with \`task_complete\`
42
+ 8. If you need human input to proceed, call \`task_block\` with a clear explanation
43
+ 9. Otherwise, stop — you will continue in the next cycle
44
+
45
+ Do NOT try to complete everything in one invocation.
46
+ Do ONE meaningful step, then stop and document.
47
+
48
+ TASK ID: ${taskId}
49
+ TITLE: ${taskTitle}`;
50
+ }
51
+ function buildPlanningPrompt(systemPrompt, taskId, taskTitle, maxRunSeconds, maxTurns, workingDir, sdd) {
52
+ const workspaceLine = workingDir
53
+ ? `\n**Your workspace is: \`${workingDir}\`** — operate exclusively inside this directory.\n`
54
+ : '';
55
+ const accessBlock = sdd
56
+ ? `You are in **SDD mode**: you may create and edit **markdown (.md) documents only** — specs, plans, ADRs — and you MUST follow this project's own documentation conventions (see the project context / AGENTS.md). Everything else stays read-only: explore with \`read_file\`, \`glob\`, and \`grep\`; non-markdown files and \`bash\` are not available. Reference the documents you created in the plan you submit.`
57
+ : `You have read-only access to the workspace: explore it with \`read_file\`, \`glob\`, and
58
+ \`grep\`. Write tools and \`bash\` are not available in this phase.`;
59
+ return `${systemPrompt}
60
+ ${workspaceLine}
61
+ ---
62
+
63
+ You are running in **autonomous task mode**, in the **PLANNING phase**. Your only job
64
+ is to produce an implementation plan for this task — you must NOT ${sdd ? 'implement anything; markdown documents are the only files you may touch' : 'modify anything'}.
65
+
66
+ ${accessBlock}
67
+
68
+ You have no memory of previous invocations. Your only memory is in the task messages.
69
+ You have **${maxRunSeconds} seconds** and at most **${maxTurns} turns** for this invocation.
70
+
71
+ On each invocation:
72
+ 1. Read the current state with \`task_get_state\` (objective, checklist, recent messages)
73
+ 2. Explore the workspace as needed to understand how to achieve the objective
74
+ 3. When the plan is ready:
75
+ - Replace the checklist with concrete execution steps via \`task_update_checklist\`
76
+ - Call \`task_submit_plan\` with the full plan (markdown). This ends the planning
77
+ phase and starts execution — the executing agent will read your plan from the
78
+ task thread, so make it self-contained.
79
+ 4. If you cannot finish the plan in this invocation, call \`task_add_message\` with your
80
+ findings so far, then stop — you will continue planning in the next cycle.
81
+
82
+ Do NOT call \`task_complete\` in this phase.
83
+
84
+ TASK ID: ${taskId}
85
+ TITLE: ${taskTitle}`;
86
+ }
87
+ export async function runTaskHeartbeatTick(now) {
88
+ // 1. Pick one active, unlocked task (oldest updatedAt first). Archived tasks
89
+ // are excluded from the heartbeat — they are deliberately parked.
90
+ const taskRows = (await runQuery(`SELECT * FROM tasks WHERE (status = 'active' OR status = 'reviewing' OR status = 'planning') AND lockedAt IS NULL`));
91
+ const eligible = taskRows.filter((t) => !t.archived);
92
+ if (eligible.length === 0) {
93
+ return;
94
+ }
95
+ // Sort by updatedAt asc to find the oldest
96
+ eligible.sort((a, b) => new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime());
97
+ const task = eligible[0];
98
+ const lockKey = `task_db_${task.id}`;
99
+ if (runningTasks.has(lockKey)) {
100
+ return;
101
+ }
102
+ runningTasks.add(lockKey);
103
+ console.log(`[task_heartbeat] Claimed task #${task.id}: "${task.title}"`);
104
+ // Update lockedAt in DB
105
+ task.lockedAt = new Date().toISOString();
106
+ task.updatedAt = new Date().toISOString();
107
+ await saveTask(task);
108
+ let liveMsgId = null;
109
+ try {
110
+ // 2. Load Config & Project
111
+ const config = await loadConfig();
112
+ const project = (config.projects || []).find((p) => p.id === task.projectId);
113
+ if (!project) {
114
+ throw new Error(`Project with ID ${task.projectId} not found for task #${task.id}`);
115
+ }
116
+ // 3. Load Agent — resolved per role: the task's phase decides who runs.
117
+ // planner/reviewer overrides degrade onto the developer chain
118
+ // (task.agentId -> project.agentId -> agents[0]).
119
+ const agents = await loadAgents();
120
+ const role = task.status === 'reviewing' ? 'reviewer' : task.status === 'planning' ? 'planner' : 'developer';
121
+ const agent = resolveRoleAgent(role, task, project, agents);
122
+ if (!agent) {
123
+ throw new Error(`No agent configured in agents.json for project "${project.name}"`);
124
+ }
125
+ // 4. Load Provider
126
+ const provider = config.providers.find((p) => p.name === agent.provider);
127
+ if (!provider) {
128
+ throw new Error(`Provider "${agent.provider}" not found for agent "${agent.name}"`);
129
+ }
130
+ const baseWorkingDir = project.workingDir || agent.workingDir || process.cwd();
131
+ let workingDir = baseWorkingDir;
132
+ // Worktree isolation for git projects: lazily create a dedicated branch + worktree.
133
+ if (task.worktreePath) {
134
+ workingDir = await agentDirIn(task.worktreePath, baseWorkingDir);
135
+ }
136
+ else if (await isGitRepo(baseWorkingDir)) {
137
+ const wt = await ensureWorktree(baseWorkingDir, task.projectId, task.id, task.title);
138
+ task.branch = wt.branch;
139
+ task.worktreePath = wt.worktreePath;
140
+ await saveTask(task);
141
+ workingDir = wt.agentWorkingDir;
142
+ console.log(`[task_heartbeat] Task #${task.id} worktree ${wt.worktreePath} (branch ${wt.branch})`);
143
+ }
144
+ // Non-git projects fall through: workingDir stays baseWorkingDir (run in place).
145
+ // Ensure mcp__task__* is in agent.allowedTools
146
+ const baseTools = [...agent.allowedTools];
147
+ if (!baseTools.includes('mcp__task__*')) {
148
+ baseTools.push('mcp__task__*');
149
+ }
150
+ const effectiveAgent = {
151
+ ...agent,
152
+ allowedTools: baseTools,
153
+ permissionMode: 'bypassPermissions', // unattended: mirror the auto-approve confirm gate
154
+ };
155
+ // Resolve tools
156
+ let tools = await harness.resolveAgentTools(effectiveAgent, harness.tools);
157
+ // Reviewing tasks run one independent review pass on their branch as their
158
+ // own heartbeat cycle (not the agent's task loop), then transition. The
159
+ // review gate flag is read at decision time: disabling it while a task sits
160
+ // in reviewing finalizes the task directly on the next tick.
161
+ if (task.status === 'reviewing') {
162
+ await runReviewCycle({ task, project, agent: effectiveAgent, provider, tools, workingDir });
163
+ return; // the finally{} block still runs and releases the lock
164
+ }
165
+ const planning = task.status === 'planning';
166
+ const sdd = planning && resolveSddEnabled(task, project);
167
+ if (planning) {
168
+ // Read-only phase: strip workspace-mutating tools (same post-filter
169
+ // mechanism the review uses to strip mcp__task__*). In SDD mode the
170
+ // file writers survive, wrapped to markdown-only targets.
171
+ tools = filterPlannerTools(tools, sdd);
172
+ }
173
+ // Max turns: standard sonnet settings or maxTurns
174
+ const maxTurns = agent.maxTurns || 30;
175
+ const maxRunSeconds = 120; // 2 minutes
176
+ // 5. Construct prompt
177
+ const prompt = planning
178
+ ? buildPlanningPrompt(agent.systemPrompt, task.id, task.title, maxRunSeconds, maxTurns, workingDir, sdd)
179
+ : buildPrompt(agent.systemPrompt, task.id, task.title, maxRunSeconds, maxTurns, workingDir);
180
+ const checklistBefore = (task.checklist || []).filter((item) => item.status !== 'pending').length;
181
+ // Create a live assistant message in DB
182
+ const liveMsg = await addTaskMessage({
183
+ taskId: task.id,
184
+ role: 'assistant',
185
+ messageType: 'heartbeat_live',
186
+ content: '',
187
+ });
188
+ liveMsgId = liveMsg.id;
189
+ let buffer = '';
190
+ let lastWrite = 0;
191
+ const updateLiveContent = async (force = false) => {
192
+ if (liveMsgId === null)
193
+ return;
194
+ const nowMs = Date.now();
195
+ if (force || nowMs - lastWrite > 2500) {
196
+ lastWrite = nowMs;
197
+ await updateTaskMessageContent(liveMsgId, buffer);
198
+ }
199
+ };
200
+ // Load full history for replay
201
+ const historyMessages = (await runQuery(`SELECT * FROM task_messages WHERE taskId = ${task.id}`));
202
+ historyMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
203
+ // Map history to loop-compatible message records
204
+ const historyRecords = historyMessages
205
+ .filter((m) => m.messageType === 'chat' || m.messageType === 'heartbeat' || m.messageType === 'tool_call' || m.messageType === 'review' || m.messageType === 'plan')
206
+ .map((m) => ({
207
+ id: randomUUID(),
208
+ v: 1,
209
+ type: 'message',
210
+ role: m.role,
211
+ content: m.content,
212
+ toolCallId: m.toolCallId || undefined,
213
+ createdAt: m.createdAt,
214
+ }));
215
+ console.log(`[task_heartbeat] Running agent "${agent.name}" on task #${task.id}...`);
216
+ // claude-code agents get role-scoped permission/tool extras and, when a
217
+ // task bridge is running, an injected mcp__task server so the CLI can
218
+ // still call task_get_state/task_submit_plan/etc despite --strict-mcp-config.
219
+ const isClaudeCode = provider?.type === 'claude-code';
220
+ let bridgeToken;
221
+ let claudeCode;
222
+ // Claude Code runs have no native turn cap (the CLI has no --max-turns),
223
+ // so bound them with a wall-clock timeout instead; native runs stay
224
+ // governed by maxTurns as usual.
225
+ let ccTimer;
226
+ let signal;
227
+ if (isClaudeCode) {
228
+ const bridgeUrl = getTaskBridgeUrl();
229
+ bridgeToken = bridgeUrl ? issueBridgeToken() : undefined;
230
+ claudeCode = claudeCodeTaskExtras({
231
+ planning,
232
+ sdd,
233
+ bridge: bridgeUrl && bridgeToken ? { url: bridgeUrl, token: bridgeToken } : undefined,
234
+ });
235
+ if (!bridgeUrl) {
236
+ console.warn('[tasks] claude-code agent without task bridge URL — task tools unavailable this run');
237
+ }
238
+ const ccController = new AbortController();
239
+ ccTimer = setTimeout(() => ccController.abort(), CLAUDE_CODE_MAX_RUN_MS);
240
+ signal = ccController.signal;
241
+ }
242
+ try {
243
+ await harness.run({
244
+ agent: effectiveAgent,
245
+ provider,
246
+ tools,
247
+ prompt,
248
+ history: historyRecords,
249
+ workingDir,
250
+ claudeCode,
251
+ signal,
252
+ }, {
253
+ onChunk: (chunk) => {
254
+ buffer += chunk;
255
+ void updateLiveContent();
256
+ },
257
+ onToolCall: (id, name, args) => {
258
+ void addTaskMessage({
259
+ taskId: task.id,
260
+ role: 'assistant',
261
+ messageType: 'tool_call',
262
+ content: `${name} ${JSON.stringify(args)}`,
263
+ toolCallId: id,
264
+ });
265
+ },
266
+ confirmTool: async () => 'once', // Autonomous execution auto-approves tools
267
+ });
268
+ }
269
+ finally {
270
+ if (bridgeToken)
271
+ revokeBridgeToken(bridgeToken);
272
+ if (ccTimer)
273
+ clearTimeout(ccTimer);
274
+ }
275
+ // Finalize live message
276
+ if (liveMsgId !== null) {
277
+ await updateTaskMessageContent(liveMsgId, buffer, 'heartbeat');
278
+ liveMsgId = null;
279
+ }
280
+ // 6. Reload task to evaluate checklist progress
281
+ const refreshedTask = await getTaskById(task.id);
282
+ if (refreshedTask && (refreshedTask.status === 'active' || refreshedTask.status === 'planning')) {
283
+ const checklistAfter = (refreshedTask.checklist || []).filter((item) => item.status !== 'pending').length;
284
+ let noProgressCount = refreshedTask.noProgressCount;
285
+ if (checklistAfter > checklistBefore) {
286
+ noProgressCount = 0;
287
+ console.log(`[task_heartbeat] Task #${task.id} made checklist progress: ${checklistBefore} -> ${checklistAfter}`);
288
+ }
289
+ else {
290
+ noProgressCount++;
291
+ console.log(`[task_heartbeat] Task #${task.id} made no progress (${noProgressCount}/${refreshedTask.maxNoProgress})`);
292
+ }
293
+ refreshedTask.noProgressCount = noProgressCount;
294
+ refreshedTask.updatedAt = new Date().toISOString();
295
+ if (noProgressCount >= refreshedTask.maxNoProgress) {
296
+ refreshedTask.status = 'paused';
297
+ await addTaskMessage({
298
+ taskId: task.id,
299
+ role: 'assistant',
300
+ messageType: 'system',
301
+ content: `Auto-paused: no checklist progress after ${noProgressCount} iterations.`,
302
+ });
303
+ console.log(`[task_heartbeat] Task #${task.id} auto-paused due to no progress.`);
304
+ }
305
+ await saveTask(refreshedTask);
306
+ }
307
+ // Git lifecycle: commit progress every cycle. When the agent has just
308
+ // completed the task it is now 'reviewing' (review runs next tick as its
309
+ // own cycle) — or already 'done' when the review gate is disabled, in
310
+ // which case the worktree is finalized here, after the run has ended.
311
+ const gitTask = await getTaskById(task.id);
312
+ if (gitTask && gitTask.worktreePath) {
313
+ try {
314
+ if (await commitWip(gitTask.worktreePath, gitTask.title)) {
315
+ console.log(`[task_heartbeat] Task #${task.id} committed WIP to ${gitTask.branch}`);
316
+ }
317
+ if (gitTask.status === 'done') {
318
+ await finalizeDone(gitTask.worktreePath);
319
+ gitTask.worktreePath = null;
320
+ gitTask.updatedAt = new Date().toISOString();
321
+ await saveTask(gitTask);
322
+ console.log(`[task_heartbeat] Task #${task.id} done (review gate off): worktree removed, branch ${gitTask.branch} kept`);
323
+ }
324
+ }
325
+ catch (gitErr) {
326
+ console.error(`[task_heartbeat] Task #${task.id} git step failed:`, gitErr);
327
+ }
328
+ }
329
+ }
330
+ catch (err) {
331
+ const errorMsg = err instanceof Error ? err.message : String(err);
332
+ console.error(`[task_heartbeat] Task #${task.id} run failed:`, errorMsg);
333
+ if (liveMsgId !== null) {
334
+ await updateTaskMessageContent(liveMsgId, `⚠️ Heartbeat cycle failed: ${errorMsg}`, 'heartbeat');
335
+ }
336
+ await addTaskMessage({
337
+ taskId: task.id,
338
+ role: 'assistant',
339
+ messageType: 'system',
340
+ content: `Heartbeat error: ${errorMsg}`,
341
+ });
342
+ }
343
+ finally {
344
+ // 7. Ensure task is unlocked
345
+ const finalCheck = await getTaskById(task.id);
346
+ if (finalCheck) {
347
+ finalCheck.lockedAt = null;
348
+ finalCheck.updatedAt = new Date().toISOString();
349
+ await saveTask(finalCheck);
350
+ }
351
+ runningTasks.delete(lockKey);
352
+ console.log(`[task_heartbeat] Lock released for task #${task.id}`);
353
+ }
354
+ }
355
+ async function runReviewCycle(opts) {
356
+ const { task, project, agent, provider, tools, workingDir } = opts;
357
+ if (!task.worktreePath)
358
+ return; // reviewing implies a worktree; nothing to review otherwise
359
+ // Review gate disabled (task or project level): finalize directly, no review.
360
+ if (!resolveReviewEnabled(task, project)) {
361
+ await commitWip(task.worktreePath, task.title);
362
+ const current = await getTaskById(task.id);
363
+ if (!current || current.status !== 'reviewing')
364
+ return;
365
+ await finalizeDone(current.worktreePath);
366
+ current.status = 'done';
367
+ current.worktreePath = null;
368
+ current.updatedAt = new Date().toISOString();
369
+ await saveTask(current);
370
+ console.log(`[task_heartbeat] Task #${task.id} review gate disabled: finalized as done, branch ${current.branch} kept`);
371
+ return;
372
+ }
373
+ // Finalize the agent's last work so the branch is complete before review.
374
+ await commitWip(task.worktreePath, task.title);
375
+ // Round is derived from the review-message stream, never a stored counter.
376
+ const priorReviews = (await runQuery(`SELECT * FROM task_messages WHERE taskId = ${task.id}`)).filter((m) => m.messageType === 'review').length;
377
+ const round = priorReviews + 1;
378
+ let verdict = 'pass';
379
+ let reviewText = '';
380
+ try {
381
+ const review = await runDoneReview({
382
+ agent,
383
+ provider,
384
+ tools,
385
+ objective: task.objective,
386
+ branch: task.branch || '(unknown)',
387
+ workingDir,
388
+ round,
389
+ });
390
+ verdict = review.verdict;
391
+ reviewText = review.text;
392
+ }
393
+ catch (reviewErr) {
394
+ // A broken review must not trap the task in reviewing — finalize as pass.
395
+ console.error(`[task_heartbeat] Task #${task.id} review failed, finalizing:`, reviewErr);
396
+ verdict = 'pass';
397
+ }
398
+ // Respect a Pause that arrived mid-review: only transition if still reviewing.
399
+ const current = await getTaskById(task.id);
400
+ if (!current || current.status !== 'reviewing') {
401
+ console.log(`[task_heartbeat] Task #${task.id} left reviewing mid-review (now ${current?.status}); skipping transition.`);
402
+ return;
403
+ }
404
+ if (reviewText) {
405
+ await addTaskMessage({
406
+ taskId: task.id,
407
+ role: 'user',
408
+ messageType: 'review',
409
+ content: `[CODE REVIEW round ${round}/${MAX_REVIEW_ROUNDS}] verdict=${verdict}\n\n${reviewText}`,
410
+ });
411
+ }
412
+ console.log(`[task_heartbeat] Task #${task.id} review round ${round}: ${verdict}`);
413
+ if (verdict === 'changes' && round < MAX_REVIEW_ROUNDS) {
414
+ // Reopen: keep the worktree; the review message is replayed to the agent next cycle.
415
+ current.status = 'active';
416
+ current.noProgressCount = 0;
417
+ current.updatedAt = new Date().toISOString();
418
+ await saveTask(current);
419
+ console.log(`[task_heartbeat] Task #${task.id} reopened by review (round ${round}).`);
420
+ }
421
+ else {
422
+ if (verdict === 'changes') {
423
+ await addTaskMessage({
424
+ taskId: task.id,
425
+ role: 'assistant',
426
+ messageType: 'system',
427
+ content: `Finished as done despite outstanding review findings after ${MAX_REVIEW_ROUNDS} rounds.`,
428
+ });
429
+ }
430
+ await finalizeDone(current.worktreePath);
431
+ current.status = 'done';
432
+ current.worktreePath = null;
433
+ current.updatedAt = new Date().toISOString();
434
+ await saveTask(current);
435
+ console.log(`[task_heartbeat] Task #${task.id} done: worktree removed, branch ${current.branch} kept`);
436
+ }
437
+ }
@@ -0,0 +1,7 @@
1
+ import type { SchedulerStrategy } from './strategy.js';
2
+ export declare function saveTelegramOffset(taskId: string, updateId: number): Promise<void>;
3
+ export declare function loadTelegramOffset(taskId: string): Promise<number | undefined>;
4
+ export declare function splitMessage(text: string, maxLen?: number): string[];
5
+ export declare function runTelegramPollerTick(): Promise<void>;
6
+ export declare const TelegramStrategy: SchedulerStrategy;
7
+ //# sourceMappingURL=telegram.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telegram.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/telegram.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAsBxF;AAED,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAUpF;AAiED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,SAAO,GAAG,MAAM,EAAE,CA8ClE;AAkSD,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAiB3D;AAED,eAAO,MAAM,gBAAgB,EAAE,iBAK9B,CAAC"}