@oyasmi/pipiclaw 0.9.0-beta.5 → 0.9.0-beta.7

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 (76) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +8 -0
  3. package/dist/agent/channel-runner.js +154 -132
  4. package/dist/agent/commands.d.ts +6 -0
  5. package/dist/agent/job-manager.js +6 -10
  6. package/dist/agent/progress-formatter.js +3 -3
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +2 -1
  9. package/dist/main.js +2 -1
  10. package/dist/memory/extraction.js +0 -1
  11. package/dist/memory/maintenance-gates.d.ts +1 -1
  12. package/dist/memory/maintenance-jobs.js +2 -3
  13. package/dist/memory/metadata.d.ts +0 -15
  14. package/dist/memory/metadata.js +0 -7
  15. package/dist/memory/probation.d.ts +1 -5
  16. package/dist/memory/probation.js +2 -6
  17. package/dist/models/auth-cli.d.ts +1 -1
  18. package/dist/models/auth-cli.js +3 -2
  19. package/dist/paths.d.ts +0 -6
  20. package/dist/paths.js +0 -6
  21. package/dist/playbooks/agent-delegation.md +9 -8
  22. package/dist/playbooks/background-jobs.md +1 -1
  23. package/dist/playbooks/catalog.d.ts +2 -2
  24. package/dist/playbooks/catalog.js +20 -9
  25. package/dist/playbooks/event-scheduling.md +1 -1
  26. package/dist/playbooks/memory-and-learning.md +1 -1
  27. package/dist/playbooks/outbound-media.md +5 -5
  28. package/dist/playbooks/runtime-orientation.md +1 -1
  29. package/dist/playbooks/task-driving.md +1 -1
  30. package/dist/playbooks/task-planning.md +1 -1
  31. package/dist/runtime/app-home.d.ts +32 -0
  32. package/dist/runtime/app-home.js +319 -0
  33. package/dist/runtime/bootstrap.d.ts +3 -69
  34. package/dist/runtime/bootstrap.js +113 -511
  35. package/dist/runtime/delivery.js +1 -1
  36. package/dist/runtime/dingtalk.d.ts +7 -6
  37. package/dist/runtime/dingtalk.js +5 -13
  38. package/dist/runtime/task-wake.d.ts +54 -0
  39. package/dist/runtime/task-wake.js +99 -0
  40. package/dist/shared/host-process.d.ts +5 -5
  41. package/dist/shared/host-process.js +19 -0
  42. package/dist/shared/wake-claim.d.ts +23 -0
  43. package/dist/shared/wake-claim.js +26 -0
  44. package/dist/subagents/discovery.d.ts +9 -1
  45. package/dist/subagents/discovery.js +37 -9
  46. package/dist/subagents/external/claude-code.js +4 -5
  47. package/dist/subagents/external/codex-cli.js +1 -7
  48. package/dist/subagents/external/exec.js +7 -2
  49. package/dist/subagents/external/harness.d.ts +0 -3
  50. package/dist/subagents/external/harness.js +18 -3
  51. package/dist/subagents/external/run.d.ts +5 -0
  52. package/dist/subagents/external/run.js +70 -31
  53. package/dist/subagents/runs.d.ts +40 -9
  54. package/dist/subagents/runs.js +194 -31
  55. package/dist/subagents/tool.d.ts +3 -1
  56. package/dist/subagents/tool.js +33 -14
  57. package/dist/tools/memory-manage.js +0 -1
  58. package/dist/tools/subagent-manage.js +18 -1
  59. package/dist/tui/app.d.ts +1 -1
  60. package/dist/tui/app.js +3 -2
  61. package/dist/tui/cli.d.ts +1 -1
  62. package/dist/tui/cli.js +1 -1
  63. package/dist/tui/terminal-media-sender.d.ts +1 -1
  64. package/examples/sub-agents/README.md +25 -16
  65. package/examples/sub-agents/builder-hard.md +9 -8
  66. package/examples/sub-agents/builder.md +12 -11
  67. package/examples/sub-agents/documenter.md +11 -14
  68. package/examples/sub-agents/explorer.md +16 -13
  69. package/examples/sub-agents/git-committer.md +18 -16
  70. package/examples/sub-agents/log-sifter.md +19 -16
  71. package/examples/sub-agents/planner.md +17 -17
  72. package/examples/sub-agents/reviewer.md +13 -23
  73. package/examples/sub-agents/scout.md +5 -6
  74. package/examples/sub-agents/verifier.md +8 -14
  75. package/examples/sub-agents/worker.md +7 -8
  76. package/package.json +1 -1
@@ -1,9 +1,9 @@
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
5
  import { getOrCreateRunner } from "../agent/index.js";
6
- import { configureJobRuntime, getChannelJobManager, restoreChannelJobs, } from "../agent/job-manager.js";
6
+ import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
8
8
  import { resetRunner } from "../agent/runner-factory.js";
9
9
  import { renderStatus } from "../agent/status-render.js";
@@ -11,7 +11,6 @@ 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";
15
14
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
16
15
  import { flushSecurityLogs } from "../security/logger.js";
17
16
  import { PipiclawSettingsManager } from "../settings.js";
@@ -19,16 +18,17 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
19
18
  import { fileStamp } from "../shared/file-stamp.js";
20
19
  import { errorMessage } from "../shared/text-utils.js";
21
20
  import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
22
- import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, } from "../subagents/runs.js";
21
+ import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentSweeper } from "../subagents/runs.js";
23
22
  import { readActiveTasks } from "../tasks/ledger.js";
24
- import { activateWaitingTaskAndClaimAttempt, finishTaskAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
23
+ import { finishTaskAttempt } from "../tasks/store.js";
25
24
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
26
25
  import { getUsageLedger } from "../usage/ledger.js";
27
26
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
27
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
28
28
  import { createChannelIndex } from "./channel-index.js";
29
29
  import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
30
30
  import { createDingTalkContext } from "./delivery.js";
31
- import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
31
+ import { DingTalkBot, } from "./dingtalk.js";
32
32
  import { DurableDispatchService } from "./durable-dispatch.js";
33
33
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
34
34
  import { createEventsWatcher } from "./events.js";
@@ -38,342 +38,11 @@ import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-comman
38
38
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
39
39
  import { createTaskDriverEvent, createTaskVerificationEvent, TaskDriver } from "./task-driver.js";
40
40
  import { migrateLegacyTaskScheduleEvents, migrateLegacyTaskState } from "./task-migration.js";
41
- import { DEFAULT_AGENTS, DEFAULT_SOUL } from "./workspace-templates.js";
42
- const DEFAULT_MEMORY = `# Workspace Memory
43
-
44
- This file stores stable workspace-level memory.
45
-
46
- - It is intended to be managed by a human administrator.
47
- - It is not automatically rewritten by normal runtime consolidation.
48
- - Store durable shared background here when it should apply across channels.
49
- - Keep this file focused on stable facts, policies, and shared context, not transient conversation history.
50
-
51
- ## Shared Context
52
-
53
- <!-- Put team-wide or workspace-wide background here. -->
54
-
55
- ## Tooling And Environment
56
-
57
- <!-- Put durable tool usage rules, environment assumptions, or shared operational conventions here. -->
58
-
59
- ## Project Notes
60
-
61
- <!-- Put long-lived project facts here. -->
62
- `;
63
- const DEFAULT_ENVIRONMENT = `# Environment
64
-
65
- This file records durable environment facts and notable machine-level changes.
66
-
67
- - Record installed tools, runtime prerequisites, and important config changes here.
68
- - Keep entries concise and factual.
69
- - Do not use this file for task progress, conversation summaries, or project-specific decisions.
70
-
71
- ## Environment Facts
72
-
73
- <!-- Put stable machine or runtime facts here. -->
74
-
75
- ## Installed Tools
76
-
77
- <!-- Record durable tools or dependencies that were installed for this workspace. -->
78
-
79
- ## Config Changes
80
-
81
- <!-- Record important config or environment changes that affect future work. -->
82
- `;
83
- const CHANNEL_CONFIG_TEMPLATE = {
84
- clientId: "your-dingtalk-client-id",
85
- clientSecret: "your-dingtalk-client-secret",
86
- robotCode: "your-robot-code",
87
- cardTemplateId: "your-card-template-id",
88
- cardTemplateKey: "content",
89
- allowFrom: ["your-staff-id"],
90
- busyMessageDefault: "steer",
91
- responseMode: "full_progress_then_plain_final",
92
- cardAutoLayout: true,
93
- };
94
- const MODELS_CONFIG_TEMPLATE = { providers: {} };
95
- const TOOLS_CONFIG_TEMPLATE = {
96
- tools: {
97
- web: {
98
- enable: false,
99
- proxy: null,
100
- search: {
101
- provider: "brave",
102
- apiKey: "",
103
- maxResults: 5,
104
- },
105
- },
106
- tasks: {
107
- enabled: true,
108
- },
109
- },
110
- _examples: {
111
- proxy: "http://127.0.0.1:7890",
112
- apiKey: "BSA...",
113
- },
114
- _notes: [
115
- "Set tools.web.enable to true to register web_search and web_fetch.",
116
- "Replace tools.web.search.apiKey with your Brave API key before enabling web tools.",
117
- "If needed, copy _examples.proxy to tools.web.proxy.",
118
- "tools.tasks.enabled is the master switch for autonomous long-running tasks (task_manage tool + task driver + task digest).",
119
- ],
120
- };
121
- const SECURITY_CONFIG_TEMPLATE = {
122
- pathGuard: {
123
- enabled: true,
124
- },
125
- commandGuard: {
126
- enabled: true,
127
- },
128
- networkGuard: {
129
- enabled: false,
130
- },
131
- };
41
+ import { claimVerifiedDelegationWake, claimVerifiedJobWake } from "./task-wake.js";
132
42
  const SHUTDOWN_WAIT_MS = 15000;
133
43
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
134
44
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
135
45
  const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
136
- export const DEFAULT_BOOTSTRAP_PATHS = {
137
- appName: APP_NAME,
138
- appHomeDir: APP_HOME_DIR,
139
- workspaceDir: WORKSPACE_DIR,
140
- authConfigPath: AUTH_CONFIG_PATH,
141
- channelConfigPath: CHANNEL_CONFIG_PATH,
142
- modelsConfigPath: MODELS_CONFIG_PATH,
143
- settingsConfigPath: SETTINGS_CONFIG_PATH,
144
- toolsConfigPath: TOOLS_CONFIG_PATH,
145
- securityConfigPath: SECURITY_CONFIG_PATH,
146
- eventHistoryPath: EVENT_HISTORY_PATH,
147
- };
148
- export class BootstrapExitError extends Error {
149
- constructor(code, message) {
150
- super(message ?? `Bootstrap requested exit with code ${code}`);
151
- this.code = code;
152
- this.name = "BootstrapExitError";
153
- }
154
- }
155
- export function isBootstrapExitError(error) {
156
- return error instanceof BootstrapExitError;
157
- }
158
- export function readCliVersion() {
159
- try {
160
- const raw = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf-8"));
161
- return typeof raw.version === "string" && raw.version.trim() ? raw.version : "0.0.0";
162
- }
163
- catch {
164
- return "0.0.0";
165
- }
166
- }
167
- function writeTextFileIfMissing(path, content, label, created, mode) {
168
- if (existsSync(path)) {
169
- return false;
170
- }
171
- writeFileSync(path, content, mode !== undefined ? { encoding: "utf-8", mode } : "utf-8");
172
- created.push(label);
173
- return true;
174
- }
175
- function writeJsonFileIfMissing(path, value, label, created, mode) {
176
- return writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\n`, label, created, mode);
177
- }
178
- // App-level config files that may hold secrets (DingTalk client secret, provider
179
- // API keys, Brave key). They are created owner-only, and any pre-existing file with
180
- // looser bits is tightened on startup.
181
- const SECRET_FILE_MODE = 0o600;
182
- function hardenExistingSecretFile(path) {
183
- if (!existsSync(path)) {
184
- return;
185
- }
186
- try {
187
- const mode = statSync(path).mode & 0o777;
188
- if ((mode & 0o077) !== 0) {
189
- chmodSync(path, SECRET_FILE_MODE);
190
- log.logInfo(`Tightened permissions on ${path} to 0600`);
191
- }
192
- }
193
- catch (err) {
194
- log.logWarning(`Failed to tighten permissions on ${path}`, errorMessage(err));
195
- }
196
- }
197
- // FIXME(0.9.0): remove this legacy-home migration (and LEGACY_APP_HOME_DIR).
198
- // The default app home moved from `~/.pi/pipiclaw` to `~/.pipiclaw`. When the
199
- // new default location is not yet present but a legacy install is, move the old
200
- // directory over so existing users keep their config/workspace/state with no
201
- // manual step. Exported for direct testing; the env-gating (only for the real
202
- // default home, never a custom PIPICLAW_HOME) lives at the call site.
203
- export function migrateLegacyAppHome(targetDir, legacyDir, io) {
204
- if (existsSync(targetDir) || !existsSync(legacyDir)) {
205
- return false;
206
- }
207
- try {
208
- renameSync(legacyDir, targetDir);
209
- io.log(`Migrated existing data from ${legacyDir} to ${targetDir}.`);
210
- return true;
211
- }
212
- catch (err) {
213
- io.error(`Failed to migrate ${legacyDir} to ${targetDir}: ${errorMessage(err)}`);
214
- io.error(`Move it manually, or set PIPICLAW_HOME=${legacyDir} to keep using the old location.`);
215
- throw new BootstrapExitError(1);
216
- }
217
- }
218
- export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
219
- const created = [];
220
- // FIXME(0.9.0): remove alongside migrateLegacyAppHome.
221
- if (paths.appHomeDir === DEFAULT_APP_HOME_DIR) {
222
- migrateLegacyAppHome(paths.appHomeDir, LEGACY_APP_HOME_DIR, io);
223
- }
224
- if (!existsSync(paths.appHomeDir)) {
225
- mkdirSync(paths.appHomeDir, { recursive: true });
226
- created.push("app home");
227
- }
228
- if (!existsSync(paths.workspaceDir)) {
229
- mkdirSync(paths.workspaceDir, { recursive: true });
230
- created.push("workspace/");
231
- }
232
- for (const dir of ["skills", "events", "sub-agents"]) {
233
- const dirPath = join(paths.workspaceDir, dir);
234
- if (!existsSync(dirPath)) {
235
- mkdirSync(dirPath, { recursive: true });
236
- created.push(`workspace/${dir}/`);
237
- }
238
- }
239
- writeTextFileIfMissing(join(paths.workspaceDir, "SOUL.md"), DEFAULT_SOUL, "workspace/SOUL.md", created);
240
- writeTextFileIfMissing(join(paths.workspaceDir, "AGENTS.md"), DEFAULT_AGENTS, "workspace/AGENTS.md", created);
241
- writeTextFileIfMissing(join(paths.workspaceDir, "MEMORY.md"), DEFAULT_MEMORY, "workspace/MEMORY.md", created);
242
- writeTextFileIfMissing(join(paths.workspaceDir, "ENVIRONMENT.md"), DEFAULT_ENVIRONMENT, "workspace/ENVIRONMENT.md", created);
243
- const secretConfigPaths = [
244
- paths.channelConfigPath,
245
- paths.authConfigPath,
246
- paths.modelsConfigPath,
247
- paths.settingsConfigPath,
248
- paths.toolsConfigPath,
249
- paths.securityConfigPath,
250
- ];
251
- const channelTemplateCreated = writeJsonFileIfMissing(paths.channelConfigPath, CHANNEL_CONFIG_TEMPLATE, "channel.json", created, SECRET_FILE_MODE);
252
- writeJsonFileIfMissing(paths.authConfigPath, {}, "auth.json", created, SECRET_FILE_MODE);
253
- writeJsonFileIfMissing(paths.modelsConfigPath, MODELS_CONFIG_TEMPLATE, "models.json", created, SECRET_FILE_MODE);
254
- writeJsonFileIfMissing(paths.settingsConfigPath, {}, "settings.json", created, SECRET_FILE_MODE);
255
- writeJsonFileIfMissing(paths.toolsConfigPath, TOOLS_CONFIG_TEMPLATE, "tools.json", created, SECRET_FILE_MODE);
256
- writeJsonFileIfMissing(paths.securityConfigPath, SECURITY_CONFIG_TEMPLATE, "security.json", created, SECRET_FILE_MODE);
257
- // Tighten any pre-existing config that predates owner-only creation.
258
- for (const secretPath of secretConfigPaths) {
259
- hardenExistingSecretFile(secretPath);
260
- }
261
- return { created, channelTemplateCreated };
262
- }
263
- function isPlaceholderString(value) {
264
- return value.trim().startsWith("your-");
265
- }
266
- function listChannelConfigIssues(config) {
267
- const issues = [];
268
- if (!config.clientId) {
269
- issues.push("Missing required field `clientId`.");
270
- }
271
- else if (isPlaceholderString(config.clientId)) {
272
- issues.push("Replace placeholder value for `clientId`.");
273
- }
274
- if (!config.clientSecret) {
275
- issues.push("Missing required field `clientSecret`.");
276
- }
277
- else if (isPlaceholderString(config.clientSecret)) {
278
- issues.push("Replace placeholder value for `clientSecret`.");
279
- }
280
- if (config.robotCode && isPlaceholderString(config.robotCode)) {
281
- issues.push("Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.");
282
- }
283
- if (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {
284
- issues.push("Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.");
285
- }
286
- if (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {
287
- issues.push("Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.");
288
- }
289
- const busyMessageDefault = config.busyMessageDefault;
290
- if (busyMessageDefault !== undefined && !isBusyMessageDefaultConfig(busyMessageDefault)) {
291
- issues.push('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
292
- }
293
- const responseMode = config.responseMode;
294
- if (responseMode !== undefined && !isResponseModeConfig(responseMode)) {
295
- issues.push('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
296
- }
297
- const cardAutoLayout = config.cardAutoLayout;
298
- if (cardAutoLayout !== undefined && typeof cardAutoLayout !== "boolean") {
299
- issues.push("Invalid `cardAutoLayout`: expected boolean.");
300
- }
301
- return issues;
302
- }
303
- export function printBootstrapSummary(result, io = console, paths = DEFAULT_BOOTSTRAP_PATHS) {
304
- if (result.created.length === 0) {
305
- return;
306
- }
307
- io.log(`Initialized ${paths.appName} under ${paths.appHomeDir}:`);
308
- for (const item of result.created) {
309
- io.log(` - ${item}`);
310
- }
311
- io.log("");
312
- }
313
- export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
314
- let parsed;
315
- try {
316
- parsed = JSON.parse(readFileSync(paths.channelConfigPath, "utf-8"));
317
- }
318
- catch (err) {
319
- io.error(`Failed to parse configuration: ${paths.channelConfigPath}`);
320
- io.error(errorMessage(err));
321
- throw new BootstrapExitError(1);
322
- }
323
- const issues = listChannelConfigIssues(parsed);
324
- if (issues.length > 0) {
325
- io.error(`Configuration is not ready: ${paths.channelConfigPath}`);
326
- for (const issue of issues) {
327
- io.error(` - ${issue}`);
328
- }
329
- io.error("");
330
- io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
331
- throw new BootstrapExitError(1);
332
- }
333
- parsed.cardTemplateKey = parsed.cardTemplateKey || "content";
334
- parsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;
335
- parsed.busyMessageDefault = normalizeBusyMessageDefault(parsed.busyMessageDefault);
336
- parsed.responseMode = normalizeResponseMode(parsed.responseMode);
337
- parsed.cardAutoLayout = parsed.cardAutoLayout ?? true;
338
- if (Array.isArray(parsed.allowFrom)) {
339
- parsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);
340
- }
341
- return parsed;
342
- }
343
- export function parseArgs(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
344
- const args = argv.slice(2);
345
- for (let index = 0; index < args.length; index += 1) {
346
- const arg = args[index];
347
- if (index === 0 && arg === "run") {
348
- // Explicit name for the default daemon mode (`pipiclaw run` == `pipiclaw`).
349
- continue;
350
- }
351
- if (arg === "--help" || arg === "-h") {
352
- io.log(`Usage: ${paths.appName} [command] [options]`);
353
- io.log("");
354
- io.log("Commands:");
355
- io.log(" run Run the long-lived DingTalk daemon (default)");
356
- io.log(" tui [prompt] Chat with the agent in the terminal");
357
- io.log("");
358
- io.log("Options:");
359
- io.log(" --version Print the current version and exit");
360
- io.log(" --help, -h Show this help and exit");
361
- io.log("");
362
- io.log(`Config: ${paths.channelConfigPath}`);
363
- io.log(`Workspace: ${paths.workspaceDir}`);
364
- throw new BootstrapExitError(0);
365
- }
366
- else if (arg === "--version") {
367
- io.log(readCliVersion());
368
- throw new BootstrapExitError(0);
369
- }
370
- else {
371
- io.error(`Unknown option: ${arg}`);
372
- io.error(`Run \`${paths.appName} --help\` for usage.`);
373
- throw new BootstrapExitError(1);
374
- }
375
- }
376
- }
377
46
  function waitForTasks(tasks, timeoutMs) {
378
47
  if (tasks.length === 0) {
379
48
  return Promise.resolve(true);
@@ -403,68 +72,13 @@ function isNoRunningTaskQueueError(err) {
403
72
  return err instanceof Error && err.message === "No task is currently running.";
404
73
  }
405
74
  /**
406
- * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
407
- * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
408
- * accepting it anyway would let a message merely mentioning a live job's id activate a task
409
- * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
410
- * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
411
- * untrusted stdout.
412
- */
413
- export function isVerifiedJobWake(jobs, jobId, taskId) {
414
- const job = jobs.find((candidate) => candidate.id === jobId);
415
- return job !== undefined && job.status !== "running" && job.taskId === taskId;
416
- }
417
- /**
418
- * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
419
- * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
420
- * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
421
- * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
75
+ * The `runRuntimeCommand` names usable on the idle-turn path. `context` is deliberately excluded:
76
+ * idle answers it through the runner's ChannelContext-aware command path (thread-reply, delete
77
+ * semantics) instead, so it is not part of this stateless-report dispatch here.
422
78
  */
423
- export function isVerifiedDelegationWake(record, taskId) {
424
- return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
425
- }
426
- /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
427
- * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
428
- * not populate `internalWake`, so copying a real wake's text is insufficient. */
429
- export function isTrustedInternalWake(event, kind, resourceId, taskId) {
430
- const wake = event.internalWake;
431
- return (wake?.kind === kind &&
432
- wake.resourceId === resourceId &&
433
- wake.taskId === taskId &&
434
- typeof event.dispatchId === "string" &&
435
- wake.dispatchId === event.dispatchId);
436
- }
437
- /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
438
- * final marker separate lets transports such as TUI mark it consumed only after they have accepted
439
- * the corresponding turn; a rejected submit remains replayable in the same or next process. */
440
- export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
441
- const wake = event.internalWake;
442
- if (wake?.kind !== "subagent")
443
- return undefined;
444
- const runManager = getSubAgentRunManager(event.channelId);
445
- const record = runManager.get(wake.resourceId);
446
- if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
447
- !isVerifiedDelegationWake(record, wake.taskId) ||
448
- !(await runManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
449
- return undefined;
450
- }
451
- const channelDir = getChannelDir(workspaceDir, event.channelId);
452
- const handoff = {
453
- kind: "subagent",
454
- resourceId: wake.resourceId,
455
- dispatchId: event.dispatchId,
456
- };
457
- const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "external-signal", new Date(), hooks, handoff);
458
- return {
459
- taskId: wake.taskId,
460
- generation: activated?.generation,
461
- activated: activated !== undefined,
462
- finish: async () => {
463
- await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
464
- await finishWakeTaskActivation(channelDir, wake.taskId, handoff);
465
- },
466
- rollback: () => rollbackWakeTaskActivation(channelDir, wake.taskId, handoff),
467
- };
79
+ const IDLE_RUNTIME_COMMAND_NAMES = new Set(["events", "tasks", "status", "usage", "subagents"]);
80
+ function isIdleRuntimeCommandName(name) {
81
+ return IDLE_RUNTIME_COMMAND_NAMES.has(name);
468
82
  }
469
83
  /**
470
84
  * How long `/stop` waits for the turn to actually end before force-releasing it.
@@ -499,7 +113,7 @@ export async function forceEndStuckTurnAfterStop(input) {
499
113
  .catch(() => undefined);
500
114
  return true;
501
115
  }
502
- export function createRuntimeContext(options) {
116
+ export async function createRuntimeContext(options) {
503
117
  const startServices = options.startServices ?? true;
504
118
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
505
119
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
@@ -613,70 +227,63 @@ export function createRuntimeContext(options) {
613
227
  }
614
228
  return { pausedTaskId };
615
229
  },
616
- async handleEventsCommand(event, bot, args) {
617
- const response = await runEventsCommand({
618
- args,
619
- workspaceDir: options.paths.workspaceDir,
620
- historyPath: options.paths.eventHistoryPath,
621
- });
622
- await bot.sendPlain(event.channelId, response);
623
- },
624
- async handleTasksCommand(event, bot, args) {
625
- const response = await runTasksCommand({
626
- args,
627
- channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
628
- workspaceDir: options.paths.workspaceDir,
629
- channelId: event.channelId,
630
- dispatchTask: async (id, attemptGeneration) => {
631
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
632
- const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
633
- if (!entry)
634
- return false;
635
- // A human asking to run a task twice means twice, so this key is deliberately
636
- // unique per invocation rather than sharing the driver's occurrence key (D1).
637
- const now = Date.now();
638
- const driverEvent = createTaskDriverEvent(event.channelId, entry, now, attemptGeneration);
639
- return ((await durableDispatch?.dispatch({
640
- ...driverEvent,
641
- dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
642
- })) ?? false);
643
- },
644
- });
645
- await bot.sendPlain(event.channelId, response);
646
- },
647
- async handleStatusCommand(event, bot) {
648
- const response = renderStatus({
649
- runner: channelRunners.get(event.channelId),
650
- version: cliVersion,
651
- uptimeMs: Date.now() - startedAt,
652
- });
653
- await bot.sendPlain(event.channelId, response);
654
- },
655
- async handleUsageCommand(event, bot, args) {
656
- const response = await renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
657
- await bot.sendPlain(event.channelId, response);
658
- },
659
- // Read-only prompt accounting; safe mid-turn, so it is answered here rather than by
660
- // the runner's idle command path.
661
- async handleContextCommand(event, bot, args) {
662
- await bot.sendPlain(event.channelId, getRunner(event.channelId).renderContextReport(args));
663
- },
664
- // A human control path independent of the model (spec 040, D6): `/stop` no longer kills a
665
- // dispatched delegation, so cancel must work whether or not a runner is currently active.
666
- async handleSubagentsCommand(event, bot, args) {
667
- const response = await runSubagentsCommand({
668
- args,
669
- channelId: event.channelId,
670
- discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
671
- // `roles` needs a role directory even for a channel that has never spoken this boot —
672
- // resolved from disk, without spinning up a full ChannelRunner (spec 041).
673
- getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
674
- workspaceDir: options.paths.workspaceDir,
675
- authConfigPath: options.paths.authConfigPath,
676
- modelsConfigPath: options.paths.modelsConfigPath,
677
- }),
678
- });
679
- await bot.sendPlain(event.channelId, response);
230
+ async runRuntimeCommand(event, name, args) {
231
+ switch (name) {
232
+ case "events":
233
+ return runEventsCommand({
234
+ args,
235
+ workspaceDir: options.paths.workspaceDir,
236
+ historyPath: options.paths.eventHistoryPath,
237
+ });
238
+ case "tasks":
239
+ return runTasksCommand({
240
+ args,
241
+ channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
242
+ workspaceDir: options.paths.workspaceDir,
243
+ channelId: event.channelId,
244
+ dispatchTask: async (id, attemptGeneration) => {
245
+ const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
246
+ const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
247
+ if (!entry)
248
+ return false;
249
+ // A human asking to run a task twice means twice, so this key is deliberately
250
+ // unique per invocation rather than sharing the driver's occurrence key (D1).
251
+ const now = Date.now();
252
+ const driverEvent = createTaskDriverEvent(event.channelId, entry, now, attemptGeneration);
253
+ return ((await durableDispatch?.dispatch({
254
+ ...driverEvent,
255
+ dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
256
+ })) ?? false);
257
+ },
258
+ });
259
+ case "status":
260
+ return renderStatus({
261
+ runner: channelRunners.get(event.channelId),
262
+ version: cliVersion,
263
+ uptimeMs: Date.now() - startedAt,
264
+ });
265
+ case "usage":
266
+ return renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
267
+ // Read-only prompt accounting; safe mid-turn, so the busy path answers it through
268
+ // this stateless report rather than the runner's ChannelContext-aware idle path.
269
+ case "context":
270
+ return getRunner(event.channelId).renderContextReport(args);
271
+ // A human control path independent of the model (spec 040, D6): `/stop` no longer kills a
272
+ // dispatched delegation, so cancel must work whether or not a runner is currently active.
273
+ case "subagents":
274
+ return runSubagentsCommand({
275
+ args,
276
+ channelId: event.channelId,
277
+ discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
278
+ // `roles` needs a role directory even for a channel that has never spoken this boot —
279
+ // resolved from disk, without spinning up a full ChannelRunner (spec 041).
280
+ getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
281
+ workspaceDir: options.paths.workspaceDir,
282
+ authConfigPath: options.paths.authConfigPath,
283
+ modelsConfigPath: options.paths.modelsConfigPath,
284
+ }),
285
+ });
286
+ }
680
287
  },
681
288
  async handleBusyMessage(event, bot, mode, queueText) {
682
289
  if (shuttingDown) {
@@ -761,24 +368,9 @@ export function createRuntimeContext(options) {
761
368
  ctx: { channelId: event.channelId, userName: event.userName },
762
369
  fields: { command: builtInCommand.name },
763
370
  });
764
- if (builtInCommand.name === "events") {
765
- await handler.handleEventsCommand(event, bot, builtInCommand.args);
766
- return;
767
- }
768
- if (builtInCommand.name === "tasks") {
769
- await handler.handleTasksCommand(event, bot, builtInCommand.args);
770
- return;
771
- }
772
- if (builtInCommand.name === "status") {
773
- await handler.handleStatusCommand(event, bot);
774
- return;
775
- }
776
- if (builtInCommand.name === "usage") {
777
- await handler.handleUsageCommand(event, bot, builtInCommand.args);
778
- return;
779
- }
780
- if (builtInCommand.name === "subagents") {
781
- await handler.handleSubagentsCommand(event, bot, builtInCommand.args);
371
+ if (isIdleRuntimeCommandName(builtInCommand.name)) {
372
+ const response = await handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
373
+ await bot.sendPlain(event.channelId, response);
782
374
  return;
783
375
  }
784
376
  if (isRunnerBuiltInCommand(builtInCommand)) {
@@ -821,21 +413,15 @@ export function createRuntimeContext(options) {
821
413
  let recoveredJobTaskId;
822
414
  if (jobMatch) {
823
415
  const [, jobId, jobTaskId] = jobMatch;
824
- const jobManager = getChannelJobManager(event.channelId, executor);
825
- const jobs = await jobManager.list();
826
- const verified = isTrustedInternalWake(event, "job", jobId, jobTaskId) &&
827
- isVerifiedJobWake(jobs, jobId, jobTaskId) &&
828
- (await jobManager.beginWakeConsumption(jobId, jobTaskId, event.dispatchId));
829
- if (verified) {
830
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
831
- const activated = await activateWaitingTaskAndClaimAttempt(channelDir, jobTaskId, "job", new Date(), options.wakeTransitionHooks?.job);
832
- if (activated) {
833
- recoveredJobTaskId = jobTaskId;
834
- event.taskAttemptGeneration = activated.generation;
835
- }
836
- await jobManager.finishWakeConsumption(jobId, event.dispatchId);
416
+ const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, executor, options.wakeTransitionHooks?.job);
417
+ if (claimed) {
418
+ if (claimed.activated)
419
+ recoveredJobTaskId = claimed.taskId;
420
+ if (claimed.generation !== undefined)
421
+ event.taskAttemptGeneration = claimed.generation;
422
+ await claimed.finish();
837
423
  structuredWakeFinalized = true;
838
- if (event.internalWake?.kind === "job" && !activated)
424
+ if (event.internalWake?.kind === "job" && !claimed.activated)
839
425
  return;
840
426
  }
841
427
  else {
@@ -878,14 +464,11 @@ export function createRuntimeContext(options) {
878
464
  const result = await runner.run(ctx, store);
879
465
  const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
880
466
  const taskAttemptId = taskDriverMatch?.[1] ?? recoveredJobTaskId ?? recoveredDelegationTaskId;
881
- if (taskDriverMatch?.[1]) {
882
- noteTaskEffects(event.channelId, taskDriverMatch[1], channelEffectCount(event.channelId) - effectsBefore);
883
- }
884
- if (recoveredJobTaskId) {
885
- noteTaskEffects(event.channelId, recoveredJobTaskId, channelEffectCount(event.channelId) - effectsBefore);
886
- }
887
- if (recoveredDelegationTaskId) {
888
- noteTaskEffects(event.channelId, recoveredDelegationTaskId, channelEffectCount(event.channelId) - effectsBefore);
467
+ // The three sources above are mutually exclusive (each regex is anchored at the
468
+ // start of a distinct prefix), so crediting effects to whichever one matched is
469
+ // equivalent to checking all three separately.
470
+ if (taskAttemptId) {
471
+ noteTaskEffects(event.channelId, taskAttemptId, channelEffectCount(event.channelId) - effectsBefore);
889
472
  }
890
473
  if (taskAttemptId && result.usage && result.durationMs !== undefined) {
891
474
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskAttemptId, {
@@ -952,7 +535,10 @@ export function createRuntimeContext(options) {
952
535
  ledger: getUsageLedger(),
953
536
  store,
954
537
  });
955
- void restoreAllSubAgentRuns();
538
+ // Admission (bot.start() below) must not open until every persisted run is back in memory
539
+ // (P0-1): a message arriving mid-restore would see partial running-count/short-id/lease state,
540
+ // and durableDispatch's redelivery of a pending completion wake would find no record to claim.
541
+ await restoreAllSubAgentRuns();
956
542
  const eventsWatcher = options.createEventsWatcher
957
543
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
958
544
  : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
@@ -1028,6 +614,7 @@ export function createRuntimeContext(options) {
1028
614
  durableDispatch?.stop();
1029
615
  memoryMaintenanceScheduler.stop();
1030
616
  eventsWatcher.stop();
617
+ stopSubAgentSweeper();
1031
618
  await bot.stop();
1032
619
  const runningTasks = Array.from(activeTasks);
1033
620
  if (runningTasks.length > 0) {
@@ -1101,10 +688,25 @@ export function createRuntimeContext(options) {
1101
688
  });
1102
689
  }
1103
690
  if (startServices) {
1104
- // One-time close of the 027 migration window: fold any residual legacy `.schedule`
1105
- // events into task frontmatter before the driver relies on frontmatter as the only cadence.
1106
- void migrateLegacyTaskScheduleEvents(options.paths.workspaceDir);
1107
- void migrateLegacyTaskState(options.paths.workspaceDir);
691
+ // One-time close of the 027/038 migration windows: fold any residual legacy `.schedule`
692
+ // events into task frontmatter, and upgrade v1 task status vocabulary, before the driver
693
+ // relies on the v2 contract alone. Both scan every channel's tasks/events, so they are
694
+ // gated on a marker file rather than repeated on every restart once a home has migrated.
695
+ const taskMigrationMarkerPath = join(options.paths.appHomeDir, "state", "task-migration.done");
696
+ if (!existsSync(taskMigrationMarkerPath)) {
697
+ void Promise.all([
698
+ migrateLegacyTaskScheduleEvents(options.paths.workspaceDir),
699
+ migrateLegacyTaskState(options.paths.workspaceDir),
700
+ ]).then(() => {
701
+ try {
702
+ mkdirSync(join(options.paths.appHomeDir, "state"), { recursive: true });
703
+ writeFileSync(taskMigrationMarkerPath, `${new Date().toISOString()}\n`);
704
+ }
705
+ catch (error) {
706
+ log.logWarning("Failed to write task migration marker", errorMessage(error));
707
+ }
708
+ });
709
+ }
1108
710
  eventsWatcher.start();
1109
711
  memoryMaintenanceScheduler.start();
1110
712
  taskDriver.start();
@@ -1161,7 +763,7 @@ export async function bootstrap(argv, options = {}) {
1161
763
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
1162
764
  const startServices = options.startServices ?? true;
1163
765
  parseArgs(argv, paths, io);
1164
- const bootstrapResult = bootstrapAppHome(paths, io);
766
+ const bootstrapResult = bootstrapAppHome(paths);
1165
767
  printBootstrapSummary(bootstrapResult, io, paths);
1166
768
  if (bootstrapResult.channelTemplateCreated) {
1167
769
  io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
@@ -1171,7 +773,7 @@ export async function bootstrap(argv, options = {}) {
1171
773
  dingtalkConfig.stateDir = paths.workspaceDir;
1172
774
  prepareAppServices(paths);
1173
775
  log.logStartup(paths.workspaceDir);
1174
- const runtime = createRuntimeContext({
776
+ const runtime = await createRuntimeContext({
1175
777
  paths,
1176
778
  dingtalkConfig,
1177
779
  registerSignalHandlers,