@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
@@ -1,376 +1,50 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs";
1
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
2
2
  import { join } from "path";
3
3
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
4
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
5
- import { getOrCreateRunner } from "../agent/index.js";
6
- import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
5
+ import { createRunner } from "../agent/index.js";
6
+ import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
8
- import { resetRunner } from "../agent/runner-factory.js";
9
8
  import { renderStatus } from "../agent/status-render.js";
9
+ import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
10
10
  import { createExecutor } from "../executor.js";
11
11
  import * as log from "../log.js";
12
12
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
13
13
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
14
- import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, DEFAULT_APP_HOME_DIR, EVENT_HISTORY_PATH, LEGACY_APP_HOME_DIR, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
14
+ import { defaultModel } from "../models/utils.js";
15
15
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
16
16
  import { flushSecurityLogs } from "../security/logger.js";
17
17
  import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
19
19
  import { fileStamp } from "../shared/file-stamp.js";
20
20
  import { errorMessage } from "../shared/text-utils.js";
21
+ import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
22
+ import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
21
23
  import { readActiveTasks } from "../tasks/ledger.js";
22
- import { activateWaitingTask, claimTaskAttempt, finishTaskAttempt } from "../tasks/store.js";
24
+ import { finishTaskAttempt } from "../tasks/store.js";
23
25
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
24
26
  import { getUsageLedger } from "../usage/ledger.js";
25
27
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
28
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
26
29
  import { createChannelIndex } from "./channel-index.js";
27
30
  import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
28
31
  import { createDingTalkContext } from "./delivery.js";
29
- import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
32
+ import { DingTalkBot, } from "./dingtalk.js";
30
33
  import { DurableDispatchService } from "./durable-dispatch.js";
31
34
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
32
35
  import { createEventsWatcher } from "./events.js";
36
+ import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
33
37
  import { installLlmProxy } from "./proxy.js";
34
38
  import { ChannelStore } from "./store.js";
39
+ import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
35
40
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
36
41
  import { createTaskDriverEvent, createTaskVerificationEvent, TaskDriver } from "./task-driver.js";
37
42
  import { migrateLegacyTaskScheduleEvents, migrateLegacyTaskState } from "./task-migration.js";
38
- import { DEFAULT_AGENTS, DEFAULT_SOUL } from "./workspace-templates.js";
39
- const DEFAULT_MEMORY = `# Workspace Memory
40
-
41
- This file stores stable workspace-level memory.
42
-
43
- - It is intended to be managed by a human administrator.
44
- - It is not automatically rewritten by normal runtime consolidation.
45
- - Store durable shared background here when it should apply across channels.
46
- - Keep this file focused on stable facts, policies, and shared context, not transient conversation history.
47
-
48
- ## Shared Context
49
-
50
- <!-- Put team-wide or workspace-wide background here. -->
51
-
52
- ## Tooling And Environment
53
-
54
- <!-- Put durable tool usage rules, environment assumptions, or shared operational conventions here. -->
55
-
56
- ## Project Notes
57
-
58
- <!-- Put long-lived project facts here. -->
59
- `;
60
- const DEFAULT_ENVIRONMENT = `# Environment
61
-
62
- This file records durable environment facts and notable machine-level changes.
63
-
64
- - Record installed tools, runtime prerequisites, and important config changes here.
65
- - Keep entries concise and factual.
66
- - Do not use this file for task progress, conversation summaries, or project-specific decisions.
67
-
68
- ## Environment Facts
69
-
70
- <!-- Put stable machine or runtime facts here. -->
71
-
72
- ## Installed Tools
73
-
74
- <!-- Record durable tools or dependencies that were installed for this workspace. -->
75
-
76
- ## Config Changes
77
-
78
- <!-- Record important config or environment changes that affect future work. -->
79
- `;
80
- const CHANNEL_CONFIG_TEMPLATE = {
81
- clientId: "your-dingtalk-client-id",
82
- clientSecret: "your-dingtalk-client-secret",
83
- robotCode: "your-robot-code",
84
- cardTemplateId: "your-card-template-id",
85
- cardTemplateKey: "content",
86
- allowFrom: ["your-staff-id"],
87
- busyMessageDefault: "steer",
88
- responseMode: "full_progress_then_plain_final",
89
- cardAutoLayout: true,
90
- };
91
- const MODELS_CONFIG_TEMPLATE = { providers: {} };
92
- const TOOLS_CONFIG_TEMPLATE = {
93
- tools: {
94
- web: {
95
- enable: false,
96
- proxy: null,
97
- search: {
98
- provider: "brave",
99
- apiKey: "",
100
- maxResults: 5,
101
- },
102
- },
103
- tasks: {
104
- enabled: true,
105
- },
106
- },
107
- _examples: {
108
- proxy: "http://127.0.0.1:7890",
109
- apiKey: "BSA...",
110
- },
111
- _notes: [
112
- "Set tools.web.enable to true to register web_search and web_fetch.",
113
- "Replace tools.web.search.apiKey with your Brave API key before enabling web tools.",
114
- "If needed, copy _examples.proxy to tools.web.proxy.",
115
- "tools.tasks.enabled is the master switch for autonomous long-running tasks (task_manage tool + task driver + task digest).",
116
- ],
117
- };
118
- const SECURITY_CONFIG_TEMPLATE = {
119
- pathGuard: {
120
- enabled: true,
121
- },
122
- commandGuard: {
123
- enabled: true,
124
- },
125
- networkGuard: {
126
- enabled: false,
127
- },
128
- };
43
+ import { claimVerifiedDelegationWake, claimVerifiedJobWake } from "./task-wake.js";
129
44
  const SHUTDOWN_WAIT_MS = 15000;
130
45
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
131
46
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
132
47
  const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
133
- export const DEFAULT_BOOTSTRAP_PATHS = {
134
- appName: APP_NAME,
135
- appHomeDir: APP_HOME_DIR,
136
- workspaceDir: WORKSPACE_DIR,
137
- authConfigPath: AUTH_CONFIG_PATH,
138
- channelConfigPath: CHANNEL_CONFIG_PATH,
139
- modelsConfigPath: MODELS_CONFIG_PATH,
140
- settingsConfigPath: SETTINGS_CONFIG_PATH,
141
- toolsConfigPath: TOOLS_CONFIG_PATH,
142
- securityConfigPath: SECURITY_CONFIG_PATH,
143
- eventHistoryPath: EVENT_HISTORY_PATH,
144
- };
145
- export class BootstrapExitError extends Error {
146
- constructor(code, message) {
147
- super(message ?? `Bootstrap requested exit with code ${code}`);
148
- this.code = code;
149
- this.name = "BootstrapExitError";
150
- }
151
- }
152
- export function isBootstrapExitError(error) {
153
- return error instanceof BootstrapExitError;
154
- }
155
- export function readCliVersion() {
156
- try {
157
- const raw = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf-8"));
158
- return typeof raw.version === "string" && raw.version.trim() ? raw.version : "0.0.0";
159
- }
160
- catch {
161
- return "0.0.0";
162
- }
163
- }
164
- function writeTextFileIfMissing(path, content, label, created, mode) {
165
- if (existsSync(path)) {
166
- return false;
167
- }
168
- writeFileSync(path, content, mode !== undefined ? { encoding: "utf-8", mode } : "utf-8");
169
- created.push(label);
170
- return true;
171
- }
172
- function writeJsonFileIfMissing(path, value, label, created, mode) {
173
- return writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\n`, label, created, mode);
174
- }
175
- // App-level config files that may hold secrets (DingTalk client secret, provider
176
- // API keys, Brave key). They are created owner-only, and any pre-existing file with
177
- // looser bits is tightened on startup.
178
- const SECRET_FILE_MODE = 0o600;
179
- function hardenExistingSecretFile(path) {
180
- if (!existsSync(path)) {
181
- return;
182
- }
183
- try {
184
- const mode = statSync(path).mode & 0o777;
185
- if ((mode & 0o077) !== 0) {
186
- chmodSync(path, SECRET_FILE_MODE);
187
- log.logInfo(`Tightened permissions on ${path} to 0600`);
188
- }
189
- }
190
- catch (err) {
191
- log.logWarning(`Failed to tighten permissions on ${path}`, errorMessage(err));
192
- }
193
- }
194
- // FIXME(0.9.0): remove this legacy-home migration (and LEGACY_APP_HOME_DIR).
195
- // The default app home moved from `~/.pi/pipiclaw` to `~/.pipiclaw`. When the
196
- // new default location is not yet present but a legacy install is, move the old
197
- // directory over so existing users keep their config/workspace/state with no
198
- // manual step. Exported for direct testing; the env-gating (only for the real
199
- // default home, never a custom PIPICLAW_HOME) lives at the call site.
200
- export function migrateLegacyAppHome(targetDir, legacyDir, io) {
201
- if (existsSync(targetDir) || !existsSync(legacyDir)) {
202
- return false;
203
- }
204
- try {
205
- renameSync(legacyDir, targetDir);
206
- io.log(`Migrated existing data from ${legacyDir} to ${targetDir}.`);
207
- return true;
208
- }
209
- catch (err) {
210
- io.error(`Failed to migrate ${legacyDir} to ${targetDir}: ${errorMessage(err)}`);
211
- io.error(`Move it manually, or set PIPICLAW_HOME=${legacyDir} to keep using the old location.`);
212
- throw new BootstrapExitError(1);
213
- }
214
- }
215
- export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
216
- const created = [];
217
- // FIXME(0.9.0): remove alongside migrateLegacyAppHome.
218
- if (paths.appHomeDir === DEFAULT_APP_HOME_DIR) {
219
- migrateLegacyAppHome(paths.appHomeDir, LEGACY_APP_HOME_DIR, io);
220
- }
221
- if (!existsSync(paths.appHomeDir)) {
222
- mkdirSync(paths.appHomeDir, { recursive: true });
223
- created.push("app home");
224
- }
225
- if (!existsSync(paths.workspaceDir)) {
226
- mkdirSync(paths.workspaceDir, { recursive: true });
227
- created.push("workspace/");
228
- }
229
- for (const dir of ["skills", "events", "sub-agents"]) {
230
- const dirPath = join(paths.workspaceDir, dir);
231
- if (!existsSync(dirPath)) {
232
- mkdirSync(dirPath, { recursive: true });
233
- created.push(`workspace/${dir}/`);
234
- }
235
- }
236
- writeTextFileIfMissing(join(paths.workspaceDir, "SOUL.md"), DEFAULT_SOUL, "workspace/SOUL.md", created);
237
- writeTextFileIfMissing(join(paths.workspaceDir, "AGENTS.md"), DEFAULT_AGENTS, "workspace/AGENTS.md", created);
238
- writeTextFileIfMissing(join(paths.workspaceDir, "MEMORY.md"), DEFAULT_MEMORY, "workspace/MEMORY.md", created);
239
- writeTextFileIfMissing(join(paths.workspaceDir, "ENVIRONMENT.md"), DEFAULT_ENVIRONMENT, "workspace/ENVIRONMENT.md", created);
240
- const secretConfigPaths = [
241
- paths.channelConfigPath,
242
- paths.authConfigPath,
243
- paths.modelsConfigPath,
244
- paths.settingsConfigPath,
245
- paths.toolsConfigPath,
246
- paths.securityConfigPath,
247
- ];
248
- const channelTemplateCreated = writeJsonFileIfMissing(paths.channelConfigPath, CHANNEL_CONFIG_TEMPLATE, "channel.json", created, SECRET_FILE_MODE);
249
- writeJsonFileIfMissing(paths.authConfigPath, {}, "auth.json", created, SECRET_FILE_MODE);
250
- writeJsonFileIfMissing(paths.modelsConfigPath, MODELS_CONFIG_TEMPLATE, "models.json", created, SECRET_FILE_MODE);
251
- writeJsonFileIfMissing(paths.settingsConfigPath, {}, "settings.json", created, SECRET_FILE_MODE);
252
- writeJsonFileIfMissing(paths.toolsConfigPath, TOOLS_CONFIG_TEMPLATE, "tools.json", created, SECRET_FILE_MODE);
253
- writeJsonFileIfMissing(paths.securityConfigPath, SECURITY_CONFIG_TEMPLATE, "security.json", created, SECRET_FILE_MODE);
254
- // Tighten any pre-existing config that predates owner-only creation.
255
- for (const secretPath of secretConfigPaths) {
256
- hardenExistingSecretFile(secretPath);
257
- }
258
- return { created, channelTemplateCreated };
259
- }
260
- function isPlaceholderString(value) {
261
- return value.trim().startsWith("your-");
262
- }
263
- function listChannelConfigIssues(config) {
264
- const issues = [];
265
- if (!config.clientId) {
266
- issues.push("Missing required field `clientId`.");
267
- }
268
- else if (isPlaceholderString(config.clientId)) {
269
- issues.push("Replace placeholder value for `clientId`.");
270
- }
271
- if (!config.clientSecret) {
272
- issues.push("Missing required field `clientSecret`.");
273
- }
274
- else if (isPlaceholderString(config.clientSecret)) {
275
- issues.push("Replace placeholder value for `clientSecret`.");
276
- }
277
- if (config.robotCode && isPlaceholderString(config.robotCode)) {
278
- issues.push("Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.");
279
- }
280
- if (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {
281
- issues.push("Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.");
282
- }
283
- if (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {
284
- issues.push("Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.");
285
- }
286
- const busyMessageDefault = config.busyMessageDefault;
287
- if (busyMessageDefault !== undefined && !isBusyMessageDefaultConfig(busyMessageDefault)) {
288
- issues.push('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
289
- }
290
- const responseMode = config.responseMode;
291
- if (responseMode !== undefined && !isResponseModeConfig(responseMode)) {
292
- issues.push('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
293
- }
294
- const cardAutoLayout = config.cardAutoLayout;
295
- if (cardAutoLayout !== undefined && typeof cardAutoLayout !== "boolean") {
296
- issues.push("Invalid `cardAutoLayout`: expected boolean.");
297
- }
298
- return issues;
299
- }
300
- export function printBootstrapSummary(result, io = console, paths = DEFAULT_BOOTSTRAP_PATHS) {
301
- if (result.created.length === 0) {
302
- return;
303
- }
304
- io.log(`Initialized ${paths.appName} under ${paths.appHomeDir}:`);
305
- for (const item of result.created) {
306
- io.log(` - ${item}`);
307
- }
308
- io.log("");
309
- }
310
- export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
311
- let parsed;
312
- try {
313
- parsed = JSON.parse(readFileSync(paths.channelConfigPath, "utf-8"));
314
- }
315
- catch (err) {
316
- io.error(`Failed to parse configuration: ${paths.channelConfigPath}`);
317
- io.error(errorMessage(err));
318
- throw new BootstrapExitError(1);
319
- }
320
- const issues = listChannelConfigIssues(parsed);
321
- if (issues.length > 0) {
322
- io.error(`Configuration is not ready: ${paths.channelConfigPath}`);
323
- for (const issue of issues) {
324
- io.error(` - ${issue}`);
325
- }
326
- io.error("");
327
- io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
328
- throw new BootstrapExitError(1);
329
- }
330
- parsed.cardTemplateKey = parsed.cardTemplateKey || "content";
331
- parsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;
332
- parsed.busyMessageDefault = normalizeBusyMessageDefault(parsed.busyMessageDefault);
333
- parsed.responseMode = normalizeResponseMode(parsed.responseMode);
334
- parsed.cardAutoLayout = parsed.cardAutoLayout ?? true;
335
- if (Array.isArray(parsed.allowFrom)) {
336
- parsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);
337
- }
338
- return parsed;
339
- }
340
- export function parseArgs(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
341
- const args = argv.slice(2);
342
- for (let index = 0; index < args.length; index += 1) {
343
- const arg = args[index];
344
- if (index === 0 && arg === "run") {
345
- // Explicit name for the default daemon mode (`pipiclaw run` == `pipiclaw`).
346
- continue;
347
- }
348
- if (arg === "--help" || arg === "-h") {
349
- io.log(`Usage: ${paths.appName} [command] [options]`);
350
- io.log("");
351
- io.log("Commands:");
352
- io.log(" run Run the long-lived DingTalk daemon (default)");
353
- io.log(" tui [prompt] Chat with the agent in the terminal");
354
- io.log("");
355
- io.log("Options:");
356
- io.log(" --version Print the current version and exit");
357
- io.log(" --help, -h Show this help and exit");
358
- io.log("");
359
- io.log(`Config: ${paths.channelConfigPath}`);
360
- io.log(`Workspace: ${paths.workspaceDir}`);
361
- throw new BootstrapExitError(0);
362
- }
363
- else if (arg === "--version") {
364
- io.log(readCliVersion());
365
- throw new BootstrapExitError(0);
366
- }
367
- else {
368
- io.error(`Unknown option: ${arg}`);
369
- io.error(`Run \`${paths.appName} --help\` for usage.`);
370
- throw new BootstrapExitError(1);
371
- }
372
- }
373
- }
374
48
  function waitForTasks(tasks, timeoutMs) {
375
49
  if (tasks.length === 0) {
376
50
  return Promise.resolve(true);
@@ -384,31 +58,90 @@ function waitForTasks(tasks, timeoutMs) {
384
58
  });
385
59
  });
386
60
  }
387
- function flushInactiveChannelMemory(channelRunners) {
388
- const flushes = [];
61
+ /**
62
+ * Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
63
+ * `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
64
+ * from, unbounded, for the life of the process. Eviction below only ever touches idle runners —
65
+ * a busy one is left cached past the cap rather than mid-turn disposed.
66
+ */
67
+ const MAX_CACHED_RUNNERS = 50;
68
+ /**
69
+ * Drop the least-recently-used *idle* runners until the cache is back at the cap, disposing each
70
+ * one (flush memory, unsubscribe, release the SDK session) before dropping it. `channelRunners`
71
+ * is a `Map`, so insertion order is iteration order; `getRunner` below re-inserts on every cache
72
+ * hit to keep that order equal to recency of use — the standard "LRU via Map" idiom.
73
+ */
74
+ async function evictIdleRunnersOverCap(channelRunners) {
75
+ if (channelRunners.size <= MAX_CACHED_RUNNERS)
76
+ return;
389
77
  for (const [channelId, runner] of channelRunners) {
390
- if (runner.isBusy()) {
78
+ if (channelRunners.size <= MAX_CACHED_RUNNERS)
79
+ break;
80
+ if (runner.isBusy())
391
81
  continue;
392
- }
393
- flushes.push(runner.flushMemoryForShutdown().catch((err) => {
394
- log.logWarning(`[${channelId}] Failed to flush memory during shutdown`, errorMessage(err));
395
- }));
82
+ channelRunners.delete(channelId);
83
+ await runner.dispose().catch((err) => {
84
+ log.logWarning(`[${channelId}] Failed to dispose evicted runner`, errorMessage(err));
85
+ });
396
86
  }
397
- return flushes;
398
87
  }
399
88
  function isNoRunningTaskQueueError(err) {
400
89
  return err instanceof Error && err.message === "No task is currently running.";
401
90
  }
402
- export function createRuntimeContext(options) {
91
+ /**
92
+ * The `runRuntimeCommand` names usable on the idle-turn path. `context` is deliberately excluded:
93
+ * idle answers it through the runner's ChannelContext-aware command path (thread-reply, delete
94
+ * semantics) instead, so it is not part of this stateless-report dispatch here.
95
+ */
96
+ const IDLE_RUNTIME_COMMAND_NAMES = new Set(["events", "tasks", "status", "usage", "subagents", "project"]);
97
+ function isIdleRuntimeCommandName(name) {
98
+ return IDLE_RUNTIME_COMMAND_NAMES.has(name);
99
+ }
100
+ /**
101
+ * How long `/stop` waits for the turn to actually end before force-releasing it.
102
+ * `requestStop` + `abort` only reach the agent loop; a turn wedged in its
103
+ * epilogue (delivery drain, session-resource reload, memory flush) ignores both
104
+ * and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
105
+ */
106
+ const STOP_FORCE_END_GRACE_MS = 15_000;
107
+ const STOP_FORCE_END_POLL_MS = 250;
108
+ function sleepUnref(ms) {
109
+ return new Promise((resolve) => {
110
+ const timer = setTimeout(resolve, ms);
111
+ timer.unref?.();
112
+ });
113
+ }
114
+ /**
115
+ * Watchdog for `/stop`: release the channel if the stopped turn has not ended
116
+ * once the grace window elapses. Returns true when it had to force the release.
117
+ */
118
+ export async function forceEndStuckTurnAfterStop(input) {
119
+ const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
120
+ const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
121
+ const deadline = Date.now() + graceMs;
122
+ while (input.runner.isBusy() && Date.now() < deadline) {
123
+ await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
124
+ }
125
+ if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
126
+ return false;
127
+ }
128
+ await input
129
+ .notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
130
+ .catch(() => undefined);
131
+ return true;
132
+ }
133
+ export async function createRuntimeContext(options) {
403
134
  const startServices = options.startServices ?? true;
404
135
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
405
136
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
406
- const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
137
+ const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
407
138
  log.configureLogging(runtimeSettingsManager.getLoggingSettings());
408
139
  const startedAt = Date.now();
409
140
  const cliVersion = readCliVersion();
410
141
  const channelRunners = new Map();
411
142
  const activeTasks = new Set();
143
+ /** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
144
+ const stopWatchdogs = new Set();
412
145
  // `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
413
146
  // stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
414
147
  const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
@@ -424,30 +157,37 @@ export function createRuntimeContext(options) {
424
157
  }
425
158
  };
426
159
  const getRunner = (channelId) => {
427
- let runner = channelRunners.get(channelId);
428
- if (!runner) {
429
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
430
- ensureChannelMemoryFilesSync(channelDir);
431
- runner = getOrCreateRunner(channelId, channelDir, {
432
- appHomeDir: options.paths.appHomeDir,
433
- authConfigPath: options.paths.authConfigPath,
434
- modelsConfigPath: options.paths.modelsConfigPath,
435
- onSessionEvent: options.observer,
436
- // The DingTalk bot is the media sender for this transport; enables `send_media`.
437
- // `bot` is defined below in this same scope and initialized before any message
438
- // (and thus any getRunner call) can arrive.
439
- mediaSender: bot,
440
- dispatchVerification: async (taskId) => {
441
- const entries = await readActiveTasks(join(channelDir, "tasks"));
442
- const entry = entries.find((candidate) => candidate.id === taskId);
443
- if (!entry)
444
- return false;
445
- const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
446
- return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
447
- },
448
- });
449
- channelRunners.set(channelId, runner);
160
+ const existing = channelRunners.get(channelId);
161
+ if (existing) {
162
+ // Re-insert to move this channel to the end (most-recently-used) of the Map's
163
+ // iteration order, which evictIdleRunnersOverCap relies on.
164
+ channelRunners.delete(channelId);
165
+ channelRunners.set(channelId, existing);
166
+ return existing;
450
167
  }
168
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
169
+ ensureChannelMemoryFilesSync(channelDir);
170
+ const runner = createRunner(channelId, channelDir, {
171
+ appHomeDir: options.paths.appHomeDir,
172
+ authConfigPath: options.paths.authConfigPath,
173
+ modelsConfigPath: options.paths.modelsConfigPath,
174
+ settingsManager: runtimeSettingsManager,
175
+ onSessionEvent: options.observer,
176
+ // The DingTalk bot is the media sender for this transport; enables `send_media`.
177
+ // `bot` is defined below in this same scope and initialized before any message
178
+ // (and thus any getRunner call) can arrive.
179
+ mediaSender: bot,
180
+ dispatchVerification: async (taskId) => {
181
+ const entries = await readActiveTasks(join(channelDir, "tasks"));
182
+ const entry = entries.find((candidate) => candidate.id === taskId);
183
+ if (!entry)
184
+ return false;
185
+ const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
186
+ return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
187
+ },
188
+ });
189
+ channelRunners.set(channelId, runner);
190
+ void evictIdleRunnersOverCap(channelRunners);
451
191
  return runner;
452
192
  };
453
193
  const handler = {
@@ -493,56 +233,106 @@ export function createRuntimeContext(options) {
493
233
  log.logWarning(`[${channelId}] Failed to reset durable-dispatch leases on stop`, errorMessage(err));
494
234
  });
495
235
  log.logInfo(`[${channelId}] Stop requested`);
236
+ if (!stopWatchdogs.has(channelId)) {
237
+ stopWatchdogs.add(channelId);
238
+ void forceEndStuckTurnAfterStop({
239
+ channelId,
240
+ runner,
241
+ graceMs: options.stopForceEndGraceMs,
242
+ notify: (text) => _bot.sendPlain(channelId, text),
243
+ })
244
+ .catch((err) => {
245
+ log.logWarning(`[${channelId}] Stop watchdog failed`, errorMessage(err));
246
+ })
247
+ .finally(() => {
248
+ stopWatchdogs.delete(channelId);
249
+ });
250
+ }
496
251
  }
497
252
  return { pausedTaskId };
498
253
  },
499
- async handleEventsCommand(event, bot, args) {
500
- const response = await runEventsCommand({
501
- args,
502
- workspaceDir: options.paths.workspaceDir,
503
- historyPath: options.paths.eventHistoryPath,
504
- });
505
- await bot.sendPlain(event.channelId, response);
506
- },
507
- async handleTasksCommand(event, bot, args) {
508
- const response = await runTasksCommand({
509
- args,
510
- channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
511
- workspaceDir: options.paths.workspaceDir,
512
- channelId: event.channelId,
513
- dispatchTask: async (id, attemptGeneration) => {
514
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
515
- const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
516
- if (!entry)
517
- return false;
518
- // A human asking to run a task twice means twice, so this key is deliberately
519
- // unique per invocation rather than sharing the driver's occurrence key (D1).
520
- const now = Date.now();
521
- const driverEvent = createTaskDriverEvent(event.channelId, entry, now, attemptGeneration);
522
- return ((await durableDispatch?.dispatch({
523
- ...driverEvent,
524
- dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
525
- })) ?? false);
526
- },
527
- });
528
- await bot.sendPlain(event.channelId, response);
529
- },
530
- async handleStatusCommand(event, bot) {
531
- const response = renderStatus({
532
- runner: channelRunners.get(event.channelId),
533
- version: cliVersion,
534
- uptimeMs: Date.now() - startedAt,
535
- });
536
- await bot.sendPlain(event.channelId, response);
537
- },
538
- async handleUsageCommand(event, bot, args) {
539
- const response = await renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
540
- await bot.sendPlain(event.channelId, response);
541
- },
542
- // Read-only prompt accounting; safe mid-turn, so it is answered here rather than by
543
- // the runner's idle command path.
544
- async handleContextCommand(event, bot, args) {
545
- await bot.sendPlain(event.channelId, getRunner(event.channelId).renderContextReport(args));
254
+ async runRuntimeCommand(event, name, args) {
255
+ switch (name) {
256
+ case "events":
257
+ return runEventsCommand({
258
+ args,
259
+ workspaceDir: options.paths.workspaceDir,
260
+ historyPath: options.paths.eventHistoryPath,
261
+ });
262
+ case "tasks":
263
+ return runTasksCommand({
264
+ args,
265
+ channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
266
+ workspaceDir: options.paths.workspaceDir,
267
+ channelId: event.channelId,
268
+ dispatchTask: async (id, attemptGeneration) => {
269
+ const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
270
+ const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
271
+ if (!entry)
272
+ return false;
273
+ // A human asking to run a task twice means twice, so this key is deliberately
274
+ // unique per invocation rather than sharing the driver's occurrence key (D1).
275
+ const now = Date.now();
276
+ const driverEvent = createTaskDriverEvent(event.channelId, entry, now, attemptGeneration);
277
+ return ((await durableDispatch?.dispatch({
278
+ ...driverEvent,
279
+ dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
280
+ })) ?? false);
281
+ },
282
+ });
283
+ case "status":
284
+ return renderStatus({
285
+ runner: channelRunners.get(event.channelId),
286
+ version: cliVersion,
287
+ uptimeMs: Date.now() - startedAt,
288
+ });
289
+ case "usage":
290
+ return renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
291
+ // Read-only prompt accounting; safe mid-turn, so the busy path answers it through
292
+ // this stateless report rather than the runner's ChannelContext-aware idle path.
293
+ case "context":
294
+ return getRunner(event.channelId).renderContextReport(args);
295
+ // A human control path independent of the model (spec 040, D6): `/stop` no longer kills a
296
+ // dispatched delegation, so cancel must work whether or not a runner is currently active.
297
+ case "subagents":
298
+ return runSubagentsCommand({
299
+ args,
300
+ channelId: event.channelId,
301
+ discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
302
+ // `roles` needs a role directory even for a channel that has never spoken this boot —
303
+ // resolved from disk, without spinning up a full ChannelRunner (spec 041).
304
+ getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
305
+ workspaceDir: options.paths.workspaceDir,
306
+ authConfigPath: options.paths.authConfigPath,
307
+ modelsConfigPath: options.paths.modelsConfigPath,
308
+ }),
309
+ });
310
+ case "project":
311
+ return runProjectCommand({
312
+ args,
313
+ channelId: event.channelId,
314
+ channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
315
+ appHomeDir: options.paths.appHomeDir,
316
+ actor: "dingtalk-command",
317
+ isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
318
+ listActiveBlockers: () => [
319
+ ...getSubAgentRunManager(event.channelId)
320
+ .list()
321
+ .filter((record) => record.status === "running")
322
+ .map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
323
+ ...channelRunningJobLines(event.channelId),
324
+ ],
325
+ // D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
326
+ // The active-session ref is untouched — same session, new project root.
327
+ onScopeChanged: async () => {
328
+ const runner = channelRunners.get(event.channelId);
329
+ channelRunners.delete(event.channelId);
330
+ await runner?.dispose().catch((err) => {
331
+ log.logWarning(`[${event.channelId}] Failed to dispose runner after /project`, errorMessage(err));
332
+ });
333
+ },
334
+ });
335
+ }
546
336
  },
547
337
  async handleBusyMessage(event, bot, mode, queueText) {
548
338
  if (shuttingDown) {
@@ -607,6 +397,7 @@ export function createRuntimeContext(options) {
607
397
  }
608
398
  const runner = getRunner(event.channelId);
609
399
  await durableDispatch?.markStarted(event.dispatchId);
400
+ let structuredWakeFinalized = event.internalWake === undefined;
610
401
  const task = (async () => {
611
402
  try {
612
403
  await archiveIncomingMessage(event.channelId, {
@@ -626,20 +417,9 @@ export function createRuntimeContext(options) {
626
417
  ctx: { channelId: event.channelId, userName: event.userName },
627
418
  fields: { command: builtInCommand.name },
628
419
  });
629
- if (builtInCommand.name === "events") {
630
- await handler.handleEventsCommand(event, bot, builtInCommand.args);
631
- return;
632
- }
633
- if (builtInCommand.name === "tasks") {
634
- await handler.handleTasksCommand(event, bot, builtInCommand.args);
635
- return;
636
- }
637
- if (builtInCommand.name === "status") {
638
- await handler.handleStatusCommand(event, bot);
639
- return;
640
- }
641
- if (builtInCommand.name === "usage") {
642
- await handler.handleUsageCommand(event, bot, builtInCommand.args);
420
+ if (isIdleRuntimeCommandName(builtInCommand.name)) {
421
+ const response = await handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
422
+ await bot.sendPlain(event.channelId, response);
643
423
  return;
644
424
  }
645
425
  if (isRunnerBuiltInCommand(builtInCommand)) {
@@ -666,27 +446,78 @@ export function createRuntimeContext(options) {
666
446
  // task-driver turn is measured as a delta (turns on a channel are serialized)
667
447
  // and credited to the task it was dispatched for.
668
448
  const effectsBefore = channelEffectCount(event.channelId);
669
- const jobTaskId = /^\[JOB:[^\]]+\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text)?.[1];
449
+ // Both wake formats below carry an unauthenticated claim in plain text: anything
450
+ // that can put a message on this channel can *write* "[JOB:x] ... belongs to task
451
+ // y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
452
+ // external agent's own untrusted stdout (spec 040, D8's threat model explicitly
453
+ // treats external output as untrusted). Activating a waiting task on text pattern
454
+ // alone lets that forged claim advance an unrelated task's attempt generation. The
455
+ // pattern match only extracts a *candidate* id pair now; both paths verify the
456
+ // named run/job actually exists, is done, and really is the one that names this
457
+ // taskId before ever calling `activateWaitingTask` (T9).
458
+ const jobTextMatch = /^\[JOB:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
459
+ const jobMatch = event.internalWake?.kind === "job"
460
+ ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
461
+ : jobTextMatch;
670
462
  let recoveredJobTaskId;
671
- if (jobTaskId) {
672
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
673
- const activated = await activateWaitingTask(channelDir, jobTaskId, "job");
674
- if (activated)
675
- recoveredJobTaskId = jobTaskId;
676
- if (activated?.fields.control) {
677
- const claim = await claimTaskAttempt(channelDir, jobTaskId, new Date());
678
- if (claim)
679
- event.taskAttemptGeneration = claim.generation;
463
+ if (jobMatch) {
464
+ const [, jobId, jobTaskId] = jobMatch;
465
+ const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, executor, options.wakeTransitionHooks?.job);
466
+ if (claimed) {
467
+ if (claimed.activated)
468
+ recoveredJobTaskId = claimed.taskId;
469
+ if (claimed.generation !== undefined)
470
+ event.taskAttemptGeneration = claimed.generation;
471
+ await claimed.finish();
472
+ structuredWakeFinalized = true;
473
+ if (event.internalWake?.kind === "job" && !claimed.activated)
474
+ return;
475
+ }
476
+ else {
477
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable [JOB:${jobId}] wake claiming task ${jobTaskId}`);
478
+ if (event.internalWake?.kind === "job") {
479
+ structuredWakeFinalized = true;
480
+ return;
481
+ }
482
+ }
483
+ }
484
+ // Spec 040, D7: a delegation run's completion wake carries the same "belongs to
485
+ // task" contract as a background job's, and reactivates a task parked with
486
+ // waitingFor="external-signal" the same way — verified the same way (T9).
487
+ const delegationTextMatch = /^\[SUBAGENT:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
488
+ const delegationMatch = event.internalWake?.kind === "subagent"
489
+ ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
490
+ : delegationTextMatch;
491
+ let recoveredDelegationTaskId;
492
+ if (delegationMatch) {
493
+ const [, runId, delegationTaskId] = delegationMatch;
494
+ const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, options.wakeTransitionHooks?.subagent);
495
+ if (claimed) {
496
+ if (claimed.activated)
497
+ recoveredDelegationTaskId = claimed.taskId;
498
+ if (claimed.generation !== undefined)
499
+ event.taskAttemptGeneration = claimed.generation;
500
+ await claimed.finish();
501
+ structuredWakeFinalized = true;
502
+ if (event.internalWake?.kind === "subagent" && !claimed.activated)
503
+ return;
504
+ }
505
+ else {
506
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable [SUBAGENT:${runId}] wake claiming task ${delegationTaskId}`);
507
+ if (event.internalWake?.kind === "subagent") {
508
+ structuredWakeFinalized = true;
509
+ return;
510
+ }
680
511
  }
681
512
  }
682
513
  const result = await runner.run(ctx, store);
683
514
  const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
684
- const taskAttemptId = taskDriverMatch?.[1] ?? recoveredJobTaskId;
685
- if (taskDriverMatch?.[1]) {
686
- noteTaskEffects(event.channelId, taskDriverMatch[1], channelEffectCount(event.channelId) - effectsBefore);
687
- }
688
- if (recoveredJobTaskId) {
689
- noteTaskEffects(event.channelId, recoveredJobTaskId, channelEffectCount(event.channelId) - effectsBefore);
515
+ const taskAttemptId = taskDriverMatch?.[1] ?? recoveredJobTaskId ?? recoveredDelegationTaskId;
516
+ // The three sources above are mutually exclusive (each regex is anchored at the
517
+ // start of a distinct prefix), so crediting effects to whichever one matched is
518
+ // equivalent to checking all three separately.
519
+ if (taskAttemptId) {
520
+ noteTaskEffects(event.channelId, taskAttemptId, channelEffectCount(event.channelId) - effectsBefore);
690
521
  }
691
522
  if (taskAttemptId && result.usage && result.durationMs !== undefined) {
692
523
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskAttemptId, {
@@ -711,7 +542,10 @@ export function createRuntimeContext(options) {
711
542
  });
712
543
  }
713
544
  finally {
714
- await durableDispatch?.markCompleted(event.dispatchId);
545
+ if (structuredWakeFinalized)
546
+ await durableDispatch?.markCompleted(event.dispatchId);
547
+ else
548
+ await durableDispatch?.markRetryable(event.dispatchId);
715
549
  runner.endTurn();
716
550
  // A finished turn may have written task files (progress/complete/set); rescan
717
551
  // now so a continuing task chain advances immediately instead of after a full sleep.
@@ -741,7 +575,39 @@ export function createRuntimeContext(options) {
741
575
  jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
742
576
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
743
577
  });
744
- void restoreChannelJobs(executor);
578
+ // Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
579
+ // and the usage/archive authority, wired before any turn can start a run.
580
+ configureSubAgentRuntime({
581
+ stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
582
+ dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
583
+ ledger: getUsageLedger(),
584
+ store,
585
+ });
586
+ // Admission (bot.start() below) must not open until every persisted job and run is back in
587
+ // memory: a message arriving mid-restore would see partial running-count/short-id/lease state,
588
+ // and durableDispatch's redelivery of a pending completion wake would find no record to claim.
589
+ // Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
590
+ // was already awaited — the same admission race P0-1 closed for delegation runs was still open
591
+ // for background jobs.
592
+ await restoreChannelJobs(executor);
593
+ await restoreAllSubAgentRuns();
594
+ // Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
595
+ // admission — a message routed to a still-dangling session would 400 against the provider on
596
+ // every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
597
+ // the job/run restores above: admission must see a structurally legal session, not a partial one.
598
+ const recoveryReport = await scanWorkspaceForInterruptedTurns(options.paths.workspaceDir, {
599
+ api: defaultModel.api,
600
+ provider: defaultModel.provider,
601
+ model: defaultModel.id,
602
+ });
603
+ if (recoveryReport.repaired.length > 0) {
604
+ log.logWarning("Repaired interrupted turns on restart", `${recoveryReport.repaired.length}/${recoveryReport.scanned} channel(s): ${recoveryReport.repaired
605
+ .map((r) => r.channelDir)
606
+ .join(", ")}`);
607
+ }
608
+ if (recoveryReport.blocked.length > 0) {
609
+ log.logWarning("Some channels have an unrecoverable session and will refuse new turns", recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "));
610
+ }
745
611
  const eventsWatcher = options.createEventsWatcher
746
612
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
747
613
  : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
@@ -773,6 +639,7 @@ export function createRuntimeContext(options) {
773
639
  runtimeSettingsManager.reload();
774
640
  return {
775
641
  memoryMaintenance: runtimeSettingsManager.getMemoryMaintenanceSettings(),
642
+ sessionMemory: runtimeSettingsManager.getSessionMemorySettings(),
776
643
  };
777
644
  },
778
645
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
@@ -817,6 +684,7 @@ export function createRuntimeContext(options) {
817
684
  durableDispatch?.stop();
818
685
  memoryMaintenanceScheduler.stop();
819
686
  eventsWatcher.stop();
687
+ stopSubAgentGarbageCollector();
820
688
  await bot.stop();
821
689
  const runningTasks = Array.from(activeTasks);
822
690
  if (runningTasks.length > 0) {
@@ -844,23 +712,25 @@ export function createRuntimeContext(options) {
844
712
  }
845
713
  }
846
714
  }
847
- const flushes = flushInactiveChannelMemory(channelRunners);
848
- if (flushes.length > 0) {
849
- log.logInfo(`Flushing memory for ${flushes.length} inactive channel(s) before shutdown`);
850
- const flushed = await waitForTasks(flushes, SHUTDOWN_FLUSH_WAIT_MS);
851
- if (!flushed) {
852
- log.logWarning(`Shutdown memory flush exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
853
- }
715
+ // Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
716
+ // still-busy one — its turn already aborted above — is just dropped from the cache and
717
+ // left to unwind on its own as the process exits.
718
+ const disposals = [];
719
+ for (const [channelId, runner] of channelRunners) {
720
+ if (runner.isBusy())
721
+ continue;
722
+ disposals.push(runner.dispose().catch((err) => {
723
+ log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
724
+ }));
854
725
  }
855
- for (const channelId of channelRunners.keys()) {
856
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
857
- resetRunner(channelId, {
858
- appHomeDir: options.paths.appHomeDir,
859
- authConfigPath: options.paths.authConfigPath,
860
- modelsConfigPath: options.paths.modelsConfigPath,
861
- onSessionEvent: options.observer,
862
- }, channelDir);
726
+ if (disposals.length > 0) {
727
+ log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
728
+ const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
729
+ if (!disposed) {
730
+ log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
731
+ }
863
732
  }
733
+ channelRunners.clear();
864
734
  const storageFlushes = [
865
735
  store.close(),
866
736
  // Cancels the debounce timer and lands the last activity times.
@@ -890,10 +760,25 @@ export function createRuntimeContext(options) {
890
760
  });
891
761
  }
892
762
  if (startServices) {
893
- // One-time close of the 027 migration window: fold any residual legacy `.schedule`
894
- // events into task frontmatter before the driver relies on frontmatter as the only cadence.
895
- void migrateLegacyTaskScheduleEvents(options.paths.workspaceDir);
896
- void migrateLegacyTaskState(options.paths.workspaceDir);
763
+ // One-time close of the 027/038 migration windows: fold any residual legacy `.schedule`
764
+ // events into task frontmatter, and upgrade v1 task status vocabulary, before the driver
765
+ // relies on the v2 contract alone. Both scan every channel's tasks/events, so they are
766
+ // gated on a marker file rather than repeated on every restart once a home has migrated.
767
+ const taskMigrationMarkerPath = join(options.paths.appHomeDir, "state", "task-migration.done");
768
+ if (!existsSync(taskMigrationMarkerPath)) {
769
+ void Promise.all([
770
+ migrateLegacyTaskScheduleEvents(options.paths.workspaceDir),
771
+ migrateLegacyTaskState(options.paths.workspaceDir),
772
+ ]).then(() => {
773
+ try {
774
+ mkdirSync(join(options.paths.appHomeDir, "state"), { recursive: true });
775
+ writeFileSync(taskMigrationMarkerPath, `${new Date().toISOString()}\n`);
776
+ }
777
+ catch (error) {
778
+ log.logWarning("Failed to write task migration marker", errorMessage(error));
779
+ }
780
+ });
781
+ }
897
782
  eventsWatcher.start();
898
783
  memoryMaintenanceScheduler.start();
899
784
  taskDriver.start();
@@ -950,7 +835,7 @@ export async function bootstrap(argv, options = {}) {
950
835
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
951
836
  const startServices = options.startServices ?? true;
952
837
  parseArgs(argv, paths, io);
953
- const bootstrapResult = bootstrapAppHome(paths, io);
838
+ const bootstrapResult = bootstrapAppHome(paths);
954
839
  printBootstrapSummary(bootstrapResult, io, paths);
955
840
  if (bootstrapResult.channelTemplateCreated) {
956
841
  io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
@@ -958,13 +843,14 @@ export async function bootstrap(argv, options = {}) {
958
843
  }
959
844
  const dingtalkConfig = loadConfig(paths, io);
960
845
  dingtalkConfig.stateDir = paths.workspaceDir;
961
- prepareAppServices(paths);
846
+ const { settingsManager } = prepareAppServices(paths);
962
847
  log.logStartup(paths.workspaceDir);
963
- const runtime = createRuntimeContext({
848
+ const runtime = await createRuntimeContext({
964
849
  paths,
965
850
  dingtalkConfig,
966
851
  registerSignalHandlers,
967
852
  startServices,
853
+ settingsManager,
968
854
  });
969
855
  return {
970
856
  bot: runtime.bot,