@oyasmi/pipiclaw 0.7.7 → 0.8.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 (114) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/channel-runner.d.ts +4 -4
  3. package/dist/agent/channel-runner.js +25 -23
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/job-manager.d.ts +5 -5
  6. package/dist/agent/prompt-builder.d.ts +3 -13
  7. package/dist/agent/prompt-builder.js +49 -159
  8. package/dist/agent/run-queue.js +2 -1
  9. package/dist/agent/runner-factory.d.ts +1 -2
  10. package/dist/agent/runner-factory.js +2 -2
  11. package/dist/agent/status-render.d.ts +0 -7
  12. package/dist/agent/status-render.js +8 -3
  13. package/dist/agent/types.d.ts +2 -0
  14. package/dist/agent/workspace-resources.d.ts +1 -1
  15. package/dist/agent/workspace-resources.js +3 -15
  16. package/dist/executor.d.ts +20 -0
  17. package/dist/{sandbox.js → executor.js} +3 -95
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/log.d.ts +1 -1
  21. package/dist/log.js +1 -2
  22. package/dist/memory/files.js +0 -0
  23. package/dist/memory/lifecycle.js +6 -5
  24. package/dist/memory/maintenance-jobs.d.ts +0 -1
  25. package/dist/memory/maintenance-jobs.js +2 -2
  26. package/dist/memory/maintenance-state.js +2 -1
  27. package/dist/memory/post-turn-review.d.ts +0 -1
  28. package/dist/memory/post-turn-review.js +4 -4
  29. package/dist/memory/scheduler.d.ts +0 -1
  30. package/dist/memory/scheduler.js +2 -2
  31. package/dist/memory/session.js +2 -2
  32. package/dist/memory/task-digest.js +17 -0
  33. package/dist/paths.d.ts +2 -0
  34. package/dist/paths.js +11 -0
  35. package/dist/playbooks/catalog.d.ts +9 -0
  36. package/dist/playbooks/catalog.js +44 -0
  37. package/dist/playbooks/event-scheduling.md +43 -0
  38. package/dist/playbooks/memory-and-learning.md +45 -0
  39. package/dist/playbooks/runtime-orientation.md +48 -0
  40. package/dist/playbooks/task-closeout.md +45 -0
  41. package/dist/playbooks/task-delegation.md +44 -0
  42. package/dist/playbooks/task-driving.md +43 -0
  43. package/dist/playbooks/task-planning.md +47 -0
  44. package/dist/playbooks/task-recurring.md +42 -0
  45. package/dist/playbooks/task-repair.md +43 -0
  46. package/dist/runtime/bootstrap.d.ts +12 -11
  47. package/dist/runtime/bootstrap.js +81 -57
  48. package/dist/runtime/delivery.js +4 -3
  49. package/dist/runtime/dingtalk.d.ts +2 -0
  50. package/dist/runtime/dingtalk.js +15 -14
  51. package/dist/runtime/durable-dispatch.d.ts +30 -0
  52. package/dist/runtime/durable-dispatch.js +172 -0
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +5 -3
  55. package/dist/runtime/events.js +17 -13
  56. package/dist/runtime/task-commands.d.ts +6 -0
  57. package/dist/runtime/task-commands.js +292 -6
  58. package/dist/runtime/task-driver.d.ts +32 -0
  59. package/dist/runtime/task-driver.js +268 -0
  60. package/dist/security/config.js +2 -1
  61. package/dist/security/network.js +9 -2
  62. package/dist/security/path-guard.js +12 -24
  63. package/dist/security/types.d.ts +0 -1
  64. package/dist/settings.d.ts +12 -0
  65. package/dist/settings.js +30 -0
  66. package/dist/shared/jsonl-appender.js +2 -1
  67. package/dist/shared/task-ledger.d.ts +35 -0
  68. package/dist/shared/task-ledger.js +229 -15
  69. package/dist/shared/text-utils.d.ts +1 -0
  70. package/dist/shared/text-utils.js +3 -0
  71. package/dist/subagents/discovery.js +3 -2
  72. package/dist/subagents/tool.d.ts +15 -3
  73. package/dist/subagents/tool.js +194 -17
  74. package/dist/tasks/artifact-subject.d.ts +6 -0
  75. package/dist/tasks/artifact-subject.js +29 -0
  76. package/dist/tasks/control.d.ts +83 -0
  77. package/dist/tasks/control.js +293 -0
  78. package/dist/tasks/store.d.ts +32 -0
  79. package/dist/tasks/store.js +142 -0
  80. package/dist/tasks/verification.d.ts +23 -0
  81. package/dist/tasks/verification.js +69 -0
  82. package/dist/tools/bash.d.ts +1 -1
  83. package/dist/tools/bash.js +3 -5
  84. package/dist/tools/command-optimizer.d.ts +1 -1
  85. package/dist/tools/command-optimizer.js +4 -6
  86. package/dist/tools/config.js +4 -3
  87. package/dist/tools/edit.d.ts +1 -1
  88. package/dist/tools/edit.js +0 -0
  89. package/dist/tools/event-manage.d.ts +0 -1
  90. package/dist/tools/event-manage.js +9 -14
  91. package/dist/tools/grep.d.ts +1 -1
  92. package/dist/tools/grep.js +4 -6
  93. package/dist/tools/index.d.ts +1 -3
  94. package/dist/tools/index.js +1 -4
  95. package/dist/tools/read.d.ts +1 -1
  96. package/dist/tools/read.js +1 -2
  97. package/dist/tools/registry.d.ts +2 -3
  98. package/dist/tools/registry.js +5 -11
  99. package/dist/tools/skill-manage.d.ts +0 -1
  100. package/dist/tools/skill-manage.js +7 -14
  101. package/dist/tools/task-manage.d.ts +37 -4
  102. package/dist/tools/task-manage.js +398 -39
  103. package/dist/tools/write-content.d.ts +1 -1
  104. package/dist/tools/write-content.js +0 -1
  105. package/dist/tools/write.d.ts +1 -1
  106. package/dist/tui/app.d.ts +0 -2
  107. package/dist/tui/app.js +12 -7
  108. package/dist/tui/cli.d.ts +0 -2
  109. package/dist/tui/cli.js +3 -25
  110. package/dist/tui/turn-controller.d.ts +7 -3
  111. package/dist/tui/turn-controller.js +9 -6
  112. package/dist/web/client.js +2 -1
  113. package/package.json +2 -2
  114. package/dist/sandbox.d.ts +0 -42
@@ -3,12 +3,12 @@ const channelRunners = new Map();
3
3
  function runnerKey(paths, channelId, channelDir) {
4
4
  return `${paths.appHomeDir}\0${channelDir}\0${channelId}`;
5
5
  }
6
- export function getOrCreateRunner(sandboxConfig, channelId, channelDir, paths) {
6
+ export function getOrCreateRunner(channelId, channelDir, paths) {
7
7
  const key = runnerKey(paths, channelId, channelDir);
8
8
  const existing = channelRunners.get(key);
9
9
  if (existing)
10
10
  return existing;
11
- const runner = new ChannelRunner(sandboxConfig, channelId, channelDir, paths);
11
+ const runner = new ChannelRunner(channelId, channelDir, paths);
12
12
  channelRunners.set(key, runner);
13
13
  return runner;
14
14
  }
@@ -1,9 +1,3 @@
1
- /**
2
- * `/status` rendering. Extracted verbatim from `runtime/bootstrap.ts` so both
3
- * the DingTalk runtime and the terminal TUI can render the same status block
4
- * from an `AgentRunner` status snapshot. Pure functions, no side effects.
5
- */
6
- import type { SandboxConfig } from "../sandbox.js";
7
1
  import type { AgentRunner } from "./types.js";
8
2
  /** Minimal per-channel run state the status renderer needs. */
9
3
  export interface StatusRenderState {
@@ -15,7 +9,6 @@ export interface RenderStatusOptions {
15
9
  state: StatusRenderState | undefined;
16
10
  version: string;
17
11
  uptimeMs: number;
18
- sandbox: SandboxConfig;
19
12
  }
20
13
  export declare function formatTokenCount(count: number): string;
21
14
  export declare function formatUptime(ms: number): string;
@@ -1,3 +1,9 @@
1
+ /**
2
+ * `/status` rendering. Extracted verbatim from `runtime/bootstrap.ts` so both
3
+ * the DingTalk runtime and the terminal TUI can render the same status block
4
+ * from an `AgentRunner` status snapshot. Pure functions, no side effects.
5
+ */
6
+ import { errorMessage } from "../shared/text-utils.js";
1
7
  export function formatTokenCount(count) {
2
8
  if (count < 1000)
3
9
  return count.toString();
@@ -19,7 +25,7 @@ export function formatUptime(ms) {
19
25
  return parts.join(" ");
20
26
  }
21
27
  export function renderStatus(options) {
22
- const { state, version, uptimeMs, sandbox } = options;
28
+ const { state, version, uptimeMs } = options;
23
29
  const lines = ["# Status"];
24
30
  if (state?.running) {
25
31
  const task = state.currentTaskText?.trim();
@@ -48,13 +54,12 @@ export function renderStatus(options) {
48
54
  }
49
55
  }
50
56
  catch (err) {
51
- lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
57
+ lines.push(`- Model: unavailable (${errorMessage(err)})`);
52
58
  }
53
59
  }
54
60
  else {
55
61
  lines.push("- Model: no session started for this channel yet");
56
62
  }
57
- lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
58
63
  lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
59
64
  lines.push(`- Version: ${version}`);
60
65
  return lines.join("\n");
@@ -18,6 +18,8 @@ export interface AgentRunner {
18
18
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
19
19
  stopReason: string;
20
20
  errorMessage?: string;
21
+ usage?: UsageTotals;
22
+ durationMs?: number;
21
23
  }>;
22
24
  handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
23
25
  queueSteer(text: string, userName?: string): Promise<void>;
@@ -16,4 +16,4 @@ export declare function getAgentConfig(channelDir: string): string;
16
16
  /**
17
17
  * Load skills from the workspace-level skill directory only.
18
18
  */
19
- export declare function loadPipiclawSkills(channelDir: string, workspacePath: string): Skill[];
19
+ export declare function loadPipiclawSkills(channelDir: string): Skill[];
@@ -46,19 +46,7 @@ export function getAgentConfig(channelDir) {
46
46
  /**
47
47
  * Load skills from the workspace-level skill directory only.
48
48
  */
49
- export function loadPipiclawSkills(channelDir, workspacePath) {
50
- const hostWorkspacePath = join(channelDir, "..");
51
- const translatePath = (hostPath) => {
52
- if (hostPath.startsWith(hostWorkspacePath)) {
53
- return workspacePath + hostPath.slice(hostWorkspacePath.length);
54
- }
55
- return hostPath;
56
- };
57
- const workspaceSkillsDir = join(hostWorkspacePath, "skills");
58
- const skills = loadSkillsFromDir({ dir: workspaceSkillsDir, source: "workspace" }).skills;
59
- for (const skill of skills) {
60
- skill.filePath = translatePath(skill.filePath);
61
- skill.baseDir = translatePath(skill.baseDir);
62
- }
63
- return skills;
49
+ export function loadPipiclawSkills(channelDir) {
50
+ const workspaceSkillsDir = join(channelDir, "..", "skills");
51
+ return loadSkillsFromDir({ dir: workspaceSkillsDir, source: "workspace" }).skills;
64
52
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Create an executor that runs commands on the host machine.
3
+ */
4
+ export declare function createExecutor(): Executor;
5
+ export interface Executor {
6
+ /**
7
+ * Execute a bash command
8
+ */
9
+ exec(command: string, options?: ExecOptions): Promise<ExecResult>;
10
+ }
11
+ export interface ExecOptions {
12
+ timeout?: number;
13
+ signal?: AbortSignal;
14
+ stdin?: string;
15
+ }
16
+ export interface ExecResult {
17
+ stdout: string;
18
+ stderr: string;
19
+ code: number;
20
+ }
@@ -1,82 +1,9 @@
1
1
  import { spawn } from "child_process";
2
- import { shellEscape } from "./shared/shell-escape.js";
3
2
  /**
4
- * Error raised when sandbox configuration is invalid or the target sandbox is not
5
- * usable. Thrown instead of calling process.exit so callers (bootstrap) decide how
6
- * to surface it and the functions stay testable.
3
+ * Create an executor that runs commands on the host machine.
7
4
  */
8
- export class SandboxConfigError extends Error {
9
- constructor(message) {
10
- super(message);
11
- this.name = "SandboxConfigError";
12
- }
13
- }
14
- export function parseSandboxArg(value) {
15
- if (value === "host") {
16
- return { type: "host" };
17
- }
18
- if (value.startsWith("docker:")) {
19
- const container = value.slice("docker:".length);
20
- if (!container) {
21
- throw new SandboxConfigError("docker sandbox requires container name (e.g., docker:pipiclaw-sandbox)");
22
- }
23
- return { type: "docker", container };
24
- }
25
- throw new SandboxConfigError(`Invalid sandbox type '${value}'. Use 'host' or 'docker:<container-name>'`);
26
- }
27
- export async function validateSandbox(config) {
28
- if (config.type === "host") {
29
- return;
30
- }
31
- // Check if Docker is available
32
- try {
33
- await execSimple("docker", ["--version"]);
34
- }
35
- catch {
36
- throw new SandboxConfigError("Docker is not installed or not in PATH");
37
- }
38
- // Check if container exists and is running
39
- let running;
40
- try {
41
- running = await execSimple("docker", ["inspect", "-f", "{{.State.Running}}", config.container]);
42
- }
43
- catch {
44
- throw new SandboxConfigError(`Container '${config.container}' does not exist.\nCreate it with: ./docker.sh create <data-dir>`);
45
- }
46
- if (running.trim() !== "true") {
47
- throw new SandboxConfigError(`Container '${config.container}' is not running.\nStart it with: docker start ${config.container}`);
48
- }
49
- console.log(` Docker container '${config.container}' is running.`);
50
- }
51
- function execSimple(cmd, args) {
52
- return new Promise((resolve, reject) => {
53
- const child = spawn(cmd, args, {
54
- stdio: ["ignore", "pipe", "pipe"],
55
- });
56
- let stdout = "";
57
- let stderr = "";
58
- child.stdout?.on("data", (d) => {
59
- stdout += d;
60
- });
61
- child.stderr?.on("data", (d) => {
62
- stderr += d;
63
- });
64
- child.on("close", (code) => {
65
- if (code === 0)
66
- resolve(stdout);
67
- else
68
- reject(new Error(stderr || `Exit code ${code}`));
69
- });
70
- });
71
- }
72
- /**
73
- * Create an executor that runs commands either on host or in Docker container
74
- */
75
- export function createExecutor(config) {
76
- if (config.type === "host") {
77
- return new HostExecutor();
78
- }
79
- return new DockerExecutor(config.container);
5
+ export function createExecutor() {
6
+ return new HostExecutor();
80
7
  }
81
8
  class HostExecutor {
82
9
  async exec(command, options) {
@@ -178,25 +105,6 @@ class HostExecutor {
178
105
  }
179
106
  });
180
107
  }
181
- getWorkspacePath(hostPath) {
182
- return hostPath;
183
- }
184
- }
185
- class DockerExecutor {
186
- constructor(container) {
187
- this.container = container;
188
- }
189
- async exec(command, options) {
190
- // Wrap command for docker exec
191
- const interactive = options?.stdin !== undefined ? "-i " : "";
192
- const dockerCmd = `docker exec ${interactive}${this.container} sh -c ${shellEscape(command)}`;
193
- const hostExecutor = new HostExecutor();
194
- return hostExecutor.exec(dockerCmd, options);
195
- }
196
- getWorkspacePath(_hostPath) {
197
- // Docker container sees /workspace
198
- return "/workspace";
199
- }
200
108
  }
201
109
  function killProcessTree(pid) {
202
110
  try {
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { type BuiltInCommand, type BuiltInCommandName, parseBuiltInCommand, rend
3
3
  export { type AgentRunner, getOrCreateRunner } from "./agent/index.js";
4
4
  export { type AppendSystemPromptOptions, buildAppendSystemPrompt } from "./agent/prompt-builder.js";
5
5
  export { getAgentConfig, getSoul, loadPipiclawSkills, } from "./agent/workspace-resources.js";
6
+ export { createExecutor, type ExecOptions, type ExecResult, type Executor } from "./executor.js";
6
7
  export { type BuildMemoryCandidatesOptions, buildMemoryCandidates, createMemoryCandidateStore, type MemoryCandidate, type MemoryCandidateStore, } from "./memory/candidates.js";
7
8
  export { type ConsolidationRunOptions, type InlineConsolidationResult, runInlineConsolidation, } from "./memory/consolidation.js";
8
9
  export { ensureChannelMemoryFiles, ensureChannelMemoryFilesSync, getChannelSessionPath, readChannelSession, rewriteChannelSession, } from "./memory/files.js";
@@ -19,7 +20,6 @@ export { createDingTalkContext } from "./runtime/delivery.js";
19
20
  export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
20
21
  export { createEventsWatcher, type EventAction, EventsWatcher, type ImmediateEvent, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
21
22
  export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
22
- export { createExecutor, type ExecOptions, type ExecResult, type Executor, parseSandboxArg, type SandboxConfig, validateSandbox, } from "./sandbox.js";
23
23
  export { type PipiclawMemoryGrowthSettings, type PipiclawMemoryMaintenanceSettings, type PipiclawMemoryRecallSettings, type PipiclawSessionMemorySettings, type PipiclawSettings, PipiclawSettingsManager, } from "./settings.js";
24
24
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
25
25
  export { createSubAgentTool, type SubAgentToolDetails, type SubAgentToolOptions, } from "./subagents/tool.js";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ export { parseBuiltInCommand, renderBuiltInHelp, } from "./agent/commands.js";
3
3
  export { getOrCreateRunner } from "./agent/index.js";
4
4
  export { buildAppendSystemPrompt } from "./agent/prompt-builder.js";
5
5
  export { getAgentConfig, getSoul, loadPipiclawSkills, } from "./agent/workspace-resources.js";
6
+ export { createExecutor } from "./executor.js";
6
7
  export { buildMemoryCandidates, createMemoryCandidateStore, } from "./memory/candidates.js";
7
8
  export { runInlineConsolidation, } from "./memory/consolidation.js";
8
9
  export { ensureChannelMemoryFiles, ensureChannelMemoryFilesSync, getChannelSessionPath, readChannelSession, rewriteChannelSession, } from "./memory/files.js";
@@ -18,7 +19,6 @@ export { createDingTalkContext } from "./runtime/delivery.js";
18
19
  export { DingTalkBot, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, } from "./runtime/dingtalk.js";
19
20
  export { createEventsWatcher, EventsWatcher, } from "./runtime/events.js";
20
21
  export { ChannelStore } from "./runtime/store.js";
21
- export { createExecutor, parseSandboxArg, validateSandbox, } from "./sandbox.js";
22
22
  export { PipiclawSettingsManager, } from "./settings.js";
23
23
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, resolveSubAgentConfig, } from "./subagents/discovery.js";
24
24
  export { createSubAgentTool, } from "./subagents/tool.js";
package/dist/log.d.ts CHANGED
@@ -57,5 +57,5 @@ export declare function logUsageSummary(ctx: LogContext, usage: {
57
57
  total: number;
58
58
  };
59
59
  }, contextTokens?: number, contextWindow?: number): string;
60
- export declare function logStartup(workingDir: string, sandbox: string): void;
60
+ export declare function logStartup(workingDir: string): void;
61
61
  export declare function logConnected(): void;
package/dist/log.js CHANGED
@@ -288,10 +288,9 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
288
288
  return summary;
289
289
  }
290
290
  // Startup
291
- export function logStartup(workingDir, sandbox) {
291
+ export function logStartup(workingDir) {
292
292
  con("Starting pipiclaw...");
293
293
  con(` Working directory: ${workingDir}`);
294
- con(` Sandbox: ${sandbox}`);
295
294
  }
296
295
  export function logConnected() {
297
296
  con("⚡️ pipiclaw connected and listening!");
Binary file
@@ -1,4 +1,5 @@
1
1
  import * as log from "../log.js";
2
+ import { errorMessage } from "../shared/text-utils.js";
2
3
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
3
4
  import { runInlineConsolidation, } from "./consolidation.js";
4
5
  import { appendMemoryReviewLog } from "./review-log.js";
@@ -103,7 +104,7 @@ export class MemoryLifecycle {
103
104
  return true;
104
105
  }
105
106
  catch (error) {
106
- const message = error instanceof Error ? error.message : String(error);
107
+ const message = errorMessage(error);
107
108
  log.logWarning(`[${this.options.channelId}] Session memory update failed (${reason})`, message);
108
109
  return false;
109
110
  }
@@ -142,7 +143,7 @@ export class MemoryLifecycle {
142
143
  });
143
144
  }
144
145
  catch (error) {
145
- const message = error instanceof Error ? error.message : String(error);
146
+ const message = errorMessage(error);
146
147
  log.logWarning(`[${this.options.channelId}] Failed to write memory review log`, message);
147
148
  }
148
149
  }
@@ -194,7 +195,7 @@ export class MemoryLifecycle {
194
195
  await this.recordConsolidationReview(reason, result);
195
196
  }
196
197
  catch (error) {
197
- const message = error instanceof Error ? error.message : String(error);
198
+ const message = errorMessage(error);
198
199
  log.logWarning(`[${this.options.channelId}] Memory consolidation failed (${reason})`, message);
199
200
  await this.appendReviewLog({
200
201
  reason,
@@ -224,7 +225,7 @@ export class MemoryLifecycle {
224
225
  // and logs its own errors, and the serial queue keeps this from racing with
225
226
  // idle/maintenance work on the same channel.
226
227
  this.backgroundNewSessionConsolidation = this.runPreflightConsolidation("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
227
- const message = error instanceof Error ? error.message : String(error);
228
+ const message = errorMessage(error);
228
229
  log.logWarning(`[${this.options.channelId}] Background new-session consolidation rejected`, message);
229
230
  });
230
231
  }
@@ -251,7 +252,7 @@ export class MemoryLifecycle {
251
252
  void this.options.recordMemoryActivity?.(event);
252
253
  }
253
254
  catch (error) {
254
- const message = error instanceof Error ? error.message : String(error);
255
+ const message = errorMessage(error);
255
256
  log.logWarning(`[${this.options.channelId}] Failed to record memory activity`, message);
256
257
  }
257
258
  }
@@ -28,7 +28,6 @@ export interface DurableConsolidationJobInput extends BaseMaintenanceJobInput {
28
28
  }
29
29
  export interface GrowthReviewJobInput extends BaseMaintenanceJobInput {
30
30
  workspaceDir: string;
31
- workspacePath: string;
32
31
  loadedSkills: Array<{
33
32
  name: string;
34
33
  description?: string;
@@ -1,3 +1,4 @@
1
+ import { errorMessage } from "../shared/text-utils.js";
1
2
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
2
3
  import { cleanupChannelMemory, foldChannelHistory, getStructuralMaintenanceStats, runInlineConsolidation, } from "./consolidation.js";
3
4
  import { readChannelHistory, readChannelMemory } from "./files.js";
@@ -88,7 +89,7 @@ function failed(jobKind, error) {
88
89
  jobKind,
89
90
  ran: false,
90
91
  skipped: false,
91
- error: error instanceof Error ? error.message : String(error),
92
+ error: errorMessage(error),
92
93
  };
93
94
  }
94
95
  async function runQueued(input, job) {
@@ -218,7 +219,6 @@ export async function runGrowthReviewJob(input) {
218
219
  channelId: input.channelId,
219
220
  channelDir: input.channelDir,
220
221
  workspaceDir: input.workspaceDir,
221
- workspacePath: input.workspacePath,
222
222
  messages: input.messages,
223
223
  model: input.model,
224
224
  resolveApiKey: input.resolveApiKey,
@@ -3,6 +3,7 @@ import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
5
  import { createSerialQueue } from "../shared/serial-queue.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
6
7
  const stateUpdateQueue = createSerialQueue();
7
8
  export function getMemoryMaintenanceStateDir(appHomeDir) {
8
9
  return join(appHomeDir, "state", "memory");
@@ -68,7 +69,7 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
68
69
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
69
70
  return createDefaultState(channelId);
70
71
  }
71
- const message = error instanceof Error ? error.message : String(error);
72
+ const message = errorMessage(error);
72
73
  log.logWarning(`[${channelId}] Failed to read memory maintenance state; rebuilding defaults`, message);
73
74
  return createDefaultState(channelId);
74
75
  }
@@ -5,7 +5,6 @@ export interface PostTurnReviewOptions {
5
5
  channelId: string;
6
6
  channelDir: string;
7
7
  workspaceDir: string;
8
- workspacePath: string;
9
8
  messages: AgentMessage[];
10
9
  model: Model<Api>;
11
10
  resolveApiKey: (model: Model<Api>) => Promise<string>;
@@ -1,6 +1,6 @@
1
1
  import { serializeConversation } from "@earendil-works/pi-coding-agent";
2
2
  import { parseJsonObject } from "../shared/llm-json.js";
3
- import { clipText } from "../shared/text-utils.js";
3
+ import { clipText, errorMessage } from "../shared/text-utils.js";
4
4
  import { isRecord } from "../shared/type-guards.js";
5
5
  import { manageWorkspaceSkill } from "../tools/skill-manage.js";
6
6
  import { appendChannelMemoryUpdate, readChannelHistory, readChannelMemory, readChannelSession } from "./files.js";
@@ -171,7 +171,7 @@ async function applySkillCandidate(options, candidate, result) {
171
171
  return;
172
172
  }
173
173
  try {
174
- const managed = await manageWorkspaceSkill({ workspaceDir: options.workspaceDir, workspacePath: options.workspacePath }, {
174
+ const managed = await manageWorkspaceSkill({ workspaceDir: options.workspaceDir }, {
175
175
  action: candidate.action,
176
176
  name: candidate.name,
177
177
  content: candidate.content,
@@ -186,7 +186,7 @@ async function applySkillCandidate(options, candidate, result) {
186
186
  }
187
187
  }
188
188
  catch (error) {
189
- const message = error instanceof Error ? error.message : String(error);
189
+ const message = errorMessage(error);
190
190
  result.skipped.push({ type: "skill", candidate, reason: message });
191
191
  result.suggestions.push({ type: "skill", candidate, blockedReason: message });
192
192
  }
@@ -233,7 +233,7 @@ export async function runPostTurnReview(options) {
233
233
  return await applyPostTurnReviewResult(options, review);
234
234
  }
235
235
  catch (error) {
236
- const message = error instanceof Error ? error.message : String(error);
236
+ const message = errorMessage(error);
237
237
  await appendMemoryReviewLog(options.channelDir, {
238
238
  timestamp: new Date().toISOString(),
239
239
  channelId: options.channelId,
@@ -6,7 +6,6 @@ export interface MemoryMaintenanceRuntimeContext {
6
6
  channelId: string;
7
7
  channelDir: string;
8
8
  workspaceDir: string;
9
- workspacePath: string;
10
9
  messages: AgentMessage[];
11
10
  sessionEntries: SessionEntry[];
12
11
  model: Model<Api>;
@@ -1,6 +1,7 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { basename } from "node:path";
3
3
  import * as log from "../log.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
4
5
  import { runDurableConsolidationJob, runGrowthReviewJob, runSessionRefreshJob, runStructuralMaintenanceJob, } from "./maintenance-jobs.js";
5
6
  import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
6
7
  const DEFAULT_TICK_INTERVAL_MS = 60_000;
@@ -60,7 +61,7 @@ export class MemoryMaintenanceScheduler {
60
61
  }
61
62
  this.timer = setInterval(() => {
62
63
  void this.runOnce().catch((error) => {
63
- log.logWarning("Memory maintenance scheduler tick failed", error instanceof Error ? error.message : String(error));
64
+ log.logWarning("Memory maintenance scheduler tick failed", errorMessage(error));
64
65
  });
65
66
  }, this.options.intervalMs ?? DEFAULT_TICK_INTERVAL_MS);
66
67
  this.timer.unref?.();
@@ -137,7 +138,6 @@ export class MemoryMaintenanceScheduler {
137
138
  const growth = await runGrowthReviewJob({
138
139
  ...common,
139
140
  workspaceDir: context.workspaceDir,
140
- workspacePath: context.workspacePath,
141
141
  loadedSkills: context.loadedSkills,
142
142
  emitNotice: this.options.emitNotice
143
143
  ? async (notice) => this.options.emitNotice?.(channelId, notice)
@@ -3,7 +3,7 @@ import { writeFile } from "fs/promises";
3
3
  import { join } from "path";
4
4
  import { parseJsonObject } from "../shared/llm-json.js";
5
5
  import { splitH1Sections } from "../shared/markdown-sections.js";
6
- import { clipText } from "../shared/text-utils.js";
6
+ import { clipText, errorMessage } from "../shared/text-utils.js";
7
7
  import { isRecord } from "../shared/type-guards.js";
8
8
  import { readChannelMemory, readChannelSession, rewriteChannelSession } from "./files.js";
9
9
  import { runRetriedSidecarTask, SidecarParseError } from "./sidecar-worker.js";
@@ -199,7 +199,7 @@ async function writeSessionMemoryDebugFile(channelDir, error, rawText) {
199
199
  const debugPath = join(channelDir, "SESSION.invalid-response.txt");
200
200
  const header = [
201
201
  `timestamp: ${new Date().toISOString()}`,
202
- `error: ${error instanceof Error ? error.message : String(error)}`,
202
+ `error: ${errorMessage(error)}`,
203
203
  "",
204
204
  "raw response:",
205
205
  "",
@@ -17,6 +17,23 @@ function relativeWake(wakeMs, now) {
17
17
  function renderLine(entry, now) {
18
18
  const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
19
19
  const parts = [`${entry.id} — ${entry.title}`, status, relativeWake(entry.wakeMs, now)];
20
+ const control = entry.frontmatter.control;
21
+ if (control) {
22
+ parts.push(`priority ${control.priority}`);
23
+ parts.push(`attempt ${control.usage.attempts}/${control.budget.maxAttempts}`);
24
+ parts.push(`verify ${control.verification.mode}/${control.verification.status}`);
25
+ if (control.isolation !== "shared")
26
+ parts.push(`isolation ${control.isolation}`);
27
+ if (control.sideEffects !== "workspace") {
28
+ parts.push(`effects ${control.sideEffects}/${control.externalApproval}`);
29
+ }
30
+ if (control.deadline)
31
+ parts.push(`deadline ${control.deadline}`);
32
+ if (control.dependsOn.length > 0)
33
+ parts.push(`depends ${control.dependsOn.join(",")}`);
34
+ if (control.nextAction)
35
+ parts.push(`next ${control.nextAction}`);
36
+ }
20
37
  if (entry.latestNote) {
21
38
  const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
22
39
  parts.push(note);
package/dist/paths.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export declare const APP_NAME = "pipiclaw";
2
+ /** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
3
+ export declare const PLAYBOOKS_DIR: string;
2
4
  export declare const APP_HOME_DIR: string;
3
5
  export declare const WORKSPACE_DIR: string;
4
6
  export declare const STATE_DIR: string;
package/dist/paths.js CHANGED
@@ -1,6 +1,17 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { homedir } from "os";
2
3
  import { join } from "path";
4
+ import { fileURLToPath } from "url";
3
5
  export const APP_NAME = "pipiclaw";
6
+ /**
7
+ * Agent-facing playbooks bundled inside the installed package (src/playbooks
8
+ * in a checkout, dist/playbooks when built). Read-only runtime self-docs: the
9
+ * system prompt carries a small index and the agent reads them on demand.
10
+ */
11
+ const bundledPlaybooksDir = fileURLToPath(new URL("./playbooks", import.meta.url));
12
+ const checkoutPlaybooksDir = fileURLToPath(new URL("../src/playbooks", import.meta.url));
13
+ /** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
14
+ export const PLAYBOOKS_DIR = existsSync(checkoutPlaybooksDir) ? checkoutPlaybooksDir : bundledPlaybooksDir;
4
15
  export const APP_HOME_DIR = process.env.PIPICLAW_HOME ?? join(homedir(), ".pi", APP_NAME);
5
16
  export const WORKSPACE_DIR = join(APP_HOME_DIR, "workspace");
6
17
  export const STATE_DIR = join(APP_HOME_DIR, "state");
@@ -0,0 +1,9 @@
1
+ export interface RuntimePlaybookMetadata {
2
+ name: string;
3
+ description: string;
4
+ filename: string;
5
+ path: string;
6
+ }
7
+ /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
8
+ export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimePlaybookMetadata[];
9
+ export declare function renderRuntimePlaybookIndex(directory?: string): string;
@@ -0,0 +1,44 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { PLAYBOOKS_DIR } from "../paths.js";
4
+ function parseFrontmatter(content, filename) {
5
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
6
+ if (!match)
7
+ throw new Error(`Runtime playbook ${filename} has no YAML frontmatter.`);
8
+ const fields = new Map();
9
+ for (const line of match[1]?.split(/\r?\n/) ?? []) {
10
+ const separator = line.indexOf(":");
11
+ if (separator < 0)
12
+ continue;
13
+ const key = line.slice(0, separator).trim();
14
+ let value = line.slice(separator + 1).trim();
15
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
16
+ value = value.slice(1, -1);
17
+ }
18
+ fields.set(key, value);
19
+ }
20
+ const name = fields.get("name")?.trim();
21
+ const description = fields.get("description")?.trim();
22
+ if (!name || !description) {
23
+ throw new Error(`Runtime playbook ${filename} requires non-empty name and description metadata.`);
24
+ }
25
+ if (`${name}.md` !== filename) {
26
+ throw new Error(`Runtime playbook ${filename} metadata name must be "${basename(filename, ".md")}".`);
27
+ }
28
+ return { name, description };
29
+ }
30
+ /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
31
+ export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
32
+ return readdirSync(directory)
33
+ .filter((filename) => filename.endsWith(".md"))
34
+ .sort()
35
+ .map((filename) => {
36
+ const path = join(directory, filename);
37
+ return { ...parseFrontmatter(readFileSync(path, "utf-8"), filename), filename, path };
38
+ });
39
+ }
40
+ export function renderRuntimePlaybookIndex(directory = PLAYBOOKS_DIR) {
41
+ return loadRuntimePlaybookCatalog(directory)
42
+ .map((playbook) => `- ${playbook.filename} — ${playbook.description}`)
43
+ .join("\n");
44
+ }
@@ -0,0 +1,43 @@
1
+ ---
2
+ name: event-scheduling
3
+ description: Read before creating, updating, diagnosing, or retiring reminders, one-shot wakeups, periodic schedules, preAction gates, or background-job check-ins.
4
+ ---
5
+
6
+ # 事件与调度
7
+
8
+ 事件负责“什么时候唤醒”,不是长程工作的完整状态。可验收、需积累步骤的工作用 task;纯提醒或外部条件探测才单独用 event。
9
+
10
+ ## 选择类型
11
+
12
+ - 当前回合立即能做:直接做,不建 immediate。`event_manage` 会拒绝 immediate,防止自触发循环。
13
+ - 将来某时只提醒一次:one-shot,至少提前 2 分钟。
14
+ - 固定节奏重复提醒/检查:periodic,五段 cron + timezone。
15
+ - 周期性产出任务:task + canonical `.schedule`,见 `task-recurring.md`。
16
+
17
+ 优先使用 `event_manage`,它会验证 JSON、channel、时间间隔、preAction command guard 和总量。工具不可用时才直接维护 `events/*.json`;无效文件可能被 scheduler 忽略。
18
+
19
+ ## 基本定义
20
+
21
+ ```json
22
+ {"type":"one-shot","channelId":"<当前channel>","text":"检查处理结果","at":"2026-07-12T10:00:00+08:00"}
23
+ ```
24
+
25
+ ```json
26
+ {"type":"periodic","channelId":"<当前channel>","text":"执行工作日巡检","schedule":"0 9 * * 1-5","timezone":"Asia/Shanghai"}
27
+ ```
28
+
29
+ 普通 periodic 最小间隔 30 分钟;带 preAction gate 时最小 5 分钟;事件总数上限 50。任务拥有的事件使用 `task.<channelId>.<taskId>.<use>`,便于闭环清理。
30
+
31
+ ## preAction 是传感器,不是工作流
32
+
33
+ preAction 的 bash 命令退出 0 才唤醒 agent,非 0 静默跳过。它适合调用用户已经安装、稳定可执行的工具来检测外部条件。不要在 runtime playbook 中捆绑第三方工具脚本,也不要把来源不明的脚本复制进 workspace。
34
+
35
+ 如果某个工具(例如 agentmux)需要完成态检测,由用户层对应 skill/可执行文件定义命令和状态语义;Pipiclaw 只负责运行经过 command guard 的 preAction。
36
+
37
+ 传感器应使用 periodic:one-shot 即使 gate 未通过也会被消费。任何传感器都要有退出条件和合理频率;task-owned 传感器还要保留任务 `wake` 兜底,避免永久静默或空转。
38
+
39
+ ## 后台 job 的回访
40
+
41
+ 短等待直接 `job poll`。不能在当前回合等待时,按预计完成时间建 one-shot 回访;需要条件检测时才用 periodic + preAction。回访后删除临时事件。
42
+
43
+ 周期事件无新结果时只回复 `[SILENT]`,避免发送空状态卡。更新事件时整体替换 definition;不再需要时及时删除,并用 `/events history` 排查触发与 gate 结果。