@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -1,9 +1,10 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
- import { join, resolve, sep } from "path";
3
+ import { join } from "path";
4
4
  import { renderSubcommandUsage } from "../agent/commands.js";
5
5
  import { capReply } from "../agent/reply-limits.js";
6
- import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
6
+ import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
+ import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
7
8
  import { parseScheduledEventContent } from "./events.js";
8
9
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
9
10
  const DEFAULT_HISTORY_LIMIT = 20;
@@ -41,28 +42,18 @@ export function parseEventsCommand(args) {
41
42
  function eventsDir(workspaceDir) {
42
43
  return join(workspaceDir, "events");
43
44
  }
45
+ const SAFE_ID_OPTIONS = { suffix: ".json", pattern: EVENT_NAME_PATTERN, label: "event name" };
44
46
  // English on purpose: shared with the model-facing `event_manage` tool (src/tools/event-manage.ts),
45
47
  // which follows the tool-error convention elsewhere in the codebase, not the command-reply one.
46
48
  export function normalizeEventName(name) {
47
- const trimmed = name.trim();
48
- const normalized = trimmed.endsWith(".json") ? trimmed.slice(0, -".json".length) : trimmed;
49
- if (!normalized || normalized === "." || normalized === ".." || !EVENT_NAME_PATTERN.test(normalized)) {
50
- throw new Error(`Invalid event name: ${name}`);
51
- }
52
- return normalized;
49
+ return normalizeSafeId(name, SAFE_ID_OPTIONS);
53
50
  }
54
51
  export function resolveEventPath(workspaceDir, name) {
55
- const eventName = normalizeEventName(name);
56
- const dir = resolve(eventsDir(workspaceDir));
57
- const eventPath = resolve(dir, `${eventName}.json`);
58
- if (eventPath !== join(dir, `${eventName}.json`) || !eventPath.startsWith(`${dir}${sep}`)) {
59
- throw new Error(`Invalid event name: ${name}`);
60
- }
52
+ const { id: eventName, path: eventPath } = resolveSafeIdPath(eventsDir(workspaceDir), name, SAFE_ID_OPTIONS);
61
53
  return { eventName, eventPath };
62
54
  }
63
55
  function clipText(text, maxChars = TEXT_PREVIEW_MAX_CHARS) {
64
- const normalized = text.replace(/\s+/g, " ").trim();
65
- return normalized.length > maxChars ? `${normalized.slice(0, maxChars - 1)}...` : normalized;
56
+ return sharedClipText(text, maxChars, { headRatio: 1, omitHint: "...", collapseWhitespace: true });
66
57
  }
67
58
  function formatEventSummary(name, event) {
68
59
  const lines = [`**${name}**`, `- 类型:${event.type}`, `- channelId:${event.channelId}`];
@@ -102,8 +102,10 @@ export declare class EventsWatcher {
102
102
  * by hand, and then wakes the channel forever about work that no longer exists. Checking the
103
103
  * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
104
104
  *
105
- * The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
106
- * from the event definition and only the task id is parsed out of the remainder.
105
+ * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
106
+ * owning channel is taken from the event definition and the id is parsed with the same
107
+ * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
108
+ * split that would cut a dotted task id short.
107
109
  */
108
110
  private orphanedOwnerReason;
109
111
  private execute;
@@ -4,11 +4,13 @@ import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
+ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
7
8
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
8
9
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
- import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
10
+ import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
+ import { isPlainObject } from "../shared/type-guards.js";
10
12
  import { parseTaskFrontmatter } from "../tasks/ledger.js";
11
- import { taskEventPrefix } from "../tasks/task-events.js";
13
+ import { parseTaskEventName } from "../tasks/task-events.js";
12
14
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
15
  // ============================================================================
14
16
  // EventsWatcher
@@ -20,13 +22,7 @@ const SCAN_CONCURRENCY = 4;
20
22
  const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
21
23
  const TEXT_PREVIEW_MAX_CHARS = 160;
22
24
  function truncateTextPreview(text) {
23
- const normalized = text.replace(/\s+/g, " ").trim();
24
- return normalized.length > TEXT_PREVIEW_MAX_CHARS
25
- ? `${normalized.slice(0, TEXT_PREVIEW_MAX_CHARS - 1)}…`
26
- : normalized;
27
- }
28
- function isRecord(value) {
29
- return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ return clipText(text, TEXT_PREVIEW_MAX_CHARS, { headRatio: 1, omitHint: "…", collapseWhitespace: true });
30
26
  }
31
27
  function readRequiredString(data, field, filename) {
32
28
  const value = data[field];
@@ -38,7 +34,7 @@ function readRequiredString(data, field, filename) {
38
34
  function parsePreAction(data, filename) {
39
35
  if (!data.preAction)
40
36
  return undefined;
41
- if (!isRecord(data.preAction)) {
37
+ if (!isPlainObject(data.preAction)) {
42
38
  throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
43
39
  }
44
40
  const action = data.preAction;
@@ -61,7 +57,7 @@ function parsePreAction(data, filename) {
61
57
  }
62
58
  export function parseScheduledEventContent(content, filename) {
63
59
  const data = JSON.parse(content);
64
- if (!isRecord(data)) {
60
+ if (!isPlainObject(data)) {
65
61
  throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
66
62
  }
67
63
  const type = readRequiredString(data, "type", filename);
@@ -479,17 +475,16 @@ export class EventsWatcher {
479
475
  * by hand, and then wakes the channel forever about work that no longer exists. Checking the
480
476
  * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
481
477
  *
482
- * The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
483
- * from the event definition and only the task id is parsed out of the remainder.
478
+ * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
479
+ * owning channel is taken from the event definition and the id is parsed with the same
480
+ * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
481
+ * split that would cut a dotted task id short.
484
482
  */
485
483
  async orphanedOwnerReason(filename, event) {
486
- const prefix = taskEventPrefix(event.channelId);
487
- const name = eventNameFromFilename(filename);
488
- if (!name.startsWith(prefix))
489
- return undefined;
490
- const taskId = name.slice(prefix.length).split(".")[0];
491
- if (!taskId)
484
+ const parsed = parseTaskEventName(eventNameFromFilename(filename), event.channelId);
485
+ if (!parsed)
492
486
  return undefined;
487
+ const taskId = parsed.id;
493
488
  const taskPath = join(dirname(this.eventsDir), event.channelId, "tasks", `${taskId}.md`);
494
489
  let content;
495
490
  try {
@@ -655,7 +650,7 @@ export class EventsWatcher {
655
650
  }
656
651
  markInvalid(filename, message) {
657
652
  try {
658
- writeFileSync(this.getInvalidMarkerPath(filename), [`timestamp: ${new Date().toISOString()}`, `file: ${filename}`, "", message.trim()].join("\n"), "utf-8");
653
+ writeFileAtomicallySync(this.getInvalidMarkerPath(filename), [`timestamp: ${formatLocalTime()}`, `file: ${filename}`, "", message.trim()].join("\n"));
659
654
  }
660
655
  catch (err) {
661
656
  log.logWarning(`Failed to write event error marker: ${filename}`, String(err));
@@ -213,7 +213,7 @@ async function showRun(channelId, ref) {
213
213
  lines.push("", "⚠ 派发时的警告:", ...record.invocationWarnings.map((warning) => `- ${warning}`));
214
214
  }
215
215
  if (record.sessionId)
216
- lines.push(`- sessionId:\`${record.sessionId}\`(可用于 subagent_manage op=follow_up)`);
216
+ lines.push(`- sessionId:\`${record.sessionId}\`(可用于 subagent_run op=follow_up)`);
217
217
  if (record.runtime === "external") {
218
218
  const stderrTail = await readFile(join(record.artifactDir, "stderr.log"), "utf-8")
219
219
  .then((text) => text.slice(-STDERR_TAIL_CHARS))
@@ -13,7 +13,7 @@ export interface HandleTasksCommandOptions {
13
13
  *
14
14
  * Deliberately a small, flat set: the ones a user already knows they want to change (when it
15
15
  * should wake, what it should do next, how much rope it has). Everything structural — status
16
- * transitions and verification — stays with `task_manage`, whose state
16
+ * transitions and verification — stays with `task_update`/`task_close`/`task_verify`, whose state
17
17
  * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
18
18
  */
19
19
  declare const SETTABLE_TASK_FIELDS: readonly ["wake", "next", "deadline"];
@@ -6,7 +6,7 @@ import { channelJobTaskIds } from "../agent/job-manager.js";
6
6
  import { capReply } from "../agent/reply-limits.js";
7
7
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
- import { channelDelegationTaskIds } from "../subagents/runs.js";
9
+ import { channelDelegationTaskIds, getSubAgentRunManager } from "../subagents/runs.js";
10
10
  import { applyTaskControlPatch, createDefaultTaskControl, taskBudgetViolation } from "../tasks/control.js";
11
11
  import { countTaskDodItems, extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
12
12
  import { withTaskMutation } from "../tasks/mutation-lock.js";
@@ -21,7 +21,7 @@ import { parseScheduledEventContent } from "./events.js";
21
21
  *
22
22
  * Deliberately a small, flat set: the ones a user already knows they want to change (when it
23
23
  * should wake, what it should do next, how much rope it has). Everything structural — status
24
- * transitions and verification — stays with `task_manage`, whose state
24
+ * transitions and verification — stays with `task_update`/`task_close`/`task_verify`, whose state
25
25
  * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
26
26
  */
27
27
  const SETTABLE_TASK_FIELDS = ["wake", "next", "deadline"];
@@ -279,7 +279,7 @@ export async function resumeTask(options, idInput) {
279
279
  * The alternative — telling the model "change wake to tomorrow 9am" — costs a whole turn and its
280
280
  * tokens to reach the same one-line write. Validation is not re-implemented here: `wake` reuses
281
281
  * the shared local-time parser (accepting a local timestamp or a relative offset like `+2h`) and
282
- * everything else goes through `applyTaskControlPatch`, the same function `task_manage set` uses,
282
+ * everything else goes through `applyTaskControlPatch`, the same function `task_update` (no note) uses,
283
283
  * so the two entry points cannot drift apart.
284
284
  */
285
285
  async function setTaskField(options, idInput, field, value) {
@@ -411,12 +411,12 @@ async function doctor(options) {
411
411
  continue;
412
412
  }
413
413
  if (entry.frontmatter.controlReadable === false) {
414
- issues.push(issue(`tasks/${entry.id}.md 的 control 元数据无效;治理机制 fail-open,但无法生效`, `用 task_manage set 或直接修复那一行 control JSON,然后再允许任务运行`));
414
+ issues.push(issue(`tasks/${entry.id}.md 的 control 元数据无效;治理机制 fail-open,但无法生效`, `用 task_update(不带 note)或直接修复那一行 control JSON,然后再允许任务运行`));
415
415
  continue;
416
416
  }
417
417
  const control = entry.frontmatter.control;
418
418
  if (!control && entry.frontmatter.enabled === false) {
419
- issues.push(issue(`tasks/${entry.id}.md 已停用,但完全没有 control.stop 回执`, `用 task_manage set 修复 control 元数据,确认可以继续后再 /tasks resume ${entry.id}`));
419
+ issues.push(issue(`tasks/${entry.id}.md 已停用,但完全没有 control.stop 回执`, `用 task_update(不带 note)修复 control 元数据,确认可以继续后再 /tasks resume ${entry.id}`));
420
420
  }
421
421
  if (control) {
422
422
  const storedTask = await readStoredTask(options.channelDir, entry.id);
@@ -425,19 +425,24 @@ async function doctor(options) {
425
425
  issues.push(issue(`tasks/${entry.id}.md 超出了它的 control 限额:${violation}`, `检查这个任务,明确提高 budget/deadline 或取消它;否则 driver 会升级处理`));
426
426
  }
427
427
  if (status !== "sleeping" && control.verification.status === "passed") {
428
+ const verificationRun = control.verification.runId && options.channelId
429
+ ? getSubAgentRunManager(options.channelId).get(control.verification.runId)
430
+ : undefined;
428
431
  const attestationOk = control.verification.runId
429
- ? await readVerificationAttestation(options.channelDir, control.verification.runId)
432
+ ? await readVerificationAttestation(options.channelDir, control.verification.runId, {
433
+ trustedWorkingDirectory: verificationRun?.workingDirectory,
434
+ })
430
435
  .then((attestation) => attestation.taskId === entry.id &&
431
436
  attestation.verdict === "pass" &&
432
437
  (!storedTask || attestation.bodyHash === taskBodyHash(storedTask.body)))
433
438
  .catch(() => false)
434
439
  : false;
435
440
  if (!attestationOk) {
436
- issues.push(issue(`tasks/${entry.id}.md 记录了一次独立 PASS,但磁盘上没有匹配且新鲜的验证 attestation`, `跑一次新的 purpose=verify 子代理,并用 task_manage verify 导入它的 attestation 后再完成`));
441
+ issues.push(issue(`tasks/${entry.id}.md 记录了一次独立 PASS,但磁盘上没有匹配且新鲜的验证 attestation`, `跑一次新的 purpose=verify 子代理,并用 task_verify 导入它的 attestation 后再完成`));
437
442
  }
438
443
  }
439
444
  if (entry.frontmatter.enabled === false && !control.stop) {
440
- issues.push(issue(`tasks/${entry.id}.md 已停用,但 control 里没有 stop 回执`, `先弄清是谁停用的,再 /tasks resume ${entry.id};或者用 task_manage set 写一条合法的 stop 记录`));
445
+ issues.push(issue(`tasks/${entry.id}.md 已停用,但 control 里没有 stop 回执`, `先弄清是谁停用的,再 /tasks resume ${entry.id};或者用 task_update(不带 note)写一条合法的 stop 记录`));
441
446
  }
442
447
  if (entry.frontmatter.enabled !== false && control.stop) {
443
448
  issues.push(issue(`tasks/${entry.id}.md 有 stop 回执,但 enabled 是 true`, `跑 /tasks resume ${entry.id} 清掉过期的 stop 回执,或者显式停用这个任务`));
@@ -445,7 +450,7 @@ async function doctor(options) {
445
450
  }
446
451
  const recurring = Boolean(entry.frontmatter.schedule);
447
452
  if (status === "sleeping" && !recurring) {
448
- issues.push(issue(`tasks/${entry.id}.md 处于 sleeping,但没有 recurring schedule`, `一次性任务用 task_manage complete/cancel 结束;要保留 sleeping 需要先加一个合法的 schedule`));
453
+ issues.push(issue(`tasks/${entry.id}.md 处于 sleeping,但没有 recurring schedule`, `一次性任务用 task_close outcome=complete/cancel 结束;要保留 sleeping 需要先加一个合法的 schedule`));
449
454
  }
450
455
  if (recurring) {
451
456
  try {
@@ -462,7 +467,7 @@ async function doctor(options) {
462
467
  entry.frontmatter.wake &&
463
468
  validWakeMs(entry) !== undefined &&
464
469
  validWakeMs(entry) > now) {
465
- issues.push(issue(`tasks/${entry.id}.md 处于 active,但它的 wake 在未来`, `用 task_manage set/progress 把它改成 waiting 且 waitingFor=time,或者清空 wake 让它现在继续`));
470
+ issues.push(issue(`tasks/${entry.id}.md 处于 active,但它的 wake 在未来`, `用 task_update 把它改成 waiting 且 waitingFor=time,或者清空 wake 让它现在继续`));
466
471
  }
467
472
  if (recurringTaskMissedOccurrence({ status, schedule: entry.frontmatter.schedule, control }, new Date(now))) {
468
473
  issues.push(issue(`tasks/${entry.id}.md 有一个已过下次 recurring 时点、仍处于 ${status} 的周期,且没有并行开启新周期`, `完成、跳过或取消 ${entry.id} 当前周期,之后让 driver 计算下一次时点`));
@@ -505,7 +510,7 @@ async function doctor(options) {
505
510
  }
506
511
  }
507
512
  if (entry.frontmatter.wake && validWakeMs(entry) === undefined) {
508
- issues.push(issue(`tasks/${entry.id}.md 的 wake 值无效(${entry.frontmatter.wake});原生 driver 会把它当成已到期处理`, `用 task_manage set 或 progress 把 wake 换成合法本地时间,或者清空它让任务直接继续`));
513
+ issues.push(issue(`tasks/${entry.id}.md 的 wake 值无效(${entry.frontmatter.wake});原生 driver 会把它当成已到期处理`, `用 task_update 把 wake 换成合法本地时间,或者清空它让任务直接继续`));
509
514
  }
510
515
  // A recurring task's wake should always be an occurrence of its own schedule. A wake that
511
516
  // isn't — a stale value left over from a since-changed cron, or a hand-typed local↔UTC
@@ -517,7 +522,7 @@ async function doctor(options) {
517
522
  if (wakeMs !== undefined) {
518
523
  const priorOccurrence = nextTaskWake(schedule, new Date(wakeMs - 1));
519
524
  if (priorOccurrence?.getTime() !== wakeMs) {
520
- issues.push(issue(`tasks/${entry.id}.md 的 wake(${formatLocalTime(new Date(wakeMs))})不是它 schedule "${schedule}" 的一个合法时点`, `跑 task_manage set schedule="${schedule}"(不变)用 cron 重新计算 wake,或者手动明确设置 wake`));
525
+ issues.push(issue(`tasks/${entry.id}.md 的 wake(${formatLocalTime(new Date(wakeMs))})不是它 schedule "${schedule}" 的一个合法时点`, `跑 task_update schedule="${schedule}"(不变)用 cron 重新计算 wake,或者手动明确设置 wake`));
521
526
  }
522
527
  }
523
528
  }
@@ -143,8 +143,8 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
143
143
  (repairOnly
144
144
  ? "After the metadata is repaired, leave task work for a later wake. "
145
145
  : "Advance the next concrete step under the task's current goal, control, acceptance, and verification state. ") +
146
- `If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook. ` +
147
- "For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_manage skip with the reason, then respond with exactly [SILENT]. " +
146
+ `If complete or waiting, use the matching task_close/task_update action from the playbook. ` +
147
+ "For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_close outcome=skip with the reason, then respond with exactly [SILENT]. " +
148
148
  "If no task state or tool action is needed and this wake produces no user-visible result, respond with exactly [SILENT].",
149
149
  ts: String(nowMs),
150
150
  conversationType: channelId.startsWith("group_") ? "2" : "1",
@@ -21,8 +21,8 @@ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, ta
21
21
  /**
22
22
  * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
23
23
  * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
24
- * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
25
- * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
24
+ * because it is published with the terminal record before usage/archive/wake side effects — the
25
+ * same idempotency guard the manager itself relies on. A pending settlement intent leaves it unset.
26
26
  */
27
27
  export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
28
28
  /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
@@ -23,8 +23,8 @@ export function isVerifiedJobWake(jobs, jobId, taskId) {
23
23
  /**
24
24
  * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
25
25
  * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
26
- * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
27
- * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
26
+ * because it is published with the terminal record before usage/archive/wake side effects — the
27
+ * same idempotency guard the manager itself relies on. A pending settlement intent leaves it unset.
28
28
  */
29
29
  export function isVerifiedDelegationWake(record, taskId) {
30
30
  return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
@@ -0,0 +1,11 @@
1
+ /** One `Label: value` line in a security-guard block message. */
2
+ export interface BlockMessageDetail {
3
+ label: string;
4
+ value: string;
5
+ }
6
+ /**
7
+ * Shared scaffold for a guard's user/model-facing block message: `"<Subject> blocked [category]"`
8
+ * followed by one line per detail. Used by both the path guard and the command guard so their
9
+ * wording does not drift line by line as each grows its own detail set.
10
+ */
11
+ export declare function formatBlockMessage(subject: string, category: string | undefined, details: BlockMessageDetail[]): string;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Shared scaffold for a guard's user/model-facing block message: `"<Subject> blocked [category]"`
3
+ * followed by one line per detail. Used by both the path guard and the command guard so their
4
+ * wording does not drift line by line as each grows its own detail set.
5
+ */
6
+ export function formatBlockMessage(subject, category, details) {
7
+ const lines = [`${subject} blocked${category ? ` [${category}]` : ""}`];
8
+ for (const detail of details) {
9
+ lines.push(`${detail.label}: ${detail.value}`);
10
+ }
11
+ return lines.join("\n");
12
+ }
@@ -0,0 +1,13 @@
1
+ import type { SecurityConfig, SecurityRuntimeContext } from "./types.js";
2
+ export interface PathGuardCheckOptions {
3
+ tool: string;
4
+ channelId?: string;
5
+ }
6
+ /**
7
+ * Run the path guard and return the single resolved path every file tool must operate on from
8
+ * here on (spec 044, D1.1) -- what the guard judged and what `FileStore`/`Executor` actually opens
9
+ * are the same value by construction, never re-derived. Always returns a `resolvedPath`, including
10
+ * when `security.json` has the guard disabled: resolution is normalization, not policy, so turning
11
+ * the guard off must not be the one case where a tool falls back to an unresolved raw path.
12
+ */
13
+ export declare function checkPathGuard(rawPath: string, operation: "read" | "write", securityConfig: SecurityConfig, securityContext: SecurityRuntimeContext, options: PathGuardCheckOptions): Promise<string>;
@@ -0,0 +1,39 @@
1
+ import { formatBlockMessage } from "./block-message.js";
2
+ import { logSecurityEvent } from "./logger.js";
3
+ import { guardPath } from "./path-guard.js";
4
+ function formatPathBlockMessage(resolvedPath, category, reason) {
5
+ const details = [];
6
+ if (reason)
7
+ details.push({ label: "Reason", value: reason });
8
+ if (resolvedPath)
9
+ details.push({ label: "Resolved path", value: resolvedPath });
10
+ return formatBlockMessage("Path", category, details);
11
+ }
12
+ /**
13
+ * Run the path guard and return the single resolved path every file tool must operate on from
14
+ * here on (spec 044, D1.1) -- what the guard judged and what `FileStore`/`Executor` actually opens
15
+ * are the same value by construction, never re-derived. Always returns a `resolvedPath`, including
16
+ * when `security.json` has the guard disabled: resolution is normalization, not policy, so turning
17
+ * the guard off must not be the one case where a tool falls back to an unresolved raw path.
18
+ */
19
+ export async function checkPathGuard(rawPath, operation, securityConfig, securityContext, options) {
20
+ const effectiveConfig = securityConfig.enabled
21
+ ? securityConfig.pathGuard
22
+ : { ...securityConfig.pathGuard, enabled: false };
23
+ const guardResult = guardPath(rawPath, operation, { ...securityContext, config: effectiveConfig });
24
+ if (!guardResult.allowed) {
25
+ await logSecurityEvent(securityContext.agentWorkspaceDir, securityConfig, {
26
+ type: "path",
27
+ tool: options.tool,
28
+ channelId: options.channelId,
29
+ rawPath,
30
+ operation,
31
+ resolvedPath: guardResult.resolvedPath,
32
+ category: guardResult.category,
33
+ reason: guardResult.reason,
34
+ });
35
+ throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
36
+ }
37
+ // `guardPath` always populates `resolvedPath` on an allowed result (see D1.1 above).
38
+ return guardResult.resolvedPath;
39
+ }
@@ -124,9 +124,24 @@ function resolveForGuard(path, ctx) {
124
124
  if (existsSync(normalized)) {
125
125
  return realpathSync(normalized);
126
126
  }
127
- const parentDir = dirname(normalized);
128
- const parentRealPath = resolveExistingAncestor(parentDir);
129
- return resolve(parentRealPath, basename(normalized));
127
+ // Walk up to the nearest existing ancestor, remembering every missing path segment along the
128
+ // way, then reattach them onto that ancestor's realpath (spec 044: a file tool's real write
129
+ // target is now this resolved path, not a raw `mkdir -p`'d one, so this has to be exact). A
130
+ // naive "existing ancestor + basename" only handles a single missing directory level -- writing
131
+ // `a/b/c.txt` where neither `a` nor `a/b` exist yet used to silently drop the `a/b` segment and
132
+ // resolve to `<ancestor>/c.txt` instead of `<ancestor>/a/b/c.txt`.
133
+ const missingSegments = [];
134
+ let current = normalized;
135
+ while (!existsSync(current)) {
136
+ missingSegments.unshift(basename(current));
137
+ const parent = dirname(current);
138
+ if (parent === current) {
139
+ break;
140
+ }
141
+ current = parent;
142
+ }
143
+ const ancestorRealPath = existsSync(current) ? realpathSync(current) : current;
144
+ return resolve(ancestorRealPath, ...missingSegments);
130
145
  }
131
146
  function matchesAnyPath(path, exactPaths, prefixes) {
132
147
  return exactPaths.includes(path) || prefixes.some((prefix) => startsWithPathPrefix(path, prefix));
@@ -215,13 +230,13 @@ function isWithinProjectRoot(path, ctx) {
215
230
  }
216
231
  return startsWithPathPrefix(path, normalize(root));
217
232
  }
218
- /** Runtime-owned, read-only exception: the AgentWorkspace's `skills/` tree stays readable under
219
- * `boundary: "project"` so the model can load a skill's playbook regardless of which project it
220
- * has selected (spec 043, D6.2). Never a write exception. */
221
- function isAgentWorkspaceSkillsRead(path, operation, ctx) {
222
- if (operation !== "read") {
223
- return false;
224
- }
233
+ /** Runtime-owned exception: the AgentWorkspace's `skills/` tree stays reachable under
234
+ * `boundary: "project"` regardless of which project is selected (spec 043, D6.2) -- reads so the
235
+ * model can load a skill's playbook, and writes so `write`/`edit` can author one (the `skill` tool
236
+ * itself is read-only; authoring goes through the generic file tools). The symlink-write check
237
+ * above this call in `guardPath` still applies, so a skill file that is itself a symlink cannot be
238
+ * written through even inside this exception. */
239
+ function isAgentWorkspaceSkillsAccess(path, ctx) {
225
240
  return startsWithPathPrefix(path, normalize(join(ctx.agentWorkspaceDir, "skills")));
226
241
  }
227
242
  /**
@@ -232,8 +247,8 @@ function isAgentWorkspaceSkillsRead(path, operation, ctx) {
232
247
  * `tasks/<id>.md` and the guard would refuse.
233
248
  *
234
249
  * Reads are allowed throughout. Writes are allowed only under `tasks/`: the three memory files are
235
- * runtime-maintained and go through `memory_manage` (a file write there races the maintenance
236
- * queue), while a task's body is model-authored prose that `task_manage` cannot rewrite — `set`
250
+ * runtime-maintained and go through the memory tools (a file write there races the maintenance
251
+ * queue), while a task's body is model-authored prose that `task_update` cannot rewrite — it
237
252
  * replaces frontmatter and keeps the body verbatim, so revising a task contract needs `edit`.
238
253
  */
239
254
  function isChannelDirAccess(path, operation, ctx) {
@@ -284,7 +299,10 @@ function formatBlockedResult(operation, rawPath, resolvedPath, category, reason)
284
299
  }
285
300
  export function guardPath(rawPath, operation, ctx) {
286
301
  if (!ctx.config.enabled) {
287
- return { allowed: true, operation, rawPath };
302
+ // Resolution is normalization, not policy, so `resolvedPath` stays populated even with the
303
+ // guard off (spec 044, D1.1): callers rely on it being the one path every file tool actually
304
+ // opens, and a guard-disabled deployment must not be the one case that breaks that invariant.
305
+ return { allowed: true, operation, rawPath, resolvedPath: resolveForGuard(resolveTargetPath(rawPath, ctx), ctx) };
288
306
  }
289
307
  const homeDir = ctx.homeDir ?? homedir();
290
308
  const effectiveCtx = {
@@ -323,7 +341,7 @@ export function guardPath(rawPath, operation, ctx) {
323
341
  }
324
342
  if (pathAllowedByDefaults(guardedPath, effectiveCtx) ||
325
343
  isBundledPlaybookRead(guardedPath, operation) ||
326
- isAgentWorkspaceSkillsRead(guardedPath, operation, effectiveCtx) ||
344
+ isAgentWorkspaceSkillsAccess(guardedPath, effectiveCtx) ||
327
345
  isChannelDirAccess(guardedPath, operation, effectiveCtx)) {
328
346
  return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
329
347
  }
package/dist/settings.js CHANGED
@@ -6,10 +6,11 @@
6
6
  *
7
7
  * This module currently provides only PipiclawSettingsManager.
8
8
  */
9
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
9
+ import { existsSync, mkdirSync, readFileSync } from "fs";
10
10
  import { dirname, join } from "path";
11
11
  import * as log from "./log.js";
12
12
  import { getMemoryMaintenanceTuning, getSessionRefreshCadence, } from "./memory/maintenance-tuning.js";
13
+ import { writeFileAtomicallySync } from "./shared/atomic-file.js";
13
14
  import { fileStamp } from "./shared/file-stamp.js";
14
15
  const DEFAULT_TUI = {
15
16
  responseMode: "full_progress_then_plain_final",
@@ -178,7 +179,7 @@ export class PipiclawSettingsManager {
178
179
  if (!existsSync(dir)) {
179
180
  mkdirSync(dir, { recursive: true });
180
181
  }
181
- writeFileSync(this.settingsPath, JSON.stringify(this.settings, null, 2), "utf-8");
182
+ writeFileAtomicallySync(this.settingsPath, JSON.stringify(this.settings, null, 2));
182
183
  }
183
184
  catch (error) {
184
185
  log.logWarning(`Could not save settings file`, `${this.settingsPath}\n${String(error)}`);
@@ -1,2 +1,18 @@
1
1
  export declare function createAtomicTempPath(path: string): string;
2
- export declare function writeFileAtomically(path: string, content: string, tempPath?: string): Promise<void>;
2
+ export interface WriteFileAtomicallyOptions {
3
+ tempPath?: string;
4
+ /**
5
+ * `fchmod` the temp file to the existing target's permission bits before renaming over it, so
6
+ * an atomic overwrite of an executable file does not silently strip its `x` bit (spec 044,
7
+ * D1.2). A missing target (first write) leaves the temp file's own default mode untouched.
8
+ */
9
+ preserveMode?: boolean;
10
+ }
11
+ export declare function writeFileAtomically(path: string, content: string | Buffer, optionsOrTempPath?: WriteFileAtomicallyOptions | string): Promise<void>;
12
+ /**
13
+ * Synchronous counterpart to {@link writeFileAtomically} for the handful of call sites that
14
+ * cannot go async (a settings-manager `save(): void` and a per-message conversation-meta write
15
+ * called from a sync event handler) — write-temp-then-rename still beats a direct
16
+ * `writeFileSync`, since a crash mid-write can no longer truncate the target in place.
17
+ */
18
+ export declare function writeFileAtomicallySync(path: string, content: string | Buffer, tempPath?: string): void;
@@ -1,16 +1,36 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, open, rename, unlink } from "node:fs/promises";
2
+ import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { mkdir, open, rename, stat, unlink } from "node:fs/promises";
3
4
  import { dirname } from "node:path";
4
5
  export function createAtomicTempPath(path) {
5
6
  return `${path}.${process.pid}.${randomUUID()}.tmp`;
6
7
  }
7
- export async function writeFileAtomically(path, content, tempPath = createAtomicTempPath(path)) {
8
+ async function existingMode(path) {
9
+ try {
10
+ return (await stat(path)).mode & 0o777;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ }
16
+ export async function writeFileAtomically(path, content, optionsOrTempPath = {}) {
17
+ const options = typeof optionsOrTempPath === "string" ? { tempPath: optionsOrTempPath } : optionsOrTempPath;
18
+ const tempPath = options.tempPath ?? createAtomicTempPath(path);
8
19
  const dir = dirname(path);
9
20
  await mkdir(dir, { recursive: true });
10
21
  try {
22
+ const mode = options.preserveMode ? await existingMode(path) : undefined;
11
23
  const handle = await open(tempPath, "w");
12
24
  try {
13
- await handle.writeFile(content, "utf-8");
25
+ if (mode !== undefined) {
26
+ await handle.chmod(mode);
27
+ }
28
+ if (typeof content === "string") {
29
+ await handle.writeFile(content, "utf-8");
30
+ }
31
+ else {
32
+ await handle.writeFile(content);
33
+ }
14
34
  await handle.sync();
15
35
  }
16
36
  finally {
@@ -35,3 +55,30 @@ export async function writeFileAtomically(path, content, tempPath = createAtomic
35
55
  throw error;
36
56
  }
37
57
  }
58
+ /**
59
+ * Synchronous counterpart to {@link writeFileAtomically} for the handful of call sites that
60
+ * cannot go async (a settings-manager `save(): void` and a per-message conversation-meta write
61
+ * called from a sync event handler) — write-temp-then-rename still beats a direct
62
+ * `writeFileSync`, since a crash mid-write can no longer truncate the target in place.
63
+ */
64
+ export function writeFileAtomicallySync(path, content, tempPath) {
65
+ const resolvedTempPath = tempPath ?? createAtomicTempPath(path);
66
+ const dir = dirname(path);
67
+ mkdirSync(dir, { recursive: true });
68
+ try {
69
+ if (typeof content === "string") {
70
+ writeFileSync(resolvedTempPath, content, "utf-8");
71
+ }
72
+ else {
73
+ writeFileSync(resolvedTempPath, content);
74
+ }
75
+ renameSync(resolvedTempPath, path);
76
+ }
77
+ catch (error) {
78
+ try {
79
+ unlinkSync(resolvedTempPath);
80
+ }
81
+ catch { }
82
+ throw error;
83
+ }
84
+ }
@@ -0,0 +1,2 @@
1
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
+ export declare function formatDuration(ms: number): string;
@@ -0,0 +1,7 @@
1
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
+ export function formatDuration(ms) {
3
+ const seconds = Math.round(ms / 1000);
4
+ if (seconds < 60)
5
+ return `${seconds}s`;
6
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
7
+ }
@@ -0,0 +1,19 @@
1
+ export interface SafeIdOptions {
2
+ /** File suffix to strip (e.g. `.md`, `.json`) and re-append when resolving a path. */
3
+ suffix: string;
4
+ /** Allowed id characters after suffix stripping. */
5
+ pattern: RegExp;
6
+ /** Used in error messages, e.g. "task id", "event name". */
7
+ label: string;
8
+ }
9
+ /** Validate/normalize an id (a file basename minus its suffix), rejecting path traversal. */
10
+ export declare function normalizeSafeId(id: string, options: SafeIdOptions): string;
11
+ /**
12
+ * {@link normalizeSafeId}, then resolves the id to a path confined under `dir` — defense in
13
+ * depth beyond the pattern check, for the one caller (`event_manage`) whose directory is
14
+ * agent-writable.
15
+ */
16
+ export declare function resolveSafeIdPath(dir: string, id: string, options: SafeIdOptions): {
17
+ id: string;
18
+ path: string;
19
+ };