@ilya-lesikov/pi-pi 0.1.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 (271) hide show
  1. package/3p/pi-ask-user/index.ts +1835 -0
  2. package/3p/pi-ask-user/package.json +50 -0
  3. package/3p/pi-ask-user/single-select-layout.ts +203 -0
  4. package/3p/pi-lsp/extensions/lsp/client.ts +542 -0
  5. package/3p/pi-lsp/extensions/lsp/config.ts +135 -0
  6. package/3p/pi-lsp/extensions/lsp/effects/command.ts +42 -0
  7. package/3p/pi-lsp/extensions/lsp/effects/filesystem.ts +50 -0
  8. package/3p/pi-lsp/extensions/lsp/effects/runtime.ts +21 -0
  9. package/3p/pi-lsp/extensions/lsp/errors.ts +113 -0
  10. package/3p/pi-lsp/extensions/lsp/formatting.ts +315 -0
  11. package/3p/pi-lsp/extensions/lsp/index.ts +231 -0
  12. package/3p/pi-lsp/extensions/lsp/protocol.ts +209 -0
  13. package/3p/pi-lsp/extensions/lsp/retry.ts +39 -0
  14. package/3p/pi-lsp/extensions/lsp/tools/programs.ts +293 -0
  15. package/3p/pi-lsp/extensions/lsp/tools.ts +89 -0
  16. package/3p/pi-lsp/extensions/lsp/types.ts +243 -0
  17. package/3p/pi-lsp/package.json +54 -0
  18. package/3p/pi-plannotator/AGENTS.md +583 -0
  19. package/3p/pi-plannotator/apps/pi-extension/README.md +228 -0
  20. package/3p/pi-plannotator/apps/pi-extension/assistant-message.ts +128 -0
  21. package/3p/pi-plannotator/apps/pi-extension/config.test.ts +166 -0
  22. package/3p/pi-plannotator/apps/pi-extension/config.ts +318 -0
  23. package/3p/pi-plannotator/apps/pi-extension/current-pi-session.ts +147 -0
  24. package/3p/pi-plannotator/apps/pi-extension/index.ts +1279 -0
  25. package/3p/pi-plannotator/apps/pi-extension/package.json +56 -0
  26. package/3p/pi-plannotator/apps/pi-extension/plannotator-browser.test.ts +13 -0
  27. package/3p/pi-plannotator/apps/pi-extension/plannotator-browser.ts +616 -0
  28. package/3p/pi-plannotator/apps/pi-extension/plannotator-events.ts +342 -0
  29. package/3p/pi-plannotator/apps/pi-extension/plannotator.json +12 -0
  30. package/3p/pi-plannotator/apps/pi-extension/server/agent-jobs.ts +515 -0
  31. package/3p/pi-plannotator/apps/pi-extension/server/ai-runtime.ts +169 -0
  32. package/3p/pi-plannotator/apps/pi-extension/server/annotations.ts +85 -0
  33. package/3p/pi-plannotator/apps/pi-extension/server/external-annotations.ts +189 -0
  34. package/3p/pi-plannotator/apps/pi-extension/server/handlers.ts +210 -0
  35. package/3p/pi-plannotator/apps/pi-extension/server/helpers.ts +78 -0
  36. package/3p/pi-plannotator/apps/pi-extension/server/ide.ts +46 -0
  37. package/3p/pi-plannotator/apps/pi-extension/server/integrations.ts +195 -0
  38. package/3p/pi-plannotator/apps/pi-extension/server/network.test.ts +158 -0
  39. package/3p/pi-plannotator/apps/pi-extension/server/network.ts +268 -0
  40. package/3p/pi-plannotator/apps/pi-extension/server/pr.ts +126 -0
  41. package/3p/pi-plannotator/apps/pi-extension/server/project.ts +64 -0
  42. package/3p/pi-plannotator/apps/pi-extension/server/reference.ts +362 -0
  43. package/3p/pi-plannotator/apps/pi-extension/server/serverAnnotate.ts +199 -0
  44. package/3p/pi-plannotator/apps/pi-extension/server/serverPlan.ts +505 -0
  45. package/3p/pi-plannotator/apps/pi-extension/server/serverReview.ts +1229 -0
  46. package/3p/pi-plannotator/apps/pi-extension/server/vcs.ts +121 -0
  47. package/3p/pi-plannotator/apps/pi-extension/server.test.ts +966 -0
  48. package/3p/pi-plannotator/apps/pi-extension/server.ts +44 -0
  49. package/3p/pi-plannotator/apps/pi-extension/tool-scope.test.ts +88 -0
  50. package/3p/pi-plannotator/apps/pi-extension/tool-scope.ts +39 -0
  51. package/3p/pi-plannotator/apps/pi-extension/tsconfig.json +16 -0
  52. package/3p/pi-plannotator/apps/pi-extension/vendor.sh +48 -0
  53. package/3p/pi-plannotator/package.json +53 -0
  54. package/3p/pi-plannotator/packages/ai/ai.test.ts +1407 -0
  55. package/3p/pi-plannotator/packages/ai/base-session.ts +94 -0
  56. package/3p/pi-plannotator/packages/ai/context.ts +250 -0
  57. package/3p/pi-plannotator/packages/ai/endpoints.ts +326 -0
  58. package/3p/pi-plannotator/packages/ai/index.ts +105 -0
  59. package/3p/pi-plannotator/packages/ai/package.json +21 -0
  60. package/3p/pi-plannotator/packages/ai/provider.ts +103 -0
  61. package/3p/pi-plannotator/packages/ai/providers/claude-agent-sdk.ts +447 -0
  62. package/3p/pi-plannotator/packages/ai/providers/codex-sdk.ts +430 -0
  63. package/3p/pi-plannotator/packages/ai/providers/command-path.ts +115 -0
  64. package/3p/pi-plannotator/packages/ai/providers/opencode-sdk.ts +546 -0
  65. package/3p/pi-plannotator/packages/ai/providers/pi-events.ts +110 -0
  66. package/3p/pi-plannotator/packages/ai/providers/pi-sdk-node.ts +425 -0
  67. package/3p/pi-plannotator/packages/ai/providers/pi-sdk.ts +469 -0
  68. package/3p/pi-plannotator/packages/ai/session-manager.ts +195 -0
  69. package/3p/pi-plannotator/packages/ai/tsconfig.json +15 -0
  70. package/3p/pi-plannotator/packages/ai/types.ts +379 -0
  71. package/3p/pi-plannotator/packages/server/agent-jobs.ts +538 -0
  72. package/3p/pi-plannotator/packages/server/agent-review-message.test.ts +135 -0
  73. package/3p/pi-plannotator/packages/server/agent-review-message.ts +243 -0
  74. package/3p/pi-plannotator/packages/server/ai-runtime.ts +108 -0
  75. package/3p/pi-plannotator/packages/server/annotate.ts +401 -0
  76. package/3p/pi-plannotator/packages/server/browser.test.ts +87 -0
  77. package/3p/pi-plannotator/packages/server/browser.ts +245 -0
  78. package/3p/pi-plannotator/packages/server/claude-review.ts +352 -0
  79. package/3p/pi-plannotator/packages/server/code-nav.ts +73 -0
  80. package/3p/pi-plannotator/packages/server/codex-review-schema.json +41 -0
  81. package/3p/pi-plannotator/packages/server/codex-review.ts +330 -0
  82. package/3p/pi-plannotator/packages/server/config.ts +8 -0
  83. package/3p/pi-plannotator/packages/server/draft.ts +1 -0
  84. package/3p/pi-plannotator/packages/server/editor-annotations.ts +76 -0
  85. package/3p/pi-plannotator/packages/server/external-annotations.test.ts +18 -0
  86. package/3p/pi-plannotator/packages/server/external-annotations.ts +207 -0
  87. package/3p/pi-plannotator/packages/server/git.ts +141 -0
  88. package/3p/pi-plannotator/packages/server/goal-setup.test.ts +55 -0
  89. package/3p/pi-plannotator/packages/server/goal-setup.ts +248 -0
  90. package/3p/pi-plannotator/packages/server/ide.ts +43 -0
  91. package/3p/pi-plannotator/packages/server/image.test.ts +63 -0
  92. package/3p/pi-plannotator/packages/server/image.ts +66 -0
  93. package/3p/pi-plannotator/packages/server/index.ts +648 -0
  94. package/3p/pi-plannotator/packages/server/integrations.test.ts +172 -0
  95. package/3p/pi-plannotator/packages/server/integrations.ts +214 -0
  96. package/3p/pi-plannotator/packages/server/jj.test.ts +69 -0
  97. package/3p/pi-plannotator/packages/server/jj.ts +86 -0
  98. package/3p/pi-plannotator/packages/server/p4.ts +417 -0
  99. package/3p/pi-plannotator/packages/server/package.json +40 -0
  100. package/3p/pi-plannotator/packages/server/path-utils.ts +18 -0
  101. package/3p/pi-plannotator/packages/server/pr.ts +146 -0
  102. package/3p/pi-plannotator/packages/server/project.test.ts +115 -0
  103. package/3p/pi-plannotator/packages/server/project.ts +45 -0
  104. package/3p/pi-plannotator/packages/server/reference-handlers.ts +404 -0
  105. package/3p/pi-plannotator/packages/server/remote.test.ts +150 -0
  106. package/3p/pi-plannotator/packages/server/remote.ts +74 -0
  107. package/3p/pi-plannotator/packages/server/repo.ts +80 -0
  108. package/3p/pi-plannotator/packages/server/resolve-file.test.ts +310 -0
  109. package/3p/pi-plannotator/packages/server/review-workspace.test.ts +1032 -0
  110. package/3p/pi-plannotator/packages/server/review-workspace.ts +48 -0
  111. package/3p/pi-plannotator/packages/server/review.ts +1318 -0
  112. package/3p/pi-plannotator/packages/server/sessions.ts +111 -0
  113. package/3p/pi-plannotator/packages/server/share-url.ts +53 -0
  114. package/3p/pi-plannotator/packages/server/shared-handlers.test.ts +43 -0
  115. package/3p/pi-plannotator/packages/server/shared-handlers.ts +177 -0
  116. package/3p/pi-plannotator/packages/server/storage.test.ts +176 -0
  117. package/3p/pi-plannotator/packages/server/storage.ts +17 -0
  118. package/3p/pi-plannotator/packages/server/tour/tour-review.test.ts +146 -0
  119. package/3p/pi-plannotator/packages/server/tour/tour-review.ts +604 -0
  120. package/3p/pi-plannotator/packages/server/tsconfig.json +15 -0
  121. package/3p/pi-plannotator/packages/server/vcs.test.ts +48 -0
  122. package/3p/pi-plannotator/packages/server/vcs.ts +80 -0
  123. package/3p/pi-plannotator/packages/shared/agent-jobs.ts +132 -0
  124. package/3p/pi-plannotator/packages/shared/agents.ts +53 -0
  125. package/3p/pi-plannotator/packages/shared/annotate-args.test.ts +386 -0
  126. package/3p/pi-plannotator/packages/shared/annotate-args.ts +107 -0
  127. package/3p/pi-plannotator/packages/shared/at-reference.test.ts +99 -0
  128. package/3p/pi-plannotator/packages/shared/at-reference.ts +52 -0
  129. package/3p/pi-plannotator/packages/shared/checklist.ts +52 -0
  130. package/3p/pi-plannotator/packages/shared/code-file.test.ts +112 -0
  131. package/3p/pi-plannotator/packages/shared/code-file.ts +41 -0
  132. package/3p/pi-plannotator/packages/shared/code-nav.test.ts +515 -0
  133. package/3p/pi-plannotator/packages/shared/code-nav.ts +436 -0
  134. package/3p/pi-plannotator/packages/shared/compress.ts +51 -0
  135. package/3p/pi-plannotator/packages/shared/config.ts +262 -0
  136. package/3p/pi-plannotator/packages/shared/crypto.test.ts +172 -0
  137. package/3p/pi-plannotator/packages/shared/crypto.ts +97 -0
  138. package/3p/pi-plannotator/packages/shared/data-dir.ts +42 -0
  139. package/3p/pi-plannotator/packages/shared/diff-paths.test.ts +30 -0
  140. package/3p/pi-plannotator/packages/shared/diff-paths.ts +137 -0
  141. package/3p/pi-plannotator/packages/shared/draft.ts +64 -0
  142. package/3p/pi-plannotator/packages/shared/external-annotation.ts +397 -0
  143. package/3p/pi-plannotator/packages/shared/extract-code-paths.test.ts +59 -0
  144. package/3p/pi-plannotator/packages/shared/extract-code-paths.ts +66 -0
  145. package/3p/pi-plannotator/packages/shared/favicon.ts +5 -0
  146. package/3p/pi-plannotator/packages/shared/feedback-templates.test.ts +65 -0
  147. package/3p/pi-plannotator/packages/shared/feedback-templates.ts +29 -0
  148. package/3p/pi-plannotator/packages/shared/goal-setup.test.ts +231 -0
  149. package/3p/pi-plannotator/packages/shared/goal-setup.ts +336 -0
  150. package/3p/pi-plannotator/packages/shared/html-to-markdown.test.ts +62 -0
  151. package/3p/pi-plannotator/packages/shared/html-to-markdown.ts +32 -0
  152. package/3p/pi-plannotator/packages/shared/improvement-hooks.test.ts +135 -0
  153. package/3p/pi-plannotator/packages/shared/improvement-hooks.ts +115 -0
  154. package/3p/pi-plannotator/packages/shared/integrations-common.ts +243 -0
  155. package/3p/pi-plannotator/packages/shared/jj-core.test.ts +236 -0
  156. package/3p/pi-plannotator/packages/shared/jj-core.ts +433 -0
  157. package/3p/pi-plannotator/packages/shared/package.json +55 -0
  158. package/3p/pi-plannotator/packages/shared/pfm-reminder.test.ts +88 -0
  159. package/3p/pi-plannotator/packages/shared/pfm-reminder.ts +80 -0
  160. package/3p/pi-plannotator/packages/shared/pr-github.ts +661 -0
  161. package/3p/pi-plannotator/packages/shared/pr-gitlab.test.ts +202 -0
  162. package/3p/pi-plannotator/packages/shared/pr-gitlab.ts +620 -0
  163. package/3p/pi-plannotator/packages/shared/pr-provider.test.ts +266 -0
  164. package/3p/pi-plannotator/packages/shared/pr-provider.ts +123 -0
  165. package/3p/pi-plannotator/packages/shared/pr-stack.test.ts +104 -0
  166. package/3p/pi-plannotator/packages/shared/pr-stack.ts +194 -0
  167. package/3p/pi-plannotator/packages/shared/pr-types.ts +326 -0
  168. package/3p/pi-plannotator/packages/shared/project.ts +71 -0
  169. package/3p/pi-plannotator/packages/shared/prompts-integration.test.ts +421 -0
  170. package/3p/pi-plannotator/packages/shared/prompts.test.ts +504 -0
  171. package/3p/pi-plannotator/packages/shared/prompts.ts +247 -0
  172. package/3p/pi-plannotator/packages/shared/reference-common.ts +87 -0
  173. package/3p/pi-plannotator/packages/shared/repo.ts +71 -0
  174. package/3p/pi-plannotator/packages/shared/resolve-file.test.ts +113 -0
  175. package/3p/pi-plannotator/packages/shared/resolve-file.ts +509 -0
  176. package/3p/pi-plannotator/packages/shared/review-args.test.ts +64 -0
  177. package/3p/pi-plannotator/packages/shared/review-args.ts +85 -0
  178. package/3p/pi-plannotator/packages/shared/review-core.test.ts +286 -0
  179. package/3p/pi-plannotator/packages/shared/review-core.ts +895 -0
  180. package/3p/pi-plannotator/packages/shared/review-workspace-node.ts +230 -0
  181. package/3p/pi-plannotator/packages/shared/review-workspace.ts +436 -0
  182. package/3p/pi-plannotator/packages/shared/semantic-diff-types.ts +76 -0
  183. package/3p/pi-plannotator/packages/shared/semantic-diff.test.ts +322 -0
  184. package/3p/pi-plannotator/packages/shared/semantic-diff.ts +520 -0
  185. package/3p/pi-plannotator/packages/shared/storage.ts +378 -0
  186. package/3p/pi-plannotator/packages/shared/tour.ts +61 -0
  187. package/3p/pi-plannotator/packages/shared/tsconfig.json +15 -0
  188. package/3p/pi-plannotator/packages/shared/types.ts +29 -0
  189. package/3p/pi-plannotator/packages/shared/url-to-markdown.test.ts +177 -0
  190. package/3p/pi-plannotator/packages/shared/url-to-markdown.ts +351 -0
  191. package/3p/pi-plannotator/packages/shared/vcs-core.test.ts +332 -0
  192. package/3p/pi-plannotator/packages/shared/vcs-core.ts +482 -0
  193. package/3p/pi-plannotator/packages/shared/worktree-pool.test.ts +162 -0
  194. package/3p/pi-plannotator/packages/shared/worktree-pool.ts +103 -0
  195. package/3p/pi-plannotator/packages/shared/worktree.ts +119 -0
  196. package/3p/pi-subagents/package.json +50 -0
  197. package/3p/pi-subagents/src/agent-manager.ts +413 -0
  198. package/3p/pi-subagents/src/agent-runner.ts +502 -0
  199. package/3p/pi-subagents/src/agent-types.ts +248 -0
  200. package/3p/pi-subagents/src/context.ts +58 -0
  201. package/3p/pi-subagents/src/cross-extension-rpc.ts +135 -0
  202. package/3p/pi-subagents/src/custom-agents.ts +137 -0
  203. package/3p/pi-subagents/src/default-agents.ts +144 -0
  204. package/3p/pi-subagents/src/env.ts +33 -0
  205. package/3p/pi-subagents/src/group-join.ts +141 -0
  206. package/3p/pi-subagents/src/index.ts +1811 -0
  207. package/3p/pi-subagents/src/invocation-config.ts +40 -0
  208. package/3p/pi-subagents/src/memory.ts +165 -0
  209. package/3p/pi-subagents/src/model-resolver.ts +81 -0
  210. package/3p/pi-subagents/src/output-file.ts +77 -0
  211. package/3p/pi-subagents/src/prompts.ts +85 -0
  212. package/3p/pi-subagents/src/skill-loader.ts +79 -0
  213. package/3p/pi-subagents/src/types.ts +111 -0
  214. package/3p/pi-subagents/src/ui/agent-widget.ts +496 -0
  215. package/3p/pi-subagents/src/ui/conversation-viewer.ts +250 -0
  216. package/3p/pi-subagents/src/worktree.ts +162 -0
  217. package/3p/pi-tasks/package.json +52 -0
  218. package/3p/pi-tasks/src/auto-clear.ts +91 -0
  219. package/3p/pi-tasks/src/index.ts +1150 -0
  220. package/3p/pi-tasks/src/process-tracker.ts +140 -0
  221. package/3p/pi-tasks/src/reminder-cadence.ts +90 -0
  222. package/3p/pi-tasks/src/task-store.ts +324 -0
  223. package/3p/pi-tasks/src/tasks-config.ts +27 -0
  224. package/3p/pi-tasks/src/types.ts +40 -0
  225. package/3p/pi-tasks/src/ui/settings-menu.ts +152 -0
  226. package/3p/pi-tasks/src/ui/task-widget.ts +296 -0
  227. package/AGENTS.md +28 -0
  228. package/LICENSE +201 -0
  229. package/extensions/orchestrator/agents/brainstorm-reviewer.ts +77 -0
  230. package/extensions/orchestrator/agents/code-reviewer.ts +89 -0
  231. package/extensions/orchestrator/agents/explore.ts +33 -0
  232. package/extensions/orchestrator/agents/librarian.ts +43 -0
  233. package/extensions/orchestrator/agents/plan-reviewer.ts +75 -0
  234. package/extensions/orchestrator/agents/planner.ts +61 -0
  235. package/extensions/orchestrator/agents/registry.ts +156 -0
  236. package/extensions/orchestrator/agents/task.ts +50 -0
  237. package/extensions/orchestrator/agents/tool-routing.ts +84 -0
  238. package/extensions/orchestrator/ast-search.ts +85 -0
  239. package/extensions/orchestrator/cbm.ts +330 -0
  240. package/extensions/orchestrator/command-handlers.test.ts +163 -0
  241. package/extensions/orchestrator/command-handlers.ts +116 -0
  242. package/extensions/orchestrator/commands.test.ts +81 -0
  243. package/extensions/orchestrator/commands.ts +75 -0
  244. package/extensions/orchestrator/config.test.ts +221 -0
  245. package/extensions/orchestrator/config.ts +230 -0
  246. package/extensions/orchestrator/context.test.ts +293 -0
  247. package/extensions/orchestrator/context.ts +206 -0
  248. package/extensions/orchestrator/event-handlers.test.ts +190 -0
  249. package/extensions/orchestrator/event-handlers.ts +1416 -0
  250. package/extensions/orchestrator/exa.ts +104 -0
  251. package/extensions/orchestrator/flant-infra.ts +486 -0
  252. package/extensions/orchestrator/index.ts +80 -0
  253. package/extensions/orchestrator/integration.test.ts +1214 -0
  254. package/extensions/orchestrator/orchestrator.test.ts +252 -0
  255. package/extensions/orchestrator/orchestrator.ts +538 -0
  256. package/extensions/orchestrator/phases/brainstorm.test.ts +15 -0
  257. package/extensions/orchestrator/phases/brainstorm.ts +273 -0
  258. package/extensions/orchestrator/phases/implementation.ts +40 -0
  259. package/extensions/orchestrator/phases/machine.test.ts +293 -0
  260. package/extensions/orchestrator/phases/machine.ts +209 -0
  261. package/extensions/orchestrator/phases/planning.ts +255 -0
  262. package/extensions/orchestrator/phases/review.ts +193 -0
  263. package/extensions/orchestrator/plannotator.ts +56 -0
  264. package/extensions/orchestrator/pp-menu.ts +866 -0
  265. package/extensions/orchestrator/state.test.ts +343 -0
  266. package/extensions/orchestrator/state.ts +237 -0
  267. package/extensions/orchestrator/validate-artifacts.test.ts +88 -0
  268. package/extensions/orchestrator/validate-artifacts.ts +272 -0
  269. package/extensions/orchestrator/vendor.d.ts +26 -0
  270. package/package.json +73 -0
  271. package/scripts/postinstall.sh +18 -0
@@ -0,0 +1,1150 @@
1
+ /**
2
+ * @tintinweb/pi-tasks — A pi extension providing Claude Code-style task tracking and coordination.
3
+ *
4
+ * Tools:
5
+ * TaskCreate — Create a structured task
6
+ * TaskList — List all tasks with status
7
+ * TaskGet — Get full task details
8
+ * TaskUpdate — Update task fields, status, dependencies
9
+ * TaskOutput — Get output from a background task process
10
+ * TaskStop — Stop a running background task process
11
+ * TaskExecute — Execute tasks as subagents (requires @tintinweb/pi-subagents)
12
+ *
13
+ * Commands:
14
+ * /tasks — Interactive task management menu
15
+ */
16
+
17
+ import { randomUUID } from "node:crypto";
18
+ import { join, resolve } from "node:path";
19
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
20
+ import { Type } from "typebox";
21
+ import { AutoClearManager } from "./auto-clear.js";
22
+ import { ProcessTracker } from "./process-tracker.js";
23
+ import {
24
+ type CadenceConfig,
25
+ createCadenceState,
26
+ drainReminderForContext,
27
+ evaluateToolResult,
28
+ onTurnStart,
29
+ resetCadenceState,
30
+ } from "./reminder-cadence.js";
31
+ import { TaskStore } from "./task-store.js";
32
+ import { loadTasksConfig } from "./tasks-config.js";
33
+ import { openSettingsMenu } from "./ui/settings-menu.js";
34
+ import { TaskWidget, type UICtx } from "./ui/task-widget.js";
35
+
36
+ // ---- Debug ----
37
+
38
+ const DEBUG = !!process.env.PI_TASKS_DEBUG;
39
+ function debug(...args: unknown[]) {
40
+ if (DEBUG) console.error("[pi-tasks]", ...args);
41
+ }
42
+
43
+ // ---- Helpers ----
44
+
45
+ function textResult(msg: string) {
46
+ return { content: [{ type: "text" as const, text: msg }], details: undefined as any };
47
+ }
48
+
49
+ /** Task tool names — used to detect task tool usage for reminder suppression. */
50
+ const TASK_TOOL_NAMES = new Set(["TaskCreate", "TaskList", "TaskGet", "TaskUpdate", "TaskOutput", "TaskStop", "TaskExecute"]);
51
+
52
+ /** How many turns without task tool usage before injecting a reminder. */
53
+ const REMINDER_INTERVAL = 4;
54
+
55
+ /** How many turns completed tasks linger before auto-clearing. */
56
+ const AUTO_CLEAR_DELAY = 4;
57
+
58
+ const SYSTEM_REMINDER = `<system-reminder>
59
+ The task tools haven't been used recently. If you're working on tasks that would benefit from tracking progress, consider using TaskCreate to add new tasks and TaskUpdate to update task status (set to in_progress when starting, completed when done). Also consider cleaning up the task list if it has become stale. Only use these if relevant to the current work. This is just a gentle reminder - ignore if not applicable. Make sure that you NEVER mention this reminder to the user
60
+ </system-reminder>`;
61
+
62
+ export default function (pi: ExtensionAPI) {
63
+ const subagentSessionKey = Symbol.for("pi-pi:subagent-session");
64
+ // Initialize store and config
65
+ const cfg = loadTasksConfig();
66
+ const piTasks = process.env.PI_TASKS;
67
+ const taskScope = cfg.taskScope ?? "session";
68
+
69
+ /** Resolve the task store path from env/config (without session ID). */
70
+ function resolveStorePath(sessionId?: string): string | undefined {
71
+ if (piTasks === "off") return undefined;
72
+ if (piTasks?.startsWith("/")) return piTasks;
73
+ if (piTasks?.startsWith(".")) return resolve(piTasks);
74
+ if (piTasks) return piTasks;
75
+ if (taskScope === "memory") return undefined;
76
+ if (taskScope === "session" && sessionId) {
77
+ return join(process.cwd(), ".pi", "tasks", `tasks-${sessionId}.json`);
78
+ }
79
+ if (taskScope === "session") return undefined; // no session ID yet, start in-memory
80
+ return join(process.cwd(), ".pi", "tasks", "tasks.json");
81
+ }
82
+
83
+ // For project scope (or env override), create store immediately.
84
+ // For session scope, start with in-memory and upgrade once we have the session ID.
85
+ let store = new TaskStore(resolveStorePath());
86
+ const tracker = new ProcessTracker();
87
+ const widget = new TaskWidget(store, cfg);
88
+ const STORE_KEY = Symbol.for("pi-tasks:store");
89
+ const storeApi = {
90
+ create: (subject: string, description: string, activeForm?: string) => store.create(subject, description, activeForm),
91
+ update: (id: string, fields: Record<string, any>) => store.update(id, fields),
92
+ list: () => store.list(),
93
+ get: (id: string) => store.get(id),
94
+ delete: (id: string) => store.update(id, { status: "deleted" }),
95
+ clearAll: () => { store.clearAll(); widget.update(); },
96
+ refreshWidget: (uiCtx?: any) => {
97
+ if (uiCtx) widget.setUICtx(uiCtx as UICtx);
98
+ widget.update();
99
+ },
100
+ };
101
+ (globalThis as any)[STORE_KEY] = storeApi;
102
+
103
+ // ── Subagent integration state ──
104
+ /** Latest ExtensionContext — refreshed on every tool execution so cascade always has a valid one. */
105
+ let latestCtx: ExtensionContext | undefined;
106
+ /** Cascade config — set by TaskExecute, consumed by completion listener. */
107
+ let cascadeConfig: { additionalContext?: string; model?: string; maxTurns?: number } | undefined;
108
+ /** Maps agent IDs to task IDs for O(1) completion lookup. */
109
+ const agentTaskMap = new Map<string, string>();
110
+
111
+ // ── Subagent RPC helpers ──
112
+
113
+ /** RPC reply envelope — matches pi-mono's RpcResponse shape. */
114
+ type RpcReply<T = void> =
115
+ | { success: true; data?: T }
116
+ | { success: false; error: string };
117
+
118
+ /** Call a subagents RPC method: emit request, wait for scoped reply, unwrap envelope. */
119
+ function rpcCall<T>(channel: string, params: Record<string, unknown>, timeoutMs: number): Promise<T> {
120
+ const requestId = randomUUID();
121
+ debug(`rpc:send ${channel}`, { requestId });
122
+ return new Promise<T>((resolve, reject) => {
123
+ const timer = setTimeout(() => {
124
+ unsub();
125
+ debug(`rpc:timeout ${channel}`, { requestId });
126
+ reject(new Error(`${channel} timeout`));
127
+ }, timeoutMs);
128
+ const unsub = pi.events.on(`${channel}:reply:${requestId}`, (raw: unknown) => {
129
+ unsub(); clearTimeout(timer);
130
+ debug(`rpc:reply ${channel}`, { requestId, raw });
131
+ const reply = raw as RpcReply<T>;
132
+ if (reply.success) resolve(reply.data as T);
133
+ else reject(new Error(reply.error));
134
+ });
135
+ pi.events.emit(channel, { requestId, ...params });
136
+ debug(`rpc:emitted ${channel}`, { requestId });
137
+ });
138
+ }
139
+
140
+ /** Spawn a subagent via pi.events RPC (requires @tintinweb/pi-subagents extension). */
141
+ function spawnSubagent(type: string, prompt: string, options?: any): Promise<string> {
142
+ debug("spawn:call", { type, options: { ...options, prompt: undefined } });
143
+ return rpcCall<{ id: string }>("subagents:rpc:spawn", { type, prompt, options }, 30_000)
144
+ .then(d => { debug("spawn:ok", d); return d.id; });
145
+ }
146
+
147
+ /** Stop a subagent via pi.events RPC (requires @tintinweb/pi-subagents extension). */
148
+ function stopSubagent(agentId: string): Promise<void> {
149
+ return rpcCall<void>("subagents:rpc:stop", { agentId }, 10_000).catch(() => {});
150
+ }
151
+
152
+ // ── Subagent extension presence & version detection ──
153
+ const PROTOCOL_VERSION = 2;
154
+ let subagentsAvailable = false;
155
+ let pendingWarning: string | undefined;
156
+
157
+ /** Ping subagents and check protocol version. Works with any handler version. */
158
+ function checkSubagentsVersion() {
159
+ const requestId = randomUUID();
160
+ const timer = setTimeout(() => { unsub(); }, 5_000);
161
+ const unsub = pi.events.on(`subagents:rpc:ping:reply:${requestId}`, (raw: unknown) => {
162
+ unsub(); clearTimeout(timer);
163
+ const remoteVersion = (raw as any)?.data?.version as number | undefined;
164
+ if (remoteVersion === undefined) {
165
+ pendingWarning =
166
+ "@tintinweb/pi-subagents is outdated — please update for task execution support.";
167
+ } else if (remoteVersion > PROTOCOL_VERSION) {
168
+ pendingWarning =
169
+ `@tintinweb/pi-tasks is outdated (protocol v${PROTOCOL_VERSION}, ` +
170
+ `pi-subagents has v${remoteVersion}) — please update for task execution support.`;
171
+ } else if (remoteVersion < PROTOCOL_VERSION) {
172
+ pendingWarning =
173
+ `@tintinweb/pi-subagents is outdated (protocol v${remoteVersion}, ` +
174
+ `pi-tasks has v${PROTOCOL_VERSION}) — please update for task execution support.`;
175
+ } else {
176
+ subagentsAvailable = true;
177
+ }
178
+ });
179
+ pi.events.emit("subagents:rpc:ping", { requestId });
180
+ }
181
+
182
+ checkSubagentsVersion();
183
+ pi.events.on("subagents:ready", () => checkSubagentsVersion());
184
+
185
+ /** Build a prompt for a task being executed by a subagent.
186
+ * Injects completed dependency results so cascaded agents have context from prerequisites.
187
+ */
188
+ function buildTaskPrompt(
189
+ task: { id: string; subject: string; description: string; blockedBy?: string[] },
190
+ additionalContext?: string,
191
+ ): string {
192
+ let prompt = `You are executing task #${task.id}: "${task.subject}"\n\n${task.description}`;
193
+
194
+ // Inject completed dependency results so cascaded agents have full context
195
+ if (task.blockedBy && task.blockedBy.length > 0) {
196
+ const depResults: string[] = [];
197
+ for (const depId of task.blockedBy) {
198
+ const dep = store.get(depId);
199
+ if (dep?.metadata?.result) {
200
+ const result = dep.metadata.result.length > 4000
201
+ ? dep.metadata.result.slice(0, 4000) + "\n\n[... truncated — use TaskGet for full output]"
202
+ : dep.metadata.result;
203
+ depResults.push(`### Task #${depId}: ${dep.subject}\n${result}`);
204
+ }
205
+ }
206
+ if (depResults.length > 0) {
207
+ prompt += `\n\n## Prerequisite task results\n\n${depResults.join("\n\n")}`;
208
+ }
209
+ }
210
+
211
+ if (additionalContext) prompt += `\n\n${additionalContext}`;
212
+ prompt += `\n\nComplete this task fully. Do not attempt to manage tasks yourself.`;
213
+ return prompt;
214
+ }
215
+
216
+ const autoClear = new AutoClearManager(() => store, () => cfg.autoClearCompleted ?? "on_list_complete", AUTO_CLEAR_DELAY);
217
+
218
+ // ── Subagent completion listener ──
219
+ // Listens for subagent lifecycle events to update task status and optionally cascade.
220
+
221
+ // Success → mark task completed, cascade if enabled
222
+ pi.events.on("subagents:completed", async (data) => {
223
+ const { id, result } = data as { id: string; result?: string };
224
+ const taskId = agentTaskMap.get(id);
225
+ if (!taskId) return;
226
+ agentTaskMap.delete(id);
227
+ const task = store.get(taskId);
228
+ if (!task) return;
229
+
230
+ store.update(task.id, { status: "completed", metadata: { ...task.metadata, result } });
231
+ widget.setActiveTask(task.id, false);
232
+
233
+ // Auto-cascade: find unblocked dependents with agentType
234
+ if ((cfg.autoCascade ?? false) && cascadeConfig && latestCtx) {
235
+ const unblocked = store.list().filter(t =>
236
+ t.status === "pending" &&
237
+ t.metadata?.agentType &&
238
+ t.blockedBy.includes(task.id) &&
239
+ t.blockedBy.every(depId => store.get(depId)?.status === "completed")
240
+ );
241
+ for (const next of unblocked) {
242
+ store.update(next.id, { status: "in_progress" });
243
+ const prompt = buildTaskPrompt(next, cascadeConfig.additionalContext);
244
+ try {
245
+ const agentId = await spawnSubagent(next.metadata.agentType, prompt, {
246
+ description: next.subject,
247
+ isBackground: true,
248
+ maxTurns: cascadeConfig.maxTurns,
249
+ ...(cascadeConfig.model ? { model: cascadeConfig.model } : {}),
250
+ });
251
+ agentTaskMap.set(agentId, next.id);
252
+ store.update(next.id, { owner: agentId, metadata: { ...next.metadata, agentId } });
253
+ widget.setActiveTask(next.id);
254
+ } catch (err: any) {
255
+ store.update(next.id, { status: "pending", metadata: { ...next.metadata, lastError: err.message } });
256
+ }
257
+ }
258
+ }
259
+ autoClear.trackCompletion(task.id, cadence.currentTurn);
260
+ widget.update();
261
+ });
262
+
263
+ // Failure → store error, revert to pending, don't cascade (branch stops)
264
+ // Intentional stop (status === "stopped") → mark completed, preserve partial result
265
+ pi.events.on("subagents:failed", (data) => {
266
+ const { id, error, result, status } = data as { id: string; error?: string; result?: string; status: string };
267
+ const taskId = agentTaskMap.get(id);
268
+ if (!taskId) return;
269
+ agentTaskMap.delete(id);
270
+ const task = store.get(taskId);
271
+ if (!task) return;
272
+
273
+ if (status === "stopped") {
274
+ // Intentional stop — mark completed, preserve partial result
275
+ store.update(task.id, { status: "completed", metadata: { ...task.metadata, result: result || task.metadata?.result } });
276
+ autoClear.trackCompletion(task.id, cadence.currentTurn);
277
+ } else {
278
+ // Actual error — revert to pending
279
+ store.update(task.id, { status: "pending", metadata: { ...task.metadata, lastError: error || status } });
280
+ autoClear.resetBatchCountdown();
281
+ }
282
+ widget.setActiveTask(task.id, false);
283
+ widget.update();
284
+ });
285
+
286
+ // ── Session-scoped store upgrade ──
287
+ // For session scope, the store starts in-memory (no session ID at init time).
288
+ // Upgrade to file-backed on first context arrival (turn_start, before_agent_start,
289
+ // or tool_execution_start — whichever fires first).
290
+ let storeUpgraded = false;
291
+ let persistedTasksShown = false;
292
+ function upgradeStoreIfNeeded(ctx: ExtensionContext) {
293
+ if (storeUpgraded) return;
294
+ if (taskScope === "session" && !piTasks) {
295
+ const sessionId = ctx.sessionManager.getSessionId();
296
+ const path = resolveStorePath(sessionId);
297
+ store = new TaskStore(path);
298
+ widget.setStore(store);
299
+ }
300
+ storeUpgraded = true;
301
+ }
302
+
303
+ /** Restore widget on session start/resume if there's unfinished work.
304
+ * On new sessions, auto-clear if all tasks are completed (clean slate).
305
+ * On resume, always show tasks (user may want to review).
306
+ * Only runs once — the first caller wins. */
307
+ function showPersistedTasks(isResume = false) {
308
+ if (persistedTasksShown) return;
309
+ persistedTasksShown = true;
310
+ const tasks = store.list();
311
+ if (tasks.length > 0) {
312
+ if (!isResume && tasks.every(t => t.status === "completed")) {
313
+ store.clearCompleted();
314
+ if (taskScope === "session") store.deleteFileIfEmpty();
315
+ } else {
316
+ widget.update();
317
+ }
318
+ }
319
+ }
320
+
321
+ // ── Turn tracking for system-reminder injection ──
322
+ // Cadence decisions live in `reminder-cadence.ts` so they're
323
+ // unit-testable without spinning up a fake ExtensionAPI.
324
+ const cadence = createCadenceState();
325
+ const cadenceConfig: CadenceConfig = {
326
+ reminderInterval: REMINDER_INTERVAL,
327
+ taskToolNames: TASK_TOOL_NAMES,
328
+ };
329
+
330
+ pi.on("turn_start", async (_event, ctx) => {
331
+ if ((globalThis as any)[subagentSessionKey]) return;
332
+ onTurnStart(cadence);
333
+ latestCtx = ctx;
334
+ widget.setUICtx(ctx.ui as UICtx);
335
+ upgradeStoreIfNeeded(ctx);
336
+ if (autoClear.onTurnStart(cadence.currentTurn)) widget.update();
337
+ });
338
+
339
+ // ── Token usage tracking ──
340
+ // Feed per-turn token counts from assistant messages into the widget.
341
+ pi.on("turn_end", async (event) => {
342
+ if ((globalThis as any)[subagentSessionKey]) return;
343
+ const msg = event.message as any;
344
+ if (msg?.role === "assistant" && msg.usage) {
345
+ widget.addTokenUsage(msg.usage.input ?? 0, msg.usage.output ?? 0);
346
+ }
347
+ });
348
+
349
+ // ── System-reminder injection ──
350
+ //
351
+ // tool_result is used ONLY to track cadence. We DO NOT mutate non-task
352
+ // tool result content — appending a <system-reminder> there would
353
+ // corrupt model-visible transcript semantics for unrelated tools (read,
354
+ // bash, grep, …) and make tool-output debugging miserable.
355
+ //
356
+ // The actual injection happens in the `context` hook below, which fires
357
+ // before each LLM call and returns a modified copy of the messages
358
+ // without persisting or polluting any tool output.
359
+ pi.on("tool_result", async (event) => {
360
+ if ((globalThis as any)[subagentSessionKey]) return {};
361
+ // Cheap-first: avoid store.list() disk I/O unless the cadence helper
362
+ // says the call could matter (i.e. it's a task tool that resets state,
363
+ // or it might queue the reminder).
364
+ const isTaskTool = TASK_TOOL_NAMES.has(event.toolName);
365
+ if (
366
+ !isTaskTool &&
367
+ cadence.currentTurn - cadence.lastTaskToolUseTurn < REMINDER_INTERVAL
368
+ ) {
369
+ return {};
370
+ }
371
+ if (!isTaskTool && cadence.reminderInjectedThisCycle) return {};
372
+
373
+ const hasTasks = isTaskTool ? false : store.list().length > 0;
374
+ evaluateToolResult(cadence, event.toolName, hasTasks, cadenceConfig);
375
+ return {};
376
+ });
377
+
378
+ // Inject the transient system-reminder into the upcoming LLM call's
379
+ // messages, never into a tool result. The reminder is appended as a
380
+ // user message so models that don't support custom message types still
381
+ // receive it. It is not persisted in the session store — `context`
382
+ // returns a transformed messages array used only for this one request.
383
+ pi.on("context", async (event) => {
384
+ if ((globalThis as any)[subagentSessionKey]) return {};
385
+ if (!drainReminderForContext(cadence)) return {};
386
+
387
+ return {
388
+ messages: [
389
+ ...event.messages,
390
+ {
391
+ role: "user" as const,
392
+ content: [{ type: "text" as const, text: SYSTEM_REMINDER }],
393
+ timestamp: Date.now(),
394
+ },
395
+ ],
396
+ };
397
+ });
398
+
399
+ // Grab UI context early — before_agent_start fires before any tool calls,
400
+ // so persisted tasks show up immediately on session start.
401
+ pi.on("before_agent_start", async (_event, ctx) => {
402
+ if ((globalThis as any)[subagentSessionKey]) return;
403
+ latestCtx = ctx;
404
+ widget.setUICtx(ctx.ui as UICtx);
405
+ upgradeStoreIfNeeded(ctx);
406
+ showPersistedTasks();
407
+ if (pendingWarning) {
408
+ ctx.ui.notify(pendingWarning, "warning");
409
+ pendingWarning = undefined;
410
+ }
411
+ });
412
+
413
+ // session_switch fires on /new (reason: "new") and /resume (reason: "resume").
414
+ // On /new: reset all session-scoped state so the store switches to the new session file.
415
+ // On resume: reload persisted tasks from the existing session file.
416
+ pi.on("session_switch" as any, async (event: any, ctx: ExtensionContext) => {
417
+ if ((globalThis as any)[subagentSessionKey]) return;
418
+ latestCtx = ctx;
419
+ widget.setUICtx(ctx.ui as UICtx);
420
+
421
+ const isResume = event?.reason === "resume";
422
+
423
+ // Reset session-scoped state for both /new and /resume
424
+ storeUpgraded = false;
425
+ persistedTasksShown = false;
426
+ resetCadenceState(cadence);
427
+ autoClear.reset();
428
+
429
+ // Memory mode has no file-backed store to switch — clear explicitly on /new
430
+ if (!isResume && taskScope === "memory") {
431
+ store.clearAll();
432
+ }
433
+
434
+ upgradeStoreIfNeeded(ctx);
435
+ showPersistedTasks(isResume);
436
+ });
437
+
438
+ // Keep latestCtx fresh on every tool execution as well.
439
+ pi.on("tool_execution_start", async (_event, ctx) => {
440
+ if ((globalThis as any)[subagentSessionKey]) return;
441
+ latestCtx = ctx;
442
+ widget.setUICtx(ctx.ui as UICtx);
443
+ upgradeStoreIfNeeded(ctx);
444
+ widget.update();
445
+ });
446
+
447
+ // ──────────────────────────────────────────────────
448
+ // Tool 1: TaskCreate
449
+ // ──────────────────────────────────────────────────
450
+
451
+ pi.registerTool({
452
+ name: "TaskCreate",
453
+ label: "TaskCreate",
454
+ description: `Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
455
+ It also helps the user understand the progress of the task and overall progress of their requests.
456
+
457
+ ## When to Use This Tool
458
+
459
+ Use this tool proactively in these scenarios:
460
+
461
+ - Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
462
+ - Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
463
+ - Plan mode - When using plan mode, create a task list to track the work
464
+ - User explicitly requests todo list - When the user directly asks you to use the todo list
465
+ - User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
466
+ - After receiving new instructions - Immediately capture user requirements as tasks
467
+ - When you start working on a task - Mark it as in_progress BEFORE beginning work
468
+ - After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
469
+
470
+ ## When NOT to Use This Tool
471
+
472
+ Skip using this tool when:
473
+ - There is only a single, straightforward task
474
+ - The task is trivial and tracking it provides no organizational benefit
475
+ - The task can be completed in less than 3 trivial steps
476
+ - The task is purely conversational or informational
477
+
478
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
479
+
480
+ ## Task Fields
481
+
482
+ - **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")
483
+ - **description**: Detailed description of what needs to be done, including context and acceptance criteria
484
+ - **activeForm** (optional): Present continuous form shown in the spinner when the task is in_progress (e.g., "Fixing authentication bug"). If omitted, the spinner shows the subject instead.
485
+
486
+ All tasks are created with status \`pending\`.
487
+
488
+ ## Tips
489
+
490
+ - Create tasks with clear, specific subjects that describe the outcome
491
+ - Include enough detail in the description for another agent to understand and complete the task
492
+ - After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed
493
+ - Check TaskList first to avoid creating duplicate tasks
494
+ - Include \`agentType\` (e.g., "general-purpose", "Explore") to mark tasks for subagent execution via TaskExecute`,
495
+ promptGuidelines: [
496
+ "When working on complex multi-step tasks, use TaskCreate to track progress and TaskUpdate to update status.",
497
+ "Mark tasks as in_progress before starting work and completed when done.",
498
+ "Use TaskList to check for available work after completing a task.",
499
+ ],
500
+ parameters: Type.Object({
501
+ subject: Type.String({ description: "A brief title for the task" }),
502
+ description: Type.String({ description: "A detailed description of what needs to be done" }),
503
+ activeForm: Type.Optional(Type.String({ description: "Present continuous form shown in spinner when in_progress (e.g., 'Running tests')" })),
504
+ agentType: Type.Optional(Type.String({ description: "Agent type for subagent execution (e.g., 'general-purpose', 'Explore'). Tasks with agentType can be started via TaskExecute." })),
505
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Any(), { description: "Arbitrary metadata to attach to the task" })),
506
+ }),
507
+
508
+ execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
509
+ autoClear.resetBatchCountdown();
510
+ const meta = params.metadata ?? {};
511
+ if (params.agentType) meta.agentType = params.agentType;
512
+ const task = store.create(params.subject, params.description, params.activeForm, Object.keys(meta).length > 0 ? meta : undefined);
513
+ widget.update();
514
+ return Promise.resolve(textResult(`Task #${task.id} created successfully: ${task.subject}`));
515
+ },
516
+ });
517
+
518
+ // ──────────────────────────────────────────────────
519
+ // Tool 2: TaskList
520
+ // ──────────────────────────────────────────────────
521
+
522
+ pi.registerTool({
523
+ name: "TaskList",
524
+ label: "TaskList",
525
+ description: `Use this tool to list all tasks in the task list.
526
+
527
+ ## When to Use This Tool
528
+
529
+ - To see what tasks are available to work on (status: 'pending', no owner, not blocked)
530
+ - To check overall progress on the project
531
+ - To find tasks that are blocked and need dependencies resolved
532
+ - After completing a task, to check for newly unblocked work or claim the next available task
533
+ - **Prefer working on tasks in ID order** (lowest ID first) when multiple tasks are available, as earlier tasks often set up context for later ones
534
+
535
+ ## Output
536
+
537
+ Returns a summary of each task:
538
+ - **id**: Task identifier (use with TaskGet, TaskUpdate)
539
+ - **subject**: Brief description of the task
540
+ - **status**: 'pending', 'in_progress', or 'completed'
541
+ - **owner**: Agent ID if assigned, empty if available
542
+ - **blockedBy**: List of open task IDs that must be resolved first (tasks with blockedBy cannot be claimed until dependencies resolve)
543
+
544
+ Use TaskGet with a specific task ID to view full details including description and comments.`,
545
+ parameters: Type.Object({}),
546
+
547
+ execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
548
+ const tasks = store.list();
549
+ if (tasks.length === 0) return Promise.resolve(textResult("No tasks found"));
550
+
551
+ // Sort: pending first (by ID), then in_progress (by ID), then completed (by ID)
552
+ const statusOrder: Record<string, number> = { pending: 0, in_progress: 1, completed: 2 };
553
+ const sorted = [...tasks].sort((a, b) => {
554
+ const so = (statusOrder[a.status] ?? 0) - (statusOrder[b.status] ?? 0);
555
+ if (so !== 0) return so;
556
+ return Number(a.id) - Number(b.id);
557
+ });
558
+
559
+ const lines = sorted.map(task => {
560
+ let line = `#${task.id} [${task.status}] ${task.subject}`;
561
+
562
+ if (task.owner) {
563
+ line += ` (${task.owner})`;
564
+ }
565
+
566
+ // Only show non-completed blockers
567
+ if (task.blockedBy.length > 0) {
568
+ const openBlockers = task.blockedBy.filter(bid => {
569
+ const blocker = store.get(bid);
570
+ return blocker && blocker.status !== "completed";
571
+ });
572
+ if (openBlockers.length > 0) {
573
+ line += ` [blocked by ${openBlockers.map(id => "#" + id).join(", ")}]`;
574
+ }
575
+ }
576
+
577
+ return line;
578
+ });
579
+
580
+ return Promise.resolve(textResult(lines.join("\n")));
581
+ },
582
+ });
583
+
584
+ // ──────────────────────────────────────────────────
585
+ // Tool 3: TaskGet
586
+ // ──────────────────────────────────────────────────
587
+
588
+ pi.registerTool({
589
+ name: "TaskGet",
590
+ label: "TaskGet",
591
+ description: `Use this tool to retrieve a task by its ID from the task list.
592
+
593
+ ## When to Use This Tool
594
+
595
+ - When you need the full description and context before starting work on a task
596
+ - To understand task dependencies (what it blocks, what blocks it)
597
+ - After being assigned a task, to get complete requirements
598
+
599
+ ## Output
600
+
601
+ Returns full task details:
602
+ - **subject**: Task title
603
+ - **description**: Detailed requirements and context
604
+ - **status**: 'pending', 'in_progress', or 'completed'
605
+ - **blocks**: Tasks waiting on this one to complete
606
+ - **blockedBy**: Tasks that must complete before this one can start
607
+
608
+ ## Tips
609
+
610
+ - After fetching a task, verify its blockedBy list is empty before beginning work.
611
+ - Use TaskList to see all tasks in summary form.`,
612
+ parameters: Type.Object({
613
+ taskId: Type.String({ description: "The ID of the task to retrieve" }),
614
+ }),
615
+
616
+ execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
617
+ const task = store.get(params.taskId);
618
+ if (!task) return Promise.resolve(textResult(`Task not found`));
619
+
620
+ // Unescape literal \n sequences the LLM may have double-escaped in JSON
621
+ const desc = task.description.replace(/\\n/g, "\n");
622
+
623
+ const lines: string[] = [
624
+ `Task #${task.id}: ${task.subject}`,
625
+ `Status: ${task.status}`,
626
+ ];
627
+ if (task.owner) {
628
+ lines.push(`Owner: ${task.owner}`);
629
+ }
630
+ lines.push(`Description: ${desc}`);
631
+
632
+ if (task.blockedBy.length > 0) {
633
+ const openBlockers = task.blockedBy.filter(bid => {
634
+ const blocker = store.get(bid);
635
+ return blocker && blocker.status !== "completed";
636
+ });
637
+ if (openBlockers.length > 0) {
638
+ lines.push(`Blocked by: ${openBlockers.map(id => "#" + id).join(", ")}`);
639
+ }
640
+ }
641
+ if (task.blocks.length > 0) {
642
+ lines.push(`Blocks: ${task.blocks.map(id => "#" + id).join(", ")}`);
643
+ }
644
+
645
+ // Show metadata if non-empty
646
+ const metaKeys = Object.keys(task.metadata);
647
+ if (metaKeys.length > 0) {
648
+ lines.push(`Metadata: ${JSON.stringify(task.metadata)}`);
649
+ }
650
+
651
+ return Promise.resolve(textResult(lines.join("\n")));
652
+ },
653
+ });
654
+
655
+ // ──────────────────────────────────────────────────
656
+ // Tool 4: TaskUpdate
657
+ // ──────────────────────────────────────────────────
658
+
659
+ pi.registerTool({
660
+ name: "TaskUpdate",
661
+ label: "TaskUpdate",
662
+ description: `Use this tool to update a task in the task list.
663
+
664
+ ## When to Use This Tool
665
+
666
+ **Before starting work on a task:**
667
+ - Mark it in_progress BEFORE beginning — do not start work without updating status first
668
+ - After resolving, call TaskList to find your next task
669
+
670
+ **Mark tasks as resolved:**
671
+ - When you have completed the work described in a task
672
+ - When a task is no longer needed or has been superseded
673
+ - IMPORTANT: Always mark your assigned tasks as resolved when you finish them
674
+ - After resolving, call TaskList to find your next task
675
+
676
+ - ONLY mark a task as completed when you have FULLY accomplished it
677
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
678
+ - When blocked, create a new task describing what needs to be resolved
679
+ - Never mark a task as completed if:
680
+ - Tests are failing
681
+ - Implementation is partial
682
+ - You encountered unresolved errors
683
+ - You couldn't find necessary files or dependencies
684
+
685
+ **Delete tasks:**
686
+ - When a task is no longer relevant or was created in error
687
+ - Setting status to \`deleted\` permanently removes the task
688
+
689
+ **Update task details:**
690
+ - When requirements change or become clearer
691
+ - When establishing dependencies between tasks
692
+
693
+ ## Fields You Can Update
694
+
695
+ - **status**: The task status (see Status Workflow below)
696
+ - **subject**: Change the task title (imperative form, e.g., "Run tests")
697
+ - **description**: Change the task description
698
+ - **activeForm**: Present continuous form shown in spinner when in_progress (e.g., "Running tests")
699
+ - **owner**: Change the task owner (agent name)
700
+ - **metadata**: Merge metadata keys into the task (set a key to null to delete it)
701
+ - **addBlocks**: Mark tasks that cannot start until this one completes
702
+ - **addBlockedBy**: Mark tasks that must complete before this one can start
703
+
704
+ ## Status Workflow
705
+
706
+ Status progresses: \`pending\` → \`in_progress\` → \`completed\`
707
+
708
+ Use \`deleted\` to permanently remove a task.
709
+
710
+ ## Staleness
711
+
712
+ Make sure to read a task's latest state using \`TaskGet\` before updating it.
713
+
714
+ ## Examples
715
+
716
+ Mark task as in progress when starting work:
717
+ \`\`\`json
718
+ {"taskId": "1", "status": "in_progress"}
719
+ \`\`\`
720
+
721
+ Mark task as completed after finishing work:
722
+ \`\`\`json
723
+ {"taskId": "1", "status": "completed"}
724
+ \`\`\`
725
+
726
+ Delete a task:
727
+ \`\`\`json
728
+ {"taskId": "1", "status": "deleted"}
729
+ \`\`\`
730
+
731
+ Claim a task by setting owner:
732
+ \`\`\`json
733
+ {"taskId": "1", "owner": "my-name"}
734
+ \`\`\`
735
+
736
+ Set up task dependencies:
737
+ \`\`\`json
738
+ {"taskId": "2", "addBlockedBy": ["1"]}
739
+ \`\`\``,
740
+ parameters: Type.Object({
741
+ taskId: Type.String({ description: "The ID of the task to update" }),
742
+ status: Type.Optional(Type.Unsafe<"pending" | "in_progress" | "completed" | "deleted">({
743
+ type: "string",
744
+ enum: ["pending", "in_progress", "completed", "deleted"],
745
+ description: "New status for the task",
746
+ })),
747
+ subject: Type.Optional(Type.String({ description: "New subject for the task" })),
748
+ description: Type.Optional(Type.String({ description: "New description for the task" })),
749
+ activeForm: Type.Optional(Type.String({ description: "Present continuous form shown in spinner when in_progress" })),
750
+ owner: Type.Optional(Type.String({ description: "New owner for the task" })),
751
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Any(), { description: "Metadata keys to merge into the task. Set a key to null to delete it." })),
752
+ addBlocks: Type.Optional(Type.Array(Type.String(), { description: "Task IDs that this task blocks" })),
753
+ addBlockedBy: Type.Optional(Type.Array(Type.String(), { description: "Task IDs that block this task" })),
754
+ }),
755
+
756
+ execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
757
+ const { taskId, ...fields } = params;
758
+ const { task, changedFields, warnings } = store.update(taskId, fields);
759
+
760
+ if (changedFields.length === 0 && !task) {
761
+ return Promise.resolve(textResult(`Task #${taskId} not found`));
762
+ }
763
+
764
+ // Update widget active task tracking
765
+ if (fields.status === "in_progress") {
766
+ widget.setActiveTask(taskId);
767
+ autoClear.resetBatchCountdown();
768
+ } else if (fields.status === "pending") {
769
+ autoClear.resetBatchCountdown();
770
+ } else if (fields.status === "completed" || fields.status === "deleted") {
771
+ widget.setActiveTask(taskId, false);
772
+ if (fields.status === "completed") autoClear.trackCompletion(taskId, cadence.currentTurn);
773
+ }
774
+
775
+ widget.update();
776
+ let msg = `Updated task #${taskId} ${changedFields.join(", ")}`;
777
+ if (warnings.length > 0) {
778
+ msg += ` (warning: ${warnings.join("; ")})`;
779
+ }
780
+ return Promise.resolve(textResult(msg));
781
+ },
782
+ });
783
+
784
+ // ──────────────────────────────────────────────────
785
+ // Tool 5: TaskOutput
786
+ // ──────────────────────────────────────────────────
787
+
788
+ pi.registerTool({
789
+ name: "TaskOutput",
790
+ label: "TaskOutput",
791
+ description: `- Retrieves output from a running or completed task (background shell, agent, or remote session)
792
+ - Takes a task_id parameter identifying the task
793
+ - Returns the task output along with status information
794
+ - Use block=true (default) to wait for task completion
795
+ - Use block=false for non-blocking check of current status
796
+ - Task IDs can be found using the /tasks command
797
+ - Works with all task types: background shells, async agents, and remote sessions`,
798
+ parameters: Type.Object({
799
+ task_id: Type.String({ description: "The task ID to get output from" }),
800
+ block: Type.Boolean({ description: "Whether to wait for completion", default: true }),
801
+ timeout: Type.Number({ description: "Max wait time in ms", default: 30000, minimum: 0, maximum: 600000 }),
802
+ }),
803
+
804
+ async execute(_toolCallId, params, signal, _onUpdate, _ctx) {
805
+ const { task_id, block, timeout } = params;
806
+
807
+ const processOutput = tracker.getOutput(task_id);
808
+ if (!processOutput) {
809
+ // No shell process — check if this is a subagent task
810
+ // Support both task IDs and agent IDs (resolve agent ID → task ID)
811
+ let resolvedId = task_id;
812
+ if (!store.get(resolvedId)) {
813
+ // Check if this is an agent ID mapped to a task
814
+ for (const [agentId, taskId] of agentTaskMap) {
815
+ if (agentId === task_id || agentId.startsWith(task_id)) { resolvedId = taskId; break; }
816
+ }
817
+ }
818
+ const task = store.get(resolvedId);
819
+ if (!task) throw new Error(`No task found with ID ${task_id}`);
820
+
821
+ if (task.metadata?.agentId) {
822
+ // Subagent task — wait for completion if blocking
823
+ if (block && task.status === "in_progress") {
824
+ await new Promise<void>((resolve) => {
825
+ const timer = setTimeout(() => { unsubOk(); unsubFail(); resolve(); }, timeout ?? 30000);
826
+ const cleanup = () => { clearTimeout(timer); resolve(); };
827
+ const unsubOk = pi.events.on("subagents:completed", (d: unknown) => {
828
+ if ((d as any).id === task.metadata?.agentId) { unsubOk(); unsubFail(); cleanup(); }
829
+ });
830
+ const unsubFail = pi.events.on("subagents:failed", (d: unknown) => {
831
+ if ((d as any).id === task.metadata?.agentId) { unsubOk(); unsubFail(); cleanup(); }
832
+ });
833
+ // Re-check in case status changed between the outer check and listener registration
834
+ const current = store.get(task_id);
835
+ if (current && current.status !== "in_progress") { unsubOk(); unsubFail(); cleanup(); }
836
+ signal?.addEventListener("abort", () => { unsubOk(); unsubFail(); cleanup(); }, { once: true });
837
+ });
838
+ }
839
+ const updated = store.get(task_id) ?? task;
840
+ return textResult(`Task #${task_id} [${updated.status}] — subagent ${task.metadata.agentId}`);
841
+ }
842
+ throw new Error(`No background process for task ${task_id}`);
843
+ }
844
+
845
+ if (block && processOutput.status === "running") {
846
+ const result = await tracker.waitForCompletion(task_id, timeout ?? 30000, signal ?? undefined);
847
+ if (result) {
848
+ return textResult(
849
+ `Task #${task_id} (${result.status})${result.exitCode !== undefined ? ` exit code: ${result.exitCode}` : ""}\n\n${result.output}`,
850
+ );
851
+ }
852
+ }
853
+
854
+ return textResult(
855
+ `Task #${task_id} (${processOutput.status})${processOutput.exitCode !== undefined ? ` exit code: ${processOutput.exitCode}` : ""}\n\n${processOutput.output}`,
856
+ );
857
+ },
858
+ });
859
+
860
+ // ──────────────────────────────────────────────────
861
+ // Tool 6: TaskStop
862
+ // ──────────────────────────────────────────────────
863
+
864
+ pi.registerTool({
865
+ name: "TaskStop",
866
+ label: "TaskStop",
867
+ description: `
868
+ - Stops a running background task by its ID
869
+ - Takes a task_id parameter identifying the task to stop
870
+ - Returns a success or failure status
871
+ - Use this tool when you need to terminate a long-running task`,
872
+ parameters: Type.Object({
873
+ task_id: Type.Optional(Type.String({ description: "The ID of the background task to stop" })),
874
+ shell_id: Type.Optional(Type.String({ description: "Deprecated: use task_id instead" })),
875
+ }),
876
+
877
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
878
+ const taskId = params.task_id ?? params.shell_id;
879
+ if (!taskId) throw new Error("task_id is required");
880
+
881
+ const stopped = await tracker.stop(taskId);
882
+ if (!stopped) {
883
+ // No shell process — check if this is a subagent task
884
+ // Support both task IDs and agent IDs
885
+ let resolvedId = taskId;
886
+ if (!store.get(resolvedId)) {
887
+ for (const [agentId, tId] of agentTaskMap) {
888
+ if (agentId === taskId || agentId.startsWith(taskId)) { resolvedId = tId; break; }
889
+ }
890
+ }
891
+ const task = store.get(resolvedId);
892
+ if (task?.metadata?.agentId && task.status === "in_progress") {
893
+ store.update(taskId, { status: "completed" });
894
+ autoClear.trackCompletion(taskId, cadence.currentTurn);
895
+ await stopSubagent(task.metadata.agentId);
896
+ widget.setActiveTask(taskId, false);
897
+ widget.update();
898
+ return textResult(`Task #${taskId} stopped successfully`);
899
+ }
900
+ throw new Error(`No running background process for task ${taskId}`);
901
+ }
902
+
903
+ store.update(taskId, { status: "completed" });
904
+ autoClear.trackCompletion(taskId, cadence.currentTurn);
905
+ widget.setActiveTask(taskId, false);
906
+ widget.update();
907
+ return textResult(`Task #${taskId} stopped successfully`);
908
+ },
909
+ });
910
+
911
+ // ──────────────────────────────────────────────────
912
+ // Tool 7: TaskExecute
913
+ // ──────────────────────────────────────────────────
914
+
915
+ pi.registerTool({
916
+ name: "TaskExecute",
917
+ label: "TaskExecute",
918
+ description: `Execute one or more tasks as subagents.
919
+
920
+ ## When to Use This Tool
921
+
922
+ - To start execution of tasks that have \`agentType\` set (created via TaskCreate with agentType parameter)
923
+ - Tasks must be \`pending\` with all blockedBy dependencies \`completed\`
924
+ - Each task runs as an independent background subagent
925
+
926
+ ## Parameters
927
+
928
+ - **task_ids**: Array of task IDs to execute
929
+ - **additional_context**: Extra context appended to each agent's prompt
930
+ - **model**: Model override for agents (e.g., "sonnet", "haiku")
931
+ - **max_turns**: Maximum turns per agent`,
932
+ promptGuidelines: [
933
+ "Never use the Agent tool for tasks launched via TaskExecute — agents are already running.",
934
+ ],
935
+ parameters: Type.Object({
936
+ task_ids: Type.Array(Type.String(), { description: "Task IDs to execute as subagents" }),
937
+ additional_context: Type.Optional(Type.String({ description: "Extra context for agent prompts" })),
938
+ model: Type.Optional(Type.String({ description: "Model override for agents" })),
939
+ max_turns: Type.Optional(Type.Number({ description: "Max turns per agent", minimum: 1 })),
940
+ }),
941
+
942
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
943
+ if (!subagentsAvailable) {
944
+ return textResult(
945
+ "Subagent execution is currently unavailable. " +
946
+ "Ensure the @tintinweb/pi-subagents extension is loaded and try again."
947
+ );
948
+ }
949
+
950
+ const results: string[] = [];
951
+ const launched: string[] = [];
952
+
953
+ for (const taskId of params.task_ids) {
954
+ const task = store.get(taskId);
955
+ if (!task) {
956
+ results.push(`#${taskId}: not found`);
957
+ continue;
958
+ }
959
+ if (task.status !== "pending") {
960
+ results.push(`#${taskId}: not pending (status: ${task.status})`);
961
+ continue;
962
+ }
963
+ if (!task.metadata?.agentType) {
964
+ results.push(`#${taskId}: no agentType set — create with agentType parameter or update metadata`);
965
+ continue;
966
+ }
967
+
968
+ // Check all blockers are completed
969
+ const openBlockers = task.blockedBy.filter(bid => {
970
+ const blocker = store.get(bid);
971
+ return !blocker || blocker.status !== "completed";
972
+ });
973
+ if (openBlockers.length > 0) {
974
+ results.push(`#${taskId}: blocked by ${openBlockers.map(id => "#" + id).join(", ")}`);
975
+ continue;
976
+ }
977
+
978
+ // Mark in_progress and spawn agent via RPC
979
+ store.update(taskId, { status: "in_progress" });
980
+ const prompt = buildTaskPrompt(task, params.additional_context);
981
+ try {
982
+ const agentId = await spawnSubagent(task.metadata.agentType, prompt, {
983
+ description: task.subject,
984
+ isBackground: true,
985
+ maxTurns: params.max_turns,
986
+ ...(params.model ? { model: params.model } : {}),
987
+ });
988
+ agentTaskMap.set(agentId, taskId);
989
+ store.update(taskId, { owner: agentId, metadata: { ...task.metadata, agentId } });
990
+ widget.setActiveTask(taskId);
991
+ launched.push(`#${taskId} → agent ${agentId}`);
992
+ } catch (err: any) {
993
+ debug(`spawn:error task=#${taskId}`, err);
994
+ store.update(taskId, { status: "pending" });
995
+ results.push(`#${taskId}: spawn failed — ${err.message}`);
996
+ }
997
+ }
998
+
999
+ // Save cascade config for the completion listener
1000
+ cascadeConfig = {
1001
+ additionalContext: params.additional_context,
1002
+ model: params.model,
1003
+ maxTurns: params.max_turns,
1004
+ };
1005
+
1006
+ widget.update();
1007
+
1008
+ const lines: string[] = [];
1009
+ if (launched.length > 0) {
1010
+ lines.push(
1011
+ `Launched ${launched.length} agent(s):\n${launched.join("\n")}\n` +
1012
+ `Use TaskOutput to check progress. Do not spawn additional agents for these tasks.`
1013
+ );
1014
+ }
1015
+ if (results.length > 0) lines.push(`Skipped:\n${results.join("\n")}`);
1016
+ if (lines.length === 0) lines.push("No tasks to execute.");
1017
+
1018
+ return textResult(lines.join("\n\n"));
1019
+ },
1020
+ });
1021
+
1022
+ // ──────────────────────────────────────────────────
1023
+ // /tasks command
1024
+ // ──────────────────────────────────────────────────
1025
+
1026
+ pi.registerCommand("tasks", {
1027
+ description: "Manage tasks — view, create, clear completed",
1028
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
1029
+ const ui = ctx.ui;
1030
+
1031
+ const mainMenu = async (): Promise<void> => {
1032
+ const tasks = store.list();
1033
+ const taskCount = tasks.length;
1034
+ const completedCount = tasks.filter(t => t.status === "completed").length;
1035
+
1036
+ const choices: string[] = [
1037
+ `View all tasks (${taskCount})`,
1038
+ "Create task",
1039
+ ];
1040
+ if (completedCount > 0) choices.push(`Clear completed (${completedCount})`);
1041
+ if (taskCount > 0) choices.push(`Clear all (${taskCount})`);
1042
+ choices.push("Settings");
1043
+
1044
+ const choice = await ui.select("Tasks", choices);
1045
+ if (!choice) return;
1046
+
1047
+ if (choice.startsWith("View")) {
1048
+ await viewTasks();
1049
+ } else if (choice === "Create task") {
1050
+ await createTask();
1051
+ } else if (choice === "Settings") {
1052
+ await settingsMenu();
1053
+ } else if (choice.startsWith("Clear completed")) {
1054
+ store.clearCompleted();
1055
+ if (taskScope === "session") store.deleteFileIfEmpty();
1056
+ widget.update();
1057
+ await mainMenu();
1058
+ } else if (choice.startsWith("Clear all")) {
1059
+ store.clearAll();
1060
+ if (taskScope === "session") store.deleteFileIfEmpty();
1061
+ widget.update();
1062
+ await mainMenu();
1063
+ }
1064
+ };
1065
+
1066
+ const viewTasks = async (): Promise<void> => {
1067
+ const tasks = store.list();
1068
+ if (tasks.length === 0) {
1069
+ await ui.select("No tasks", ["← Back"]);
1070
+ return mainMenu();
1071
+ }
1072
+
1073
+ const statusIcon = (status: string) => {
1074
+ switch (status) {
1075
+ case "completed": return "✔";
1076
+ case "in_progress": return "◼";
1077
+ default: return "◻";
1078
+ }
1079
+ };
1080
+
1081
+ const choices = tasks.map(t =>
1082
+ `${statusIcon(t.status)} #${t.id} [${t.status}] ${t.subject}`
1083
+ );
1084
+ choices.push("← Back");
1085
+
1086
+ const selected = await ui.select("Tasks", choices);
1087
+ if (!selected || selected === "← Back") return mainMenu();
1088
+
1089
+ // Extract task ID from selection
1090
+ const match = selected.match(/#(\d+)/);
1091
+ if (match) await viewTaskDetail(match[1]);
1092
+ else return viewTasks();
1093
+ };
1094
+
1095
+ const viewTaskDetail = async (taskId: string): Promise<void> => {
1096
+ const task = store.get(taskId);
1097
+ if (!task) return viewTasks();
1098
+
1099
+ const actions: string[] = [];
1100
+
1101
+ if (task.status === "pending") {
1102
+ actions.push("▸ Start (in_progress)");
1103
+ }
1104
+ if (task.status === "in_progress") {
1105
+ actions.push("✓ Complete");
1106
+ }
1107
+ actions.push("✗ Delete");
1108
+ actions.push("← Back");
1109
+
1110
+ const title = `#${task.id} [${task.status}] ${task.subject}\n${task.description}`;
1111
+ const action = await ui.select(title, actions);
1112
+
1113
+ if (action === "▸ Start (in_progress)") {
1114
+ store.update(taskId, { status: "in_progress" });
1115
+ widget.setActiveTask(taskId);
1116
+ widget.update();
1117
+ return viewTasks();
1118
+ } else if (action === "✓ Complete") {
1119
+ store.update(taskId, { status: "completed" });
1120
+ autoClear.trackCompletion(taskId, cadence.currentTurn);
1121
+ widget.setActiveTask(taskId, false);
1122
+ widget.update();
1123
+ return viewTasks();
1124
+ } else if (action === "✗ Delete") {
1125
+ store.update(taskId, { status: "deleted" });
1126
+ widget.setActiveTask(taskId, false);
1127
+ widget.update();
1128
+ return viewTasks();
1129
+ }
1130
+ return viewTasks();
1131
+ };
1132
+
1133
+ const settingsMenu = (): Promise<void> =>
1134
+ openSettingsMenu(ui, cfg, mainMenu, AUTO_CLEAR_DELAY);
1135
+
1136
+ const createTask = async (): Promise<void> => {
1137
+ const subject = await ui.input("Task subject");
1138
+ if (!subject) return mainMenu();
1139
+ const description = await ui.input("Task description");
1140
+ if (!description) return mainMenu();
1141
+
1142
+ store.create(subject, description);
1143
+ widget.update();
1144
+ return mainMenu();
1145
+ };
1146
+
1147
+ await mainMenu();
1148
+ },
1149
+ });
1150
+ }