rovecode 0.3.2
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.
- package/LICENSE +662 -0
- package/README.md +737 -0
- package/THIRD_PARTY_NOTICES.md +268 -0
- package/bin/rovecode.ts +21 -0
- package/package.json +56 -0
- package/src/acp/server.ts +374 -0
- package/src/cli/auth-login.ts +122 -0
- package/src/cli/connect.ts +244 -0
- package/src/cli/context-cmd.ts +199 -0
- package/src/cli/dispatch.ts +82 -0
- package/src/cli/doctor.ts +362 -0
- package/src/cli/export.ts +276 -0
- package/src/cli/help.ts +293 -0
- package/src/cli/is-tui-invocation.ts +8 -0
- package/src/cli/main.ts +583 -0
- package/src/cli/market-cmd.ts +658 -0
- package/src/cli/mcp-login.ts +141 -0
- package/src/cli/mcp-market-cmd.ts +302 -0
- package/src/cli/output.ts +382 -0
- package/src/cli/repl.ts +250 -0
- package/src/cli/repomap-root.ts +14 -0
- package/src/cli/resume.ts +57 -0
- package/src/cli/run-flags.ts +43 -0
- package/src/cli/run-limits.ts +78 -0
- package/src/cli/runtime.ts +931 -0
- package/src/cli/session-arg.ts +30 -0
- package/src/cli/sessions-cmd.ts +145 -0
- package/src/cli/setup.ts +153 -0
- package/src/cli/skills-cmd.ts +194 -0
- package/src/cli/start-chat.ts +65 -0
- package/src/cli/trust-cmd.ts +52 -0
- package/src/coding/bash.ts +148 -0
- package/src/coding/checkpoints.ts +327 -0
- package/src/coding/diff.ts +138 -0
- package/src/coding/files.ts +341 -0
- package/src/coding/hashline.ts +274 -0
- package/src/coding/lsp-gate.ts +254 -0
- package/src/coding/lsp-servers.ts +147 -0
- package/src/coding/lsp.ts +283 -0
- package/src/coding/repomap-cache.ts +99 -0
- package/src/coding/repomap-files.ts +192 -0
- package/src/coding/repomap.ts +481 -0
- package/src/core/agents.ts +255 -0
- package/src/core/compaction.ts +259 -0
- package/src/core/config.ts +289 -0
- package/src/core/context-report.ts +228 -0
- package/src/core/context.ts +60 -0
- package/src/core/count-remote.ts +107 -0
- package/src/core/execpolicy-rules.ts +196 -0
- package/src/core/execpolicy.ts +385 -0
- package/src/core/executor.ts +454 -0
- package/src/core/guardrails.ts +400 -0
- package/src/core/hooks.ts +411 -0
- package/src/core/images.ts +230 -0
- package/src/core/intro.ts +266 -0
- package/src/core/loop.ts +567 -0
- package/src/core/modes.ts +372 -0
- package/src/core/orchestrator.ts +245 -0
- package/src/core/proc-group.ts +48 -0
- package/src/core/project-trust.ts +98 -0
- package/src/core/reflection.ts +165 -0
- package/src/core/sandbox-config.ts +186 -0
- package/src/core/session-id.ts +24 -0
- package/src/core/session-images.ts +73 -0
- package/src/core/session-ops.ts +183 -0
- package/src/core/session-text.ts +29 -0
- package/src/core/session.ts +469 -0
- package/src/core/settings.ts +170 -0
- package/src/core/tasks.ts +646 -0
- package/src/core/token-scale.ts +108 -0
- package/src/core/tools.ts +309 -0
- package/src/core/trust.ts +104 -0
- package/src/core/types.ts +330 -0
- package/src/core/update-check.ts +171 -0
- package/src/core/usage.ts +204 -0
- package/src/core/validate.ts +121 -0
- package/src/core/verify-gate.ts +159 -0
- package/src/core/verify.ts +236 -0
- package/src/core/voice.ts +158 -0
- package/src/core/win-job.ts +183 -0
- package/src/core/workspace.ts +184 -0
- package/src/design/audit.ts +797 -0
- package/src/design/direction.ts +190 -0
- package/src/design/rules.ts +157 -0
- package/src/eval/bench.ts +150 -0
- package/src/eval/gauntlet-runner.ts +215 -0
- package/src/eval/gauntlet-support.ts +84 -0
- package/src/eval/gauntlet-wave3.ts +269 -0
- package/src/eval/gauntlet-wave4.ts +217 -0
- package/src/eval/gauntlet.ts +253 -0
- package/src/index.ts +17 -0
- package/src/lanes/agy.ts +95 -0
- package/src/lanes/approval.ts +24 -0
- package/src/lanes/claude.ts +129 -0
- package/src/lanes/codex.ts +127 -0
- package/src/lanes/events.ts +130 -0
- package/src/lanes/job.ts +142 -0
- package/src/lanes/opencode.ts +122 -0
- package/src/lanes/process.ts +184 -0
- package/src/lanes/progress.ts +183 -0
- package/src/lanes/registry.ts +178 -0
- package/src/lanes/runner.ts +124 -0
- package/src/lanes/types.ts +112 -0
- package/src/market/catalogs/mcp-docs.json +111 -0
- package/src/market/catalogs/plugins.json +111 -0
- package/src/market/catalogs/skills.json +478 -0
- package/src/market/clone.ts +72 -0
- package/src/market/context-cost.ts +121 -0
- package/src/market/digest.ts +106 -0
- package/src/market/index.ts +22 -0
- package/src/market/install.ts +578 -0
- package/src/market/manifest.ts +187 -0
- package/src/market/prereq.ts +145 -0
- package/src/market/registry.ts +363 -0
- package/src/market/resolve.ts +111 -0
- package/src/market/types.ts +236 -0
- package/src/market/validate.ts +227 -0
- package/src/mcp/client.ts +449 -0
- package/src/mcp/config.ts +252 -0
- package/src/mcp/local-package.ts +211 -0
- package/src/mcp/market-catalog.ts +84 -0
- package/src/mcp/market-install.ts +289 -0
- package/src/mcp/market.ts +362 -0
- package/src/mcp/oauth.ts +251 -0
- package/src/mcp/prompts-resources.ts +249 -0
- package/src/mcp/shared.ts +149 -0
- package/src/mcp/status.ts +67 -0
- package/src/mcp/tools.ts +275 -0
- package/src/mcp/transport.ts +122 -0
- package/src/mcp/trust.ts +25 -0
- package/src/memory/blocks.ts +278 -0
- package/src/memory/recall.ts +355 -0
- package/src/memory/scope.ts +182 -0
- package/src/memory/store.ts +105 -0
- package/src/memory/tools.ts +99 -0
- package/src/plugins/cli.ts +119 -0
- package/src/plugins/discover.ts +108 -0
- package/src/plugins/index.ts +50 -0
- package/src/plugins/install.ts +184 -0
- package/src/plugins/load.ts +124 -0
- package/src/plugins/manifest.ts +92 -0
- package/src/plugins/state.ts +83 -0
- package/src/providers/auth.ts +408 -0
- package/src/providers/cache.ts +223 -0
- package/src/providers/catalog-local.ts +160 -0
- package/src/providers/catalog.ts +421 -0
- package/src/providers/middleware-context.ts +86 -0
- package/src/providers/middleware.ts +373 -0
- package/src/providers/model-list.ts +23 -0
- package/src/providers/models-index.json +1 -0
- package/src/providers/oauth/common.ts +105 -0
- package/src/providers/oauth/device-code.ts +107 -0
- package/src/providers/oauth/github-copilot.ts +146 -0
- package/src/providers/oauth/loopback.ts +158 -0
- package/src/providers/oauth/openai.ts +163 -0
- package/src/providers/oauth/openrouter.ts +89 -0
- package/src/providers/oauth/pkce.ts +45 -0
- package/src/providers/oauth/registry.ts +39 -0
- package/src/providers/oauth/seam.ts +89 -0
- package/src/providers/profile-glm53.ts +111 -0
- package/src/providers/profile-sonnet5-persona.ts +65 -0
- package/src/providers/profile-sonnet5-voice.ts +23 -0
- package/src/providers/profiles.ts +156 -0
- package/src/providers/provider-config.ts +311 -0
- package/src/providers/registry.ts +333 -0
- package/src/providers/responses.ts +209 -0
- package/src/providers/retry.ts +234 -0
- package/src/providers/router.ts +294 -0
- package/src/providers/sse.ts +26 -0
- package/src/providers/stream-errors.ts +117 -0
- package/src/providers/stream.ts +566 -0
- package/src/providers/thinking.ts +189 -0
- package/src/providers/wire-messages.ts +129 -0
- package/src/providers/wire-responses.ts +79 -0
- package/src/providers/wire-select.ts +53 -0
- package/src/server/http.ts +291 -0
- package/src/server/openapi.ts +246 -0
- package/src/sextant/card-hits.ts +102 -0
- package/src/sextant/card-keys.ts +55 -0
- package/src/sextant/context-source.ts +157 -0
- package/src/sextant/crew-cards.ts +350 -0
- package/src/sextant/draw-agents.ts +273 -0
- package/src/sextant/draw-code.ts +388 -0
- package/src/sextant/draw-context.ts +222 -0
- package/src/sextant/draw-frame.ts +164 -0
- package/src/sextant/draw-market.ts +573 -0
- package/src/sextant/draw-messages.ts +386 -0
- package/src/sextant/draw-pet.ts +230 -0
- package/src/sextant/draw-plan.ts +187 -0
- package/src/sextant/draw-tabs.ts +85 -0
- package/src/sextant/draw-util.ts +65 -0
- package/src/sextant/draw-wizard.ts +378 -0
- package/src/sextant/engine.ts +230 -0
- package/src/sextant/frame-hits.ts +25 -0
- package/src/sextant/frame.ts +101 -0
- package/src/sextant/git-status.ts +197 -0
- package/src/sextant/grid.ts +59 -0
- package/src/sextant/input.ts +119 -0
- package/src/sextant/keys.ts +521 -0
- package/src/sextant/layout.ts +86 -0
- package/src/sextant/local-commands.ts +169 -0
- package/src/sextant/market-source.ts +287 -0
- package/src/sextant/mentions.ts +200 -0
- package/src/sextant/message-hits.ts +26 -0
- package/src/sextant/model.ts +387 -0
- package/src/sextant/overlays.ts +456 -0
- package/src/sextant/panel-hits.ts +38 -0
- package/src/sextant/pet.ts +399 -0
- package/src/sextant/screen.ts +324 -0
- package/src/sextant/scroll-hits.ts +66 -0
- package/src/sextant/scrollbar.ts +82 -0
- package/src/sextant/sextant-bridge.ts +174 -0
- package/src/sextant/sextant-cards.ts +142 -0
- package/src/sextant/sextant-diff-base.ts +63 -0
- package/src/sextant/sextant-files.ts +154 -0
- package/src/sextant/sextant-frame-loop.ts +335 -0
- package/src/sextant/sextant-renderer.ts +574 -0
- package/src/sextant/sextant-repo.ts +140 -0
- package/src/sextant/theme.ts +66 -0
- package/src/sextant/tool-rows.ts +189 -0
- package/src/sextant/types.ts +493 -0
- package/src/skills/index.ts +387 -0
- package/src/skills/pack.ts +220 -0
- package/src/skills/spec.ts +162 -0
- package/src/skills/tools.ts +69 -0
- package/src/skills/versioned.ts +227 -0
- package/src/telemetry/otel-export.ts +122 -0
- package/src/telemetry/otel-lanes.ts +89 -0
- package/src/telemetry/otel-logs.ts +131 -0
- package/src/telemetry/otel-metrics.ts +136 -0
- package/src/telemetry/otel.ts +397 -0
- package/src/telemetry/otlp.ts +76 -0
- package/src/tools/ask-user.ts +156 -0
- package/src/tools/bash-bg.ts +94 -0
- package/src/tools/bash-jobs.ts +237 -0
- package/src/tools/design.ts +151 -0
- package/src/tools/evalcell.ts +338 -0
- package/src/tools/html-text.ts +139 -0
- package/src/tools/provider.ts +149 -0
- package/src/tools/task.ts +250 -0
- package/src/tools/todo.ts +320 -0
- package/src/tools/webfetch.ts +332 -0
- package/src/tools/websearch.ts +359 -0
- package/src/tui/agents-cmd.ts +41 -0
- package/src/tui/app.ts +749 -0
- package/src/tui/attach.ts +127 -0
- package/src/tui/boot-notes.ts +41 -0
- package/src/tui/builtin-prompts.ts +59 -0
- package/src/tui/checkpoints-cmd.ts +70 -0
- package/src/tui/clipboard-image.ts +81 -0
- package/src/tui/clipboard.ts +78 -0
- package/src/tui/commands.ts +283 -0
- package/src/tui/config-view.ts +53 -0
- package/src/tui/context-cmds.ts +282 -0
- package/src/tui/cost.ts +108 -0
- package/src/tui/crash-guard.ts +173 -0
- package/src/tui/focus-terminal.ts +34 -0
- package/src/tui/git-cmds.ts +273 -0
- package/src/tui/git-plain.ts +58 -0
- package/src/tui/info-cmd.ts +150 -0
- package/src/tui/input-plain.ts +76 -0
- package/src/tui/mcp-cmd.ts +128 -0
- package/src/tui/memory-note.ts +77 -0
- package/src/tui/modes-cmd.ts +45 -0
- package/src/tui/notify-seq.ts +100 -0
- package/src/tui/notify.ts +318 -0
- package/src/tui/overlays.ts +97 -0
- package/src/tui/pi-renderer.ts +428 -0
- package/src/tui/providers-cmd.ts +377 -0
- package/src/tui/reasoning-view.ts +56 -0
- package/src/tui/renderer.ts +128 -0
- package/src/tui/replay-marker.ts +29 -0
- package/src/tui/session-cmd.ts +148 -0
- package/src/tui/session-manage.ts +95 -0
- package/src/tui/sextant-attach.ts +102 -0
- package/src/tui/sextant-io.ts +202 -0
- package/src/tui/sextant-smoke.ts +110 -0
- package/src/tui/shell-cmd.ts +158 -0
- package/src/tui/smoke.ts +72 -0
- package/src/tui/staged-terminal.ts +50 -0
- package/src/tui/startup.ts +12 -0
- package/src/tui/theme.ts +59 -0
- package/src/tui/todo-label.ts +7 -0
- package/src/tui/trust-card.ts +107 -0
- package/src/tui/tui-commands.ts +87 -0
- package/tsconfig.json +30 -0
- package/vendor/pi-tui/LICENSE +21 -0
- package/vendor/pi-tui/PATCHES.md +12 -0
- package/vendor/pi-tui/PROVENANCE.md +12 -0
- package/vendor/pi-tui/README.upstream.md +854 -0
- package/vendor/pi-tui/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
- package/vendor/pi-tui/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
- package/vendor/pi-tui/src/alt-screen-search.ts +158 -0
- package/vendor/pi-tui/src/autocomplete.ts +827 -0
- package/vendor/pi-tui/src/components/alt-screen-flash.ts +52 -0
- package/vendor/pi-tui/src/components/box.ts +138 -0
- package/vendor/pi-tui/src/components/cancellable-loader.ts +41 -0
- package/vendor/pi-tui/src/components/editor.ts +2364 -0
- package/vendor/pi-tui/src/components/h-stack.ts +45 -0
- package/vendor/pi-tui/src/components/image.ts +128 -0
- package/vendor/pi-tui/src/components/input.ts +448 -0
- package/vendor/pi-tui/src/components/loader.ts +93 -0
- package/vendor/pi-tui/src/components/markdown.ts +1016 -0
- package/vendor/pi-tui/src/components/scroll-view.ts +217 -0
- package/vendor/pi-tui/src/components/select-list.ts +230 -0
- package/vendor/pi-tui/src/components/settings-list.ts +277 -0
- package/vendor/pi-tui/src/components/spacer.ts +29 -0
- package/vendor/pi-tui/src/components/stack.ts +155 -0
- package/vendor/pi-tui/src/components/text.ts +108 -0
- package/vendor/pi-tui/src/components/truncated-text.ts +66 -0
- package/vendor/pi-tui/src/components/v-stack.ts +34 -0
- package/vendor/pi-tui/src/editor-component.ts +75 -0
- package/vendor/pi-tui/src/fuzzy.ts +138 -0
- package/vendor/pi-tui/src/index.ts +149 -0
- package/vendor/pi-tui/src/keybindings.ts +321 -0
- package/vendor/pi-tui/src/keys.ts +1402 -0
- package/vendor/pi-tui/src/kill-ring.ts +47 -0
- package/vendor/pi-tui/src/latex.ts +1381 -0
- package/vendor/pi-tui/src/layout-node.ts +52 -0
- package/vendor/pi-tui/src/layout.ts +411 -0
- package/vendor/pi-tui/src/native-modifiers.ts +60 -0
- package/vendor/pi-tui/src/native-module-path.ts +32 -0
- package/vendor/pi-tui/src/stdin-buffer.ts +445 -0
- package/vendor/pi-tui/src/terminal-colors.ts +74 -0
- package/vendor/pi-tui/src/terminal-image.ts +701 -0
- package/vendor/pi-tui/src/terminal.ts +554 -0
- package/vendor/pi-tui/src/tui-alt-screen.ts +1379 -0
- package/vendor/pi-tui/src/tui-main-screen.ts +655 -0
- package/vendor/pi-tui/src/tui.ts +1264 -0
- package/vendor/pi-tui/src/undo-stack.ts +29 -0
- package/vendor/pi-tui/src/utils.ts +1327 -0
- package/vendor/pi-tui/src/word-navigation.ts +118 -0
- package/vendor/pi-tui/test/test-themes.ts +39 -0
- package/vendor/pi-tui/test/virtual-terminal.ts +219 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/** `task` + `task_status` tools (port #26): the model's door to background subagents over
|
|
2
|
+
* core/tasks.ts TaskManager. Children run through orchestrator.ts runChild (the ONE
|
|
3
|
+
* agentLoop); these tools never run a loop themselves.
|
|
4
|
+
*
|
|
5
|
+
* Source shape: opencode packages/opencode/src/tool/task.ts (MIT, snapshot
|
|
6
|
+
* research/source_snapshots/opencode-2026 @ ebece6e) — parameters description/prompt/
|
|
7
|
+
* subagent_type + background flag (:43-62), "started" text that tells the model NOT to
|
|
8
|
+
* poll and to keep working or end its turn (:31-35), depth walk refusal (:104-117),
|
|
9
|
+
* result rendered as a tagged block with the child's final text (:64-79, :341-345).
|
|
10
|
+
* Departures: TWO tools split by policy class instead of background:true on a foreground
|
|
11
|
+
* tool — `task` (kind spawn: start|cancel — creating a child, or destroying its work) and
|
|
12
|
+
* `task_status` (kind read: status|result|list — registry reads; `result` is an explicit
|
|
13
|
+
* bounded wait). Refusals come from the orchestrator's preflight (depth cap / spawn
|
|
14
|
+
* policy) as tool output, never exceptions.
|
|
15
|
+
*
|
|
16
|
+
* Policy: `task` kind "spawn" → action "spawn" (core/tools.ts actionFor): the default gated
|
|
17
|
+
* rules PROMPT for it (cli/runtime.ts buildCfg) — once per start, since "once" is never
|
|
18
|
+
* cached — yolo allows, plan mode denies (core/modes.ts); children derive prompt→deny
|
|
19
|
+
* (orchestrator deriveChildRules), so nested starts exist only under an allow rule.
|
|
20
|
+
* `task_status` kind "read" → action "file.read", which the gated rules ALLOW: collecting a
|
|
21
|
+
* result never prompts, headless surfaces (run/serve/acp) and children read it, plan mode
|
|
22
|
+
* keeps it. Its schema declares no path/command/url, so the policy resource is the tool
|
|
23
|
+
* NAME and a smuggled `path` cannot re-aim a `deny file.read task_status` rule (tools.ts
|
|
24
|
+
* describeResource honors declared keys only). Fix-wave MED-2: one action-agnostic
|
|
25
|
+
* spawn-kind tool prompted for status/result/list too (≥2 prompts per task) and failed
|
|
26
|
+
* them closed on headless surfaces. */
|
|
27
|
+
|
|
28
|
+
import type { Tool, ToolContext, ToolOutput } from "../core/types.ts";
|
|
29
|
+
import { formatTaskList, isTerminal, type TaskId, type TaskInfo, type TaskManager } from "../core/tasks.ts";
|
|
30
|
+
import type { SteeringQueue } from "../core/loop.ts";
|
|
31
|
+
import { ADAPTER_IDS } from "../lanes/types.ts";
|
|
32
|
+
import { LANES_ALLOW_ENV } from "../lanes/registry.ts";
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_WAIT_MS = 60_000;
|
|
35
|
+
export const MAX_WAIT_MS = 600_000;
|
|
36
|
+
|
|
37
|
+
export interface TaskToolOptions {
|
|
38
|
+
/** depth of the loop this tool serves (root = 0); children start at depth + 1 */
|
|
39
|
+
parentDepth?: number;
|
|
40
|
+
/** completion notes for tasks started here (default: the manager's attached queue) */
|
|
41
|
+
notify?: SteeringQueue;
|
|
42
|
+
/** the task id of the child this tool serves (nested); enables slot lending */
|
|
43
|
+
caller?: TaskId;
|
|
44
|
+
/** owner signal for tasks started here (nested: the serving task's own run signal, so
|
|
45
|
+
* cancelling a task cancels its children). Root tools leave it unset — the manager's
|
|
46
|
+
* bindRun() signal owns root tasks; ToolContext.signal is NOT usable (loop.ts:91). */
|
|
47
|
+
owner?: AbortSignal;
|
|
48
|
+
/** agent name used when `agent` is omitted */
|
|
49
|
+
defaultAgent?: string;
|
|
50
|
+
/** the custom subagent definitions loaded at boot (core/agents.ts agentRows) — enumerated in the schema so the model
|
|
51
|
+
* knows which `agent` names exist; absent/empty = only the default */
|
|
52
|
+
agents?: readonly { name: string; description: string }[];
|
|
53
|
+
/** nested tools: the tool names of the registry THIS tool serves, read lazily at each start (the registry is filled
|
|
54
|
+
* after the tool is built) → StartOptions.parentTools, so a child started from a restricted agent is clamped to that
|
|
55
|
+
* agent's set (the allow-list is transitive). Root tools leave it unset. */
|
|
56
|
+
parentTools?: () => ReadonlySet<string>;
|
|
57
|
+
/** nested tools: the working tree of the child THIS tool serves (ChildContext.dir — its worktree when
|
|
58
|
+
* it is isolated) → StartOptions.parentDir. An external lane started from here builds its worktree
|
|
59
|
+
* from that directory and merges its patch back into it, so a nested lane's work travels up through
|
|
60
|
+
* its parent's patch instead of landing in the user's live tree behind the parent's back. Root tools
|
|
61
|
+
* leave it unset: there the manager's rootDir IS the working tree. */
|
|
62
|
+
parentDir?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface TaskStatusToolOptions {
|
|
66
|
+
/** the task id of the child this tool serves (nested): a `result` wait lends its slot to
|
|
67
|
+
* the waited-on queued task (TaskManager.result slot lending) */
|
|
68
|
+
caller?: TaskId;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const NOT_POLLING =
|
|
72
|
+
"You will be notified in this conversation when it finishes — do NOT poll or sleep: " +
|
|
73
|
+
"continue other non-overlapping work or end your turn. Use `task_status result` to wait for it when you need its output.";
|
|
74
|
+
/** one-shot policy (cli/main.ts cmdRun exit): tasks never outlive the process that started them */
|
|
75
|
+
const ONE_SHOT =
|
|
76
|
+
"In a one-shot run (`rovecode run`) background tasks do not outlive the run: collect what you need with " +
|
|
77
|
+
"`task_status result` before ending your turn.";
|
|
78
|
+
|
|
79
|
+
interface Args {
|
|
80
|
+
action?: unknown; goal?: unknown; agent?: unknown; isolated?: unknown; label?: unknown; id?: unknown; timeout_ms?: unknown;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const err = (output: string): ToolOutput => ({ ok: false, output: `Error: ${output}` });
|
|
84
|
+
const need = (tool: string, what: string): ToolOutput => err(`${tool} ${what} requires a string \`id\` (see \`task_status list\`)`);
|
|
85
|
+
|
|
86
|
+
function describe(t: TaskInfo, now: number): string {
|
|
87
|
+
const secs = t.startedAt !== undefined ? Math.max(0, Math.round(((t.finishedAt ?? now) - t.startedAt) / 1000)) : 0;
|
|
88
|
+
const usage = t.usage ? `, tokens ${t.usage.input}in/${t.usage.output}out` : "";
|
|
89
|
+
return `task ${t.id} (${t.label}) ${t.status} — agent ${t.agent}, ${t.isolated ? "isolated, " : ""}${secs}s${usage}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function renderResult(t: TaskInfo, now: number): ToolOutput {
|
|
93
|
+
const head = describe(t, now);
|
|
94
|
+
if (t.status === "done") {
|
|
95
|
+
const patch = t.patchLines !== undefined ? `\n[isolated: ${t.patchLines === 0 ? "no file changes" : `patch of ${t.patchLines} lines merged back`}]` : "";
|
|
96
|
+
// #47: a lane's permissions were the CLI's own flags — the ones the approval card stated. Repeating
|
|
97
|
+
// them on the result is not decoration: it is the only place the model can see what the lane was
|
|
98
|
+
// actually allowed to do, which is rarely what our own children are allowed to do.
|
|
99
|
+
const lane = t.kind === "external"
|
|
100
|
+
? `\n[external ${t.agent} lane — permissions: ${t.permissions ?? "(unknown)"}${t.laneExit !== undefined ? `; exit ${t.laneExit}` : ""}${t.laneModel ? `; model ${t.laneModel}` : ""}]`
|
|
101
|
+
: "";
|
|
102
|
+
return { ok: true, output: `${head}${lane}${patch}\n${t.summary ?? "(no output)"}`, data: t };
|
|
103
|
+
}
|
|
104
|
+
if (t.status === "failed") return { ok: false, output: `${head}\n${t.error ?? "unknown error"}`, data: t };
|
|
105
|
+
if (t.status === "cancelled") return { ok: false, output: head, data: t };
|
|
106
|
+
return { ok: true, output: `${head}. ${NOT_POLLING}`, data: t };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** `timeout_ms`: numbers and numeric strings ("5000" — models quote integers) clamp to
|
|
110
|
+
* [0, MAX_WAIT_MS]; absent → the default; anything else is a clear error, never a silent
|
|
111
|
+
* default (fix-wave L6: a quoted "5000" used to become the 60s default). */
|
|
112
|
+
function parseTimeout(v: unknown): number | { error: string } {
|
|
113
|
+
if (v === undefined || v === null) return DEFAULT_WAIT_MS;
|
|
114
|
+
const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN;
|
|
115
|
+
if (!Number.isFinite(n)) return { error: `task_status result: \`timeout_ms\` must be a number of milliseconds (got ${JSON.stringify(v) ?? String(v)})` };
|
|
116
|
+
return Math.min(MAX_WAIT_MS, Math.max(0, Math.floor(n)));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** kind spawn: `start` (a new child) and `cancel` (destroys the child's work) — the two
|
|
120
|
+
* actions a gated policy should ask about. Reads live on `task_status`. */
|
|
121
|
+
export function createTaskTool(tasks: TaskManager, opts: TaskToolOptions = {}): Tool {
|
|
122
|
+
const defaultAgent = opts.defaultAgent ?? "main";
|
|
123
|
+
// custom definitions, enumerated (bounded per row) so the model can pick one by name
|
|
124
|
+
const custom = (opts.agents ?? []).filter((a) => a.name !== defaultAgent);
|
|
125
|
+
const clipRow = (s: string): string => (s.length > 120 ? s.slice(0, 119) + "…" : s);
|
|
126
|
+
const customNote = custom.length > 0
|
|
127
|
+
? `Custom agent definitions (.rovecode/agents/<name>.md — own system prompt, model, mode and tool allow-list): ${custom.map((a) => `${a.name} — ${clipRow(a.description)}`).join("; ")}. `
|
|
128
|
+
: "";
|
|
129
|
+
return {
|
|
130
|
+
schema: {
|
|
131
|
+
name: "task",
|
|
132
|
+
description:
|
|
133
|
+
"Run subagents as background tasks. `start` launches a child agent session on `goal` and returns " +
|
|
134
|
+
"at once with a task id; the child works while you continue, and a note lands in this conversation " +
|
|
135
|
+
"when it finishes (do not poll). Read its state or output with the `task_status` tool (status/result/list " +
|
|
136
|
+
"— never prompts); `cancel` aborts a task. Children see only `goal` (write it self-contained). " +
|
|
137
|
+
`At most ${tasks.maxConcurrent} run concurrently; extra starts queue FIFO. ` +
|
|
138
|
+
"`isolated` runs the child in a git worktree copy and merges its file changes back as a patch on success. " +
|
|
139
|
+
`\`agent\` may also name an EXTERNAL agentic-CLI lane — ${ADAPTER_IDS.join(" | ")} — which runs \`goal\` in that CLI ` +
|
|
140
|
+
"instead of in one of our agents. A lane always works in its own worktree, its diff merges back like any " +
|
|
141
|
+
`isolated child, and it runs with the flags stated on the approval card. Lanes are OFF unless ${LANES_ALLOW_ENV} lists the id. ` +
|
|
142
|
+
"Policy: under gated rules each `start` needs approval and the child runs read-only (prompt-gated actions " +
|
|
143
|
+
"are denied for children) unless allow rules cover them; under yolo it inherits allow-all. " + customNote + ONE_SHOT,
|
|
144
|
+
args: {
|
|
145
|
+
type: "object",
|
|
146
|
+
properties: {
|
|
147
|
+
action: { type: "string", enum: ["start", "cancel"] },
|
|
148
|
+
goal: { type: "string", description: "start: the child's task, self-contained (it has no access to this conversation)" },
|
|
149
|
+
agent: { type: "string", description: `start: agent definition to run (default "${defaultAgent}"${custom.length > 0 ? `; custom: ${custom.map((a) => a.name).join(", ")}` : ""}), or an external CLI lane: ${ADAPTER_IDS.join(" | ")} (needs ${LANES_ALLOW_ENV})` },
|
|
150
|
+
isolated: { type: "boolean", description: "start: run in an isolated worktree copy; file changes merge back as a patch when the task finishes ok" },
|
|
151
|
+
label: { type: "string", description: "start: short label (3-5 words) shown in task lists and completion notes" },
|
|
152
|
+
id: { type: "string", description: "cancel: task id (e.g. t1)" },
|
|
153
|
+
},
|
|
154
|
+
required: ["action"],
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
kind: "spawn",
|
|
158
|
+
sequential: true,
|
|
159
|
+
async execute(args: unknown): Promise<ToolOutput> {
|
|
160
|
+
const a = (args ?? {}) as Args;
|
|
161
|
+
const id = typeof a.id === "string" ? a.id.trim() : "";
|
|
162
|
+
switch (a.action) {
|
|
163
|
+
case "start": {
|
|
164
|
+
if (typeof a.goal !== "string" || a.goal.trim() === "") return err("task start requires a non-empty string `goal`");
|
|
165
|
+
const agent = typeof a.agent === "string" && a.agent.trim() !== "" ? a.agent.trim() : defaultAgent;
|
|
166
|
+
const r = tasks.start(
|
|
167
|
+
{ agent, goal: a.goal, isolated: a.isolated === true, background: true },
|
|
168
|
+
{ label: typeof a.label === "string" ? a.label : undefined, parentDepth: opts.parentDepth ?? 0, notify: opts.notify, caller: opts.caller, owner: opts.owner, ...(opts.parentTools ? { parentTools: opts.parentTools() } : {}), ...(opts.parentDir !== undefined ? { parentDir: opts.parentDir } : {}) },
|
|
169
|
+
);
|
|
170
|
+
if (!r.ok) return err(`task refused: ${r.reason}`);
|
|
171
|
+
const t = tasks.status(r.id)!;
|
|
172
|
+
const state = t.status === "running" ? "running" : `queued (${tasks.counts().running} running, bound ${tasks.maxConcurrent})`;
|
|
173
|
+
// the approver/model must know what the child CAN do (deriveChildRules: prompt → deny); an
|
|
174
|
+
// external lane's permissions are the CLI's OWN flags (#47) — the ones the approval card
|
|
175
|
+
// stated — and they are not ours to describe in our own words
|
|
176
|
+
const policy = t.kind === "external"
|
|
177
|
+
? `External ${t.agent} lane — permissions: ${t.permissions ?? "(unknown)"}; its worktree patch merges back when it finishes ok.`
|
|
178
|
+
: r.childPolicy === "gated"
|
|
179
|
+
? "Policy: gated — the child runs read-only (prompt-gated actions are DENIED for children) unless allow rules cover them."
|
|
180
|
+
: "Policy: the child inherits your allow rules.";
|
|
181
|
+
return { ok: true, output: `task ${t.id} (${t.label}) started: ${state}. ${policy} ${NOT_POLLING}`, data: t };
|
|
182
|
+
}
|
|
183
|
+
case "cancel": {
|
|
184
|
+
if (id === "") return need("task", "cancel");
|
|
185
|
+
const before = tasks.status(id);
|
|
186
|
+
if (!before) return err(`unknown task '${id}'`);
|
|
187
|
+
if (isTerminal(before.status)) return { ok: true, output: `task ${id} already ${before.status}`, data: before };
|
|
188
|
+
const t = tasks.cancel(id)!;
|
|
189
|
+
return { ok: true, output: `task ${t.id} (${t.label}) cancelled`, data: t };
|
|
190
|
+
}
|
|
191
|
+
default:
|
|
192
|
+
return err(`task requires action start|cancel (got ${JSON.stringify(a.action ?? null)}); status|result|list live on task_status`);
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** kind read: `status` | `result` (bounded wait, aborts with the run) | `list`. Auto-allowed by
|
|
199
|
+
* the gated rules (file.read) and plan mode; no path/command/url in the schema, so the policy
|
|
200
|
+
* resource is always the tool name. */
|
|
201
|
+
export function createTaskStatusTool(tasks: TaskManager, opts: TaskStatusToolOptions = {}): Tool {
|
|
202
|
+
return {
|
|
203
|
+
schema: {
|
|
204
|
+
name: "task_status",
|
|
205
|
+
description:
|
|
206
|
+
"Read background tasks started with `task` (never prompts, never mutates). `status` shows one task's " +
|
|
207
|
+
"state; `result` waits (bounded by `timeout_ms`, default 60s) for a task to finish and returns the " +
|
|
208
|
+
"child's final output — call it when you need the output, otherwise wait for the completion note; " +
|
|
209
|
+
"`list` shows every task. " + ONE_SHOT,
|
|
210
|
+
args: {
|
|
211
|
+
type: "object",
|
|
212
|
+
properties: {
|
|
213
|
+
action: { type: "string", enum: ["status", "result", "list"] },
|
|
214
|
+
id: { type: "string", description: "status/result: task id (e.g. t1)" },
|
|
215
|
+
timeout_ms: { type: "integer", description: `result: max wait in ms (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS}); 0 = report the current state at once` },
|
|
216
|
+
},
|
|
217
|
+
required: ["action"],
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
kind: "read",
|
|
221
|
+
sequential: true,
|
|
222
|
+
async execute(args: unknown, ctx: ToolContext): Promise<ToolOutput> {
|
|
223
|
+
const a = (args ?? {}) as Args;
|
|
224
|
+
const now = Date.now();
|
|
225
|
+
const id = typeof a.id === "string" ? a.id.trim() : "";
|
|
226
|
+
switch (a.action) {
|
|
227
|
+
case "status": {
|
|
228
|
+
if (id === "") return need("task_status", "status");
|
|
229
|
+
const t = tasks.status(id);
|
|
230
|
+
return t ? { ok: true, output: describe(t, now), data: t } : err(`unknown task '${id}'`);
|
|
231
|
+
}
|
|
232
|
+
case "result": {
|
|
233
|
+
if (id === "") return need("task_status", "result");
|
|
234
|
+
if (!tasks.status(id)) return err(`unknown task '${id}'`);
|
|
235
|
+
const timeoutMs = parseTimeout(a.timeout_ms);
|
|
236
|
+
if (typeof timeoutMs !== "number") return err(timeoutMs.error);
|
|
237
|
+
const t = await tasks.result(id, { timeoutMs, signal: ctx.signal, caller: opts.caller });
|
|
238
|
+
if (!t) return err(`unknown task '${id}'`);
|
|
239
|
+
if (!isTerminal(t.status) && ctx.signal.aborted) return err(`wait for task ${id} aborted`);
|
|
240
|
+
if (!isTerminal(t.status)) return { ok: true, output: `${describe(t, Date.now())} — still running after ${Math.round(timeoutMs / 1000)}s. ${NOT_POLLING}`, data: t };
|
|
241
|
+
return renderResult(t, Date.now());
|
|
242
|
+
}
|
|
243
|
+
case "list":
|
|
244
|
+
return { ok: true, output: formatTaskList(tasks.list(), now), data: tasks.counts() };
|
|
245
|
+
default:
|
|
246
|
+
return err(`task_status requires action status|result|list (got ${JSON.stringify(a.action ?? null)}); start|cancel live on task`);
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/** Session todo / plan tool (PORT #32): `todo_write` + `todo_read` over one
|
|
2
|
+
* JSON file per session, plus pure render helpers for the TUI surface.
|
|
3
|
+
*
|
|
4
|
+
* Ported from opencode (MIT, snapshot ebece6e):
|
|
5
|
+
* - tool contract — ONE `todos` array argument that REPLACES the whole list
|
|
6
|
+
* (packages/opencode/src/tool/todo.ts:6-8, :31-34; packages/core/src/tool/
|
|
7
|
+
* todowrite.ts:14-16, :49); the store's update is delete-all + insert in
|
|
8
|
+
* list order (packages/opencode/src/session/todo.ts:29-51), reads come back
|
|
9
|
+
* in that order (:53-66);
|
|
10
|
+
* - item shape content / status / priority with the status and priority sets
|
|
11
|
+
* (packages/schema/src/session-todo.ts:7-15);
|
|
12
|
+
* - the when-to-use / when-not / rules guidance folded into the tool
|
|
13
|
+
* description (packages/opencode/src/tool/todowrite.txt:3-16, :24-30, :44).
|
|
14
|
+
* Validation follows gemini-cli (Apache-2.0, snapshot 0bd1d43)
|
|
15
|
+
* packages/core/src/tools/write-todos.ts:100-129 validateToolParamValues —
|
|
16
|
+
* array check, per-item object / non-empty description / status-enum checks,
|
|
17
|
+
* and the at-most-ONE-in_progress rule (:120-126); "Cleared todo list" is
|
|
18
|
+
* gemini's wording (:52, :68). Both upstreams reject an invalid list whole.
|
|
19
|
+
*
|
|
20
|
+
* Deviations: items carry a caller-chosen `id` (whole-list replace needs a
|
|
21
|
+
* stable handle the model can quote back; opencode is position-keyed, gemini
|
|
22
|
+
* has none); three statuses only (no cancelled/blocked — drop the item
|
|
23
|
+
* instead); bounds (≤50 items, id ≤64 chars, content ≤500 chars) so tool output
|
|
24
|
+
* stays bounded; storage is `<sessionDir>/todos.json` written tmp+rename
|
|
25
|
+
* (session.ts persistLeaf pattern; opencode uses SQLite, gemini is in-memory).
|
|
26
|
+
* No in-memory cache: every read hits disk, so a second tool instance, a
|
|
27
|
+
* resumed session and the TUI `/todos` surface all see the same truth. A
|
|
28
|
+
* corrupt file is reported as empty + note — loading never throws.
|
|
29
|
+
*
|
|
30
|
+
* Policy: todo_write is kind "memory" — a disk write of agent-private,
|
|
31
|
+
* session-scoped metadata, the same class as memory_edit (BlockStore under
|
|
32
|
+
* <session>/memory). core/tools.ts actionFor() maps it to memory.write, which
|
|
33
|
+
* the runtime's default gated rules ALLOW (runtime.ts buildCfg), so the list
|
|
34
|
+
* never prompts; kind "read" would also auto-run but would let read-only rule
|
|
35
|
+
* sets write to disk unseen — the mirror of recall.ts's argument against
|
|
36
|
+
* mislabeling kinds. The schemas declare no `path`/`command`, so the policy
|
|
37
|
+
* resource is the tool name: `memory.write todo_write` targets it precisely —
|
|
38
|
+
* which is how plan mode (modes.ts planModeRules) denies memory.write wholesale
|
|
39
|
+
* and then re-allows exactly todo_write: the list is the plan's own artifact
|
|
40
|
+
* (agent-private session metadata, not workspace state), while memory_edit,
|
|
41
|
+
* file.write and shell.exec stay denied there; todo_read (kind "read" →
|
|
42
|
+
* file.read) is always available. Not in checkpoints.ts MUTATING_KINDS, so
|
|
43
|
+
* todo writes never trigger snapshots. */
|
|
44
|
+
|
|
45
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
46
|
+
import { basename, join } from "node:path";
|
|
47
|
+
import type { Tool, ToolContext, ToolOutput } from "../core/types.ts";
|
|
48
|
+
|
|
49
|
+
// ---------- schema ----------
|
|
50
|
+
|
|
51
|
+
export type TodoStatus = "pending" | "in_progress" | "completed";
|
|
52
|
+
export type TodoPriority = "high" | "medium" | "low";
|
|
53
|
+
export interface TodoItem { id: string; content: string; status: TodoStatus; priority?: TodoPriority }
|
|
54
|
+
|
|
55
|
+
export const TODO_STATUSES: readonly TodoStatus[] = ["pending", "in_progress", "completed"];
|
|
56
|
+
export const TODO_PRIORITIES: readonly TodoPriority[] = ["high", "medium", "low"];
|
|
57
|
+
export const MAX_TODOS = 50;
|
|
58
|
+
export const MAX_ID_CHARS = 64;
|
|
59
|
+
export const MAX_CONTENT_CHARS = 500;
|
|
60
|
+
export const TODOS_FILE = "todos.json";
|
|
61
|
+
const FILE_VERSION = 1;
|
|
62
|
+
const RENDER_CONTENT_CHARS = 200; // per-line render clip (content is ≤500 on disk; the TUI note stays scannable)
|
|
63
|
+
|
|
64
|
+
function isStatus(v: unknown): v is TodoStatus { return (TODO_STATUSES as readonly unknown[]).includes(v); }
|
|
65
|
+
function isPriority(v: unknown): v is TodoPriority { return (TODO_PRIORITIES as readonly unknown[]).includes(v); }
|
|
66
|
+
|
|
67
|
+
/** Bounded echo of a rejected value — a 200k-char status must not reflect into the error. */
|
|
68
|
+
function show(v: unknown): string {
|
|
69
|
+
let s: string;
|
|
70
|
+
try { s = JSON.stringify(v) ?? String(v); } catch { s = String(v); }
|
|
71
|
+
return s.length > 40 ? s.slice(0, 40).replace(/[\uD800-\uDBFF]$/, "") + "…" : s;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type TodoValidation = { ok: true; items: TodoItem[] } | { ok: false; error: string };
|
|
75
|
+
|
|
76
|
+
/** Whole-list validation (gemini-cli write-todos.ts:100-129 shape, plus ids and
|
|
77
|
+
* bounds). Returns NORMALIZED items — ids/content trimmed, unknown keys
|
|
78
|
+
* dropped, `priority` omitted when absent — or the first precise error. */
|
|
79
|
+
export function validateTodos(raw: unknown): TodoValidation {
|
|
80
|
+
const err = (error: string): TodoValidation => ({ ok: false, error });
|
|
81
|
+
if (!Array.isArray(raw)) return err("`todos` must be an array of {id, content, status, priority?}");
|
|
82
|
+
if (raw.length > MAX_TODOS) return err(`too many todos: ${raw.length} (max ${MAX_TODOS})`);
|
|
83
|
+
const items: TodoItem[] = [];
|
|
84
|
+
const seen = new Set<string>();
|
|
85
|
+
const inProgress: string[] = [];
|
|
86
|
+
for (let i = 0; i < raw.length; i++) {
|
|
87
|
+
const t: unknown = raw[i];
|
|
88
|
+
const at = `todos[${i}]`;
|
|
89
|
+
if (!t || typeof t !== "object" || Array.isArray(t)) return err(`${at} must be an object {id, content, status, priority?}`);
|
|
90
|
+
const o = t as Record<string, unknown>;
|
|
91
|
+
if (typeof o.id !== "string" || o.id.trim().length === 0) return err(`${at}.id must be a non-empty string`);
|
|
92
|
+
const id = o.id.trim();
|
|
93
|
+
if (id.length > MAX_ID_CHARS) return err(`${at}.id exceeds ${MAX_ID_CHARS} chars`);
|
|
94
|
+
if (seen.has(id)) return err(`duplicate id "${id}" at ${at} — ids must be unique`);
|
|
95
|
+
seen.add(id);
|
|
96
|
+
if (typeof o.content !== "string" || o.content.trim().length === 0) return err(`${at} ("${id}"): content must be a non-empty string`);
|
|
97
|
+
const content = o.content.trim();
|
|
98
|
+
if (content.length > MAX_CONTENT_CHARS) return err(`${at} ("${id}"): content exceeds ${MAX_CONTENT_CHARS} chars`);
|
|
99
|
+
if (!isStatus(o.status)) return err(`${at} ("${id}"): status must be one of ${TODO_STATUSES.join(", ")} (got ${show(o.status)})`);
|
|
100
|
+
const item: TodoItem = { id, content, status: o.status };
|
|
101
|
+
if (o.priority !== undefined && o.priority !== null) {
|
|
102
|
+
if (!isPriority(o.priority)) return err(`${at} ("${id}"): priority must be one of ${TODO_PRIORITIES.join(", ")} (got ${show(o.priority)})`);
|
|
103
|
+
item.priority = o.priority;
|
|
104
|
+
}
|
|
105
|
+
if (item.status === "in_progress") inProgress.push(id);
|
|
106
|
+
items.push(item);
|
|
107
|
+
}
|
|
108
|
+
// gemini-cli write-todos.ts:120-126: only one task can be in_progress at a time
|
|
109
|
+
if (inProgress.length > 1) return err(`only one todo may be in_progress at a time (found ${inProgress.length}: ${inProgress.join(", ")})`);
|
|
110
|
+
return { ok: true, items };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---------- persistence (<sessionDir>/todos.json) ----------
|
|
114
|
+
|
|
115
|
+
export interface LoadedTodos { items: TodoItem[]; note?: string }
|
|
116
|
+
|
|
117
|
+
/** Read the session's list. Missing file = empty (the normal initial state, no
|
|
118
|
+
* note). Unreadable / malformed / schema-invalid content = empty + a note
|
|
119
|
+
* saying so — never throws; the next todo_write replaces the file. */
|
|
120
|
+
export function loadTodos(sessionDir: string): LoadedTodos {
|
|
121
|
+
const file = join(sessionDir, TODOS_FILE);
|
|
122
|
+
const tail = "treating the list as empty; the next todo_write replaces it";
|
|
123
|
+
let text: string;
|
|
124
|
+
try {
|
|
125
|
+
text = readFileSync(file, "utf8");
|
|
126
|
+
} catch (e) {
|
|
127
|
+
if ((e as { code?: unknown } | null)?.code === "ENOENT") return { items: [] };
|
|
128
|
+
return { items: [], note: `${TODOS_FILE} could not be read (${e instanceof Error ? e.message : String(e)}) — ${tail}` };
|
|
129
|
+
}
|
|
130
|
+
let raw: unknown;
|
|
131
|
+
try { raw = JSON.parse(text); } catch { return { items: [], note: `${TODOS_FILE} is not valid JSON — ${tail}` }; }
|
|
132
|
+
const o = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : null;
|
|
133
|
+
if (!o || o.version !== FILE_VERSION || !Array.isArray(o.items)) {
|
|
134
|
+
return { items: [], note: `${TODOS_FILE} has an unexpected shape (expected {version: ${FILE_VERSION}, items: [...]}) — ${tail}` };
|
|
135
|
+
}
|
|
136
|
+
const v = validateTodos(o.items);
|
|
137
|
+
if (!v.ok) return { items: [], note: `${TODOS_FILE} failed validation (${v.error}) — ${tail}` };
|
|
138
|
+
return { items: v.items };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Atomic replace: write `todos.json.tmp`, then rename over the target (session.ts
|
|
142
|
+
* persistLeaf). Creates the session dir if needed. IO errors propagate — the
|
|
143
|
+
* tool turns them into ok:false. */
|
|
144
|
+
export function saveTodos(sessionDir: string, items: readonly TodoItem[]): void {
|
|
145
|
+
mkdirSync(sessionDir, { recursive: true });
|
|
146
|
+
const file = join(sessionDir, TODOS_FILE);
|
|
147
|
+
const tmp = file + ".tmp";
|
|
148
|
+
writeFileSync(tmp, JSON.stringify({ version: FILE_VERSION, items }, null, 2) + "\n");
|
|
149
|
+
renameSync(tmp, file);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A session id must be a plain directory name: `<root>/<id>/todos.json` may never
|
|
153
|
+
* resolve outside the sessions root (listSessions identity = directory name). */
|
|
154
|
+
function sessionDirFor(root: string, sessionId: string): string | null {
|
|
155
|
+
// both slashes are refused on every host: a backslash is a legal file-name byte on POSIX, but an id
|
|
156
|
+
// that would be a path on Windows is not a plain directory name anywhere
|
|
157
|
+
if (!sessionId || sessionId === "." || sessionId === ".." || /[\\/]/.test(sessionId) || basename(sessionId) !== sessionId) return null;
|
|
158
|
+
return join(root, sessionId);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ---------- rendering (pure; shared by tool output and the TUI) ----------
|
|
162
|
+
|
|
163
|
+
export interface TodoCounts { total: number; pending: number; inProgress: number; completed: number }
|
|
164
|
+
|
|
165
|
+
export function todoCounts(items: readonly TodoItem[]): TodoCounts {
|
|
166
|
+
const c: TodoCounts = { total: items.length, pending: 0, inProgress: 0, completed: 0 };
|
|
167
|
+
for (const t of items) {
|
|
168
|
+
if (t.status === "completed") c.completed++;
|
|
169
|
+
else if (t.status === "in_progress") c.inProgress++;
|
|
170
|
+
else c.pending++;
|
|
171
|
+
}
|
|
172
|
+
return c;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const GLYPH: Record<TodoStatus, string> = { pending: "[ ]", in_progress: "[>]", completed: "[x]" };
|
|
176
|
+
|
|
177
|
+
/** Single-line content: whitespace collapsed, clipped with an ellipsis (surrogate-safe). */
|
|
178
|
+
function oneLine(text: string): string {
|
|
179
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
180
|
+
return flat.length > RENDER_CONTENT_CHARS
|
|
181
|
+
? flat.slice(0, RENDER_CONTENT_CHARS).replace(/[\uD800-\uDBFF]$/, "") + "…"
|
|
182
|
+
: flat;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Checkbox rendering: a summary line, then one `[glyph] id: content (priority)`
|
|
186
|
+
* row per item in list order. Bounded: ≤MAX_TODOS rows, content clipped, and the
|
|
187
|
+
* id flattened too (a trimmed id may still carry an inner newline — one row per item). */
|
|
188
|
+
export function renderTodos(items: readonly TodoItem[]): string {
|
|
189
|
+
if (items.length === 0) return "todos: (empty)";
|
|
190
|
+
const c = todoCounts(items);
|
|
191
|
+
const lines = [`todos: ${c.total} total · ${c.completed} completed · ${c.inProgress} in progress · ${c.pending} pending`];
|
|
192
|
+
for (const t of items.slice(0, MAX_TODOS)) {
|
|
193
|
+
lines.push(`${GLYPH[t.status]} ${oneLine(t.id)}: ${oneLine(t.content)}${t.priority ? ` (${t.priority})` : ""}`);
|
|
194
|
+
}
|
|
195
|
+
if (items.length > MAX_TODOS) lines.push(`(+${items.length - MAX_TODOS} more not shown)`);
|
|
196
|
+
return lines.join("\n");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The re-send the loop makes while a plan is open (loop.ts LoopDeps.planReminder).
|
|
200
|
+
*
|
|
201
|
+
* A list written twenty turns ago is buried under tool results: the model stops marking items done,
|
|
202
|
+
* starts a second item without finishing the first, or forgets the tail of the plan entirely. This is
|
|
203
|
+
* the same shape as the tool's own output, plus the one instruction that matters right now — so the
|
|
204
|
+
* plan is always the most recent thing in the request, not the oldest.
|
|
205
|
+
*
|
|
206
|
+
* null when there is nothing to chase (no list, or everything completed): a finished plan must not
|
|
207
|
+
* keep nagging, and an empty one has nothing to say. */
|
|
208
|
+
export function planReminder(items: readonly TodoItem[]): string | null {
|
|
209
|
+
const c = todoCounts(items);
|
|
210
|
+
if (c.total === 0 || c.completed === c.total) return null;
|
|
211
|
+
return [
|
|
212
|
+
"<plan-reminder>",
|
|
213
|
+
"Your own todo list for this task, still open — not a message from the user.",
|
|
214
|
+
renderTodos(items),
|
|
215
|
+
c.inProgress === 0
|
|
216
|
+
? "Nothing is in progress. Mark the next item in_progress with todo_write before you start it."
|
|
217
|
+
: "Mark the in_progress item completed with todo_write the moment it is done, then start the next one.",
|
|
218
|
+
"Rewrite the list if the plan changed. Never mention this reminder in your reply.",
|
|
219
|
+
"</plan-reminder>",
|
|
220
|
+
].join("\n");
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Status-bar label, e.g. "todos 1/3" (completed/total); "" when the list is empty. */
|
|
224
|
+
export function todoStatusLabel(items: readonly TodoItem[]): string {
|
|
225
|
+
if (items.length === 0) return "";
|
|
226
|
+
const c = todoCounts(items);
|
|
227
|
+
return `todos ${c.completed}/${c.total}`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---------- tools ----------
|
|
231
|
+
|
|
232
|
+
const WRITE_DESCRIPTION =
|
|
233
|
+
"Create or update this session's structured todo list (your plan). REPLACES the whole list: send every item " +
|
|
234
|
+
`you want kept — items {id, content, status, priority?}; at most ${MAX_TODOS} items, ids unique and non-empty ` +
|
|
235
|
+
`(≤${MAX_ID_CHARS} chars), content non-empty (≤${MAX_CONTENT_CHARS} chars). Statuses: pending | in_progress ` +
|
|
236
|
+
"(exactly ONE at a time) | completed. Priority: high | medium | low (optional). An invalid list is rejected whole " +
|
|
237
|
+
"and nothing changes; an empty list clears the todos. Use proactively when: the task needs 3+ distinct steps; the " +
|
|
238
|
+
"work is non-trivial and benefits from planning; the user gives multiple tasks or asks for a todo list; new " +
|
|
239
|
+
"instructions arrive (capture them as todos); you start a step (mark it in_progress first) or finish one (mark it " +
|
|
240
|
+
"completed only once the work, including verification, is actually done — never on intent; add follow-ups " +
|
|
241
|
+
"discovered on the way). Skip it for a single straightforward task, a purely informational request, or when " +
|
|
242
|
+
"tracking adds no value. Update in real time — don't batch completions. When in doubt, use it.";
|
|
243
|
+
|
|
244
|
+
const READ_DESCRIPTION =
|
|
245
|
+
"Read this session's todo list as last written by todo_write: ids, content, status, priority. Use it to get the " +
|
|
246
|
+
"current ids before updating the list, or to check what remains. Empty until todo_write creates a list.";
|
|
247
|
+
|
|
248
|
+
const itemSchema = {
|
|
249
|
+
type: "object",
|
|
250
|
+
properties: {
|
|
251
|
+
id: { type: "string", description: `stable short id, unique within the list (e.g. "t1"); ≤${MAX_ID_CHARS} chars` },
|
|
252
|
+
content: { type: "string", description: `brief, specific, actionable description of the task; ≤${MAX_CONTENT_CHARS} chars` },
|
|
253
|
+
status: { type: "string", enum: [...TODO_STATUSES], description: "pending | in_progress (exactly one at a time) | completed" },
|
|
254
|
+
priority: { type: "string", enum: [...TODO_PRIORITIES], description: "optional priority" },
|
|
255
|
+
},
|
|
256
|
+
required: ["id", "content", "status"],
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
/** `todo_write` bound to a sessions root; the list lives at <root>/<ctx.sessionId>/todos.json. */
|
|
260
|
+
export function todoWriteTool(sessionsRoot: string): Tool {
|
|
261
|
+
return {
|
|
262
|
+
schema: {
|
|
263
|
+
name: "todo_write",
|
|
264
|
+
description: WRITE_DESCRIPTION,
|
|
265
|
+
args: {
|
|
266
|
+
type: "object",
|
|
267
|
+
properties: {
|
|
268
|
+
todos: { type: "array", description: "the complete, updated todo list (replaces the current one)", maxItems: MAX_TODOS, items: itemSchema },
|
|
269
|
+
},
|
|
270
|
+
required: ["todos"],
|
|
271
|
+
},
|
|
272
|
+
},
|
|
273
|
+
kind: "memory",
|
|
274
|
+
sequential: true,
|
|
275
|
+
execute(args: unknown, ctx: ToolContext): Promise<ToolOutput> {
|
|
276
|
+
const dir = sessionDirFor(sessionsRoot, ctx.sessionId);
|
|
277
|
+
if (!dir) return Promise.resolve({ ok: false, output: `todo_write failed: invalid session id ${show(ctx.sessionId)}` });
|
|
278
|
+
// keep ONLY the schema arg (recall.ts idiom): smuggled keys never influence behavior
|
|
279
|
+
const raw = (args && typeof args === "object" ? args : {}) as Record<string, unknown>;
|
|
280
|
+
const v = validateTodos(raw.todos);
|
|
281
|
+
if (!v.ok) return Promise.resolve({ ok: false, output: `todo_write failed: ${v.error}; the list was not changed` });
|
|
282
|
+
try {
|
|
283
|
+
saveTodos(dir, v.items);
|
|
284
|
+
} catch (e) {
|
|
285
|
+
return Promise.resolve({ ok: false, output: `todo_write failed: could not write ${TODOS_FILE}: ${e instanceof Error ? e.message : String(e)}` });
|
|
286
|
+
}
|
|
287
|
+
// gemini write-todos.ts:52/:68 wording for the clear case; otherwise the checkbox view
|
|
288
|
+
const output = v.items.length === 0 ? "Cleared todo list." : renderTodos(v.items);
|
|
289
|
+
return Promise.resolve({ ok: true, output, data: { items: v.items } });
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** `todo_read` bound to the same root. Pure read (kind "read"): never creates the file. */
|
|
295
|
+
export function todoReadTool(sessionsRoot: string): Tool {
|
|
296
|
+
return {
|
|
297
|
+
schema: {
|
|
298
|
+
name: "todo_read",
|
|
299
|
+
description: READ_DESCRIPTION,
|
|
300
|
+
args: { type: "object", properties: {} },
|
|
301
|
+
},
|
|
302
|
+
kind: "read",
|
|
303
|
+
sequential: false,
|
|
304
|
+
execute(_args: unknown, ctx: ToolContext): Promise<ToolOutput> {
|
|
305
|
+
const dir = sessionDirFor(sessionsRoot, ctx.sessionId);
|
|
306
|
+
if (!dir) return Promise.resolve({ ok: false, output: `todo_read failed: invalid session id ${show(ctx.sessionId)}` });
|
|
307
|
+
const { items, note } = loadTodos(dir);
|
|
308
|
+
if (items.length === 0) {
|
|
309
|
+
const head = note ? `${note}\n` : "";
|
|
310
|
+
return Promise.resolve({ ok: true, output: `${head}No todos for this session yet — use todo_write to create a list.`, data: { items, ...(note ? { note } : {}) } });
|
|
311
|
+
}
|
|
312
|
+
return Promise.resolve({ ok: true, output: renderTodos(items), data: { items } });
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Both tools over one sessions root — the runtime registration unit. */
|
|
318
|
+
export function todoTools(sessionsRoot: string): Tool[] {
|
|
319
|
+
return [todoWriteTool(sessionsRoot), todoReadTool(sessionsRoot)];
|
|
320
|
+
}
|