@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.6

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 (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -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/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /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,14 @@
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 InboundImage } from "../channel/channel-event.js";
6
+ import type { ChannelStore } from "../channel/store.js";
7
+ import { type RunnerBuiltInCommand } from "../commands/catalog.js";
4
8
  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
9
  import type { UsageTotals } from "../shared/types.js";
8
10
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
9
- import { type RunnerBuiltInCommand } from "./commands.js";
10
- import type { RunnerFactoryPaths } from "./runner-factory.js";
11
+ import type { RunnerDeps, RunnerFactoryPaths } from "./runner-factory.js";
11
12
  import { type AgentRunner, type RunnerStatusSnapshot, type TurnStatus } from "./types.js";
12
13
  /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
13
14
  export declare function setModelWithThinkingPreservation(session: AgentSession, manager: SDKSettingsManager, model: Model<Api>): Promise<void>;
@@ -32,6 +33,8 @@ export declare class ChannelRunner implements AgentRunner {
32
33
  * Changing project is a dispose-and-rebuild of the whole runner, not a field mutation.
33
34
  */
34
35
  private readonly projectScope;
36
+ /** Re-read per use, not captured once: an edited security.json takes effect without a restart. */
37
+ private readonly loadSecurityConfig;
35
38
  private session;
36
39
  /** Settings manager owned by the currently bound AgentSession. */
37
40
  private sessionSettingsManager;
@@ -46,6 +49,13 @@ export declare class ChannelRunner implements AgentRunner {
46
49
  private readonly memoryActivityRecorder;
47
50
  private readonly sessionResourceGate;
48
51
  private readonly sessionReady;
52
+ /**
53
+ * Flips true only once `initializeSession` has fully assigned `this.session`
54
+ * and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
55
+ * must not touch `this.session` before this — the model runtime takes hundreds
56
+ * of ms to build and the first message can arrive first (spec 048 F2).
57
+ */
58
+ private sessionInitialized;
49
59
  private sessionRuntime;
50
60
  private sessionUnsubscribe?;
51
61
  private subAgentDiscovery;
@@ -62,26 +72,18 @@ export declare class ChannelRunner implements AgentRunner {
62
72
  private firstTurnMemoryBootstrapPending;
63
73
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
64
74
  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;
75
+ /** Single owner of turn state; see TurnPhase in types.ts and TurnStateMachine in turn-state.ts. */
76
+ private readonly turnState;
73
77
  /** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
74
78
  private retired;
75
79
  /** When the primary model last failed and we switched to the backup. null = on primary. */
76
80
  private primaryFailedAt;
77
81
  private runState;
78
- constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths);
82
+ constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths, deps: RunnerDeps);
79
83
  beginTurn(taskText: string): void;
80
84
  endTurn(): void;
81
85
  forceEndTurn(reason: string): boolean;
82
86
  isBusy(): boolean;
83
- /** Advance a turn's phase, unless that turn has since been released. */
84
- private setPhase;
85
87
  requestStop(): void;
86
88
  getTurnStatus(): TurnStatus;
87
89
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
@@ -109,7 +111,7 @@ export declare class ChannelRunner implements AgentRunner {
109
111
  * full LLM turn.
110
112
  */
111
113
  isKnownSlashCommand(text: string): boolean;
112
- queueSteer(text: string, userName?: string): Promise<void>;
114
+ queueSteer(text: string, userName?: string, images?: InboundImage[]): Promise<void>;
113
115
  flushMemoryForShutdown(): Promise<void>;
114
116
  dispose(): Promise<void>;
115
117
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -126,9 +128,10 @@ export declare class ChannelRunner implements AgentRunner {
126
128
  renderContextReport(args?: string): string;
127
129
  /**
128
130
  * `/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).
131
+ * prompt templates this session can actually invoke via `/<template-name>`. Workspace skills
132
+ * have their own dedicated command (`/skills`) and are deliberately not duplicated here.
133
+ * Prompt templates aren't knowable to `renderBuiltInHelp` itself (it is a pure function with
134
+ * no session state), so the runner appends them here (review 2026-08-24 §1.9).
132
135
  */
133
136
  private renderHelpWithDiscovery;
134
137
  /** `/subagents list`'s role-directory health tail — whatever this runner already discovered. */
@@ -163,6 +166,29 @@ export declare class ChannelRunner implements AgentRunner {
163
166
  */
164
167
  private persistOversizedInput;
165
168
  private formatUserMessage;
169
+ /**
170
+ * Turn `InboundImage`s (already downloaded and persisted by the transport, spec 049) into the
171
+ * `ImageContent[]` `AgentSession.prompt`/`steer` accept, plus any notices to surface to the
172
+ * user about images that did not make it into this turn.
173
+ *
174
+ * Two gates apply, both fail *open* toward "still deliver the message" rather than dropping
175
+ * the whole turn over one bad attachment:
176
+ *
177
+ * - The current model's `input` capability (spec 049 D7). A model that does not declare
178
+ * `"image"` support has its image blocks silently replaced with a text placeholder by the
179
+ * SDK's provider layer — exactly the failure this spec exists to fix, so it is checked
180
+ * explicitly here rather than trusted to fail loudly on its own. Re-checked on every call
181
+ * (including a mid-turn steer after a model fallback), since a fallback model's capability
182
+ * can differ from the one the turn started with.
183
+ * - A defense-in-depth size re-check against `MAX_INBOUND_IMAGE_BYTES`. The transport already
184
+ * enforces this at download time, but the check is cheap and free of assumptions about how
185
+ * an `InboundImage` reached this method.
186
+ *
187
+ * An image already marked `unsupportedFormat` (sniffing failed at download time) is skipped
188
+ * without its own notice — the `[图片N:格式不支持,已保存]` marker already in the message text
189
+ * covers it.
190
+ */
191
+ private prepareInboundImages;
166
192
  /**
167
193
  * Single source of truth for the busy-message window: steer is accepted while
168
194
  * the prompt is being assembled ("preparing") or while the agent loop is
@@ -3,8 +3,10 @@ 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 { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
8
+ import { resolveProjectScope } from "../channel/project-scope-store.js";
9
+ import { isKnownCommandName, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
8
10
  import * as log from "../log.js";
9
11
  import { buildFirstTurnMemoryBootstrapResult, FIRST_TURN_BOOTSTRAP_MAX_UNITS, } from "../memory/bootstrap.js";
10
12
  import { createMemoryCandidateStore } from "../memory/candidates.js";
@@ -17,22 +19,19 @@ import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js
17
19
  import { getApiKeyForModel } from "../models/api-keys.js";
18
20
  import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
19
21
  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
22
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
23
+ import { TASK_DIGEST_SETTINGS } from "../settings.js";
24
24
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
25
25
  import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
26
- import { countPromptUnits } from "../shared/prompt-units.js";
27
26
  import { errorMessage } from "../shared/text-utils.js";
28
27
  import { isRecord } from "../shared/type-guards.js";
29
28
  import { withTimeout } from "../shared/with-timeout.js";
30
29
  import { discoverSubAgents } from "../subagents/discovery.js";
31
30
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
32
31
  import { createPipiclawTools } from "../tools/index.js";
32
+ import { formatSize } from "../tools/truncate.js";
33
33
  import { getUsageLedger } from "../usage/ledger.js";
34
34
  import { createCommandExtension } from "./command-extension.js";
35
- import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./commands.js";
36
35
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
37
36
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
38
37
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
@@ -43,7 +42,9 @@ import { loadWorkspacePromptResources } from "./prompt/resources.js";
43
42
  import { createRunQueue } from "./run-queue.js";
44
43
  import { handleSessionEvent } from "./session-events.js";
45
44
  import { SessionResourceGate } from "./session-resource-gate.js";
45
+ import { assembleTurnPrompt } from "./turn-prompt.js";
46
46
  import { recoverInterruptedTurn } from "./turn-recovery.js";
47
+ import { TurnStateMachine } from "./turn-state.js";
47
48
  import { getLastAssistantUsage } from "./type-guards.js";
48
49
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
49
50
  import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
@@ -126,23 +127,21 @@ export function initializeThinkingLevelCompat(agent, model, sessionManager, conf
126
127
  const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
127
128
  const SESSION_RELOAD_TIMEOUT_MS = 30_000;
128
129
  export class ChannelRunner {
129
- constructor(channelId, channelDir, paths) {
130
+ constructor(channelId, channelDir, paths, deps) {
130
131
  this.ledger = getUsageLedger();
132
+ /**
133
+ * Flips true only once `initializeSession` has fully assigned `this.session`
134
+ * and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
135
+ * must not touch `this.session` before this — the model runtime takes hundreds
136
+ * of ms to build and the first message can arrive first (spec 048 F2).
137
+ */
138
+ this.sessionInitialized = false;
131
139
  this.currentTools = [];
132
140
  this.firstTurnMemoryBootstrapPending = true;
133
141
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
134
142
  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;
143
+ /** Single owner of turn state; see TurnPhase in types.ts and TurnStateMachine in turn-state.ts. */
144
+ this.turnState = new TurnStateMachine((message, detail) => log.logWarning(`[${this.channelId}] ${message}`, detail));
146
145
  /** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
147
146
  this.retired = false;
148
147
  /** When the primary model last failed and we switched to the backup. null = on primary. */
@@ -156,9 +155,9 @@ export class ChannelRunner {
156
155
  this.modelsConfigPath = paths.modelsConfigPath;
157
156
  this.onSessionEvent = paths.onSessionEvent;
158
157
  this.mediaSender = paths.mediaSender;
159
- const executor = createExecutor();
160
- this.executor = executor;
161
- this.fileStore = createFileStore();
158
+ this.executor = deps.executor;
159
+ this.fileStore = deps.fileStore;
160
+ this.loadSecurityConfig = deps.loadSecurityConfig;
162
161
  this.workspaceDir = resolve(dirname(channelDir));
163
162
  // Resolve and freeze this generation's ProjectScope (spec 043, D2/D3/D4.2). A channel with
164
163
  // no persisted selection gets the app default, materialized as its first selection right
@@ -166,7 +165,7 @@ export class ChannelRunner {
166
165
  // or a since-tightened allowlist) fails the whole runner closed rather than silently
167
166
  // falling back to a different root (P7) — the fix is `/project set`/`reset` from a plain
168
167
  // runtime command path, not a degraded-but-running channel; see project-scope-store.ts.
169
- const securityConfigForScope = loadSecurityConfigWithDiagnostics(this.appHomeDir);
168
+ const securityConfigForScope = this.loadSecurityConfig();
170
169
  const projectAccessResolution = resolveProjectAccessPolicy(securityConfigForScope.config, process.cwd());
171
170
  const scopeOutcome = resolveProjectScope(channelDir, projectAccessResolution);
172
171
  if (scopeOutcome.kind === "blocked") {
@@ -240,59 +239,36 @@ export class ChannelRunner {
240
239
  }
241
240
  // === Public API ===
242
241
  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 };
242
+ this.turnState.begin(taskText);
247
243
  }
248
244
  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 };
245
+ this.turnState.end();
255
246
  }
256
247
  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;
248
+ return this.turnState.forceEnd(reason);
264
249
  }
265
250
  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;
251
+ return this.turnState.isBusy();
274
252
  }
275
253
  requestStop() {
276
- if (this.turn.phase !== "idle") {
277
- this.turn.stopRequested = true;
278
- }
254
+ this.turnState.requestStop();
279
255
  }
280
256
  getTurnStatus() {
281
- return { ...this.turn };
257
+ return this.turnState.status();
282
258
  }
283
259
  async run(ctx, store) {
284
260
  const startedAt = Date.now();
285
261
  this.resetRunState(ctx, store);
286
262
  // Direct callers (tests) may skip the transport's beginTurn/endTurn wrapper;
287
263
  // then run() owns the whole turn itself.
288
- const implicitTurn = this.turn.phase === "idle";
264
+ const implicitTurn = !this.turnState.isBusy();
289
265
  if (implicitTurn) {
290
266
  this.beginTurn(ctx.message.text);
291
267
  }
292
268
  // 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");
269
+ // has released this turn, the machine's current turn may already belong to the next one.
270
+ const ownTurn = this.turnState.current();
271
+ this.turnState.setPhase(ownTurn, "preparing");
296
272
  const runQueue = createRunQueue();
297
273
  this.runState.queue = runQueue.queue;
298
274
  let promptSubmitted = false;
@@ -323,12 +299,10 @@ export class ChannelRunner {
323
299
  const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
324
300
  // Ensure channel directory exists
325
301
  await mkdir(this.channelDir, { recursive: true });
326
- promptText = preserveRawInput ? clippedInput : userMessage;
327
302
  if (!preserveRawInput) {
328
303
  // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
329
304
  // system prompt is what lets every channel in a workspace share one cached prefix.
330
305
  channelCapsuleText = this.renderChannelTurnContext();
331
- promptText = `${channelCapsuleText}\n\n<user_message>\n${promptText}\n</user_message>`;
332
306
  // The task digest reads the whole tasks/ directory and depends on nothing the memory
333
307
  // work below produces, so it runs alongside the bootstrap and recall rather than
334
308
  // queuing behind them. Settled into a result object rather than left as a bare
@@ -369,7 +343,6 @@ export class ChannelRunner {
369
343
  });
370
344
  if (recall.renderedText) {
371
345
  recalledContextText = recall.renderedText;
372
- promptText = `${recall.renderedText}\n\n${promptText}`;
373
346
  }
374
347
  }
375
348
  const taskDigestResult = await taskDigestPromise;
@@ -377,32 +350,38 @@ export class ChannelRunner {
377
350
  throw taskDigestResult.error;
378
351
  }
379
352
  taskDigestText = taskDigestResult.text ?? "";
380
- if (taskDigestText) {
381
- promptText = `${taskDigestText}\n\n${promptText}`;
382
- }
383
- if (durableMemoryBootstrapText) {
384
- promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
385
- }
353
+ }
354
+ const assembled = assembleTurnPrompt({
355
+ clippedInput,
356
+ userMessage,
357
+ preserveRawInput,
358
+ channelCapsule: channelCapsuleText,
359
+ durableMemoryBootstrap: durableMemoryBootstrapText,
360
+ taskDigest: taskDigestText,
361
+ recalledMemory: recalledContextText,
362
+ });
363
+ promptText = assembled.text;
364
+ // Resolved before the compaction estimate below (which needs the image count) and
365
+ // refreshed inside `setModel` further down if a fallback switches models mid-turn
366
+ // (spec 049 D7) — a model's image support is looked up here explicitly because the
367
+ // SDK's own handling of an unsupported model is to silently replace each image block
368
+ // with a text placeholder.
369
+ let preparedImages = await this.prepareInboundImages(ctx.message.images);
370
+ for (const notice of preparedImages.notices) {
371
+ await ctx.respondInThread(notice);
386
372
  }
387
373
  // 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
374
+ // included above), not just the bare user message — those pieces can add thousands of
389
375
  // characters and must count against the projected context usage this guard is checking.
390
- 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
- };
376
+ // Each image adds a fixed per-image estimate on top of the text: three attached photos
377
+ // can by themselves push a turn over the threshold that would trigger this guard.
378
+ await this.maybeRunPreventiveCompactionForIncomingText(promptText, preparedImages.images.length);
379
+ this.lastTurnContextStats = assembled.stats;
401
380
  const fallbackDeps = {
402
381
  prompt: async (text) => {
403
382
  try {
404
383
  await this.sessionResourceGate.runPrompt(async () => {
405
- await this.session.prompt(text);
384
+ await this.session.prompt(text, preparedImages.images.length > 0 ? { images: preparedImages.images } : undefined);
406
385
  promptSubmitted = true;
407
386
  if (bootstrapPrepared)
408
387
  this.firstTurnMemoryBootstrapPending = false;
@@ -436,6 +415,13 @@ export class ChannelRunner {
436
415
  resolveFallbackModel: () => this.resolveFallbackModel(),
437
416
  setModel: async (model) => {
438
417
  await this.setModelWithThinkingPreservation(model);
418
+ // The fallback model's vision support can differ from the one this turn started
419
+ // on; re-resolve against it rather than resend whatever was prepared for the
420
+ // model that just failed.
421
+ preparedImages = await this.prepareInboundImages(ctx.message.images);
422
+ for (const notice of preparedImages.notices) {
423
+ await ctx.respondInThread(notice);
424
+ }
439
425
  },
440
426
  notifySwitch: (from, to, errorSummary) => {
441
427
  fallbackTargetRef = to;
@@ -497,7 +483,7 @@ export class ChannelRunner {
497
483
  */
498
484
  async finishTurn(input) {
499
485
  const { ctx, ownTurn, implicitTurn, promptSubmitted, runQueue, fallbackAttempted, fallbackTargetRef } = input;
500
- this.setPhase(ownTurn, "finishing");
486
+ this.turnState.setPhase(ownTurn, "finishing");
501
487
  // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
502
488
  // string the provider actually received — base sections, pi's tail, and the boundary
503
489
  // footer the prompt extension appends at before_agent_start.
@@ -635,6 +621,10 @@ export class ChannelRunner {
635
621
  }
636
622
  async handleBuiltinCommand(ctx, command) {
637
623
  try {
624
+ // `/help` and `/context` read `this.session` (prompt templates, active model).
625
+ // The session runtime is built asynchronously after construction, so a command
626
+ // that lands before it is ready would otherwise hit a TypeError (spec 048 F2).
627
+ await this.ensureSessionReady();
638
628
  switch (command.name) {
639
629
  case "help":
640
630
  await this.sendCommandReply(ctx, this.renderHelpWithDiscovery(command.args), "help");
@@ -684,10 +674,17 @@ export class ChannelRunner {
684
674
  if (isKnownCommandName(name, this.currentSkills.skills.map((skill) => skill.name.toLowerCase()))) {
685
675
  return true;
686
676
  }
677
+ // Synchronous dispatch-path call: before the session runtime finishes building,
678
+ // fall back to the static catalog + skills only. Misclassifying a prompt template
679
+ // as "unknown" for the first few hundred ms after a runner is created is far
680
+ // cheaper than throwing on the dispatch main path (spec 048 F2/D7).
681
+ if (!this.sessionInitialized) {
682
+ return false;
683
+ }
687
684
  return this.session.promptTemplates.some((template) => template.name.toLowerCase() === name);
688
685
  }
689
- async queueSteer(text, userName) {
690
- await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName);
686
+ async queueSteer(text, userName, images) {
687
+ await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName, images);
691
688
  }
692
689
  async flushMemoryForShutdown() {
693
690
  await this.flushMemoryActivity();
@@ -806,9 +803,10 @@ export class ChannelRunner {
806
803
  }
807
804
  /**
808
805
  * `/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).
806
+ * prompt templates this session can actually invoke via `/<template-name>`. Workspace skills
807
+ * have their own dedicated command (`/skills`) and are deliberately not duplicated here.
808
+ * Prompt templates aren't knowable to `renderBuiltInHelp` itself (it is a pure function with
809
+ * no session state), so the runner appends them here (review 2026-08-24 §1.9).
812
810
  */
813
811
  renderHelpWithDiscovery(args) {
814
812
  const help = renderBuiltInHelp(args);
@@ -816,11 +814,6 @@ export class ChannelRunner {
816
814
  return help;
817
815
  }
818
816
  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
817
  if (this.session.promptTemplates.length > 0) {
825
818
  sections.push(`**Prompt templates**\n\n${this.session.promptTemplates
826
819
  .map((template) => `- \`/${template.name}\``)
@@ -915,6 +908,63 @@ export class ChannelRunner {
915
908
  formatUserMessage(text, userName, now = new Date()) {
916
909
  return `[${formatLocalTime(now)}] [${userName || "unknown"}]: ${text}`;
917
910
  }
911
+ /**
912
+ * Turn `InboundImage`s (already downloaded and persisted by the transport, spec 049) into the
913
+ * `ImageContent[]` `AgentSession.prompt`/`steer` accept, plus any notices to surface to the
914
+ * user about images that did not make it into this turn.
915
+ *
916
+ * Two gates apply, both fail *open* toward "still deliver the message" rather than dropping
917
+ * the whole turn over one bad attachment:
918
+ *
919
+ * - The current model's `input` capability (spec 049 D7). A model that does not declare
920
+ * `"image"` support has its image blocks silently replaced with a text placeholder by the
921
+ * SDK's provider layer — exactly the failure this spec exists to fix, so it is checked
922
+ * explicitly here rather than trusted to fail loudly on its own. Re-checked on every call
923
+ * (including a mid-turn steer after a model fallback), since a fallback model's capability
924
+ * can differ from the one the turn started with.
925
+ * - A defense-in-depth size re-check against `MAX_INBOUND_IMAGE_BYTES`. The transport already
926
+ * enforces this at download time, but the check is cheap and free of assumptions about how
927
+ * an `InboundImage` reached this method.
928
+ *
929
+ * An image already marked `unsupportedFormat` (sniffing failed at download time) is skipped
930
+ * without its own notice — the `[图片N:格式不支持,已保存]` marker already in the message text
931
+ * covers it.
932
+ */
933
+ async prepareInboundImages(images) {
934
+ if (!images || images.length === 0) {
935
+ return { images: [], notices: [] };
936
+ }
937
+ const model = this.session.model ?? this.activeModel;
938
+ if (!model.input.includes("image")) {
939
+ const modelRef = formatModelReference(model);
940
+ return {
941
+ images: [],
942
+ notices: [
943
+ `⚠️ 当前模型 ${modelRef} 不支持图片输入,收到的图片已保存但未加入本轮上下文:\n` +
944
+ images.map((image) => `- \`${image.path}\``).join("\n") +
945
+ "\n可以切换到支持视觉的模型后让我 read 该文件。",
946
+ ],
947
+ };
948
+ }
949
+ const contents = [];
950
+ const notices = [];
951
+ for (const image of images) {
952
+ if (image.unsupportedFormat)
953
+ continue;
954
+ if (image.byteSize > MAX_INBOUND_IMAGE_BYTES) {
955
+ notices.push(`⚠️ 图片 \`${image.path}\`(${formatSize(image.byteSize)})超过 ${formatSize(MAX_INBOUND_IMAGE_BYTES)} 上限,未加入本轮上下文,可以让我 read 该文件查看。`);
956
+ continue;
957
+ }
958
+ try {
959
+ const data = await readFile(image.path);
960
+ contents.push({ type: "image", data: data.toString("base64"), mimeType: image.mimeType });
961
+ }
962
+ catch (error) {
963
+ notices.push(`⚠️ 图片 \`${image.path}\` 读取失败:${errorMessage(error)}`);
964
+ }
965
+ }
966
+ return { images: contents, notices };
967
+ }
918
968
  /**
919
969
  * Single source of truth for the busy-message window: steer is accepted while
920
970
  * the prompt is being assembled ("preparing") or while the agent loop is
@@ -922,15 +972,15 @@ export class ChannelRunner {
922
972
  * while this call was suspended.
923
973
  */
924
974
  assertBusyWindowOpen() {
925
- if (this.turn.phase === "preparing") {
975
+ if (this.turnState.phase() === "preparing") {
926
976
  return;
927
977
  }
928
- if (this.turn.phase === "streaming" && this.session.isStreaming) {
978
+ if (this.turnState.phase() === "streaming" && this.session.isStreaming) {
929
979
  return;
930
980
  }
931
981
  throw new Error("No task is currently running.");
932
982
  }
933
- async queueBusyMessage(text, userName) {
983
+ async queueBusyMessage(text, userName, images) {
934
984
  this.assertBusyWindowOpen();
935
985
  await this.ensureSessionReady();
936
986
  const oversized = text.replace(/\r/g, "").trim().length > MAX_USER_MESSAGE_CHARS;
@@ -940,11 +990,15 @@ export class ChannelRunner {
940
990
  log.logWarning(`[${this.channelId}] Queued message exceeded ${MAX_USER_MESSAGE_CHARS} chars and was clipped`);
941
991
  }
942
992
  const queuedMessage = this.formatUserMessage(clippedText, userName);
943
- await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage);
993
+ const preparedImages = await this.prepareInboundImages(images);
994
+ for (const notice of preparedImages.notices) {
995
+ await this.runState.ctx?.respondInThread(notice);
996
+ }
997
+ await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage, preparedImages.images.length);
944
998
  this.assertBusyWindowOpen();
945
999
  const queueMessage = async () => {
946
1000
  this.assertBusyWindowOpen();
947
- await this.session.steer(queuedMessage);
1001
+ await this.session.steer(queuedMessage, preparedImages.images.length > 0 ? preparedImages.images : undefined);
948
1002
  };
949
1003
  await this.sessionResourceGate.runPrompt(queueMessage);
950
1004
  }
@@ -1070,6 +1124,7 @@ export class ChannelRunner {
1070
1124
  this.subscribeToSessionEvents();
1071
1125
  await this.reloadSessionResources();
1072
1126
  await this.bindSessionExtensions();
1127
+ this.sessionInitialized = true;
1073
1128
  }
1074
1129
  async reloadSessionResources() {
1075
1130
  this.settingsManager.reload();
@@ -1112,11 +1167,11 @@ export class ChannelRunner {
1112
1167
  async ensureSessionReady() {
1113
1168
  await this.sessionReady;
1114
1169
  }
1115
- async maybeRunPreventiveCompactionForIncomingText(incomingText) {
1170
+ async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
1116
1171
  const currentModel = this.session.model ?? this.activeModel;
1117
1172
  const contextUsage = this.session.getContextUsage();
1118
1173
  const contextTokens = contextUsage?.tokens;
1119
- const incomingTokens = estimateIncomingMessageTokens(incomingText);
1174
+ const incomingTokens = estimateIncomingMessageTokens(incomingText, imageCount);
1120
1175
  const decision = getPreventiveCompactionDecision(contextTokens, incomingTokens, currentModel.contextWindow);
1121
1176
  if (!decision.shouldCompact) {
1122
1177
  return;
@@ -1318,7 +1373,7 @@ export class ChannelRunner {
1318
1373
  return { agent, session, resourceLoader };
1319
1374
  }
1320
1375
  buildRuntimeTools() {
1321
- const securityLoad = loadSecurityConfigWithDiagnostics(this.appHomeDir);
1376
+ const securityLoad = this.loadSecurityConfig();
1322
1377
  const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
1323
1378
  this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
1324
1379
  this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
@@ -1381,8 +1436,8 @@ export class ChannelRunner {
1381
1436
  catch (err) {
1382
1437
  log.logWarning(`[${this.channelId}] session observer failed`, errorMessage(err));
1383
1438
  }
1384
- if (isRecord(event) && event.type === "message_start" && this.turn.phase === "preparing") {
1385
- this.turn.phase = "streaming";
1439
+ if (isRecord(event) && event.type === "message_start") {
1440
+ this.turnState.markStreaming();
1386
1441
  }
1387
1442
  if (isRecord(event) && "reason" in event && event.reason === "new") {
1388
1443
  this.firstTurnMemoryBootstrapPending = true;
@@ -1416,11 +1471,10 @@ export class ChannelRunner {
1416
1471
  }
1417
1472
  /** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
1418
1473
  buildTaskDigestForTurn() {
1419
- const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
1420
1474
  return buildTaskDigest({
1421
1475
  channelDir: this.channelDir,
1422
- maxTasks: taskDigestSettings.maxTasks,
1423
- maxChars: taskDigestSettings.maxChars,
1476
+ maxTasks: TASK_DIGEST_SETTINGS.maxTasks,
1477
+ maxChars: TASK_DIGEST_SETTINGS.maxChars,
1424
1478
  maxUnits: TASK_AGENDA_MAX_UNITS,
1425
1479
  });
1426
1480
  }
@@ -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;