@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.2-beta.1

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 (189) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -1
  2. package/dist/agent/channel-runner.js +51 -18
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/effect-ledger.js +9 -2
  7. package/dist/agent/job-manager.d.ts +4 -0
  8. package/dist/agent/job-manager.js +17 -2
  9. package/dist/agent/prompt/manifest.d.ts +1 -1
  10. package/dist/agent/prompt/manifest.js +6 -7
  11. package/dist/agent/prompt/sections.js +9 -5
  12. package/dist/agent/reply-limits.d.ts +16 -0
  13. package/dist/agent/reply-limits.js +17 -0
  14. package/dist/agent/session-events.d.ts +2 -0
  15. package/dist/agent/session-events.js +29 -14
  16. package/dist/agent/status-render.js +12 -12
  17. package/dist/agent/turn-recovery.js +2 -2
  18. package/dist/agent/type-guards.js +5 -1
  19. package/dist/agent/workspace-resources.d.ts +2 -2
  20. package/dist/agent/workspace-resources.js +41 -3
  21. package/dist/executor.d.ts +28 -0
  22. package/dist/executor.js +120 -18
  23. package/dist/file-store.d.ts +96 -0
  24. package/dist/file-store.js +189 -0
  25. package/dist/main.js +3 -4
  26. package/dist/memory/commands.js +79 -38
  27. package/dist/memory/consolidation.d.ts +5 -1
  28. package/dist/memory/consolidation.js +35 -38
  29. package/dist/memory/extraction.d.ts +8 -1
  30. package/dist/memory/extraction.js +47 -4
  31. package/dist/memory/files.d.ts +0 -1
  32. package/dist/memory/files.js +31 -12
  33. package/dist/memory/lifecycle.js +9 -2
  34. package/dist/memory/maintenance-jobs.js +16 -38
  35. package/dist/memory/maintenance-state.js +2 -1
  36. package/dist/memory/metadata.d.ts +3 -0
  37. package/dist/memory/metadata.js +7 -0
  38. package/dist/memory/recall.d.ts +19 -0
  39. package/dist/memory/recall.js +116 -24
  40. package/dist/memory/review-log.d.ts +0 -2
  41. package/dist/memory/review-log.js +0 -0
  42. package/dist/memory/session-corpus.js +5 -0
  43. package/dist/memory/session-search.js +15 -22
  44. package/dist/memory/sidecar-worker.js +4 -0
  45. package/dist/memory/source-window.d.ts +0 -1
  46. package/dist/memory/source-window.js +0 -5
  47. package/dist/memory/transcript.d.ts +10 -0
  48. package/dist/memory/transcript.js +39 -0
  49. package/dist/playbooks/agent-delegation.md +34 -25
  50. package/dist/playbooks/background-jobs.md +8 -16
  51. package/dist/playbooks/catalog.d.ts +1 -1
  52. package/dist/playbooks/catalog.js +1 -1
  53. package/dist/playbooks/event-scheduling.md +15 -15
  54. package/dist/playbooks/memory-and-learning.md +30 -23
  55. package/dist/playbooks/outbound-media.md +15 -8
  56. package/dist/playbooks/runtime-orientation.md +40 -37
  57. package/dist/playbooks/task-driving.md +36 -38
  58. package/dist/playbooks/task-planning.md +21 -21
  59. package/dist/runtime/app-home.d.ts +6 -0
  60. package/dist/runtime/app-home.js +16 -7
  61. package/dist/runtime/bootstrap.js +54 -13
  62. package/dist/runtime/channel-context.d.ts +2 -1
  63. package/dist/runtime/delivery.js +3 -3
  64. package/dist/runtime/dingtalk.d.ts +9 -1
  65. package/dist/runtime/dingtalk.js +30 -15
  66. package/dist/runtime/durable-dispatch.d.ts +26 -1
  67. package/dist/runtime/durable-dispatch.js +51 -5
  68. package/dist/runtime/event-commands.d.ts +15 -0
  69. package/dist/runtime/event-commands.js +55 -56
  70. package/dist/runtime/events.d.ts +4 -2
  71. package/dist/runtime/events.js +15 -20
  72. package/dist/runtime/project-commands.d.ts +16 -0
  73. package/dist/runtime/project-commands.js +13 -17
  74. package/dist/runtime/subagent-commands.d.ts +20 -0
  75. package/dist/runtime/subagent-commands.js +61 -58
  76. package/dist/runtime/task-commands.d.ts +37 -0
  77. package/dist/runtime/task-commands.js +108 -66
  78. package/dist/runtime/task-driver.js +2 -2
  79. package/dist/security/block-message.d.ts +11 -0
  80. package/dist/security/block-message.js +12 -0
  81. package/dist/security/path-guard-check.d.ts +13 -0
  82. package/dist/security/path-guard-check.js +39 -0
  83. package/dist/security/path-guard.js +61 -12
  84. package/dist/security/types.d.ts +9 -0
  85. package/dist/settings.js +3 -2
  86. package/dist/shared/atomic-file.d.ts +17 -1
  87. package/dist/shared/atomic-file.js +50 -3
  88. package/dist/shared/duration.d.ts +2 -0
  89. package/dist/shared/duration.js +7 -0
  90. package/dist/shared/safe-id.d.ts +19 -0
  91. package/dist/shared/safe-id.js +24 -0
  92. package/dist/shared/text-utils.d.ts +1 -1
  93. package/dist/shared/text-utils.js +3 -8
  94. package/dist/shared/type-guards.d.ts +2 -0
  95. package/dist/shared/type-guards.js +4 -0
  96. package/dist/subagents/discovery.d.ts +51 -19
  97. package/dist/subagents/discovery.js +93 -98
  98. package/dist/subagents/external/claude-code.js +40 -2
  99. package/dist/subagents/external/harness.d.ts +1 -1
  100. package/dist/subagents/external/run.js +61 -8
  101. package/dist/subagents/format.d.ts +3 -2
  102. package/dist/subagents/format.js +3 -7
  103. package/dist/subagents/runs.d.ts +1 -1
  104. package/dist/subagents/runs.js +10 -9
  105. package/dist/subagents/tool.d.ts +31 -18
  106. package/dist/subagents/tool.js +592 -562
  107. package/dist/subagents/workspace-lease.js +1 -1
  108. package/dist/tasks/control.js +7 -9
  109. package/dist/tasks/ledger.d.ts +2 -2
  110. package/dist/tasks/ledger.js +3 -7
  111. package/dist/tasks/transitions.d.ts +5 -1
  112. package/dist/tasks/transitions.js +2 -2
  113. package/dist/tasks/verification.d.ts +7 -5
  114. package/dist/tools/bash.d.ts +1 -2
  115. package/dist/tools/bash.js +99 -76
  116. package/dist/tools/config.d.ts +6 -1
  117. package/dist/tools/config.js +9 -0
  118. package/dist/tools/edit.d.ts +2 -3
  119. package/dist/tools/edit.js +276 -75
  120. package/dist/tools/event-manage.d.ts +13 -7
  121. package/dist/tools/event-manage.js +52 -14
  122. package/dist/tools/glob-match.d.ts +11 -0
  123. package/dist/tools/glob-match.js +75 -0
  124. package/dist/tools/glob.d.ts +15 -0
  125. package/dist/tools/glob.js +113 -0
  126. package/dist/tools/grep.d.ts +0 -1
  127. package/dist/tools/grep.js +60 -44
  128. package/dist/tools/ignore-dirs.d.ts +6 -0
  129. package/dist/tools/ignore-dirs.js +15 -0
  130. package/dist/tools/index.d.ts +3 -0
  131. package/dist/tools/index.js +54 -40
  132. package/dist/tools/job.d.ts +0 -1
  133. package/dist/tools/job.js +3 -9
  134. package/dist/tools/line-index.d.ts +16 -0
  135. package/dist/tools/line-index.js +76 -0
  136. package/dist/tools/memory-manage.d.ts +21 -8
  137. package/dist/tools/memory-manage.js +114 -103
  138. package/dist/tools/presentation.d.ts +2 -0
  139. package/dist/tools/presentation.js +109 -0
  140. package/dist/tools/read.d.ts +2 -2
  141. package/dist/tools/read.js +100 -120
  142. package/dist/tools/registry.d.ts +4 -1
  143. package/dist/tools/registry.js +89 -22
  144. package/dist/tools/send-media.d.ts +6 -6
  145. package/dist/tools/send-media.js +21 -43
  146. package/dist/tools/session-search.d.ts +0 -1
  147. package/dist/tools/session-search.js +0 -1
  148. package/dist/tools/skill-security.d.ts +0 -2
  149. package/dist/tools/skill-security.js +1 -25
  150. package/dist/tools/skill.d.ts +31 -0
  151. package/dist/tools/skill.js +153 -0
  152. package/dist/tools/subagent-manage.d.ts +6 -5
  153. package/dist/tools/subagent-manage.js +47 -47
  154. package/dist/tools/task-manage/create.d.ts +2 -2
  155. package/dist/tools/task-manage/create.js +1 -3
  156. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  157. package/dist/tools/task-manage/lifecycle.js +49 -56
  158. package/dist/tools/task-manage/schema.d.ts +27 -15
  159. package/dist/tools/task-manage/schema.js +58 -74
  160. package/dist/tools/task-manage/shared.d.ts +11 -6
  161. package/dist/tools/task-manage/shared.js +30 -21
  162. package/dist/tools/task-manage/types.d.ts +14 -15
  163. package/dist/tools/task-manage/verification.d.ts +4 -4
  164. package/dist/tools/task-manage/verification.js +6 -8
  165. package/dist/tools/task-manage.d.ts +8 -11
  166. package/dist/tools/task-manage.js +63 -50
  167. package/dist/tools/tool-details.d.ts +17 -1
  168. package/dist/tools/tool-details.js +24 -0
  169. package/dist/tools/truncate.d.ts +8 -0
  170. package/dist/tools/truncate.js +8 -0
  171. package/dist/tools/web-fetch.d.ts +0 -1
  172. package/dist/tools/web-fetch.js +9 -2
  173. package/dist/tools/web-search.d.ts +0 -1
  174. package/dist/tools/web-search.js +0 -1
  175. package/dist/tools/write-content.d.ts +3 -3
  176. package/dist/tools/write-content.js +12 -41
  177. package/dist/tools/write.d.ts +2 -3
  178. package/dist/tools/write.js +3 -4
  179. package/dist/tui/app.js +1 -1
  180. package/dist/tui/commands.d.ts +1 -1
  181. package/dist/tui/commands.js +1 -1
  182. package/dist/tui/turn-controller.d.ts +1 -1
  183. package/dist/tui/turn-controller.js +14 -4
  184. package/dist/usage/ledger.js +7 -4
  185. package/dist/usage/render.js +10 -8
  186. package/examples/sub-agents/README.md +2 -0
  187. package/package.json +3 -2
  188. package/dist/tools/skill-manage.d.ts +0 -41
  189. package/dist/tools/skill-manage.js +0 -231
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { isRecord } from "../../shared/type-guards.js";
2
3
  import { detectExistingFlags, expandPlaceholders, formatDroppedPlaceholderWarnings, } from "./harness.js";
3
4
  /**
4
5
  * `claude-code` harness (spec 040, D3/D4). Same one-prompt-one-process model as codex-cli; the
@@ -31,7 +32,10 @@ function toClaudeEffort(level) {
31
32
  }
32
33
  export const claudeCodeHarness = {
33
34
  id: "claude-code",
34
- parserVersion: 1,
35
+ // 2: parseOutcome now falls back to the last streamed `assistant` message's text/usage when a
36
+ // `result` event never arrives (timeout/cancel kill the process before claude-code emits one) —
37
+ // `op=show` can use this to distinguish "adapter is stale" from "the agent itself crashed".
38
+ parserVersion: 2,
35
39
  buildInvocation(input) {
36
40
  if (input.argv.length === 0) {
37
41
  throw new Error("claude-code: command produced no argv tokens");
@@ -82,6 +86,12 @@ export const claudeCodeHarness = {
82
86
  let costKnown = false;
83
87
  let costTotal;
84
88
  let parsedAnyLine = false;
89
+ // Fallback only: a run killed by timeout/cancel never gets a `result` event, so without this
90
+ // a fully productive 90-minute run reports empty text and zero usage (D-review §1.2). Neither
91
+ // of these ever sets `terminalSeen`/`protocolStatus` — only a real `result` event may do that;
92
+ // streamed text is not proof the run finished.
93
+ let lastAssistantText = "";
94
+ let streamedUsage;
85
95
  for (const line of input.eventsText.split("\n")) {
86
96
  const trimmed = line.trim();
87
97
  if (!trimmed)
@@ -138,12 +148,40 @@ export const claudeCodeHarness = {
138
148
  usageKnown = true;
139
149
  }
140
150
  }
151
+ if (record.type === "assistant") {
152
+ const message = record.message;
153
+ if (isRecord(message)) {
154
+ const parts = Array.isArray(message.content) ? message.content : [];
155
+ const text = parts
156
+ .filter((part) => isRecord(part) && part.type === "text" && typeof part.text === "string")
157
+ .map((part) => part.text)
158
+ .join("");
159
+ if (text.trim())
160
+ lastAssistantText = text;
161
+ const rawUsage = message.usage;
162
+ if (isRecord(rawUsage)) {
163
+ streamedUsage = {
164
+ input: Number(rawUsage.input_tokens ?? 0) || 0,
165
+ output: Number(rawUsage.output_tokens ?? 0) || 0,
166
+ cacheRead: Number(rawUsage.cache_read_input_tokens ?? 0) || 0,
167
+ cacheWrite: Number(rawUsage.cache_creation_input_tokens ?? 0) || 0,
168
+ };
169
+ }
170
+ }
171
+ }
141
172
  }
142
173
  if (!parsedAnyLine && input.eventsText.trim()) {
143
174
  protocolStatus = "unparsable";
144
175
  }
176
+ if (!terminalSeen && !usageKnown && streamedUsage) {
177
+ usage = {
178
+ ...streamedUsage,
179
+ total: streamedUsage.input + streamedUsage.output + streamedUsage.cacheRead + streamedUsage.cacheWrite,
180
+ };
181
+ usageKnown = true;
182
+ }
145
183
  return {
146
- finalText,
184
+ finalText: finalText || lastAssistantText,
147
185
  terminalSeen,
148
186
  protocolStatus,
149
187
  exitCode: input.exitCode,
@@ -18,7 +18,7 @@ export interface ExternalInvocationInput {
18
18
  /** Path to the role's system-prompt file (`<artifactDir>/system-prompt.txt`), for harnesses
19
19
  * that reference it by flag (e.g. claude-code's `--append-system-prompt-file`). */
20
20
  systemPromptFile: string;
21
- /** Set when this invocation continues an earlier run (`subagent_manage op=follow_up`, D6). */
21
+ /** Set when this invocation continues an earlier run (`subagent_run op=follow_up`, D6). */
22
22
  resumeSessionId?: string;
23
23
  }
24
24
  export interface BuildInvocationResult {
@@ -13,21 +13,73 @@ import { getSubAgentRunManager } from "../runs.js";
13
13
  import { getExternalHarness } from "./registry.js";
14
14
  import { finalizeExternalRun } from "./settlement.js";
15
15
  /**
16
- * Env vars the daemon's own credentials tend to live in — dropped by default from an external
16
+ * Env vars pipiclaw's own credentials tend to live in — dropped by default from an external
17
17
  * process's environment. A target repo's `CLAUDE.md`/prompt can steer an external agent's actions
18
18
  * (it is a separate, untrusted host process, not sandboxed by pipiclaw's own guards), so it should
19
- * not inherit pipiclaw's own provider keys or DingTalk credentials just because it inherits the
20
- * daemon's shell (review 2026-08-23 §2.4). A role can add any of these back explicitly via `env:`.
19
+ * not inherit pipiclaw's own LLM provider keys or DingTalk credentials just because it inherits
20
+ * the daemon's shell (review 2026-08-23 §2.4). A role can add any of these back explicitly via
21
+ * `env:`.
22
+ *
23
+ * An explicit name list, not a suffix pattern (fix plan §4.3): a `_API_KEY`/`_SECRET`/`_TOKEN`/
24
+ * `_PASSWORD` suffix regex both over-blocks (a role that shells out to `gh`/`npm` loses
25
+ * `GITHUB_TOKEN`/`NPM_TOKEN` with zero explanation) and under-blocks (`AWS_SECRET_ACCESS_KEY`,
26
+ * `GOOGLE_APPLICATION_CREDENTIALS`, `SSH_AUTH_SOCK` do not match the suffix at all). This list is
27
+ * therefore deliberately narrow: only the env vars pipiclaw's own LLM calls and DingTalk transport
28
+ * read (`src/models/api-keys.ts`, the `pi-ai` provider registry). It is a courtesy against
29
+ * accidental inheritance, not a security boundary — the real boundary is the role's own command,
30
+ * CLI sandbox, and host account (AGENTS.md).
21
31
  */
22
- const SENSITIVE_ENV_PATTERN = /(?:_API_KEY|_SECRET|_TOKEN|_PASSWORD)$/i;
32
+ const SENSITIVE_ENV_VAR_NAMES = new Set([
33
+ "ANTHROPIC_API_KEY",
34
+ "ANTHROPIC_AUTH_TOKEN",
35
+ "ANTHROPIC_OAUTH_TOKEN",
36
+ "OPENAI_API_KEY",
37
+ "GOOGLE_API_KEY",
38
+ "GEMINI_API_KEY",
39
+ "GOOGLE_CLOUD_API_KEY",
40
+ "AZURE_OPENAI_API_KEY",
41
+ "MISTRAL_API_KEY",
42
+ "GROQ_API_KEY",
43
+ "CEREBRAS_API_KEY",
44
+ "DEEPSEEK_API_KEY",
45
+ "XAI_API_KEY",
46
+ "OPENROUTER_API_KEY",
47
+ "TOGETHER_API_KEY",
48
+ "FIREWORKS_API_KEY",
49
+ "MOONSHOT_API_KEY",
50
+ "MINIMAX_API_KEY",
51
+ "MINIMAX_CN_API_KEY",
52
+ "KIMI_API_KEY",
53
+ "ZAI_API_KEY",
54
+ "QWEN_TOKEN_PLAN_API_KEY",
55
+ "QWEN_TOKEN_PLAN_CN_API_KEY",
56
+ "NVIDIA_API_KEY",
57
+ "OPENCODE_API_KEY",
58
+ "CLOUDFLARE_API_KEY",
59
+ "AI_GATEWAY_API_KEY",
60
+ ]);
61
+ /** Filters an external process's inherited env, returning the keys it actually dropped so the
62
+ * caller can surface them in `invocationWarnings` — silently dropping `GITHUB_TOKEN` or
63
+ * similar with zero trace is exactly what made this hard to diagnose before (fix plan §4.3). */
23
64
  function filterSensitiveEnv(env) {
24
65
  const filtered = {};
66
+ const dropped = [];
25
67
  for (const [key, value] of Object.entries(env)) {
26
- if (SENSITIVE_ENV_PATTERN.test(key) || key.startsWith("DINGTALK_"))
68
+ if (SENSITIVE_ENV_VAR_NAMES.has(key) || key.startsWith("DINGTALK_")) {
69
+ dropped.push(key);
27
70
  continue;
71
+ }
28
72
  filtered[key] = value;
29
73
  }
30
- return filtered;
74
+ return { filtered, dropped };
75
+ }
76
+ /** Only set when at least one credential was actually present and dropped -- a role that never
77
+ * had `GITHUB_TOKEN` set in the first place gets no noise about it. */
78
+ function mergeInvocationWarnings(warnings, droppedEnvVars) {
79
+ if (droppedEnvVars.length === 0)
80
+ return warnings;
81
+ const envWarning = `Dropped from this process's environment (add back via the role's env: if needed): ${droppedEnvVars.join(", ")}`;
82
+ return warnings ? [...warnings, envWarning] : [envWarning];
31
83
  }
32
84
  function classifySpawnError(error) {
33
85
  const code = error.code;
@@ -149,13 +201,14 @@ export async function launchExternalRun(input) {
149
201
  await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
150
202
  return { ok: false, kind: "launch-failed", reason };
151
203
  }
204
+ const envFilterResult = filterSensitiveEnv(process.env);
152
205
  const spawnFn = input.spawnFn ?? nodeSpawn;
153
206
  let child;
154
207
  try {
155
208
  child = spawnFn(invocation.executable, invocation.args, {
156
209
  detached: true,
157
210
  cwd: input.workingDirectory,
158
- env: { ...filterSensitiveEnv(process.env), ...input.env },
211
+ env: { ...envFilterResult.filtered, ...input.env },
159
212
  // stdout/stderr point straight at the artifact files (P0-1): the child writes them
160
213
  // itself, so they land on disk even if this daemon disappears before it exits.
161
214
  stdio: ["pipe", eventsFd, stderrFd],
@@ -226,7 +279,7 @@ export async function launchExternalRun(input) {
226
279
  maxWallTimeSec: input.maxWallTimeSec,
227
280
  processStartedAt,
228
281
  channelDir: input.channelDir,
229
- invocationWarnings: invocation.warnings,
282
+ invocationWarnings: mergeInvocationWarnings(invocation.warnings, envFilterResult.dropped),
230
283
  // Spec 042 D12: distinguishes "the target CLI's schema drifted" from "the agent failed".
231
284
  parserVersion: harness.parserVersion,
232
285
  cliVersion,
@@ -1,11 +1,12 @@
1
+ import { formatDuration } from "../shared/duration.js";
1
2
  import type { RunRecord } from "./runs.js";
2
3
  /**
3
4
  * Shared display primitives for delegation runs (spec 041), used by both the model-facing
4
- * `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
5
+ * `subagent_list`/`subagent_run` tools and the human-facing `/subagents` runtime command. Only the pieces that
5
6
  * are genuinely language/audience-neutral live here — duration math, the harness label, and the
6
7
  * cost guard — not full line templates, since the two surfaces render in different languages.
7
8
  */
8
- export declare function formatDuration(ms: number): string;
9
+ export { formatDuration };
9
10
  export declare function elapsedMs(record: RunRecord, now?: number): number;
10
11
  /** Spec 042 D1: a restart-reconciled run's duration is an estimate (from the artifact file's mtime
11
12
  * or a wall-clock fallback), not a measured process lifetime — prefix it so a reader does not
@@ -1,15 +1,11 @@
1
+ import { formatDuration } from "../shared/duration.js";
1
2
  /**
2
3
  * Shared display primitives for delegation runs (spec 041), used by both the model-facing
3
- * `subagent_manage` tool and the human-facing `/subagents` runtime command. Only the pieces that
4
+ * `subagent_list`/`subagent_run` tools and the human-facing `/subagents` runtime command. Only the pieces that
4
5
  * are genuinely language/audience-neutral live here — duration math, the harness label, and the
5
6
  * cost guard — not full line templates, since the two surfaces render in different languages.
6
7
  */
7
- export function formatDuration(ms) {
8
- const seconds = Math.round(ms / 1000);
9
- if (seconds < 60)
10
- return `${seconds}s`;
11
- return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
12
- }
8
+ export { formatDuration };
13
9
  export function elapsedMs(record, now = Date.now()) {
14
10
  return (record.finishedAt ?? now) - record.startedAt;
15
11
  }
@@ -283,7 +283,7 @@ export declare class SubAgentRunManager {
283
283
  * harmless — this is the same fix as job-manager's `announce()` reordering (D7).
284
284
  */
285
285
  private announce;
286
- /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
286
+ /** Explicit cancel (`subagent_run op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
287
287
  cancel(runId: string): Promise<RunStatus | "not_found">;
288
288
  /**
289
289
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
@@ -2,6 +2,7 @@ import { mkdir, readdir, readFile, rmdir, stat, unlink } from "node:fs/promises"
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { formatDuration } from "../shared/duration.js";
5
6
  import { isProcessAlive, killProcessGroup, readProcessStartTime } from "../shared/host-process.js";
6
7
  import { RecoverableToolError } from "../shared/recoverable-error.js";
7
8
  import { createSerialQueue } from "../shared/serial-queue.js";
@@ -82,12 +83,6 @@ function parseRunRecord(raw) {
82
83
  }
83
84
  return value;
84
85
  }
85
- function formatDuration(ms) {
86
- const seconds = Math.round(ms / 1000);
87
- if (seconds < 60)
88
- return `${seconds}s`;
89
- return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
90
- }
91
86
  /**
92
87
  * Per-channel manager for delegation runs — the single settlement/usage/wake authority for both
93
88
  * internal sub-agents and (once wired) external harnesses (D7). Modeled directly on
@@ -218,7 +213,7 @@ export class SubAgentRunManager {
218
213
  // non-goals). Checked before anything is persisted, so a rejected run costs nothing.
219
214
  if (this.runningCount() >= MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL) {
220
215
  throw new RecoverableToolError(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
221
- "Wait for one to finish, or cancel one with subagent_manage first.");
216
+ "Wait for one to finish, or cancel one with subagent_run op=cancel first.");
222
217
  }
223
218
  if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
224
219
  throw new RecoverableToolError(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
@@ -467,7 +462,7 @@ export class SubAgentRunManager {
467
462
  const tail = outputText.slice(-WAKE_OUTPUT_TAIL_CHARS).trim();
468
463
  const harnessLabel = record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
469
464
  // K parallel fan-out runs otherwise produce K wake turns, each re-asking "is this the only
470
- // one?" via a fresh subagent_manage op=list call — this answers it inline (review 2026-08-23
465
+ // one?" via a fresh subagent_list call — this answers it inline (review 2026-08-23
471
466
  // §3.3), so the model can reliably reply [SILENT] to every wake but the last.
472
467
  const siblingCount = record.taskId
473
468
  ? Array.from(this.runs.values()).filter((other) => other.taskId === record.taskId && other.status === "running" && other.runId !== record.runId).length
@@ -512,6 +507,12 @@ export class SubAgentRunManager {
512
507
  }
513
508
  : {}),
514
509
  };
510
+ // The `boolean` return value (queue-full/backpressure -> `false`) is deliberately not
511
+ // checked here, unlike the thrown-error case above: `DurableDispatchService.enqueueEvent`
512
+ // puts a rejected record back into `pending` rather than dropping it, and the 30s periodic
513
+ // drain retries it from there -- so marking `wakeEnqueued` on a `false` return is still safe,
514
+ // not a lost wake (fix plan §1.7 / review 2026-08-24 §1.7). Re-verify this against
515
+ // `durable-dispatch.ts` before changing either side.
515
516
  try {
516
517
  await this.options.dispatch(event);
517
518
  }
@@ -522,7 +523,7 @@ export class SubAgentRunManager {
522
523
  record.wakeEnqueued = true;
523
524
  await this.persist(record);
524
525
  }
525
- /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
526
+ /** Explicit cancel (`subagent_run op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
526
527
  async cancel(runId) {
527
528
  let adoptedRecord;
528
529
  const status = await this.queue.run(runId, async () => {
@@ -2,6 +2,7 @@ import { type AgentEvent, type AgentMessage, type AgentTool } from "@earendil-wo
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { Type } from "typebox";
4
4
  import type { Executor } from "../executor.js";
5
+ import type { FileStore } from "../file-store.js";
5
6
  import type { MemoryCandidateStore } from "../memory/candidates.js";
6
7
  import type { SecurityConfig } from "../security/types.js";
7
8
  import type { PipiclawMemoryRecallSettings } from "../settings.js";
@@ -9,22 +10,34 @@ import { type UsageTotals } from "../shared/types.js";
9
10
  import type { PipiclawWebToolsConfig } from "../tools/config.js";
10
11
  import { type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
11
12
  import { getSubAgentRunManager } from "./runs.js";
13
+ /**
14
+ * Role-based delegation (spec 046, D2.1): the common path. No override fields beyond routing
15
+ * ones — tools, model, effort, context, thinkingLevel and mutates all live in the role file, so
16
+ * a call naming an external role cannot pass any of them (there is nowhere for it to put them).
17
+ */
12
18
  declare const subagentSchema: Type.TObject<{
13
- label: Type.TString;
14
- agent: Type.TOptional<Type.TString>;
15
- name: Type.TOptional<Type.TString>;
19
+ agent: Type.TString;
16
20
  task: Type.TString;
17
- systemPrompt: Type.TOptional<Type.TString>;
21
+ workingDirectory: Type.TOptional<Type.TString>;
22
+ purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
23
+ taskId: Type.TOptional<Type.TString>;
24
+ }>;
25
+ /**
26
+ * Inline delegation (spec 046, D2.1): a one-off executor for when no configured role fits.
27
+ * Carries every field a role file would otherwise supply.
28
+ */
29
+ declare const subagentInlineSchema: Type.TObject<{
30
+ task: Type.TString;
31
+ systemPrompt: Type.TString;
18
32
  tools: Type.TOptional<Type.TArray<Type.TString>>;
19
33
  model: Type.TOptional<Type.TString>;
20
34
  effort: Type.TOptional<Type.TUnion<[Type.TLiteral<"quick">, Type.TLiteral<"standard">, Type.TLiteral<"deep">]>>;
21
35
  context: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"session">, Type.TLiteral<"relevant">]>>;
22
- paths: Type.TOptional<Type.TArray<Type.TString>>;
36
+ thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
37
+ mutates: Type.TOptional<Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"write">]>>;
23
38
  workingDirectory: Type.TOptional<Type.TString>;
24
39
  purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
25
40
  taskId: Type.TOptional<Type.TString>;
26
- returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
27
- thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
28
41
  }>;
29
42
  /**
30
43
  * Fields the `subagent` tool itself constructs. `kind` is not among them: `withToolDetails`
@@ -45,10 +58,8 @@ export interface SubAgentToolFields {
45
58
  purpose: "work" | "verify";
46
59
  taskId?: string;
47
60
  verificationVerdict?: "pass" | "fail";
48
- /** Always populated (spec 032 D4): the full output is saved to `${artifactDir}/output.md` regardless of `returns`. */
61
+ /** Always populated (spec 032 D4): the full output is saved to `${artifactDir}/output.md`. */
49
62
  artifactDir: string;
50
- /** Set only when `returns: "artifact"` and the sub-agent emitted a valid ARTIFACT: marker. */
51
- artifactPath?: string;
52
63
  /** True when the reply text was truncated against MAX_SUBAGENT_RESULT_UNITS; the full text is still on disk. */
53
64
  resultTruncated: boolean;
54
65
  /**
@@ -60,10 +71,11 @@ export interface SubAgentToolFields {
60
71
  }
61
72
  /** The shape consumers read post-wrap, once `withToolDetails` has stamped `kind`. */
62
73
  export type SubAgentToolDetails = SubAgentToolFields & {
63
- kind: "subagent";
74
+ kind: "subagent" | "subagent_inline";
64
75
  };
65
76
  export interface SubAgentToolOptions {
66
77
  executor: Executor;
78
+ fileStore: FileStore;
67
79
  /** Host checkout used as the sub-agent's cwd. Defaults to process.cwd(). */
68
80
  workingDirectory?: string;
69
81
  /** Mirrors the parent channel's ProjectScope.boundary onto the sub-agent's own tool set (spec 043, D6.2). */
@@ -116,7 +128,7 @@ interface SubAgentWorker {
116
128
  * only caps what gets echoed into the parent's context.
117
129
  */
118
130
  export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
119
- /** Exported for `subagent_manage op=follow_up` (spec 042 D7), which constructs one of these for
131
+ /** Exported for `subagent_run op=follow_up` (spec 042 D7), which constructs one of these for
120
132
  * its own new run rather than a hand-rolled envelope. */
121
133
  export interface SubAgentRunContext {
122
134
  runId: string;
@@ -141,30 +153,31 @@ export declare function assertWithinProjectBoundary(target: string, base: string
141
153
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
142
154
  */
143
155
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
144
- /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
156
+ /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
145
157
  export declare function buildVerificationProtocol(taskPath: string): string;
146
158
  /**
147
159
  * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
148
160
  * protocol terminal to prove it even ran to completion, and a target with an active write lease
149
161
  * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
150
- * Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
162
+ * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
151
163
  * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
152
164
  * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
153
165
  */
154
166
  export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
155
167
  /**
156
- * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
168
+ * Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
157
169
  * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
158
170
  * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
159
171
  * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
160
172
  * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
161
173
  */
162
- export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext, returns: "text" | "artifact"): string;
163
- /** Exported for `subagent_manage op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
174
+ export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext): string;
175
+ /** Exported for `subagent_run op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
164
176
  /** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
165
- * D7) so `subagent_manage op=follow_up` only needs to wire these six fields, not the full tool
177
+ * D7) so `subagent_run op=follow_up` only needs to wire these six fields, not the full tool
166
178
  * option surface (executor, discovery, web config, etc. that a context-block build never touches). */
167
179
  export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "getMemoryRecallSettings" | "runtimeContext" | "workspaceDir" | "resolveApiKey" | "memoryCandidateStore">;
168
180
  export declare function buildContextualBlocks(task: string, config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory" | "description">, options: ContextualBlocksOptions, currentModel: Model<Api>): Promise<string[]>;
169
181
  export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolFields>;
182
+ export declare function createSubAgentInlineTool(options: SubAgentToolOptions): AgentTool<typeof subagentInlineSchema, SubAgentToolFields>;
170
183
  export {};