@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.10

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 (186) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +28 -0
  3. package/dist/agent/channel-runner.js +293 -145
  4. package/dist/agent/commands.d.ts +7 -1
  5. package/dist/agent/commands.js +26 -0
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +1 -1
  8. package/dist/agent/job-manager.d.ts +34 -6
  9. package/dist/agent/job-manager.js +73 -7
  10. package/dist/agent/progress-formatter.js +3 -3
  11. package/dist/agent/prompt/sections.js +46 -7
  12. package/dist/agent/prompt/types.d.ts +9 -0
  13. package/dist/agent/run-queue.d.ts +10 -1
  14. package/dist/agent/run-queue.js +19 -2
  15. package/dist/agent/runner-factory.d.ts +16 -4
  16. package/dist/agent/runner-factory.js +9 -23
  17. package/dist/agent/session-events.js +7 -42
  18. package/dist/agent/session-resource-gate.d.ts +17 -0
  19. package/dist/agent/session-resource-gate.js +33 -2
  20. package/dist/agent/status-render.js +1 -3
  21. package/dist/agent/turn-recovery.d.ts +72 -0
  22. package/dist/agent/turn-recovery.js +193 -0
  23. package/dist/agent/types.d.ts +21 -1
  24. package/dist/agent/types.js +3 -16
  25. package/dist/index.d.ts +2 -1
  26. package/dist/index.js +2 -1
  27. package/dist/main.js +2 -1
  28. package/dist/memory/extraction.js +0 -1
  29. package/dist/memory/maintenance-gates.d.ts +1 -1
  30. package/dist/memory/maintenance-jobs.js +2 -3
  31. package/dist/memory/metadata.d.ts +0 -15
  32. package/dist/memory/metadata.js +0 -7
  33. package/dist/memory/probation.d.ts +1 -5
  34. package/dist/memory/probation.js +2 -6
  35. package/dist/memory/review-log.js +0 -0
  36. package/dist/memory/scheduler.d.ts +1 -0
  37. package/dist/memory/scheduler.js +64 -6
  38. package/dist/models/auth-cli.d.ts +1 -1
  39. package/dist/models/auth-cli.js +3 -2
  40. package/dist/paths.d.ts +0 -6
  41. package/dist/paths.js +0 -6
  42. package/dist/playbooks/agent-delegation.md +48 -22
  43. package/dist/playbooks/background-jobs.md +1 -1
  44. package/dist/playbooks/catalog.d.ts +2 -2
  45. package/dist/playbooks/catalog.js +20 -9
  46. package/dist/playbooks/event-scheduling.md +1 -1
  47. package/dist/playbooks/memory-and-learning.md +1 -1
  48. package/dist/playbooks/outbound-media.md +5 -5
  49. package/dist/playbooks/runtime-orientation.md +8 -3
  50. package/dist/playbooks/task-driving.md +1 -1
  51. package/dist/playbooks/task-planning.md +1 -1
  52. package/dist/runtime/active-session-store.d.ts +42 -0
  53. package/dist/runtime/active-session-store.js +100 -0
  54. package/dist/runtime/app-home.d.ts +32 -0
  55. package/dist/runtime/app-home.js +319 -0
  56. package/dist/runtime/bootstrap.d.ts +30 -36
  57. package/dist/runtime/bootstrap.js +359 -473
  58. package/dist/runtime/channel-event.d.ts +41 -0
  59. package/dist/runtime/channel-event.js +1 -0
  60. package/dist/runtime/delivery.d.ts +3 -2
  61. package/dist/runtime/delivery.js +11 -6
  62. package/dist/runtime/dingtalk.d.ts +16 -28
  63. package/dist/runtime/dingtalk.js +6 -10
  64. package/dist/runtime/durable-dispatch.d.ts +8 -2
  65. package/dist/runtime/durable-dispatch.js +52 -25
  66. package/dist/runtime/events.d.ts +3 -2
  67. package/dist/runtime/events.js +2 -3
  68. package/dist/runtime/project-commands.d.ts +16 -0
  69. package/dist/runtime/project-commands.js +112 -0
  70. package/dist/runtime/project-scope-store.d.ts +31 -0
  71. package/dist/runtime/project-scope-store.js +102 -0
  72. package/dist/runtime/store.d.ts +7 -0
  73. package/dist/runtime/subagent-commands.d.ts +17 -0
  74. package/dist/runtime/subagent-commands.js +360 -0
  75. package/dist/runtime/task-commands.js +7 -3
  76. package/dist/runtime/task-driver.d.ts +7 -7
  77. package/dist/runtime/task-driver.js +1 -4
  78. package/dist/runtime/task-migration.js +1 -1
  79. package/dist/runtime/task-wake.d.ts +54 -0
  80. package/dist/runtime/task-wake.js +99 -0
  81. package/dist/security/config.js +10 -0
  82. package/dist/security/logger.js +10 -1
  83. package/dist/security/path-guard.js +34 -9
  84. package/dist/security/project-scope.d.ts +45 -0
  85. package/dist/security/project-scope.js +107 -0
  86. package/dist/security/types.d.ts +37 -3
  87. package/dist/settings.d.ts +0 -106
  88. package/dist/settings.js +0 -224
  89. package/dist/shared/host-process.d.ts +37 -0
  90. package/dist/shared/host-process.js +112 -0
  91. package/dist/shared/jsonl-appender.d.ts +2 -0
  92. package/dist/shared/jsonl-appender.js +25 -13
  93. package/dist/shared/shell-words.d.ts +9 -0
  94. package/dist/shared/shell-words.js +52 -0
  95. package/dist/shared/types.d.ts +1 -0
  96. package/dist/shared/types.js +10 -1
  97. package/dist/shared/wake-claim.d.ts +23 -0
  98. package/dist/shared/wake-claim.js +26 -0
  99. package/dist/shared/with-timeout.d.ts +14 -0
  100. package/dist/shared/with-timeout.js +38 -0
  101. package/dist/subagents/detached-discovery.d.ts +13 -0
  102. package/dist/subagents/detached-discovery.js +17 -0
  103. package/dist/subagents/discovery.d.ts +74 -1
  104. package/dist/subagents/discovery.js +429 -82
  105. package/dist/subagents/external/claude-code.d.ts +2 -0
  106. package/dist/subagents/external/claude-code.js +158 -0
  107. package/dist/subagents/external/codex-cli.d.ts +2 -0
  108. package/dist/subagents/external/codex-cli.js +133 -0
  109. package/dist/subagents/external/exec.d.ts +2 -0
  110. package/dist/subagents/external/exec.js +44 -0
  111. package/dist/subagents/external/harness.d.ts +121 -0
  112. package/dist/subagents/external/harness.js +109 -0
  113. package/dist/subagents/external/registry.d.ts +2 -0
  114. package/dist/subagents/external/registry.js +11 -0
  115. package/dist/subagents/external/run.d.ts +74 -0
  116. package/dist/subagents/external/run.js +286 -0
  117. package/dist/subagents/external/settlement.d.ts +50 -0
  118. package/dist/subagents/external/settlement.js +123 -0
  119. package/dist/subagents/format.d.ts +16 -0
  120. package/dist/subagents/format.js +31 -0
  121. package/dist/subagents/runs.d.ts +342 -0
  122. package/dist/subagents/runs.js +909 -0
  123. package/dist/subagents/tool.d.ts +68 -6
  124. package/dist/subagents/tool.js +547 -206
  125. package/dist/subagents/verification-outcome.d.ts +26 -0
  126. package/dist/subagents/verification-outcome.js +16 -0
  127. package/dist/subagents/workspace-lease.d.ts +45 -0
  128. package/dist/subagents/workspace-lease.js +61 -0
  129. package/dist/tasks/artifact-subject.js +50 -2
  130. package/dist/tasks/control.d.ts +12 -0
  131. package/dist/tasks/control.js +20 -0
  132. package/dist/tasks/ledger.js +1 -1
  133. package/dist/tasks/store.d.ts +21 -0
  134. package/dist/tasks/store.js +80 -0
  135. package/dist/{shared → tasks}/task-schedule.js +1 -1
  136. package/dist/tasks/verification.d.ts +8 -0
  137. package/dist/tasks/verification.js +10 -2
  138. package/dist/tools/bash.js +4 -4
  139. package/dist/tools/edit.js +3 -3
  140. package/dist/tools/event-manage.js +1 -4
  141. package/dist/tools/grep.js +5 -6
  142. package/dist/tools/index.d.ts +4 -1
  143. package/dist/tools/index.js +25 -3
  144. package/dist/tools/job.js +5 -5
  145. package/dist/tools/memory-manage.js +3 -7
  146. package/dist/tools/read.js +3 -3
  147. package/dist/tools/registry.js +2 -1
  148. package/dist/tools/send-media.js +2 -2
  149. package/dist/tools/session-search.js +0 -1
  150. package/dist/tools/skill-manage.js +3 -3
  151. package/dist/tools/subagent-manage.d.ts +37 -0
  152. package/dist/tools/subagent-manage.js +245 -0
  153. package/dist/tools/task-manage/shared.js +2 -2
  154. package/dist/tools/task-manage.js +1 -4
  155. package/dist/tools/tool-details.d.ts +1 -1
  156. package/dist/tools/web-fetch.js +0 -1
  157. package/dist/tools/write-content.js +3 -3
  158. package/dist/tui/app.d.ts +1 -1
  159. package/dist/tui/app.js +55 -6
  160. package/dist/tui/cli.d.ts +1 -1
  161. package/dist/tui/cli.js +1 -1
  162. package/dist/tui/commands.d.ts +2 -0
  163. package/dist/tui/commands.js +4 -0
  164. package/dist/tui/terminal-media-sender.d.ts +1 -1
  165. package/dist/tui/turn-controller.d.ts +2 -0
  166. package/dist/tui/turn-controller.js +2 -0
  167. package/dist/usage/ledger.d.ts +13 -0
  168. package/dist/usage/ledger.js +15 -2
  169. package/dist/usage/render.js +22 -0
  170. package/examples/sub-agents/README.md +75 -14
  171. package/examples/sub-agents/builder-hard.md +46 -0
  172. package/examples/sub-agents/builder.md +42 -0
  173. package/examples/sub-agents/documenter.md +50 -0
  174. package/examples/sub-agents/explorer.md +16 -13
  175. package/examples/sub-agents/git-committer.md +33 -40
  176. package/examples/sub-agents/log-sifter.md +46 -0
  177. package/examples/sub-agents/planner.md +42 -0
  178. package/examples/sub-agents/reviewer.md +31 -41
  179. package/examples/sub-agents/scout.md +30 -0
  180. package/examples/sub-agents/verifier.md +27 -37
  181. package/examples/sub-agents/worker.md +35 -0
  182. package/package.json +1 -1
  183. package/examples/sub-agents/researcher.md +0 -41
  184. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  185. /package/dist/{shared → tasks}/task-events.js +0 -0
  186. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -39,15 +39,13 @@ export function renderStatus(options) {
39
39
  try {
40
40
  const snapshot = runner.getStatusSnapshot();
41
41
  lines.push(`- Model: ${snapshot.model}`);
42
+ lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
42
43
  if (snapshot.fallback) {
43
44
  const until = new Date(snapshot.fallback.cooldownUntilMs);
44
45
  const hh = String(until.getHours()).padStart(2, "0");
45
46
  const mm = String(until.getMinutes()).padStart(2, "0");
46
47
  lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
47
48
  }
48
- if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
49
- lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
50
- }
51
49
  if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
52
50
  const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
53
51
  lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
@@ -0,0 +1,72 @@
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import { type SessionEntry, SessionManager } from "@earendil-works/pi-coding-agent";
3
+ interface DeclaredToolCall {
4
+ id: string;
5
+ name: string;
6
+ /** Index into the branch's message-entry sequence (source order), used to detect anomalies. */
7
+ entryIndex: number;
8
+ }
9
+ export type RepairPlan = {
10
+ kind: "none";
11
+ } | {
12
+ kind: "append-aborted-assistant";
13
+ } | {
14
+ kind: "append-tool-results";
15
+ calls: DeclaredToolCall[];
16
+ } | {
17
+ kind: "blocked";
18
+ reason: string;
19
+ };
20
+ /**
21
+ * Pure D11 planner: declared − fulfilled → the one repair action to take, or `blocked` when the
22
+ * branch's shape doesn't match a plain crash window (P7: an undecidable shape stops the channel,
23
+ * it never guesses).
24
+ */
25
+ export declare function planTurnRecovery(branch: SessionEntry[]): RepairPlan;
26
+ /** Fallback identity for the runtime-authored aborted assistant when the branch has no prior
27
+ * assistant message to copy api/provider/model from (e.g. crash before the first response ever
28
+ * landed). Never sent to a provider — this is a resolved message, not a request. */
29
+ export interface FallbackModelIdentity {
30
+ api: AssistantMessage["api"];
31
+ provider: AssistantMessage["provider"];
32
+ model: string;
33
+ }
34
+ export type TurnRecoveryOutcome = {
35
+ kind: "clean";
36
+ } | {
37
+ kind: "repaired";
38
+ appendedToolResults: number;
39
+ appendedAbortedAssistant: boolean;
40
+ } | {
41
+ kind: "blocked";
42
+ reason: string;
43
+ };
44
+ /**
45
+ * Runs the D11 plan against `sessionManager`'s current branch and, if a repair is called for,
46
+ * applies it via `appendMessage()` — the only mutation path (D12): never a direct rewrite of the
47
+ * JSONL file, never a tool call, never a model call, never a second delivery attempt.
48
+ */
49
+ export declare function recoverInterruptedTurn(sessionManager: SessionManager, fallbackModel: FallbackModelIdentity): TurnRecoveryOutcome;
50
+ export interface WorkspaceRecoveryReport {
51
+ scanned: number;
52
+ repaired: Array<{
53
+ channelDir: string;
54
+ outcome: Extract<TurnRecoveryOutcome, {
55
+ kind: "repaired";
56
+ }>;
57
+ }>;
58
+ blocked: Array<{
59
+ channelDir: string;
60
+ reason: string;
61
+ }>;
62
+ }
63
+ /**
64
+ * Daemon-startup half of D10: scans every channel directory under `workspaceDir` and repairs any
65
+ * interrupted turn found, *before* the daemon accepts traffic (point 1). Each channel gets its own
66
+ * fresh `SessionManager` here — safe because, at this point in startup, no `ChannelRunner` for any
67
+ * of these channels has been constructed yet, so nothing else holds a competing in-memory instance
68
+ * over the same file. `ChannelRunner`'s own constructor (D10 point 2) covers everything this scan
69
+ * cannot: a channel created after this scan ran, and re-running the barrier is idempotent either way.
70
+ */
71
+ export declare function scanWorkspaceForInterruptedTurns(workspaceDir: string, fallbackModel: FallbackModelIdentity): Promise<WorkspaceRecoveryReport>;
72
+ export {};
@@ -0,0 +1,193 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import { resolveActiveSessionFile } from "../runtime/active-session-store.js";
5
+ /**
6
+ * Repairs a session branch left with a declared-but-unfulfilled tool call by a process that
7
+ * exited between the assistant's tool call and the tool result being recorded (spec 043, D8-D16).
8
+ *
9
+ * The only thing this module does is make the branch structurally legal again (every declared
10
+ * tool call has a result) and honest about what happened (a runtime-authored, clearly-labeled
11
+ * message, never something dressed up as a real model or tool response). It never executes a
12
+ * tool, never calls a model, and never repeats a side effect — see D9/P6 for why that boundary is
13
+ * load-bearing, not just caution.
14
+ */
15
+ const SYNTHETIC_TOOL_RESULT_HEADER = "Error: Pipiclaw restarted before a durable result was recorded for this tool call.\n" +
16
+ "The operation may or may not have taken effect. Inspect the current target state before retrying; " +
17
+ "do not repeat the operation blindly.";
18
+ const SYNTHETIC_ABORTED_ASSISTANT_TEXT = "Error: Pipiclaw restarted before a response was generated. Re-send the request if it is still needed.";
19
+ function toolGuidance(toolName) {
20
+ if (toolName === "subagent" || toolName === "subagent_manage") {
21
+ return "先用 `subagent_manage op=list` / `show` 查询这次委派是否已经作为一个 durable run 存在。";
22
+ }
23
+ if (toolName === "job" || toolName === "bash") {
24
+ return "若这是一次异步操作(后台 job 或已启动的进程),先用 job `list` / `poll` 查记录,再决定是否需要重跑。";
25
+ }
26
+ if (toolName === "write" || toolName === "edit") {
27
+ return "用 read / grep / git status 检查目标文件的当前内容,再决定是否需要重新执行。";
28
+ }
29
+ if (toolName === "send_media") {
30
+ return "查询目标系统或向用户确认对方是否已经收到,不要自动再发一次。";
31
+ }
32
+ return "检查目标状态后再决定是否需要重试,不要盲目重复这次调用。";
33
+ }
34
+ function messageEntriesOf(branch) {
35
+ return branch.filter((entry) => entry.type === "message");
36
+ }
37
+ /**
38
+ * Pure D11 planner: declared − fulfilled → the one repair action to take, or `blocked` when the
39
+ * branch's shape doesn't match a plain crash window (P7: an undecidable shape stops the channel,
40
+ * it never guesses).
41
+ */
42
+ export function planTurnRecovery(branch) {
43
+ const entries = messageEntriesOf(branch);
44
+ if (entries.length === 0) {
45
+ return { kind: "none" };
46
+ }
47
+ const declared = [];
48
+ const fulfilled = new Set();
49
+ for (let i = 0; i < entries.length; i++) {
50
+ const message = entries[i].message;
51
+ if (message.role === "assistant") {
52
+ for (const item of message.content) {
53
+ if (item.type === "toolCall") {
54
+ declared.push({ id: item.id, name: item.name, entryIndex: i });
55
+ }
56
+ }
57
+ }
58
+ else if (message.role === "toolResult") {
59
+ if (fulfilled.has(message.toolCallId)) {
60
+ return { kind: "blocked", reason: `Duplicate tool result recorded for tool call ${message.toolCallId}.` };
61
+ }
62
+ fulfilled.add(message.toolCallId);
63
+ }
64
+ }
65
+ const missing = declared.filter((call) => !fulfilled.has(call.id));
66
+ if (missing.length > 0) {
67
+ const firstMissingIndex = missing[0].entryIndex;
68
+ // Sibling calls declared by the *same* assistant message as the first missing one are
69
+ // expected to show up as results in any order (parallel tool calls) — only a message that
70
+ // isn't one of them signals a genuine anomaly, not the ordinary interleaving of results.
71
+ const siblingIds = new Set(declared.filter((call) => call.entryIndex === firstMissingIndex).map((call) => call.id));
72
+ for (let i = firstMissingIndex + 1; i < entries.length; i++) {
73
+ const message = entries[i].message;
74
+ const isExpectedResult = message.role === "toolResult" && siblingIds.has(message.toolCallId);
75
+ if (!isExpectedResult) {
76
+ return {
77
+ kind: "blocked",
78
+ reason: "A message unrelated to the missing tool result(s) appears after them; this is not a plain " +
79
+ "crash window and cannot be safely repaired automatically.",
80
+ };
81
+ }
82
+ }
83
+ return { kind: "append-tool-results", calls: missing };
84
+ }
85
+ const last = entries[entries.length - 1].message;
86
+ if (last.role === "user") {
87
+ return { kind: "append-aborted-assistant" };
88
+ }
89
+ return { kind: "none" };
90
+ }
91
+ function mostRecentAssistant(branch) {
92
+ for (let i = branch.length - 1; i >= 0; i--) {
93
+ const entry = branch[i];
94
+ if (entry.type === "message" && entry.message.role === "assistant") {
95
+ return entry.message;
96
+ }
97
+ }
98
+ return undefined;
99
+ }
100
+ const ZERO_USAGE = {
101
+ input: 0,
102
+ output: 0,
103
+ cacheRead: 0,
104
+ cacheWrite: 0,
105
+ totalTokens: 0,
106
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
107
+ };
108
+ /**
109
+ * Runs the D11 plan against `sessionManager`'s current branch and, if a repair is called for,
110
+ * applies it via `appendMessage()` — the only mutation path (D12): never a direct rewrite of the
111
+ * JSONL file, never a tool call, never a model call, never a second delivery attempt.
112
+ */
113
+ export function recoverInterruptedTurn(sessionManager, fallbackModel) {
114
+ const branch = sessionManager.getBranch();
115
+ const plan = planTurnRecovery(branch);
116
+ if (plan.kind === "blocked") {
117
+ return plan;
118
+ }
119
+ if (plan.kind === "none") {
120
+ return { kind: "clean" };
121
+ }
122
+ if (plan.kind === "append-tool-results") {
123
+ for (const call of plan.calls) {
124
+ sessionManager.appendMessage({
125
+ role: "toolResult",
126
+ toolCallId: call.id,
127
+ toolName: call.name,
128
+ content: [{ type: "text", text: `${SYNTHETIC_TOOL_RESULT_HEADER}\n\n${toolGuidance(call.name)}` }],
129
+ isError: true,
130
+ timestamp: Date.now(),
131
+ });
132
+ }
133
+ return { kind: "repaired", appendedToolResults: plan.calls.length, appendedAbortedAssistant: false };
134
+ }
135
+ // plan.kind === "append-aborted-assistant"
136
+ const recent = mostRecentAssistant(branch);
137
+ const stopReason = "aborted";
138
+ sessionManager.appendMessage({
139
+ role: "assistant",
140
+ content: [{ type: "text", text: SYNTHETIC_ABORTED_ASSISTANT_TEXT }],
141
+ api: recent?.api ?? fallbackModel.api,
142
+ provider: recent?.provider ?? fallbackModel.provider,
143
+ model: recent?.model ?? fallbackModel.model,
144
+ usage: ZERO_USAGE,
145
+ stopReason,
146
+ timestamp: Date.now(),
147
+ });
148
+ return { kind: "repaired", appendedToolResults: 0, appendedAbortedAssistant: true };
149
+ }
150
+ /** A workspace child directory belongs to a channel iff its name starts with one of these
151
+ * prefixes — matches `channel-paths.ts`'s `CHANNEL_ID_PATTERN` without needing to reverse its
152
+ * `/` → `__` escaping, and skips AgentWorkspace resource dirs (skills/, sub-agents/, events/…). */
153
+ const CHANNEL_DIR_PREFIXES = ["dm_", "group_"];
154
+ /**
155
+ * Daemon-startup half of D10: scans every channel directory under `workspaceDir` and repairs any
156
+ * interrupted turn found, *before* the daemon accepts traffic (point 1). Each channel gets its own
157
+ * fresh `SessionManager` here — safe because, at this point in startup, no `ChannelRunner` for any
158
+ * of these channels has been constructed yet, so nothing else holds a competing in-memory instance
159
+ * over the same file. `ChannelRunner`'s own constructor (D10 point 2) covers everything this scan
160
+ * cannot: a channel created after this scan ran, and re-running the barrier is idempotent either way.
161
+ */
162
+ export async function scanWorkspaceForInterruptedTurns(workspaceDir, fallbackModel) {
163
+ const report = { scanned: 0, repaired: [], blocked: [] };
164
+ let entries;
165
+ try {
166
+ entries = await readdir(workspaceDir, { withFileTypes: true });
167
+ }
168
+ catch {
169
+ return report;
170
+ }
171
+ for (const entry of entries) {
172
+ if (!entry.isDirectory() || !CHANNEL_DIR_PREFIXES.some((prefix) => entry.name.startsWith(prefix))) {
173
+ continue;
174
+ }
175
+ const channelDir = join(workspaceDir, entry.name);
176
+ report.scanned++;
177
+ try {
178
+ const activeSessionFile = resolveActiveSessionFile(channelDir);
179
+ const sessionManager = SessionManager.open(join(channelDir, activeSessionFile), channelDir);
180
+ const outcome = recoverInterruptedTurn(sessionManager, fallbackModel);
181
+ if (outcome.kind === "repaired") {
182
+ report.repaired.push({ channelDir, outcome });
183
+ }
184
+ else if (outcome.kind === "blocked") {
185
+ report.blocked.push({ channelDir, reason: outcome.reason });
186
+ }
187
+ }
188
+ catch (error) {
189
+ report.blocked.push({ channelDir, reason: error instanceof Error ? error.message : String(error) });
190
+ }
191
+ }
192
+ return report;
193
+ }
@@ -1,7 +1,8 @@
1
1
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
2
  import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
- import type { UsageTotals } from "../shared/types.js";
4
+ import { type UsageTotals } from "../shared/types.js";
5
+ import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
5
6
  import type { RunnerBuiltInCommand } from "./commands.js";
6
7
  export interface RunnerStatusSnapshot {
7
8
  model: string;
@@ -51,6 +52,9 @@ export interface AgentRunner {
51
52
  getStatusSnapshot(): RunnerStatusSnapshot;
52
53
  /** `/context`: prompt/tool-schema accounting for the live session (spec 025 §9). */
53
54
  renderContextReport(args?: string): string;
55
+ /** `/subagents list`'s role-directory health tail (spec 040, D6): whatever this runner has
56
+ * already discovered, without forcing a rescan. */
57
+ getSubAgentDiscoverySnapshot(): SubAgentDiscoveryResult;
54
58
  abort(): Promise<void>;
55
59
  /**
56
60
  * Synchronously reserve the turn for a message. Transports MUST call this in
@@ -60,11 +64,27 @@ export interface AgentRunner {
60
64
  beginTurn(taskText: string): void;
61
65
  /** Release the turn (idempotent). Transports call this after all per-message work. */
62
66
  endTurn(): void;
67
+ /**
68
+ * Release a turn whose owner is wedged (a stalled epilogue: delivery drain,
69
+ * resource reload, memory flush) so the channel stops reporting busy. The
70
+ * wedged turn keeps running to completion; its later `endTurn` is ignored.
71
+ * Returns false when the runner was already idle. `/stop`'s last resort — a
72
+ * normal stop goes through `requestStop` + `abort`.
73
+ */
74
+ forceEndTurn(reason: string): boolean;
63
75
  /** True from beginTurn until endTurn. */
64
76
  isBusy(): boolean;
65
77
  /** Mark the current turn as user-stopped (no-op when idle). */
66
78
  requestStop(): void;
67
79
  getTurnStatus(): TurnStatus;
80
+ /**
81
+ * Release this runner's resources: flush pending memory, unsubscribe from session events, and
82
+ * dispose the underlying SDK session. A no-op (memory still flushed) while `isBusy()` — disposing
83
+ * the SDK session aborts in-flight work, so a caller must never call this on a busy runner and
84
+ * expect the turn to survive. The owning cache (daemon runtime map, TUI's single runner) must
85
+ * drop its own reference after calling this; a disposed runner is not reusable.
86
+ */
87
+ dispose(): Promise<void>;
68
88
  }
69
89
  export type FinalOutcome = {
70
90
  kind: "none";
@@ -1,3 +1,4 @@
1
+ import { createEmptyUsageTotals } from "../shared/types.js";
1
2
  export function createEmptyRunState() {
2
3
  return {
3
4
  ctx: null,
@@ -5,22 +6,8 @@ export function createEmptyRunState() {
5
6
  store: null,
6
7
  queue: null,
7
8
  pendingTools: new Map(),
8
- totalUsage: {
9
- input: 0,
10
- output: 0,
11
- cacheRead: 0,
12
- cacheWrite: 0,
13
- total: 0,
14
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
15
- },
16
- assistantUsage: {
17
- input: 0,
18
- output: 0,
19
- cacheRead: 0,
20
- cacheWrite: 0,
21
- total: 0,
22
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
23
- },
9
+ totalUsage: createEmptyUsageTotals(),
10
+ assistantUsage: createEmptyUsageTotals(),
24
11
  costKnown: true,
25
12
  usageSources: 0,
26
13
  stopReason: "stop",
package/dist/index.d.ts CHANGED
@@ -10,7 +10,8 @@
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
12
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
- export { type AppContext, type BootstrapOptions, type BootstrapPaths, type BootstrapResult, bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
13
+ export { type BootstrapPaths, type BootstrapResult, isBootstrapExitError } from "./runtime/app-home.js";
14
+ export { type AppContext, type BootstrapOptions, bootstrap } from "./runtime/bootstrap.js";
14
15
  export type { ChannelContext, FinalDelivery, ProgressStyle } from "./runtime/channel-context.js";
15
16
  export { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, type ResponseMode, } from "./runtime/dingtalk.js";
16
17
  export type { PipiclawSettings } from "./settings.js";
package/dist/index.js CHANGED
@@ -10,5 +10,6 @@
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
12
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
- export { bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
13
+ export { isBootstrapExitError } from "./runtime/app-home.js";
14
+ export { bootstrap } from "./runtime/bootstrap.js";
14
15
  export { DingTalkBot, } from "./runtime/dingtalk.js";
package/dist/main.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { runAuth } from "./models/auth-cli.js";
3
- import { bootstrap, isBootstrapExitError } from "./runtime/bootstrap.js";
3
+ import { isBootstrapExitError } from "./runtime/app-home.js";
4
+ import { bootstrap } from "./runtime/bootstrap.js";
4
5
  import { runTui } from "./tui/cli.js";
5
6
  function handleError(error) {
6
7
  if (isBootstrapExitError(error)) {
@@ -140,7 +140,6 @@ export function toMemoryOp(candidate, provenance, tier) {
140
140
  const metadata = {
141
141
  kind: candidate.kind,
142
142
  sourceType: "agent",
143
- trust: "inferred",
144
143
  sourceCorrelationId: provenance.correlationId,
145
144
  probationUntil: tier === "probationary" ? probationDeadline() : null,
146
145
  };
@@ -41,7 +41,7 @@ export interface StructuralMaintenanceMaterial {
41
41
  historyFoldingNeeded: boolean;
42
42
  hasMemoryContent: boolean;
43
43
  hasHistoryContent: boolean;
44
- /** Active entries whose probation lapsed or `expiresAt` was reached (spec 037, D8). */
44
+ /** Active entries whose probation lapsed (spec 037, D8). */
45
45
  expiredEntryCount: number;
46
46
  }
47
47
  export interface StructuralMaintenanceGateInput {
@@ -245,9 +245,8 @@ export async function runStructuralMaintenanceJob(input) {
245
245
  try {
246
246
  const correlationId = `structural-maintenance:${formatLocalTime(now)}`;
247
247
  const options = makeRunOptions(input, correlationId);
248
- // Probation/expiresAt eviction runs first, deterministically, before the LLM cleanup
249
- // pass sees the file — no point spending a cleanup prompt on entries about to be
250
- // invalidated (spec 037, D8).
248
+ // Probation eviction runs first, deterministically, before the LLM cleanup pass sees the
249
+ // file — no point spending a cleanup prompt on entries about to be invalidated (spec 037, D8).
251
250
  const expiredCount = decision.runProbationExpiry ? await expireMemoryEntries(input.channelDir, now) : 0;
252
251
  const [cachedMemory, currentHistory] = await loadFiles();
253
252
  // `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
@@ -1,17 +1,9 @@
1
1
  export type MemoryEntryKind = "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
2
2
  export type MemorySourceType = "user" | "agent" | "repo" | "tool" | "web" | "legacy";
3
- export type MemoryTrust = "explicit" | "verified" | "inferred" | "untrusted";
4
- export type MemorySensitivity = "normal" | "personal" | "secret";
5
3
  export type MemoryEntryStatus = "active" | "superseded" | "invalidated" | "forgotten";
6
4
  export interface MemoryWriteMetadataInput {
7
5
  kind?: MemoryEntryKind;
8
- subjectId?: string;
9
- ownerId?: string;
10
6
  sourceType?: MemorySourceType;
11
- trust?: MemoryTrust;
12
- validFrom?: string;
13
- expiresAt?: string;
14
- sensitivity?: MemorySensitivity;
15
7
  sourceCorrelationId?: string;
16
8
  /**
17
9
  * Probationary write deadline (spec 037, D6/D7): `undefined` leaves any existing value alone,
@@ -24,19 +16,12 @@ export interface MemoryWriteMetadataInput {
24
16
  export interface MemoryEntryMetadata {
25
17
  id: string;
26
18
  kind: MemoryEntryKind;
27
- scope: "channel";
28
- subjectId?: string;
29
- ownerId?: string;
30
19
  sourceEntryIds: string[];
31
20
  sourceCorrelationIds: string[];
32
21
  sourceType: MemorySourceType;
33
- trust: MemoryTrust;
34
22
  createdAt: string;
35
23
  updatedAt: string;
36
- validFrom?: string;
37
- expiresAt?: string;
38
24
  status: MemoryEntryStatus;
39
- sensitivity: MemorySensitivity;
40
25
  sectionHeading: string;
41
26
  contentHash: string;
42
27
  recallCount: number;
@@ -57,22 +57,15 @@ export async function syncMemoryMetadata(channelDir, activeEntries, updates = []
57
57
  entries[entry.id] = {
58
58
  id: entry.id,
59
59
  kind: hint?.kind ?? previous?.kind ?? inferKind(entry.sectionHeading),
60
- scope: "channel",
61
- subjectId: hint?.subjectId ?? previous?.subjectId,
62
- ownerId: hint?.ownerId ?? previous?.ownerId,
63
60
  sourceEntryIds: Array.from(new Set([...(previous?.sourceEntryIds ?? []), ...(update?.sourceEntryIds ?? [])])),
64
61
  sourceCorrelationIds: Array.from(new Set([
65
62
  ...(previous?.sourceCorrelationIds ?? []),
66
63
  ...(hint?.sourceCorrelationId ? [hint.sourceCorrelationId] : []),
67
64
  ])),
68
65
  sourceType: hint?.sourceType ?? previous?.sourceType ?? "legacy",
69
- trust: hint?.trust ?? previous?.trust ?? "inferred",
70
66
  createdAt: previous?.createdAt ?? entry.timestamp ?? timestamp,
71
67
  updatedAt: update || previous?.contentHash !== contentHash(entry.content) ? timestamp : previous.updatedAt,
72
- validFrom: hint?.validFrom ?? previous?.validFrom,
73
- expiresAt: hint?.expiresAt ?? previous?.expiresAt,
74
68
  status: "active",
75
- sensitivity: hint?.sensitivity ?? previous?.sensitivity ?? "normal",
76
69
  sectionHeading: entry.sectionHeading,
77
70
  contentHash: contentHash(entry.content),
78
71
  recallCount: previous?.recallCount ?? 0,
@@ -6,11 +6,7 @@ import { readMemoryMetadata } from "./metadata.js";
6
6
  */
7
7
  export declare const MEMORY_PROBATION_DAYS = 30;
8
8
  export declare function probationDeadline(now?: Date): string;
9
- /**
10
- * Active entries whose probation lapsed, or whose (otherwise unconsumed) `expiresAt` was
11
- * reached. Both are "this entry's time is up" — they share one eviction path even though their
12
- * semantics differ: `probationUntil` is cancelled by use, `expiresAt` is unconditional.
13
- */
9
+ /** Active entries whose probation lapsed. */
14
10
  export declare function collectExpiredEntryIds(metadata: Awaited<ReturnType<typeof readMemoryMetadata>>, now?: Date): string[];
15
11
  /**
16
12
  * Evict every expired entry via `invalidate`, never `forget` (spec 037, D8): probation lapsing
@@ -16,15 +16,11 @@ function isPast(value, nowMs) {
16
16
  const ms = parseLocalTime(value);
17
17
  return ms !== undefined && ms <= nowMs;
18
18
  }
19
- /**
20
- * Active entries whose probation lapsed, or whose (otherwise unconsumed) `expiresAt` was
21
- * reached. Both are "this entry's time is up" — they share one eviction path even though their
22
- * semantics differ: `probationUntil` is cancelled by use, `expiresAt` is unconditional.
23
- */
19
+ /** Active entries whose probation lapsed. */
24
20
  export function collectExpiredEntryIds(metadata, now = new Date()) {
25
21
  const nowMs = now.getTime();
26
22
  return Object.values(metadata.entries)
27
- .filter((entry) => entry.status === "active" && (isPast(entry.probationUntil, nowMs) || isPast(entry.expiresAt, nowMs)))
23
+ .filter((entry) => entry.status === "active" && isPast(entry.probationUntil, nowMs))
28
24
  .map((entry) => entry.id);
29
25
  }
30
26
  /**
Binary file
@@ -27,6 +27,7 @@ export interface MemoryMaintenanceSchedulerOptions {
27
27
  isChannelActive: (channelId: string) => boolean;
28
28
  getSettings: () => {
29
29
  memoryMaintenance: PipiclawMemoryMaintenanceSettings;
30
+ sessionMemory: PipiclawSessionMemorySettings;
30
31
  };
31
32
  intervalMs?: number;
32
33
  }
@@ -6,9 +6,57 @@ import * as log from "../log.js";
6
6
  import { discoverWorkspaceChannelIds } from "../runtime/channel-index.js";
7
7
  import { isChannelId } from "../runtime/channel-paths.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
+ import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
9
10
  import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
10
- import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
11
+ import { getMemoryMaintenanceStateDir, readMemoryMaintenanceState } from "./maintenance-state.js";
11
12
  const DEFAULT_TICK_INTERVAL_MS = 60_000;
13
+ /**
14
+ * Cheap due-time predicate, evaluated before `getRuntimeContext` (transcript access, model
15
+ * resolution, settings reload) is paid for.
16
+ *
17
+ * Reuses the real gates with optimistic material (transcript-derived checks always pass), so the
18
+ * only work here is one state-file read plus timestamp arithmetic. A gate's material checks are
19
+ * purely additive restrictions on top of the cheap checks (interval/backoff/idle/dirty), so
20
+ * optimistic material can only ever make this predicate *more* permissive than the real job would
21
+ * be — it never wrongly skips a channel that a job would actually run for.
22
+ */
23
+ async function mightAnyMaintenanceJobBeDue(input) {
24
+ const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
25
+ const sessionRefresh = shouldRunSessionRefresh({
26
+ now: input.now,
27
+ state,
28
+ sessionMemory: input.settings.sessionMemory,
29
+ maintenance: input.settings.memoryMaintenance,
30
+ channelActive: false,
31
+ hasNewSessionEntry: () => true,
32
+ hasMeaningfulMaterial: () => true,
33
+ });
34
+ if (sessionRefresh.allowed)
35
+ return true;
36
+ const checkpoint = shouldRunMemoryCheckpoint({
37
+ now: input.now,
38
+ state,
39
+ maintenance: input.settings.memoryMaintenance,
40
+ channelActive: false,
41
+ material: () => ({ hasNewEntry: true, hasMeaningfulExchange: true, batchSize: Number.MAX_SAFE_INTEGER }),
42
+ });
43
+ if (checkpoint.allowed)
44
+ return true;
45
+ const structural = await shouldRunStructuralMaintenance({
46
+ now: input.now,
47
+ state,
48
+ maintenance: input.settings.memoryMaintenance,
49
+ channelActive: false,
50
+ material: async () => ({
51
+ memoryCleanupNeeded: true,
52
+ historyFoldingNeeded: true,
53
+ hasMemoryContent: true,
54
+ hasHistoryContent: true,
55
+ expiredEntryCount: 1,
56
+ }),
57
+ });
58
+ return structural.allowed;
59
+ }
12
60
  async function listStateChannels(appHomeDir) {
13
61
  try {
14
62
  const entries = await readdir(getMemoryMaintenanceStateDir(appHomeDir), { withFileTypes: true });
@@ -47,9 +95,12 @@ export class MemoryMaintenanceScheduler {
47
95
  this.nextChannelIndex = 0;
48
96
  }
49
97
  start() {
50
- if (this.timer || !this.options.getSettings().memoryMaintenance.enabled) {
98
+ if (this.timer) {
51
99
  return;
52
100
  }
101
+ // `enabled` is re-checked on every tick inside `runOnce`, which is nearly free when
102
+ // disabled (one cached settings read, no channel scan). Gating `start()` on it too would
103
+ // mean flipping `memoryMaintenance.enabled` on at runtime never actually starts the timer.
53
104
  this.timer = setInterval(() => {
54
105
  void this.runOnce().catch((error) => {
55
106
  log.logWarning("Memory maintenance scheduler tick failed", errorMessage(error));
@@ -65,8 +116,8 @@ export class MemoryMaintenanceScheduler {
65
116
  this.timer = null;
66
117
  }
67
118
  async runOnce(now = new Date()) {
68
- const settings = this.options.getSettings().memoryMaintenance;
69
- if (!settings.enabled || this.running) {
119
+ const settings = this.options.getSettings();
120
+ if (!settings.memoryMaintenance.enabled || this.running) {
70
121
  return;
71
122
  }
72
123
  this.running = true;
@@ -76,7 +127,7 @@ export class MemoryMaintenanceScheduler {
76
127
  workspaceDir: this.options.workspaceDir,
77
128
  knownChannelIds: this.options.getKnownChannelIds?.(),
78
129
  });
79
- const maxConcurrent = normalizeMaxConcurrentChannels(settings.maxConcurrentChannels);
130
+ const maxConcurrent = normalizeMaxConcurrentChannels(settings.memoryMaintenance.maxConcurrentChannels);
80
131
  if (channelIds.length === 0) {
81
132
  return;
82
133
  }
@@ -85,7 +136,14 @@ export class MemoryMaintenanceScheduler {
85
136
  let index = this.nextChannelIndex % channelIds.length;
86
137
  while (scanned < channelIds.length && selected.length < maxConcurrent) {
87
138
  const channelId = channelIds[index];
88
- if (channelId && !this.options.isChannelActive(channelId)) {
139
+ if (channelId &&
140
+ !this.options.isChannelActive(channelId) &&
141
+ (await mightAnyMaintenanceJobBeDue({
142
+ appHomeDir: this.options.appHomeDir,
143
+ channelId,
144
+ settings,
145
+ now,
146
+ }))) {
89
147
  selected.push(channelId);
90
148
  }
91
149
  index = (index + 1) % channelIds.length;
@@ -1,4 +1,4 @@
1
- import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/app-home.js";
2
2
  export type ParsedAuth = {
3
3
  kind: "status";
4
4
  } | {