@oyasmi/pipiclaw 0.9.3 → 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 (336) 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 +167 -1188
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.d.ts +3 -0
  10. package/dist/agent/prompt/resources.js +11 -2
  11. package/dist/agent/runner-factory.d.ts +1 -43
  12. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  13. package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
  14. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  15. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  16. package/dist/agent/session/model-selection.d.ts +47 -0
  17. package/dist/agent/session/model-selection.js +99 -0
  18. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  19. package/dist/agent/session/session-adapter.js +159 -0
  20. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  21. package/dist/agent/{session-events.js → session/session-events.js} +24 -13
  22. package/dist/agent/session/session-host.d.ts +200 -0
  23. package/dist/agent/session/session-host.js +621 -0
  24. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
  25. package/dist/agent/status-render.d.ts +0 -1
  26. package/dist/agent/status-render.js +4 -16
  27. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  28. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  29. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  30. package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
  31. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  32. package/dist/agent/turn/turn-context.d.ts +14 -0
  33. package/dist/agent/turn/turn-context.js +64 -0
  34. package/dist/agent/turn/turn-error.d.ts +31 -0
  35. package/dist/agent/turn/turn-error.js +68 -0
  36. package/dist/agent/turn/turn-finish.d.ts +50 -0
  37. package/dist/agent/turn/turn-finish.js +188 -0
  38. package/dist/agent/turn/turn-input.d.ts +43 -0
  39. package/dist/agent/turn/turn-input.js +79 -0
  40. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  41. package/dist/agent/turn/turn-pipeline.js +257 -0
  42. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  43. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  44. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  45. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  46. package/dist/agent/types.d.ts +43 -2
  47. package/dist/agent/types.js +1 -1
  48. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  49. package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
  50. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
  51. package/dist/{runtime/app-home.js → app/home.js} +22 -75
  52. package/dist/{runtime → app}/proxy.js +4 -2
  53. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  54. package/dist/{app-services.js → app/services.js} +17 -14
  55. package/dist/channel/channel-context.d.ts +12 -2
  56. package/dist/channel/channel-context.js +29 -2
  57. package/dist/channel/channel-event.d.ts +10 -2
  58. package/dist/channel/channel-event.js +1 -1
  59. package/dist/channel/channel-index.js +4 -1
  60. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  61. package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
  62. package/dist/channel/project-scope-store.js +1 -1
  63. package/dist/channel/store.js +4 -0
  64. package/dist/commands/catalog.d.ts +24 -7
  65. package/dist/commands/catalog.js +91 -44
  66. package/dist/commands/reply-limits.d.ts +6 -0
  67. package/dist/commands/reply-limits.js +24 -0
  68. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  69. package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
  70. package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
  71. package/dist/{settings.js → config/settings.js} +11 -11
  72. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  73. package/dist/{tools/config.js → config/tools.js} +5 -2
  74. package/dist/dingtalk/access-token.d.ts +12 -0
  75. package/dist/dingtalk/access-token.js +51 -0
  76. package/dist/dingtalk/api.d.ts +19 -0
  77. package/dist/dingtalk/api.js +67 -0
  78. package/dist/dingtalk/bot.d.ts +97 -0
  79. package/dist/dingtalk/bot.js +389 -0
  80. package/dist/dingtalk/cards.d.ts +56 -0
  81. package/dist/dingtalk/cards.js +318 -0
  82. package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
  83. package/dist/dingtalk/config.d.ts +19 -0
  84. package/dist/dingtalk/config.js +95 -0
  85. package/dist/dingtalk/connection.d.ts +57 -0
  86. package/dist/dingtalk/connection.js +356 -0
  87. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  88. package/dist/dingtalk/conversation-meta.js +77 -0
  89. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  90. package/dist/{runtime → dingtalk}/delivery.js +29 -15
  91. package/dist/dingtalk/handler.d.ts +90 -0
  92. package/dist/dingtalk/handler.js +1 -0
  93. package/dist/dingtalk/inbound.d.ts +66 -0
  94. package/dist/dingtalk/inbound.js +137 -0
  95. package/dist/dingtalk/media.d.ts +66 -0
  96. package/dist/dingtalk/media.js +214 -0
  97. package/dist/events/{event-commands.js → commands.js} +99 -45
  98. package/dist/events/parse.d.ts +14 -0
  99. package/dist/events/parse.js +114 -0
  100. package/dist/events/types.d.ts +93 -0
  101. package/dist/events/types.js +1 -0
  102. package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
  103. package/dist/events/{event-validation.js → validation.js} +17 -9
  104. package/dist/events/watcher.d.ts +67 -0
  105. package/dist/events/{events.js → watcher.js} +63 -121
  106. package/dist/executor.js +2 -2
  107. package/dist/index.d.ts +6 -4
  108. package/dist/index.js +2 -2
  109. package/dist/jobs/launch.d.ts +42 -0
  110. package/dist/jobs/launch.js +118 -0
  111. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  112. package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
  113. package/dist/jobs/record.d.ts +55 -0
  114. package/dist/jobs/record.js +36 -0
  115. package/dist/log.d.ts +12 -2
  116. package/dist/log.js +26 -34
  117. package/dist/main.js +3 -3
  118. package/dist/memory/commands.js +29 -23
  119. package/dist/memory/lifecycle.js +26 -5
  120. package/dist/memory/maintenance-gates.d.ts +2 -2
  121. package/dist/memory/maintenance-state.js +4 -1
  122. package/dist/memory/maintenance-tuning.d.ts +15 -0
  123. package/dist/memory/maintenance-tuning.js +3 -0
  124. package/dist/memory/reflect-job.d.ts +2 -2
  125. package/dist/memory/reflect-job.js +4 -2
  126. package/dist/memory/scheduler.d.ts +3 -3
  127. package/dist/memory/scheduler.js +5 -2
  128. package/dist/memory/sidecar-worker.js +1 -1
  129. package/dist/memory/transcript.js +1 -1
  130. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  131. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  132. package/dist/models/login-identity.d.ts +2 -0
  133. package/dist/models/login-identity.js +83 -0
  134. package/dist/models/provider-login.d.ts +3 -1
  135. package/dist/models/provider-login.js +8 -2
  136. package/dist/models/reference.d.ts +20 -0
  137. package/dist/models/{utils.js → reference.js} +0 -48
  138. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  139. package/dist/models/runtime.js +52 -0
  140. package/dist/paths.d.ts +2 -0
  141. package/dist/paths.js +9 -0
  142. package/dist/playbooks/agent-delegation.md +2 -2
  143. package/dist/playbooks/catalog.d.ts +6 -2
  144. package/dist/playbooks/catalog.js +9 -6
  145. package/dist/runtime/bootstrap.d.ts +7 -17
  146. package/dist/runtime/bootstrap.js +70 -659
  147. package/dist/runtime/durable-dispatch.d.ts +43 -4
  148. package/dist/runtime/durable-dispatch.js +153 -3
  149. package/dist/runtime/inbound-images.d.ts +18 -0
  150. package/dist/runtime/inbound-images.js +51 -0
  151. package/dist/runtime/shutdown.d.ts +39 -0
  152. package/dist/runtime/shutdown.js +120 -0
  153. package/dist/runtime/stop-watchdog.d.ts +16 -0
  154. package/dist/runtime/stop-watchdog.js +32 -0
  155. package/dist/runtime/task-driver.d.ts +6 -4
  156. package/dist/runtime/task-driver.js +58 -23
  157. package/dist/runtime/task-migration.js +25 -8
  158. package/dist/runtime/task-spawn.d.ts +1 -1
  159. package/dist/runtime/task-spawn.js +13 -6
  160. package/dist/runtime/turn-handler.d.ts +47 -0
  161. package/dist/runtime/turn-handler.js +318 -0
  162. package/dist/runtime/turn-run.d.ts +52 -0
  163. package/dist/runtime/turn-run.js +318 -0
  164. package/dist/runtime/wake-coalescing.d.ts +18 -0
  165. package/dist/runtime/wake-coalescing.js +29 -0
  166. package/dist/security/block-message.d.ts +22 -1
  167. package/dist/security/block-message.js +66 -1
  168. package/dist/security/command-guard.js +4 -0
  169. package/dist/security/network.d.ts +2 -1
  170. package/dist/security/network.js +7 -2
  171. package/dist/security/path-guard-check.js +2 -2
  172. package/dist/security/path-guard.js +4 -0
  173. package/dist/security/types.d.ts +1 -2
  174. package/dist/security/types.js +1 -2
  175. package/dist/shared/exact-keys.d.ts +1 -1
  176. package/dist/shared/format.d.ts +12 -0
  177. package/dist/shared/format.js +37 -0
  178. package/dist/shared/host-process.js +16 -4
  179. package/dist/shared/wake-claim.d.ts +1 -1
  180. package/dist/shared/with-timeout.d.ts +3 -2
  181. package/dist/shared/with-timeout.js +14 -3
  182. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  183. package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
  184. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  185. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  186. package/dist/skills/workspace.d.ts +33 -0
  187. package/dist/skills/workspace.js +116 -0
  188. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
  189. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
  190. package/dist/subagents/completion-wake.d.ts +17 -0
  191. package/dist/subagents/completion-wake.js +76 -0
  192. package/dist/subagents/detached-discovery.js +1 -1
  193. package/dist/subagents/discovery.d.ts +1 -1
  194. package/dist/subagents/discovery.js +2 -2
  195. package/dist/subagents/dispatch.d.ts +33 -0
  196. package/dist/subagents/dispatch.js +190 -0
  197. package/dist/subagents/external/claude-code.js +23 -1
  198. package/dist/subagents/external/dispatch.d.ts +25 -0
  199. package/dist/subagents/external/dispatch.js +90 -0
  200. package/dist/subagents/external/harness.d.ts +1 -1
  201. package/dist/subagents/external/progress-tail.d.ts +18 -1
  202. package/dist/subagents/external/progress-tail.js +64 -17
  203. package/dist/subagents/external/run.d.ts +5 -1
  204. package/dist/subagents/external/run.js +23 -9
  205. package/dist/subagents/external/settlement.d.ts +4 -1
  206. package/dist/subagents/external/settlement.js +1 -1
  207. package/dist/subagents/format.d.ts +1 -1
  208. package/dist/subagents/grace.d.ts +24 -0
  209. package/dist/subagents/grace.js +57 -0
  210. package/dist/subagents/internal/outcome.d.ts +24 -0
  211. package/dist/subagents/internal/outcome.js +149 -0
  212. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  213. package/dist/subagents/internal/provider-retry.js +83 -0
  214. package/dist/subagents/internal/run.d.ts +31 -0
  215. package/dist/subagents/internal/run.js +240 -0
  216. package/dist/subagents/internal/state.d.ts +43 -0
  217. package/dist/subagents/internal/state.js +48 -0
  218. package/dist/subagents/internal/worker.d.ts +51 -0
  219. package/dist/subagents/internal/worker.js +167 -0
  220. package/dist/subagents/result.d.ts +62 -0
  221. package/dist/subagents/result.js +103 -0
  222. package/dist/subagents/run-record.d.ts +222 -0
  223. package/dist/subagents/run-record.js +101 -0
  224. package/dist/subagents/run-registry.d.ts +9 -0
  225. package/dist/subagents/run-registry.js +125 -0
  226. package/dist/subagents/runs.d.ts +16 -232
  227. package/dist/subagents/runs.js +132 -310
  228. package/dist/subagents/task-envelope.d.ts +36 -0
  229. package/dist/subagents/task-envelope.js +168 -0
  230. package/dist/subagents/types.d.ts +154 -0
  231. package/dist/subagents/types.js +1 -0
  232. package/dist/subagents/verification-outcome.d.ts +1 -1
  233. package/dist/subagents/workspace-summary.d.ts +16 -4
  234. package/dist/subagents/workspace-summary.js +74 -18
  235. package/dist/tasks/board.d.ts +10 -3
  236. package/dist/tasks/board.js +38 -3
  237. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  238. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  239. package/dist/tasks/brief.js +1 -1
  240. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  241. package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
  242. package/dist/tasks/contract-input.d.ts +1 -1
  243. package/dist/tasks/contract-input.js +1 -1
  244. package/dist/tasks/create.js +1 -1
  245. package/dist/tasks/frontmatter.d.ts +5 -0
  246. package/dist/tasks/frontmatter.js +8 -0
  247. package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
  248. package/dist/tasks/{log.js → loop-log.js} +59 -3
  249. package/dist/tasks/mutation-lock.js +1 -1
  250. package/dist/tasks/session-path.js +1 -1
  251. package/dist/tasks/steer.js +1 -1
  252. package/dist/tasks/store.js +6 -4
  253. package/dist/tasks/ticket.d.ts +3 -1
  254. package/dist/tasks/ticket.js +19 -1
  255. package/dist/tools/bash.d.ts +1 -1
  256. package/dist/tools/bash.js +2 -2
  257. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
  258. package/dist/tools/{tool-details.js → contract/details.js} +42 -5
  259. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  260. package/dist/tools/event-manage.d.ts +1 -1
  261. package/dist/tools/event-manage.js +4 -4
  262. package/dist/tools/index.d.ts +5 -3
  263. package/dist/tools/index.js +8 -6
  264. package/dist/tools/job.d.ts +1 -1
  265. package/dist/tools/memory-manage.js +4 -1
  266. package/dist/tools/registry.d.ts +7 -7
  267. package/dist/tools/registry.js +6 -6
  268. package/dist/tools/session-search.d.ts +1 -1
  269. package/dist/tools/skill.d.ts +2 -34
  270. package/dist/tools/skill.js +8 -116
  271. package/dist/tools/subagent-manage.d.ts +1 -1
  272. package/dist/tools/subagent-manage.js +19 -13
  273. package/dist/tools/subagent.d.ts +46 -0
  274. package/dist/tools/subagent.js +127 -0
  275. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  276. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  277. package/dist/tools/task-manage/lifecycle.js +2 -2
  278. package/dist/tools/task-manage/log-view.js +2 -2
  279. package/dist/tools/task-manage/shared.js +3 -3
  280. package/dist/tools/task-manage/step-end.js +7 -4
  281. package/dist/tools/task-manage/types.d.ts +1 -1
  282. package/dist/tools/web-fetch.d.ts +1 -1
  283. package/dist/tools/web-search.d.ts +1 -1
  284. package/dist/tui/app.d.ts +1 -1
  285. package/dist/tui/app.js +6 -6
  286. package/dist/tui/cli.d.ts +1 -1
  287. package/dist/tui/cli.js +3 -3
  288. package/dist/tui/commands.js +4 -4
  289. package/dist/tui/frontend.d.ts +44 -0
  290. package/dist/tui/frontend.js +13 -0
  291. package/dist/tui/pitui-frontend.d.ts +1 -1
  292. package/dist/tui/pitui-frontend.js +1 -1
  293. package/dist/tui/plain-frontend.d.ts +1 -1
  294. package/dist/tui/renderer.d.ts +3 -42
  295. package/dist/tui/renderer.js +3 -2
  296. package/dist/tui/terminal-context.d.ts +2 -2
  297. package/dist/tui/terminal-media-sender.d.ts +1 -1
  298. package/dist/tui/turn-controller.d.ts +3 -1
  299. package/dist/tui/turn-controller.js +36 -21
  300. package/dist/usage/ledger.js +7 -1
  301. package/dist/usage/render.js +3 -1
  302. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  303. package/dist/web/client.d.ts +5 -1
  304. package/dist/web/client.js +4 -0
  305. package/dist/web/config.d.ts +1 -1
  306. package/dist/web/fetch.d.ts +1 -1
  307. package/dist/web/search-providers.d.ts +1 -1
  308. package/dist/web/search.d.ts +1 -1
  309. package/package.json +9 -7
  310. package/dist/agent/session-adapter.js +0 -77
  311. package/dist/events/events.d.ts +0 -159
  312. package/dist/runtime/dingtalk.d.ts +0 -272
  313. package/dist/runtime/dingtalk.js +0 -1416
  314. package/dist/subagents/tool.d.ts +0 -206
  315. package/dist/subagents/tool.js +0 -1088
  316. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  317. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  318. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  319. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  320. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  321. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  322. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  323. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  324. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  325. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  326. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  327. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  328. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  329. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  330. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  331. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  332. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  333. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  334. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  335. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  336. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Preparing a user's input for a turn: the timestamped message line, oversized-input spill to disk,
3
+ * raw-passthrough detection for slash commands, and inbound images turned into `ImageContent`.
4
+ */
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { MAX_INBOUND_IMAGE_BYTES } from "../../channel/channel-event.js";
8
+ import * as log from "../../log.js";
9
+ import { formatModelReference } from "../../models/reference.js";
10
+ import { formatLocalTime, localStampForFilename } from "../../shared/local-time.js";
11
+ import { errorMessage } from "../../shared/text-utils.js";
12
+ import { formatSize } from "../../tools/truncate.js";
13
+ export function shouldPreserveRawInput(text) {
14
+ return text.trim().startsWith("/");
15
+ }
16
+ /**
17
+ * Save a message that exceeds the per-turn input budget so its clipped middle stays reachable.
18
+ *
19
+ * Pasting a long build log or diff is a normal way to start driving work here, and the clip
20
+ * keeps head and tail — which is where the failing frames usually are *not*. Landing the
21
+ * original under the channel directory puts it inside the paths `read` already allows, so
22
+ * recovery is the ordinary paging path rather than a special case.
23
+ *
24
+ * Best-effort: if the write fails the turn still runs on the clipped text, just without a
25
+ * pointer.
26
+ */
27
+ export async function persistOversizedInput(channelDir, channelId, text) {
28
+ try {
29
+ const dir = join(channelDir, "inbox");
30
+ await mkdir(dir, { recursive: true });
31
+ const path = join(dir, `message-${localStampForFilename()}.txt`);
32
+ await writeFile(path, text.replace(/\r/g, ""), { mode: 0o600 });
33
+ return path;
34
+ }
35
+ catch (error) {
36
+ log.logWarn("agent.input.persist_failed", "Oversized user message could not be saved", {
37
+ channelId: channelId,
38
+ reason: errorMessage(error),
39
+ });
40
+ return undefined;
41
+ }
42
+ }
43
+ export function formatUserMessage(text, userName, now = new Date()) {
44
+ return `[${formatLocalTime(now)}] [${userName || "unknown"}]: ${text}`;
45
+ }
46
+ export async function prepareInboundImages(images, model) {
47
+ if (!images || images.length === 0) {
48
+ return { images: [], notices: [] };
49
+ }
50
+ if (!model.input.includes("image")) {
51
+ const modelRef = formatModelReference(model);
52
+ return {
53
+ images: [],
54
+ notices: [
55
+ `⚠️ 当前模型 ${modelRef} 不支持图片输入,收到的图片已保存但未加入本轮上下文:\n` +
56
+ images.map((image) => `- \`${image.path}\``).join("\n") +
57
+ "\n用 `/model` 切换到支持图片的模型后,再让我读取这些图片。",
58
+ ],
59
+ };
60
+ }
61
+ const contents = [];
62
+ const notices = [];
63
+ for (const image of images) {
64
+ if (image.unsupportedFormat)
65
+ continue;
66
+ if (image.byteSize > MAX_INBOUND_IMAGE_BYTES) {
67
+ notices.push(`⚠️ 图片 \`${image.path}\`(${formatSize(image.byteSize)})超过 ${formatSize(MAX_INBOUND_IMAGE_BYTES)} 上限,未加入本轮上下文;需要时让我读取这个文件。`);
68
+ continue;
69
+ }
70
+ try {
71
+ const data = await readFile(image.path);
72
+ contents.push({ type: "image", data: data.toString("base64"), mimeType: image.mimeType });
73
+ }
74
+ catch (error) {
75
+ notices.push(`⚠️ 图片 \`${image.path}\` 读取失败:${errorMessage(error)}`);
76
+ }
77
+ }
78
+ return { images: contents, notices };
79
+ }
@@ -0,0 +1,68 @@
1
+ import type { ChannelContext } from "../../channel/channel-context.js";
2
+ import type { InboundImage } from "../../channel/channel-event.js";
3
+ import type { FallbackRunDeps } from "../../models/fallback.js";
4
+ import type { ModelSelection } from "../session/model-selection.js";
5
+ import type { SessionHost } from "../session/session-host.js";
6
+ import { type RunState } from "../types.js";
7
+ import type { createRunQueue } from "./run-queue.js";
8
+ import { type PreparedInboundImages } from "./turn-input.js";
9
+ import type { TurnHandle, TurnStateMachine } from "./turn-state.js";
10
+ /** What `run()` accumulates across its steps; the epilogue reports it as the turn was actually sent. */
11
+ export interface TurnProgress {
12
+ promptSubmitted: boolean;
13
+ fallbackAttempted: boolean;
14
+ fallbackTargetRef: string | undefined;
15
+ promptText: string;
16
+ taskDigestText: string;
17
+ durableMemoryBootstrapText: string;
18
+ bootstrapPrepared: boolean;
19
+ images: PreparedInboundImages;
20
+ }
21
+ export declare function createTurnProgress(): TurnProgress;
22
+ export interface TurnPipelineDeps {
23
+ channelId: string;
24
+ channelDir: string;
25
+ workspaceDir: string;
26
+ host: SessionHost;
27
+ models: ModelSelection;
28
+ turnState: TurnStateMachine;
29
+ isRetired: () => boolean;
30
+ /** The live run state: `ChannelRunner` replaces it at the start of every run. */
31
+ getRunState: () => RunState;
32
+ }
33
+ export declare class TurnPipeline {
34
+ private readonly deps;
35
+ private readonly channelId;
36
+ private readonly channelDir;
37
+ private readonly workspaceDir;
38
+ private readonly host;
39
+ private readonly models;
40
+ private readonly turnState;
41
+ constructor(deps: TurnPipelineDeps);
42
+ private get runState();
43
+ private get session();
44
+ /** Oversized input is spilled to disk and clipped; the user is told. Slash commands pass through raw. */
45
+ prepareUserInput(ctx: ChannelContext): Promise<{
46
+ clippedInput: string;
47
+ userMessage: string;
48
+ preserveRawInput: boolean;
49
+ }>;
50
+ /**
51
+ * The turn-dynamic context: the channel capsule (returned) plus, recorded on `turn`, the task
52
+ * digest and the first-turn memory bootstrap. A raw-passthrough input (a slash command) gets none.
53
+ */
54
+ gatherTurnContext(preserveRawInput: boolean, turn: TurnProgress): Promise<string>;
55
+ /** Inbound images for the current model, with a notice to the user for each one that was left out. */
56
+ prepareTurnImages(ctx: ChannelContext): Promise<PreparedInboundImages>;
57
+ /** The seams `runPromptWithFallback` drives: submit the prompt, observe/reset the error, switch model. */
58
+ buildFallbackDeps(ctx: ChannelContext, runQueue: ReturnType<typeof createRunQueue>, turn: TurnProgress, ownTurn: TurnHandle): FallbackRunDeps;
59
+ /**
60
+ * Single source of truth for the busy-message window: steer is accepted while
61
+ * the prompt is being assembled ("preparing") or while the agent loop is
62
+ * actually streaming. Re-asserted after every await because the turn can end
63
+ * while this call was suspended.
64
+ */
65
+ private assertBusyWindowOpen;
66
+ queueBusyMessage(text: string, userName?: string, images?: InboundImage[]): Promise<void>;
67
+ maybeRunPreventiveCompactionForIncomingText(incomingText: string, imageCount?: number): Promise<void>;
68
+ }
@@ -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,12 +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";
11
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
12
- import { ReadlineLoginUi } from "./login-ui.js";
13
- import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
14
- import { createModelRuntime, formatModelReference } from "./utils.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";
14
+ import { docsUrl } from "../paths.js";
15
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "./home.js";
16
+ import { prepareAppServices } from "./services.js";
15
17
  /** Parse `pipiclaw auth` arguments (everything after the `auth` subcommand, including the subcommand name itself). */
16
18
  export function parseAuthArgs(args) {
17
19
  if (args.length === 0) {
@@ -172,7 +174,7 @@ function auditAuthEvent(action, providerId, authType, ok) {
172
174
  // token/secret fragment.
173
175
  log.logInfo(`auth ${action}: ${providerId}${authType ? ` (${authType})` : ""} — ${ok ? "ok" : "failed"}`);
174
176
  }
175
- async function runLogin(runtime, parsed, io, signal) {
177
+ async function runLogin(runtime, parsed, io, signal, paths) {
176
178
  const ui = new ReadlineLoginUi({
177
179
  signal,
178
180
  presetFirstSelect: parsed.deviceCode ? "device_code" : undefined,
@@ -182,12 +184,14 @@ async function runLogin(runtime, parsed, io, signal) {
182
184
  const target = await resolveLoginTarget(runtime, parsed, ui);
183
185
  if (target.kind === "unsupported") {
184
186
  io.error(`"${target.name}" uses ambient credentials (environment variables / local config files), not interactive login.`);
185
- io.error("See docs/configuration.md for how to configure it.");
187
+ io.error(`See ${docsUrl("configuration.md")} for how to configure it.`);
186
188
  throw new BootstrapExitError(1);
187
189
  }
188
190
  let result;
189
191
  try {
190
- result = await loginProvider(runtime, target.providerId, target.authType, ui);
192
+ result = await loginProvider(runtime, target.providerId, target.authType, ui, {
193
+ appHomeDir: paths.appHomeDir,
194
+ });
191
195
  }
192
196
  catch (error) {
193
197
  auditAuthEvent("login", target.providerId, target.authType, false);
@@ -213,7 +217,7 @@ async function runLogin(runtime, parsed, io, signal) {
213
217
  io.log("");
214
218
  io.log("Warning: PIPICLAW_PROXY is set but HTTPS_PROXY/HTTP_PROXY is not. Codex chat traffic uses a " +
215
219
  "WebSocket transport that only honors HTTPS_PROXY/HTTP_PROXY and may connect directly — see " +
216
- "docs/configuration.md.");
220
+ `${docsUrl("configuration.md")}.`);
217
221
  }
218
222
  }
219
223
  catch (error) {
@@ -333,7 +337,7 @@ export async function runAuth(argv, io = console, paths = DEFAULT_BOOTSTRAP_PATH
333
337
  process.once("SIGINT", onSigint);
334
338
  try {
335
339
  if (parsed.kind === "login") {
336
- await runLogin(runtime, parsed, io, controller.signal);
340
+ await runLogin(runtime, parsed, io, controller.signal, paths);
337
341
  }
338
342
  else {
339
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;
@@ -28,7 +27,12 @@ export declare function isBootstrapExitError(error: unknown): error is Bootstrap
28
27
  export declare function readCliVersion(): string;
29
28
  export declare function bootstrapAppHome(paths?: BootstrapPaths): BootstrapResult;
30
29
  export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
31
- export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
30
+ /**
31
+ * What a new deployer does after the very first run created the templates (spec 053, D11). A
32
+ * fresh template is not an error, so the caller exits 0 after this; it names the required fields,
33
+ * where they come from, and the model credential step the daemon cannot run without.
34
+ */
35
+ export declare function printFirstRunGuide(io?: BootstrapIO, paths?: BootstrapPaths): void;
32
36
  /**
33
37
  * The one place that lists `pipiclaw`'s top-level subcommands. `parseArgs`'s own `--help` uses it;
34
38
  * `main.ts`'s unknown-subcommand branch used to hand-copy the same three lines separately (review