@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,12 +1,25 @@
1
1
  import * as log from "../log.js";
2
- import { extractLabelFromArgs, truncate } from "../shared/text-utils.js";
2
+ import { truncate } from "../shared/text-utils.js";
3
3
  import { isRecord } from "../shared/type-guards.js";
4
- import { toolResultDetails } from "../tools/tool-details.js";
4
+ import { describeToolCall } from "../tools/presentation.js";
5
+ import { isArgumentValidationFailure, isRecoverableRejection, toolResultDetails, } from "../tools/tool-details.js";
5
6
  import { isEffectfulTool, noteChannelEffect } from "./effect-ledger.js";
6
7
  import { extractToolResultText, formatProgressEntry } from "./progress-formatter.js";
7
8
  import { extractCustomCommandResultText, isAssistantEventMessage, isAutoCompactionEndEvent, isAutoCompactionStartEvent, isAutoRetryStartEvent, isMessageEndEvent, isMessageStartEvent, isSubAgentToolDetails, isTextPart, isThinkingPart, isToolExecutionEndEvent, isToolExecutionStartEvent, isToolExecutionUpdateEvent, isTurnEndEvent, } from "./type-guards.js";
8
- function isSkillManageDetails(value) {
9
- return isRecord(value) && value.kind === "skill_manage";
9
+ /**
10
+ * A `write`/`edit` result whose resolved target landed inside the workspace `skills/` tree. The
11
+ * `skill` tool is read-only (spec 045); authoring a workspace skill goes through the generic file
12
+ * tools, so this is the only way the runtime learns "the skill catalog may have changed" — no
13
+ * per-tool `requiresResourceRefresh` flag to keep in sync any more.
14
+ */
15
+ function isWorkspaceSkillWrite(toolName, details, skillsDir) {
16
+ if (toolName !== "write" && toolName !== "edit") {
17
+ return false;
18
+ }
19
+ if (!isRecord(details) || typeof details.path !== "string") {
20
+ return false;
21
+ }
22
+ return details.path === skillsDir || details.path.startsWith(`${skillsDir}/`);
10
23
  }
11
24
  function mergeSubAgentUsage(totalUsage, details) {
12
25
  totalUsage.input += details.usage.input;
@@ -43,7 +56,7 @@ export async function handleSessionEvent(event, context) {
43
56
  const showProgress = ctx.progressStyle !== "none";
44
57
  const finalToCard = ctx.finalDelivery === "card";
45
58
  if (isToolExecutionStartEvent(event)) {
46
- const label = extractLabelFromArgs(event.args) || event.toolName;
59
+ const label = describeToolCall(event.toolName, event.args);
47
60
  pendingTools.set(event.toolCallId, {
48
61
  toolName: event.toolName,
49
62
  args: event.args,
@@ -93,21 +106,23 @@ export async function handleSessionEvent(event, context) {
93
106
  subAgentDetails.usage.cost.total > 0 || (context.isModelCostKnown?.(subAgentDetails.model) ?? false);
94
107
  }
95
108
  const details = toolResultDetails(event.result);
96
- if (isSkillManageDetails(details)) {
97
- if (details.requiresResourceRefresh && context.refreshSessionResources) {
98
- queue.enqueue(() => context.refreshSessionResources?.() ?? Promise.resolve(), "refresh skills");
99
- }
100
- if (details.notice) {
101
- queue.enqueue(() => ctx.respondInThread(details.notice ?? ""), "skill notice");
102
- }
109
+ if (context.skillsDir &&
110
+ context.refreshSessionResources &&
111
+ isWorkspaceSkillWrite(event.toolName, details, context.skillsDir)) {
112
+ queue.enqueue(() => context.refreshSessionResources?.() ?? Promise.resolve(), "refresh skills");
113
+ queue.enqueue(() => ctx.respondInThread("已沉淀:workspace skill 已更新,下一轮生效。"), "skill notice");
103
114
  }
104
115
  // A recoverable rejection (bad arguments, unmet precondition the model can fix) is not a
105
116
  // fault: the model normally corrects it on the next call. It is logged so the retry is
106
117
  // still diagnosable, but never rendered to the user — a red bubble would report a failure
107
118
  // that never happened and make the assistant look broken mid-turn. Rejections the *user*
108
119
  // must resolve (a security guard refusal or an external decision) stay plain errors and remain visible.
109
- const rejected = details?.recoverable === true;
110
- const treatAsError = event.isError || Boolean(subAgentDetails?.failed);
120
+ // Spec 047, D4.2: a schema-validation failure is rejected by the SDK before `execute`, so it
121
+ // never passes through `withToolDetails` and carries no `recoverable` flag — but it is still
122
+ // something the model fixes by re-issuing correct arguments, so it must not surface as a
123
+ // user-visible error. `event.isError` is true for it, so it has to win over `treatAsError`.
124
+ const rejected = isRecoverableRejection(event.result) || isArgumentValidationFailure(event.result, event.isError === true);
125
+ const treatAsError = (event.isError || Boolean(subAgentDetails?.failed)) && !rejected;
111
126
  if (treatAsError) {
112
127
  log.logToolError(logCtx, event.toolName, durationMs, resultStr);
113
128
  }
@@ -26,39 +26,39 @@ export function formatUptime(ms) {
26
26
  }
27
27
  export function renderStatus(options) {
28
28
  const { runner, version, uptimeMs } = options;
29
- const lines = ["# Status"];
29
+ let runState;
30
30
  if (runner?.isBusy()) {
31
31
  const task = runner.getTurnStatus().taskText?.trim();
32
- const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
33
- lines.push(`- Run state: running${preview}`);
32
+ const preview = task ? `:${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
33
+ runState = `运行中${preview}`;
34
34
  }
35
35
  else {
36
- lines.push("- Run state: idle");
36
+ runState = "空闲";
37
37
  }
38
+ const lines = [`**状态** · ${runState}`];
38
39
  if (runner) {
39
40
  try {
40
41
  const snapshot = runner.getStatusSnapshot();
41
- lines.push(`- Model: ${snapshot.model}`);
42
- lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
42
+ let modelLine = `- 模型:\`${snapshot.model}\`(thinking \`${snapshot.thinkingLevel}\`)`;
43
43
  if (snapshot.fallback) {
44
44
  const until = new Date(snapshot.fallback.cooldownUntilMs);
45
45
  const hh = String(until.getHours()).padStart(2, "0");
46
46
  const mm = String(until.getMinutes()).padStart(2, "0");
47
- lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
47
+ modelLine += ` · fallback 生效中(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`;
48
48
  }
49
+ lines.push(modelLine);
49
50
  if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
50
51
  const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
51
- lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
52
+ lines.push(`- 上下文:${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)}(${percent}%)`);
52
53
  }
53
54
  }
54
55
  catch (err) {
55
- lines.push(`- Model: unavailable (${errorMessage(err)})`);
56
+ lines.push(`- 模型:不可用(${errorMessage(err)})`);
56
57
  }
57
58
  }
58
59
  else {
59
- lines.push("- Model: no session started for this channel yet");
60
+ lines.push("- 模型:本频道尚未开始过会话");
60
61
  }
61
- lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
62
- lines.push(`- Version: ${version}`);
62
+ lines.push(`- 已运行 ${formatUptime(uptimeMs)} · 版本 \`${version}\``);
63
63
  return lines.join("\n");
64
64
  }
@@ -17,8 +17,8 @@ const SYNTHETIC_TOOL_RESULT_HEADER = "Error: Pipiclaw restarted before a durable
17
17
  "do not repeat the operation blindly.";
18
18
  const SYNTHETIC_ABORTED_ASSISTANT_TEXT = "Error: Pipiclaw restarted before a response was generated. Re-send the request if it is still needed.";
19
19
  function toolGuidance(toolName) {
20
- if (toolName === "subagent" || toolName === "subagent_manage") {
21
- return "先用 `subagent_manage op=list` / `show` 查询这次委派是否已经作为一个 durable run 存在。";
20
+ if (toolName === "subagent" || toolName === "subagent_list" || toolName === "subagent_run") {
21
+ return "先用 `subagent_list` / `subagent_run op=show` 查询这次委派是否已经作为一个 durable run 存在。";
22
22
  }
23
23
  if (toolName === "job" || toolName === "bash") {
24
24
  return "若这是一次异步操作(后台 job 或已启动的进程),先用 job `list` / `poll` 查记录,再决定是否需要重跑。";
@@ -78,7 +78,11 @@ export function isAutoRetryStartEvent(value) {
78
78
  typeof value.errorMessage === "string");
79
79
  }
80
80
  export function isSubAgentToolDetails(value) {
81
- if (!value || typeof value !== "object" || !("kind" in value) || value.kind !== "subagent") {
81
+ if (!value || typeof value !== "object" || !("kind" in value)) {
82
+ return false;
83
+ }
84
+ const kind = value.kind;
85
+ if (kind !== "subagent" && kind !== "subagent_inline") {
82
86
  return false;
83
87
  }
84
88
  if (!("usage" in value)) {
@@ -12,8 +12,8 @@ export interface PipiclawSkillsResult {
12
12
  /**
13
13
  * Load skills from the workspace-level skill directory.
14
14
  *
15
- * Diagnostics (an unreadable SKILL.md, bad frontmatter, a duplicate name) were
16
- * previously dropped on the floor, so a broken workspace skill silently vanished
15
+ * Diagnostics (an unreadable SKILL.md, bad frontmatter, a duplicate name, content that failed the
16
+ * scan above) were previously dropped on the floor, so a broken workspace skill silently vanished
17
17
  * from the prompt. They are returned now and surfaced by the runner.
18
18
  */
19
19
  export declare function loadPipiclawSkills(channelDir: string): PipiclawSkillsResult;
@@ -4,19 +4,57 @@
4
4
  * SOUL.md and AGENTS.md are loaded by the prompt pipeline itself
5
5
  * (`agent/prompt/resources.ts`), which owns their budgets and framing.
6
6
  */
7
+ import { readFileSync } from "node:fs";
7
8
  import { loadSkillsFromDir } from "@earendil-works/pi-coding-agent";
8
9
  import { join } from "path";
10
+ import { scanSkillContent } from "../tools/skill-security.js";
11
+ /**
12
+ * Content scanning moved here from the old `skill_manage` write path (spec 045): `skill` is now
13
+ * read-only and workspace skills are authored through the generic `write`/`edit` tools, which have
14
+ * no reason to know about skill-specific content rules. `Skill` (from pi's resource loader) carries
15
+ * only catalog metadata, not the file body, so this reads each candidate's `SKILL.md` itself --
16
+ * that read is also what keeps a scan-failing skill out of the `<available_skills>` catalog
17
+ * entirely, not just out of the (optional) `skill read` tool: the catalog is what tells the model
18
+ * the skill exists in the first place. An unreadable file is treated as "keep it" here -- a race or
19
+ * permission glitch should not itself become a silent content-policy rejection.
20
+ */
21
+ function filterScannedSkills(skills) {
22
+ const kept = [];
23
+ const diagnostics = [];
24
+ for (const skill of skills) {
25
+ let content;
26
+ try {
27
+ content = readFileSync(skill.filePath, "utf-8");
28
+ }
29
+ catch {
30
+ kept.push(skill);
31
+ continue;
32
+ }
33
+ const scan = scanSkillContent(content);
34
+ if (scan.ok) {
35
+ kept.push(skill);
36
+ continue;
37
+ }
38
+ diagnostics.push({
39
+ type: "warning",
40
+ message: `Skill "${skill.name}" was not loaded: ${scan.error}.`,
41
+ path: skill.filePath,
42
+ });
43
+ }
44
+ return { skills: kept, diagnostics };
45
+ }
9
46
  /**
10
47
  * Load skills from the workspace-level skill directory.
11
48
  *
12
- * Diagnostics (an unreadable SKILL.md, bad frontmatter, a duplicate name) were
13
- * previously dropped on the floor, so a broken workspace skill silently vanished
49
+ * Diagnostics (an unreadable SKILL.md, bad frontmatter, a duplicate name, content that failed the
50
+ * scan above) were previously dropped on the floor, so a broken workspace skill silently vanished
14
51
  * from the prompt. They are returned now and surfaced by the runner.
15
52
  */
16
53
  export function loadPipiclawSkills(channelDir) {
17
54
  const workspaceSkillsDir = join(channelDir, "..", "skills");
18
55
  const loaded = loadSkillsFromDir({ dir: workspaceSkillsDir, source: "workspace" });
19
- return { skills: loaded.skills, diagnostics: loaded.diagnostics };
56
+ const scanned = filterScannedSkills(loaded.skills);
57
+ return { skills: scanned.skills, diagnostics: [...loaded.diagnostics, ...scanned.diagnostics] };
20
58
  }
21
59
  /**
22
60
  * Merge pi's auto-discovered skills with the workspace ones. Workspace wins on a
@@ -2,6 +2,20 @@
2
2
  * Create an executor that runs commands on the host machine.
3
3
  */
4
4
  export declare function createExecutor(): Executor;
5
+ /**
6
+ * Thrown instead of a plain `Error` when a command is cut short by timeout or abort. Kept
7
+ * deliberately short (no stdout/stderr in the message) because the caught `Error.message` is what
8
+ * a pi SDK tool-call rejection puts, verbatim and untruncated, into the model's context (fix plan
9
+ * §2.2) -- `stdout`/`stderr` are still here for a caller (bash.ts) that wants to show a truncated
10
+ * tail instead of losing the partial output outright.
11
+ */
12
+ export declare class CommandTerminatedError extends Error {
13
+ readonly stdout: string;
14
+ readonly stderr: string;
15
+ readonly reason: "timeout" | "aborted";
16
+ readonly timeoutSeconds?: number;
17
+ constructor(reason: "timeout" | "aborted", stdout: string, stderr: string, timeoutSeconds?: number);
18
+ }
5
19
  export interface Executor {
6
20
  /**
7
21
  * Execute a bash command
@@ -14,9 +28,23 @@ export interface ExecOptions {
14
28
  stdin?: string;
15
29
  /** Directory to run the command in. Defaults to the daemon's own working directory. */
16
30
  cwd?: string;
31
+ /** Override the default 10MB in-memory capture cap for this call (spec 044, D6.2). */
32
+ maxCaptureBytes?: number;
33
+ /**
34
+ * When set, every stdout/stderr byte is also streamed to this path as it arrives, independent
35
+ * of `maxCaptureBytes` -- so a caller (e.g. `bash`) can offer a genuinely complete "full output"
36
+ * file even for a command whose captured `ExecResult.stdout`/`stderr` was truncated (spec 044,
37
+ * D6.3). Best-effort: a stream failure is swallowed, since the capped in-memory result is still
38
+ * returned either way. Interleaves stdout and stderr in arrival order.
39
+ */
40
+ spillTo?: string;
17
41
  }
18
42
  export interface ExecResult {
19
43
  stdout: string;
20
44
  stderr: string;
21
45
  code: number;
46
+ /** True when `stdout` was cut at the capture cap and does not hold the command's full output. */
47
+ stdoutTruncated?: boolean;
48
+ /** True when `stderr` was cut at the capture cap and does not hold the command's full output. */
49
+ stderrTruncated?: boolean;
22
50
  }
package/dist/executor.js CHANGED
@@ -1,10 +1,70 @@
1
+ import { createWriteStream } from "node:fs";
1
2
  import { spawn } from "child_process";
3
+ /**
4
+ * Default in-memory capture cap for a command's stdout/stderr, in bytes (spec 044, D6.1/D6.2).
5
+ * This is `Executor`'s own bound for *command output* -- file content never goes through it (see
6
+ * `src/file-store.ts`). A caller that needs a different bound (e.g. `grep`) can override it with
7
+ * `ExecOptions.maxCaptureBytes`.
8
+ */
9
+ const MAX_CAPTURE_BYTES = 10 * 1024 * 1024;
2
10
  /**
3
11
  * Create an executor that runs commands on the host machine.
4
12
  */
5
13
  export function createExecutor() {
6
14
  return new HostExecutor();
7
15
  }
16
+ /**
17
+ * Thrown instead of a plain `Error` when a command is cut short by timeout or abort. Kept
18
+ * deliberately short (no stdout/stderr in the message) because the caught `Error.message` is what
19
+ * a pi SDK tool-call rejection puts, verbatim and untruncated, into the model's context (fix plan
20
+ * §2.2) -- `stdout`/`stderr` are still here for a caller (bash.ts) that wants to show a truncated
21
+ * tail instead of losing the partial output outright.
22
+ */
23
+ export class CommandTerminatedError extends Error {
24
+ constructor(reason, stdout, stderr, timeoutSeconds) {
25
+ super(reason === "timeout" ? `Command timed out after ${timeoutSeconds} seconds` : "Command aborted");
26
+ this.name = "CommandTerminatedError";
27
+ this.reason = reason;
28
+ this.stdout = stdout;
29
+ this.stderr = stderr;
30
+ this.timeoutSeconds = timeoutSeconds;
31
+ }
32
+ }
33
+ /** Accumulates raw chunks up to a byte cap without re-copying already-capped data on every event. */
34
+ class CappedByteAccumulator {
35
+ constructor(maxBytes) {
36
+ this.maxBytes = maxBytes;
37
+ this.chunks = [];
38
+ this.bytes = 0;
39
+ this.capped = false;
40
+ }
41
+ push(chunk) {
42
+ if (this.capped)
43
+ return;
44
+ const room = this.maxBytes - this.bytes;
45
+ if (chunk.length <= room) {
46
+ this.chunks.push(chunk);
47
+ this.bytes += chunk.length;
48
+ if (this.bytes >= this.maxBytes) {
49
+ this.capped = true;
50
+ }
51
+ return;
52
+ }
53
+ if (room > 0) {
54
+ this.chunks.push(chunk.subarray(0, room));
55
+ this.bytes += room;
56
+ }
57
+ this.capped = true;
58
+ }
59
+ get truncated() {
60
+ return this.capped;
61
+ }
62
+ /** Decode once, at close, rather than per-chunk -- see D6.1: per-chunk `toString()` can split a
63
+ * multi-byte UTF-8 sequence across chunk boundaries and mint U+FFFD in the middle of valid text. */
64
+ toText() {
65
+ return Buffer.concat(this.chunks).toString("utf-8");
66
+ }
67
+ }
8
68
  class HostExecutor {
9
69
  async exec(command, options) {
10
70
  return new Promise((resolve, reject) => {
@@ -24,30 +84,64 @@ class HostExecutor {
24
84
  if (!child) {
25
85
  return;
26
86
  }
27
- let stdout = "";
28
- let stderr = "";
87
+ const maxCaptureBytes = options?.maxCaptureBytes ?? MAX_CAPTURE_BYTES;
88
+ const stdoutAcc = new CappedByteAccumulator(maxCaptureBytes);
89
+ const stderrAcc = new CappedByteAccumulator(maxCaptureBytes);
29
90
  let timedOut = false;
30
91
  let settled = false;
31
- const cleanup = () => {
92
+ let spillStream;
93
+ let spillFailed = false;
94
+ if (options?.spillTo) {
95
+ try {
96
+ spillStream = createWriteStream(options.spillTo, { mode: 0o600 });
97
+ spillStream.on("error", () => {
98
+ spillFailed = true;
99
+ });
100
+ }
101
+ catch {
102
+ spillFailed = true;
103
+ }
104
+ }
105
+ const spill = (chunk) => {
106
+ if (spillStream && !spillFailed) {
107
+ spillStream.write(chunk);
108
+ }
109
+ };
110
+ // Waits for the spill file to actually finish flushing to disk before settling the promise
111
+ // -- `spillStream.end()` alone only *starts* the flush, so a caller that reads the spill
112
+ // path immediately after `exec()` resolves could otherwise race an incomplete write.
113
+ const finalize = (action) => {
32
114
  if (timeoutHandle)
33
115
  clearTimeout(timeoutHandle);
34
116
  if (options?.signal) {
35
117
  options.signal.removeEventListener("abort", onAbort);
36
118
  }
119
+ if (!spillStream) {
120
+ action();
121
+ return;
122
+ }
123
+ const stream = spillStream;
124
+ let settledSpill = false;
125
+ const done = () => {
126
+ if (settledSpill)
127
+ return;
128
+ settledSpill = true;
129
+ action();
130
+ };
131
+ stream.once("error", done);
132
+ stream.end(done);
37
133
  };
38
134
  const rejectOnce = (err) => {
39
135
  if (settled)
40
136
  return;
41
137
  settled = true;
42
- cleanup();
43
- reject(err);
138
+ finalize(() => reject(err));
44
139
  };
45
140
  const resolveOnce = (result) => {
46
141
  if (settled)
47
142
  return;
48
143
  settled = true;
49
- cleanup();
50
- resolve(result);
144
+ finalize(() => resolve(result));
51
145
  };
52
146
  const timeoutHandle = options?.timeout && options.timeout > 0
53
147
  ? setTimeout(() => {
@@ -67,31 +161,39 @@ class HostExecutor {
67
161
  options.signal.addEventListener("abort", onAbort, { once: true });
68
162
  }
69
163
  }
164
+ // Capped-and-discard rather than "append then re-slice to the cap every chunk": the latter
165
+ // re-copies up to MAX_CAPTURE_BYTES on every single data event once a command is already
166
+ // at the cap, which for a high-output command is many GB of memcpy that blocks the event
167
+ // loop for the whole daemon (fix plan §2.2).
70
168
  child.stdout?.on("data", (data) => {
71
- stdout += data.toString();
72
- if (stdout.length > 10 * 1024 * 1024) {
73
- stdout = stdout.slice(0, 10 * 1024 * 1024);
74
- }
169
+ stdoutAcc.push(data);
170
+ spill(data);
75
171
  });
76
172
  child.stderr?.on("data", (data) => {
77
- stderr += data.toString();
78
- if (stderr.length > 10 * 1024 * 1024) {
79
- stderr = stderr.slice(0, 10 * 1024 * 1024);
80
- }
173
+ stderrAcc.push(data);
174
+ spill(data);
81
175
  });
82
176
  child.on("error", (err) => {
83
177
  rejectOnce(err instanceof Error ? err : new Error(String(err)));
84
178
  });
85
179
  child.on("close", (code) => {
180
+ const stdout = stdoutAcc.toText();
181
+ const stderr = stderrAcc.toText();
86
182
  if (options?.signal?.aborted) {
87
- rejectOnce(new Error(`${stdout}\n${stderr}\nCommand aborted`.trim()));
183
+ rejectOnce(new CommandTerminatedError("aborted", stdout, stderr));
88
184
  return;
89
185
  }
90
186
  if (timedOut) {
91
- rejectOnce(new Error(`${stdout}\n${stderr}\nCommand timed out after ${options?.timeout} seconds`.trim()));
187
+ rejectOnce(new CommandTerminatedError("timeout", stdout, stderr, options?.timeout));
92
188
  return;
93
189
  }
94
- resolveOnce({ stdout, stderr, code: code ?? 0 });
190
+ resolveOnce({
191
+ stdout,
192
+ stderr,
193
+ code: code ?? 0,
194
+ ...(stdoutAcc.truncated ? { stdoutTruncated: true } : {}),
195
+ ...(stderrAcc.truncated ? { stderrTruncated: true } : {}),
196
+ });
95
197
  });
96
198
  if (options?.stdin !== undefined) {
97
199
  child.stdin?.on("error", (err) => {
@@ -0,0 +1,96 @@
1
+ import { type Readable, Writable } from "node:stream";
2
+ /**
3
+ * `FileStore` is the file-content counterpart to `Executor` (spec 044, D1): where `Executor` runs
4
+ * a shell command and captures its stdout/stderr, `FileStore` reads and writes file *content*
5
+ * directly over `node:fs`. File content must never be routed through argv, stdout, or stdin --
6
+ * that path forces every read/write through `Executor`'s bounded capture buffer, which silently
7
+ * truncates and can corrupt multi-byte text mid-stream (see the spec's F2/F3 evidence).
8
+ *
9
+ * All paths passed to a `FileStore` method are expected to be the absolute `resolvedPath` that
10
+ * `guardPath` already produced -- callers resolve a path exactly once and pass that same value to
11
+ * both the guard and the store (spec 044, D1.1).
12
+ */
13
+ export interface FileStat {
14
+ size: number;
15
+ mtimeMs: number;
16
+ ino: number;
17
+ mode: number;
18
+ isDirectory: boolean;
19
+ isFile: boolean;
20
+ }
21
+ /** Lightweight fingerprint used to detect a concurrent write between a read and a later write-back (D2.4). */
22
+ export interface FileFingerprint {
23
+ size: number;
24
+ mtimeMs: number;
25
+ ino: number;
26
+ }
27
+ export declare function fingerprintOf(stat: FileStat): FileFingerprint;
28
+ export declare function fingerprintsEqual(a: FileFingerprint, b: FileFingerprint): boolean;
29
+ export interface DirectoryEntry {
30
+ /** Basename of the entry. */
31
+ name: string;
32
+ /** Path relative to the directory passed to `listDirectory`, using `/` separators. */
33
+ relativePath: string;
34
+ isDirectory: boolean;
35
+ }
36
+ export interface ReadBytesOptions {
37
+ start?: number;
38
+ maxBytes?: number;
39
+ signal?: AbortSignal;
40
+ }
41
+ export interface ReadBytesResult {
42
+ data: Buffer;
43
+ /** Whether this read reached the end of the file -- the caller's cue for "is there more?" (P2). */
44
+ eof: boolean;
45
+ stat: FileStat;
46
+ }
47
+ export interface WriteAtomicOptions {
48
+ createParentDir?: boolean;
49
+ /** Preserve the existing file's permission bits across the rename (see `shared/atomic-file.ts`). */
50
+ preserveMode?: boolean;
51
+ signal?: AbortSignal;
52
+ }
53
+ export interface ReplaceViaTempOptions {
54
+ preserveMode?: boolean;
55
+ signal?: AbortSignal;
56
+ }
57
+ export interface WalkFilesOptions {
58
+ /** Stop once this many file paths have been collected; the walk short-circuits, `truncated` says so. */
59
+ maxEntries: number;
60
+ /** Called with a directory's basename; returning true skips descending into it (never dereferenced). */
61
+ prune?: (dirName: string) => boolean;
62
+ signal?: AbortSignal;
63
+ }
64
+ export interface WalkFilesResult {
65
+ /** Regular-file paths only (never directories or symlinks), `/`-joined and relative to the walked root. */
66
+ files: string[];
67
+ /** True when `maxEntries` was hit before the walk finished -- the result is a partial, not the complete tree. */
68
+ truncated: boolean;
69
+ }
70
+ export interface FileStore {
71
+ /** ENOENT resolves to `undefined` rather than throwing. */
72
+ stat(path: string): Promise<FileStat | undefined>;
73
+ /** Single bounded read. `eof` tells the caller whether there is more file left to fetch. */
74
+ readBytes(path: string, opts?: ReadBytesOptions): Promise<ReadBytesResult>;
75
+ /** Streaming read, for `edit`'s large-file path and `read`'s line-index scan. */
76
+ openRead(path: string, opts?: {
77
+ start?: number;
78
+ end?: number;
79
+ }): Readable;
80
+ /** Write-temp-then-rename with fsync, mirroring `shared/atomic-file.ts`'s guarantees. */
81
+ writeAtomic(path: string, data: Buffer | string, opts?: WriteAtomicOptions): Promise<void>;
82
+ /** Streaming atomic replace: `produce` writes to a temp file; on success it is renamed over `path`. */
83
+ replaceViaTemp(path: string, produce: (out: Writable) => Promise<void>, opts?: ReplaceViaTempOptions): Promise<void>;
84
+ /** Depth-bounded directory listing, replacing the `find -maxdepth` shell-out. */
85
+ listDirectory(path: string, opts: {
86
+ maxDepth: number;
87
+ }): Promise<DirectoryEntry[]>;
88
+ /**
89
+ * Unbounded-depth file discovery for `glob`, replacing the `find` shell-out. Directories are
90
+ * pruned by `opts.prune` before being entered (so a huge `node_modules` is never walked at all,
91
+ * mirroring `grep`'s `--exclude-dir` push-down); symlinks (file or directory) are never followed,
92
+ * since `Dirent.isFile()`/`isDirectory()` reflect the link itself, not its target.
93
+ */
94
+ walkFiles(path: string, opts: WalkFilesOptions): Promise<WalkFilesResult>;
95
+ }
96
+ export declare function createFileStore(): FileStore;