@oyasmi/pipiclaw 0.9.6-beta.1 → 0.9.6-beta.2

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 (258) hide show
  1. package/README.en.md +279 -215
  2. package/README.md +274 -213
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +3 -2
  6. package/dist/agent/channel-runner.js +16 -27
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +1 -1
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/event-guards.d.ts +2 -1
  23. package/dist/agent/session/event-guards.js +6 -0
  24. package/dist/agent/session/model-selection.d.ts +2 -1
  25. package/dist/agent/session/model-selection.js +5 -5
  26. package/dist/agent/session/session-events.js +31 -4
  27. package/dist/agent/session/session-host.d.ts +4 -2
  28. package/dist/agent/session/session-host.js +17 -15
  29. package/dist/agent/status-render.js +3 -0
  30. package/dist/agent/turn/task-digest.d.ts +2 -5
  31. package/dist/agent/turn/task-digest.js +25 -45
  32. package/dist/agent/turn/turn-context.js +4 -6
  33. package/dist/agent/turn/turn-error.d.ts +1 -1
  34. package/dist/agent/turn/turn-error.js +9 -0
  35. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  36. package/dist/agent/turn/turn-pipeline.js +36 -7
  37. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  38. package/dist/agent/turn/turn-prompt.js +2 -1
  39. package/dist/agent/turn/turn-recovery.js +4 -1
  40. package/dist/agent/types.d.ts +20 -2
  41. package/dist/agent/types.js +2 -0
  42. package/dist/app/auth-command.d.ts +25 -0
  43. package/dist/app/auth-command.js +200 -67
  44. package/dist/app/home.d.ts +7 -8
  45. package/dist/app/home.js +143 -56
  46. package/dist/channel/channel-context.d.ts +6 -0
  47. package/dist/channel/config.d.ts +3 -0
  48. package/dist/channel/config.js +11 -5
  49. package/dist/commands/catalog.js +22 -6
  50. package/dist/desk/commands.d.ts +31 -4
  51. package/dist/desk/commands.js +101 -15
  52. package/dist/desk/paths.d.ts +6 -0
  53. package/dist/desk/paths.js +21 -1
  54. package/dist/desk/registry.d.ts +11 -0
  55. package/dist/desk/registry.js +53 -9
  56. package/dist/desk/types.d.ts +66 -1
  57. package/dist/dingtalk/config.js +10 -10
  58. package/dist/dingtalk/delivery.js +2 -0
  59. package/dist/dingtalk/inbound.js +2 -3
  60. package/dist/events/watcher.d.ts +1 -1
  61. package/dist/events/watcher.js +2 -2
  62. package/dist/main.js +15 -3
  63. package/dist/memory/boundary-work.d.ts +2 -1
  64. package/dist/memory/boundary-work.js +1 -1
  65. package/dist/memory/lifecycle.d.ts +2 -1
  66. package/dist/memory/lifecycle.js +2 -2
  67. package/dist/memory/reflect-job.d.ts +2 -1
  68. package/dist/memory/reflect-job.js +1 -1
  69. package/dist/memory/reflect.d.ts +2 -1
  70. package/dist/memory/reflect.js +2 -1
  71. package/dist/memory/scheduler.d.ts +2 -1
  72. package/dist/memory/scheduler.js +1 -1
  73. package/dist/memory/session-corpus.js +7 -1
  74. package/dist/memory/session-search.d.ts +2 -1
  75. package/dist/memory/session-search.js +1 -1
  76. package/dist/memory/sidecar-worker.d.ts +2 -1
  77. package/dist/memory/sidecar-worker.js +2 -4
  78. package/dist/models/credential-work.d.ts +7 -0
  79. package/dist/models/credential-work.js +36 -0
  80. package/dist/models/login-ui.js +4 -4
  81. package/dist/models/provider-login.js +7 -6
  82. package/dist/models/requests.d.ts +8 -0
  83. package/dist/models/requests.js +69 -0
  84. package/dist/models/runtime.d.ts +3 -1
  85. package/dist/models/runtime.js +9 -2
  86. package/dist/playbooks/agent-delegation.md +19 -45
  87. package/dist/playbooks/background-jobs.md +1 -1
  88. package/dist/playbooks/catalog.js +1 -1
  89. package/dist/playbooks/delegation-inline.md +25 -0
  90. package/dist/playbooks/delegation-recovery.md +28 -0
  91. package/dist/playbooks/event-scheduling.md +18 -37
  92. package/dist/playbooks/event-sensors.md +26 -0
  93. package/dist/playbooks/event-task-template.md +22 -0
  94. package/dist/playbooks/learning-and-skills.md +26 -0
  95. package/dist/playbooks/memory-operations.md +36 -0
  96. package/dist/playbooks/outbound-media.md +2 -2
  97. package/dist/playbooks/runtime-files.md +29 -0
  98. package/dist/playbooks/runtime-operations.md +25 -0
  99. package/dist/playbooks/runtime-orientation.md +18 -53
  100. package/dist/playbooks/task-lead.md +22 -68
  101. package/dist/playbooks/task-manage.md +38 -0
  102. package/dist/playbooks/task-recovery.md +24 -0
  103. package/dist/playbooks/task-verify.md +22 -0
  104. package/dist/runtime/bootstrap.d.ts +4 -0
  105. package/dist/runtime/bootstrap.js +82 -22
  106. package/dist/runtime/daemon-lock.js +3 -3
  107. package/dist/runtime/desk-runtime.d.ts +33 -6
  108. package/dist/runtime/desk-runtime.js +302 -47
  109. package/dist/runtime/ingress-commands.js +24 -4
  110. package/dist/runtime/shutdown.d.ts +3 -1
  111. package/dist/runtime/shutdown.js +1 -0
  112. package/dist/runtime/task-close.d.ts +1 -1
  113. package/dist/runtime/task-close.js +6 -3
  114. package/dist/runtime/task-control.d.ts +1 -3
  115. package/dist/runtime/task-control.js +15 -11
  116. package/dist/runtime/task-input.js +1 -1
  117. package/dist/runtime/task-lane-types.d.ts +12 -2
  118. package/dist/runtime/task-lane-types.js +9 -0
  119. package/dist/runtime/task-lane.d.ts +1 -0
  120. package/dist/runtime/task-lane.js +17 -14
  121. package/dist/runtime/task-step.d.ts +3 -3
  122. package/dist/runtime/task-step.js +23 -14
  123. package/dist/runtime/transports.js +6 -5
  124. package/dist/security/command-guard.js +23 -1
  125. package/dist/subagents/commands.js +14 -5
  126. package/dist/subagents/completion-wake.js +6 -0
  127. package/dist/subagents/dispatch.js +20 -18
  128. package/dist/subagents/external/dispatch.js +20 -14
  129. package/dist/subagents/external/run.js +10 -20
  130. package/dist/subagents/external/settlement.js +5 -1
  131. package/dist/subagents/internal/outcome.js +19 -12
  132. package/dist/subagents/internal/provider-retry.js +1 -3
  133. package/dist/subagents/internal/run.d.ts +1 -1
  134. package/dist/subagents/internal/run.js +27 -4
  135. package/dist/subagents/internal/state.d.ts +1 -3
  136. package/dist/subagents/internal/state.js +1 -2
  137. package/dist/subagents/internal/worker.js +17 -9
  138. package/dist/subagents/result.d.ts +5 -2
  139. package/dist/subagents/result.js +35 -6
  140. package/dist/subagents/run-record.d.ts +21 -0
  141. package/dist/subagents/run-record.js +5 -0
  142. package/dist/subagents/runs.d.ts +4 -7
  143. package/dist/subagents/runs.js +24 -35
  144. package/dist/subagents/task-envelope.js +5 -0
  145. package/dist/subagents/task-settlement.js +1 -0
  146. package/dist/subagents/types.d.ts +14 -4
  147. package/dist/subagents/workspace-lease.d.ts +37 -10
  148. package/dist/subagents/workspace-lease.js +121 -13
  149. package/dist/subagents/worktree.d.ts +47 -5
  150. package/dist/subagents/worktree.js +316 -30
  151. package/dist/tasks/brief.d.ts +5 -1
  152. package/dist/tasks/brief.js +19 -5
  153. package/dist/tasks/commands.d.ts +3 -1
  154. package/dist/tasks/commands.js +17 -6
  155. package/dist/tasks/control.d.ts +9 -0
  156. package/dist/tasks/loop-log.d.ts +10 -0
  157. package/dist/tasks/loop-log.js +1 -1
  158. package/dist/tasks/receipts.d.ts +7 -3
  159. package/dist/tasks/receipts.js +34 -5
  160. package/dist/tools/bash.d.ts +3 -0
  161. package/dist/tools/bash.js +27 -15
  162. package/dist/tools/contract/presentation.js +4 -1
  163. package/dist/tools/edit-diff.d.ts +11 -0
  164. package/dist/tools/edit-diff.js +148 -0
  165. package/dist/tools/edit-match.d.ts +18 -0
  166. package/dist/tools/edit-match.js +242 -0
  167. package/dist/tools/edit.d.ts +10 -2
  168. package/dist/tools/edit.js +91 -361
  169. package/dist/tools/event-manage.d.ts +1 -2
  170. package/dist/tools/event-manage.js +27 -38
  171. package/dist/tools/file-observations.d.ts +9 -0
  172. package/dist/tools/file-observations.js +50 -0
  173. package/dist/tools/glob-match.d.ts +3 -1
  174. package/dist/tools/glob-match.js +40 -17
  175. package/dist/tools/glob.d.ts +1 -0
  176. package/dist/tools/glob.js +39 -19
  177. package/dist/tools/grep-command.d.ts +13 -0
  178. package/dist/tools/grep-command.js +77 -0
  179. package/dist/tools/grep.js +96 -201
  180. package/dist/tools/index.d.ts +4 -1
  181. package/dist/tools/index.js +7 -4
  182. package/dist/tools/job.js +12 -11
  183. package/dist/tools/read.d.ts +2 -0
  184. package/dist/tools/read.js +10 -2
  185. package/dist/tools/registry.d.ts +16 -11
  186. package/dist/tools/registry.js +29 -11
  187. package/dist/tools/session-search.d.ts +2 -1
  188. package/dist/tools/session-search.js +14 -4
  189. package/dist/tools/skill.js +13 -12
  190. package/dist/tools/subagent-manage.js +10 -3
  191. package/dist/tools/subagent.d.ts +22 -2
  192. package/dist/tools/subagent.js +19 -18
  193. package/dist/tools/task-manage/control-tools.js +1 -1
  194. package/dist/tools/task-manage/factory.d.ts +2 -2
  195. package/dist/tools/task-manage/factory.js +39 -3
  196. package/dist/tools/task-manage/lifecycle.d.ts +2 -2
  197. package/dist/tools/task-manage/lifecycle.js +7 -4
  198. package/dist/tools/task-manage/shared.d.ts +1 -1
  199. package/dist/tools/task-manage/types.d.ts +1 -0
  200. package/dist/tools/write-content.d.ts +7 -1
  201. package/dist/tools/write-content.js +18 -6
  202. package/dist/tools/write.d.ts +3 -0
  203. package/dist/tools/write.js +6 -2
  204. package/dist/tui/cli.d.ts +5 -0
  205. package/dist/tui/cli.js +97 -31
  206. package/dist/tui/client.d.ts +5 -0
  207. package/dist/tui/client.js +63 -21
  208. package/dist/tui/frontend.d.ts +2 -0
  209. package/dist/tui/pitui-frontend.d.ts +4 -0
  210. package/dist/tui/pitui-frontend.js +27 -0
  211. package/dist/tui/render.d.ts +1 -0
  212. package/dist/tui/render.js +5 -0
  213. package/dist/tui/session.js +6 -0
  214. package/dist/web/client.d.ts +1 -0
  215. package/dist/web/client.js +11 -0
  216. package/dist/web/fetch.js +6 -3
  217. package/dist/webapi/auth.d.ts +0 -3
  218. package/dist/webapi/auth.js +3 -7
  219. package/dist/webapi/config.js +17 -14
  220. package/dist/webapi/key-command.js +41 -41
  221. package/dist/webapi/response-state.d.ts +7 -1
  222. package/dist/webapi/response-state.js +166 -3
  223. package/dist/webapi/routes/websocket.js +24 -1
  224. package/dist/webapi/server.d.ts +3 -1
  225. package/dist/webapi/server.js +32 -1
  226. package/dist/webapi/service.js +8 -0
  227. package/dist/webapi/transport.d.ts +2 -0
  228. package/dist/webapi/transport.js +11 -1
  229. package/examples/sub-agents/README.md +9 -7
  230. package/examples/sub-agents/agy-main.md +21 -0
  231. package/examples/sub-agents/claude-high.md +21 -0
  232. package/examples/sub-agents/claude-main.md +21 -0
  233. package/examples/sub-agents/codex-flash.md +21 -0
  234. package/examples/sub-agents/codex-high.md +21 -0
  235. package/examples/sub-agents/codex-main.md +21 -0
  236. package/examples/sub-agents/codex-review.md +20 -0
  237. package/examples/sub-agents/cursor-high.md +20 -0
  238. package/examples/sub-agents/cursor-main.md +20 -0
  239. package/examples/sub-agents/glm-flash.md +21 -0
  240. package/examples/sub-agents/glm-high.md +21 -0
  241. package/examples/sub-agents/pi-scout.md +20 -0
  242. package/package.json +8 -9
  243. package/dist/agent/session/request-tools.d.ts +0 -3
  244. package/dist/agent/session/request-tools.js +0 -20
  245. package/dist/models/api-keys.d.ts +0 -11
  246. package/dist/models/api-keys.js +0 -22
  247. package/dist/playbooks/memory-and-learning.md +0 -55
  248. package/examples/sub-agents/agents/agy-main.md +0 -23
  249. package/examples/sub-agents/agents/claude-high.md +0 -23
  250. package/examples/sub-agents/agents/claude-main.md +0 -23
  251. package/examples/sub-agents/agents/codex-flash.md +0 -23
  252. package/examples/sub-agents/agents/codex-high.md +0 -23
  253. package/examples/sub-agents/agents/codex-main.md +0 -23
  254. package/examples/sub-agents/agents/codex-review.md +0 -23
  255. package/examples/sub-agents/agents/cursor-high.md +0 -22
  256. package/examples/sub-agents/agents/cursor-main.md +0 -22
  257. package/examples/sub-agents/agents/glm-flash.md +0 -23
  258. package/examples/sub-agents/agents/glm-high.md +0 -23
@@ -13,7 +13,10 @@ import { describeToolCall } from "../../tools/contract/presentation.js";
13
13
  import { addUsage } from "../../usage/totals.js";
14
14
  import { extractToolResultText } from "../turn/progress-formatter.js";
15
15
  import { renderCompactionFailure } from "../turn/turn-error.js";
16
- import { extractCustomCommandResultText, isAssistantEventMessage, isAutoCompactionEndEvent, isAutoCompactionStartEvent, isAutoRetryStartEvent, isMessageEndEvent, isMessageStartEvent, isSubAgentToolDetails, isTextPart, isThinkingPart, isToolExecutionEndEvent, isToolExecutionStartEvent, isToolExecutionUpdateEvent, isTurnEndEvent, isUserEventMessage, } from "./event-guards.js";
16
+ import { extractCustomCommandResultText, isAssistantEventMessage, isAutoCompactionEndEvent, isAutoCompactionStartEvent, isAutoRetryStartEvent, isMessageEndEvent, isMessageStartEvent, isMessageUpdateEvent, isSubAgentToolDetails, isTextPart, isThinkingPart, isToolExecutionEndEvent, isToolExecutionStartEvent, isToolExecutionUpdateEvent, isTurnEndEvent, isUserEventMessage, } from "./event-guards.js";
17
+ function isDelegationToolName(name) {
18
+ return name === "subagent" || name === "subagent_inline";
19
+ }
17
20
  /**
18
21
  * A `write`/`edit` result whose resolved target landed inside either skill tree. The
19
22
  * `skill` tool is read-only (spec 045); authoring a workspace skill goes through the generic file
@@ -70,7 +73,7 @@ export async function handleSessionEvent(event, context) {
70
73
  return;
71
74
  }
72
75
  if (isToolExecutionUpdateEvent(event)) {
73
- if (event.toolName !== "subagent") {
76
+ if (!isDelegationToolName(event.toolName)) {
74
77
  return;
75
78
  }
76
79
  const partialText = truncate(extractToolResultText(event.partialResult), 200);
@@ -85,7 +88,7 @@ export async function handleSessionEvent(event, context) {
85
88
  const pending = pendingTools.get(event.toolCallId);
86
89
  pendingTools.delete(event.toolCallId);
87
90
  const durationMs = pending ? Date.now() - pending.startTime : 0;
88
- const subAgentDetails = event.toolName === "subagent" &&
91
+ const subAgentDetails = isDelegationToolName(event.toolName) &&
89
92
  isRecord(event.result) &&
90
93
  "details" in event.result &&
91
94
  isSubAgentToolDetails(event.result.details)
@@ -151,7 +154,7 @@ export async function handleSessionEvent(event, context) {
151
154
  ctx.emit({
152
155
  type: "tool.end",
153
156
  callId: event.toolCallId,
154
- ok: !event.isError && !subAgentDetails?.failed,
157
+ ok: !treatAsError && !rejected,
155
158
  output: truncate(resultStr, TOOL_EVENT_OUTPUT_CHARS),
156
159
  ...(failure ? { failure } : {}),
157
160
  });
@@ -159,6 +162,8 @@ export async function handleSessionEvent(event, context) {
159
162
  }
160
163
  if (isMessageStartEvent(event)) {
161
164
  if (isAssistantEventMessage(event.message)) {
165
+ runState.streamingTextBuffer = "";
166
+ runState.streamingTextFlushed = false;
162
167
  log.logResponseStart(logCtx);
163
168
  }
164
169
  else if (isUserEventMessage(event.message)) {
@@ -170,6 +175,28 @@ export async function handleSessionEvent(event, context) {
170
175
  }
171
176
  return;
172
177
  }
178
+ if (isMessageUpdateEvent(event)) {
179
+ const sub = event.assistantMessageEvent;
180
+ if (sub.type === "thinking_delta" && typeof sub.delta === "string" && sub.delta.length > 0) {
181
+ ctx.emit({ type: "reasoning.delta", delta: sub.delta });
182
+ }
183
+ else if (sub.type === "text_delta" && typeof sub.delta === "string" && sub.delta.length > 0) {
184
+ if (runState.streamingTextFlushed) {
185
+ ctx.emit({ type: "text.delta", delta: sub.delta });
186
+ }
187
+ else {
188
+ runState.streamingTextBuffer += sub.delta;
189
+ const trimmed = runState.streamingTextBuffer.trimStart();
190
+ if (trimmed.length > 0 && !"[SILENT]".startsWith(trimmed) && !trimmed.startsWith("[SILENT]")) {
191
+ runState.streamingTextFlushed = true;
192
+ const flushed = runState.streamingTextBuffer;
193
+ runState.streamingTextBuffer = "";
194
+ ctx.emit({ type: "text.delta", delta: flushed });
195
+ }
196
+ }
197
+ }
198
+ return;
199
+ }
173
200
  if (isMessageEndEvent(event)) {
174
201
  const commandResultText = extractCustomCommandResultText(event.message);
175
202
  if (commandResultText) {
@@ -6,7 +6,7 @@
6
6
  * turns; `ChannelRunner` drives turns through it.
7
7
  */
8
8
  import { Agent, type AgentTool } from "@earendil-works/pi-agent-core";
9
- import { AgentSession, type ModelRegistry, type SettingsManager as SDKSettingsManager, type SessionManager } from "@earendil-works/pi-coding-agent";
9
+ import { AgentSession, type ModelRegistry, type ModelRuntime, type SettingsManager as SDKSettingsManager, type SessionManager } from "@earendil-works/pi-coding-agent";
10
10
  import type { SendMedia } from "../../channel/transport.js";
11
11
  import type { TurnContext } from "../../channel/turn-context.js";
12
12
  import type { PipiclawSettingsManager } from "../../config/settings.js";
@@ -15,6 +15,7 @@ import type { Executor } from "../../executor.js";
15
15
  import type { FileStore } from "../../file-store.js";
16
16
  import type { DeskJobManager } from "../../jobs/manager.js";
17
17
  import type { MemoryLifecycle } from "../../memory/lifecycle.js";
18
+ import { type ModelRequests } from "../../models/requests.js";
18
19
  import type { LoadedSecurityConfig } from "../../security/config.js";
19
20
  import type { PipiclawSkillsResult } from "../../skills/types.js";
20
21
  import type { SubAgentRunManager } from "../../subagents/runs.js";
@@ -88,8 +89,9 @@ export declare class SessionHost {
88
89
  session: AgentSession;
89
90
  /** Settings manager owned by the currently bound AgentSession. */
90
91
  sessionSettingsManager: SDKSettingsManager;
91
- private modelRuntime;
92
+ modelRuntime: ModelRuntime;
92
93
  modelRegistry: ModelRegistry;
94
+ modelRequests: ModelRequests;
93
95
  /** Mutual exclusion between prompt submission and session-resource reloads. */
94
96
  private readonly sessionResourceGate;
95
97
  sessionReady: Promise<void>;
@@ -6,16 +6,17 @@
6
6
  * turns; `ChannelRunner` drives turns through it.
7
7
  */
8
8
  import { Agent } from "@earendil-works/pi-agent-core";
9
- import { streamSimple } from "@earendil-works/pi-ai/compat";
10
9
  import { AgentSession, AgentSessionRuntime, DefaultResourceLoader, } from "@earendil-works/pi-coding-agent";
11
10
  import { commitActiveSessionRef } from "../../channel/active-session-store.js";
12
11
  import { loadToolsConfigWithDiagnostics } from "../../config/tools.js";
13
12
  import * as log from "../../log.js";
14
13
  import { handleMemoryCommand } from "../../memory/commands.js";
15
14
  import { hasMemoryBootstrapBlock } from "../../memory/render.js";
16
- import { getApiKeyForModel } from "../../models/api-keys.js";
15
+ import { trackModelWork } from "../../models/credential-work.js";
17
16
  import { findExactModelReferenceMatch, hasKnownModelPricing } from "../../models/reference.js";
18
- import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../../models/runtime.js";
17
+ import { createModelRequests } from "../../models/requests.js";
18
+ import { createModelRuntime, refreshModelRegistry, resolveInitialModel, wrapModelRegistry, } from "../../models/runtime.js";
19
+ import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../../playbooks/catalog.js";
19
20
  import { errorMessage } from "../../shared/text-utils.js";
20
21
  import { isRecord } from "../../shared/type-guards.js";
21
22
  import { withTimeout } from "../../shared/with-timeout.js";
@@ -24,16 +25,16 @@ import { getSkillRoots } from "../../skills/roots.js";
24
25
  import { discoverSubAgents } from "../../subagents/discovery.js";
25
26
  import { withExecutionTrace } from "../../tools/contract/execution-trace.js";
26
27
  import { createPipiclawTools } from "../../tools/index.js";
28
+ import { TOOL_NAMES } from "../../tools/registry.js";
27
29
  import { buildPipiclawSystemPrompt } from "../prompt/builder.js";
28
30
  import { createPromptBoundaryExtension } from "../prompt/extension.js";
29
31
  import { measureToolSchemas, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning } from "../prompt/manifest.js";
30
- import { loadPlaybooks, loadWorkspacePromptResources } from "../prompt/resources.js";
32
+ import { loadWorkspacePromptResources } from "../prompt/resources.js";
31
33
  import { createCommandExtension } from "./command-extension.js";
32
34
  import { SessionCompaction } from "./compaction.js";
33
35
  import { RequestContextInput } from "./context-input.js";
34
36
  import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./event-guards.js";
35
37
  import { SessionExecutionTrace } from "./execution-trace.js";
36
- import { requestTools } from "./request-tools.js";
37
38
  import { asSdkSettingsManager, DEFAULT_MAIN_THINKING_LEVEL, initializeThinkingLevelCompat, setSessionBaseToolsOverride, } from "./session-adapter.js";
38
39
  import { handleSessionEvent } from "./session-events.js";
39
40
  import { SessionResourceGate } from "./session-resource-gate.js";
@@ -193,6 +194,7 @@ export class SessionHost {
193
194
  modelsConfigPath: this.modelsConfigPath,
194
195
  });
195
196
  this.modelRegistry = wrapModelRegistry(this.modelRuntime);
197
+ this.modelRequests = createModelRequests(this.modelRuntime);
196
198
  // Resolve model: prefer saved global default, fall back to first available model.
197
199
  this.models.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
198
200
  log.logInfo(`Using model: ${this.models.activeModel.provider}/${this.models.activeModel.id} (${this.models.activeModel.name})`);
@@ -259,7 +261,7 @@ export class SessionHost {
259
261
  return;
260
262
  this.rebuildSessionTools();
261
263
  try {
262
- await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
264
+ await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => trackModelWork(this.modelRuntime, () => this.session.reload()));
263
265
  }
264
266
  catch (error) {
265
267
  log.logWarn("agent.session.reload_unsettled", "Session reload did not settle", {
@@ -281,7 +283,7 @@ export class SessionHost {
281
283
  return { cancelled: result.cancelled };
282
284
  },
283
285
  navigateTree: async (targetId, options) => {
284
- const result = await this.session.navigateTree(targetId, options);
286
+ const result = await trackModelWork(this.modelRuntime, () => this.session.navigateTree(targetId, options));
285
287
  this.syncMemoryBootstrapPendingFromSession();
286
288
  return { cancelled: result.cancelled };
287
289
  },
@@ -305,7 +307,7 @@ export class SessionHost {
305
307
  // snapshot — stale availability is a far smaller problem than a reload
306
308
  // (and, through it, a `/new` turn) that never returns.
307
309
  try {
308
- await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => this.modelRegistry.refresh());
310
+ await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => refreshModelRegistry(this.modelRuntime));
309
311
  }
310
312
  catch (error) {
311
313
  log.logWarn("agent.models.refresh_unsettled", "Model registry refresh did not settle; using the previous snapshot", { channelId: this.channelId, reason: errorMessage(error) });
@@ -331,7 +333,7 @@ export class SessionHost {
331
333
  })),
332
334
  soul: resources.soul,
333
335
  agents: resources.agents,
334
- playbooks: loadPlaybooks(toolNames),
336
+ playbooks: selectRuntimePlaybooks(loadRuntimePlaybookCatalog(TOOL_NAMES), toolNames),
335
337
  subAgents: this.subAgentDiscovery.agents.map((agent) => ({
336
338
  name: agent.name,
337
339
  description: agent.description,
@@ -375,7 +377,7 @@ export class SessionHost {
375
377
  createCommandExtension({
376
378
  getCurrentModel: () => this.session.model ?? this.models.activeModel,
377
379
  getAvailableModels: async () => {
378
- await this.modelRegistry.refresh();
380
+ await refreshModelRegistry(this.modelRuntime);
379
381
  return this.modelRegistry.getAvailable();
380
382
  },
381
383
  getSessionStats: () => this.session.getSessionStats(),
@@ -463,6 +465,7 @@ export class SessionHost {
463
465
  throw new Error("Session generation retired");
464
466
  const tools = this.buildRuntimeTools();
465
467
  const agent = new Agent({
468
+ sessionId: sessionManager.getSessionId(),
466
469
  initialState: {
467
470
  systemPrompt: "",
468
471
  model: this.models.activeModel,
@@ -471,10 +474,9 @@ export class SessionHost {
471
474
  messages: sessionManager.buildSessionContext().messages,
472
475
  },
473
476
  convertToLlm: (messages) => this.contextInput.convert(messages),
474
- getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.models.activeModel),
475
477
  streamFn: (model, context, options) => {
476
478
  this.trace.startRequest();
477
- return streamSimple(model, context, options);
479
+ return this.modelRequests.stream(model, context, options);
478
480
  },
479
481
  });
480
482
  this.initializeThinkingLevel(agent, this.models.activeModel, sessionManager);
@@ -520,14 +522,15 @@ export class SessionHost {
520
522
  const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
521
523
  reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics], this.channelId);
522
524
  this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
523
- const tools = createPipiclawTools({
525
+ const active = createPipiclawTools({
526
+ requestScoped: this.deps.profile.kind === "request",
524
527
  jobManager: this.jobManager,
525
528
  runManager: this.runManager,
526
529
  executor: this.executor,
527
530
  fileStore: this.fileStore,
528
531
  getCurrentModel: () => this.models.activeModel,
529
532
  getAvailableModels: () => this.modelRegistry.getAvailable(),
530
- resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
533
+ modelRequests: this.modelRequests,
531
534
  workspaceDir: this.workspaceDir,
532
535
  appHomeDir: this.appHomeDir,
533
536
  cwd: this.cwd,
@@ -545,7 +548,6 @@ export class SessionHost {
545
548
  ...(this.deps.profile.kind === "task" ? { taskSession: this.deps.profile.session } : {}),
546
549
  ...(this.deps.profile.kind === "chat" ? { taskControl: this.deps.getTaskControl?.() } : {}),
547
550
  });
548
- const active = this.deps.profile.kind === "request" ? requestTools(tools) : tools;
549
551
  this.currentTools = active;
550
552
  // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
551
553
  // Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
@@ -31,6 +31,9 @@ export function renderStatus(options) {
31
31
  else if (runner && snapshot) {
32
32
  try {
33
33
  let modelLine = `- 模型:\`${snapshot.model}\`(思考档位 \`${snapshot.thinkingLevel}\`)`;
34
+ if (snapshot.modelConfigured === false) {
35
+ modelLine += " · ⚠️ 未检测到凭据(在终端执行 `pipiclaw auth login` 或配置 `models.json`)";
36
+ }
34
37
  if (snapshot.fallback) {
35
38
  const until = new Date(snapshot.fallback.cooldownUntilMs);
36
39
  const hh = String(until.getHours()).padStart(2, "0");
@@ -3,11 +3,8 @@ export declare const TASK_AGENDA_MAX_UNITS = 600;
3
3
  /**
4
4
  * Builds the `<task_agenda>` block injected into each main-agent turn (spec 020 §2).
5
5
  *
6
- * Unlike memory recall — which is relevance-gated because candidate memory can be large —
7
- * the agenda is deterministic and always-on: the candidate set is a handful of task
8
- * frontmatters, and the in-flight agenda is universally relevant to an agent that drives
9
- * work across turns. The block is bounded (maxTasks / maxChars) and framed as background
10
- * reference, not instruction, so it can never turn an unrelated user turn into task work.
6
+ * The agenda lets chat match a reply to a pending question and identify other work by id.
7
+ * Task controls provide the authoritative state and complete progress.
11
8
  */
12
9
  export interface TaskDigestOptions {
13
10
  /** The desk directory; tasks live in `<deskDir>/tasks/`. */
@@ -1,7 +1,6 @@
1
1
  import { join } from "node:path";
2
2
  import { countPromptUnits } from "../../shared/prompt-units.js";
3
3
  import { truncate } from "../../shared/text-utils.js";
4
- import { taskCostSummary } from "../../tasks/budget.js";
5
4
  import { readActiveTasks } from "../../tasks/contract.js";
6
5
  /** Automatic-context share for the in-flight task agenda (spec 026 §5.3). */
7
6
  export const TASK_AGENDA_MAX_UNITS = 600;
@@ -24,26 +23,18 @@ function describeState(fields) {
24
23
  }
25
24
  }
26
25
  }
26
+ function deliveryRank(entry, channelId) {
27
+ if (channelId && entry.fields.channel !== channelId)
28
+ return 2;
29
+ return entry.fields.state === "waiting" && entry.fields.waiting?.kind === "user" ? 0 : 1;
30
+ }
27
31
  function renderLine(entry, channelId) {
28
- const parts = [
29
- `${entry.id} — ${entry.title}`,
30
- entry.readable ? describeState(entry.fields) : "⚠ unreadable frontmatter",
31
- ];
32
- if (channelId && entry.fields.channel !== channelId) {
33
- parts.push(entry.fields.channel ? `reports to ${entry.fields.channel}` : "no delivery channel (suspended)");
34
- }
35
- // The agenda shows Work Items progress and the current item, not the full list — the complete
36
- // section is read from the task file by the loop itself, staying well inside the 600-unit
37
- // budget this block competes for (spec 025/026).
38
- if (entry.items) {
39
- parts.push(`items ${entry.items.done}/${entry.items.total} · @${entry.items.current?.id ?? "-"}`);
32
+ if (!entry.readable)
33
+ return `- ${entry.id} · unreadable frontmatter`;
34
+ if (deliveryRank(entry, channelId) === 2) {
35
+ return `- ${entry.id} · ${entry.fields.channel ? `reports to ${entry.fields.channel}` : "delivery suspended"}`;
40
36
  }
41
- const usage = entry.fields.usage;
42
- if (usage) {
43
- const cost = usage.usd > 0 || usage.unknownCostCount ? ` · ${taskCostSummary(usage)}` : "";
44
- parts.push(`${usage.steps} 步${cost}`);
45
- }
46
- return `- ${parts.join(" · ")}`;
37
+ return `- ${entry.id} — ${truncate(entry.title, 80)} · ${describeState(entry.fields)}`;
47
38
  }
48
39
  /**
49
40
  * Render the in-flight task agenda, or `""` when there are no live tasks to show.
@@ -57,37 +48,26 @@ export async function buildTaskDigest(options) {
57
48
  const agenda = all.filter((entry) => !entry.fields.outcome);
58
49
  if (agenda.length === 0)
59
50
  return "";
60
- const shown = agenda.slice(0, Math.max(1, options.maxTasks));
61
- const omitted = agenda.length - shown.length;
62
- const header = [
63
- "<task_agenda>",
64
- "Your desk's in-flight tasks (background reference, not a new instruction).",
65
- "Inspect current state before reporting progress. Relay user instructions and answers",
66
- "through task controls; use them to pause, resume, or cancel when requested.",
67
- "The task lane advances the work: do not take it over or advance it because chat is idle.",
68
- "Full detail lives in the matching tasks/<id>.md file.",
69
- "",
70
- ];
71
- const lines = shown.map((entry) => renderLine(entry, options.channelId));
72
- if (omitted > 0)
73
- lines.push(`- (+${omitted} more)`);
74
- const footer = ["</task_agenda>"];
51
+ agenda.sort((a, b) => deliveryRank(a, options.channelId) - deliveryRank(b, options.channelId));
52
+ const header = "<task_agenda>\nBackground reference. Use task_list for current state. Relay matching answers via task_message when available. The task lane advances the work.";
53
+ const render = (kept) => {
54
+ const omitted = agenda.length - kept.length;
55
+ const tail = omitted > 0 ? [`- (+${omitted} more)`] : [];
56
+ return [header, ...kept, ...tail, "</task_agenda>"].join("\n");
57
+ };
75
58
  const maxUnits = options.maxUnits ?? Number.POSITIVE_INFINITY;
76
59
  const fits = (text) => text.length <= options.maxChars && countPromptUnits(text) <= maxUnits;
77
- let rendered = [...header, ...lines, ...footer].join("\n");
78
- if (fits(rendered))
79
- return rendered;
80
- // Over one of the budgets: drop whole lines from the end until it fits, keeping
81
- // actionable-first order. Chars and units are checked together (spec 026 §10.7).
82
60
  const kept = [];
83
- for (const line of lines) {
84
- const candidate = [...header, ...kept, line, `- (+${agenda.length - kept.length - 1} more)`, ...footer].join("\n");
85
- if (!fits(candidate) && kept.length > 0)
61
+ let rendered = render(kept);
62
+ if (!fits(rendered))
63
+ return "";
64
+ for (const entry of agenda.slice(0, options.maxTasks)) {
65
+ const line = renderLine(entry, options.channelId);
66
+ const candidate = render([...kept, line]);
67
+ if (!fits(candidate))
86
68
  break;
87
69
  kept.push(line);
70
+ rendered = candidate;
88
71
  }
89
- const droppedCount = agenda.length - kept.length;
90
- const tail = droppedCount > 0 ? [`- (+${droppedCount} more)`] : [];
91
- rendered = [...header, ...kept, ...tail, ...footer].join("\n");
92
72
  return rendered;
93
73
  }
@@ -23,12 +23,10 @@ export function renderDeskTurnContext(conversation,
23
23
  channelLabel, workspaceDir) {
24
24
  return [
25
25
  "<runtime_turn_context>",
26
- `Workspace: ${workspaceDir} — shared identity, rules, skills and roles. You are the same Pipiclaw assistant across desks.`,
27
- conversation.cwd === conversation.deskDir
28
- ? `Desk: ${conversation.desk} — directory ${conversation.deskDir} (your working directory).`
29
- : `Desk: ${conversation.desk} — directory ${conversation.deskDir}. Your working directory is ${conversation.cwd}.`,
30
- `This conversation: ${channelLabel ? `${channelLabel} ` : ""}(channel ${conversation.channelId}).`,
31
- "The desk's `MEMORY.md` index, `memory/`, `journal/`, `tasks/` and `events/` live in the desk directory. Prefer the context supplied with this turn and the desk-bound tools; read those files directly only when you need detail they did not provide.",
26
+ `Workspace: ${workspaceDir}`,
27
+ `Desk: ${conversation.desk} (${conversation.deskDir})`,
28
+ `Cwd: ${conversation.cwd}`,
29
+ `Channel: ${conversation.channelId}${channelLabel ? ` (${channelLabel})` : ""}`,
32
30
  "</runtime_turn_context>",
33
31
  ].join("\n");
34
32
  }
@@ -9,7 +9,7 @@
9
9
  * Only stable features are matched — HTTP status codes and the phrases providers have used for
10
10
  * years. Anything unrecognised is `other`, which still carries a next step.
11
11
  */
12
- export type TurnErrorKind = "auth" | "rate_limit" | "context_overflow" | "network" | "other";
12
+ export type TurnErrorKind = "missing_credentials" | "auth" | "rate_limit" | "context_overflow" | "network" | "other";
13
13
  export declare function classifyTurnError(message: string): TurnErrorKind;
14
14
  /** What the user is told for each class: a reason (absent for `other`) and what to do next. */
15
15
  export declare function describeTurnError(kind: TurnErrorKind): {
@@ -1,4 +1,8 @@
1
1
  const PATTERNS = [
2
+ [
3
+ "missing_credentials",
4
+ /\bno api[ _-]?key found\b|missing[ _-]?api[ _-]?key|no credentials found for provider|provider is not configured:|尚未配置.*模型凭据/i,
5
+ ],
2
6
  [
3
7
  "auth",
4
8
  /\b40[13]\b|unauthori[sz]ed|forbidden|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|authentication[ _-]?(?:error|failed)|(?:token|credential)s? (?:has |have )?expired/i,
@@ -26,6 +30,11 @@ export function classifyTurnError(message) {
26
30
  /** What the user is told for each class: a reason (absent for `other`) and what to do next. */
27
31
  export function describeTurnError(kind) {
28
32
  switch (kind) {
33
+ case "missing_credentials":
34
+ return {
35
+ reason: "尚未配置可用的模型凭据。",
36
+ nextStep: "请在终端执行 `pipiclaw auth login` 登录,或设置供应商环境变量(如 `ANTHROPIC_API_KEY`),或在 `models.json` 中配置模型网关后发送 `/reload`。",
37
+ };
29
38
  case "auth":
30
39
  return {
31
40
  reason: "模型凭据无效或已过期。",
@@ -2,6 +2,7 @@ import type { InboundImage } from "../../channel/channel-event.js";
2
2
  import type { TurnInfo } from "../../channel/transport.js";
3
3
  import type { DeskConversation } from "../../desk/types.js";
4
4
  import type { FallbackRunDeps } from "../../models/fallback.js";
5
+ import type { TaskBrief } from "../../tasks/brief.js";
5
6
  import type { ModelSelection } from "../session/model-selection.js";
6
7
  import type { SessionHost } from "../session/session-host.js";
7
8
  import { type RunnerProfile, type RunState, type TaskSteerScope } from "../types.js";
@@ -19,6 +20,11 @@ export interface TurnProgress {
19
20
  bootstrapPrepared: boolean;
20
21
  images: PreparedInboundImages;
21
22
  }
23
+ interface PreparedTurnInput {
24
+ clippedInput: string;
25
+ userMessage: string;
26
+ preserveRawInput: boolean;
27
+ }
22
28
  export declare function createTurnProgress(): TurnProgress;
23
29
  export interface TurnPipelineDeps {
24
30
  profile: RunnerProfile;
@@ -46,16 +52,14 @@ export declare class TurnPipeline {
46
52
  private get runState();
47
53
  private get session();
48
54
  /** Oversized input is spilled to disk and clipped; the user is told. Slash commands pass through raw. */
49
- prepareUserInput(turn: TurnInfo, ctx: TurnOutput): Promise<{
50
- clippedInput: string;
51
- userMessage: string;
52
- preserveRawInput: boolean;
53
- }>;
55
+ prepareUserInput(turn: TurnInfo, ctx: TurnOutput): Promise<PreparedTurnInput>;
54
56
  /**
55
57
  * The turn-dynamic context: the channel capsule (returned) plus, recorded on `turn`, the task
56
58
  * digest and the first-turn memory bootstrap. A raw-passthrough input (a slash command) gets none.
57
59
  */
58
60
  gatherTurnContext(preserveRawInput: boolean, turn: TurnProgress): Promise<string>;
61
+ private prepareMemoryBootstrap;
62
+ preparePrompt(input: PreparedTurnInput, turn: TurnProgress, channelCapsule: string, taskContract?: TaskBrief["contract"]): Promise<import("../prompt/manifest.js").PromptTurnContextStats>;
59
63
  /** Inbound images for the current model, with a notice to the user for each one that was left out. */
60
64
  prepareTurnImages(turn: TurnInfo, ctx: TurnOutput): Promise<PreparedInboundImages>;
61
65
  /** The seams `runPromptWithFallback` drives: submit the prompt, observe/reset the error, switch model. */
@@ -71,3 +75,4 @@ export declare class TurnPipeline {
71
75
  private acceptsScope;
72
76
  maybeRunPreventiveCompactionForIncomingText(incomingText: string, imageCount?: number): Promise<void>;
73
77
  }
78
+ export {};
@@ -8,6 +8,7 @@ import { clipUserInput } from "./progress-formatter.js";
8
8
  import { buildFirstTurnMemoryBootstrap, buildTaskDigestForTurn, renderDeskTurnContext } from "./turn-context.js";
9
9
  import { renderFallbackSwitch } from "./turn-error.js";
10
10
  import { formatUserMessage, persistOversizedInput, prepareInboundImages, shouldPreserveRawInput, } from "./turn-input.js";
11
+ import { assembleTurnPrompt } from "./turn-prompt.js";
11
12
  export function createTurnProgress() {
12
13
  return {
13
14
  promptSubmitted: false,
@@ -78,13 +79,7 @@ export class TurnPipeline {
78
79
  const taskDigestPromise = (this.host.tasksEnabled && this.deps.profile.kind !== "task"
79
80
  ? buildTaskDigestForTurn(this.deskDir, this.channelId)
80
81
  : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
81
- // Spec 050, D1: the memory index is injected in full on the first turn of a session
82
- // (and the first turn after compaction — see `subscribeToSessionEvents`), never per
83
- // turn. Mid-session, the model uses `memory_search` to look things up.
84
- if (this.host.firstTurnMemoryBootstrapPending) {
85
- turn.durableMemoryBootstrapText = await buildFirstTurnMemoryBootstrap(this.deskDir, this.workspaceDir);
86
- turn.bootstrapPrepared = true;
87
- }
82
+ await this.prepareMemoryBootstrap(turn);
88
83
  const taskDigestResult = await taskDigestPromise;
89
84
  if (taskDigestResult.error !== undefined) {
90
85
  throw taskDigestResult.error;
@@ -92,6 +87,40 @@ export class TurnPipeline {
92
87
  turn.taskDigestText = taskDigestResult.text ?? "";
93
88
  return channelCapsuleText;
94
89
  }
90
+ async prepareMemoryBootstrap(turn) {
91
+ if (turn.bootstrapPrepared || !this.host.firstTurnMemoryBootstrapPending)
92
+ return false;
93
+ turn.durableMemoryBootstrapText = await buildFirstTurnMemoryBootstrap(this.deskDir, this.workspaceDir);
94
+ turn.bootstrapPrepared = true;
95
+ return Boolean(turn.durableMemoryBootstrapText);
96
+ }
97
+ async preparePrompt(input, turn, channelCapsule, taskContract) {
98
+ let restoredContract;
99
+ // Check the final projection after compaction. Rebudget when we attach missing context;
100
+ // each source can be added at most once. Keep the task inputs and their receipts intact.
101
+ while (true) {
102
+ const assembled = assembleTurnPrompt({
103
+ ...input,
104
+ channelCapsule,
105
+ durableMemoryBootstrap: turn.durableMemoryBootstrapText,
106
+ taskDigest: turn.taskDigestText,
107
+ taskContract: restoredContract,
108
+ });
109
+ turn.promptText = assembled.text;
110
+ await this.maybeRunPreventiveCompactionForIncomingText(turn.promptText, turn.images.images.length);
111
+ if (input.preserveRawInput)
112
+ return assembled.stats;
113
+ const addedMemory = await this.prepareMemoryBootstrap(turn);
114
+ if (!restoredContract &&
115
+ taskContract &&
116
+ !this.host.contextIncludes((text) => text.includes(taskContract.tag))) {
117
+ restoredContract = clipUserInput(taskContract.text, MAX_USER_MESSAGE_CHARS, taskContract.path);
118
+ continue;
119
+ }
120
+ if (!addedMemory)
121
+ return assembled.stats;
122
+ }
123
+ }
95
124
  /** Inbound images for the current model, with a notice to the user for each one that was left out. */
96
125
  async prepareTurnImages(turn, ctx) {
97
126
  const prepared = await prepareInboundImages(turn.images, this.session.model ?? this.models.activeModel);
@@ -14,6 +14,8 @@ export interface TurnPromptParts {
14
14
  /** `<memory_bootstrap>`: workspace memory + desk memory index + journal, first turn only (spec 050, D1). */
15
15
  durableMemoryBootstrap: string;
16
16
  taskDigest: string;
17
+ /** Restored contract for a delta brief when the canonical projection dropped its original. */
18
+ taskContract?: string;
17
19
  }
18
20
  export interface AssembledTurnPrompt {
19
21
  text: string;
@@ -32,7 +32,8 @@ export function assembleTurnPrompt(parts) {
32
32
  parts.durableMemoryBootstrap,
33
33
  parts.taskDigest,
34
34
  parts.channelCapsule,
35
+ parts.taskContract,
35
36
  `<user_message>\n${parts.userMessage}\n</user_message>`,
36
37
  ];
37
- return { text: blocks.filter((block) => block !== "").join("\n\n"), stats };
38
+ return { text: blocks.filter(Boolean).join("\n\n"), stats };
38
39
  }
@@ -16,7 +16,10 @@ const SYNTHETIC_TOOL_RESULT_HEADER = "Error: Pipiclaw restarted before a durable
16
16
  "do not repeat the operation blindly.";
17
17
  const SYNTHETIC_ABORTED_ASSISTANT_TEXT = "Error: Pipiclaw restarted before a response was generated. Re-send the request if it is still needed.";
18
18
  function toolGuidance(toolName) {
19
- if (toolName === "subagent" || toolName === "subagent_list" || toolName === "subagent_run") {
19
+ if (toolName === "subagent" ||
20
+ toolName === "subagent_inline" ||
21
+ toolName === "subagent_list" ||
22
+ toolName === "subagent_run") {
20
23
  return "先用 `subagent_list` / `subagent_run op=show` 查询这次委派是否已经作为一个 durable run 存在。";
21
24
  }
22
25
  if (toolName === "job" || toolName === "bash") {
@@ -12,11 +12,14 @@ import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
12
12
  import type { LoadedSecurityConfig } from "../security/config.js";
13
13
  import type { SubAgentRunManager } from "../subagents/runs.js";
14
14
  import type { SubAgentDiscoveryResult } from "../subagents/types.js";
15
+ import type { TaskBrief } from "../tasks/brief.js";
15
16
  import type { TaskControl, TaskSessionContext } from "../tasks/control.js";
16
17
  import { type UsageTotals } from "../usage/totals.js";
17
18
  import type { TurnOutput } from "./turn/turn-output.js";
18
19
  export interface RunnerStatusSnapshot {
19
20
  model: string;
21
+ /** False when the active model currently has no configured credentials. */
22
+ modelConfigured?: boolean;
20
23
  contextTokens?: number;
21
24
  contextWindow: number;
22
25
  thinkingLevel: string;
@@ -57,7 +60,7 @@ export interface AgentRunner {
57
60
  /** The (desk, channel) pairing this runner serves; fixed for the runner's lifetime. */
58
61
  readonly conversation: DeskConversation;
59
62
  /** Run one turn for `turn`, writing its progress and answer to `ctx`. */
60
- run(turn: TurnInfo, ctx: ChannelContext, store: ChannelStore): Promise<{
63
+ run(turn: TurnInfo, ctx: ChannelContext, store: ChannelStore, taskContract?: TaskBrief["contract"]): Promise<{
61
64
  stopReason: string;
62
65
  errorMessage?: string;
63
66
  usage?: UsageTotals;
@@ -88,7 +91,7 @@ export interface AgentRunner {
88
91
  /** `undefined` while the SDK session is still being built. */
89
92
  getStatusSnapshot(): RunnerStatusSnapshot | undefined;
90
93
  /** `/context`: prompt/tool-schema accounting for the live session (spec 025 §9). */
91
- renderContextReport(args?: string): string;
94
+ renderContextReport(args?: string): Promise<string>;
92
95
  /** `/subagents list`'s role-directory health tail (spec 040, D6): whatever this runner has
93
96
  * already discovered, without forcing a rescan. */
94
97
  getSubAgentDiscoverySnapshot(): SubAgentDiscoveryResult;
@@ -194,6 +197,9 @@ export interface RunState {
194
197
  toolsUsed: string[];
195
198
  /** The text of the latest assistant message that had any, tool-calling messages included. */
196
199
  lastAssistantText: string;
200
+ /** Buffered leading text of the current assistant message until we know it does not start with `[SILENT]`. */
201
+ streamingTextBuffer: string;
202
+ streamingTextFlushed: boolean;
197
203
  }
198
204
  export declare function createEmptyRunState(): RunState;
199
205
  export interface AssistantUsage {
@@ -258,6 +264,13 @@ export type SessionEvent = {
258
264
  } | {
259
265
  type: "message_start";
260
266
  message: unknown;
267
+ } | {
268
+ type: "message_update";
269
+ message: unknown;
270
+ assistantMessageEvent: {
271
+ type: string;
272
+ delta?: string;
273
+ };
261
274
  } | {
262
275
  type: "message_end";
263
276
  message: unknown;
@@ -296,6 +309,9 @@ export type ToolExecutionEndEvent = Extract<SessionEvent, {
296
309
  export type MessageStartEvent = Extract<SessionEvent, {
297
310
  type: "message_start";
298
311
  }>;
312
+ export type MessageUpdateEvent = Extract<SessionEvent, {
313
+ type: "message_update";
314
+ }>;
299
315
  export type MessageEndEvent = Extract<SessionEvent, {
300
316
  type: "message_end";
301
317
  }>;
@@ -335,6 +351,8 @@ export type RunnerProfile = {
335
351
  };
336
352
  export interface RunnerFactoryPaths {
337
353
  fileStore?: FileStore;
354
+ /** Shared host executor. The runtime owns it so one process does not grow a second, unobserved one. */
355
+ executor?: Executor;
338
356
  profile?: RunnerProfile;
339
357
  /** Chat only: resolves the task lane's control port (the lane is built after the runners' factory). */
340
358
  getTaskControl?: () => TaskControl | undefined;