@oyasmi/pipiclaw 0.9.3-beta.4 → 0.9.3-beta.6

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 (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -1,59 +1,46 @@
1
1
  /**
2
- * Verifying and claiming a background job's or delegation run's completion wake before it may
3
- * activate a parked task (spec 040, D7/T9). Split out of `bootstrap.ts`: these are pure functions
4
- * over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
- * `createRuntimeContext`'s closures.
2
+ * Claiming a background job's or delegation run's completion wake before it may reopen a parked
3
+ * task (spec 040, D7/T9). Pure functions over an explicit `event`/`workspaceDir`/owner, with no
4
+ * dependency on `createRuntimeContext`'s closures.
5
+ *
6
+ * Trust comes from two things only: the producer-created `internalWake` envelope (DingTalk
7
+ * inbound parsing never populates it, so user text or an external agent's stdout cannot forge
8
+ * one), and the owner's `beginWakeConsumption`, which re-checks that the resource exists, has
9
+ * settled, names this task, and that the dispatch id is exactly the one its own completion wake
10
+ * carries.
6
11
  */
7
- import type { ChannelJobManager, JobSnapshot } from "../agent/job-manager.js";
8
12
  import type { ChannelEvent } from "../channel/channel-event.js";
9
- import type { RunRecord, SubAgentRunManager } from "../subagents/runs.js";
10
- /**
11
- * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
12
- * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
13
- * accepting it anyway would let a message merely mentioning a live job's id activate a task
14
- * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
15
- * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
16
- * untrusted stdout.
17
- */
18
- export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
19
- /**
20
- * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
21
- * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
22
- * because it is published with the terminal record before usage/archive/wake side effects — the
23
- * same idempotency guard the manager itself relies on. A pending settlement intent leaves it unset.
24
- */
25
- export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
26
- /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
27
- * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
28
- * not populate `internalWake`, so copying a real wake's text is insufficient. */
29
- export declare function isTrustedInternalWake(event: ChannelEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is ChannelEvent & {
30
- dispatchId: string;
31
- };
32
- export interface ClaimedDelegationWake {
33
- taskId: string;
34
- activated: boolean;
35
- /** True when it is safe to drop this wake without a turn even though it did not redeem a
36
- * ticket itself — see `isTaskActivelyDriven`. Always true when `activated` is true. */
37
- taskStillDriven: boolean;
38
- finish(): Promise<void>;
39
- rollback(): Promise<void>;
13
+ /** The slice of `ChannelJobManager` / `SubAgentRunManager` a wake claim needs. */
14
+ export interface WakeOwner {
15
+ beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
16
+ finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
40
17
  }
41
18
  /** Test-only fault seam, kept for the restart/interrupt cases that exercise a failed write. */
42
19
  export interface WakeTaskTransitionHooks {
43
20
  beforeActivation?: () => void;
44
21
  }
45
- /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
46
- * final marker separate lets transports such as TUI mark it consumed only after they have accepted
47
- * the corresponding turn; a rejected submit remains replayable in the same or next process. */
48
- export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, runManager: SubAgentRunManager, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
49
- export interface ClaimedJobWake {
22
+ export interface ClaimedWake {
50
23
  taskId: string;
24
+ /** True when this wake redeemed the task's `work` ticket. */
51
25
  activated: boolean;
52
- /** See `ClaimedDelegationWake.taskStillDriven`. */
26
+ /**
27
+ * True when it is safe to drop this wake without a turn even though it did not redeem a ticket
28
+ * itself: the task is already `open` and not paused, so some other wake in the same fan-out
29
+ * reopened it and the driver will pick up the result. Every other case — done, archived,
30
+ * paused, or the task missing — has nobody left to look at the result if it is dropped, so the
31
+ * caller must still route it to a normal turn. Always true when `activated` is true.
32
+ */
53
33
  taskStillDriven: boolean;
34
+ /** Mark the wake consumed. Kept separate so the caller finalizes only after it accepted the turn. */
54
35
  finish(): Promise<void>;
55
36
  }
56
- /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
57
- * <taskId>.` completion wake. A background job has no rollback bookkeeping — its wake
58
- * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
59
- export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string, jobManager: ChannelJobManager, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
37
+ /**
38
+ * Claim a producer-created completion wake and redeem the task's ticket for it. Returns
39
+ * `undefined` for an event with no (or an unverifiable) `internalWake`.
40
+ *
41
+ * Only a `work` ticket may be redeemed by a settling run or job (any bound run or job settling
42
+ * wakes the leader, spec 052, D3): a task parked on a clock or a question to the user is not
43
+ * waiting for it, and reopening it here would be exactly the unverified resumption path spec 051
44
+ * exists to remove.
45
+ */
46
+ export declare function claimVerifiedWake(event: ChannelEvent, workspaceDir: string, owner: WakeOwner, hooks?: WakeTaskTransitionHooks): Promise<ClaimedWake | undefined>;
@@ -1,107 +1,32 @@
1
1
  import { getChannelDir } from "../channel/channel-paths.js";
2
- import { parkTask, readStoredTask, redeemTicket } from "../tasks/store.js";
3
- /**
4
- * True when `taskId` is already `open` and not paused — i.e. the driver already owns advancing
5
- * it. A completion wake that could not redeem a ticket (because the task was not parked on one)
6
- * is safe to drop without spending an agent turn only in this case: some other wake in the same
7
- * fan-out already reopened it, and the driver will pick up the result. Every other case — done,
8
- * archived, paused, or the task missing entirely — has nobody left to look at the wake's result
9
- * if it is dropped here, so the caller must still route it to a normal turn.
10
- */
2
+ import { readStoredTask, redeemTicket } from "../tasks/store.js";
11
3
  async function isTaskActivelyDriven(channelDir, taskId) {
12
4
  const document = await readStoredTask(channelDir, taskId).catch(() => undefined);
13
5
  return document !== undefined && document.fields.state === "open" && !document.fields.paused;
14
6
  }
15
7
  /**
16
- * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
17
- * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
18
- * accepting it anyway would let a message merely mentioning a live job's id activate a task
19
- * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
20
- * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
21
- * untrusted stdout.
22
- */
23
- export function isVerifiedJobWake(jobs, jobId, taskId) {
24
- const job = jobs.find((candidate) => candidate.id === jobId);
25
- return job !== undefined && job.status !== "running" && job.taskId === taskId;
26
- }
27
- /**
28
- * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
29
- * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
30
- * because it is published with the terminal record before usage/archive/wake side effects — the
31
- * same idempotency guard the manager itself relies on. A pending settlement intent leaves it unset.
8
+ * Claim a producer-created completion wake and redeem the task's ticket for it. Returns
9
+ * `undefined` for an event with no (or an unverifiable) `internalWake`.
10
+ *
11
+ * Only a `work` ticket may be redeemed by a settling run or job (any bound run or job settling
12
+ * wakes the leader, spec 052, D3): a task parked on a clock or a question to the user is not
13
+ * waiting for it, and reopening it here would be exactly the unverified resumption path spec 051
14
+ * exists to remove.
32
15
  */
33
- export function isVerifiedDelegationWake(record, taskId) {
34
- return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
35
- }
36
- /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
37
- * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
38
- * not populate `internalWake`, so copying a real wake's text is insufficient. */
39
- export function isTrustedInternalWake(event, kind, resourceId, taskId) {
40
- const wake = event.internalWake;
41
- return (wake?.kind === kind &&
42
- wake.resourceId === resourceId &&
43
- wake.taskId === taskId &&
44
- typeof event.dispatchId === "string" &&
45
- wake.dispatchId === event.dispatchId);
46
- }
47
- /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
48
- * final marker separate lets transports such as TUI mark it consumed only after they have accepted
49
- * the corresponding turn; a rejected submit remains replayable in the same or next process. */
50
- export async function claimVerifiedDelegationWake(event, workspaceDir, runManager, hooks) {
51
- const wake = event.internalWake;
52
- if (wake?.kind !== "subagent")
53
- return undefined;
54
- const record = runManager.get(wake.resourceId);
55
- if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
56
- !isVerifiedDelegationWake(record, wake.taskId) ||
57
- !(await runManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
58
- return undefined;
59
- }
60
- const channelDir = getChannelDir(workspaceDir, event.channelId);
61
- hooks?.beforeActivation?.();
62
- // Only a `run` ticket naming this very run may be redeemed: a task parked on something else
63
- // (a job, a question to the user) is not waiting for this delegation, and reopening it here
64
- // would be exactly the unverified resumption path spec 051 D2 exists to remove.
65
- const redeemed = await redeemTicket(channelDir, wake.taskId, (ticket) => ticket.kind === "run" && ticket.id === wake.resourceId);
66
- const taskStillDriven = redeemed !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId));
67
- return {
68
- taskId: wake.taskId,
69
- activated: redeemed !== undefined,
70
- taskStillDriven,
71
- finish: async () => {
72
- await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
73
- },
74
- // Re-park on the same ticket when the transport could not accept the turn, so a rejected
75
- // submit leaves the task exactly as it was rather than silently `open` with no step queued.
76
- rollback: async () => {
77
- if (redeemed)
78
- await parkTask(channelDir, wake.taskId, redeemed.ticket);
79
- },
80
- };
81
- }
82
- /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
83
- * <taskId>.` completion wake. A background job has no rollback bookkeeping — its wake
84
- * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
85
- export async function claimVerifiedJobWake(event, workspaceDir, jobManager, hooks) {
16
+ export async function claimVerifiedWake(event, workspaceDir, owner, hooks) {
86
17
  const wake = event.internalWake;
87
- if (wake?.kind !== "job")
18
+ if (!wake || typeof event.dispatchId !== "string")
88
19
  return undefined;
89
- const jobs = await jobManager.list();
90
- if (!isTrustedInternalWake(event, "job", wake.resourceId, wake.taskId) ||
91
- !isVerifiedJobWake(jobs, wake.resourceId, wake.taskId) ||
92
- !(await jobManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
20
+ if (!(await owner.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId)))
93
21
  return undefined;
94
- }
22
+ const dispatchId = event.dispatchId;
95
23
  const channelDir = getChannelDir(workspaceDir, event.channelId);
96
24
  hooks?.beforeActivation?.();
97
- const redeemed = await redeemTicket(channelDir, wake.taskId, (ticket) => ticket.kind === "job" && ticket.id === wake.resourceId);
98
- const taskStillDriven = redeemed !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId));
25
+ const redeemed = await redeemTicket(channelDir, wake.taskId, (ticket) => ticket.kind === "work");
99
26
  return {
100
27
  taskId: wake.taskId,
101
28
  activated: redeemed !== undefined,
102
- taskStillDriven,
103
- finish: async () => {
104
- await jobManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
105
- },
29
+ taskStillDriven: redeemed !== undefined || (await isTaskActivelyDriven(channelDir, wake.taskId)),
30
+ finish: () => owner.finishWakeConsumption(wake.resourceId, dispatchId),
106
31
  };
107
32
  }
@@ -129,22 +129,57 @@ function matchesAllowedHost(hostname, allowedHosts) {
129
129
  const normalized = normalizeHost(hostname);
130
130
  return allowedHosts.some((candidate) => normalizeHost(candidate) === normalized);
131
131
  }
132
+ /**
133
+ * An IPv4-mapped IPv6 address (`::ffff:a.b.c.d`, the `::ffff:0:0/96` range) is the same host as
134
+ * the embedded IPv4 address — a dual-stack socket connecting to `::ffff:127.0.0.1` reaches
135
+ * loopback exactly as `127.0.0.1` would. `isPrivateAddress`/`matchesAllowedCidr` used to check
136
+ * such an address only against the IPv6 private ranges, which do not cover this mapped range, so
137
+ * a mapped private/loopback address (R4) sailed through as "not private". Returns the dotted-quad
138
+ * form when `address` is a mapped IPv4 address, else `null`.
139
+ */
140
+ function ipv4MappedEmbeddedAddress(address) {
141
+ if (isIP(address) !== 6) {
142
+ return null;
143
+ }
144
+ const value = parseIpv6(address);
145
+ if (value === null) {
146
+ return null;
147
+ }
148
+ if (value >> 32n !== 0xffffn) {
149
+ return null;
150
+ }
151
+ const low32 = value & 0xffffffffn;
152
+ return [24n, 16n, 8n, 0n].map((shift) => Number((low32 >> shift) & 0xffn)).join(".");
153
+ }
154
+ /** Every address form a guard check must consider for `address`: itself, plus (when it is an
155
+ * IPv4-mapped IPv6 address) the IPv4 address it actually maps to. */
156
+ function expandForGuardCheck(address) {
157
+ const version = isIP(address);
158
+ if (version === 4) {
159
+ return [{ address, version: 4 }];
160
+ }
161
+ if (version === 6) {
162
+ const mapped = ipv4MappedEmbeddedAddress(address);
163
+ return mapped
164
+ ? [
165
+ { address, version: 6 },
166
+ { address: mapped, version: 4 },
167
+ ]
168
+ : [{ address, version: 6 }];
169
+ }
170
+ return [];
171
+ }
132
172
  function matchesAllowedCidr(address, allowedCidrs) {
133
- return allowedCidrs.some((cidr) => ipInCidr(address, cidr.trim()));
173
+ return expandForGuardCheck(address).some(({ address: candidate }) => allowedCidrs.some((cidr) => ipInCidr(candidate, cidr.trim())));
134
174
  }
135
175
  function isBlockedHost(hostname) {
136
176
  const normalized = normalizeHost(hostname);
137
177
  return normalized.endsWith(".localhost") || BLOCKED_HOSTS.has(normalized);
138
178
  }
139
179
  function isPrivateAddress(address) {
140
- const version = isIP(address);
141
- if (version === 4) {
142
- return PRIVATE_IPV4_CIDRS.some((cidr) => ipInCidr(address, cidr));
143
- }
144
- if (version === 6) {
145
- return PRIVATE_IPV6_CIDRS.some((cidr) => ipInCidr(address, cidr));
146
- }
147
- return false;
180
+ return expandForGuardCheck(address).some(({ address: candidate, version }) => version === 4
181
+ ? PRIVATE_IPV4_CIDRS.some((cidr) => ipInCidr(candidate, cidr))
182
+ : PRIVATE_IPV6_CIDRS.some((cidr) => ipInCidr(candidate, cidr)));
148
183
  }
149
184
  async function validateUrlTarget(rawUrl, context, stage) {
150
185
  const url = (() => {
@@ -1,11 +1,4 @@
1
- /**
2
- * Settings management for pipiclaw.
3
- *
4
- * `log.jsonl` and `context.jsonl` are treated as raw cold storage.
5
- * They are not proactively scanned or loaded as part of the memory model.
6
- *
7
- * This module currently provides only PipiclawSettingsManager.
8
- */
1
+ /** Settings management for pipiclaw: `settings.json` (product intent only) and the code constants that replaced the retired knobs. */
9
2
  import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
10
3
  import { type MemoryMaintenanceTuning } from "./memory/maintenance-tuning.js";
11
4
  import type { ResponseMode } from "./runtime/dingtalk.js";
package/dist/settings.js CHANGED
@@ -1,11 +1,4 @@
1
- /**
2
- * Settings management for pipiclaw.
3
- *
4
- * `log.jsonl` and `context.jsonl` are treated as raw cold storage.
5
- * They are not proactively scanned or loaded as part of the memory model.
6
- *
7
- * This module currently provides only PipiclawSettingsManager.
8
- */
1
+ /** Settings management for pipiclaw: `settings.json` (product intent only) and the code constants that replaced the retired knobs. */
9
2
  import { existsSync, mkdirSync, readFileSync } from "fs";
10
3
  import { dirname, join } from "path";
11
4
  import * as log from "./log.js";
@@ -22,8 +22,6 @@ const MAX_SUB_AGENT_TASK_CHARS = 12000;
22
22
  const MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS = 16000;
23
23
  const ALLOWED_CONTEXT_MODES = ["isolated", "contextual"];
24
24
  const ALLOWED_MEMORY_MODES = ["none", "index"];
25
- /** Spec 050, D12: `session`/`relevant` are retired — both collapse to `index`. */
26
- const LEGACY_MEMORY_MODE_ALIASES = { session: "index", relevant: "index" };
27
25
  // "max" is a real SDK ThinkingLevel; pipiclaw's own whitelist previously omitted it (spec 040, D4).
28
26
  const ALLOWED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
29
27
  const ALLOWED_RUNTIMES = ["internal", "external"];
@@ -195,8 +193,7 @@ function parseContextChoice(raw) {
195
193
  }
196
194
  /**
197
195
  * `defaultValue` is computed per call site rather than derived from `contextMode` inside this
198
- * function (spec 042 D4): internal keeps following `contextMode` (`contextual` → `relevant`),
199
- * but an external role's default is always `none` regardless of `contextMode` — a role that
196
+ * function (spec 042 D4): internal keeps following `contextMode` (`contextual` → `index`), but an external role's default is always `none` regardless of `contextMode` — a role that
200
197
  * merely wants `paths` injected (via `contextMode: contextual`) should not also silently start
201
198
  * sending session/memory content to a third-party process.
202
199
  */
@@ -208,13 +205,6 @@ function parseMemoryMode(raw, defaultValue) {
208
205
  if (ALLOWED_MEMORY_MODES.includes(normalized)) {
209
206
  return { value: normalized };
210
207
  }
211
- // Frontmatter lives in the user's workspace, not under this codebase's control, so a role
212
- // written against the retired `session`/`relevant` values keeps loading — with a warning —
213
- // instead of being dropped (spec 050, D12).
214
- const legacy = LEGACY_MEMORY_MODE_ALIASES[normalized];
215
- if (legacy) {
216
- return { value: legacy, warning: `memory: "${normalized}" is retired; treating it as "${legacy}"` };
217
- }
218
208
  return {
219
209
  value: defaultValue,
220
210
  error: `Unknown memory "${normalized}". Allowed values: ${ALLOWED_MEMORY_MODES.join(", ")}`,
@@ -404,9 +394,7 @@ function parseInternalAgent(entryName, filePath, frontmatter, body, name, descri
404
394
  const bashWithoutMutatesWarning = toolParse.tools.includes("bash") && mutates.value === undefined
405
395
  ? 'tools include bash but "mutates" is not declared; if this role writes to the workspace, declare mutates: write so it participates in the workspace write lease'
406
396
  : undefined;
407
- const combinedWarningBody = [numericWarning, memoryMode.warning, bashWithoutMutatesWarning]
408
- .filter(Boolean)
409
- .join("; ");
397
+ const combinedWarningBody = [numericWarning, bashWithoutMutatesWarning].filter(Boolean).join("; ");
410
398
  return {
411
399
  warning: combinedWarningBody ? `${entryName}: ${combinedWarningBody}` : undefined,
412
400
  agent: {
@@ -484,9 +472,11 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
484
472
  ? `${entryName}: memory: ${memoryMode.value} sends the channel memory index / journal content to this external process`
485
473
  : undefined;
486
474
  const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC);
475
+ // An empty body is a legitimate declaration for an external role, not a defect: a capability
476
+ // entry ("this agent, this model, this reasoning level") deliberately carries no standing
477
+ // instruction, because the only party that knows what this delegation is for is the main
478
+ // agent writing `task`. Internal roles still require a body — they have no other prompt.
487
479
  const trimmedBody = body.trim();
488
- if (!trimmedBody)
489
- return { warning: `${entryName}: empty system prompt body` };
490
480
  const promptLengthError = validateSubAgentSystemPrompt(trimmedBody, "Sub-agent system prompt");
491
481
  if (promptLengthError)
492
482
  return { warning: `${entryName}: ${promptLengthError}` };
@@ -509,7 +499,7 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
509
499
  : undefined;
510
500
  // All non-fatal (the role still loads); joined rather than picking one so an unlucky
511
501
  // combination never silently loses one of them.
512
- const combinedWarning = [memoryMode.warning, memoryDisclosureWarning, modelPlaceholderWarning].filter(Boolean).join("; ") || undefined;
502
+ const combinedWarning = [memoryDisclosureWarning, modelPlaceholderWarning].filter(Boolean).join("; ") || undefined;
513
503
  return {
514
504
  warning: combinedWarning,
515
505
  agent: {
@@ -56,7 +56,9 @@ export const claudeCodeHarness = {
56
56
  if (!existing.effort && effort && !used.has("$EFFORT")) {
57
57
  args.push("--effort", effort);
58
58
  }
59
- if (!used.has("$SYSTEM_PROMPT_FILE")) {
59
+ // A role with an empty body has no system-prompt file on disk, so the flag is omitted
60
+ // entirely rather than pointed at a path that was never written.
61
+ if (!used.has("$SYSTEM_PROMPT_FILE") && input.systemPromptFile) {
60
62
  args.push("--append-system-prompt-file", input.systemPromptFile);
61
63
  }
62
64
  let presetSessionId;
@@ -16,8 +16,10 @@ export interface ExternalInvocationInput {
16
16
  /** Path to the stdin prompt file (D1 layout: `<artifactDir>/prompt.txt`). */
17
17
  promptFile: string;
18
18
  /** Path to the role's system-prompt file (`<artifactDir>/system-prompt.txt`), for harnesses
19
- * that reference it by flag (e.g. claude-code's `--append-system-prompt-file`). */
20
- systemPromptFile: string;
19
+ * that reference it by flag (e.g. claude-code's `--append-system-prompt-file`). Undefined
20
+ * when the role declares no system prompt at all (a capability entry with an empty body):
21
+ * the file is then not written, so no harness may reference a path that does not exist. */
22
+ systemPromptFile?: string;
21
23
  /** Set when this invocation continues an earlier run (`subagent_run op=follow_up`, D6). */
22
24
  resumeSessionId?: string;
23
25
  }
@@ -18,7 +18,7 @@ export interface LaunchExternalRunInput {
18
18
  runManager: SubAgentRunManager;
19
19
  runId: string;
20
20
  channelId: string;
21
- /** Needed only for `purpose=verify`: where the attestation gets written. */
21
+ /** Where a task-bound run logs its dispatch and settlement (spec 052, D4). */
22
22
  channelDir?: string;
23
23
  label: string;
24
24
  agent: string;
@@ -38,6 +38,8 @@ export interface LaunchExternalRunInput {
38
38
  artifactDir: string;
39
39
  purpose: "work" | "verify";
40
40
  taskId?: string;
41
+ /** The Work Items id this run was dispatched for (spec 052, D4). */
42
+ item?: string;
41
43
  leaseKey?: string;
42
44
  resumeSessionId?: string;
43
45
  /** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
@@ -8,7 +8,6 @@ import { killProcessGroup, probeCliVersion, readProcessStartTime, reapProcessGro
8
8
  import { splitShellWords } from "../../shared/shell-words.js";
9
9
  import { errorMessage } from "../../shared/text-utils.js";
10
10
  import { createEmptyUsageTotals } from "../../shared/types.js";
11
- import { workspaceSubjectSnapshot } from "../../tasks/artifact-subject.js";
12
11
  import { getExternalHarness } from "./registry.js";
13
12
  import { finalizeExternalRun } from "./settlement.js";
14
13
  /**
@@ -102,7 +101,12 @@ function buildStdinContent(harnessId, systemPrompt, task) {
102
101
  // itself, folded ahead of the task.
103
102
  if (harnessId === "claude-code")
104
103
  return task;
105
- return `${systemPrompt.trim()}\n\n---\n\n${task.trim()}\n`;
104
+ const trimmedPrompt = systemPrompt.trim();
105
+ // A capability entry declares no system prompt at all: the task must then start the prompt,
106
+ // with no leading blank section and no `---` fence separating it from nothing.
107
+ if (!trimmedPrompt)
108
+ return `${task.trim()}\n`;
109
+ return `${trimmedPrompt}\n\n---\n\n${task.trim()}\n`;
106
110
  }
107
111
  /** Launches an external run. Resolves once the process is confirmed spawned (or fails fast if it
108
112
  * never starts, spec 042 D2); the wait-for-exit-and-settle work continues in the background
@@ -120,18 +124,14 @@ export async function launchExternalRun(input) {
120
124
  // either way.
121
125
  await mkdir(input.artifactDir, { recursive: true });
122
126
  const promptFile = join(input.artifactDir, "prompt.txt");
123
- const systemPromptFile = join(input.artifactDir, "system-prompt.txt");
127
+ const trimmedSystemPrompt = input.systemPrompt.trim();
128
+ // Only written when the role actually declares one, so `system-prompt.txt`'s presence in a run's
129
+ // artifacts stays a truthful record of what was sent (D1 layout) instead of an empty decoy.
130
+ const systemPromptFile = trimmedSystemPrompt ? join(input.artifactDir, "system-prompt.txt") : undefined;
124
131
  const stdinContent = buildStdinContent(harness.id, input.systemPrompt, input.task);
125
132
  await writeFile(promptFile, `${input.task.trim()}\n`, "utf-8");
126
- await writeFile(systemPromptFile, `${input.systemPrompt.trim()}\n`, "utf-8");
127
- // D9: an external verifier's advisory attestation needs a before/after subject snapshot the
128
- // same way the internal path does — taken here, before the process starts, since this is the
129
- // earliest point at which the run is committed to running against this workingDirectory. The
130
- // fixed base and initial untracked manifest survive a later normal Git commit.
131
- const verifySubjectSnapshot = input.purpose === "verify" ? await workspaceSubjectSnapshot(input.workingDirectory) : undefined;
132
- const verifySubjectBefore = verifySubjectSnapshot?.hash;
133
- const verifyBaseCommit = verifySubjectSnapshot?.baseCommit;
134
- const verifyBaselineUntrackedPaths = verifySubjectSnapshot?.baselineUntrackedPaths;
133
+ if (systemPromptFile)
134
+ await writeFile(systemPromptFile, `${trimmedSystemPrompt}\n`, "utf-8");
135
135
  const argv = input.shell ? [] : splitShellWords(input.command);
136
136
  const invocation = input.shell
137
137
  ? { executable: "/bin/sh", args: ["-lc", input.command], resumable: false }
@@ -163,6 +163,7 @@ export async function launchExternalRun(input) {
163
163
  model: input.externalModelRef,
164
164
  purpose: input.purpose,
165
165
  taskId: input.taskId,
166
+ item: input.item,
166
167
  workingDirectory: input.workingDirectory,
167
168
  artifactDir: input.artifactDir,
168
169
  channelDir: input.channelDir,
@@ -286,10 +287,7 @@ export async function launchExternalRun(input) {
286
287
  sessionId: invocation.presetSessionId,
287
288
  // Spec 042 D1: persisted so a restart reconciliation has the same inputs the live watcher
288
289
  // below would — without these, a run that finishes after the daemon disappears would settle
289
- // with an inaccurate timeout message, no verify attestation, and an unestimatable duration.
290
- verifySubjectBefore,
291
- verifyBaseCommit,
292
- verifyBaselineUntrackedPaths,
290
+ // with an inaccurate timeout message and an unestimatable duration.
293
291
  maxWallTimeSec: input.maxWallTimeSec,
294
292
  processStartedAt,
295
293
  channelDir: input.channelDir,
@@ -377,21 +375,14 @@ export async function launchExternalRun(input) {
377
375
  // id — `finalizeExternalRun` keeps all of that; only `status` and `failureReason` get overridden
378
376
  // by `terminationReason` (P1-1).
379
377
  await finalizeExternalRun({
380
- runId: input.runId,
381
- channelId: input.channelId,
382
- channelDir: input.channelDir,
383
378
  harnessId: harness.id,
384
379
  purpose: input.purpose,
385
- taskId: input.taskId,
386
380
  workingDirectory: input.workingDirectory,
387
381
  artifactDir: input.artifactDir,
388
382
  exitCode,
389
383
  durationMs,
390
384
  terminationReason,
391
385
  maxWallTimeSec: input.maxWallTimeSec,
392
- verifySubjectBefore,
393
- verifyBaseCommit,
394
- verifyBaselineUntrackedPaths,
395
386
  mutates: input.mutates,
396
387
  }, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
397
388
  log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
@@ -16,14 +16,8 @@ export interface BuildExternalSettleInputInput {
16
16
  */
17
17
  export declare function buildExternalSettleInput(input: BuildExternalSettleInputInput): SettleInput;
18
18
  export interface FinalizeExternalRunInput {
19
- runId: string;
20
- channelId: string;
21
- /** Needed only for `purpose=verify`: where the attestation gets written. Absent on an older
22
- * record (predating spec 042) — verify processing degrades to "skip" rather than guessing. */
23
- channelDir?: string;
24
19
  harnessId: RunHarness;
25
20
  purpose: "work" | "verify";
26
- taskId?: string;
27
21
  workingDirectory: string;
28
22
  artifactDir: string;
29
23
  /** `undefined` when the process was killed by a signal, or when this is a restart
@@ -33,21 +27,15 @@ export interface FinalizeExternalRunInput {
33
27
  durationEstimated?: boolean;
34
28
  terminationReason?: "timeout" | "cancelled";
35
29
  maxWallTimeSec?: number;
36
- /** The workspace subject hash taken just before this run started (D9's before/after pair for
37
- * external verify) — persisted at launch so restart reconciliation has it too. */
38
- verifySubjectBefore?: string;
39
- /** Fixed verification base and initial untracked manifest, persisted for restart reconciliation. */
40
- verifyBaseCommit?: string;
41
- verifyBaselineUntrackedPaths?: string[];
42
30
  /** P2-2: only a `write` run's completion pays for a `git status` summary — a `read` run cannot
43
31
  * have changed anything, and this must never become a hidden cost on the common read-only path. */
44
32
  mutates?: RunMutates;
45
33
  }
46
34
  /**
47
- * Read this run's artifact files, parse them through its harness, decide its verdict (including a
48
- * verify attestation when applicable), and hand the result to `settle`. Both the live post-exit
49
- * path and restart reconciliation call this and only this — there is no second implementation to
50
- * drift out of sync with the first (spec 042 F1).
35
+ * Read this run's artifact files, parse them through its harness, decide its verdict (for a
36
+ * `purpose=verify` run), and hand the result to `settle`. Both the live post-exit path and
37
+ * restart reconciliation call this and only this — there is no second implementation to drift out
38
+ * of sync with the first (spec 042 F1).
51
39
  */
52
40
  export declare function finalizeExternalRun(input: FinalizeExternalRunInput, settle: (settleInput: SettleInput, options: {
53
41
  announce: boolean;