@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4-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 (291) hide show
  1. package/dist/agent/builtin-commands.d.ts +19 -0
  2. package/dist/agent/builtin-commands.js +80 -0
  3. package/dist/agent/channel-runner.d.ts +20 -208
  4. package/dist/agent/channel-runner.js +148 -1245
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/resources.d.ts +3 -0
  8. package/dist/agent/prompt/resources.js +7 -1
  9. package/dist/agent/runner-factory.d.ts +1 -43
  10. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  11. package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
  12. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  13. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  14. package/dist/agent/session/model-selection.d.ts +47 -0
  15. package/dist/agent/session/model-selection.js +99 -0
  16. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  17. package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
  18. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  19. package/dist/agent/{session-events.js → session/session-events.js} +10 -10
  20. package/dist/agent/session/session-host.d.ts +200 -0
  21. package/dist/agent/session/session-host.js +621 -0
  22. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
  23. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  24. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  25. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  26. package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
  27. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  28. package/dist/agent/turn/turn-context.d.ts +14 -0
  29. package/dist/agent/turn/turn-context.js +64 -0
  30. package/dist/agent/turn/turn-finish.d.ts +50 -0
  31. package/dist/agent/turn/turn-finish.js +188 -0
  32. package/dist/agent/turn/turn-input.d.ts +43 -0
  33. package/dist/agent/turn/turn-input.js +79 -0
  34. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  35. package/dist/agent/turn/turn-pipeline.js +257 -0
  36. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  37. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  38. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  39. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  40. package/dist/agent/types.d.ts +43 -2
  41. package/dist/agent/types.js +1 -1
  42. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  43. package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
  44. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
  45. package/dist/{runtime/app-home.js → app/home.js} +4 -75
  46. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  47. package/dist/{app-services.js → app/services.js} +10 -10
  48. package/dist/channel/channel-context.d.ts +12 -2
  49. package/dist/channel/channel-context.js +29 -2
  50. package/dist/channel/channel-event.d.ts +10 -2
  51. package/dist/channel/channel-event.js +1 -1
  52. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  53. package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
  54. package/dist/channel/store.js +4 -0
  55. package/dist/commands/catalog.d.ts +3 -3
  56. package/dist/commands/catalog.js +3 -3
  57. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  58. package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
  59. package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
  60. package/dist/{settings.js → config/settings.js} +7 -10
  61. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  62. package/dist/{tools/config.js → config/tools.js} +5 -2
  63. package/dist/dingtalk/access-token.d.ts +12 -0
  64. package/dist/dingtalk/access-token.js +51 -0
  65. package/dist/dingtalk/api.d.ts +19 -0
  66. package/dist/dingtalk/api.js +67 -0
  67. package/dist/dingtalk/bot.d.ts +97 -0
  68. package/dist/dingtalk/bot.js +389 -0
  69. package/dist/dingtalk/cards.d.ts +56 -0
  70. package/dist/dingtalk/cards.js +318 -0
  71. package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
  72. package/dist/dingtalk/config.d.ts +19 -0
  73. package/dist/dingtalk/config.js +95 -0
  74. package/dist/dingtalk/connection.d.ts +57 -0
  75. package/dist/dingtalk/connection.js +356 -0
  76. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  77. package/dist/dingtalk/conversation-meta.js +77 -0
  78. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  79. package/dist/dingtalk/handler.d.ts +90 -0
  80. package/dist/dingtalk/handler.js +1 -0
  81. package/dist/dingtalk/inbound.d.ts +66 -0
  82. package/dist/dingtalk/inbound.js +137 -0
  83. package/dist/dingtalk/media.d.ts +66 -0
  84. package/dist/dingtalk/media.js +214 -0
  85. package/dist/events/{event-commands.js → commands.js} +6 -2
  86. package/dist/events/parse.d.ts +14 -0
  87. package/dist/events/parse.js +114 -0
  88. package/dist/events/types.d.ts +93 -0
  89. package/dist/events/types.js +1 -0
  90. package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
  91. package/dist/events/watcher.d.ts +67 -0
  92. package/dist/events/{events.js → watcher.js} +6 -109
  93. package/dist/index.d.ts +6 -4
  94. package/dist/index.js +2 -2
  95. package/dist/jobs/launch.d.ts +42 -0
  96. package/dist/jobs/launch.js +118 -0
  97. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  98. package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
  99. package/dist/jobs/record.d.ts +55 -0
  100. package/dist/jobs/record.js +36 -0
  101. package/dist/main.js +2 -2
  102. package/dist/memory/maintenance-gates.d.ts +2 -2
  103. package/dist/memory/maintenance-tuning.d.ts +15 -0
  104. package/dist/memory/maintenance-tuning.js +3 -0
  105. package/dist/memory/reflect-job.d.ts +2 -2
  106. package/dist/memory/reflect-job.js +4 -2
  107. package/dist/memory/scheduler.d.ts +3 -3
  108. package/dist/memory/scheduler.js +2 -1
  109. package/dist/memory/sidecar-worker.js +1 -1
  110. package/dist/memory/transcript.js +1 -1
  111. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  112. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  113. package/dist/models/login-identity.d.ts +2 -0
  114. package/dist/models/login-identity.js +83 -0
  115. package/dist/models/provider-login.d.ts +3 -1
  116. package/dist/models/provider-login.js +8 -2
  117. package/dist/models/reference.d.ts +20 -0
  118. package/dist/models/{utils.js → reference.js} +0 -48
  119. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  120. package/dist/models/runtime.js +52 -0
  121. package/dist/playbooks/catalog.d.ts +6 -2
  122. package/dist/playbooks/catalog.js +9 -6
  123. package/dist/runtime/bootstrap.d.ts +7 -17
  124. package/dist/runtime/bootstrap.js +37 -755
  125. package/dist/runtime/durable-dispatch.d.ts +17 -4
  126. package/dist/runtime/durable-dispatch.js +60 -18
  127. package/dist/runtime/inbound-images.d.ts +18 -0
  128. package/dist/runtime/inbound-images.js +51 -0
  129. package/dist/runtime/shutdown.d.ts +39 -0
  130. package/dist/runtime/shutdown.js +120 -0
  131. package/dist/runtime/stop-watchdog.d.ts +16 -0
  132. package/dist/runtime/stop-watchdog.js +32 -0
  133. package/dist/runtime/task-driver.d.ts +2 -2
  134. package/dist/runtime/task-driver.js +3 -3
  135. package/dist/runtime/task-migration.js +2 -2
  136. package/dist/runtime/task-spawn.d.ts +1 -1
  137. package/dist/runtime/task-spawn.js +1 -1
  138. package/dist/runtime/turn-handler.d.ts +47 -0
  139. package/dist/runtime/turn-handler.js +318 -0
  140. package/dist/runtime/turn-run.d.ts +52 -0
  141. package/dist/runtime/turn-run.js +318 -0
  142. package/dist/security/command-guard.js +4 -0
  143. package/dist/security/network.js +4 -0
  144. package/dist/security/path-guard.js +4 -0
  145. package/dist/security/types.d.ts +1 -2
  146. package/dist/security/types.js +1 -2
  147. package/dist/shared/exact-keys.d.ts +1 -1
  148. package/dist/shared/host-process.js +1 -1
  149. package/dist/shared/wake-claim.d.ts +1 -1
  150. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  151. package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
  152. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  153. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  154. package/dist/skills/workspace.d.ts +33 -0
  155. package/dist/skills/workspace.js +116 -0
  156. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
  157. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
  158. package/dist/subagents/completion-wake.d.ts +17 -0
  159. package/dist/subagents/completion-wake.js +76 -0
  160. package/dist/subagents/detached-discovery.js +1 -1
  161. package/dist/subagents/discovery.d.ts +1 -1
  162. package/dist/subagents/discovery.js +2 -2
  163. package/dist/subagents/dispatch.d.ts +33 -0
  164. package/dist/subagents/dispatch.js +190 -0
  165. package/dist/subagents/external/dispatch.d.ts +25 -0
  166. package/dist/subagents/external/dispatch.js +90 -0
  167. package/dist/subagents/external/harness.d.ts +1 -1
  168. package/dist/subagents/external/progress-tail.d.ts +1 -1
  169. package/dist/subagents/external/run.d.ts +2 -1
  170. package/dist/subagents/external/run.js +2 -2
  171. package/dist/subagents/external/settlement.d.ts +1 -1
  172. package/dist/subagents/format.d.ts +1 -1
  173. package/dist/subagents/grace.d.ts +24 -0
  174. package/dist/subagents/grace.js +57 -0
  175. package/dist/subagents/internal/outcome.d.ts +24 -0
  176. package/dist/subagents/internal/outcome.js +149 -0
  177. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  178. package/dist/subagents/internal/provider-retry.js +83 -0
  179. package/dist/subagents/internal/run.d.ts +31 -0
  180. package/dist/subagents/internal/run.js +240 -0
  181. package/dist/subagents/internal/state.d.ts +43 -0
  182. package/dist/subagents/internal/state.js +48 -0
  183. package/dist/subagents/internal/worker.d.ts +51 -0
  184. package/dist/subagents/internal/worker.js +167 -0
  185. package/dist/subagents/result.d.ts +62 -0
  186. package/dist/subagents/result.js +103 -0
  187. package/dist/subagents/run-record.d.ts +222 -0
  188. package/dist/subagents/run-record.js +101 -0
  189. package/dist/subagents/run-registry.d.ts +9 -0
  190. package/dist/subagents/run-registry.js +125 -0
  191. package/dist/subagents/runs.d.ts +7 -243
  192. package/dist/subagents/runs.js +8 -291
  193. package/dist/subagents/task-envelope.d.ts +36 -0
  194. package/dist/subagents/task-envelope.js +168 -0
  195. package/dist/subagents/types.d.ts +154 -0
  196. package/dist/subagents/types.js +1 -0
  197. package/dist/subagents/verification-outcome.d.ts +1 -1
  198. package/dist/tasks/board.d.ts +2 -2
  199. package/dist/tasks/board.js +2 -2
  200. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  201. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  202. package/dist/tasks/brief.js +1 -1
  203. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  204. package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
  205. package/dist/tasks/contract-input.d.ts +1 -1
  206. package/dist/tasks/contract-input.js +1 -1
  207. package/dist/tasks/create.js +1 -1
  208. package/dist/tasks/{log.js → loop-log.js} +1 -1
  209. package/dist/tasks/mutation-lock.js +1 -1
  210. package/dist/tasks/session-path.js +1 -1
  211. package/dist/tasks/steer.js +1 -1
  212. package/dist/tasks/store.js +2 -2
  213. package/dist/tools/bash.d.ts +1 -1
  214. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
  215. package/dist/tools/{tool-details.js → contract/details.js} +4 -4
  216. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  217. package/dist/tools/event-manage.d.ts +1 -1
  218. package/dist/tools/event-manage.js +4 -4
  219. package/dist/tools/index.d.ts +3 -3
  220. package/dist/tools/index.js +7 -6
  221. package/dist/tools/job.d.ts +1 -1
  222. package/dist/tools/registry.d.ts +7 -7
  223. package/dist/tools/registry.js +6 -6
  224. package/dist/tools/session-search.d.ts +1 -1
  225. package/dist/tools/skill.d.ts +2 -34
  226. package/dist/tools/skill.js +8 -116
  227. package/dist/tools/subagent-manage.js +4 -3
  228. package/dist/tools/subagent.d.ts +46 -0
  229. package/dist/tools/subagent.js +127 -0
  230. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  231. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  232. package/dist/tools/task-manage/lifecycle.js +2 -2
  233. package/dist/tools/task-manage/log-view.js +2 -2
  234. package/dist/tools/task-manage/shared.js +3 -3
  235. package/dist/tools/task-manage/step-end.js +3 -3
  236. package/dist/tools/task-manage/types.d.ts +1 -1
  237. package/dist/tools/web-fetch.d.ts +1 -1
  238. package/dist/tools/web-search.d.ts +1 -1
  239. package/dist/tui/app.d.ts +1 -1
  240. package/dist/tui/app.js +6 -6
  241. package/dist/tui/cli.d.ts +1 -1
  242. package/dist/tui/cli.js +1 -1
  243. package/dist/tui/frontend.d.ts +44 -0
  244. package/dist/tui/frontend.js +13 -0
  245. package/dist/tui/pitui-frontend.d.ts +1 -1
  246. package/dist/tui/plain-frontend.d.ts +1 -1
  247. package/dist/tui/renderer.d.ts +3 -42
  248. package/dist/tui/terminal-context.d.ts +2 -2
  249. package/dist/tui/terminal-media-sender.d.ts +1 -1
  250. package/dist/tui/turn-controller.d.ts +1 -1
  251. package/dist/usage/ledger.js +4 -0
  252. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  253. package/dist/web/client.d.ts +5 -1
  254. package/dist/web/client.js +4 -0
  255. package/dist/web/config.d.ts +1 -1
  256. package/dist/web/fetch.d.ts +1 -1
  257. package/dist/web/search-providers.d.ts +1 -1
  258. package/dist/web/search.d.ts +1 -1
  259. package/package.json +9 -7
  260. package/dist/events/events.d.ts +0 -159
  261. package/dist/runtime/dingtalk.d.ts +0 -272
  262. package/dist/runtime/dingtalk.js +0 -1470
  263. package/dist/subagents/tool.d.ts +0 -213
  264. package/dist/subagents/tool.js +0 -1282
  265. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  266. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  267. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  268. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  269. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  270. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  271. /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
  272. /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
  273. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  274. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  275. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  276. /package/dist/{runtime → app}/proxy.js +0 -0
  277. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  278. /package/dist/{runtime → dingtalk}/delivery.js +0 -0
  279. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  280. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  281. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  282. /package/dist/events/{event-validation.js → validation.js} +0 -0
  283. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  284. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  285. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  286. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  287. /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
  288. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  289. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  290. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  291. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,257 @@
1
+ import * as log from "../../log.js";
2
+ import { formatModelReference } from "../../models/reference.js";
3
+ import { errorMessage } from "../../shared/text-utils.js";
4
+ import { SessionRetryAttempt } from "../session/session-adapter.js";
5
+ import { MAX_USER_MESSAGE_CHARS } from "../types.js";
6
+ import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
7
+ import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
8
+ import { buildFirstTurnMemoryBootstrap, buildTaskDigestForTurn, renderChannelTurnContext } from "./turn-context.js";
9
+ import { renderFallbackSwitch } from "./turn-error.js";
10
+ import { formatUserMessage, persistOversizedInput, prepareInboundImages, shouldPreserveRawInput, } from "./turn-input.js";
11
+ export function createTurnProgress() {
12
+ return {
13
+ promptSubmitted: false,
14
+ fallbackAttempted: false,
15
+ fallbackTargetRef: undefined,
16
+ promptText: "",
17
+ taskDigestText: "",
18
+ durableMemoryBootstrapText: "",
19
+ bootstrapPrepared: false,
20
+ images: { images: [], notices: [] },
21
+ };
22
+ }
23
+ export class TurnPipeline {
24
+ constructor(deps) {
25
+ this.deps = deps;
26
+ this.channelId = deps.channelId;
27
+ this.channelDir = deps.channelDir;
28
+ this.workspaceDir = deps.workspaceDir;
29
+ this.host = deps.host;
30
+ this.models = deps.models;
31
+ this.turnState = deps.turnState;
32
+ }
33
+ get runState() {
34
+ return this.deps.getRunState();
35
+ }
36
+ get session() {
37
+ return this.host.session;
38
+ }
39
+ /** Oversized input is spilled to disk and clipped; the user is told. Slash commands pass through raw. */
40
+ async prepareUserInput(ctx) {
41
+ const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
42
+ let oversizedInputPath;
43
+ if (normalizedInputLength > MAX_USER_MESSAGE_CHARS) {
44
+ oversizedInputPath = await persistOversizedInput(this.channelDir, this.channelId, ctx.message.text);
45
+ await ctx.respondInThread(oversizedInputPath
46
+ ? `⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理;完整内容已存到 \`${oversizedInputPath}\`,需要时让我读取这个文件查看被省略的部分。`
47
+ : `⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理。`);
48
+ }
49
+ const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS, oversizedInputPath);
50
+ return {
51
+ clippedInput,
52
+ userMessage: formatUserMessage(clippedInput, ctx.message.userName),
53
+ preserveRawInput: shouldPreserveRawInput(ctx.message.text),
54
+ };
55
+ }
56
+ /**
57
+ * The turn-dynamic context: the channel capsule (returned) plus, recorded on `turn`, the task
58
+ * digest and the first-turn memory bootstrap. A raw-passthrough input (a slash command) gets none.
59
+ */
60
+ async gatherTurnContext(preserveRawInput, turn) {
61
+ if (preserveRawInput)
62
+ return "";
63
+ // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
64
+ // system prompt is what lets every channel in a workspace share one cached prefix.
65
+ const channelCapsuleText = renderChannelTurnContext(this.channelDir);
66
+ // The task digest reads the whole tasks/ directory and depends on nothing the memory
67
+ // bootstrap below produces, so it runs alongside it rather than queuing behind it.
68
+ // Settled into a result object rather than left as a bare promise: if the bootstrap
69
+ // throws first we would otherwise leave a rejection unobserved, which Node's default
70
+ // policy turns into a process exit. Rethrown at the await, so a digest failure still
71
+ // fails the turn exactly as it did when this ran inline. A task step gets none: its brief
72
+ // already carries its own task, and the channel's other tasks are noise there.
73
+ const taskDigestPromise = (this.host.tasksEnabled && !this.host.taskLoop ? buildTaskDigestForTurn(this.channelDir) : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
74
+ // Spec 050, D1: the memory index is injected in full on the first turn of a session
75
+ // (and the first turn after compaction — see `subscribeToSessionEvents`), never per
76
+ // turn. Mid-session, the model uses `memory_search` to look things up.
77
+ if (this.host.firstTurnMemoryBootstrapPending) {
78
+ turn.durableMemoryBootstrapText = await buildFirstTurnMemoryBootstrap(this.channelDir, this.workspaceDir);
79
+ turn.bootstrapPrepared = true;
80
+ }
81
+ const taskDigestResult = await taskDigestPromise;
82
+ if (taskDigestResult.error !== undefined) {
83
+ throw taskDigestResult.error;
84
+ }
85
+ turn.taskDigestText = taskDigestResult.text ?? "";
86
+ return channelCapsuleText;
87
+ }
88
+ /** Inbound images for the current model, with a notice to the user for each one that was left out. */
89
+ async prepareTurnImages(ctx) {
90
+ const prepared = await prepareInboundImages(ctx.message.images, this.session.model ?? this.models.activeModel);
91
+ for (const notice of prepared.notices) {
92
+ await ctx.respondInThread(notice);
93
+ }
94
+ return prepared;
95
+ }
96
+ /** The seams `runPromptWithFallback` drives: submit the prompt, observe/reset the error, switch model. */
97
+ buildFallbackDeps(ctx, runQueue, turn, ownTurn) {
98
+ let attempt;
99
+ const canRetry = () => !this.deps.isRetired() &&
100
+ this.turnState.current() === ownTurn &&
101
+ !ownTurn.stopRequested &&
102
+ (!attempt || this.host.session === attempt.session);
103
+ const submit = async (session, text) => {
104
+ await session.prompt(text, turn.images.images.length > 0 ? { images: turn.images.images } : undefined);
105
+ turn.promptSubmitted = true;
106
+ if (turn.bootstrapPrepared)
107
+ this.host.firstTurnMemoryBootstrapPending = false;
108
+ };
109
+ return {
110
+ prompt: async (text) => {
111
+ try {
112
+ await this.host.runPrompt(async () => {
113
+ if (!canRetry())
114
+ return;
115
+ attempt = new SessionRetryAttempt(this.session);
116
+ await submit(attempt.session, text);
117
+ });
118
+ }
119
+ catch (err) {
120
+ this.runState.stopReason = "error";
121
+ this.runState.errorMessage = errorMessage(err);
122
+ log.logEvent("error", "agent.turn.failed", "Runner failed", {
123
+ ctx: this.runState.logCtx ?? { channelId: this.channelId },
124
+ fields: { error: this.runState.errorMessage },
125
+ });
126
+ }
127
+ },
128
+ getRunError: () => ({
129
+ stopReason: this.runState.stopReason,
130
+ errorMessage: this.runState.errorMessage,
131
+ }),
132
+ resetRunError: () => {
133
+ this.runState.stopReason = "stop";
134
+ this.runState.errorMessage = undefined;
135
+ this.runState.finalOutcome = { kind: "none" };
136
+ this.runState.lastCompactionError = undefined;
137
+ },
138
+ canRetry,
139
+ prepareRetry: () => {
140
+ const captured = attempt;
141
+ const classified = captured?.prepare();
142
+ if (!captured || !classified || !canRetry())
143
+ return null;
144
+ return {
145
+ kind: classified.kind,
146
+ run: (text, onReady) => this.host.runPrompt(async () => {
147
+ if (!canRetry())
148
+ return "stale";
149
+ try {
150
+ if (!captured.omitFailedContext())
151
+ return "stale";
152
+ }
153
+ catch (error) {
154
+ throw this.host.markContextFault(captured.session, error);
155
+ }
156
+ if (!canRetry())
157
+ return "stale";
158
+ onReady();
159
+ await submit(captured.session, text);
160
+ return "attempted";
161
+ }),
162
+ };
163
+ },
164
+ getCurrentModelRef: () => formatModelReference(this.session.model ?? this.models.activeModel),
165
+ resolveFallbackModel: () => this.models.resolveFallbackModel(),
166
+ setModel: async (model) => {
167
+ await this.models.setModelWithThinkingPreservation(model);
168
+ if (!canRetry())
169
+ return;
170
+ // The fallback model's vision support can differ from the one this turn started
171
+ // on; re-resolve against it rather than resend whatever was prepared for the
172
+ // model that just failed.
173
+ turn.images = await this.prepareTurnImages(ctx);
174
+ },
175
+ notifySwitch: (from, to, errorSummary) => {
176
+ turn.fallbackTargetRef = to;
177
+ if (this.runState.logCtx) {
178
+ log.logModelFallback(this.runState.logCtx, from, to, errorSummary);
179
+ }
180
+ const text = renderFallbackSwitch(from, to, errorSummary);
181
+ if (ctx.progressStyle !== "none") {
182
+ runQueue.queue.enqueue(() => ctx.respond(formatProgressEntry("error", text), false), "fallback switch");
183
+ }
184
+ else {
185
+ runQueue.queue.enqueue(() => ctx.respondInThread(`⚠️ ${text}`), "fallback switch");
186
+ }
187
+ },
188
+ markPrimaryFailed: () => {
189
+ this.models.markPrimaryFailed();
190
+ },
191
+ };
192
+ }
193
+ /**
194
+ * Single source of truth for the busy-message window: steer is accepted while
195
+ * the prompt is being assembled ("preparing") or while the agent loop is
196
+ * actually streaming. Re-asserted after every await because the turn can end
197
+ * while this call was suspended.
198
+ */
199
+ assertBusyWindowOpen() {
200
+ if (this.turnState.phase() === "preparing") {
201
+ return;
202
+ }
203
+ if (this.turnState.phase() === "streaming" && this.session.isStreaming) {
204
+ return;
205
+ }
206
+ throw new Error("No task is currently running.");
207
+ }
208
+ async queueBusyMessage(text, userName, images) {
209
+ this.assertBusyWindowOpen();
210
+ await this.host.ensureSessionReady();
211
+ const oversized = text.replace(/\r/g, "").trim().length > MAX_USER_MESSAGE_CHARS;
212
+ const oversizedPath = oversized ? await persistOversizedInput(this.channelDir, this.channelId, text) : undefined;
213
+ const clippedText = clipUserInput(text, MAX_USER_MESSAGE_CHARS, oversizedPath);
214
+ if (oversized) {
215
+ log.logWarn("agent.input.clipped", "Queued message clipped", {
216
+ channelId: this.channelId,
217
+ fields: { limitChars: MAX_USER_MESSAGE_CHARS },
218
+ });
219
+ }
220
+ const queuedMessage = formatUserMessage(clippedText, userName);
221
+ const preparedImages = await prepareInboundImages(images, this.session.model ?? this.models.activeModel);
222
+ for (const notice of preparedImages.notices) {
223
+ await this.runState.ctx?.respondInThread(notice);
224
+ }
225
+ await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage, preparedImages.images.length);
226
+ this.assertBusyWindowOpen();
227
+ const queueMessage = async () => {
228
+ this.assertBusyWindowOpen();
229
+ await this.session.steer(queuedMessage, preparedImages.images.length > 0 ? preparedImages.images : undefined);
230
+ };
231
+ await this.host.runPrompt(queueMessage);
232
+ }
233
+ async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
234
+ const currentModel = this.session.model ?? this.models.activeModel;
235
+ const contextUsage = this.session.getContextUsage();
236
+ const contextTokens = contextUsage?.tokens;
237
+ const incomingTokens = estimateIncomingMessageTokens(incomingText, imageCount);
238
+ const decision = getPreventiveCompactionDecision(contextTokens, incomingTokens, currentModel.contextWindow);
239
+ if (!decision.shouldCompact) {
240
+ return;
241
+ }
242
+ const currentTokens = contextTokens ?? 0;
243
+ const startedAt = Date.now();
244
+ log.logInfo(`[${this.channelId}] Preventive compaction triggered: projected ${decision.projectedTokens}/${currentModel.contextWindow} tokens (current=${currentTokens}, incoming≈${incomingTokens}), threshold=${decision.thresholdTokens}`);
245
+ try {
246
+ await this.session.compact();
247
+ log.logInfo(`[${this.channelId}] Preventive compaction complete in ${Date.now() - startedAt}ms`);
248
+ }
249
+ catch (error) {
250
+ const message = errorMessage(error);
251
+ log.logWarn("agent.compaction.preventive_failed", "Preventive compaction failed", {
252
+ channelId: this.channelId,
253
+ reason: message,
254
+ });
255
+ }
256
+ }
257
+ }
@@ -1,4 +1,4 @@
1
- import type { PromptTurnContextStats } from "./prompt/manifest.js";
1
+ import type { PromptTurnContextStats } from "../prompt/manifest.js";
2
2
  export interface TurnPromptParts {
3
3
  /** The user's message, already clipped to `MAX_USER_MESSAGE_CHARS`. Measured, not rendered. */
4
4
  clippedInput: string;
@@ -30,6 +30,6 @@ export interface AssembledTurnPrompt {
30
30
  *
31
31
  * `stats` measures the inputs, never the rendered wrapper — it is what `/context` reports as the
32
32
  * previous turn's automatic context, and the per-piece unit caps are enforced upstream by the
33
- * builders themselves (`memory/index-budget.ts`, `memory/task-digest.ts`).
33
+ * builders themselves (`memory/index-budget.ts`, `agent/turn/task-digest.ts`).
34
34
  */
35
35
  export declare function assembleTurnPrompt(parts: TurnPromptParts): AssembledTurnPrompt;
@@ -1,4 +1,8 @@
1
- import { countPromptUnits } from "../shared/prompt-units.js";
1
+ /**
2
+ * Assembles one turn's prompt from the pieces gathered for it (memory bootstrap, task agenda, channel
3
+ * capsule, the user's message) and measures what each piece cost.
4
+ */
5
+ import { countPromptUnits } from "../../shared/prompt-units.js";
2
6
  /**
3
7
  * Compose one turn's prompt from the pieces `run()` gathered, and measure what each piece cost.
4
8
  *
@@ -10,7 +14,7 @@ import { countPromptUnits } from "../shared/prompt-units.js";
10
14
  *
11
15
  * `stats` measures the inputs, never the rendered wrapper — it is what `/context` reports as the
12
16
  * previous turn's automatic context, and the per-piece unit caps are enforced upstream by the
13
- * builders themselves (`memory/index-budget.ts`, `memory/task-digest.ts`).
17
+ * builders themselves (`memory/index-budget.ts`, `agent/turn/task-digest.ts`).
14
18
  */
15
19
  export function assembleTurnPrompt(parts) {
16
20
  const stats = {
@@ -1,7 +1,7 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { SessionManager } from "@earendil-works/pi-coding-agent";
4
- import { resolveActiveSessionFile } from "../channel/active-session-store.js";
4
+ import { resolveActiveSessionFile } from "../../channel/active-session-store.js";
5
5
  /**
6
6
  * Repairs a session branch left with a declared-but-unfulfilled tool call by a process that
7
7
  * exited between the assistant's tool call and the tool result being recorded (spec 043, D8-D16).
@@ -1,4 +1,4 @@
1
- import type { TurnPhase, TurnStatus } from "./types.js";
1
+ import type { TurnPhase, TurnStatus } from "../types.js";
2
2
  /**
3
3
  * One turn's mutable state. `current()` hands it out so the owning `run()` can address *its own*
4
4
  * turn for later phase writes: once `forceEnd()` has released a turn, the machine's current turn
@@ -1,10 +1,16 @@
1
- import type { ChannelContext } from "../channel/channel-context.js";
1
+ import type { ChannelContext, MediaSender } from "../channel/channel-context.js";
2
2
  import type { InboundImage } from "../channel/channel-event.js";
3
3
  import type { ChannelStore } from "../channel/store.js";
4
4
  import type { RunnerBuiltInCommand } from "../commands/catalog.js";
5
+ import type { PipiclawSettingsManager } from "../config/settings.js";
6
+ import type { Executor } from "../executor.js";
7
+ import type { FileStore } from "../file-store.js";
8
+ import type { ChannelJobManager } from "../jobs/manager.js";
5
9
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
6
- import { type UsageTotals } from "../shared/types.js";
10
+ import type { LoadedSecurityConfig } from "../security/config.js";
7
11
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
12
+ import type { SubAgentRunManager } from "../subagents/runs.js";
13
+ import { type UsageTotals } from "../usage/totals.js";
8
14
  export interface RunnerStatusSnapshot {
9
15
  model: string;
10
16
  contextTokens?: number;
@@ -266,3 +272,38 @@ export type AutoRetryStartEvent = Extract<SessionEvent, {
266
272
  }>;
267
273
  export type ProgressEntryKind = "tool" | "thinking" | "error" | "assistant";
268
274
  export declare const MAX_USER_MESSAGE_CHARS = 12000;
275
+ export interface RunnerFactoryPaths {
276
+ jobManager: ChannelJobManager;
277
+ runManager: SubAgentRunManager;
278
+ appHomeDir: string;
279
+ authConfigPath: string;
280
+ modelsConfigPath: string;
281
+ /**
282
+ * The single app-level settings manager (from `prepareAppServices`), shared across every
283
+ * channel's runner rather than each constructing its own. Keeps `drainErrors()`/diagnostics
284
+ * ordering and `reload()`'s file-stamp guard meaningful instead of racing N independent copies.
285
+ */
286
+ settingsManager: PipiclawSettingsManager;
287
+ /** Optional, side-effect-free observer used by the behavior-eval harness. */
288
+ onSessionEvent?: (event: unknown, channelId: string) => void;
289
+ /**
290
+ * Transport that can deliver file attachments (the DingTalk bot, or the terminal).
291
+ * Present enables the `send_media` tool; absent, the tool is not built.
292
+ */
293
+ mediaSender?: MediaSender;
294
+ }
295
+ /**
296
+ * The collaborators a runner uses but does not build. Composing them here rather than inside
297
+ * `ChannelRunner`'s constructor keeps the "which implementation" decision at the one place that
298
+ * already owns wiring, and is what makes `Executor`/`FileStore` real ports (a remote executor is
299
+ * a different value passed in, not a different branch inside the runner).
300
+ */
301
+ export interface RunnerDeps {
302
+ executor: Executor;
303
+ fileStore: FileStore;
304
+ /**
305
+ * Called per use, not resolved once: the runner re-reads security policy on every tool rebuild
306
+ * so an edited `security.json` takes effect without restarting the daemon.
307
+ */
308
+ loadSecurityConfig: () => LoadedSecurityConfig;
309
+ }
@@ -1,4 +1,4 @@
1
- import { createEmptyUsageTotals } from "../shared/types.js";
1
+ import { createEmptyUsageTotals } from "../usage/totals.js";
2
2
  export function createEmptyRunState() {
3
3
  return {
4
4
  ctx: null,
@@ -1,4 +1,4 @@
1
- import { type BootstrapIO, type BootstrapPaths } from "../runtime/app-home.js";
1
+ import { type BootstrapIO, type BootstrapPaths } from "./home.js";
2
2
  export type ParsedAuth = {
3
3
  kind: "status";
4
4
  } | {
@@ -6,13 +6,14 @@
6
6
  * login is a short, one-shot operation (spec 039 §5.1).
7
7
  */
8
8
  import { createInterface } from "node:readline/promises";
9
- import { prepareAppServices } from "../app-services.js";
10
9
  import * as log from "../log.js";
10
+ import { ReadlineLoginUi } from "../models/login-ui.js";
11
+ import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "../models/provider-login.js";
12
+ import { formatModelReference } from "../models/reference.js";
13
+ import { createModelRuntime } from "../models/runtime.js";
11
14
  import { docsUrl } from "../paths.js";
12
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
13
- import { ReadlineLoginUi } from "./login-ui.js";
14
- import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
15
- import { createModelRuntime, formatModelReference } from "./utils.js";
15
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "./home.js";
16
+ import { prepareAppServices } from "./services.js";
16
17
  /** Parse `pipiclaw auth` arguments (everything after the `auth` subcommand, including the subcommand name itself). */
17
18
  export function parseAuthArgs(args) {
18
19
  if (args.length === 0) {
@@ -173,7 +174,7 @@ function auditAuthEvent(action, providerId, authType, ok) {
173
174
  // token/secret fragment.
174
175
  log.logInfo(`auth ${action}: ${providerId}${authType ? ` (${authType})` : ""} — ${ok ? "ok" : "failed"}`);
175
176
  }
176
- async function runLogin(runtime, parsed, io, signal) {
177
+ async function runLogin(runtime, parsed, io, signal, paths) {
177
178
  const ui = new ReadlineLoginUi({
178
179
  signal,
179
180
  presetFirstSelect: parsed.deviceCode ? "device_code" : undefined,
@@ -188,7 +189,9 @@ async function runLogin(runtime, parsed, io, signal) {
188
189
  }
189
190
  let result;
190
191
  try {
191
- result = await loginProvider(runtime, target.providerId, target.authType, ui);
192
+ result = await loginProvider(runtime, target.providerId, target.authType, ui, {
193
+ appHomeDir: paths.appHomeDir,
194
+ });
192
195
  }
193
196
  catch (error) {
194
197
  auditAuthEvent("login", target.providerId, target.authType, false);
@@ -334,7 +337,7 @@ export async function runAuth(argv, io = console, paths = DEFAULT_BOOTSTRAP_PATH
334
337
  process.once("SIGINT", onSigint);
335
338
  try {
336
339
  if (parsed.kind === "login") {
337
- await runLogin(runtime, parsed, io, controller.signal);
340
+ await runLogin(runtime, parsed, io, controller.signal, paths);
338
341
  }
339
342
  else {
340
343
  await runLogout(runtime, parsed, io, controller.signal);
@@ -1,4 +1,3 @@
1
- import { type DingTalkConfig } from "./dingtalk.js";
2
1
  export interface BootstrapPaths {
3
2
  appName: string;
4
3
  appHomeDir: string;
@@ -34,7 +33,6 @@ export declare function printBootstrapSummary(result: BootstrapResult, io?: Boot
34
33
  * where they come from, and the model credential step the daemon cannot run without.
35
34
  */
36
35
  export declare function printFirstRunGuide(io?: BootstrapIO, paths?: BootstrapPaths): void;
37
- export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
38
36
  /**
39
37
  * The one place that lists `pipiclaw`'s top-level subcommands. `parseArgs`'s own `--help` uses it;
40
38
  * `main.ts`'s unknown-subcommand branch used to hand-copy the same three lines separately (review
@@ -1,15 +1,15 @@
1
1
  /**
2
- * App-home scaffolding: create `~/.pipiclaw` (or `PIPICLAW_HOME`) on first run, validate
3
- * `channel.json`, and parse CLI args shared by every entrypoint. Pure functions over explicit
2
+ * App-home scaffolding: create `~/.pipiclaw` (or `PIPICLAW_HOME`) on first run (writing the
3
+ * `channel.json` template; `dingtalk/config.ts` loads and validates it), and parse CLI args
4
+ * shared by every entrypoint. Pure functions over explicit
4
5
  * `paths`/`io` parameters — no dependency on the runtime wiring in `bootstrap.ts`.
5
6
  */
6
7
  import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
7
8
  import { join } from "path";
9
+ import { DEFAULT_AGENTS, DEFAULT_SOUL } from "../agent/prompt/workspace-templates.js";
8
10
  import * as log from "../log.js";
9
11
  import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, docsUrl, EVENT_HISTORY_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
10
12
  import { errorMessage } from "../shared/text-utils.js";
11
- import { isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
12
- import { DEFAULT_AGENTS, DEFAULT_SOUL } from "./workspace-templates.js";
13
13
  const DEFAULT_MEMORY = `# Workspace Memory
14
14
 
15
15
  This file stores stable workspace-level memory.
@@ -205,46 +205,6 @@ export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS) {
205
205
  }
206
206
  return { created, channelTemplateCreated };
207
207
  }
208
- function isPlaceholderString(value) {
209
- return value.trim().startsWith("your-");
210
- }
211
- function listChannelConfigIssues(config) {
212
- const issues = [];
213
- if (!config.clientId) {
214
- issues.push("Missing required field `clientId`.");
215
- }
216
- else if (isPlaceholderString(config.clientId)) {
217
- issues.push("Replace placeholder value for `clientId`.");
218
- }
219
- if (!config.clientSecret) {
220
- issues.push("Missing required field `clientSecret`.");
221
- }
222
- else if (isPlaceholderString(config.clientSecret)) {
223
- issues.push("Replace placeholder value for `clientSecret`.");
224
- }
225
- if (config.robotCode && isPlaceholderString(config.robotCode)) {
226
- issues.push("Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.");
227
- }
228
- if (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {
229
- issues.push("Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.");
230
- }
231
- if (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {
232
- issues.push("Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.");
233
- }
234
- const busyMessageDefault = config.busyMessageDefault;
235
- if (busyMessageDefault !== undefined && !isBusyMessageDefaultConfig(busyMessageDefault)) {
236
- issues.push('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
237
- }
238
- const responseMode = config.responseMode;
239
- if (responseMode !== undefined && !isResponseModeConfig(responseMode)) {
240
- issues.push('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
241
- }
242
- const cardAutoLayout = config.cardAutoLayout;
243
- if (cardAutoLayout !== undefined && typeof cardAutoLayout !== "boolean") {
244
- issues.push("Invalid `cardAutoLayout`: expected boolean.");
245
- }
246
- return issues;
247
- }
248
208
  export function printBootstrapSummary(result, io = console, paths = DEFAULT_BOOTSTRAP_PATHS) {
249
209
  if (result.created.length === 0) {
250
210
  return;
@@ -269,37 +229,6 @@ export function printFirstRunGuide(io = console, paths = DEFAULT_BOOTSTRAP_PATHS
269
229
  io.log(` 3. Run \`${paths.appName}\` again.`);
270
230
  io.log(`Docs: ${docsUrl("configuration.md")}`);
271
231
  }
272
- export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
273
- let parsed;
274
- try {
275
- parsed = JSON.parse(readFileSync(paths.channelConfigPath, "utf-8"));
276
- }
277
- catch (err) {
278
- io.error(`Failed to parse configuration: ${paths.channelConfigPath}`);
279
- io.error(errorMessage(err));
280
- throw new BootstrapExitError(1);
281
- }
282
- const issues = listChannelConfigIssues(parsed);
283
- if (issues.length > 0) {
284
- io.error(`Configuration is not ready: ${paths.channelConfigPath}`);
285
- for (const issue of issues) {
286
- io.error(` - ${issue}`);
287
- }
288
- io.error("");
289
- io.error(`Fix ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
290
- io.error(`Docs: ${docsUrl("configuration.md")}`);
291
- throw new BootstrapExitError(1);
292
- }
293
- parsed.cardTemplateKey = parsed.cardTemplateKey || "content";
294
- parsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;
295
- parsed.busyMessageDefault = normalizeBusyMessageDefault(parsed.busyMessageDefault);
296
- parsed.responseMode = normalizeResponseMode(parsed.responseMode);
297
- parsed.cardAutoLayout = parsed.cardAutoLayout ?? true;
298
- if (Array.isArray(parsed.allowFrom)) {
299
- parsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);
300
- }
301
- return parsed;
302
- }
303
232
  /**
304
233
  * The one place that lists `pipiclaw`'s top-level subcommands. `parseArgs`'s own `--help` uses it;
305
234
  * `main.ts`'s unknown-subcommand branch used to hand-copy the same three lines separately (review
@@ -1,16 +1,16 @@
1
- import { type BootstrapPaths } from "./runtime/app-home.js";
2
- import { PipiclawSettingsManager } from "./settings.js";
1
+ import { PipiclawSettingsManager } from "../config/settings.js";
2
+ import { type BootstrapPaths } from "./home.js";
3
3
  /**
4
4
  * Transport-neutral app services shared by the DingTalk runtime, the terminal TUI, and the
5
5
  * `pipiclaw auth` CLI: loads settings (surfacing load errors) and reports tool/security config
6
6
  * diagnostics. Does NOT touch DingTalk config, so non-DingTalk entrypoints can call it without
7
7
  * any DingTalk credentials.
8
8
  *
9
- * Lives at the package root rather than in `runtime/` on purpose: `models/auth-cli.ts` needs it
9
+ * Lives in `app/` rather than in `runtime/` on purpose: `app/auth-command.ts` needs it
10
10
  * before a runner or channel exists, and `runtime/bootstrap.ts` separately depends on `models/`
11
11
  * (for the default model reference) — parking this function inside `bootstrap.ts` made `models`
12
- * and `runtime` depend on each other. Everything this function touches (`settings.ts`,
13
- * `tools/config.ts`, `security/config.ts`, `runtime/app-home.ts`, `runtime/proxy.ts`) has no
12
+ * and `runtime` depend on each other. Everything this function touches (`config/settings.ts`,
13
+ * `config/tools.ts`, `security/config.ts`, `app/home.ts`, `app/proxy.ts`) has no
14
14
  * import back to `models/`, so this file doesn't reintroduce the cycle it was extracted to break.
15
15
  */
16
16
  export declare function prepareAppServices(paths?: BootstrapPaths): {
@@ -1,21 +1,21 @@
1
- import * as log from "./log.js";
2
- import { DEFAULT_BOOTSTRAP_PATHS } from "./runtime/app-home.js";
3
- import { installLlmProxy } from "./runtime/proxy.js";
4
- import { loadSecurityConfigWithDiagnostics } from "./security/config.js";
5
- import { PipiclawSettingsManager } from "./settings.js";
6
- import { formatConfigDiagnostic } from "./shared/config-diagnostic.js";
7
- import { loadToolsConfigWithDiagnostics } from "./tools/config.js";
1
+ import { PipiclawSettingsManager } from "../config/settings.js";
2
+ import { loadToolsConfigWithDiagnostics } from "../config/tools.js";
3
+ import * as log from "../log.js";
4
+ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
5
+ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
6
+ import { DEFAULT_BOOTSTRAP_PATHS } from "./home.js";
7
+ import { installLlmProxy } from "./proxy.js";
8
8
  /**
9
9
  * Transport-neutral app services shared by the DingTalk runtime, the terminal TUI, and the
10
10
  * `pipiclaw auth` CLI: loads settings (surfacing load errors) and reports tool/security config
11
11
  * diagnostics. Does NOT touch DingTalk config, so non-DingTalk entrypoints can call it without
12
12
  * any DingTalk credentials.
13
13
  *
14
- * Lives at the package root rather than in `runtime/` on purpose: `models/auth-cli.ts` needs it
14
+ * Lives in `app/` rather than in `runtime/` on purpose: `app/auth-command.ts` needs it
15
15
  * before a runner or channel exists, and `runtime/bootstrap.ts` separately depends on `models/`
16
16
  * (for the default model reference) — parking this function inside `bootstrap.ts` made `models`
17
- * and `runtime` depend on each other. Everything this function touches (`settings.ts`,
18
- * `tools/config.ts`, `security/config.ts`, `runtime/app-home.ts`, `runtime/proxy.ts`) has no
17
+ * and `runtime` depend on each other. Everything this function touches (`config/settings.ts`,
18
+ * `config/tools.ts`, `security/config.ts`, `app/home.ts`, `app/proxy.ts`) has no
19
19
  * import back to `models/`, so this file doesn't reintroduce the cycle it was extracted to break.
20
20
  */
21
21
  export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
@@ -3,12 +3,12 @@
3
3
  *
4
4
  * `ChannelContext` is the surface a `ChannelRunner` turn writes to: progress
5
5
  * updates, the final answer, side notices, and lifecycle hooks. The DingTalk
6
- * transport implements it via AI Card streaming (`runtime/delivery.ts`); the
6
+ * transport implements it via AI Card streaming (`dingtalk/delivery.ts`); the
7
7
  * terminal TUI implements it by rendering to the console (`tui/`). The runner
8
8
  * and `session-events` depend only on this interface, never on a concrete
9
9
  * transport.
10
10
  *
11
- * These declarations previously lived in `runtime/dingtalk.ts` under the name
11
+ * These declarations previously lived in `dingtalk/bot.ts` under the name
12
12
  * `DingTalkContext`; they were lifted out (and renamed) so a second transport
13
13
  * can implement the contract without importing anything DingTalk-specific. They
14
14
  * live in `src/channel/` rather than `src/runtime/` because a port belongs with
@@ -24,6 +24,16 @@ import type { InboundImage } from "./channel-event.js";
24
24
  export type ProgressStyle = "full" | "rolling" | "none";
25
25
  /** How the final answer is delivered. */
26
26
  export type FinalDelivery = "plain" | "card";
27
+ /**
28
+ * User-facing delivery preset (`channel.json` `responseMode`, `settings.json` `tui.responseMode`).
29
+ * Transport-neutral on purpose: the DingTalk bot and the TUI both map it onto
30
+ * `ProgressStyle` / `FinalDelivery` and nothing else should branch on the raw strings.
31
+ */
32
+ export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
33
+ export declare function progressStyleOf(mode: ResponseMode): ProgressStyle;
34
+ export declare function finalDeliveryOf(mode: ResponseMode): FinalDelivery;
35
+ export declare function isResponseModeConfig(value: unknown): value is ResponseMode;
36
+ export declare function normalizeResponseMode(value: unknown): ResponseMode;
27
37
  /**
28
38
  * A file the agent wants to push to a channel as a native attachment (image or
29
39
  * downloadable file), as opposed to text/markdown in the transcript.