@oyasmi/pipiclaw 0.8.0 → 0.8.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 (106) hide show
  1. package/README.md +115 -510
  2. package/dist/agent/channel-runner.d.ts +11 -6
  3. package/dist/agent/channel-runner.js +44 -24
  4. package/dist/agent/command-extension.js +5 -4
  5. package/dist/agent/commands.d.ts +50 -0
  6. package/dist/agent/commands.js +176 -67
  7. package/dist/agent/job-manager.d.ts +5 -5
  8. package/dist/agent/prompt-builder.d.ts +3 -13
  9. package/dist/agent/prompt-builder.js +44 -204
  10. package/dist/agent/run-queue.d.ts +1 -2
  11. package/dist/agent/run-queue.js +3 -5
  12. package/dist/agent/runner-factory.d.ts +1 -2
  13. package/dist/agent/runner-factory.js +2 -2
  14. package/dist/agent/status-render.d.ts +0 -7
  15. package/dist/agent/status-render.js +8 -3
  16. package/dist/agent/types.d.ts +4 -3
  17. package/dist/agent/workspace-resources.d.ts +1 -1
  18. package/dist/agent/workspace-resources.js +3 -15
  19. package/dist/executor.d.ts +20 -0
  20. package/dist/{sandbox.js → executor.js} +3 -95
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/log.d.ts +1 -3
  24. package/dist/log.js +1 -20
  25. package/dist/main.js +14 -4
  26. package/dist/memory/files.js +0 -0
  27. package/dist/memory/lifecycle.js +6 -5
  28. package/dist/memory/maintenance-jobs.d.ts +0 -1
  29. package/dist/memory/maintenance-jobs.js +2 -2
  30. package/dist/memory/maintenance-state.js +2 -1
  31. package/dist/memory/post-turn-review.d.ts +0 -1
  32. package/dist/memory/post-turn-review.js +4 -4
  33. package/dist/memory/scheduler.d.ts +0 -1
  34. package/dist/memory/scheduler.js +2 -2
  35. package/dist/memory/session.js +2 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +11 -0
  38. package/dist/playbooks/event-scheduling.md +43 -0
  39. package/dist/playbooks/memory-and-learning.md +45 -0
  40. package/dist/playbooks/runtime-orientation.md +48 -0
  41. package/dist/playbooks/task-closeout.md +45 -0
  42. package/dist/playbooks/task-delegation.md +44 -0
  43. package/dist/playbooks/task-driving.md +43 -0
  44. package/dist/playbooks/task-planning.md +47 -0
  45. package/dist/playbooks/task-recurring.md +42 -0
  46. package/dist/playbooks/task-repair.md +43 -0
  47. package/dist/runtime/bootstrap.d.ts +7 -11
  48. package/dist/runtime/bootstrap.js +50 -57
  49. package/dist/runtime/delivery.js +4 -3
  50. package/dist/runtime/dingtalk.js +50 -57
  51. package/dist/runtime/durable-dispatch.d.ts +2 -0
  52. package/dist/runtime/durable-dispatch.js +29 -1
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +1 -1
  55. package/dist/runtime/events.js +5 -5
  56. package/dist/runtime/task-commands.js +9 -4
  57. package/dist/runtime/task-driver.js +12 -14
  58. package/dist/security/config.js +2 -1
  59. package/dist/security/network.js +9 -2
  60. package/dist/security/path-guard.js +12 -24
  61. package/dist/security/types.d.ts +0 -1
  62. package/dist/shared/jsonl-appender.js +2 -1
  63. package/dist/shared/task-ledger.d.ts +9 -1
  64. package/dist/shared/task-ledger.js +28 -14
  65. package/dist/shared/text-utils.d.ts +1 -0
  66. package/dist/shared/text-utils.js +3 -0
  67. package/dist/subagents/discovery.js +3 -2
  68. package/dist/subagents/tool.d.ts +2 -3
  69. package/dist/subagents/tool.js +9 -24
  70. package/dist/tasks/control.js +2 -1
  71. package/dist/tasks/verification.js +2 -1
  72. package/dist/tools/bash.d.ts +1 -1
  73. package/dist/tools/bash.js +3 -5
  74. package/dist/tools/command-optimizer.d.ts +1 -1
  75. package/dist/tools/command-optimizer.js +4 -6
  76. package/dist/tools/config.js +4 -3
  77. package/dist/tools/edit.d.ts +1 -1
  78. package/dist/tools/edit.js +0 -0
  79. package/dist/tools/event-manage.d.ts +0 -1
  80. package/dist/tools/event-manage.js +9 -14
  81. package/dist/tools/grep.d.ts +1 -1
  82. package/dist/tools/grep.js +4 -6
  83. package/dist/tools/index.d.ts +1 -3
  84. package/dist/tools/index.js +1 -4
  85. package/dist/tools/read.d.ts +1 -1
  86. package/dist/tools/read.js +1 -2
  87. package/dist/tools/registry.d.ts +1 -2
  88. package/dist/tools/registry.js +3 -10
  89. package/dist/tools/skill-manage.d.ts +0 -1
  90. package/dist/tools/skill-manage.js +7 -14
  91. package/dist/tools/task-manage.d.ts +0 -1
  92. package/dist/tools/task-manage.js +18 -16
  93. package/dist/tools/write-content.d.ts +1 -1
  94. package/dist/tools/write-content.js +0 -1
  95. package/dist/tools/write.d.ts +1 -1
  96. package/dist/tui/app.d.ts +0 -2
  97. package/dist/tui/app.js +12 -7
  98. package/dist/tui/cli.d.ts +3 -2
  99. package/dist/tui/cli.js +12 -24
  100. package/dist/tui/commands.d.ts +4 -1
  101. package/dist/tui/commands.js +10 -14
  102. package/dist/tui/turn-controller.d.ts +7 -3
  103. package/dist/tui/turn-controller.js +18 -6
  104. package/dist/web/client.js +2 -1
  105. package/package.json +2 -2
  106. package/dist/sandbox.d.ts +0 -42
@@ -84,11 +84,9 @@ export function isTaskActionable(frontmatter, now) {
84
84
  frontmatter.status === "paused") {
85
85
  return false;
86
86
  }
87
- if (frontmatter.wake) {
88
- const wakeAt = new Date(frontmatter.wake).getTime();
89
- if (Number.isFinite(wakeAt) && wakeAt > now)
90
- return false;
91
- }
87
+ const wakeAt = parseWakeMs(frontmatter);
88
+ if (wakeAt !== undefined && wakeAt > now)
89
+ return false;
92
90
  return true;
93
91
  }
94
92
  /** First `# ` heading after the frontmatter block, or the id when there is none. */
@@ -119,11 +117,21 @@ export function hasTaskHeading(content, names) {
119
117
  export function missingStandardTaskSections(content) {
120
118
  return STANDARD_TASK_SECTIONS.filter((section) => !hasTaskHeading(content, section.names)).map((section) => section.label);
121
119
  }
122
- /** Unchecked Markdown acceptance boxes under DoD or Verification sections. */
120
+ /**
121
+ * Unchecked Markdown acceptance boxes under the DoD section, plus a synthetic
122
+ * entry when DoD has content but no checkbox syntax at all.
123
+ *
124
+ * Without the "no checklist items" case, a DoD written as prose or a numbered
125
+ * list (no `- [ ]` anywhere) makes this function return an empty array —
126
+ * indistinguishable from "everything is checked" — which would silently let
127
+ * `task_manage candidate`/`done` through with nothing ever actually verified.
128
+ */
123
129
  export function uncheckedTaskAcceptanceItems(content) {
124
130
  const unchecked = [];
125
131
  let section;
126
132
  let sectionLevel = 0;
133
+ let dodHasContent = false;
134
+ let dodHasCheckbox = false;
127
135
  for (const line of content.split("\n")) {
128
136
  const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
129
137
  if (heading) {
@@ -143,9 +151,18 @@ export function uncheckedTaskAcceptanceItems(content) {
143
151
  }
144
152
  if (!section)
145
153
  continue;
146
- const item = /^\s*[-*]\s+\[\s\]\s*(.+?)\s*$/.exec(line)?.[1];
147
- if (item)
148
- unchecked.push(`${section}: ${item}`);
154
+ if (section === "DoD" && line.trim())
155
+ dodHasContent = true;
156
+ const checkbox = /^\s*[-*]\s+\[([ xX])\]\s*(.+?)\s*$/.exec(line);
157
+ if (checkbox) {
158
+ if (section === "DoD")
159
+ dodHasCheckbox = true;
160
+ if (checkbox[1] === " ")
161
+ unchecked.push(`${section}: ${checkbox[2]}`);
162
+ }
163
+ }
164
+ if (dodHasContent && !dodHasCheckbox) {
165
+ unchecked.push('DoD has no checklist items — rewrite it as "- [ ] ..." acceptance items before requesting verification or done.');
149
166
  }
150
167
  return unchecked;
151
168
  }
@@ -235,7 +252,6 @@ export function startTaskCycle(content, cycleId) {
235
252
  let currentStart = -1;
236
253
  let currentLevel = 0;
237
254
  let historyStart = -1;
238
- let historyLevel = 0;
239
255
  for (let index = 0; index < lines.length; index++) {
240
256
  const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
241
257
  if (!match)
@@ -247,7 +263,6 @@ export function startTaskCycle(content, cycleId) {
247
263
  }
248
264
  if (matchesTaskSectionTitle(match[2] ?? "", ["History", "历史"])) {
249
265
  historyStart = index;
250
- historyLevel = level;
251
266
  break;
252
267
  }
253
268
  }
@@ -280,7 +295,6 @@ export function startTaskCycle(content, cycleId) {
280
295
  ];
281
296
  // A nested history heading would be unusual; inserting directly after the
282
297
  // canonical History heading remains predictable and preserves all older notes.
283
- void historyLevel;
284
298
  lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
285
299
  return lines.join("\n");
286
300
  }
@@ -309,7 +323,7 @@ function extractLatestNote(content) {
309
323
  }
310
324
  return latest;
311
325
  }
312
- function wakeMsOf(frontmatter) {
326
+ function parseWakeMs(frontmatter) {
313
327
  if (!frontmatter.wake)
314
328
  return undefined;
315
329
  const at = new Date(frontmatter.wake).getTime();
@@ -346,7 +360,7 @@ function toEntry(id, content, now) {
346
360
  title: extractTaskTitle(content, id),
347
361
  frontmatter,
348
362
  actionable: isTaskActionable(frontmatter, now),
349
- wakeMs: wakeMsOf(frontmatter),
363
+ wakeMs: parseWakeMs(frontmatter),
350
364
  latestNote: extractLatestNote(content),
351
365
  };
352
366
  }
@@ -8,4 +8,5 @@ export declare const HAN_REGEX: RegExp;
8
8
  /** Strip a trailing `.json` from an event filename to get its logical name. */
9
9
  export declare function eventNameFromFilename(filename: string): string;
10
10
  export declare function extractLabelFromArgs(args: unknown): string | null;
11
+ export declare function errorMessage(err: unknown): string;
11
12
  export declare function extractAssistantText(message: AssistantMessage): string;
@@ -31,6 +31,9 @@ export function extractLabelFromArgs(args) {
31
31
  const label = args.label;
32
32
  return typeof label === "string" && label.trim() ? label.trim() : null;
33
33
  }
34
+ export function errorMessage(err) {
35
+ return err instanceof Error ? err.message : String(err);
36
+ }
34
37
  export function extractAssistantText(message) {
35
38
  return message.content
36
39
  .filter((part) => part.type === "text")
@@ -3,6 +3,7 @@ import { existsSync, readdirSync, readFileSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { findExactModelReferenceMatch, formatModelReference } from "../models/utils.js";
5
5
  import { SUB_AGENTS_DIR_NAME } from "../paths.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
6
7
  const ALLOWED_SUB_AGENT_TOOLS = ["read", "bash", "edit", "write", "web_search", "web_fetch"];
7
8
  const DEFAULT_SUB_AGENT_TOOLS = ["read", "bash"];
8
9
  const DEFAULT_MAX_TURNS = 24;
@@ -188,7 +189,7 @@ export function discoverSubAgents(workspaceDir, availableModels) {
188
189
  return {
189
190
  directory,
190
191
  agents: [],
191
- warnings: [`Failed to read sub-agents directory (${error instanceof Error ? error.message : String(error)})`],
192
+ warnings: [`Failed to read sub-agents directory (${errorMessage(error)})`],
192
193
  };
193
194
  }
194
195
  for (const entry of entries) {
@@ -198,7 +199,7 @@ export function discoverSubAgents(workspaceDir, availableModels) {
198
199
  content = readFileSync(filePath, "utf-8");
199
200
  }
200
201
  catch (error) {
201
- warnings.push(`${entry.name}: failed to read file (${error instanceof Error ? error.message : String(error)})`);
202
+ warnings.push(`${entry.name}: failed to read file (${errorMessage(error)})`);
202
203
  continue;
203
204
  }
204
205
  const { frontmatter, body } = parseFrontmatter(content);
@@ -1,8 +1,8 @@
1
1
  import { type AgentEvent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { Type } from "typebox";
4
+ import type { Executor } from "../executor.js";
4
5
  import type { MemoryCandidateStore } from "../memory/candidates.js";
5
- import type { Executor } from "../sandbox.js";
6
6
  import type { SecurityConfig } from "../security/types.js";
7
7
  import type { PipiclawMemoryRecallSettings } from "../settings.js";
8
8
  import type { UsageTotals } from "../shared/types.js";
@@ -64,9 +64,8 @@ export interface SubAgentToolOptions {
64
64
  webConfig?: PipiclawWebToolsConfig;
65
65
  rtkEnabled?: boolean;
66
66
  runtimeContext: {
67
- workspacePath: string;
67
+ workspaceDir: string;
68
68
  channelId: string;
69
- sandbox: string;
70
69
  };
71
70
  createWorker?: (config: {
72
71
  subAgent: ResolvedSubAgentConfig;
@@ -9,7 +9,7 @@ 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
11
  import { shellEscape } from "../shared/shell-escape.js";
12
- import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
12
+ import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
13
13
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
14
14
  import { applyTaskControlPatch } from "../tasks/control.js";
15
15
  import { readStoredTask, updateStoredTask } from "../tasks/store.js";
@@ -44,7 +44,7 @@ const subagentSchema = Type.Object({
44
44
  })),
45
45
  taskId: Type.Optional(Type.String({ description: "Persistent task id, required when purpose=verify." })),
46
46
  isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")], {
47
- description: '"worktree" runs in a dedicated git worktree (host sandbox only).',
47
+ description: '"worktree" runs in a dedicated git worktree.',
48
48
  })),
49
49
  worktreePath: Type.Optional(Type.String({ description: "Reuse an existing task-owned worktree; must be under channel tasks/worktrees/." })),
50
50
  });
@@ -68,9 +68,6 @@ class DirectoryExecutor {
68
68
  exec(command, options) {
69
69
  return this.base.exec(`cd ${shellEscape(this.directory)} && ${command}`, options);
70
70
  }
71
- getWorkspacePath(hostPath) {
72
- return this.base.getWorkspacePath(hostPath);
73
- }
74
71
  }
75
72
  function safeRunSegment(value) {
76
73
  return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
@@ -96,14 +93,9 @@ async function prepareRunContext(runId, params, options) {
96
93
  if (isolation === "shared") {
97
94
  if (params.worktreePath)
98
95
  throw new Error("worktreePath requires isolation=worktree.");
99
- const workingDirectory = options.runtimeContext.sandbox === "host"
100
- ? resolve(options.workingDirectory ?? process.cwd())
101
- : options.runtimeContext.workspacePath;
96
+ const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
102
97
  return { runId, purpose, taskId, isolation, workingDirectory };
103
98
  }
104
- if (options.runtimeContext.sandbox !== "host") {
105
- throw new Error("Git worktree isolation currently requires the host sandbox. Use isolation=shared, or run this task in host mode.");
106
- }
107
99
  if (!taskId)
108
100
  throw new Error("isolation=worktree requires taskId so the worktree has a durable owner.");
109
101
  if (!ownedTask?.fields.control) {
@@ -164,7 +156,7 @@ async function prepareRunContext(runId, params, options) {
164
156
  catch (error) {
165
157
  await options.executor.exec(`git -C ${shellEscape(repoRoot)} worktree remove --force ${shellEscape(path)}`);
166
158
  await options.executor.exec(`git -C ${shellEscape(repoRoot)} branch -D ${shellEscape(branch)}`);
167
- throw new Error(`Created the worktree but could not record its ownership on task ${taskId}; the temporary worktree was removed. ${error instanceof Error ? error.message : String(error)}`);
159
+ throw new Error(`Created the worktree but could not record its ownership on task ${taskId}; the temporary worktree was removed. ${errorMessage(error)}`);
168
160
  }
169
161
  return context;
170
162
  }
@@ -257,13 +249,11 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
257
249
  securityConfig,
258
250
  securityContext: {
259
251
  workspaceDir: options.workspaceDir,
260
- workspacePath: options.runtimeContext.workspacePath,
261
252
  cwd: runContext.workingDirectory,
262
253
  },
263
254
  channelId: options.runtimeContext.channelId,
264
255
  channelDir: options.channelDir,
265
256
  workspaceDir: options.workspaceDir,
266
- workspacePath: options.runtimeContext.workspacePath,
267
257
  webConfig: options.webConfig,
268
258
  rtkEnabled: options.rtkEnabled,
269
259
  bashDefaultTimeoutSeconds: bashTimeoutSec,
@@ -273,10 +263,9 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
273
263
  const taskText = task.trim();
274
264
  const lines = [
275
265
  `Runtime context:`,
276
- `- Workspace root: ${runtimeContext.workspacePath}`,
266
+ `- Workspace root: ${runtimeContext.workspaceDir}`,
277
267
  `- Channel id: ${runtimeContext.channelId}`,
278
- `- Channel directory: ${runtimeContext.workspacePath}/${runtimeContext.channelId}`,
279
- `- Sandbox: ${runtimeContext.sandbox}`,
268
+ `- Channel directory: ${runtimeContext.workspaceDir}/${runtimeContext.channelId}`,
280
269
  `- Working directory: ${runContext.workingDirectory}`,
281
270
  `- Filesystem isolation: ${runContext.isolation === "worktree" ? "dedicated git worktree" : "shared with parent"}`,
282
271
  `- Your configured role: ${config.name}`,
@@ -289,7 +278,7 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
289
278
  }
290
279
  lines.push("", `Task:`, taskText);
291
280
  if (runContext.purpose === "verify") {
292
- const taskPath = join(runtimeContext.workspacePath, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
281
+ const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
293
282
  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.");
294
283
  }
295
284
  return lines.join("\n");
@@ -455,9 +444,7 @@ export function createSubAgentTool(options) {
455
444
  };
456
445
  const availableTools = buildSubagentTools(scopedExecutor, config.bashTimeoutSec, options, runContext);
457
446
  const verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
458
- const verifierSubjectBefore = runContext.purpose === "verify" && options.runtimeContext.sandbox === "host"
459
- ? await workspaceSubjectHash(runContext.workingDirectory)
460
- : undefined;
447
+ const verifierSubjectBefore = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
461
448
  const worker = options.createWorker?.({
462
449
  subAgent: config,
463
450
  apiKey,
@@ -550,9 +537,7 @@ export function createSubAgentTool(options) {
550
537
  ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
551
538
  : undefined);
552
539
  const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
553
- const verifierSubjectAfter = runContext.purpose === "verify" && options.runtimeContext.sandbox === "host"
554
- ? await workspaceSubjectHash(runContext.workingDirectory)
555
- : undefined;
540
+ const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
556
541
  const workspaceChanged = runContext.purpose === "verify" &&
557
542
  (verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
558
543
  ? verifierSubjectBefore !== verifierSubjectAfter
@@ -1,3 +1,4 @@
1
+ import { errorMessage } from "../shared/text-utils.js";
1
2
  const PRIORITIES = ["low", "normal", "high", "critical"];
2
3
  const ISOLATIONS = ["shared", "worktree"];
3
4
  const SIDE_EFFECTS = ["read-only", "workspace", "external"];
@@ -75,7 +76,7 @@ export function parseTaskControl(raw) {
75
76
  value = JSON.parse(raw);
76
77
  }
77
78
  catch (error) {
78
- throw new Error(`control is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
79
+ throw new Error(`control is not valid JSON: ${errorMessage(error)}`);
79
80
  }
80
81
  if (!isRecord(value) || value.version !== 1) {
81
82
  throw new Error("control must be a version 1 JSON object");
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { mkdir, readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { errorMessage } from "../shared/text-utils.js";
5
6
  import { readStoredTask, taskBodyHash } from "./store.js";
6
7
  function attestationFilename(runId) {
7
8
  return `${createHash("sha256").update(runId).digest("hex")}.json`;
@@ -44,7 +45,7 @@ export async function readVerificationAttestation(channelDir, runId) {
44
45
  value = JSON.parse(await readFile(verificationAttestationPath(channelDir, runId), "utf-8"));
45
46
  }
46
47
  catch (error) {
47
- throw new Error(`Verification run "${runId}" was not found or is unreadable. Run a subagent with purpose=verify and taskId first. ${error instanceof Error ? error.message : String(error)}`);
48
+ throw new Error(`Verification run "${runId}" was not found or is unreadable. Run a subagent with purpose=verify and taskId first. ${errorMessage(error)}`);
48
49
  }
49
50
  if (typeof value !== "object" ||
50
51
  value === null ||
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
- import type { Executor } from "../sandbox.js";
4
+ import type { Executor } from "../executor.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
6
  /**
7
7
  * Default wall-clock timeout for bash commands when the caller supplies neither a
@@ -14,10 +14,9 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "
14
14
  */
15
15
  export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
16
16
  /**
17
- * Generate a unique spill file path for full bash output. This lives inside the
18
- * executor's filesystem (the sandbox), not the host, so the path we report back is
19
- * reachable by the same `read`/`bash` tools the model uses to open it. `/tmp` exists
20
- * and is writable in both the host and Docker (Alpine) sandboxes.
17
+ * Generate a unique spill file path for full bash output. It lives under `/tmp` so the
18
+ * path we report back is reachable by the same `read`/`bash` tools the model uses to
19
+ * open it.
21
20
  */
22
21
  function getSpillFilePath() {
23
22
  const id = randomBytes(8).toString("hex");
@@ -86,7 +85,6 @@ export function createBashTool(executor, options = {}) {
86
85
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
87
86
  const securityContext = options.securityContext ?? {
88
87
  workspaceDir: process.cwd(),
89
- workspacePath: process.cwd(),
90
88
  cwd: process.cwd(),
91
89
  };
92
90
  return {
@@ -1,4 +1,4 @@
1
- import type { Executor } from "../sandbox.js";
1
+ import type { Executor } from "../executor.js";
2
2
  /**
3
3
  * Return the rtk-optimized form of `command`, or `command` unchanged when rtk is
4
4
  * unavailable or declines to rewrite it. Never throws.
@@ -21,12 +21,10 @@ import { shellEscape } from "../shared/shell-escape.js";
21
21
  */
22
22
  const RTK_TIMEOUT_SECONDS = 2;
23
23
  /**
24
- * rtk must exist in the *execution environment* — the host PATH for a host executor, or
25
- * inside the container for a docker executor — not merely on the pipiclaw host. We probe
26
- * through the executor so the check reflects where the command will actually run, and
27
- * memoize the probe promise per executor instance so concurrent turns share one probe and
28
- * we do not re-shell on every command. The instance is stable for a channel's lifetime,
29
- * so this is effectively "probe once".
24
+ * rtk must exist on the host PATH. We probe through the executor so the check reflects
25
+ * where the command will actually run, and memoize the probe promise per executor instance
26
+ * so concurrent turns share one probe and we do not re-shell on every command. The instance
27
+ * is stable for a channel's lifetime, so this is effectively "probe once".
30
28
  */
31
29
  const availabilityByExecutor = new WeakMap();
32
30
  function probeRtk(executor) {
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { APP_HOME_DIR, TOOLS_CONFIG_PATH } from "../paths.js";
3
+ import { APP_HOME_DIR } from "../paths.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
4
5
  import { isRecord } from "../shared/type-guards.js";
5
6
  const WEB_SEARCH_PROVIDERS = ["brave", "tavily", "jina", "searxng", "duckduckgo"];
6
7
  export const DEFAULT_TOOLS_CONFIG = {
@@ -217,7 +218,7 @@ function mergeToolsConfig(source, configPath, diagnostics) {
217
218
  };
218
219
  }
219
220
  export function getToolsConfigPath(appHomeDir = APP_HOME_DIR) {
220
- return appHomeDir === APP_HOME_DIR ? TOOLS_CONFIG_PATH : join(appHomeDir, "tools.json");
221
+ return join(appHomeDir, "tools.json");
221
222
  }
222
223
  export function loadToolsConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
223
224
  const configPath = getToolsConfigPath(appHomeDir);
@@ -240,7 +241,7 @@ export function loadToolsConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
240
241
  source: "tools",
241
242
  path: configPath,
242
243
  severity: "error",
243
- message: error instanceof Error ? error.message : String(error),
244
+ message: errorMessage(error),
244
245
  },
245
246
  ],
246
247
  };
@@ -1,6 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../sandbox.js";
3
+ import type { Executor } from "../executor.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const editSchema: Type.TObject<{
6
6
  label: Type.TString;
Binary file
@@ -26,7 +26,6 @@ export interface EventManageRequest {
26
26
  }
27
27
  export interface EventManageToolOptions {
28
28
  workspaceDir: string;
29
- workspacePath: string;
30
29
  channelId: string;
31
30
  commandGuardConfig: SecurityConfig["commandGuard"];
32
31
  }
@@ -7,6 +7,7 @@ import { resolveEventPath } from "../runtime/event-commands.js";
7
7
  import { parseScheduledEventContent } from "../runtime/events.js";
8
8
  import { guardCommand } from "../security/command-guard.js";
9
9
  import { writeFileAtomically } from "../shared/atomic-file.js";
10
+ import { errorMessage } from "../shared/text-utils.js";
10
11
  import { isRecord } from "../shared/type-guards.js";
11
12
  /** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
12
13
  const MIN_ONE_SHOT_LEAD_MS = 2 * 60 * 1000;
@@ -15,8 +16,8 @@ const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
15
16
  /**
16
17
  * periodic events WITH a preAction gate may fire this often: the sensor is the token guard
17
18
  * (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
18
- * safe and is exactly the design-endorsed posture for completion-driven checks (e.g. polling
19
- * an agentmux instance until it goes idle). A hard sub-floor still applies so a bogus
19
+ * safe and is exactly the design-endorsed posture for completion-driven checks. A hard
20
+ * sub-floor still applies so a bogus
20
21
  * always-pass preAction cannot drive an arbitrarily hot loop.
21
22
  */
22
23
  const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
@@ -40,12 +41,6 @@ function parseAction(action) {
40
41
  }
41
42
  throw new Error('Unsupported event action. Use "create", "update", or "delete".');
42
43
  }
43
- function toWorkspacePath(options, hostPath) {
44
- if (hostPath.startsWith(options.workspaceDir)) {
45
- return `${options.workspacePath}${hostPath.slice(options.workspaceDir.length)}`;
46
- }
47
- return hostPath;
48
- }
49
44
  function validateTimezone(timezone) {
50
45
  try {
51
46
  new Intl.DateTimeFormat(undefined, { timeZone: timezone });
@@ -72,7 +67,7 @@ function validatePeriodic(event) {
72
67
  cron.stop();
73
68
  }
74
69
  catch (error) {
75
- const message = error instanceof Error ? error.message : String(error);
70
+ const message = errorMessage(error);
76
71
  throw new Error(`Invalid cron schedule "${event.schedule}": ${message}`);
77
72
  }
78
73
  // A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
@@ -107,7 +102,7 @@ function validateDefinition(rawDefinition, name, options) {
107
102
  data = JSON.parse(rawDefinition);
108
103
  }
109
104
  catch (error) {
110
- const message = error instanceof Error ? error.message : String(error);
105
+ const message = errorMessage(error);
111
106
  throw new Error(`definition is not valid JSON: ${message}`);
112
107
  }
113
108
  if (!isRecord(data)) {
@@ -140,7 +135,7 @@ async function readOwnedEvent(eventPath, name, options) {
140
135
  existing = parseScheduledEventContent(await readFile(eventPath, "utf-8"), `${name}.json`);
141
136
  }
142
137
  catch (error) {
143
- const message = error instanceof Error ? error.message : String(error);
138
+ const message = errorMessage(error);
144
139
  throw new Error(`Existing event "${name}" could not be parsed (${message}); use /events to manage it directly.`);
145
140
  }
146
141
  if (existing.channelId !== options.channelId) {
@@ -162,7 +157,7 @@ export async function manageEvent(options, request) {
162
157
  return {
163
158
  action: "delete",
164
159
  name: eventName,
165
- path: toWorkspacePath(options, eventPath),
160
+ path: eventPath,
166
161
  deleted: false,
167
162
  notice: `事件 \`${eventName}\` 不存在,无需删除。`,
168
163
  };
@@ -172,7 +167,7 @@ export async function manageEvent(options, request) {
172
167
  return {
173
168
  action: "delete",
174
169
  name: eventName,
175
- path: toWorkspacePath(options, eventPath),
170
+ path: eventPath,
176
171
  deleted: true,
177
172
  notice: `已删除事件 \`${eventName}\`。`,
178
173
  };
@@ -203,7 +198,7 @@ export async function manageEvent(options, request) {
203
198
  return {
204
199
  action: request.action,
205
200
  name: eventName,
206
- path: toWorkspacePath(options, eventPath),
201
+ path: eventPath,
207
202
  eventType: event.type,
208
203
  channelId: event.channelId,
209
204
  bytesWritten: Buffer.byteLength(content, "utf-8"),
@@ -1,6 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../sandbox.js";
3
+ import type { Executor } from "../executor.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const grepSchema: Type.TObject<{
6
6
  label: Type.TString;
@@ -5,11 +5,10 @@ import { guardPath } from "../security/path-guard.js";
5
5
  import { shellEscape } from "../shared/shell-escape.js";
6
6
  import { DEFAULT_MAX_BYTES, truncateHead } from "./truncate.js";
7
7
  /**
8
- * Structured content search over the sandbox filesystem. The execution layer is deliberately thin
9
- * — one `grep -rnH -B1 -A3` invocation through the shared Executor, so it works identically on the
10
- * host and inside the Docker (busybox) sandbox with no native dependency. The value lives in the
11
- * JS-side output shaping: per-file grouping, per-file and per-page caps, and a final byte bound, so
12
- * a broad search can never flood the model's context the way raw `bash grep -rn` would.
8
+ * Structured content search over the filesystem. The execution layer is deliberately thin — one
9
+ * `grep -rnH -B1 -A3` invocation through the shared Executor, with no native dependency. The value
10
+ * lives in the JS-side output shaping: per-file grouping, per-file and per-page caps, and a final
11
+ * byte bound, so a broad search can never flood the model's context the way raw `bash grep -rn` would.
13
12
  */
14
13
  const CONTEXT_BEFORE = 1;
15
14
  const CONTEXT_AFTER = 3;
@@ -136,7 +135,6 @@ export function createGrepTool(executor, options = {}) {
136
135
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
137
136
  const securityContext = options.securityContext ?? {
138
137
  workspaceDir: process.cwd(),
139
- workspacePath: process.cwd(),
140
138
  cwd: process.cwd(),
141
139
  };
142
140
  return {
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import type { Executor } from "../executor.js";
3
4
  import type { MemoryCandidateStore } from "../memory/candidates.js";
4
- import type { Executor, SandboxConfig } from "../sandbox.js";
5
5
  import type { SecurityConfig } from "../security/types.js";
6
6
  import type { PipiclawMemoryRecallSettings, PipiclawSessionSearchSettings } from "../settings.js";
7
7
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
@@ -13,9 +13,7 @@ export interface CreatePipiclawToolsOptions {
13
13
  resolveApiKey: (model: Model<Api>) => Promise<string>;
14
14
  workspaceDir: string;
15
15
  channelDir: string;
16
- workspacePath: string;
17
16
  channelId: string;
18
- sandboxConfig: SandboxConfig;
19
17
  getSubAgentDiscovery: () => SubAgentDiscoveryResult;
20
18
  getMemoryRecallSettings: () => PipiclawMemoryRecallSettings;
21
19
  getSessionSearchSettings: () => PipiclawSessionSearchSettings;
@@ -9,7 +9,6 @@ export function createPipiclawTools(options) {
9
9
  const toolsConfig = options.toolsConfig ?? loadToolsConfig(APP_HOME_DIR);
10
10
  const securityContext = {
11
11
  workspaceDir: options.workspaceDir,
12
- workspacePath: options.workspacePath,
13
12
  cwd: process.cwd(),
14
13
  };
15
14
  // The leaf tools (files, web, memory, skills) come from the single declarative
@@ -23,7 +22,6 @@ export function createPipiclawTools(options) {
23
22
  channelId: options.channelId,
24
23
  channelDir: options.channelDir,
25
24
  workspaceDir: options.workspaceDir,
26
- workspacePath: options.workspacePath,
27
25
  webConfig: toolsConfig.tools.web,
28
26
  toolsConfig,
29
27
  rtkEnabled: toolsConfig.tools.rtk.enabled,
@@ -53,9 +51,8 @@ export function createPipiclawTools(options) {
53
51
  webConfig: toolsConfig.tools.web,
54
52
  rtkEnabled: toolsConfig.tools.rtk.enabled,
55
53
  runtimeContext: {
56
- workspacePath: options.workspacePath,
54
+ workspaceDir: options.workspaceDir,
57
55
  channelId: options.channelId,
58
- sandbox: options.sandboxConfig.type === "host" ? "host" : `docker:${options.sandboxConfig.container}`,
59
56
  },
60
57
  }),
61
58
  ];
@@ -1,6 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../sandbox.js";
3
+ import type { Executor } from "../executor.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const readSchema: Type.TObject<{
6
6
  label: Type.TString;
@@ -90,7 +90,6 @@ export function createReadTool(executor, options = {}) {
90
90
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
91
91
  const securityContext = options.securityContext ?? {
92
92
  workspaceDir: process.cwd(),
93
- workspacePath: process.cwd(),
94
93
  cwd: process.cwd(),
95
94
  };
96
95
  return {
@@ -138,7 +137,7 @@ export function createReadTool(executor, options = {}) {
138
137
  if (isPdf) {
139
138
  const converted = await executor.exec(`pdftotext -layout ${shellEscape(path)} - 2>&1`, { signal });
140
139
  if (converted.code === 127) {
141
- throw new Error(`Cannot read ${path}: pdftotext is not installed. Install poppler-utils (host) or rebuild the Docker sandbox image, or ask the user to send a text version.`);
140
+ throw new Error(`Cannot read ${path}: pdftotext is not installed. Install poppler-utils, or ask the user to send a text version.`);
142
141
  }
143
142
  if (converted.code !== 0 || !converted.stdout.trim()) {
144
143
  throw new Error(`Cannot read .pdf file ${path}: ${converted.stdout.trim() || "conversion produced no text"}. ` +
@@ -1,8 +1,8 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
+ import type { Executor } from "../executor.js";
4
5
  import type { MemoryCandidateStore } from "../memory/candidates.js";
5
- import type { Executor } from "../sandbox.js";
6
6
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
7
7
  import type { PipiclawSessionSearchSettings } from "../settings.js";
8
8
  import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
@@ -22,7 +22,6 @@ export interface ToolBuildContext {
22
22
  channelId: string;
23
23
  channelDir: string;
24
24
  workspaceDir: string;
25
- workspacePath: string;
26
25
  /** Main set: `toolsConfig.tools.web`; sub-agent set: the sub-agent's own webConfig. */
27
26
  webConfig?: PipiclawWebToolsConfig;
28
27
  /** Present only on the main path; gates session_search / memory_manage / skills. */