@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
@@ -1,4 +1,4 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
2
  import { isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { Agent } from "@earendil-works/pi-agent-core";
4
4
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
@@ -8,6 +8,7 @@ import { recallRelevantMemory } from "../memory/recall.js";
8
8
  import { formatModelReference } from "../models/utils.js";
9
9
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
10
10
  import { splitH1Sections } from "../shared/markdown-sections.js";
11
+ import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
11
12
  import { shellEscape } from "../shared/shell-escape.js";
12
13
  import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
13
14
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
@@ -47,6 +48,19 @@ const subagentSchema = Type.Object({
47
48
  description: '"worktree" runs in a dedicated git worktree.',
48
49
  })),
49
50
  worktreePath: Type.Optional(Type.String({ description: "Reuse an existing task-owned worktree; must be under channel tasks/worktrees/." })),
51
+ returns: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("artifact")], {
52
+ description: 'How the sub-agent should hand back its result. "text" (default) returns the response directly. "artifact" instructs it to write its primary output to a file and end with an ARTIFACT: <filename> marker. Either way the full output is always saved under the artifact directory, and a reply over the size budget is truncated with a pointer to that file.',
53
+ })),
54
+ thinkingLevel: Type.Optional(Type.Union([
55
+ Type.Literal("off"),
56
+ Type.Literal("minimal"),
57
+ Type.Literal("low"),
58
+ Type.Literal("medium"),
59
+ Type.Literal("high"),
60
+ Type.Literal("xhigh"),
61
+ ], {
62
+ description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for purpose=verify, "off" otherwise.',
63
+ })),
50
64
  });
51
65
  const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
52
66
  enabled: true,
@@ -60,6 +74,21 @@ const MAX_SESSION_SECTION_CHARS = 280;
60
74
  const MAX_SESSION_CONTEXT_CHARS = 1800;
61
75
  const MAX_RECALL_CONTEXT_CHARS = 2200;
62
76
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
77
+ /**
78
+ * Reply budget for what a sub-agent hands back to its parent (spec 032 D4), measured in the
79
+ * same prompt-unit currency as the system prompt budget (shared/prompt-units.ts). The full
80
+ * output always lands on disk under the artifact directory regardless of this budget — this
81
+ * only caps what gets echoed into the parent's context.
82
+ */
83
+ export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
84
+ const ARTIFACT_TRUNCATION_HEAD_RATIO = 1;
85
+ /**
86
+ * Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
87
+ * tool-free turn to summarize what it already found instead of having its work discarded.
88
+ * This is a hard stop on that convergence turn itself, independent of maxWallTimeSec.
89
+ */
90
+ const CONVERGENCE_WALL_CLOCK_MS = 60_000;
91
+ const CONVERGENCE_PROMPT = "Your turn/tool-call/wall-time budget for this task is exhausted. Based only on the work you have already completed, respond now with your conclusions: confirmed facts, what remains unfinished, and suggested next steps. Do not call any more tools.";
63
92
  class DirectoryExecutor {
64
93
  constructor(base, directory) {
65
94
  this.base = base;
@@ -78,6 +107,15 @@ function safeGitBranchSegment(value) {
78
107
  .replace(/^-+|-+$/g, "")
79
108
  .slice(0, 48) || "run");
80
109
  }
110
+ function getSubAgentArtifactsRoot(channelDir) {
111
+ return join(channelDir, "subagent-artifacts");
112
+ }
113
+ /** Every run gets its own artifact directory (spec 032 D4), independent of `returns` mode. */
114
+ async function prepareArtifactDir(channelDir, runId) {
115
+ const artifactDir = join(getSubAgentArtifactsRoot(channelDir), safeRunSegment(runId));
116
+ await mkdir(artifactDir, { recursive: true });
117
+ return artifactDir;
118
+ }
81
119
  async function prepareRunContext(runId, params, options) {
82
120
  const purpose = params.purpose ?? "work";
83
121
  const taskId = params.taskId?.trim() || undefined;
@@ -89,12 +127,13 @@ async function prepareRunContext(runId, params, options) {
89
127
  if (taskId && !ownedTask) {
90
128
  throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
91
129
  }
130
+ const artifactDir = await prepareArtifactDir(options.channelDir, runId);
92
131
  const isolation = params.isolation ?? "shared";
93
132
  if (isolation === "shared") {
94
133
  if (params.worktreePath)
95
134
  throw new Error("worktreePath requires isolation=worktree.");
96
135
  const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
97
- return { runId, purpose, taskId, isolation, workingDirectory };
136
+ return { runId, purpose, taskId, isolation, workingDirectory, artifactDir };
98
137
  }
99
138
  if (!taskId)
100
139
  throw new Error("isolation=worktree requires taskId so the worktree has a durable owner.");
@@ -122,6 +161,7 @@ async function prepareRunContext(runId, params, options) {
122
161
  workingDirectory: existing,
123
162
  worktreePath: existing,
124
163
  worktreeBranch: branchResult.code === 0 ? branchResult.stdout.trim() || undefined : undefined,
164
+ artifactDir,
125
165
  };
126
166
  await recordTaskWorktree(options.channelDir, taskId, context);
127
167
  return context;
@@ -149,6 +189,7 @@ async function prepareRunContext(runId, params, options) {
149
189
  workingDirectory: path,
150
190
  worktreePath: path,
151
191
  worktreeBranch: branch,
192
+ artifactDir,
152
193
  };
153
194
  try {
154
195
  await recordTaskWorktree(options.channelDir, taskId, context);
@@ -214,6 +255,42 @@ function buildStoppedText(config, reason, finalText) {
214
255
  }
215
256
  return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
216
257
  }
258
+ const ARTIFACT_MARKER_PATTERN = /(?:^|\n)ARTIFACT:\s*(\S+)\s*$/i;
259
+ function parseArtifactMarker(output) {
260
+ return ARTIFACT_MARKER_PATTERN.exec(output.trim())?.[1];
261
+ }
262
+ /**
263
+ * Spec 032 D4: the full text always lands on disk, independent of `returns` mode and of
264
+ * whether it fits the reply budget. What comes back to the parent is capped at
265
+ * MAX_SUBAGENT_RESULT_UNITS; a reply over budget is truncated with a pointer to the file
266
+ * a chatty sub-agent can no longer blow out the parent's context.
267
+ */
268
+ async function finalizeSubAgentOutput(runContext, finalText, returns) {
269
+ const trimmed = finalText.trim();
270
+ const outputPath = join(runContext.artifactDir, "output.md");
271
+ if (trimmed) {
272
+ await writeFile(outputPath, finalText, "utf-8");
273
+ }
274
+ let artifactPath;
275
+ if (returns === "artifact" && trimmed) {
276
+ const filename = parseArtifactMarker(trimmed);
277
+ if (filename) {
278
+ const candidate = resolve(runContext.artifactDir, filename);
279
+ const rel = relative(runContext.artifactDir, candidate);
280
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) {
281
+ artifactPath = candidate;
282
+ }
283
+ }
284
+ }
285
+ if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
286
+ return { artifactPath, replyText: finalText, truncated: false };
287
+ }
288
+ const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
289
+ headRatio: ARTIFACT_TRUNCATION_HEAD_RATIO,
290
+ marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
291
+ });
292
+ return { artifactPath, replyText: clipped.text, truncated: true };
293
+ }
217
294
  /**
218
295
  * Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
219
296
  * context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
@@ -259,7 +336,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
259
336
  bashDefaultTimeoutSeconds: bashTimeoutSec,
260
337
  }, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
261
338
  }
262
- function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
339
+ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
263
340
  const taskText = task.trim();
264
341
  const lines = [
265
342
  `Runtime context:`,
@@ -268,6 +345,7 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
268
345
  `- Channel directory: ${runtimeContext.workspaceDir}/${runtimeContext.channelId}`,
269
346
  `- Working directory: ${runContext.workingDirectory}`,
270
347
  `- Filesystem isolation: ${runContext.isolation === "worktree" ? "dedicated git worktree" : "shared with parent"}`,
348
+ `- Artifact directory: ${runContext.artifactDir}`,
271
349
  `- Your configured role: ${config.name}`,
272
350
  ];
273
351
  for (const block of contextBlocks) {
@@ -281,6 +359,9 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
281
359
  const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
282
360
  lines.push("", "Verification protocol:", `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`, "- You are the checker, not the maker. Do not edit files or fix failures; report them.", "- Run deterministic checks when available and distinguish observed evidence from assumptions.", "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.");
283
361
  }
362
+ else if (returns === "artifact") {
363
+ lines.push("", "Output protocol:", `- Write your primary output as a file under the artifact directory above.`, "- End the response with exactly one final line: ARTIFACT: <filename>");
364
+ }
284
365
  return lines.join("\n");
285
366
  }
286
367
  function buildSessionContextBlock(sessionMarkdown) {
@@ -362,7 +443,7 @@ function filterToolsByName(allTools, names) {
362
443
  const allowed = new Set(names);
363
444
  return allTools.filter((tool) => allowed.has(tool.name));
364
445
  }
365
- function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict) {
446
+ function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict, extras) {
366
447
  return {
367
448
  kind: "subagent",
368
449
  agent: config.name,
@@ -385,6 +466,9 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
385
466
  worktreePath: runContext.worktreePath,
386
467
  worktreeBranch: runContext.worktreeBranch,
387
468
  verificationVerdict,
469
+ artifactDir: runContext.artifactDir,
470
+ artifactPath: extras?.artifactPath,
471
+ resultTruncated: extras?.resultTruncated ?? false,
388
472
  };
389
473
  }
390
474
  function linkAbortSignals(parentSignal, childController) {
@@ -403,7 +487,7 @@ export function createSubAgentTool(options) {
403
487
  return {
404
488
  name: "subagent",
405
489
  label: "subagent",
406
- description: "Delegate a task to a sub-agent with an isolated context. You may use a predefined sub-agent from workspaceDir/sub-agents/ or define a temporary inline sub-agent by providing systemPrompt/tools/model parameters. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
490
+ description: "Delegate a task to a sub-agent with an isolated context. Default path: pass an inline systemPrompt (plus optional tools/model) to define a temporary sub-agent — no predefined agent is required. You may instead name a predefined sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
407
491
  parameters: subagentSchema,
408
492
  execute: async (_toolCallId, params, signal, onUpdate) => {
409
493
  const availableModels = options.getAvailableModels();
@@ -417,11 +501,12 @@ export function createSubAgentTool(options) {
417
501
  if (taskLengthError) {
418
502
  throw new Error(taskLengthError);
419
503
  }
420
- const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params);
504
+ const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params, options.getSubAgentModelReference?.() ?? undefined);
421
505
  if (!invocation.config) {
422
506
  throw new Error(`${invocation.error}\n\nAvailable predefined sub-agents:\n${formatSubAgentList(discovery.agents)}`);
423
507
  }
424
508
  const config = invocation.config;
509
+ const returns = params.returns ?? "text";
425
510
  const runContext = await prepareRunContext(_toolCallId, params, options);
426
511
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
427
512
  const apiKey = await options.resolveApiKey(config.model);
@@ -430,6 +515,8 @@ export function createSubAgentTool(options) {
430
515
  let assistantTurns = 0;
431
516
  let toolCalls = 0;
432
517
  let failureReason;
518
+ /** Set alongside failureReason only for the three self-inflicted budget aborts, never for a parent-driven stop. */
519
+ let budgetExceeded = false;
433
520
  let lastUpdateText = "";
434
521
  const emitUpdate = (text) => {
435
522
  const nextText = text.trim();
@@ -454,7 +541,7 @@ export function createSubAgentTool(options) {
454
541
  initialState: {
455
542
  systemPrompt: config.systemPrompt,
456
543
  model: config.model,
457
- thinkingLevel: "off",
544
+ thinkingLevel: config.thinkingLevel,
458
545
  tools: filterToolsByName(availableTools, config.tools),
459
546
  },
460
547
  convertToLlm,
@@ -464,6 +551,7 @@ export function createSubAgentTool(options) {
464
551
  const unlinkAbortSignals = linkAbortSignals(signal, childController);
465
552
  const wallClockTimer = setTimeout(() => {
466
553
  failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
554
+ budgetExceeded = true;
467
555
  worker.abort();
468
556
  }, config.maxWallTimeSec * 1000);
469
557
  const unsubscribe = worker.subscribe((event) => {
@@ -487,6 +575,7 @@ export function createSubAgentTool(options) {
487
575
  emitUpdate(formatStatus(config.name, label));
488
576
  if (toolCalls > config.maxToolCalls) {
489
577
  failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
578
+ budgetExceeded = true;
490
579
  emitUpdate(formatStatus(config.name, "tool budget reached"));
491
580
  worker.abort();
492
581
  }
@@ -496,6 +585,7 @@ export function createSubAgentTool(options) {
496
585
  event.toolResults.length > 0 &&
497
586
  assistantTurns >= config.maxTurns) {
498
587
  failureReason = `Turn budget exceeded (${config.maxTurns})`;
588
+ budgetExceeded = true;
499
589
  emitUpdate(formatStatus(config.name, "turn budget reached"));
500
590
  worker.abort();
501
591
  }
@@ -509,12 +599,43 @@ export function createSubAgentTool(options) {
509
599
  childController.signal.addEventListener("abort", abortWorker, { once: true });
510
600
  try {
511
601
  const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
512
- await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
602
+ await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
513
603
  await worker.waitForIdle();
514
604
  }
515
605
  finally {
516
606
  childController.signal.removeEventListener("abort", abortWorker);
517
607
  }
608
+ // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
609
+ // conclusion instead of discarding the work outright. A parent-driven /stop
610
+ // (childController already aborted) skips this — the user asked to stop now.
611
+ if (budgetExceeded && !childController.signal.aborted) {
612
+ clearTimeout(wallClockTimer);
613
+ emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
614
+ const preConvergenceMessageCount = worker.state.messages.length;
615
+ worker.state.tools = [];
616
+ let convergenceTimedOut = false;
617
+ const convergenceTimer = setTimeout(() => {
618
+ convergenceTimedOut = true;
619
+ worker.abort();
620
+ }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
621
+ childController.signal.addEventListener("abort", abortWorker, { once: true });
622
+ try {
623
+ await worker.prompt(CONVERGENCE_PROMPT);
624
+ await worker.waitForIdle();
625
+ }
626
+ catch {
627
+ // Best effort: fall through to whatever worker.state.messages holds.
628
+ }
629
+ finally {
630
+ childController.signal.removeEventListener("abort", abortWorker);
631
+ clearTimeout(convergenceTimer);
632
+ }
633
+ if (convergenceTimedOut) {
634
+ // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
635
+ // convergence turn and fall back to whatever came before it.
636
+ worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
637
+ }
638
+ }
518
639
  }
519
640
  finally {
520
641
  unsubscribe();
@@ -575,14 +696,21 @@ export function createSubAgentTool(options) {
575
696
  throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
576
697
  }
577
698
  emitUpdate(formatStatus(config.name, "stopped"));
699
+ const finalized = await finalizeSubAgentOutput(runContext, finalText, returns);
578
700
  return {
579
- content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalText) }],
580
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict),
701
+ content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) }],
702
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
581
703
  };
582
704
  }
705
+ const finalized = await finalizeSubAgentOutput(runContext, finalText, returns);
583
706
  return {
584
- content: [{ type: "text", text: finalText || `(Sub-agent ${config.name} completed with no text output)` }],
585
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict),
707
+ content: [
708
+ {
709
+ type: "text",
710
+ text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
711
+ },
712
+ ],
713
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
586
714
  };
587
715
  },
588
716
  };
@@ -1,3 +1,4 @@
1
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
1
2
  /**
2
3
  * The task status model and its single transition table (spec 029, D3).
3
4
  *
@@ -68,14 +69,14 @@ export function isSettableTaskStatus(value) {
68
69
  export function resolveTaskTransition(action, id, from, requestedStatus) {
69
70
  const rule = TRANSITIONS[action];
70
71
  if (!rule.from.includes(from)) {
71
- throw new Error(`Task ${id} is ${from}; action ${action} allows only from: ${rule.from.join(", ") || "(none)"}.`);
72
+ throw new RecoverableToolError(`Task ${id} is ${from}; action ${action} allows only from: ${rule.from.join(", ") || "(none)"}.`);
72
73
  }
73
74
  if (rule.to !== "caller")
74
75
  return rule.to;
75
76
  if (requestedStatus === undefined)
76
77
  return from;
77
78
  if (!isSettableTaskStatus(requestedStatus)) {
78
- throw new Error(`Invalid status "${requestedStatus}". Use one of ${SETTABLE_TASK_STATUSES.join(", ")}.`);
79
+ throw new RecoverableToolError(`Invalid status "${requestedStatus}". Use one of ${SETTABLE_TASK_STATUSES.join(", ")}.`);
79
80
  }
80
81
  return requestedStatus;
81
82
  }
@@ -15,6 +15,8 @@ declare const bashSchema: Type.TObject<{
15
15
  command: Type.TString;
16
16
  timeout: Type.TOptional<Type.TInteger>;
17
17
  async: Type.TOptional<Type.TBoolean>;
18
+ notify: Type.TOptional<Type.TBoolean>;
19
+ taskId: Type.TOptional<Type.TString>;
18
20
  }>;
19
21
  export interface BashToolOptions {
20
22
  defaultTimeoutSeconds?: number;
@@ -30,7 +30,13 @@ const bashSchema = Type.Object({
30
30
  description: `Timeout in seconds. Defaults to ${DEFAULT_BASH_TIMEOUT_SECONDS}s; pass a larger value for long-running commands.`,
31
31
  })),
32
32
  async: Type.Optional(Type.Boolean({
33
- description: "Run in the background and return immediately with a job id instead of blocking. Use for long commands so the channel stays responsive; check it later with the job tool or a scheduled event_manage check-in.",
33
+ description: "Run in the background and return immediately with a job id instead of blocking. Use for long commands so the channel stays responsive; you are woken automatically when the job finishes.",
34
+ })),
35
+ notify: Type.Optional(Type.Boolean({
36
+ description: "For async jobs: wake this channel when the job finishes (default true). Set false only for fire-and-forget work whose result you will never need.",
37
+ })),
38
+ taskId: Type.Optional(Type.String({
39
+ description: "For async jobs: the task this job advances, so the completion wake lands in that context.",
34
40
  })),
35
41
  });
36
42
  /**
@@ -92,7 +98,7 @@ export function createBashTool(executor, options = {}) {
92
98
  label: "bash",
93
99
  description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
94
100
  parameters: bashSchema,
95
- execute: async (_toolCallId, { label, command, timeout, async: runAsync, }, signal) => {
101
+ execute: async (_toolCallId, { label, command, timeout, async: runAsync, notify, taskId, }, signal) => {
96
102
  if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
97
103
  const guardResult = guardCommand(command, securityConfig.commandGuard);
98
104
  if (!guardResult.allowed) {
@@ -129,14 +135,21 @@ export function createBashTool(executor, options = {}) {
129
135
  if (!options.jobManager) {
130
136
  throw new Error("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
131
137
  }
132
- const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, signal);
138
+ const willNotify = notify ?? true;
139
+ const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, {
140
+ signal,
141
+ notify: willNotify,
142
+ ...(taskId ? { taskId } : {}),
143
+ });
133
144
  return {
134
145
  content: [
135
146
  {
136
147
  type: "text",
137
148
  text: `Background job ${job.id} started: ${label}\n` +
138
- "It runs off-turn; you can end your turn now. Check it with the job tool (op:poll/list), " +
139
- "or schedule an event_manage check-in to be woken when it is likely done.",
149
+ (willNotify
150
+ ? "It runs off-turn; end your turn now. You will be woken automatically when it finishes, " +
151
+ "with its exit code and output — do not schedule a check-in for it."
152
+ : "It runs off-turn and will NOT wake you when it finishes; check it with the job tool (op:poll/list)."),
140
153
  },
141
154
  ],
142
155
  details: { kind: "bash", async: { state: "running", jobId: job.id } },
@@ -1,28 +1,14 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- import { Cron } from "croner";
5
4
  import { Type } from "typebox";
6
5
  import { resolveEventPath } from "../runtime/event-commands.js";
6
+ import { EventValidationError, MAX_EVENT_FILES, validateScheduledEvent } from "../runtime/event-validation.js";
7
7
  import { parseScheduledEventContent } from "../runtime/events.js";
8
- import { guardCommand } from "../security/command-guard.js";
9
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
9
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
11
11
  import { isRecord } from "../shared/type-guards.js";
12
- /** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
13
- const MIN_ONE_SHOT_LEAD_MS = 2 * 60 * 1000;
14
- /** periodic events without a preAction gate may fire no more often than this. */
15
- const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
16
- /**
17
- * periodic events WITH a preAction gate may fire this often: the sensor is the token guard
18
- * (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
19
- * safe and is exactly the design-endorsed posture for completion-driven checks. A hard
20
- * sub-floor still applies so a bogus
21
- * always-pass preAction cannot drive an arbitrarily hot loop.
22
- */
23
- const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
24
- /** sanity cap on total event files to keep the directory (and the scheduler) from being flooded. */
25
- const MAX_EVENT_FILES = 50;
26
12
  const eventManageSchema = Type.Object({
27
13
  label: Type.String({ description: "Brief description of the scheduling change (shown to the user)" }),
28
14
  action: Type.Union([Type.Literal("create"), Type.Literal("update"), Type.Literal("delete")], {
@@ -39,53 +25,17 @@ function parseAction(action) {
39
25
  if (action === "create" || action === "update" || action === "delete") {
40
26
  return action;
41
27
  }
42
- throw new Error('Unsupported event action. Use "create", "update", or "delete".');
43
- }
44
- function validateOneShot(event) {
45
- const atTime = new Date(event.at).getTime();
46
- if (!Number.isFinite(atTime)) {
47
- throw new Error(`one-shot 'at' is not a valid date: ${event.at}`);
48
- }
49
- if (atTime < Date.now() + MIN_ONE_SHOT_LEAD_MS) {
50
- throw new Error("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
51
- }
52
- }
53
- function validatePeriodic(event) {
54
- let runs;
55
- try {
56
- const cron = new Cron(event.schedule);
57
- runs = cron.nextRuns(3);
58
- cron.stop();
59
- }
60
- catch (error) {
61
- const message = errorMessage(error);
62
- throw new Error(`Invalid cron schedule "${event.schedule}": ${message}`);
63
- }
64
- // A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
65
- // without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
66
- const floorMs = event.preAction ? MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS : MIN_PERIODIC_INTERVAL_MS;
67
- const floorMinutes = Math.round(floorMs / 60000);
68
- // Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
69
- for (let i = 1; i < runs.length; i++) {
70
- if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
71
- throw new Error(`periodic events must fire no more often than every ${floorMinutes} minutes` +
72
- `${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
73
- }
74
- }
75
- }
76
- function validatePreAction(event, commandGuardConfig) {
77
- if (!event.preAction)
78
- return;
79
- const result = guardCommand(event.preAction.command, commandGuardConfig);
80
- if (!result.allowed) {
81
- throw new Error(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`);
82
- }
28
+ throw new RecoverableToolError('Unsupported event action. Use "create", "update", or "delete".');
83
29
  }
84
30
  /**
85
31
  * Validate an agent-supplied event definition and return the normalized, typed event.
86
32
  * Rejects immediate events, near-term one-shots, high-frequency periodics, guard-blocked
87
33
  * preActions, and cross-channel channelIds. The returned event is what gets persisted, so
88
34
  * the file on disk is exactly what was validated.
35
+ *
36
+ * The scheduling rules themselves live in `runtime/event-validation.ts` and are re-applied by
37
+ * the watcher (spec 031, D4); this layer only adds tool-specific framing (channel ownership,
38
+ * and turning validation failures into recoverable tool errors the model can retry).
89
39
  */
90
40
  function validateDefinition(rawDefinition, name, options) {
91
41
  let data;
@@ -94,30 +44,32 @@ function validateDefinition(rawDefinition, name, options) {
94
44
  }
95
45
  catch (error) {
96
46
  const message = errorMessage(error);
97
- throw new Error(`definition is not valid JSON: ${message}`);
47
+ throw new RecoverableToolError(`definition is not valid JSON: ${message}`);
98
48
  }
99
49
  if (!isRecord(data)) {
100
- throw new Error("definition must be a JSON object.");
50
+ throw new RecoverableToolError("definition must be a JSON object.");
101
51
  }
102
52
  const providedChannelId = data.channelId;
103
53
  if (providedChannelId === undefined || providedChannelId === null || providedChannelId === "") {
104
54
  data.channelId = options.channelId;
105
55
  }
106
56
  else if (providedChannelId !== options.channelId) {
107
- throw new Error(`definition channelId "${String(providedChannelId)}" does not match the current channel "${options.channelId}".`);
57
+ throw new RecoverableToolError(`definition channelId "${String(providedChannelId)}" does not match the current channel "${options.channelId}".`);
108
58
  }
109
- const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
110
- if (event.type === "immediate") {
111
- throw new Error("event_manage cannot create or update immediate events (self-triggering loop guard); " +
59
+ if (data.type === "immediate") {
60
+ throw new RecoverableToolError("event_manage cannot create or update immediate events (self-triggering loop guard); " +
112
61
  "do the work in the current turn instead.");
113
62
  }
114
- if (event.type === "one-shot") {
115
- validateOneShot(event);
63
+ const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
64
+ try {
65
+ validateScheduledEvent(event, { commandGuardConfig: options.commandGuardConfig });
116
66
  }
117
- if (event.type === "periodic") {
118
- validatePeriodic(event);
67
+ catch (error) {
68
+ if (error instanceof EventValidationError && error.recoverable) {
69
+ throw new RecoverableToolError(error.message);
70
+ }
71
+ throw error;
119
72
  }
120
- validatePreAction(event, options.commandGuardConfig);
121
73
  return event;
122
74
  }
123
75
  async function readOwnedEvent(eventPath, name, options) {
@@ -130,7 +82,7 @@ async function readOwnedEvent(eventPath, name, options) {
130
82
  throw new Error(`Existing event "${name}" could not be parsed (${message}); use /events to manage it directly.`);
131
83
  }
132
84
  if (existing.channelId !== options.channelId) {
133
- throw new Error(`Event "${name}" belongs to another channel and cannot be modified from here.`);
85
+ throw new RecoverableToolError(`Event "${name}" belongs to another channel and cannot be modified from here.`);
134
86
  }
135
87
  return existing;
136
88
  }
@@ -164,24 +116,23 @@ export async function manageEvent(options, request) {
164
116
  };
165
117
  }
166
118
  if (!request.definition || request.definition.trim().length === 0) {
167
- throw new Error(`${request.action} requires a non-empty definition.`);
119
+ throw new RecoverableToolError(`${request.action} requires a non-empty definition.`);
168
120
  }
169
121
  if (request.action === "create") {
170
122
  if (existsSync(eventPath)) {
171
- throw new Error(`Event "${eventName}" already exists; use action "update" to replace it.`);
123
+ throw new RecoverableToolError(`Event "${eventName}" already exists; use action "update" to replace it.`);
172
124
  }
173
125
  if ((await countEventFiles(eventsDir)) >= MAX_EVENT_FILES) {
174
- throw new Error(`Too many event files (>= ${MAX_EVENT_FILES}) in workspace/events; clean up stale events before creating more.`);
126
+ throw new RecoverableToolError(`Too many event files (>= ${MAX_EVENT_FILES}) in workspace/events; clean up stale events before creating more.`);
175
127
  }
176
128
  }
177
129
  else {
178
130
  if (!existsSync(eventPath)) {
179
- throw new Error(`Event "${eventName}" does not exist; use action "create" to add it.`);
180
- }
181
- const existing = await readOwnedEvent(eventPath, eventName, options);
182
- if (existing.type === "immediate") {
183
- throw new Error(`Event "${eventName}" is an immediate event and cannot be updated via event_manage.`);
131
+ throw new RecoverableToolError(`Event "${eventName}" does not exist; use action "create" to add it.`);
184
132
  }
133
+ // Ownership check only: an existing file that no longer parses (e.g. a legacy immediate
134
+ // event) is reported by readOwnedEvent and pointed at /events.
135
+ await readOwnedEvent(eventPath, eventName, options);
185
136
  }
186
137
  const event = validateDefinition(request.definition, eventName, options);
187
138
  // Persist the canonical form: a tolerated legacy `timezone` is dropped so freshly written
@@ -2,6 +2,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { Executor } from "../executor.js";
4
4
  import type { MemoryCandidateStore } from "../memory/candidates.js";
5
+ import type { MediaSender } from "../runtime/channel-context.js";
5
6
  import type { SecurityConfig } from "../security/types.js";
6
7
  import type { PipiclawMemoryRecallSettings, PipiclawSessionSearchSettings } from "../settings.js";
7
8
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
@@ -16,9 +17,12 @@ export interface CreatePipiclawToolsOptions {
16
17
  channelId: string;
17
18
  getSubAgentDiscovery: () => SubAgentDiscoveryResult;
18
19
  getMemoryRecallSettings: () => PipiclawMemoryRecallSettings;
20
+ getSubAgentModelReference?: () => string | null;
19
21
  getSessionSearchSettings: () => PipiclawSessionSearchSettings;
20
22
  memoryCandidateStore: MemoryCandidateStore;
21
23
  securityConfig?: SecurityConfig;
22
24
  toolsConfig?: PipiclawToolsConfig;
25
+ /** Transport-provided attachment port; when present, enables the `send_media` tool. */
26
+ mediaSender?: MediaSender;
23
27
  }
24
28
  export declare function createPipiclawTools(options: CreatePipiclawToolsOptions): AgentTool<any>[];
@@ -4,6 +4,7 @@ import { loadSecurityConfig } from "../security/config.js";
4
4
  import { createSubAgentTool } from "../subagents/tool.js";
5
5
  import { loadToolsConfig } from "./config.js";
6
6
  import { buildToolSet } from "./registry.js";
7
+ import { withToolDetails } from "./tool-details.js";
7
8
  export function createPipiclawTools(options) {
8
9
  const securityConfig = options.securityConfig ?? loadSecurityConfig(APP_HOME_DIR);
9
10
  const toolsConfig = options.toolsConfig ?? loadToolsConfig(APP_HOME_DIR);
@@ -31,10 +32,13 @@ export function createPipiclawTools(options) {
31
32
  resolveApiKey: options.resolveApiKey,
32
33
  getSessionSearchSettings: options.getSessionSearchSettings,
33
34
  memoryCandidateStore: options.memoryCandidateStore,
35
+ mediaSender: options.mediaSender,
34
36
  });
35
37
  return [
36
38
  ...leafTools,
37
- createSubAgentTool({
39
+ // Bound to the same `details` contract as the registry's tools; it is registered here
40
+ // rather than in TOOL_REGISTRY only to avoid a registry ↔ subagents/tool import cycle.
41
+ withToolDetails(createSubAgentTool({
38
42
  executor: options.executor,
39
43
  getCurrentModel: options.getCurrentModel,
40
44
  getAvailableModels: options.getAvailableModels,
@@ -43,6 +47,7 @@ export function createPipiclawTools(options) {
43
47
  channelDir: options.channelDir,
44
48
  getSubAgentDiscovery: options.getSubAgentDiscovery,
45
49
  getMemoryRecallSettings: options.getMemoryRecallSettings,
50
+ getSubAgentModelReference: options.getSubAgentModelReference,
46
51
  memoryCandidateStore: options.memoryCandidateStore,
47
52
  securityConfig,
48
53
  webConfig: toolsConfig.tools.web,
@@ -51,6 +56,6 @@ export function createPipiclawTools(options) {
51
56
  workspaceDir: options.workspaceDir,
52
57
  channelId: options.channelId,
53
58
  },
54
- }),
59
+ }), "subagent"),
55
60
  ];
56
61
  }