@oyasmi/pipiclaw 0.9.2-beta.2 → 0.9.2-beta.4

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 (116) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +13 -18
  3. package/dist/agent/channel-runner.js +44 -90
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +8 -0
  6. package/dist/agent/context-budget.js +10 -2
  7. package/dist/agent/job-manager.d.ts +1 -1
  8. package/dist/agent/job-manager.js +9 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/turn-prompt.d.ts +35 -0
  17. package/dist/agent/turn-prompt.js +37 -0
  18. package/dist/agent/turn-recovery.js +1 -1
  19. package/dist/agent/turn-state.d.ts +60 -0
  20. package/dist/agent/turn-state.js +95 -0
  21. package/dist/agent/types.d.ts +3 -3
  22. package/dist/{runtime → channel}/channel-context.d.ts +6 -2
  23. package/dist/{runtime → channel}/channel-context.js +6 -2
  24. package/dist/{runtime → channel}/channel-event.d.ts +8 -0
  25. package/dist/channel/channel-paths.d.ts +16 -0
  26. package/dist/{runtime → channel}/channel-paths.js +20 -0
  27. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +16 -1
  28. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/log.js +14 -5
  31. package/dist/main.js +29 -0
  32. package/dist/memory/commands.js +2 -2
  33. package/dist/memory/maintenance-state.d.ts +8 -0
  34. package/dist/memory/maintenance-state.js +47 -4
  35. package/dist/memory/scheduler.d.ts +6 -0
  36. package/dist/memory/scheduler.js +19 -16
  37. package/dist/playbooks/agent-delegation.md +2 -2
  38. package/dist/runtime/bootstrap.d.ts +2 -2
  39. package/dist/runtime/bootstrap.js +43 -13
  40. package/dist/runtime/delivery.d.ts +3 -3
  41. package/dist/runtime/dingtalk.d.ts +4 -4
  42. package/dist/runtime/dingtalk.js +2 -2
  43. package/dist/runtime/durable-dispatch.d.ts +7 -1
  44. package/dist/runtime/durable-dispatch.js +12 -2
  45. package/dist/runtime/event-commands.js +2 -2
  46. package/dist/runtime/events.d.ts +8 -1
  47. package/dist/runtime/events.js +15 -3
  48. package/dist/runtime/project-commands.js +2 -2
  49. package/dist/runtime/skill-commands.d.ts +27 -0
  50. package/dist/runtime/skill-commands.js +72 -0
  51. package/dist/runtime/subagent-commands.d.ts +8 -0
  52. package/dist/runtime/subagent-commands.js +29 -5
  53. package/dist/runtime/task-commands.js +2 -2
  54. package/dist/runtime/task-driver.d.ts +5 -1
  55. package/dist/runtime/task-driver.js +13 -12
  56. package/dist/runtime/task-migration.js +3 -2
  57. package/dist/runtime/task-wake.d.ts +6 -1
  58. package/dist/runtime/task-wake.js +21 -2
  59. package/dist/settings.d.ts +13 -0
  60. package/dist/settings.js +78 -0
  61. package/dist/shared/token-estimate.d.ts +1 -0
  62. package/dist/shared/token-estimate.js +19 -0
  63. package/dist/subagents/external/claude-code.js +20 -0
  64. package/dist/subagents/external/codex-cli.js +33 -0
  65. package/dist/subagents/external/harness.d.ts +8 -0
  66. package/dist/subagents/external/progress-tail.d.ts +14 -0
  67. package/dist/subagents/external/progress-tail.js +84 -0
  68. package/dist/subagents/external/run.js +1 -0
  69. package/dist/subagents/external/settlement.d.ts +4 -1
  70. package/dist/subagents/external/settlement.js +9 -2
  71. package/dist/subagents/runs.d.ts +45 -4
  72. package/dist/subagents/runs.js +187 -14
  73. package/dist/subagents/tool.js +4 -3
  74. package/dist/tasks/artifact-subject.d.ts +8 -0
  75. package/dist/tasks/artifact-subject.js +25 -0
  76. package/dist/tools/glob-match.d.ts +25 -4
  77. package/dist/tools/glob-match.js +175 -53
  78. package/dist/tools/glob.js +5 -2
  79. package/dist/tools/grep.js +4 -1
  80. package/dist/tools/index.d.ts +1 -1
  81. package/dist/tools/registry.d.ts +1 -1
  82. package/dist/tools/send-media.d.ts +1 -1
  83. package/dist/tools/skill.d.ts +15 -0
  84. package/dist/tools/skill.js +16 -8
  85. package/dist/tui/app.js +5 -3
  86. package/dist/tui/commands.d.ts +1 -0
  87. package/dist/tui/commands.js +3 -1
  88. package/dist/tui/terminal-context.d.ts +2 -2
  89. package/dist/tui/terminal-media-sender.d.ts +1 -1
  90. package/dist/tui/turn-controller.d.ts +2 -1
  91. package/dist/tui/turn-controller.js +2 -1
  92. package/examples/sub-agents/README.md +3 -2
  93. package/examples/sub-agents/builder-hard.md +17 -16
  94. package/examples/sub-agents/builder.md +16 -12
  95. package/examples/sub-agents/documenter.md +15 -16
  96. package/examples/sub-agents/explorer.md +16 -17
  97. package/examples/sub-agents/git-committer.md +18 -28
  98. package/examples/sub-agents/log-sifter.md +15 -14
  99. package/examples/sub-agents/planner.md +11 -11
  100. package/examples/sub-agents/reviewer.md +20 -13
  101. package/examples/sub-agents/scout.md +14 -11
  102. package/examples/sub-agents/verifier.md +17 -14
  103. package/examples/sub-agents/worker.md +18 -12
  104. package/package.json +1 -1
  105. package/dist/runtime/channel-paths.d.ts +0 -4
  106. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  107. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  108. /package/dist/{runtime → channel}/channel-event.js +0 -0
  109. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  110. /package/dist/{runtime → channel}/channel-index.js +0 -0
  111. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  112. /package/dist/{runtime → channel}/project-scope-store.js +0 -0
  113. /package/dist/{runtime → channel}/store.d.ts +0 -0
  114. /package/dist/{runtime → channel}/store.js +0 -0
  115. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  116. /package/dist/{agent → commands}/reply-limits.js +0 -0
package/README.md CHANGED
@@ -26,6 +26,8 @@ Pipiclaw 同时支持两类委派:内置子智能体在进程内完成检索
26
26
 
27
27
  Pipiclaw 使用钉钉 Stream Mode,不需要自建消息中转服务或公网 IP。AI Card 可以持续显示思考、工具执行和状态更新;任务进行中仍可用 `/steer` 调整方向、`/followup` 排队下一件事、`/stop` 中止当前回合。生成的报表、截图和导出文件可以作为钉钉原生附件直接交付。
28
28
 
29
+ 同一个机器人实例可以同时服务多个私聊和群聊:私聊按用户、群聊按群分别建立 channel,不同 channel 的模型回合可以并行推进;同一 channel 内则串行执行,避免一段对话的上下文被多个回合同时修改。需要注意的是,会话隔离不等于代码目录隔离;如果多个 channel 指向同一个项目目录,仍应避免让主智能体同时修改同一批文件,或为并行实现准备独立的 Git worktree。完整边界见[并发与容量](https://github.com/oyasmi/pipiclaw/blob/main/docs/scaling-and-concurrency.md)。
30
+
29
31
  ### 能自主,也能随时接管
30
32
 
31
33
  定时事件适合提醒、周期检查和零 token 的条件传感器;任务台账适合跨小时、跨会话的长期工作。运行状态、模型用量、任务、记忆和委派 run 都有不经过 LLM 的控制命令,即使模型不可用或当前回合卡住,你仍能查看和干预。
@@ -229,6 +231,7 @@ cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/{builder,reviewer}.md \
229
231
  | 记忆、定时事件和长期任务 | [记忆](https://github.com/oyasmi/pipiclaw/blob/main/docs/memory.md) · [事件与任务](https://github.com/oyasmi/pipiclaw/blob/main/docs/events-and-tasks.md) |
230
232
  | 默认安全边界和外部智能体授权 | [安全指南](https://github.com/oyasmi/pipiclaw/blob/main/docs/security.md) |
231
233
  | 部署、升级、备份和排障 | [部署与运维](https://github.com/oyasmi/pipiclaw/blob/main/docs/deployment-and-operations.md) |
234
+ | 多群、多私聊的并发模型与容量边界 | [并发与容量](https://github.com/oyasmi/pipiclaw/blob/main/docs/scaling-and-concurrency.md) |
232
235
 
233
236
  ## 开发
234
237
 
@@ -1,13 +1,13 @@
1
1
  import { Agent, type ThinkingLevel } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { AgentSession, SettingsManager as SDKSettingsManager, SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import type { ChannelContext } from "../channel/channel-context.js";
5
+ import type { ChannelStore } from "../channel/store.js";
6
+ import { type RunnerBuiltInCommand } from "../commands/catalog.js";
4
7
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
5
- import type { ChannelContext } from "../runtime/channel-context.js";
6
- import type { ChannelStore } from "../runtime/store.js";
7
8
  import type { UsageTotals } from "../shared/types.js";
8
9
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
9
- import { type RunnerBuiltInCommand } from "./commands.js";
10
- import type { RunnerFactoryPaths } from "./runner-factory.js";
10
+ import type { RunnerDeps, RunnerFactoryPaths } from "./runner-factory.js";
11
11
  import { type AgentRunner, type RunnerStatusSnapshot, type TurnStatus } from "./types.js";
12
12
  /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
13
13
  export declare function setModelWithThinkingPreservation(session: AgentSession, manager: SDKSettingsManager, model: Model<Api>): Promise<void>;
@@ -32,6 +32,8 @@ export declare class ChannelRunner implements AgentRunner {
32
32
  * Changing project is a dispose-and-rebuild of the whole runner, not a field mutation.
33
33
  */
34
34
  private readonly projectScope;
35
+ /** Re-read per use, not captured once: an edited security.json takes effect without a restart. */
36
+ private readonly loadSecurityConfig;
35
37
  private session;
36
38
  /** Settings manager owned by the currently bound AgentSession. */
37
39
  private sessionSettingsManager;
@@ -62,26 +64,18 @@ export declare class ChannelRunner implements AgentRunner {
62
64
  private firstTurnMemoryBootstrapPending;
63
65
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
64
66
  private tasksEnabled;
65
- /** Single owner of turn state; see TurnPhase in types.ts. */
66
- private turn;
67
- /**
68
- * Turns released by `forceEndTurn` whose owner has not called `endTurn` yet.
69
- * That late release must be swallowed, or it would clear the busy state of
70
- * whichever turn started in the meantime.
71
- */
72
- private abandonedTurns;
67
+ /** Single owner of turn state; see TurnPhase in types.ts and TurnStateMachine in turn-state.ts. */
68
+ private readonly turnState;
73
69
  /** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
74
70
  private retired;
75
71
  /** When the primary model last failed and we switched to the backup. null = on primary. */
76
72
  private primaryFailedAt;
77
73
  private runState;
78
- constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths);
74
+ constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths, deps: RunnerDeps);
79
75
  beginTurn(taskText: string): void;
80
76
  endTurn(): void;
81
77
  forceEndTurn(reason: string): boolean;
82
78
  isBusy(): boolean;
83
- /** Advance a turn's phase, unless that turn has since been released. */
84
- private setPhase;
85
79
  requestStop(): void;
86
80
  getTurnStatus(): TurnStatus;
87
81
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
@@ -126,9 +120,10 @@ export declare class ChannelRunner implements AgentRunner {
126
120
  renderContextReport(args?: string): string;
127
121
  /**
128
122
  * `/help` — the static per-command listing from `commands.ts`, plus (top-level only) the
129
- * workspace skills and prompt templates this session can actually invoke via `/skill:name` and
130
- * `/<template-name>`. Neither list is knowable to `renderBuiltInHelp` itself (it is a pure
131
- * function with no session state), so the runner appends it here (review 2026-08-24 §1.9).
123
+ * prompt templates this session can actually invoke via `/<template-name>`. Workspace skills
124
+ * have their own dedicated command (`/skills`) and are deliberately not duplicated here.
125
+ * Prompt templates aren't knowable to `renderBuiltInHelp` itself (it is a pure function with
126
+ * no session state), so the runner appends them here (review 2026-08-24 §1.9).
132
127
  */
133
128
  private renderHelpWithDiscovery;
134
129
  /** `/subagents list`'s role-directory health tail — whatever this runner already discovered. */
@@ -3,8 +3,9 @@ import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
3
3
  import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
4
4
  import { mkdir, readFile, writeFile } from "fs/promises";
5
5
  import { dirname, join, resolve } from "path";
6
- import { createExecutor } from "../executor.js";
7
- import { createFileStore } from "../file-store.js";
6
+ import { commitActiveSessionRef, resolveActiveSessionFile } from "../channel/active-session-store.js";
7
+ import { resolveProjectScope } from "../channel/project-scope-store.js";
8
+ import { isKnownCommandName, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
8
9
  import * as log from "../log.js";
9
10
  import { buildFirstTurnMemoryBootstrapResult, FIRST_TURN_BOOTSTRAP_MAX_UNITS, } from "../memory/bootstrap.js";
10
11
  import { createMemoryCandidateStore } from "../memory/candidates.js";
@@ -17,13 +18,9 @@ import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js
17
18
  import { getApiKeyForModel } from "../models/api-keys.js";
18
19
  import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
19
20
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
20
- import { commitActiveSessionRef, resolveActiveSessionFile } from "../runtime/active-session-store.js";
21
- import { resolveProjectScope } from "../runtime/project-scope-store.js";
22
- import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
23
21
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
24
22
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
25
23
  import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
26
- import { countPromptUnits } from "../shared/prompt-units.js";
27
24
  import { errorMessage } from "../shared/text-utils.js";
28
25
  import { isRecord } from "../shared/type-guards.js";
29
26
  import { withTimeout } from "../shared/with-timeout.js";
@@ -32,7 +29,6 @@ import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
32
29
  import { createPipiclawTools } from "../tools/index.js";
33
30
  import { getUsageLedger } from "../usage/ledger.js";
34
31
  import { createCommandExtension } from "./command-extension.js";
35
- import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./commands.js";
36
32
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
37
33
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
38
34
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
@@ -43,7 +39,9 @@ import { loadWorkspacePromptResources } from "./prompt/resources.js";
43
39
  import { createRunQueue } from "./run-queue.js";
44
40
  import { handleSessionEvent } from "./session-events.js";
45
41
  import { SessionResourceGate } from "./session-resource-gate.js";
42
+ import { assembleTurnPrompt } from "./turn-prompt.js";
46
43
  import { recoverInterruptedTurn } from "./turn-recovery.js";
44
+ import { TurnStateMachine } from "./turn-state.js";
47
45
  import { getLastAssistantUsage } from "./type-guards.js";
48
46
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
49
47
  import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
@@ -126,23 +124,14 @@ export function initializeThinkingLevelCompat(agent, model, sessionManager, conf
126
124
  const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
127
125
  const SESSION_RELOAD_TIMEOUT_MS = 30_000;
128
126
  export class ChannelRunner {
129
- constructor(channelId, channelDir, paths) {
127
+ constructor(channelId, channelDir, paths, deps) {
130
128
  this.ledger = getUsageLedger();
131
129
  this.currentTools = [];
132
130
  this.firstTurnMemoryBootstrapPending = true;
133
131
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
134
132
  this.tasksEnabled = true;
135
- /** Single owner of turn state; see TurnPhase in types.ts. */
136
- this.turn = {
137
- phase: "idle",
138
- stopRequested: false,
139
- };
140
- /**
141
- * Turns released by `forceEndTurn` whose owner has not called `endTurn` yet.
142
- * That late release must be swallowed, or it would clear the busy state of
143
- * whichever turn started in the meantime.
144
- */
145
- this.abandonedTurns = 0;
133
+ /** Single owner of turn state; see TurnPhase in types.ts and TurnStateMachine in turn-state.ts. */
134
+ this.turnState = new TurnStateMachine((message, detail) => log.logWarning(`[${this.channelId}] ${message}`, detail));
146
135
  /** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
147
136
  this.retired = false;
148
137
  /** When the primary model last failed and we switched to the backup. null = on primary. */
@@ -156,9 +145,9 @@ export class ChannelRunner {
156
145
  this.modelsConfigPath = paths.modelsConfigPath;
157
146
  this.onSessionEvent = paths.onSessionEvent;
158
147
  this.mediaSender = paths.mediaSender;
159
- const executor = createExecutor();
160
- this.executor = executor;
161
- this.fileStore = createFileStore();
148
+ this.executor = deps.executor;
149
+ this.fileStore = deps.fileStore;
150
+ this.loadSecurityConfig = deps.loadSecurityConfig;
162
151
  this.workspaceDir = resolve(dirname(channelDir));
163
152
  // Resolve and freeze this generation's ProjectScope (spec 043, D2/D3/D4.2). A channel with
164
153
  // no persisted selection gets the app default, materialized as its first selection right
@@ -166,7 +155,7 @@ export class ChannelRunner {
166
155
  // or a since-tightened allowlist) fails the whole runner closed rather than silently
167
156
  // falling back to a different root (P7) — the fix is `/project set`/`reset` from a plain
168
157
  // runtime command path, not a degraded-but-running channel; see project-scope-store.ts.
169
- const securityConfigForScope = loadSecurityConfigWithDiagnostics(this.appHomeDir);
158
+ const securityConfigForScope = this.loadSecurityConfig();
170
159
  const projectAccessResolution = resolveProjectAccessPolicy(securityConfigForScope.config, process.cwd());
171
160
  const scopeOutcome = resolveProjectScope(channelDir, projectAccessResolution);
172
161
  if (scopeOutcome.kind === "blocked") {
@@ -240,59 +229,36 @@ export class ChannelRunner {
240
229
  }
241
230
  // === Public API ===
242
231
  beginTurn(taskText) {
243
- if (this.turn.phase !== "idle") {
244
- log.logWarning(`[${this.channelId}] beginTurn while phase=${this.turn.phase}; turns must be serialized`);
245
- }
246
- this.turn = { phase: "dispatching", stopRequested: false, taskText };
232
+ this.turnState.begin(taskText);
247
233
  }
248
234
  endTurn() {
249
- // A turn that `forceEndTurn` already released no longer owns this state.
250
- if (this.abandonedTurns > 0) {
251
- this.abandonedTurns--;
252
- return;
253
- }
254
- this.turn = { phase: "idle", stopRequested: false };
235
+ this.turnState.end();
255
236
  }
256
237
  forceEndTurn(reason) {
257
- if (this.turn.phase === "idle") {
258
- return false;
259
- }
260
- log.logWarning(`[${this.channelId}] Force-ending a stuck turn (phase=${this.turn.phase})`, `${reason}; its own teardown is still running and will be ignored when it finishes`);
261
- this.abandonedTurns++;
262
- this.turn = { phase: "idle", stopRequested: false };
263
- return true;
238
+ return this.turnState.forceEnd(reason);
264
239
  }
265
240
  isBusy() {
266
- return this.turn.phase !== "idle";
267
- }
268
- /** Advance a turn's phase, unless that turn has since been released. */
269
- setPhase(turn, phase) {
270
- if (this.turn !== turn) {
271
- return;
272
- }
273
- this.turn.phase = phase;
241
+ return this.turnState.isBusy();
274
242
  }
275
243
  requestStop() {
276
- if (this.turn.phase !== "idle") {
277
- this.turn.stopRequested = true;
278
- }
244
+ this.turnState.requestStop();
279
245
  }
280
246
  getTurnStatus() {
281
- return { ...this.turn };
247
+ return this.turnState.status();
282
248
  }
283
249
  async run(ctx, store) {
284
250
  const startedAt = Date.now();
285
251
  this.resetRunState(ctx, store);
286
252
  // Direct callers (tests) may skip the transport's beginTurn/endTurn wrapper;
287
253
  // then run() owns the whole turn itself.
288
- const implicitTurn = this.turn.phase === "idle";
254
+ const implicitTurn = !this.turnState.isBusy();
289
255
  if (implicitTurn) {
290
256
  this.beginTurn(ctx.message.text);
291
257
  }
292
258
  // Every later phase write goes through this reference: once `forceEndTurn`
293
- // has released this turn, `this.turn` may already belong to the next one.
294
- const ownTurn = this.turn;
295
- this.setPhase(ownTurn, "preparing");
259
+ // has released this turn, the machine's current turn may already belong to the next one.
260
+ const ownTurn = this.turnState.current();
261
+ this.turnState.setPhase(ownTurn, "preparing");
296
262
  const runQueue = createRunQueue();
297
263
  this.runState.queue = runQueue.queue;
298
264
  let promptSubmitted = false;
@@ -323,12 +289,10 @@ export class ChannelRunner {
323
289
  const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
324
290
  // Ensure channel directory exists
325
291
  await mkdir(this.channelDir, { recursive: true });
326
- promptText = preserveRawInput ? clippedInput : userMessage;
327
292
  if (!preserveRawInput) {
328
293
  // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
329
294
  // system prompt is what lets every channel in a workspace share one cached prefix.
330
295
  channelCapsuleText = this.renderChannelTurnContext();
331
- promptText = `${channelCapsuleText}\n\n<user_message>\n${promptText}\n</user_message>`;
332
296
  // The task digest reads the whole tasks/ directory and depends on nothing the memory
333
297
  // work below produces, so it runs alongside the bootstrap and recall rather than
334
298
  // queuing behind them. Settled into a result object rather than left as a bare
@@ -369,7 +333,6 @@ export class ChannelRunner {
369
333
  });
370
334
  if (recall.renderedText) {
371
335
  recalledContextText = recall.renderedText;
372
- promptText = `${recall.renderedText}\n\n${promptText}`;
373
336
  }
374
337
  }
375
338
  const taskDigestResult = await taskDigestPromise;
@@ -377,27 +340,22 @@ export class ChannelRunner {
377
340
  throw taskDigestResult.error;
378
341
  }
379
342
  taskDigestText = taskDigestResult.text ?? "";
380
- if (taskDigestText) {
381
- promptText = `${taskDigestText}\n\n${promptText}`;
382
- }
383
- if (durableMemoryBootstrapText) {
384
- promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
385
- }
386
343
  }
344
+ const assembled = assembleTurnPrompt({
345
+ clippedInput,
346
+ userMessage,
347
+ preserveRawInput,
348
+ channelCapsule: channelCapsuleText,
349
+ durableMemoryBootstrap: durableMemoryBootstrapText,
350
+ taskDigest: taskDigestText,
351
+ recalledMemory: recalledContextText,
352
+ });
353
+ promptText = assembled.text;
387
354
  // Estimated against the fully assembled prompt (recall + task digest + bootstrap all
388
- // prepended above), not just the bare user message — those pieces can add thousands of
355
+ // included above), not just the bare user message — those pieces can add thousands of
389
356
  // characters and must count against the projected context usage this guard is checking.
390
357
  await this.maybeRunPreventiveCompactionForIncomingText(promptText);
391
- this.lastTurnContextStats = {
392
- durableMemoryChars: durableMemoryBootstrapText.length,
393
- durableMemoryUnits: countPromptUnits(durableMemoryBootstrapText),
394
- taskDigestChars: taskDigestText.length,
395
- taskDigestUnits: countPromptUnits(taskDigestText),
396
- recalledMemoryChars: recalledContextText.length,
397
- recalledMemoryUnits: countPromptUnits(recalledContextText),
398
- channelCapsuleUnits: countPromptUnits(channelCapsuleText),
399
- userMessageChars: clippedInput.length,
400
- };
358
+ this.lastTurnContextStats = assembled.stats;
401
359
  const fallbackDeps = {
402
360
  prompt: async (text) => {
403
361
  try {
@@ -497,7 +455,7 @@ export class ChannelRunner {
497
455
  */
498
456
  async finishTurn(input) {
499
457
  const { ctx, ownTurn, implicitTurn, promptSubmitted, runQueue, fallbackAttempted, fallbackTargetRef } = input;
500
- this.setPhase(ownTurn, "finishing");
458
+ this.turnState.setPhase(ownTurn, "finishing");
501
459
  // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
502
460
  // string the provider actually received — base sections, pi's tail, and the boundary
503
461
  // footer the prompt extension appends at before_agent_start.
@@ -806,9 +764,10 @@ export class ChannelRunner {
806
764
  }
807
765
  /**
808
766
  * `/help` — the static per-command listing from `commands.ts`, plus (top-level only) the
809
- * workspace skills and prompt templates this session can actually invoke via `/skill:name` and
810
- * `/<template-name>`. Neither list is knowable to `renderBuiltInHelp` itself (it is a pure
811
- * function with no session state), so the runner appends it here (review 2026-08-24 §1.9).
767
+ * prompt templates this session can actually invoke via `/<template-name>`. Workspace skills
768
+ * have their own dedicated command (`/skills`) and are deliberately not duplicated here.
769
+ * Prompt templates aren't knowable to `renderBuiltInHelp` itself (it is a pure function with
770
+ * no session state), so the runner appends them here (review 2026-08-24 §1.9).
812
771
  */
813
772
  renderHelpWithDiscovery(args) {
814
773
  const help = renderBuiltInHelp(args);
@@ -816,11 +775,6 @@ export class ChannelRunner {
816
775
  return help;
817
776
  }
818
777
  const sections = [help];
819
- if (this.currentSkills.skills.length > 0) {
820
- sections.push(`**Workspace skills** · 用 \`/skill:<名称>\` 调用\n\n${this.currentSkills.skills
821
- .map((skill) => `- \`/skill:${skill.name}\` — ${skill.description}`)
822
- .join("\n")}`);
823
- }
824
778
  if (this.session.promptTemplates.length > 0) {
825
779
  sections.push(`**Prompt templates**\n\n${this.session.promptTemplates
826
780
  .map((template) => `- \`/${template.name}\``)
@@ -922,10 +876,10 @@ export class ChannelRunner {
922
876
  * while this call was suspended.
923
877
  */
924
878
  assertBusyWindowOpen() {
925
- if (this.turn.phase === "preparing") {
879
+ if (this.turnState.phase() === "preparing") {
926
880
  return;
927
881
  }
928
- if (this.turn.phase === "streaming" && this.session.isStreaming) {
882
+ if (this.turnState.phase() === "streaming" && this.session.isStreaming) {
929
883
  return;
930
884
  }
931
885
  throw new Error("No task is currently running.");
@@ -1318,7 +1272,7 @@ export class ChannelRunner {
1318
1272
  return { agent, session, resourceLoader };
1319
1273
  }
1320
1274
  buildRuntimeTools() {
1321
- const securityLoad = loadSecurityConfigWithDiagnostics(this.appHomeDir);
1275
+ const securityLoad = this.loadSecurityConfig();
1322
1276
  const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
1323
1277
  this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
1324
1278
  this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
@@ -1381,8 +1335,8 @@ export class ChannelRunner {
1381
1335
  catch (err) {
1382
1336
  log.logWarning(`[${this.channelId}] session observer failed`, errorMessage(err));
1383
1337
  }
1384
- if (isRecord(event) && event.type === "message_start" && this.turn.phase === "preparing") {
1385
- this.turn.phase = "streaming";
1338
+ if (isRecord(event) && event.type === "message_start") {
1339
+ this.turnState.markStreaming();
1386
1340
  }
1387
1341
  if (isRecord(event) && "reason" in event && event.reason === "new") {
1388
1342
  this.firstTurnMemoryBootstrapPending = true;
@@ -1,6 +1,6 @@
1
1
  import { basename } from "path";
2
+ import { sessionCommandDescription } from "../commands/catalog.js";
2
3
  import { findModelReferenceMatch, formatModelList, formatModelReference } from "../models/utils.js";
3
- import { sessionCommandDescription } from "./commands.js";
4
4
  export const COMMAND_RESULT_CUSTOM_TYPE = "pipiclaw.command_result";
5
5
  function buildSessionText(stats, currentModel, thinkingLevel, lastResponseModel) {
6
6
  const configuredRef = currentModel ? formatModelReference(currentModel) : null;
@@ -5,5 +5,13 @@ export interface PreventiveCompactionDecision {
5
5
  thresholdTokens: number;
6
6
  ratio: number;
7
7
  }
8
+ /**
9
+ * The incoming message's share of the projected context.
10
+ *
11
+ * Script-aware on purpose (shared with the prompt manifest): a flat characters-per-token ratio
12
+ * put a 12k-character Chinese message at ~4k tokens instead of ~12k, so the projection stayed
13
+ * under the threshold and the turn went in without compacting — the case preventive compaction
14
+ * exists to catch, on this product's most common input.
15
+ */
8
16
  export declare function estimateIncomingMessageTokens(text: string): number;
9
17
  export declare function getPreventiveCompactionDecision(contextTokens: number | null | undefined, incomingTokens: number, contextWindow: number, thresholdRatio?: number): PreventiveCompactionDecision;
@@ -1,10 +1,18 @@
1
+ import { estimateTokens } from "../shared/token-estimate.js";
1
2
  export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
2
- const ESTIMATED_CHARS_PER_TOKEN = 3;
3
+ /**
4
+ * The incoming message's share of the projected context.
5
+ *
6
+ * Script-aware on purpose (shared with the prompt manifest): a flat characters-per-token ratio
7
+ * put a 12k-character Chinese message at ~4k tokens instead of ~12k, so the projection stayed
8
+ * under the threshold and the turn went in without compacting — the case preventive compaction
9
+ * exists to catch, on this product's most common input.
10
+ */
3
11
  export function estimateIncomingMessageTokens(text) {
4
12
  if (!text) {
5
13
  return 0;
6
14
  }
7
- return Math.ceil(text.length / ESTIMATED_CHARS_PER_TOKEN);
15
+ return estimateTokens(text);
8
16
  }
9
17
  export function getPreventiveCompactionDecision(contextTokens, incomingTokens, contextWindow, thresholdRatio = PREVENTIVE_COMPACTION_THRESHOLD_RATIO) {
10
18
  const normalizedContextWindow = Number.isFinite(contextWindow) ? Math.max(0, Math.floor(contextWindow)) : 0;
@@ -1,6 +1,6 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
1
2
  import type { Executor } from "../executor.js";
2
3
  import { type FileStore } from "../file-store.js";
3
- import type { ChannelEvent } from "../runtime/channel-event.js";
4
4
  /**
5
5
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
6
6
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
@@ -221,7 +221,12 @@ export class ChannelJobManager {
221
221
  return;
222
222
  }
223
223
  this.sweepTimer = setInterval(() => {
224
- void this.sweep();
224
+ // A timer callback is the last frame that can hold this promise: an unhandled
225
+ // rejection here (a probe that cannot spawn — EAGAIN/EMFILE/ENOMEM) exits the
226
+ // whole daemon, since nothing installs a process-level rejection handler.
227
+ this.sweep().catch((error) => {
228
+ log.logWarning("Background job sweep failed", errorMessage(error));
229
+ });
225
230
  }, this.sweepIntervalMs);
226
231
  // Do not keep the process alive just for the sweeper.
227
232
  this.sweepTimer.unref?.();
@@ -365,6 +370,9 @@ export class ChannelJobManager {
365
370
  ts: String(Date.now()),
366
371
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
367
372
  dispatchId: `job:${this.channelId}:${record.id}:done`,
373
+ // P0-2: a user is waiting on this job's result — render the resulting turn's progress
374
+ // instead of the "none" style autonomous check-ins get.
375
+ presentation: "awaited",
368
376
  ...(record.contract.taskId
369
377
  ? {
370
378
  internalWake: {
@@ -19,5 +19,4 @@ export declare const RUNTIME_PROMPT_TARGET_UNITS = 700;
19
19
  /** Over this it is a development error: runtime text has drifted well past its budget. */
20
20
  export declare const RUNTIME_PROMPT_HARD_UNITS = 1200;
21
21
  export declare function sha256(text: string): string;
22
- export declare function estimateTokens(text: string): number;
23
22
  export declare function buildPipiclawSystemPrompt(context: PromptBuildContext, definitions?: PromptSectionDefinition[]): PromptBuildResult;
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { createHash } from "node:crypto";
15
15
  import { countPromptUnits } from "../../shared/prompt-units.js";
16
+ import { estimateTokens } from "../../shared/token-estimate.js";
16
17
  import { FINAL_BOUNDARY_SECTION, MAIN_PROMPT_SECTIONS } from "./sections.js";
17
18
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
18
19
  export const RUNTIME_PROMPT_VERSION = 3;
@@ -37,20 +38,6 @@ export const RUNTIME_PROMPT_HARD_UNITS = 1_200;
37
38
  export function sha256(text) {
38
39
  return createHash("sha256").update(text, "utf8").digest("hex");
39
40
  }
40
- /**
41
- * Rough token estimate for reporting only. CJK runs about one token per
42
- * character, Latin text about four characters per token; the provider's real
43
- * tokenizer is the authority, and the usage ledger records what it billed.
44
- */
45
- const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
46
- export function estimateTokens(text) {
47
- let cjk = 0;
48
- for (const char of text) {
49
- if (CJK_REGEX.test(char))
50
- cjk++;
51
- }
52
- return Math.ceil(cjk + (text.length - cjk) / 4);
53
- }
54
41
  function truncateItems(content, maxChars) {
55
42
  const lines = content.split("\n");
56
43
  const kept = [];
@@ -10,7 +10,8 @@
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
12
  import { countPromptUnits } from "../../shared/prompt-units.js";
13
- import { estimateTokens, RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
13
+ import { estimateTokens } from "../../shared/token-estimate.js";
14
+ import { RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
14
15
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
15
16
  export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
16
17
  /**
@@ -133,7 +133,7 @@ export const SUBAGENTS_SECTION = {
133
133
  return [
134
134
  "## Sub-Agents",
135
135
  hasInline
136
- ? "No configured agent exists yet: delegate with `subagent_inline`, passing a `systemPrompt` (no configured agent is required)."
136
+ ? "No configured role is available, so use `subagent_inline` only as the fallback; provide a complete valid payload with required `task` and `systemPrompt`."
137
137
  : "No configured agent exists and `subagent_inline` is off; ask the deployer to add a role or enable it.",
138
138
  "A sub-agent starts blank — state goal, scope, paths, constraints, acceptance criteria in `task`.",
139
139
  "Read agent-delegation.md before non-trivial delegation.",
@@ -1,4 +1,7 @@
1
- import type { MediaSender } from "../runtime/channel-context.js";
1
+ import type { MediaSender } from "../channel/channel-context.js";
2
+ import { type Executor } from "../executor.js";
3
+ import { type FileStore } from "../file-store.js";
4
+ import { type LoadedSecurityConfig } from "../security/config.js";
2
5
  import type { PipiclawSettingsManager } from "../settings.js";
3
6
  import type { AgentRunner } from "./types.js";
4
7
  export interface RunnerFactoryPaths {
@@ -19,6 +22,21 @@ export interface RunnerFactoryPaths {
19
22
  */
20
23
  mediaSender?: MediaSender;
21
24
  }
25
+ /**
26
+ * The collaborators a runner uses but does not build. Composing them here rather than inside
27
+ * `ChannelRunner`'s constructor keeps the "which implementation" decision at the one place that
28
+ * already owns wiring, and is what makes `Executor`/`FileStore` real ports (a remote executor is
29
+ * a different value passed in, not a different branch inside the runner).
30
+ */
31
+ export interface RunnerDeps {
32
+ executor: Executor;
33
+ fileStore: FileStore;
34
+ /**
35
+ * Called per use, not resolved once: the runner re-reads security policy on every tool rebuild
36
+ * so an edited `security.json` takes effect without restarting the daemon.
37
+ */
38
+ loadSecurityConfig: () => LoadedSecurityConfig;
39
+ }
22
40
  /**
23
41
  * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
24
42
  * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
@@ -1,3 +1,6 @@
1
+ import { createExecutor } from "../executor.js";
2
+ import { createFileStore } from "../file-store.js";
3
+ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
1
4
  import { ChannelRunner } from "./channel-runner.js";
2
5
  /**
3
6
  * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
@@ -7,5 +10,9 @@ import { ChannelRunner } from "./channel-runner.js";
7
10
  * could hold a stale entry the real owner had already disposed.
8
11
  */
9
12
  export function createRunner(channelId, channelDir, paths) {
10
- return new ChannelRunner(channelId, channelDir, paths);
13
+ return new ChannelRunner(channelId, channelDir, paths, {
14
+ executor: createExecutor(),
15
+ fileStore: createFileStore(),
16
+ loadSecurityConfig: () => loadSecurityConfigWithDiagnostics(paths.appHomeDir),
17
+ });
11
18
  }
@@ -1,6 +1,6 @@
1
+ import type { ChannelContext } from "../channel/channel-context.js";
2
+ import type { ChannelStore } from "../channel/store.js";
1
3
  import type { MemoryLifecycle } from "../memory/lifecycle.js";
2
- import type { ChannelContext } from "../runtime/channel-context.js";
3
- import type { ChannelStore } from "../runtime/store.js";
4
4
  import type { UsageLedger } from "../usage/ledger.js";
5
5
  import type { PendingTool, RunLogContext, RunQueue, RunState } from "./types.js";
6
6
  export interface SessionEventHandlerContext {
@@ -0,0 +1,35 @@
1
+ import type { PromptTurnContextStats } from "./prompt/manifest.js";
2
+ export interface TurnPromptParts {
3
+ /** The user's message, already clipped to `MAX_USER_MESSAGE_CHARS`. Measured, not rendered. */
4
+ clippedInput: string;
5
+ /** `clippedInput` carrying the runtime's `[time] [user]:` prefix. Unused when raw input is preserved. */
6
+ userMessage: string;
7
+ /**
8
+ * A slash command is forwarded byte-for-byte: the SDK matches it against its own command table,
9
+ * so a wrapper or a prepended context block would stop it from matching.
10
+ */
11
+ preserveRawInput: boolean;
12
+ /** `<runtime_turn_context>`: the channel facts kept out of the cached system prompt. */
13
+ channelCapsule: string;
14
+ durableMemoryBootstrap: string;
15
+ taskDigest: string;
16
+ recalledMemory: string;
17
+ }
18
+ export interface AssembledTurnPrompt {
19
+ text: string;
20
+ stats: PromptTurnContextStats;
21
+ }
22
+ /**
23
+ * Compose one turn's prompt from the pieces `run()` gathered, and measure what each piece cost.
24
+ *
25
+ * The order is a contract, not a preference: durable memory bootstrap → task agenda → recalled
26
+ * memory → channel capsule → the user's message. Everything the runtime supplies precedes the
27
+ * message it is context *for*, and the blocks that change least between turns come first, so the
28
+ * provider's prefix cache keeps as long a match as possible. An empty piece contributes no
29
+ * separator, so a turn with nothing to recall reads exactly like one where recall is disabled.
30
+ *
31
+ * `stats` measures the inputs, never the rendered wrapper — it is what `/context` reports as the
32
+ * previous turn's automatic context, and the per-piece unit caps are enforced upstream by the
33
+ * builders themselves (`memory/recall.ts`, `memory/task-digest.ts`, `memory/bootstrap.ts`).
34
+ */
35
+ export declare function assembleTurnPrompt(parts: TurnPromptParts): AssembledTurnPrompt;