@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -1
  2. package/dist/agent/channel-runner.js +9 -5
  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 +6 -4
  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 +5 -5
  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 +10 -10
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/security/block-message.d.ts +11 -0
  50. package/dist/security/block-message.js +12 -0
  51. package/dist/security/path-guard-check.d.ts +13 -0
  52. package/dist/security/path-guard-check.js +39 -0
  53. package/dist/security/path-guard.js +32 -14
  54. package/dist/settings.js +3 -2
  55. package/dist/shared/atomic-file.d.ts +17 -1
  56. package/dist/shared/atomic-file.js +50 -3
  57. package/dist/shared/duration.d.ts +2 -0
  58. package/dist/shared/duration.js +7 -0
  59. package/dist/shared/safe-id.d.ts +19 -0
  60. package/dist/shared/safe-id.js +24 -0
  61. package/dist/shared/text-utils.d.ts +1 -1
  62. package/dist/shared/text-utils.js +3 -8
  63. package/dist/shared/type-guards.d.ts +2 -0
  64. package/dist/shared/type-guards.js +4 -0
  65. package/dist/subagents/discovery.d.ts +44 -17
  66. package/dist/subagents/discovery.js +82 -111
  67. package/dist/subagents/external/claude-code.js +1 -3
  68. package/dist/subagents/external/harness.d.ts +1 -1
  69. package/dist/subagents/format.d.ts +3 -2
  70. package/dist/subagents/format.js +3 -7
  71. package/dist/subagents/runs.d.ts +1 -1
  72. package/dist/subagents/runs.js +4 -9
  73. package/dist/subagents/tool.d.ts +31 -19
  74. package/dist/subagents/tool.js +582 -561
  75. package/dist/subagents/workspace-lease.js +1 -1
  76. package/dist/tasks/control.js +7 -9
  77. package/dist/tasks/ledger.d.ts +2 -2
  78. package/dist/tasks/ledger.js +3 -7
  79. package/dist/tasks/transitions.d.ts +5 -1
  80. package/dist/tasks/transitions.js +2 -2
  81. package/dist/tools/bash.d.ts +0 -1
  82. package/dist/tools/bash.js +45 -40
  83. package/dist/tools/config.d.ts +6 -1
  84. package/dist/tools/config.js +9 -0
  85. package/dist/tools/edit.d.ts +2 -3
  86. package/dist/tools/edit.js +274 -86
  87. package/dist/tools/event-manage.d.ts +13 -7
  88. package/dist/tools/event-manage.js +52 -14
  89. package/dist/tools/glob-match.d.ts +11 -0
  90. package/dist/tools/glob-match.js +75 -0
  91. package/dist/tools/glob.d.ts +15 -0
  92. package/dist/tools/glob.js +113 -0
  93. package/dist/tools/grep.d.ts +0 -1
  94. package/dist/tools/grep.js +57 -42
  95. package/dist/tools/ignore-dirs.d.ts +6 -0
  96. package/dist/tools/ignore-dirs.js +15 -0
  97. package/dist/tools/index.d.ts +3 -0
  98. package/dist/tools/index.js +50 -40
  99. package/dist/tools/job.d.ts +0 -1
  100. package/dist/tools/job.js +1 -8
  101. package/dist/tools/line-index.d.ts +16 -0
  102. package/dist/tools/line-index.js +76 -0
  103. package/dist/tools/memory-manage.d.ts +20 -8
  104. package/dist/tools/memory-manage.js +65 -92
  105. package/dist/tools/presentation.d.ts +2 -0
  106. package/dist/tools/presentation.js +109 -0
  107. package/dist/tools/read.d.ts +2 -2
  108. package/dist/tools/read.js +97 -133
  109. package/dist/tools/registry.d.ts +4 -1
  110. package/dist/tools/registry.js +89 -22
  111. package/dist/tools/send-media.d.ts +6 -6
  112. package/dist/tools/send-media.js +16 -49
  113. package/dist/tools/session-search.d.ts +0 -1
  114. package/dist/tools/session-search.js +0 -1
  115. package/dist/tools/skill-security.d.ts +0 -2
  116. package/dist/tools/skill-security.js +0 -24
  117. package/dist/tools/skill.d.ts +31 -0
  118. package/dist/tools/skill.js +153 -0
  119. package/dist/tools/subagent-manage.d.ts +6 -5
  120. package/dist/tools/subagent-manage.js +47 -47
  121. package/dist/tools/task-manage/create.d.ts +2 -2
  122. package/dist/tools/task-manage/create.js +1 -3
  123. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  124. package/dist/tools/task-manage/lifecycle.js +49 -56
  125. package/dist/tools/task-manage/schema.d.ts +27 -15
  126. package/dist/tools/task-manage/schema.js +58 -74
  127. package/dist/tools/task-manage/shared.d.ts +11 -6
  128. package/dist/tools/task-manage/shared.js +30 -21
  129. package/dist/tools/task-manage/types.d.ts +14 -15
  130. package/dist/tools/task-manage/verification.d.ts +4 -4
  131. package/dist/tools/task-manage/verification.js +6 -8
  132. package/dist/tools/task-manage.d.ts +8 -11
  133. package/dist/tools/task-manage.js +63 -50
  134. package/dist/tools/tool-details.d.ts +17 -1
  135. package/dist/tools/tool-details.js +24 -0
  136. package/dist/tools/truncate.d.ts +5 -5
  137. package/dist/tools/truncate.js +5 -5
  138. package/dist/tools/web-fetch.d.ts +0 -1
  139. package/dist/tools/web-fetch.js +0 -1
  140. package/dist/tools/web-search.d.ts +0 -1
  141. package/dist/tools/web-search.js +0 -1
  142. package/dist/tools/write-content.d.ts +3 -3
  143. package/dist/tools/write-content.js +12 -51
  144. package/dist/tools/write.d.ts +2 -3
  145. package/dist/tools/write.js +3 -4
  146. package/dist/usage/ledger.js +7 -4
  147. package/package.json +1 -1
  148. package/dist/tools/skill-manage.d.ts +0 -41
  149. package/dist/tools/skill-manage.js +0 -232
@@ -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);
@@ -433,11 +433,11 @@ async function doctor(options) {
433
433
  .catch(() => false)
434
434
  : false;
435
435
  if (!attestationOk) {
436
- issues.push(issue(`tasks/${entry.id}.md 记录了一次独立 PASS,但磁盘上没有匹配且新鲜的验证 attestation`, `跑一次新的 purpose=verify 子代理,并用 task_manage verify 导入它的 attestation 后再完成`));
436
+ issues.push(issue(`tasks/${entry.id}.md 记录了一次独立 PASS,但磁盘上没有匹配且新鲜的验证 attestation`, `跑一次新的 purpose=verify 子代理,并用 task_verify 导入它的 attestation 后再完成`));
437
437
  }
438
438
  }
439
439
  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 记录`));
440
+ issues.push(issue(`tasks/${entry.id}.md 已停用,但 control 里没有 stop 回执`, `先弄清是谁停用的,再 /tasks resume ${entry.id};或者用 task_update(不带 note)写一条合法的 stop 记录`));
441
441
  }
442
442
  if (entry.frontmatter.enabled !== false && control.stop) {
443
443
  issues.push(issue(`tasks/${entry.id}.md 有 stop 回执,但 enabled 是 true`, `跑 /tasks resume ${entry.id} 清掉过期的 stop 回执,或者显式停用这个任务`));
@@ -445,7 +445,7 @@ async function doctor(options) {
445
445
  }
446
446
  const recurring = Boolean(entry.frontmatter.schedule);
447
447
  if (status === "sleeping" && !recurring) {
448
- issues.push(issue(`tasks/${entry.id}.md 处于 sleeping,但没有 recurring schedule`, `一次性任务用 task_manage complete/cancel 结束;要保留 sleeping 需要先加一个合法的 schedule`));
448
+ issues.push(issue(`tasks/${entry.id}.md 处于 sleeping,但没有 recurring schedule`, `一次性任务用 task_close outcome=complete/cancel 结束;要保留 sleeping 需要先加一个合法的 schedule`));
449
449
  }
450
450
  if (recurring) {
451
451
  try {
@@ -462,7 +462,7 @@ async function doctor(options) {
462
462
  entry.frontmatter.wake &&
463
463
  validWakeMs(entry) !== undefined &&
464
464
  validWakeMs(entry) > now) {
465
- issues.push(issue(`tasks/${entry.id}.md 处于 active,但它的 wake 在未来`, `用 task_manage set/progress 把它改成 waiting 且 waitingFor=time,或者清空 wake 让它现在继续`));
465
+ issues.push(issue(`tasks/${entry.id}.md 处于 active,但它的 wake 在未来`, `用 task_update 把它改成 waiting 且 waitingFor=time,或者清空 wake 让它现在继续`));
466
466
  }
467
467
  if (recurringTaskMissedOccurrence({ status, schedule: entry.frontmatter.schedule, control }, new Date(now))) {
468
468
  issues.push(issue(`tasks/${entry.id}.md 有一个已过下次 recurring 时点、仍处于 ${status} 的周期,且没有并行开启新周期`, `完成、跳过或取消 ${entry.id} 当前周期,之后让 driver 计算下一次时点`));
@@ -505,7 +505,7 @@ async function doctor(options) {
505
505
  }
506
506
  }
507
507
  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 换成合法本地时间,或者清空它让任务直接继续`));
508
+ issues.push(issue(`tasks/${entry.id}.md 的 wake 值无效(${entry.frontmatter.wake});原生 driver 会把它当成已到期处理`, `用 task_update 把 wake 换成合法本地时间,或者清空它让任务直接继续`));
509
509
  }
510
510
  // A recurring task's wake should always be an occurrence of its own schedule. A wake that
511
511
  // isn't — a stale value left over from a since-changed cron, or a hand-typed local↔UTC
@@ -517,7 +517,7 @@ async function doctor(options) {
517
517
  if (wakeMs !== undefined) {
518
518
  const priorOccurrence = nextTaskWake(schedule, new Date(wakeMs - 1));
519
519
  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`));
520
+ issues.push(issue(`tasks/${entry.id}.md 的 wake(${formatLocalTime(new Date(wakeMs))})不是它 schedule "${schedule}" 的一个合法时点`, `跑 task_update schedule="${schedule}"(不变)用 cron 重新计算 wake,或者手动明确设置 wake`));
521
521
  }
522
522
  }
523
523
  }
@@ -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",
@@ -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
+ };
@@ -0,0 +1,24 @@
1
+ import { join, resolve, sep } from "node:path";
2
+ /** Validate/normalize an id (a file basename minus its suffix), rejecting path traversal. */
3
+ export function normalizeSafeId(id, options) {
4
+ const trimmed = id.trim();
5
+ const normalized = trimmed.endsWith(options.suffix) ? trimmed.slice(0, -options.suffix.length) : trimmed;
6
+ if (!normalized || normalized === "." || normalized === ".." || !options.pattern.test(normalized)) {
7
+ throw new Error(`Invalid ${options.label}: ${id}`);
8
+ }
9
+ return normalized;
10
+ }
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 function resolveSafeIdPath(dir, id, options) {
17
+ const normalizedId = normalizeSafeId(id, options);
18
+ const resolvedDir = resolve(dir);
19
+ const path = resolve(resolvedDir, `${normalizedId}${options.suffix}`);
20
+ if (path !== join(resolvedDir, `${normalizedId}${options.suffix}`) || !path.startsWith(`${resolvedDir}${sep}`)) {
21
+ throw new Error(`Invalid ${options.label}: ${id}`);
22
+ }
23
+ return { id: normalizedId, path };
24
+ }
@@ -2,11 +2,11 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
2
  export declare function clipText(text: string, maxChars: number, opts?: {
3
3
  headRatio?: number;
4
4
  omitHint?: string;
5
+ collapseWhitespace?: boolean;
5
6
  }): string;
6
7
  export declare function truncate(text: string, maxLen: number): string;
7
8
  export declare const HAN_REGEX: RegExp;
8
9
  /** Strip a trailing `.json` from an event filename to get its logical name. */
9
10
  export declare function eventNameFromFilename(filename: string): string;
10
- export declare function extractLabelFromArgs(args: unknown): string | null;
11
11
  export declare function errorMessage(err: unknown): string;
12
12
  export declare function extractAssistantText(message: AssistantMessage): string;
@@ -1,5 +1,7 @@
1
1
  export function clipText(text, maxChars, opts = {}) {
2
- const normalized = text.replace(/\s+\n/g, "\n").replace(/\r/g, "").trim();
2
+ const normalized = opts.collapseWhitespace
3
+ ? text.replace(/\s+/g, " ").trim()
4
+ : text.replace(/\s+\n/g, "\n").replace(/\r/g, "").trim();
3
5
  if (normalized.length <= maxChars) {
4
6
  return normalized;
5
7
  }
@@ -24,13 +26,6 @@ export const HAN_REGEX = /\p{Script=Han}/u;
24
26
  export function eventNameFromFilename(filename) {
25
27
  return filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
26
28
  }
27
- export function extractLabelFromArgs(args) {
28
- if (!args || typeof args !== "object" || !("label" in args)) {
29
- return null;
30
- }
31
- const label = args.label;
32
- return typeof label === "string" && label.trim() ? label.trim() : null;
33
- }
34
29
  export function errorMessage(err) {
35
30
  return err instanceof Error ? err.message : String(err);
36
31
  }
@@ -1,5 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Message } from "@earendil-works/pi-ai";
3
3
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
4
+ /** Like {@link isRecord}, but false for arrays — for parsing JSON where an array is not a valid shape. */
5
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
4
6
  export declare function isStandardAgentMessage(message: AgentMessage): message is Message;
5
7
  export declare function buildStandardMessages(messages: AgentMessage[]): Message[];
@@ -1,6 +1,10 @@
1
1
  export function isRecord(value) {
2
2
  return typeof value === "object" && value !== null;
3
3
  }
4
+ /** Like {@link isRecord}, but false for arrays — for parsing JSON where an array is not a valid shape. */
5
+ export function isPlainObject(value) {
6
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7
+ }
4
8
  export function isStandardAgentMessage(message) {
5
9
  return (typeof message === "object" &&
6
10
  message !== null &&
@@ -43,14 +43,6 @@ export declare const SUB_AGENT_EFFORT_PRESETS: {
43
43
  readonly bashTimeoutSec: 180;
44
44
  };
45
45
  };
46
- /**
47
- * External runs have no turn/tool-call budget (D5) — `effort` only ever moves wall time, and at
48
- * external scale, not the internal tuple above (P1-3: those numbers previously leaked onto
49
- * external roles unchanged, where `deep` at 900s was *shorter* than the external default).
50
- * `standard` and an unset `effort` both keep the role's own `maxWallTimeSec` (or the external
51
- * default), so this only has entries for the two presets that actually override it.
52
- */
53
- export declare const SUB_AGENT_EXTERNAL_EFFORT_WALL_TIME_SEC: Partial<Record<keyof typeof SUB_AGENT_EFFORT_PRESETS, number>>;
54
46
  export type SubAgentEffort = keyof typeof SUB_AGENT_EFFORT_PRESETS;
55
47
  /**
56
48
  * The invocation-side spelling of `contextMode` + `memory`. Those two frontmatter knobs
@@ -109,17 +101,30 @@ export interface SubAgentDiscoveryResult {
109
101
  agents: SubAgentConfig[];
110
102
  warnings: string[];
111
103
  }
112
- export interface SubAgentInvocationOverrides {
113
- agent?: string;
114
- name?: string;
115
- systemPrompt?: string;
104
+ /**
105
+ * `subagent` (role-based) invocation surface (spec 046, D2.1). Deliberately has no override
106
+ * fields beyond `purpose`: everything else a configured role could vary — tools, model, effort,
107
+ * context, thinkingLevel, mutates — lives in the role file, which is the deployer's decision, not
108
+ * a per-call one. This is what makes "external role + tools/model/mutates" unrepresentable at the
109
+ * type level instead of rejected at runtime (spec 042 D3's three checks are now dead by construction).
110
+ */
111
+ export interface ConfiguredRoleOverrides {
112
+ agent: string;
113
+ /** Drives the thinkingLevel default: "verify" defaults on, everything else stays off. */
114
+ purpose?: string;
115
+ }
116
+ /**
117
+ * `subagent_inline` invocation surface (spec 046, D2.1) — a one-off executor with no role file,
118
+ * so every field a role file would otherwise supply is a call-time override here instead.
119
+ */
120
+ export interface InlineAgentOverrides {
121
+ systemPrompt: string;
116
122
  tools?: string[];
117
123
  model?: string;
118
124
  /** Named budget preset; wins over frontmatter numbers as a whole tuple, never field by field. */
119
125
  effort?: string;
120
126
  /** Collapsed `contextMode` + `memory`; see SubAgentContextChoice. */
121
127
  context?: string;
122
- paths?: string[];
123
128
  thinkingLevel?: string;
124
129
  /** Drives the thinkingLevel default: "verify" defaults on, everything else stays off. */
125
130
  purpose?: string;
@@ -158,12 +163,34 @@ type FieldSupport = "supported" | "rejected";
158
163
  */
159
164
  export declare const ROLE_FIELD_MATRIX: Record<string, Record<SubAgentRuntime, FieldSupport>>;
160
165
  export declare function discoverSubAgents(workspaceDir: string, availableModels: Model<Api>[]): SubAgentDiscoveryResult;
161
- export declare function resolveSubAgentConfig(availableModels: Model<Api>[], currentModel: Model<Api>, predefinedAgents: SubAgentConfig[], overrides: SubAgentInvocationOverrides,
162
166
  /**
163
- * `settings.subagentModel` (spec 032 D5): used only when neither the invocation nor the
164
- * predefined agent's frontmatter names a model. Unset/blank is "not configured" — the
165
- * caller (tool.ts) already normalizes that, this function just treats undefined as absent.
167
+ * Resolve a `subagent` (role-based) invocation (spec 046, D2.1).
168
+ *
169
+ * Everything the old combined resolver used to override for a configured role — `tools`,
170
+ * `model`, `effort`, `context`, `mutates` — now has nowhere to come from but the role file
171
+ * itself, so this is a lookup plus the two facts a role file cannot pin down: the default model
172
+ * (parent's current model, or `settings.subagentModel`) and the purpose-driven thinkingLevel
173
+ * default. Spec 042 D3's three "external + override" rejections no longer apply: `ConfiguredRoleOverrides`
174
+ * has no `tools`/`model`/`mutates` field to reject in the first place.
175
+ */
176
+ export declare function resolveConfiguredRole(availableModels: Model<Api>[], currentModel: Model<Api>, predefinedAgents: SubAgentConfig[], overrides: ConfiguredRoleOverrides,
177
+ /**
178
+ * `settings.subagentModel` (spec 032 D5): used only when neither the role file's frontmatter
179
+ * nor this call names a model (it cannot — there is no override field for it).
180
+ */
181
+ subagentDefaultModelRef?: string): {
182
+ config?: ResolvedSubAgentConfig;
183
+ error?: string;
184
+ };
185
+ /**
186
+ * Resolve a `subagent_inline` invocation (spec 046, D2.1) — a one-off executor with no role
187
+ * file. `runtime` is always `"internal"` here: only a configured role file can name `external`,
188
+ * and `InlineAgentOverrides` has no field for it, so the old function's external branches
189
+ * (budget table, unset-by-default thinkingLevel, model/tools/mutates rejections) simply do not
190
+ * apply to this path and are not reproduced here.
166
191
  */
192
+ export declare function resolveInlineAgent(availableModels: Model<Api>[], currentModel: Model<Api>, overrides: InlineAgentOverrides,
193
+ /** `settings.subagentModel` (spec 032 D5): used only when this call does not name a model. */
167
194
  subagentDefaultModelRef?: string): {
168
195
  config?: ResolvedSubAgentConfig;
169
196
  error?: string;