@oyasmi/pipiclaw 0.8.3 → 0.8.5

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 (63) hide show
  1. package/README.md +2 -1
  2. package/dist/agent/channel-runner.d.ts +45 -3
  3. package/dist/agent/channel-runner.js +200 -77
  4. package/dist/agent/commands.d.ts +2 -2
  5. package/dist/agent/commands.js +10 -1
  6. package/dist/agent/maintenance-context.d.ts +23 -0
  7. package/dist/agent/maintenance-context.js +72 -0
  8. package/dist/agent/prompt/builder.d.ts +32 -0
  9. package/dist/agent/prompt/builder.js +252 -0
  10. package/dist/agent/prompt/extension.d.ts +22 -0
  11. package/dist/agent/prompt/extension.js +24 -0
  12. package/dist/agent/prompt/manifest.d.ts +51 -0
  13. package/dist/agent/prompt/manifest.js +84 -0
  14. package/dist/agent/prompt/resources.d.ts +18 -0
  15. package/dist/agent/prompt/resources.js +61 -0
  16. package/dist/agent/prompt/sections.d.ts +39 -0
  17. package/dist/agent/prompt/sections.js +267 -0
  18. package/dist/agent/prompt/types.d.ts +110 -0
  19. package/dist/agent/prompt/types.js +11 -0
  20. package/dist/agent/status-render.d.ts +3 -7
  21. package/dist/agent/status-render.js +5 -5
  22. package/dist/agent/types.d.ts +33 -0
  23. package/dist/agent/workspace-resources.d.ts +25 -13
  24. package/dist/agent/workspace-resources.js +28 -41
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +6 -2
  27. package/dist/memory/transcript.js +7 -6
  28. package/dist/models/utils.d.ts +3 -1
  29. package/dist/models/utils.js +8 -0
  30. package/dist/playbooks/catalog.d.ts +22 -1
  31. package/dist/playbooks/catalog.js +57 -4
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +2 -0
  34. package/dist/playbooks/runtime-orientation.md +1 -0
  35. package/dist/playbooks/task-closeout.md +3 -1
  36. package/dist/playbooks/task-delegation.md +3 -1
  37. package/dist/playbooks/task-driving.md +2 -0
  38. package/dist/playbooks/task-planning.md +2 -0
  39. package/dist/playbooks/task-recurring.md +2 -0
  40. package/dist/playbooks/task-repair.md +3 -1
  41. package/dist/runtime/bootstrap.js +77 -93
  42. package/dist/runtime/channel-queue.d.ts +17 -0
  43. package/dist/runtime/channel-queue.js +50 -0
  44. package/dist/runtime/dingtalk.d.ts +1 -0
  45. package/dist/runtime/dingtalk.js +6 -42
  46. package/dist/runtime/task-driver.d.ts +2 -0
  47. package/dist/runtime/task-driver.js +3 -26
  48. package/dist/runtime/workspace-templates.d.ts +11 -0
  49. package/dist/runtime/workspace-templates.js +51 -0
  50. package/dist/settings.d.ts +0 -3
  51. package/dist/settings.js +0 -3
  52. package/dist/tools/config.d.ts +6 -22
  53. package/dist/tools/config.js +0 -58
  54. package/dist/tools/index.js +1 -4
  55. package/dist/tools/registry.d.ts +3 -3
  56. package/dist/tools/registry.js +4 -6
  57. package/dist/tui/commands.d.ts +1 -0
  58. package/dist/tui/commands.js +2 -0
  59. package/dist/tui/turn-controller.d.ts +1 -3
  60. package/dist/tui/turn-controller.js +17 -18
  61. package/package.json +1 -1
  62. package/dist/agent/prompt-builder.d.ts +0 -12
  63. package/dist/agent/prompt-builder.js +0 -71
@@ -1,10 +1,11 @@
1
1
  import { buildStandardMessages } from "../shared/type-guards.js";
2
- // The channel runner prepends recalled memory and the durable bootstrap to the raw
3
- // user input, then wraps the input itself in <user_message>. If that combined text
4
- // flows back into consolidation / session refresh / signal scans, previously recalled
5
- // memory gets re-summarized into MEMORY.md — a self-reinforcing echo. Strip the
6
- // injected wrappers before any memory job reads the transcript.
7
- const INJECTED_CONTEXT_BLOCK = /<(runtime_context|durable_memory_snapshot)>[\s\S]*?<\/\1>\s*/gi;
2
+ // The channel runner prepends the channel capsule, recalled memory, the task agenda
3
+ // and the durable bootstrap to the raw user input, then wraps the input itself in
4
+ // <user_message>. If that combined text flows back into consolidation / session
5
+ // refresh / signal scans, previously recalled memory gets re-summarized into
6
+ // MEMORY.md — a self-reinforcing echo. Strip the injected wrappers before any memory
7
+ // job reads the transcript.
8
+ const INJECTED_CONTEXT_BLOCK = /<(runtime_context|runtime_turn_context|durable_memory_snapshot|task_agenda)>[\s\S]*?<\/\1>\s*/gi;
8
9
  const USER_MESSAGE_WRAPPER = /^<user_message>\s*([\s\S]*?)\s*<\/user_message>$/i;
9
10
  export function stripInjectedMemoryContext(text) {
10
11
  const withoutBlocks = text.replace(INJECTED_CONTEXT_BLOCK, "").trim();
@@ -1,6 +1,8 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
- import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
+ import { type AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
3
3
  import type { PipiclawSettingsManager } from "../settings.js";
4
+ /** SDK-version-tolerant construction: newer SDKs expose a static create(), older ones a constructor. */
5
+ export declare function createModelRegistry(authStorage: AuthStorage, modelsJsonPath: string): ModelRegistry;
4
6
  export declare function formatModelReference(model: Model<Api>): string;
5
7
  export declare function findExactModelReferenceMatch(modelReference: string, availableModels: Model<Api>[]): {
6
8
  match?: Model<Api>;
@@ -1,6 +1,14 @@
1
1
  import { getBuiltinModel as getModel } from "@earendil-works/pi-ai/providers/all";
2
+ import { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
3
  // Default model - will be overridden by ModelRegistry if custom models are configured
3
4
  const defaultModel = getModel("anthropic", "claude-sonnet-4-5");
5
+ /** SDK-version-tolerant construction: newer SDKs expose a static create(), older ones a constructor. */
6
+ export function createModelRegistry(authStorage, modelsJsonPath) {
7
+ const registryClass = ModelRegistry;
8
+ return typeof registryClass.create === "function"
9
+ ? registryClass.create(authStorage, modelsJsonPath)
10
+ : new registryClass(authStorage, modelsJsonPath);
11
+ }
4
12
  export function formatModelReference(model) {
5
13
  return `${model.provider}/${model.id}`;
6
14
  }
@@ -1,9 +1,30 @@
1
+ /** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
2
+ declare const PLAYBOOK_MODES: readonly ["normal", "task-driver", "event", "subagent", "maintenance"];
3
+ export type PlaybookMode = (typeof PLAYBOOK_MODES)[number];
4
+ /** A catalog entry is a trigger, not a summary; longer descriptions are clipped in the prompt. */
5
+ export declare const MAX_PLAYBOOK_DESCRIPTION_CHARS = 180;
1
6
  export interface RuntimePlaybookMetadata {
2
7
  name: string;
3
8
  description: string;
4
9
  filename: string;
5
10
  path: string;
11
+ /**
12
+ * Listed only when at least one of these tools is registered — any-of, not all-of:
13
+ * task-delegation matters to a runtime with tasks *or* with sub-agents. Empty = always
14
+ * listed. (Prompt sections gate the other way: see `requiresAllTools` in agent/prompt/types.ts.)
15
+ */
16
+ requiresAnyTool: string[];
17
+ /** Modes this playbook is offered in. Empty = all modes. */
18
+ modes: PlaybookMode[];
19
+ /** Ascending; ties break on filename. */
20
+ priority: number;
6
21
  }
7
22
  /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
8
23
  export declare function loadRuntimePlaybookCatalog(directory?: string): RuntimePlaybookMetadata[];
9
- export declare function renderRuntimePlaybookIndex(directory?: string): string;
24
+ /**
25
+ * Drop playbooks whose mechanism is unreachable with the current tool set: the task
26
+ * playbooks are pure noise for a runtime with `task_manage` switched off.
27
+ */
28
+ export declare function selectRuntimePlaybooks(catalog: RuntimePlaybookMetadata[], toolNames: readonly string[], mode?: PlaybookMode): RuntimePlaybookMetadata[];
29
+ export declare function renderPlaybookCatalog(playbooks: RuntimePlaybookMetadata[]): string;
30
+ export {};
@@ -1,6 +1,20 @@
1
1
  import { readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import { PLAYBOOKS_DIR } from "../paths.js";
4
+ import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
5
+ /** Prompt modes a playbook may be scoped to. Mirrors PromptMode in agent/prompt/types.ts. */
6
+ const PLAYBOOK_MODES = ["normal", "task-driver", "event", "subagent", "maintenance"];
7
+ const DEFAULT_PRIORITY = 100;
8
+ /** A catalog entry is a trigger, not a summary; longer descriptions are clipped in the prompt. */
9
+ export const MAX_PLAYBOOK_DESCRIPTION_CHARS = 180;
10
+ function parseList(value) {
11
+ if (!value)
12
+ return [];
13
+ return value
14
+ .split(",")
15
+ .map((item) => item.trim())
16
+ .filter(Boolean);
17
+ }
4
18
  function parseFrontmatter(content, filename) {
5
19
  const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
6
20
  if (!match)
@@ -25,7 +39,26 @@ function parseFrontmatter(content, filename) {
25
39
  if (`${name}.md` !== filename) {
26
40
  throw new Error(`Runtime playbook ${filename} metadata name must be "${basename(filename, ".md")}".`);
27
41
  }
28
- return { name, description };
42
+ // Authored metadata is validated, never silently ignored: a typo in a tool name would
43
+ // otherwise drop the playbook from the catalog with no signal anywhere.
44
+ const requiresAnyTool = parseList(fields.get("requires-tools"));
45
+ for (const tool of requiresAnyTool) {
46
+ if (!(tool in TOOL_PROMPT_HINTS)) {
47
+ throw new Error(`Runtime playbook ${filename} requires unknown tool "${tool}".`);
48
+ }
49
+ }
50
+ const modes = parseList(fields.get("modes"));
51
+ for (const mode of modes) {
52
+ if (!PLAYBOOK_MODES.includes(mode)) {
53
+ throw new Error(`Runtime playbook ${filename} declares unknown mode "${mode}".`);
54
+ }
55
+ }
56
+ const priorityField = fields.get("priority");
57
+ const priority = priorityField ? Number(priorityField) : DEFAULT_PRIORITY;
58
+ if (!Number.isFinite(priority)) {
59
+ throw new Error(`Runtime playbook ${filename} has a non-numeric priority "${priorityField}".`);
60
+ }
61
+ return { name, description, requiresAnyTool, modes: modes, priority };
29
62
  }
30
63
  /** Load the small always-on catalog; playbook bodies remain on disk until the agent reads one. */
31
64
  export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
@@ -35,10 +68,30 @@ export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
35
68
  .map((filename) => {
36
69
  const path = join(directory, filename);
37
70
  return { ...parseFrontmatter(readFileSync(path, "utf-8"), filename), filename, path };
71
+ })
72
+ .sort((a, b) => a.priority - b.priority || a.filename.localeCompare(b.filename));
73
+ }
74
+ /**
75
+ * Drop playbooks whose mechanism is unreachable with the current tool set: the task
76
+ * playbooks are pure noise for a runtime with `task_manage` switched off.
77
+ */
78
+ export function selectRuntimePlaybooks(catalog, toolNames, mode = "normal") {
79
+ const tools = new Set(toolNames);
80
+ return catalog.filter((playbook) => {
81
+ if (playbook.modes.length > 0 && !playbook.modes.includes(mode))
82
+ return false;
83
+ if (playbook.requiresAnyTool.length === 0)
84
+ return true;
85
+ return playbook.requiresAnyTool.some((tool) => tools.has(tool));
38
86
  });
39
87
  }
40
- export function renderRuntimePlaybookIndex(directory = PLAYBOOKS_DIR) {
41
- return loadRuntimePlaybookCatalog(directory)
42
- .map((playbook) => `- ${playbook.filename} — ${playbook.description}`)
88
+ export function renderPlaybookCatalog(playbooks) {
89
+ return playbooks
90
+ .map((playbook) => {
91
+ const description = playbook.description.length > MAX_PLAYBOOK_DESCRIPTION_CHARS
92
+ ? `${playbook.description.slice(0, MAX_PLAYBOOK_DESCRIPTION_CHARS - 1)}…`
93
+ : playbook.description;
94
+ return `- ${playbook.filename} — ${description}`;
95
+ })
43
96
  .join("\n");
44
97
  }
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: event-scheduling
3
3
  description: Read before creating, updating, diagnosing, or retiring reminders, one-shot wakeups, periodic schedules, preAction gates, or background-job check-ins.
4
+ requires-tools: event_manage
5
+ priority: 30
4
6
  ---
5
7
 
6
8
  # 事件与调度
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: memory-and-learning
3
3
  description: Read when remembering or forgetting facts, choosing SESSION/MEMORY/HISTORY/ENVIRONMENT/tasks/skills, or turning repeated experience into a workspace skill.
4
+ requires-tools: memory_manage, skill_manage
5
+ priority: 20
4
6
  ---
5
7
 
6
8
  # 记忆、状态与程序性学习
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: runtime-orientation
3
3
  description: Read when locating Pipiclaw state, deciding whether knowledge belongs to runtime playbooks or workspace instructions, or interpreting channel and workspace files.
4
+ priority: 10
4
5
  ---
5
6
 
6
7
  # Pipiclaw 运行时导航
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: task-closeout
3
- description: Read before candidate verification, importing a verifier verdict, requesting external approval, completing or cancelling a task, or handling combined verification-and-approval gates.
3
+ description: Read before candidate verification, importing a verifier verdict, requesting external approval, or completing/cancelling a task.
4
+ requires-tools: task_manage
5
+ priority: 42
4
6
  ---
5
7
 
6
8
  # 验收、外部审批与闭环
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: task-delegation
3
- description: Read before splitting parent/child tasks, using predefined or inline subagents, creating task-owned worktrees, or delegating to any external agent tool that must be revisited later.
3
+ description: Read before splitting parent/child tasks, using predefined or inline subagents, creating task-owned worktrees, or delegating work you must revisit later.
4
+ requires-tools: task_manage, subagent
5
+ priority: 45
4
6
  ---
5
7
 
6
8
  # 任务分解与委派
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: task-driving
3
3
  description: Read whenever TASK_DRIVER or a task-owned event resumes work, and when checkpointing progress, waiting with wake, handling idempotent recovery, or deciding the next task action.
4
+ requires-tools: task_manage
5
+ priority: 41
4
6
  ---
5
7
 
6
8
  # Task driver 推进与断点恢复
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: task-planning
3
3
  description: Read before creating or restructuring a persistent task, choosing task versus event, writing Goal/DoD/Manual/Verification, or setting control metadata and budgets.
4
+ requires-tools: task_manage
5
+ priority: 40
4
6
  ---
5
7
 
6
8
  # 长程任务规划与建档
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: task-recurring
3
3
  description: Read before creating, starting, rescheduling, pausing, completing a cycle of, or retiring a recurring task and its canonical schedule event.
4
+ requires-tools: task_manage
5
+ priority: 43
4
6
  ---
5
7
 
6
8
  # 周期性任务
@@ -1,6 +1,8 @@
1
1
  ---
2
2
  name: task-repair
3
- description: Read when a task is escalated, repeatedly stalled, not waking, has broken frontmatter/control, stale approval or verification, terminal dependencies, orphan events, or restart recovery issues.
3
+ description: Read when a task is escalated, stalled, not waking, or has broken control metadata, stale approval/verification, terminal dependencies, or orphan events.
4
+ requires-tools: task_manage
5
+ priority: 44
4
6
  ---
5
7
 
6
8
  # 任务诊断与修复
@@ -2,6 +2,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync
2
2
  import { join } from "path";
3
3
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
4
  import { getOrCreateRunner } from "../agent/index.js";
5
+ import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
5
6
  import { resetRunner } from "../agent/runner-factory.js";
6
7
  import { renderStatus } from "../agent/status-render.js";
7
8
  import { createExecutor } from "../executor.js";
@@ -15,7 +16,7 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
15
16
  import { readActiveTasks } from "../shared/task-ledger.js";
16
17
  import { errorMessage } from "../shared/text-utils.js";
17
18
  import { finishTaskAttempt } from "../tasks/store.js";
18
- import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
19
+ import { loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
19
20
  import { getUsageLedger } from "../usage/ledger.js";
20
21
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
21
22
  import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
@@ -27,43 +28,7 @@ import { createEventsWatcher } from "./events.js";
27
28
  import { ChannelStore } from "./store.js";
28
29
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
29
30
  import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
30
- const DEFAULT_SOUL = `# SOUL.md
31
-
32
- Configure Pipiclaw's identity, voice, and communication style here.
33
-
34
- Suggested sections:
35
-
36
- - Who the assistant is
37
- - Default language
38
- - Tone and personality
39
- - Reply style
40
- - Formatting preferences
41
-
42
- Example topics you may want to define:
43
-
44
- - "Answer in Chinese by default."
45
- - "Be concise and direct."
46
- - "Prefer Markdown."
47
- - "Act as an engineering assistant for our team."
48
-
49
- Replace this template with your actual identity prompt.
50
- `;
51
- const DEFAULT_AGENT = `# AGENTS.md
52
-
53
- Configure Pipiclaw's operating rules here.
54
-
55
- This file should define behavior and workflow. Identity, tone, and personality belong in \`SOUL.md\`.
56
-
57
- Suggested sections:
58
-
59
- - Tool usage policy
60
- - Security constraints
61
- - Scheduling/reminder policy
62
- - Project-specific workflows
63
- - Things the assistant must always or never do
64
-
65
- Replace this template with your actual operating instructions.
66
- `;
31
+ import { DEFAULT_AGENTS, DEFAULT_SOUL } from "./workspace-templates.js";
67
32
  const DEFAULT_MEMORY = `# Workspace Memory
68
33
 
69
34
  This file stores stable workspace-level memory.
@@ -128,6 +93,9 @@ const TOOLS_CONFIG_TEMPLATE = {
128
93
  maxResults: 5,
129
94
  },
130
95
  },
96
+ tasks: {
97
+ enabled: true,
98
+ },
131
99
  },
132
100
  _examples: {
133
101
  proxy: "http://127.0.0.1:7890",
@@ -137,6 +105,7 @@ const TOOLS_CONFIG_TEMPLATE = {
137
105
  "Set tools.web.enable to true to register web_search and web_fetch.",
138
106
  "Replace tools.web.search.apiKey with your Brave API key before enabling web tools.",
139
107
  "If needed, copy _examples.proxy to tools.web.proxy.",
108
+ "tools.tasks.enabled is the master switch for autonomous long-running tasks (task_manage tool + task driver + task digest).",
140
109
  ],
141
110
  };
142
111
  const SECURITY_CONFIG_TEMPLATE = {
@@ -232,7 +201,7 @@ export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS) {
232
201
  }
233
202
  }
234
203
  writeTextFileIfMissing(join(paths.workspaceDir, "SOUL.md"), DEFAULT_SOUL, "workspace/SOUL.md", created);
235
- writeTextFileIfMissing(join(paths.workspaceDir, "AGENTS.md"), DEFAULT_AGENT, "workspace/AGENTS.md", created);
204
+ writeTextFileIfMissing(join(paths.workspaceDir, "AGENTS.md"), DEFAULT_AGENTS, "workspace/AGENTS.md", created);
236
205
  writeTextFileIfMissing(join(paths.workspaceDir, "MEMORY.md"), DEFAULT_MEMORY, "workspace/MEMORY.md", created);
237
206
  writeTextFileIfMissing(join(paths.workspaceDir, "ENVIRONMENT.md"), DEFAULT_ENVIRONMENT, "workspace/ENVIRONMENT.md", created);
238
207
  const secretConfigPaths = [
@@ -380,13 +349,13 @@ function waitForTasks(tasks, timeoutMs) {
380
349
  }),
381
350
  ]);
382
351
  }
383
- function flushInactiveChannelMemory(channelStates) {
352
+ function flushInactiveChannelMemory(channelRunners) {
384
353
  const flushes = [];
385
- for (const [channelId, state] of channelStates) {
386
- if (state.running) {
354
+ for (const [channelId, runner] of channelRunners) {
355
+ if (runner.isBusy()) {
387
356
  continue;
388
357
  }
389
- flushes.push(state.runner.flushMemoryForShutdown().catch((err) => {
358
+ flushes.push(runner.flushMemoryForShutdown().catch((err) => {
390
359
  log.logWarning(`[${channelId}] Failed to flush memory during shutdown`, errorMessage(err));
391
360
  }));
392
361
  }
@@ -403,7 +372,7 @@ export function createRuntimeContext(options) {
403
372
  log.configureLogging(runtimeSettingsManager.getLoggingSettings());
404
373
  const startedAt = Date.now();
405
374
  const cliVersion = readCliVersion();
406
- const channelStates = new Map();
375
+ const channelRunners = new Map();
407
376
  const activeTasks = new Set();
408
377
  let durableDispatch;
409
378
  let shuttingDown = false;
@@ -416,34 +385,29 @@ export function createRuntimeContext(options) {
416
385
  log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
417
386
  }
418
387
  };
419
- const getState = (channelId) => {
420
- let state = channelStates.get(channelId);
421
- if (!state) {
388
+ const getRunner = (channelId) => {
389
+ let runner = channelRunners.get(channelId);
390
+ if (!runner) {
422
391
  const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
423
392
  ensureChannelMemoryFilesSync(channelDir);
424
- state = {
425
- running: false,
426
- runner: getOrCreateRunner(channelId, channelDir, {
427
- appHomeDir: options.paths.appHomeDir,
428
- authConfigPath: options.paths.authConfigPath,
429
- modelsConfigPath: options.paths.modelsConfigPath,
430
- }),
431
- stopRequested: false,
432
- };
433
- channelStates.set(channelId, state);
393
+ runner = getOrCreateRunner(channelId, channelDir, {
394
+ appHomeDir: options.paths.appHomeDir,
395
+ authConfigPath: options.paths.authConfigPath,
396
+ modelsConfigPath: options.paths.modelsConfigPath,
397
+ });
398
+ channelRunners.set(channelId, runner);
434
399
  }
435
- return state;
400
+ return runner;
436
401
  };
437
402
  const handler = {
438
403
  isRunning(channelId) {
439
- const state = channelStates.get(channelId);
440
- return state?.running ?? false;
404
+ return channelRunners.get(channelId)?.isBusy() ?? false;
441
405
  },
442
406
  async handleStop(channelId, _bot) {
443
- const state = channelStates.get(channelId);
444
- if (state?.running) {
445
- state.stopRequested = true;
446
- const taskId = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(state.currentTaskText ?? "")?.[1];
407
+ const runner = channelRunners.get(channelId);
408
+ if (runner?.isBusy()) {
409
+ runner.requestStop();
410
+ const taskId = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(runner.getTurnStatus().taskText ?? "")?.[1];
447
411
  if (taskId) {
448
412
  const pauseResult = await pauseTask({
449
413
  args: "",
@@ -463,7 +427,7 @@ export function createRuntimeContext(options) {
463
427
  if (canceled) {
464
428
  log.logInfo(`[${channelId}] Reset ${canceled} durable-dispatch lease(s) on stop`);
465
429
  }
466
- void state.runner.abort().catch((err) => {
430
+ void runner.abort().catch((err) => {
467
431
  log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
468
432
  });
469
433
  log.logInfo(`[${channelId}] Stop requested`);
@@ -496,7 +460,7 @@ export function createRuntimeContext(options) {
496
460
  },
497
461
  async handleStatusCommand(event, bot) {
498
462
  const response = renderStatus({
499
- state: channelStates.get(event.channelId),
463
+ runner: channelRunners.get(event.channelId),
500
464
  version: cliVersion,
501
465
  uptimeMs: Date.now() - startedAt,
502
466
  });
@@ -506,11 +470,16 @@ export function createRuntimeContext(options) {
506
470
  const response = renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
507
471
  await bot.sendPlain(event.channelId, response);
508
472
  },
473
+ // Read-only prompt accounting; safe mid-turn, so it is answered here rather than by
474
+ // the runner's idle command path.
475
+ async handleContextCommand(event, bot, args) {
476
+ await bot.sendPlain(event.channelId, getRunner(event.channelId).renderContextReport(args));
477
+ },
509
478
  async handleBusyMessage(event, bot, mode, queueText) {
510
479
  if (shuttingDown) {
511
480
  return { kind: "handled" };
512
481
  }
513
- const state = getState(event.channelId);
482
+ const runner = getRunner(event.channelId);
514
483
  const trimmedQueueText = queueText.trim();
515
484
  if (!trimmedQueueText) {
516
485
  const commandName = mode === "followUp" ? "followup" : "steer";
@@ -522,7 +491,7 @@ export function createRuntimeContext(options) {
522
491
  return { kind: "requeue", text: trimmedQueueText };
523
492
  }
524
493
  try {
525
- await state.runner.queueSteer(trimmedQueueText, event.userName);
494
+ await runner.queueSteer(trimmedQueueText, event.userName);
526
495
  await archiveIncomingMessage(event.channelId, {
527
496
  date: new Date().toISOString(),
528
497
  ts: event.ts,
@@ -556,14 +525,13 @@ export function createRuntimeContext(options) {
556
525
  log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
557
526
  return;
558
527
  }
559
- const state = getState(event.channelId);
560
- // Mark running synchronously, before yielding to the async task body.
528
+ const runner = getRunner(event.channelId);
529
+ // Reserve the turn synchronously, before yielding to the async task body.
561
530
  // The channel queue invokes this handler's synchronous prefix within the
562
- // same tick as dispatch, so setting it here closes the window where a
563
- // second message arriving in the same tick saw running=false and was
564
- // routed as a fresh run instead of a steer/follow-up.
565
- state.running = true;
566
- state.stopRequested = false;
531
+ // same tick as dispatch, so beginning the turn here closes the window
532
+ // where a second message arriving in the same tick saw an idle runner and
533
+ // was routed as a fresh run instead of a steer/follow-up.
534
+ runner.beginTurn(event.text);
567
535
  await durableDispatch?.markStarted(event.dispatchId);
568
536
  const task = (async () => {
569
537
  try {
@@ -596,24 +564,23 @@ export function createRuntimeContext(options) {
596
564
  return;
597
565
  }
598
566
  if (isRunnerBuiltInCommand(builtInCommand)) {
599
- await state.runner.handleBuiltinCommand(ctx, builtInCommand);
567
+ await runner.handleBuiltinCommand(ctx, builtInCommand);
600
568
  }
601
569
  return;
602
570
  }
603
571
  // Reject an unknown slash command instead of spending a full LLM turn
604
572
  // letting the model guess what `/modle` meant. Session commands,
605
573
  // skills, and prompt templates are recognized by isKnownSlashCommand.
606
- if (event.text.trim().startsWith("/") && !state.runner.isKnownSlashCommand(event.text)) {
574
+ if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
607
575
  const name = slashCommandName(event.text) ?? "";
608
576
  await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
609
577
  return;
610
578
  }
611
579
  log.logInfo(`[${event.channelId}] Starting run: ${event.text.substring(0, 50)}`);
612
- state.currentTaskText = event.text;
613
580
  if (!_isEvent) {
614
581
  ctx.primeCard(350);
615
582
  }
616
- const result = await state.runner.run(ctx, store);
583
+ const result = await runner.run(ctx, store);
617
584
  const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
618
585
  if (taskDriverMatch?.[1] && result.usage && result.durationMs !== undefined) {
619
586
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskDriverMatch[1], {
@@ -624,7 +591,7 @@ export function createRuntimeContext(options) {
624
591
  finishedAt: new Date(),
625
592
  });
626
593
  }
627
- if (result.stopReason === "aborted" && state.stopRequested) {
594
+ if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
628
595
  log.logInfo(`[${event.channelId}] Stopped`);
629
596
  }
630
597
  }
@@ -633,8 +600,7 @@ export function createRuntimeContext(options) {
633
600
  }
634
601
  finally {
635
602
  await durableDispatch?.markCompleted(event.dispatchId);
636
- state.running = false;
637
- state.currentTaskText = undefined;
603
+ runner.endTurn();
638
604
  }
639
605
  })();
640
606
  activeTasks.add(task);
@@ -662,9 +628,26 @@ export function createRuntimeContext(options) {
662
628
  : new MemoryMaintenanceScheduler({
663
629
  appHomeDir: options.paths.appHomeDir,
664
630
  workspaceDir: options.paths.workspaceDir,
665
- getKnownChannelIds: () => channelStates.keys(),
666
- getRuntimeContext: async (channelId) => getState(channelId).runner.getMemoryMaintenanceContext(),
667
- isChannelActive: (channelId) => channelStates.get(channelId)?.running ?? false,
631
+ getKnownChannelIds: () => channelRunners.keys(),
632
+ // Channels active this boot reuse their runner's in-memory context; every
633
+ // other discovered channel gets a lightweight disk-backed context instead
634
+ // of resurrecting a full ChannelRunner (session, tools, sub-agents) that
635
+ // would then sit in the runner cache forever.
636
+ getRuntimeContext: async (channelId) => {
637
+ const runner = channelRunners.get(channelId);
638
+ if (runner) {
639
+ return runner.getMemoryMaintenanceContext();
640
+ }
641
+ return loadDetachedMaintenanceContext({
642
+ channelId,
643
+ channelDir: getChannelDir(options.paths.workspaceDir, channelId),
644
+ workspaceDir: options.paths.workspaceDir,
645
+ authConfigPath: options.paths.authConfigPath,
646
+ modelsConfigPath: options.paths.modelsConfigPath,
647
+ settingsManager: runtimeSettingsManager,
648
+ });
649
+ },
650
+ isChannelActive: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
668
651
  getSettings: () => {
669
652
  runtimeSettingsManager.reload();
670
653
  return {
@@ -680,13 +663,14 @@ export function createRuntimeContext(options) {
680
663
  ? options.createTaskDriver()
681
664
  : new TaskDriver({
682
665
  workspaceDir: options.paths.workspaceDir,
683
- getKnownChannelIds: () => channelStates.keys(),
684
- isChannelActive: (channelId) => channelStates.get(channelId)?.running ?? false,
666
+ getKnownChannelIds: () => channelRunners.keys(),
667
+ isChannelActive: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
685
668
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
686
669
  getSettings: () => {
687
670
  runtimeSettingsManager.reload();
688
671
  return runtimeSettingsManager.getTaskDriverSettings();
689
672
  },
673
+ isEnabled: () => loadToolsConfig(options.paths.appHomeDir).tools.tasks.enabled,
690
674
  intervalMs: options.taskDriverIntervalMs,
691
675
  });
692
676
  const shutdownWithReason = async (reason = "manual") => {
@@ -708,12 +692,12 @@ export function createRuntimeContext(options) {
708
692
  if (!completed) {
709
693
  log.logWarning(`Shutdown grace period exceeded ${SHUTDOWN_WAIT_MS}ms, aborting active runs`);
710
694
  const aborts = [];
711
- for (const [channelId, state] of channelStates) {
712
- if (!state.running)
695
+ for (const [channelId, runner] of channelRunners) {
696
+ if (!runner.isBusy())
713
697
  continue;
714
- state.stopRequested = true;
698
+ runner.requestStop();
715
699
  log.logInfo(`[${channelId}] Aborting active run for shutdown`);
716
- aborts.push(state.runner.abort().catch((err) => {
700
+ aborts.push(runner.abort().catch((err) => {
717
701
  log.logWarning(`[${channelId}] Failed to abort run during shutdown`, errorMessage(err));
718
702
  }));
719
703
  }
@@ -727,7 +711,7 @@ export function createRuntimeContext(options) {
727
711
  }
728
712
  }
729
713
  }
730
- const flushes = flushInactiveChannelMemory(channelStates);
714
+ const flushes = flushInactiveChannelMemory(channelRunners);
731
715
  if (flushes.length > 0) {
732
716
  log.logInfo(`Flushing memory for ${flushes.length} inactive channel(s) before shutdown`);
733
717
  const flushed = await waitForTasks(flushes, SHUTDOWN_FLUSH_WAIT_MS);
@@ -735,7 +719,7 @@ export function createRuntimeContext(options) {
735
719
  log.logWarning(`Shutdown memory flush exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
736
720
  }
737
721
  }
738
- for (const channelId of channelStates.keys()) {
722
+ for (const channelId of channelRunners.keys()) {
739
723
  const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
740
724
  resetRunner(channelId, {
741
725
  appHomeDir: options.paths.appHomeDir,
@@ -0,0 +1,17 @@
1
+ export type QueuedWork = () => Promise<void>;
2
+ /**
3
+ * The per-channel turn serialization point: a channel processes one inbound
4
+ * message at a time; later arrivals wait here. This is runtime policy, not a
5
+ * transport detail — DingTalk consumes it via `DingTalkBot`; busy-state itself
6
+ * is owned by the runner's turn state machine (`AgentRunner.beginTurn`).
7
+ */
8
+ export declare class ChannelQueue {
9
+ private queue;
10
+ private processing;
11
+ private stopped;
12
+ enqueue(work: QueuedWork): void;
13
+ size(): number;
14
+ private processNext;
15
+ stop(): void;
16
+ clearPending(): number;
17
+ }