@oyasmi/pipiclaw 0.8.9-beta.1 → 0.8.9-beta.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.
Files changed (90) hide show
  1. package/README.md +8 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +3 -2
  4. package/dist/agent/effect-ledger.d.ts +11 -0
  5. package/dist/agent/effect-ledger.js +42 -0
  6. package/dist/agent/job-manager.d.ts +90 -13
  7. package/dist/agent/job-manager.js +235 -20
  8. package/dist/agent/prompt/sections.js +11 -2
  9. package/dist/agent/prompt/types.d.ts +7 -1
  10. package/dist/agent/runner-factory.d.ts +7 -0
  11. package/dist/agent/session-events.js +20 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/log.d.ts +6 -0
  14. package/dist/log.js +12 -0
  15. package/dist/memory/consolidation.d.ts +5 -0
  16. package/dist/memory/consolidation.js +35 -147
  17. package/dist/memory/extraction.d.ts +45 -0
  18. package/dist/memory/extraction.js +227 -0
  19. package/dist/memory/lifecycle.js +5 -0
  20. package/dist/memory/maintenance-jobs.js +7 -0
  21. package/dist/memory/post-turn-review.d.ts +3 -1
  22. package/dist/memory/post-turn-review.js +20 -189
  23. package/dist/memory/recall.d.ts +0 -1
  24. package/dist/memory/recall.js +135 -77
  25. package/dist/memory/sidecar-worker.d.ts +7 -0
  26. package/dist/memory/sidecar-worker.js +23 -5
  27. package/dist/paths.d.ts +1 -0
  28. package/dist/paths.js +11 -0
  29. package/dist/playbooks/background-jobs.md +40 -0
  30. package/dist/playbooks/catalog.d.ts +1 -7
  31. package/dist/playbooks/catalog.js +4 -14
  32. package/dist/playbooks/event-scheduling.md +8 -4
  33. package/dist/playbooks/memory-and-learning.md +1 -1
  34. package/dist/playbooks/outbound-media.md +45 -0
  35. package/dist/playbooks/runtime-orientation.md +1 -1
  36. package/dist/playbooks/task-closeout.md +1 -1
  37. package/dist/playbooks/task-delegation.md +10 -4
  38. package/dist/playbooks/task-driving.md +52 -18
  39. package/dist/playbooks/task-planning.md +43 -18
  40. package/dist/runtime/bootstrap.js +24 -3
  41. package/dist/runtime/channel-context.d.ts +33 -0
  42. package/dist/runtime/dingtalk.d.ts +22 -2
  43. package/dist/runtime/dingtalk.js +141 -0
  44. package/dist/runtime/durable-dispatch.d.ts +10 -0
  45. package/dist/runtime/durable-dispatch.js +42 -1
  46. package/dist/runtime/event-validation.d.ts +48 -0
  47. package/dist/runtime/event-validation.js +81 -0
  48. package/dist/runtime/events.d.ts +17 -8
  49. package/dist/runtime/events.js +96 -22
  50. package/dist/runtime/store.d.ts +1 -1
  51. package/dist/runtime/task-driver.d.ts +5 -0
  52. package/dist/runtime/task-driver.js +38 -12
  53. package/dist/settings.d.ts +11 -0
  54. package/dist/settings.js +12 -0
  55. package/dist/shared/recoverable-error.d.ts +26 -0
  56. package/dist/shared/recoverable-error.js +29 -0
  57. package/dist/shared/task-ledger.d.ts +9 -7
  58. package/dist/shared/task-ledger.js +1 -1
  59. package/dist/subagents/builtin/explorer.md +16 -0
  60. package/dist/subagents/builtin/researcher.md +17 -0
  61. package/dist/subagents/builtin/verifier.md +17 -0
  62. package/dist/subagents/discovery.d.ts +17 -3
  63. package/dist/subagents/discovery.js +88 -15
  64. package/dist/subagents/tool.d.ts +21 -1
  65. package/dist/subagents/tool.js +140 -12
  66. package/dist/tasks/transitions.js +3 -2
  67. package/dist/tools/bash.d.ts +2 -0
  68. package/dist/tools/bash.js +18 -5
  69. package/dist/tools/event-manage.js +28 -77
  70. package/dist/tools/index.d.ts +4 -0
  71. package/dist/tools/index.js +7 -2
  72. package/dist/tools/job.js +2 -2
  73. package/dist/tools/memory-manage.js +0 -1
  74. package/dist/tools/registry.d.ts +29 -8
  75. package/dist/tools/registry.js +39 -22
  76. package/dist/tools/send-media.d.ts +28 -0
  77. package/dist/tools/send-media.js +88 -0
  78. package/dist/tools/task-manage/create.js +5 -4
  79. package/dist/tools/task-manage/lifecycle.js +12 -11
  80. package/dist/tools/task-manage/schema.js +2 -1
  81. package/dist/tools/task-manage/shared.js +13 -12
  82. package/dist/tools/task-manage/verification.js +14 -13
  83. package/dist/tools/tool-details.d.ts +44 -0
  84. package/dist/tools/tool-details.js +62 -0
  85. package/dist/tui/app.js +2 -0
  86. package/dist/tui/terminal-media-sender.d.ts +9 -0
  87. package/dist/tui/terminal-media-sender.js +15 -0
  88. package/package.json +2 -2
  89. package/dist/playbooks/task-recurring.md +0 -44
  90. package/dist/playbooks/task-repair.md +0 -45
package/dist/tools/job.js CHANGED
@@ -38,7 +38,7 @@ export function createJobTool(options) {
38
38
  label: "job",
39
39
  description: "Inspect and control background bash jobs (started with bash async:true). op=list shows a snapshot; " +
40
40
  "op=poll waits briefly for a running job to finish and returns its output; op=cancel stops jobs by id. " +
41
- "To be woken when a long job is likely done, schedule a check-in with event_manage instead of blocking.",
41
+ "A finished job wakes this channel by itself, so never schedule a check-in for one — end the turn instead.",
42
42
  parameters: jobSchema,
43
43
  execute: async (_toolCallId, { op, ids }, signal) => {
44
44
  if (op === "cancel") {
@@ -81,7 +81,7 @@ export function createJobTool(options) {
81
81
  }
82
82
  if (running.length > 0) {
83
83
  parts.push(`## Still running (${running.length})`, ...running.map(formatJobLine));
84
- parts.push("Poll again to keep waiting, or schedule a check-in with event_manage.");
84
+ parts.push("Poll again to keep waiting, or just end your turn — you are woken when the job finishes.");
85
85
  }
86
86
  return {
87
87
  content: [{ type: "text", text: parts.join("\n\n") }],
@@ -94,7 +94,6 @@ export function createMemoryManageTool(options) {
94
94
  maxInjected: 8,
95
95
  maxChars: 4000,
96
96
  rerankWithModel: false,
97
- autoRerank: false,
98
97
  model,
99
98
  resolveApiKey: options.resolveApiKey,
100
99
  candidateStore: options.memoryCandidateStore,
@@ -3,9 +3,11 @@ import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
4
  import type { Executor } from "../executor.js";
5
5
  import type { MemoryCandidateStore } from "../memory/candidates.js";
6
+ import type { MediaSender } from "../runtime/channel-context.js";
6
7
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
7
8
  import type { PipiclawSessionSearchSettings } from "../settings.js";
8
9
  import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
10
+ import { type ToolDetailsKind } from "./tool-details.js";
9
11
  /**
10
12
  * Unified build context passed to every tool's `create` closure. It carries the union
11
13
  * of everything any registered tool might need; each closure reads only its own fields.
@@ -40,11 +42,15 @@ export interface ToolBuildContext {
40
42
  resolveApiKey?: (model: Model<Api>) => Promise<string>;
41
43
  getSessionSearchSettings?: () => PipiclawSessionSearchSettings;
42
44
  memoryCandidateStore?: MemoryCandidateStore;
45
+ /**
46
+ * Present only on the main path, and only when the driving transport can deliver
47
+ * files. Gates the `send_media` tool; sub-agents never receive it.
48
+ */
49
+ mediaSender?: MediaSender;
43
50
  }
44
51
  export interface ToolRegistration {
45
- name: string;
46
- /** One-line hint rendered in the system prompt's `## Tools` section. */
47
- promptHint: string;
52
+ /** Also the tool's `details.kind`: the name is the authoritative discriminator. */
53
+ name: ToolDetailsKind;
48
54
  /** Whether this tool is included in a sub-agent's tool set. */
49
55
  availableToSubagents: boolean;
50
56
  /** Config gate; when omitted the tool is always enabled. */
@@ -58,13 +64,28 @@ export interface ToolRegistration {
58
64
  * sub-agent tool set is built by importing `buildToolSet` from this module).
59
65
  */
60
66
  export declare const TOOL_REGISTRY: ToolRegistration[];
61
- /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
62
- export declare const SUBAGENT_TOOL_HINT = "Delegate focused work or independent verification; optionally isolate implementation in a task-owned git worktree";
63
- /** Single source of truth for prompt hints, keyed by tool name (leaf tools + subagent). */
64
- export declare const TOOL_PROMPT_HINTS: Record<string, string>;
67
+ /**
68
+ * Every tool name a tool set can contain: the registry plus `subagent`, which is registered
69
+ * outside it. Used to validate authored references to tools (playbook `requires-tools`), so a
70
+ * typo fails loudly instead of silently dropping the playbook from the catalog.
71
+ *
72
+ * This deliberately carries no per-tool prose. Tool name, description and parameter schema
73
+ * already reach the model with every request; spec 026 §3.2 removed the `## Available Tools`
74
+ * prompt section because repeating a hint for each tool cost ~180 prompt units per turn and
75
+ * added no capability. Guidance on *when* to prefer a tool belongs in that tool's own
76
+ * `description` (see `grep`, which tells the model to prefer it over `bash grep -rn`).
77
+ */
78
+ export declare const TOOL_NAMES: ReadonlySet<string>;
65
79
  export interface BuildToolSetOptions {
66
80
  /** When true, include only tools flagged `availableToSubagents`. */
67
81
  forSubagent?: boolean;
68
82
  }
69
- /** Build a tool set from the registry, honoring sub-agent availability and config gates. */
83
+ /**
84
+ * Build a tool set from the registry, honoring sub-agent availability and config gates.
85
+ *
86
+ * Every tool is bound to the `details` contract here rather than in its own factory: the
87
+ * registration name is stamped as `details.kind`, and a `RecoverableToolError` becomes a
88
+ * normal result the model can act on. Doing it at this single seam means a new tool conforms
89
+ * without its author having to remember, and `kind` can never disagree with the name.
90
+ */
70
91
  export declare function buildToolSet(ctx: ToolBuildContext, options?: BuildToolSetOptions): AgentTool<any>[];
@@ -5,9 +5,11 @@ import { createGrepTool } from "./grep.js";
5
5
  import { createJobTool } from "./job.js";
6
6
  import { createMemoryManageTool } from "./memory-manage.js";
7
7
  import { createReadTool } from "./read.js";
8
+ import { createSendMediaTool } from "./send-media.js";
8
9
  import { createSessionSearchTool } from "./session-search.js";
9
10
  import { createSkillManageTool } from "./skill-manage.js";
10
11
  import { createTaskManageTool } from "./task-manage.js";
12
+ import { withToolDetails } from "./tool-details.js";
11
13
  import { createWebFetchTool } from "./web-fetch.js";
12
14
  import { createWebSearchTool } from "./web-search.js";
13
15
  import { createWriteTool } from "./write.js";
@@ -36,13 +38,11 @@ function webEnabled(ctx) {
36
38
  export const TOOL_REGISTRY = [
37
39
  {
38
40
  name: "read",
39
- promptHint: "Read files",
40
41
  availableToSubagents: true,
41
42
  create: (ctx) => createReadTool(ctx.executor, fileToolOptions(ctx)),
42
43
  },
43
44
  {
44
45
  name: "bash",
45
- promptHint: "Run shell commands and external programs",
46
46
  availableToSubagents: true,
47
47
  create: (ctx) => createBashTool(ctx.executor, {
48
48
  ...fileToolOptions(ctx),
@@ -56,25 +56,21 @@ export const TOOL_REGISTRY = [
56
56
  },
57
57
  {
58
58
  name: "edit",
59
- promptHint: "Surgical file edits",
60
59
  availableToSubagents: true,
61
60
  create: (ctx) => createEditTool(ctx.executor, fileToolOptions(ctx)),
62
61
  },
63
62
  {
64
63
  name: "grep",
65
- promptHint: "Search file contents with a regex; grouped, paginated, token-bounded — prefer over bash grep",
66
64
  availableToSubagents: true,
67
65
  create: (ctx) => createGrepTool(ctx.executor, fileToolOptions(ctx)),
68
66
  },
69
67
  {
70
68
  name: "write",
71
- promptHint: "Create or overwrite files when needed",
72
69
  availableToSubagents: true,
73
70
  create: (ctx) => createWriteTool(ctx.executor, fileToolOptions(ctx)),
74
71
  },
75
72
  {
76
73
  name: "web_search",
77
- promptHint: "Search the public web and return titles, URLs, and snippets",
78
74
  availableToSubagents: true,
79
75
  enabledBy: webEnabled,
80
76
  create: (ctx) => createWebSearchTool({
@@ -86,7 +82,6 @@ export const TOOL_REGISTRY = [
86
82
  },
87
83
  {
88
84
  name: "web_fetch",
89
- promptHint: "Fetch a public URL and extract readable content",
90
85
  availableToSubagents: true,
91
86
  enabledBy: webEnabled,
92
87
  create: (ctx) => createWebFetchTool({
@@ -97,9 +92,21 @@ export const TOOL_REGISTRY = [
97
92
  channelDir: ctx.channelDir,
98
93
  }),
99
94
  },
95
+ {
96
+ name: "send_media",
97
+ availableToSubagents: false,
98
+ // Enabled only when the driving transport supplied a media sender (the DingTalk
99
+ // bot, or the terminal). Absent it, the tool is not built or advertised.
100
+ enabledBy: (ctx) => ctx.mediaSender != null,
101
+ create: (ctx) => createSendMediaTool(ctx.executor, {
102
+ mediaSender: req(ctx.mediaSender, "mediaSender"),
103
+ channelId: ctx.channelId,
104
+ securityConfig: ctx.securityConfig,
105
+ securityContext: ctx.securityContext,
106
+ }),
107
+ },
100
108
  {
101
109
  name: "session_search",
102
- promptHint: "Search current-channel cold transcript storage for older conversation details",
103
110
  availableToSubagents: false,
104
111
  create: (ctx) => createSessionSearchTool({
105
112
  channelId: ctx.channelId,
@@ -111,7 +118,6 @@ export const TOOL_REGISTRY = [
111
118
  },
112
119
  {
113
120
  name: "memory_manage",
114
- promptHint: "Save a durable fact, search stored memory on demand, or forget an entry — when the user asks",
115
121
  availableToSubagents: false,
116
122
  create: (ctx) => createMemoryManageTool({
117
123
  channelId: ctx.channelId,
@@ -124,13 +130,11 @@ export const TOOL_REGISTRY = [
124
130
  },
125
131
  {
126
132
  name: "skill_manage",
127
- promptHint: "List, view, create, or maintain workspace-level procedural memory in skills/",
128
133
  availableToSubagents: false,
129
134
  create: (ctx) => createSkillManageTool({ workspaceDir: ctx.workspaceDir }),
130
135
  },
131
136
  {
132
137
  name: "event_manage",
133
- promptHint: "Create/update/delete validated one-shot reminders, periodic cadences, and preAction-gated sensors",
134
138
  availableToSubagents: false,
135
139
  create: (ctx) => createEventManageTool({
136
140
  workspaceDir: ctx.workspaceDir,
@@ -140,7 +144,6 @@ export const TOOL_REGISTRY = [
140
144
  },
141
145
  {
142
146
  name: "task_manage",
143
- promptHint: "Create, checkpoint, govern, verify, complete, cancel, or list persistent tasks",
144
147
  availableToSubagents: false,
145
148
  // tools.tasks is the master switch for the whole autonomous long-running task
146
149
  // mechanism; the TaskDriver and per-turn task digest honor the same flag.
@@ -154,7 +157,6 @@ export const TOOL_REGISTRY = [
154
157
  },
155
158
  {
156
159
  name: "job",
157
- promptHint: "Inspect/poll/cancel background bash jobs started with bash async:true",
158
160
  availableToSubagents: false,
159
161
  // Present only when a job manager was supplied (always on the main path,
160
162
  // never for sub-agents).
@@ -162,14 +164,29 @@ export const TOOL_REGISTRY = [
162
164
  create: (ctx) => createJobTool({ jobManager: req(ctx.jobManager, "jobManager") }),
163
165
  },
164
166
  ];
165
- /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
166
- export const SUBAGENT_TOOL_HINT = "Delegate focused work or independent verification; optionally isolate implementation in a task-owned git worktree";
167
- /** Single source of truth for prompt hints, keyed by tool name (leaf tools + subagent). */
168
- export const TOOL_PROMPT_HINTS = {
169
- ...Object.fromEntries(TOOL_REGISTRY.map((registration) => [registration.name, registration.promptHint])),
170
- subagent: SUBAGENT_TOOL_HINT,
171
- };
172
- /** Build a tool set from the registry, honoring sub-agent availability and config gates. */
167
+ /**
168
+ * Every tool name a tool set can contain: the registry plus `subagent`, which is registered
169
+ * outside it. Used to validate authored references to tools (playbook `requires-tools`), so a
170
+ * typo fails loudly instead of silently dropping the playbook from the catalog.
171
+ *
172
+ * This deliberately carries no per-tool prose. Tool name, description and parameter schema
173
+ * already reach the model with every request; spec 026 §3.2 removed the `## Available Tools`
174
+ * prompt section because repeating a hint for each tool cost ~180 prompt units per turn and
175
+ * added no capability. Guidance on *when* to prefer a tool belongs in that tool's own
176
+ * `description` (see `grep`, which tells the model to prefer it over `bash grep -rn`).
177
+ */
178
+ export const TOOL_NAMES = new Set([
179
+ ...TOOL_REGISTRY.map((registration) => registration.name),
180
+ "subagent",
181
+ ]);
182
+ /**
183
+ * Build a tool set from the registry, honoring sub-agent availability and config gates.
184
+ *
185
+ * Every tool is bound to the `details` contract here rather than in its own factory: the
186
+ * registration name is stamped as `details.kind`, and a `RecoverableToolError` becomes a
187
+ * normal result the model can act on. Doing it at this single seam means a new tool conforms
188
+ * without its author having to remember, and `kind` can never disagree with the name.
189
+ */
173
190
  export function buildToolSet(ctx, options = {}) {
174
191
  const result = [];
175
192
  for (const registration of TOOL_REGISTRY) {
@@ -179,7 +196,7 @@ export function buildToolSet(ctx, options = {}) {
179
196
  if (registration.enabledBy && !registration.enabledBy(ctx)) {
180
197
  continue;
181
198
  }
182
- result.push(registration.create(ctx));
199
+ result.push(withToolDetails(registration.create(ctx), registration.name));
183
200
  }
184
201
  return result;
185
202
  }
@@ -0,0 +1,28 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import type { Executor } from "../executor.js";
4
+ import type { MediaSender } from "../runtime/channel-context.js";
5
+ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
+ declare const sendMediaSchema: Type.TObject<{
7
+ label: Type.TString;
8
+ path: Type.TString;
9
+ fileName: Type.TOptional<Type.TString>;
10
+ }>;
11
+ export interface SendMediaToolOptions {
12
+ /** Transport that actually delivers the attachment. Bound to `channelId`. */
13
+ mediaSender: MediaSender;
14
+ /** The channel this tool instance is bound to — supplied by the runtime, not the model. */
15
+ channelId: string;
16
+ securityConfig?: SecurityConfig;
17
+ securityContext?: SecurityRuntimeContext;
18
+ }
19
+ /**
20
+ * Send a workspace file to the current channel as a native attachment (inline
21
+ * image or downloadable file). Bound to its channel at build time — like `read`
22
+ * and `bash` — so the model never chooses the destination. The file is read
23
+ * through the `Executor` (base64, exactly as `read` does for images) so the tool
24
+ * works regardless of where the executor runs, and every path passes the same
25
+ * path-guard as the file tools before any bytes leave the box.
26
+ */
27
+ export declare function createSendMediaTool(executor: Executor, options: SendMediaToolOptions): AgentTool<typeof sendMediaSchema>;
28
+ export {};
@@ -0,0 +1,88 @@
1
+ import { basename, extname } from "path";
2
+ import { Type } from "typebox";
3
+ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
+ import { logSecurityEvent } from "../security/logger.js";
5
+ import { guardPath } from "../security/path-guard.js";
6
+ import { shellEscape } from "../shared/shell-escape.js";
7
+ /** Extensions delivered as inline images; everything else goes as a file attachment. */
8
+ const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
9
+ const sendMediaSchema = Type.Object({
10
+ label: Type.String({ description: "Brief description of what you're sending and why (shown to the user)" }),
11
+ path: Type.String({ description: "Path to the local file to send (relative to the workspace, or absolute)" }),
12
+ fileName: Type.Optional(Type.String({ description: "Display name for the recipient; defaults to the file's own name" })),
13
+ });
14
+ function formatPathBlockMessage(resolvedPath, category, reason) {
15
+ const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
16
+ if (reason)
17
+ lines.push(`Reason: ${reason}`);
18
+ if (resolvedPath)
19
+ lines.push(`Resolved path: ${resolvedPath}`);
20
+ return lines.join("\n");
21
+ }
22
+ /**
23
+ * Send a workspace file to the current channel as a native attachment (inline
24
+ * image or downloadable file). Bound to its channel at build time — like `read`
25
+ * and `bash` — so the model never chooses the destination. The file is read
26
+ * through the `Executor` (base64, exactly as `read` does for images) so the tool
27
+ * works regardless of where the executor runs, and every path passes the same
28
+ * path-guard as the file tools before any bytes leave the box.
29
+ */
30
+ export function createSendMediaTool(executor, options) {
31
+ const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
32
+ const securityContext = options.securityContext ?? { workspaceDir: process.cwd(), cwd: process.cwd() };
33
+ return {
34
+ name: "send_media",
35
+ label: "send_media",
36
+ description: "Send a local file to the user in the current channel as a native attachment. " +
37
+ "Image files (jpg, png, gif, webp, bmp) are delivered inline; everything else is sent as a downloadable file. " +
38
+ "Use this to hand the user a generated report, screenshot, chart, or export — not for showing file contents to yourself (use `read` for that).",
39
+ parameters: sendMediaSchema,
40
+ execute: async (_toolCallId, { path, fileName }, signal) => {
41
+ if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
42
+ const guardResult = guardPath(path, "read", { ...securityContext, config: securityConfig.pathGuard });
43
+ if (!guardResult.allowed) {
44
+ await logSecurityEvent(securityContext.workspaceDir, securityConfig, {
45
+ type: "path",
46
+ tool: "send_media",
47
+ channelId: options.channelId,
48
+ rawPath: path,
49
+ operation: "read",
50
+ resolvedPath: guardResult.resolvedPath,
51
+ category: guardResult.category,
52
+ reason: guardResult.reason,
53
+ });
54
+ throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
55
+ }
56
+ }
57
+ // Confirm the target is a readable regular file before reading it, so the
58
+ // agent gets "not a file" rather than a confusing base64 error.
59
+ const stat = await executor.exec(`test -f ${shellEscape(path)} && echo OK || echo NO`, { signal });
60
+ if (stat.stdout.trim() !== "OK") {
61
+ throw new Error(`Cannot send ${path}: not a regular file (does it exist?).`);
62
+ }
63
+ const encoded = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
64
+ if (encoded.code !== 0) {
65
+ throw new Error(encoded.stderr || `Failed to read file: ${path}`);
66
+ }
67
+ const data = Buffer.from(encoded.stdout.replace(/\s/g, ""), "base64");
68
+ if (data.length === 0) {
69
+ throw new Error(`Cannot send ${path}: the file is empty.`);
70
+ }
71
+ const name = fileName?.trim() || basename(path);
72
+ const kind = IMAGE_EXTENSIONS.has(extname(name).toLowerCase()) ? "image" : "file";
73
+ const result = await options.mediaSender.sendMedia(options.channelId, { data, fileName: name, kind });
74
+ if (!result.ok) {
75
+ throw new Error(result.error ?? "Failed to send the file to the channel.");
76
+ }
77
+ return {
78
+ content: [
79
+ {
80
+ type: "text",
81
+ text: `Sent ${kind === "image" ? "image" : "file"} "${name}" (${(data.length / 1024).toFixed(1)}KB) to the channel.`,
82
+ },
83
+ ],
84
+ details: undefined,
85
+ };
86
+ },
87
+ };
88
+ }
@@ -3,24 +3,25 @@ import { mkdir } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { writeFileAtomically } from "../../shared/atomic-file.js";
5
5
  import { normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../shared/task-ledger.js";
6
+ import { RecoverableToolError } from "../tool-details.js";
6
7
  import { renderTaskFile, renderTaskSkeleton, tasksDir, validateTaskRelations } from "./shared.js";
7
8
  export async function createTask(options, request) {
8
9
  if (!request.id)
9
- throw new Error('action "create" requires an id.');
10
+ throw new RecoverableToolError('action "create" requires an id.');
10
11
  const id = normalizeTaskId(request.id);
11
12
  const dir = tasksDir(options);
12
13
  const taskPath = join(dir, `${id}.md`);
13
14
  const archivePath = join(dir, "archive", `${id}.md`);
14
15
  if (existsSync(taskPath)) {
15
- throw new Error(`Task "${id}" already exists; use action "set" or edit the body instead.`);
16
+ throw new RecoverableToolError(`Task "${id}" already exists; use action "set" or edit the body instead.`);
16
17
  }
17
18
  if (existsSync(archivePath)) {
18
- throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
19
+ throw new RecoverableToolError(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
19
20
  }
20
21
  const { fields, body } = renderTaskSkeleton(request);
21
22
  const badDod = uncheckedTaskAcceptanceItems(body).find((item) => item.startsWith("DoD has no checklist items"));
22
23
  if (badDod)
23
- throw new Error(badDod);
24
+ throw new RecoverableToolError(badDod);
24
25
  await validateTaskRelations(options, id, fields);
25
26
  await mkdir(dir, { recursive: true });
26
27
  await writeFileAtomically(taskPath, renderTaskFile(fields, body));
@@ -6,11 +6,12 @@ import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
6
6
  import { invalidateTaskVerification } from "../../tasks/control.js";
7
7
  import { dependencyState, taskBodyHash } from "../../tasks/store.js";
8
8
  import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
9
+ import { RecoverableToolError } from "../tool-details.js";
9
10
  import { appendCompletionEvidence, applySet, cleanupTaskEvents, markdownValue, readTaskDocument, renderTaskFile, requiredField, tasksDir, unfinishedChildren, validateTaskRelations, } from "./shared.js";
10
11
  import { assertVerificationAttestationMatches } from "./verification.js";
11
12
  export async function setTask(options, request) {
12
13
  if (!request.id)
13
- throw new Error('action "set" requires an id.');
14
+ throw new RecoverableToolError('action "set" requires an id.');
14
15
  const id = normalizeTaskId(request.id);
15
16
  const taskPath = join(tasksDir(options), `${id}.md`);
16
17
  const { fields, body } = await readTaskDocument(taskPath, id, request.control !== undefined);
@@ -34,7 +35,7 @@ export async function setTask(options, request) {
34
35
  }
35
36
  export async function progressTask(options, request) {
36
37
  if (!request.id)
37
- throw new Error('action "progress" requires an id.');
38
+ throw new RecoverableToolError('action "progress" requires an id.');
38
39
  const id = normalizeTaskId(request.id);
39
40
  const note = requiredField(request.note, "note", "progress");
40
41
  const taskPath = join(tasksDir(options), `${id}.md`);
@@ -68,7 +69,7 @@ export async function progressTask(options, request) {
68
69
  }
69
70
  export async function doneTask(options, request) {
70
71
  if (!request.id)
71
- throw new Error('action "done" requires an id.');
72
+ throw new RecoverableToolError('action "done" requires an id.');
72
73
  const id = normalizeTaskId(request.id);
73
74
  const dir = tasksDir(options);
74
75
  const taskPath = join(dir, `${id}.md`);
@@ -76,15 +77,15 @@ export async function doneTask(options, request) {
76
77
  resolveTaskTransition("done", id, normalizeStoredStatus(fields.status));
77
78
  const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
78
79
  if (uncheckedAcceptance.length > 0) {
79
- throw new Error(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before done.`);
80
+ throw new RecoverableToolError(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before done.`);
80
81
  }
81
82
  const dependencies = await dependencyState(options.channelDir, fields.control?.dependsOn ?? [], id);
82
83
  if (!dependencies.ready) {
83
- throw new Error(`Task "${id}" cannot be completed: ${dependencies.reason}. Complete its dependencies first.`);
84
+ throw new RecoverableToolError(`Task "${id}" cannot be completed: ${dependencies.reason}. Complete its dependencies first.`);
84
85
  }
85
86
  const children = await unfinishedChildren(options, id);
86
87
  if (children.length > 0) {
87
- throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Finish or cancel them first.`);
88
+ throw new RecoverableToolError(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Finish or cancel them first.`);
88
89
  }
89
90
  if (fields.control?.sideEffects === "external") {
90
91
  if (fields.control.externalApproval === "required") {
@@ -97,15 +98,15 @@ export async function doneTask(options, request) {
97
98
  if (fields.control?.verification.mode === "independent") {
98
99
  const verification = fields.control.verification;
99
100
  if (verification.status !== "passed" || !verification.bodyHash || !verification.runId) {
100
- throw new Error(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
101
+ throw new RecoverableToolError(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
101
102
  }
102
103
  if (verification.bodyHash !== taskBodyHash(body)) {
103
- throw new Error(`Task "${id}" changed after its independent PASS; rerun verification before done.`);
104
+ throw new RecoverableToolError(`Task "${id}" changed after its independent PASS; rerun verification before done.`);
104
105
  }
105
106
  if (verification.subjectHash) {
106
107
  const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
107
108
  if (currentSubject !== verification.subjectHash) {
108
- throw new Error(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
109
+ throw new RecoverableToolError(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
109
110
  }
110
111
  }
111
112
  await assertVerificationAttestationMatches(options.channelDir, id, verification);
@@ -147,7 +148,7 @@ export async function doneTask(options, request) {
147
148
  }
148
149
  export async function cancelTask(options, request) {
149
150
  if (!request.id)
150
- throw new Error('action "cancel" requires an id.');
151
+ throw new RecoverableToolError('action "cancel" requires an id.');
151
152
  const id = normalizeTaskId(request.id);
152
153
  const reason = requiredField(request.reason, "reason", "cancel");
153
154
  const dir = tasksDir(options);
@@ -156,7 +157,7 @@ export async function cancelTask(options, request) {
156
157
  resolveTaskTransition("cancel", id, normalizeStoredStatus(fields.status));
157
158
  const children = await unfinishedChildren(options, id);
158
159
  if (children.length > 0) {
159
- throw new Error(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Cancel or re-parent them first.`);
160
+ throw new RecoverableToolError(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Cancel or re-parent them first.`);
160
161
  }
161
162
  if (fields.control) {
162
163
  fields.control.lastOutcome = "blocked";
@@ -1,5 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { SETTABLE_TASK_STATUSES } from "../../tasks/transitions.js";
3
+ import { RecoverableToolError } from "../tool-details.js";
3
4
  export const SETTABLE_STATUSES = SETTABLE_TASK_STATUSES;
4
5
  const taskControlSchema = Type.Object({
5
6
  priority: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("normal"), Type.Literal("high"), Type.Literal("critical")])),
@@ -85,5 +86,5 @@ export function parseAction(action) {
85
86
  action === "list") {
86
87
  return action;
87
88
  }
88
- throw new Error("Unsupported task action. Use create, progress, candidate, set, verify, done, cancel, or list.");
89
+ throw new RecoverableToolError("Unsupported task action. Use create, progress, candidate, set, verify, done, cancel, or list.");
89
90
  }
@@ -8,6 +8,7 @@ import { nextTaskWake, validateTaskSchedule } from "../../shared/task-schedule.j
8
8
  import { applyTaskControlPatch, createDefaultTaskControl } from "../../tasks/control.js";
9
9
  import { readStoredTask } from "../../tasks/store.js";
10
10
  import { isSettableTaskStatus } from "../../tasks/transitions.js";
11
+ import { RecoverableToolError } from "../tool-details.js";
11
12
  import { SETTABLE_STATUSES } from "./schema.js";
12
13
  export function tasksDir(options) {
13
14
  return join(options.channelDir, "tasks");
@@ -21,7 +22,7 @@ export function renderTaskFile(fields, body) {
21
22
  export function requiredField(value, field, action) {
22
23
  const trimmed = value?.trim();
23
24
  if (!trimmed) {
24
- throw new Error(`action "${action}" requires ${field}.`);
25
+ throw new RecoverableToolError(`action "${action}" requires ${field}.`);
25
26
  }
26
27
  return trimmed;
27
28
  }
@@ -55,7 +56,7 @@ function normalizeCreateStatus(status) {
55
56
  return "active";
56
57
  if (isSettableTaskStatus(status))
57
58
  return status;
58
- throw new Error(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
59
+ throw new RecoverableToolError(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
59
60
  }
60
61
  export function renderTaskSkeleton(request) {
61
62
  const title = requiredField(request.title, "title", "create");
@@ -96,15 +97,15 @@ export function renderTaskSkeleton(request) {
96
97
  */
97
98
  export async function readTaskDocument(taskPath, id, allowControlRepair = false) {
98
99
  if (!existsSync(taskPath)) {
99
- throw new Error(`Task "${id}" does not exist; create it with task_manage action "create" first.`);
100
+ throw new RecoverableToolError(`Task "${id}" does not exist; create it with task_manage action "create" first.`);
100
101
  }
101
102
  const content = await readFile(taskPath, "utf-8");
102
103
  const frontmatter = parseTaskFrontmatter(content);
103
104
  if (!frontmatter.readable) {
104
- throw new Error(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
105
+ throw new RecoverableToolError(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
105
106
  }
106
107
  if (frontmatter.controlReadable === false && !allowControlRepair) {
107
- throw new Error(`Task "${id}" has invalid control metadata; repair it with task_manage action "set" and an explicit control patch first.`);
108
+ throw new RecoverableToolError(`Task "${id}" has invalid control metadata; repair it with task_manage action "set" and an explicit control patch first.`);
108
109
  }
109
110
  return {
110
111
  fields: {
@@ -125,7 +126,7 @@ export function applySet(fields, request) {
125
126
  }
126
127
  if (request.status !== undefined) {
127
128
  if (!isSettableTaskStatus(request.status)) {
128
- throw new Error(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
129
+ throw new RecoverableToolError(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
129
130
  }
130
131
  next.status = request.status;
131
132
  }
@@ -135,7 +136,7 @@ export function applySet(fields, request) {
135
136
  next.wake = undefined;
136
137
  }
137
138
  else if (!Number.isFinite(new Date(trimmed).getTime())) {
138
- throw new Error(`wake "${request.wake}" is not a valid ISO8601 date.`);
139
+ throw new RecoverableToolError(`wake "${request.wake}" is not a valid ISO8601 date.`);
139
140
  }
140
141
  else {
141
142
  next.wake = trimmed;
@@ -167,13 +168,13 @@ export async function validateTaskRelations(options, id, fields) {
167
168
  if (!control)
168
169
  return;
169
170
  if (control.parent === id || control.dependsOn.includes(id)) {
170
- throw new Error(`Task "${id}" cannot be its own parent or dependency.`);
171
+ throw new RecoverableToolError(`Task "${id}" cannot be its own parent or dependency.`);
171
172
  }
172
173
  for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
173
174
  const active = join(tasksDir(options), `${relatedId}.md`);
174
175
  const archived = join(tasksDir(options), "archive", `${relatedId}.md`);
175
176
  if (!existsSync(active) && !existsSync(archived)) {
176
- throw new Error(`Related task "${relatedId}" does not exist; create it before linking task "${id}".`);
177
+ throw new RecoverableToolError(`Related task "${relatedId}" does not exist; create it before linking task "${id}".`);
177
178
  }
178
179
  }
179
180
  if (control.parent) {
@@ -181,10 +182,10 @@ export async function validateTaskRelations(options, id, fields) {
181
182
  let current = control.parent;
182
183
  while (current) {
183
184
  if (visited.has(current)) {
184
- throw new Error(`Existing parent chain for "${control.parent}" already contains a cycle.`);
185
+ throw new RecoverableToolError(`Existing parent chain for "${control.parent}" already contains a cycle.`);
185
186
  }
186
187
  if (current === id) {
187
- throw new Error(`Task parent cycle detected while linking "${id}" to "${control.parent}".`);
188
+ throw new RecoverableToolError(`Task parent cycle detected while linking "${id}" to "${control.parent}".`);
188
189
  }
189
190
  visited.add(current);
190
191
  const task = await readStoredTask(options.channelDir, current, true);
@@ -199,7 +200,7 @@ export async function validateTaskRelations(options, id, fields) {
199
200
  if (!current || visited.has(current))
200
201
  continue;
201
202
  if (current === id) {
202
- throw new Error(`Task dependency cycle detected while linking "${id}" to "${dependencyId}".`);
203
+ throw new RecoverableToolError(`Task dependency cycle detected while linking "${id}" to "${dependencyId}".`);
203
204
  }
204
205
  visited.add(current);
205
206
  const task = await readStoredTask(options.channelDir, current, true);