@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +10 -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,318 @@
1
+ import { muteChannelContext } from "../channel/channel-context.js";
2
+ import { ensureChannelDir } from "../channel/channel-paths.js";
3
+ import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
4
+ import { createDingTalkContext } from "../dingtalk/delivery.js";
5
+ import * as log from "../log.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
7
+ import { buildTaskStepBrief } from "../tasks/brief.js";
8
+ import { consumeTaskNotice } from "../tasks/steer.js";
9
+ import { relativeImagePaths } from "./inbound-images.js";
10
+ import { parseDriverTaskId } from "./task-driver.js";
11
+ import { claimVerifiedWake } from "./task-wake.js";
12
+ import { isCoalescableWake, MAX_COALESCED_WAKES, mergeCompletionWakes } from "./wake-coalescing.js";
13
+ /**
14
+ * The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
15
+ * *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
16
+ * exception even though it isn't runner-handled while busy (see the busy-path switch in
17
+ * `dingtalk/bot.ts`): idle answers it through the runner's ChannelContext-aware command path
18
+ * (thread-reply, delete semantics) instead, so it is routed like the runner-handled built-ins
19
+ * here and excluded from this stateless-report set.
20
+ */
21
+ const IDLE_RUNTIME_COMMAND_NAMES = new Set(BUILT_IN_COMMANDS.filter((command) => !command.runnerHandled).map((command) => command.name));
22
+ function isIdleRuntimeCommandName(name) {
23
+ return IDLE_RUNTIME_COMMAND_NAMES.has(name);
24
+ }
25
+ /**
26
+ * The turn pipeline behind `DingTalkHandler.handleEvent`: admit the dispatch, run commands or the
27
+ * agent (as a task step when the wake is one), and always settle the dispatch and release the turn.
28
+ */
29
+ export function createEventTurnRunner(deps) {
30
+ const { options, store, activeTasks, archiveIncomingMessage, getRunner, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
31
+ /**
32
+ * Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
33
+ * cycle's own session and replace the wake text with the step brief. Returns `undefined` for
34
+ * every other event, which then follows the unchanged chat path.
35
+ *
36
+ * Binding failures fall back to the chat path rather than dropping the wake — a task that
37
+ * cannot open its session should still be visible, not silently skipped.
38
+ */
39
+ const prepareTaskStep = async (event, runner) => {
40
+ const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
41
+ if (!taskId)
42
+ return undefined;
43
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
44
+ try {
45
+ const brief = await buildTaskStepBrief({ channelDir, taskId });
46
+ if (!brief)
47
+ return undefined;
48
+ await runner.bindTaskSession(taskId);
49
+ return { taskId, brief };
50
+ }
51
+ catch (error) {
52
+ log.logWarn("taskdriver.step.start_failed", "Task step start failed", {
53
+ channelId: event.channelId,
54
+ reason: errorMessage(error),
55
+ fields: { taskId },
56
+ });
57
+ return undefined;
58
+ }
59
+ };
60
+ /** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
61
+ const finishTaskStep = async (channelId, taskId, bot) => {
62
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
63
+ try {
64
+ const notice = await consumeTaskNotice(channelDir, taskId);
65
+ if (notice) {
66
+ // runner.run closes its per-turn delivery context before returning. Sending through that
67
+ // closed context silently dropped successful task_step_end notifications (T-run-01).
68
+ const delivered = await bot.sendPlain(channelId, notice);
69
+ if (delivered)
70
+ await store.logBotResponse(channelId, notice, Date.now().toString());
71
+ else
72
+ log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
73
+ channelId: channelId,
74
+ fields: { taskId },
75
+ });
76
+ }
77
+ }
78
+ catch (error) {
79
+ log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
80
+ channelId: channelId,
81
+ reason: errorMessage(error),
82
+ fields: { taskId },
83
+ });
84
+ }
85
+ await getRunner(channelId).bindChatSession();
86
+ };
87
+ /**
88
+ * Dispatch admission: refuse a stale redelivery of a wake an earlier turn already handled (the
89
+ * turn is released), and fold other pending completion wakes into this one. `undefined` = skip.
90
+ */
91
+ const admitTurn = async (inboundEvent, runner) => {
92
+ let event = inboundEvent;
93
+ const durable = getDurableDispatch();
94
+ // Sampled synchronously, before any await: `/stop` after this point cleared the queued closures.
95
+ const stopEpoch = durable?.stopEpoch(inboundEvent.channelId) ?? 0;
96
+ if (durable && !(await durable.markStarted(event.dispatchId))) {
97
+ // A stale delivery of a wake an earlier turn already absorbed and handled.
98
+ runner.endTurn();
99
+ return undefined;
100
+ }
101
+ const structuredWakeFinalized = event.internalWake === undefined;
102
+ let absorbedDispatchIds = [];
103
+ if (durable && event.dispatchId && isCoalescableWake(event)) {
104
+ const absorbed = await durable
105
+ .absorbPending(event.channelId, event.dispatchId, isCoalescableWake, MAX_COALESCED_WAKES - 1, stopEpoch)
106
+ .catch((error) => {
107
+ log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
108
+ channelId: event.channelId,
109
+ reason: errorMessage(error),
110
+ });
111
+ return [];
112
+ });
113
+ if (absorbed.length > 0) {
114
+ event = mergeCompletionWakes(event, absorbed);
115
+ absorbedDispatchIds = absorbed.flatMap((absorbedEvent) => absorbedEvent.dispatchId ? [absorbedEvent.dispatchId] : []);
116
+ log.logInfoEvent("dispatch.wake.coalesced", "Completion wakes coalesced", {
117
+ channelId: event.channelId,
118
+ fields: { primary: event.dispatchId, absorbed: absorbedDispatchIds.length },
119
+ });
120
+ }
121
+ }
122
+ return { event, baseCtx: undefined, structuredWakeFinalized, absorbedDispatchIds, mergedWakesHandled: false };
123
+ };
124
+ /** A built-in slash command typed on an idle channel: stateless reports here, session commands on the runner. */
125
+ const runBuiltinCommand = async (turn, builtInCommand, runner, ctx, bot) => {
126
+ const { event } = turn;
127
+ const commandStartedAt = Date.now();
128
+ const logCtx = { channelId: event.channelId, userName: event.userName };
129
+ log.logEvent("info", "runtime.command.started", "Executing command", {
130
+ ctx: logCtx,
131
+ fields: { command: builtInCommand.name },
132
+ });
133
+ try {
134
+ if (isIdleRuntimeCommandName(builtInCommand.name)) {
135
+ const response = await deps.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
136
+ const delivered = await bot.sendPlain(event.channelId, response, {
137
+ title: `/${builtInCommand.name}`,
138
+ markdown: true,
139
+ });
140
+ if (!delivered) {
141
+ log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
142
+ channelId: event.channelId,
143
+ fields: { command: builtInCommand.name, chars: response.length },
144
+ });
145
+ }
146
+ }
147
+ else if (isRunnerBuiltInCommand(builtInCommand)) {
148
+ await runner.handleBuiltinCommand(ctx, builtInCommand);
149
+ }
150
+ log.logEvent("info", "runtime.command.completed", "Command completed", {
151
+ ctx: logCtx,
152
+ fields: { command: builtInCommand.name, durationMs: Date.now() - commandStartedAt },
153
+ });
154
+ }
155
+ catch (err) {
156
+ log.logEvent("warn", "runtime.command.failed", "Command failed", {
157
+ ctx: logCtx,
158
+ fields: {
159
+ command: builtInCommand.name,
160
+ durationMs: Date.now() - commandStartedAt,
161
+ error: errorMessage(err),
162
+ },
163
+ });
164
+ throw err;
165
+ }
166
+ };
167
+ /**
168
+ * A completion wake for a task's job or delegation: verified against the resource's own record
169
+ * before it may reopen the task (see `claimVerifiedWake`). Plain "belongs to task" text in a
170
+ * message never counts — only the producer-created `internalWake` envelope. Returns whether the
171
+ * turn should still run.
172
+ */
173
+ const verifyInternalWake = async (turn, internalWake) => {
174
+ const { event } = turn;
175
+ const { kind, resourceId, taskId: wakeTaskId } = internalWake;
176
+ const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
177
+ if (!claimed) {
178
+ log.logWarn("dispatch.wake.unverified", "Unverifiable wake ignored", {
179
+ channelId: event.channelId,
180
+ fields: { kind, resourceId, taskId: wakeTaskId },
181
+ });
182
+ turn.structuredWakeFinalized = true;
183
+ return false;
184
+ }
185
+ await claimed.finish();
186
+ turn.structuredWakeFinalized = true;
187
+ // Drop without a turn only when something else is still driving this task (a sibling
188
+ // wake in the same fan-out already reopened it); in every other case nobody else will
189
+ // look at this result, so it still reaches a normal turn.
190
+ return claimed.activated || !claimed.taskStillDriven;
191
+ };
192
+ /** The turn proper: archive, route commands, verify wakes, then run the agent (as a task step if one). */
193
+ const executeTurn = async (turn, runner, bot, backgroundOnly) => {
194
+ const { event } = turn;
195
+ // Computed before archiving so a command's own text can be excluded from
196
+ // memory-extraction input (review 2026-08-24 §1.2): it is control-plane
197
+ // traffic, not conversation, and the history stays queryable via session_search.
198
+ const builtInCommand = parseBuiltInCommand(event.text);
199
+ await archiveIncomingMessage(event.channelId, {
200
+ date: new Date().toISOString(),
201
+ ts: event.ts,
202
+ user: event.user,
203
+ userName: event.userName,
204
+ text: event.text,
205
+ isBot: false,
206
+ skipContextSync: Boolean(builtInCommand),
207
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
208
+ }, "user message");
209
+ // Background wakes deliver their result, not their process: no progress card, no
210
+ // thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
211
+ // Awaited completions deliver their result too, without opening another progress card.
212
+ // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
213
+ // own session, with a brief instead of the wake text, and silent unless the step
214
+ // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
215
+ // only which session the turn is bound to, and what reaches the channel, differ.
216
+ let baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
217
+ turn.baseCtx = baseCtx;
218
+ let ctx = baseCtx;
219
+ if (builtInCommand) {
220
+ await runBuiltinCommand(turn, builtInCommand, runner, ctx, bot);
221
+ return;
222
+ }
223
+ // Reject an unknown slash command instead of spending a full LLM turn
224
+ // letting the model guess what `/modle` meant. Session commands,
225
+ // skills, and prompt templates are recognized by isKnownSlashCommand.
226
+ if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
227
+ const name = slashCommandName(event.text) ?? "";
228
+ await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
229
+ return;
230
+ }
231
+ log.logEvent("info", "agent.turn.started", "Starting turn", {
232
+ ctx: { channelId: event.channelId, userName: event.userName },
233
+ fields: { messageLength: event.text.length, source: backgroundOnly ? "event" : "message" },
234
+ });
235
+ if (event.internalWake && !(await verifyInternalWake(turn, event.internalWake)))
236
+ return;
237
+ // Verified job/run wakes that activate a task are task steps too. Verification must happen
238
+ // first: routing directly from user-controlled wake text would grant task-only tools.
239
+ const taskStep = await prepareTaskStep(turn.event, runner);
240
+ if (taskStep) {
241
+ await baseCtx.close();
242
+ turn.event = { ...turn.event, text: taskStep.brief };
243
+ baseCtx = createDingTalkContext(turn.event, bot, store, "none");
244
+ turn.baseCtx = baseCtx;
245
+ ctx = muteChannelContext(baseCtx);
246
+ }
247
+ if (!backgroundOnly && !taskStep)
248
+ ctx.primeCard(1500);
249
+ const result = await runner.run(ctx, store);
250
+ turn.mergedWakesHandled = result.stopReason !== "aborted" && result.stopReason !== "error";
251
+ if (taskStep)
252
+ await finishTaskStep(turn.event.channelId, taskStep.taskId, bot);
253
+ if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
254
+ log.logInfoEvent("agent.turn.stopped", "Turn stopped", { channelId: turn.event.channelId });
255
+ }
256
+ };
257
+ /** Always runs: close delivery, settle the dispatch records, release the turn, nudge the task driver. */
258
+ const finishTurn = async (turn, runner) => {
259
+ const { event } = turn;
260
+ await turn.baseCtx?.close().catch((error) => {
261
+ log.logWarn("delivery.close.failed", "Delivery close failed", {
262
+ channelId: event.channelId,
263
+ reason: errorMessage(error),
264
+ });
265
+ });
266
+ if (turn.structuredWakeFinalized)
267
+ await getDurableDispatch()?.markCompleted(event.dispatchId);
268
+ else
269
+ await getDurableDispatch()?.markRetryable(event.dispatchId);
270
+ // A stopped turn has not finished handling its merged notifications. Release their
271
+ // claims even if /stop's asynchronous cancelChannel reset raced admission or failed.
272
+ const stopped = !turn.mergedWakesHandled || runner.getTurnStatus().stopRequested;
273
+ for (const absorbedId of turn.absorbedDispatchIds) {
274
+ if (stopped)
275
+ await getDurableDispatch()?.markRetryable(absorbedId);
276
+ else
277
+ await getDurableDispatch()?.markCompleted(absorbedId);
278
+ }
279
+ runner.endTurn();
280
+ // A finished turn may have written task files; rescan now so `outcome: continue`
281
+ // queues the next step immediately instead of waiting out the current sleep.
282
+ getTaskDriver().nudge?.();
283
+ };
284
+ const runEventTurn = async (inboundEvent, bot, isEvent) => {
285
+ if (isShuttingDown()) {
286
+ log.logInfoEvent("runtime.shutdown.event_ignored", "Event ignored during shutdown", {
287
+ channelId: inboundEvent.channelId,
288
+ });
289
+ return;
290
+ }
291
+ const runner = getRunner(inboundEvent.channelId);
292
+ const turn = await admitTurn(inboundEvent, runner);
293
+ if (!turn)
294
+ return;
295
+ const task = (async () => {
296
+ try {
297
+ await executeTurn(turn, runner, bot, Boolean(isEvent));
298
+ }
299
+ catch (err) {
300
+ log.logEvent("error", "agent.turn.failed", "Turn failed", {
301
+ ctx: { channelId: turn.event.channelId, userName: turn.event.userName },
302
+ fields: { error: errorMessage(err) },
303
+ });
304
+ }
305
+ finally {
306
+ await finishTurn(turn, runner);
307
+ }
308
+ })();
309
+ activeTasks.add(task);
310
+ try {
311
+ await task;
312
+ }
313
+ finally {
314
+ activeTasks.delete(task);
315
+ }
316
+ };
317
+ return runEventTurn;
318
+ }
@@ -1,3 +1,7 @@
1
+ /**
2
+ * The command guard: decides whether a shell command may run, against the configured allow/deny
3
+ * rules and a wrapper-aware scan of every place a command can start.
4
+ */
1
5
  import { basename } from "node:path";
2
6
  import { stripNullAndNormalize } from "../shared/text-utils.js";
3
7
  const WHITESPACE = /\s+/;
@@ -1,3 +1,7 @@
1
+ /**
2
+ * The network guard for the web tools: URL and redirect validation, and rejection of private,
3
+ * loopback and link-local targets (including IPv4-mapped IPv6).
4
+ */
1
5
  import { lookup } from "node:dns/promises";
2
6
  import { isIP } from "node:net";
3
7
  import { errorMessage } from "../shared/text-utils.js";
@@ -1,3 +1,7 @@
1
+ /**
2
+ * The path guard: resolves a requested path once against the project scope and the read/write allow and
3
+ * deny lists, and returns the resolved path that file tools must then use.
4
+ */
1
5
  import { existsSync, lstatSync, realpathSync } from "node:fs";
2
6
  import { homedir, tmpdir } from "node:os";
3
7
  import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
@@ -37,8 +37,7 @@ export interface SecurityConfig {
37
37
  };
38
38
  }
39
39
  /**
40
- * Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
41
- * that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
40
+ * Every top-level `security.json` key. Kept in sync with `SecurityConfig` by
42
41
  * `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
43
42
  * no entry here) — both at `npm run typecheck`.
44
43
  */
@@ -1,6 +1,5 @@
1
1
  /**
2
- * Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
3
- * that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
2
+ * Every top-level `security.json` key. Kept in sync with `SecurityConfig` by
4
3
  * `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
5
4
  * no entry here) — both at `npm run typecheck`.
6
5
  */
@@ -3,7 +3,7 @@
3
3
  * the result to a `const` typed `true` (then `void` it to satisfy `noUnusedLocals`): if `K` is
4
4
  * missing any key of `T`, the check's type becomes `never` and the assignment fails to
5
5
  * typecheck. This is what keeps a documentation-coverage test's key list (e.g.
6
- * `SETTINGS_TOP_LEVEL_KEYS` in `settings.ts`) from silently drifting out of sync with the
6
+ * `SETTINGS_TOP_LEVEL_KEYS` in `config/settings.ts`) from silently drifting out of sync with the
7
7
  * interface it documents when a field is added — `npm run typecheck` catches it, not a human
8
8
  * remembering to update two places.
9
9
  *
@@ -4,7 +4,7 @@ import { promisify } from "node:util";
4
4
  * Stateless host-process operations shared by background jobs and external delegation runs
5
5
  * (spec 040, D1): a liveness probe and a process-group kill. Nothing here is job- or run-specific
6
6
  * — both callers bring their own persisted pid and decide what "gone" means for their own state
7
- * machine. `job-manager.ts` still probes through its shell `Executor` (its jobs are shell
7
+ * machine. `jobs/manager.ts` still probes through its shell `Executor` (its jobs are shell
8
8
  * children); this is for callers that spawn argv-direct, detached children of their own (D3/D4).
9
9
  */
10
10
  const execFileAsync = promisify(execFile);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The two-phase "claim, then finish" decision shared by `job-manager.ts` and `subagents/runs.ts`
2
+ * The two-phase "claim, then finish" decision shared by `jobs/manager.ts` and `subagents/runs.ts`
3
3
  * for reserving a completion wake exactly once (spec 040, D7/T9). Both managers persist a
4
4
  * `RunRecord`/`JobRecord` differently and gate eligibility on a different terminal condition
5
5
  * (job: `status !== "running"`; run: `settledAt` set), so only the claim/consume decision on the
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * `/skills` — the human control path for a workspace's skill catalog (spec 045's read-only
3
- * `skill` tool has no channel-command counterpart until now). Mirrors `project-commands.ts`'s
3
+ * `skill` tool has no channel-command counterpart until now). Mirrors `channel/commands.ts`'s
4
4
  * shape: pure-ish functions returning markdown, no bot/event coupling.
5
5
  *
6
6
  * Deliberately a disk scan via `listWorkspaceSkills`, not the live `ChannelRunner`'s already-
7
7
  * loaded catalog: that keeps `/skills` usable while a turn is streaming and for a channel with no
8
8
  * active runner, and — the whole reason this exists rather than reusing `/help`'s discovery tail
9
9
  * — it is the only place that shows a skill that failed the content scan and was silently dropped
10
- * from the prompt's skill list (`src/agent/workspace-resources.ts`).
10
+ * from the prompt's skill list (`src/skills/loader.ts`).
11
11
  */
12
12
  export interface HandleSkillsCommandOptions {
13
13
  args: string;
@@ -4,7 +4,7 @@ import { GuardBlockedError, renderGuardBlockForUser } from "../security/block-me
4
4
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
5
5
  import { RecoverableToolError } from "../shared/recoverable-error.js";
6
6
  import { errorMessage } from "../shared/text-utils.js";
7
- import { listWorkspaceSkills, loadWorkspaceSkillFile } from "../tools/skill.js";
7
+ import { listWorkspaceSkills, loadWorkspaceSkillFile } from "./workspace.js";
8
8
  function usage() {
9
9
  return renderSubcommandUsage("skills");
10
10
  }
@@ -7,7 +7,7 @@
7
7
  import { readFileSync } from "node:fs";
8
8
  import { loadSkillsFromDir } from "@earendil-works/pi-coding-agent";
9
9
  import { join } from "path";
10
- import { scanSkillContent } from "../tools/skill-security.js";
10
+ import { scanSkillContent } from "./validation.js";
11
11
  /**
12
12
  * Content scanning moved here from the old `skill_manage` write path (spec 045): `skill` is now
13
13
  * read-only and workspace skills are authored through the generic `write`/`edit` tools, which have
@@ -1,3 +1,7 @@
1
+ /**
2
+ * Validation of workspace skills: names, frontmatter, content scanning, and confinement of a skill's
3
+ * path to `workspace/skills/`.
4
+ */
1
5
  import { resolve } from "node:path";
2
6
  const SKILL_NAME_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3
7
  const FRONTMATTER_REGEX = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/;
@@ -0,0 +1,33 @@
1
+ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
2
+ export interface WorkspaceSkillSummary {
3
+ name: string;
4
+ description: string;
5
+ path: string;
6
+ warning?: string;
7
+ }
8
+ export interface WorkspaceSkillOptions {
9
+ workspaceDir: string;
10
+ securityConfig?: SecurityConfig;
11
+ securityContext?: SecurityRuntimeContext;
12
+ channelId?: string;
13
+ }
14
+ export declare function listWorkspaceSkills(options: {
15
+ workspaceDir: string;
16
+ securityConfig?: SecurityConfig;
17
+ securityContext?: SecurityRuntimeContext;
18
+ }): Promise<WorkspaceSkillSummary[]>;
19
+ export interface WorkspaceSkillFile {
20
+ name: string;
21
+ /** The guard-resolved path actually opened — never the raw pre-guard path. */
22
+ path: string;
23
+ /** The whole file; callers that need a size cap (the `skill` tool) apply it themselves. */
24
+ content: string;
25
+ }
26
+ /**
27
+ * Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
28
+ * through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
29
+ * (`skills/commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
30
+ * `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
31
+ * confines that) is caught here in both callers instead of being read verbatim.
32
+ */
33
+ export declare function loadWorkspaceSkillFile(options: WorkspaceSkillOptions, name: string): Promise<WorkspaceSkillFile>;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Workspace skill catalog access: list the skills under `workspace/skills/` and load one
3
+ * `SKILL.md`, both through the path guard. The `skill` tool and `/skills` are thin adapters over
4
+ * this file (spec 054 D8/D10).
5
+ */
6
+ import { existsSync } from "node:fs";
7
+ import { readdir, readFile, stat } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
10
+ import { checkPathGuard } from "../security/path-guard-check.js";
11
+ import { readGuardAllows } from "../security/path-guard-filter.js";
12
+ import { isNodeError } from "../shared/os.js";
13
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
14
+ import { resolveSkillPath, scanSkillContent, validateSkillFrontmatter, validateSkillName } from "./validation.js";
15
+ function extractDescription(content) {
16
+ const match = content.replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
17
+ if (!match) {
18
+ return "";
19
+ }
20
+ for (const line of (match[1] ?? "").split("\n")) {
21
+ const fieldMatch = line.match(/^description:\s*(.*)$/);
22
+ if (fieldMatch) {
23
+ return fieldMatch[1].replace(/^["']|["']$/g, "").trim();
24
+ }
25
+ }
26
+ return "";
27
+ }
28
+ export async function listWorkspaceSkills(options) {
29
+ const skillsDir = join(options.workspaceDir, "skills");
30
+ // `skill read` runs each SKILL.md through the path guard (`loadWorkspaceSkillFile`); `list`
31
+ // must apply the same guard so a skill whose SKILL.md is a symlink out of `workspace/skills/`
32
+ // is silently omitted here too, rather than being advertised and then refused on read.
33
+ const guardConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
34
+ const guardContext = options.securityContext ?? {
35
+ agentWorkspaceDir: options.workspaceDir,
36
+ projectRoot: options.workspaceDir,
37
+ };
38
+ let names;
39
+ try {
40
+ names = await readdir(skillsDir);
41
+ }
42
+ catch (error) {
43
+ if (isNodeError(error) && error.code === "ENOENT") {
44
+ return [];
45
+ }
46
+ throw error;
47
+ }
48
+ const summaries = [];
49
+ for (const name of names.sort()) {
50
+ const nameValidation = validateSkillName(name);
51
+ if (!nameValidation.ok) {
52
+ continue;
53
+ }
54
+ const skillDir = join(skillsDir, name);
55
+ const skillStats = await stat(skillDir).catch(() => null);
56
+ if (!skillStats?.isDirectory()) {
57
+ continue;
58
+ }
59
+ const skillPath = join(skillDir, "SKILL.md");
60
+ if (!readGuardAllows(skillPath, guardConfig, guardContext)) {
61
+ continue;
62
+ }
63
+ let content;
64
+ try {
65
+ const skillFileStats = await stat(skillPath);
66
+ if (!skillFileStats.isFile()) {
67
+ continue;
68
+ }
69
+ content = await readFile(skillPath, "utf-8");
70
+ }
71
+ catch (error) {
72
+ if (isNodeError(error) && error.code === "ENOENT") {
73
+ continue;
74
+ }
75
+ throw error;
76
+ }
77
+ const validation = validateSkillFrontmatter(content, name);
78
+ const scan = validation.ok ? scanSkillContent(content) : validation;
79
+ summaries.push({
80
+ name,
81
+ description: extractDescription(content),
82
+ path: `${options.workspaceDir}/skills/${name}/SKILL.md`,
83
+ warning: scan.ok ? undefined : scan.error,
84
+ });
85
+ }
86
+ return summaries;
87
+ }
88
+ /**
89
+ * Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
90
+ * through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
91
+ * (`skills/commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
92
+ * `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
93
+ * confines that) is caught here in both callers instead of being read verbatim.
94
+ */
95
+ export async function loadWorkspaceSkillFile(options, name) {
96
+ const nameValidation = validateSkillName(name);
97
+ if (!nameValidation.ok) {
98
+ throw new RecoverableToolError(nameValidation.error ?? `Invalid skill name "${name}".`);
99
+ }
100
+ const skillDir = resolveSkillPath(options.workspaceDir, name);
101
+ const rawPath = join(skillDir, "SKILL.md");
102
+ if (!existsSync(rawPath)) {
103
+ throw new RecoverableToolError(`Workspace skill "${name}" does not exist. Use action "list" to see what's available.`);
104
+ }
105
+ const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
106
+ const securityContext = options.securityContext ?? {
107
+ agentWorkspaceDir: options.workspaceDir,
108
+ projectRoot: options.workspaceDir,
109
+ };
110
+ const target = await checkPathGuard(rawPath, "read", securityConfig, securityContext, {
111
+ tool: "skill",
112
+ channelId: options.channelId,
113
+ });
114
+ const content = await readFile(target, "utf-8");
115
+ return { name, path: target, content };
116
+ }
@@ -1,8 +1,9 @@
1
- import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
2
- import type { RunNotice, SubAgentRunManager } from "../subagents/runs.js";
1
+ import type { SubAgentDiscoveryResult } from "./discovery.js";
2
+ import type { RunNotice } from "./run-record.js";
3
+ import type { SubAgentRunManager } from "./runs.js";
3
4
  /**
4
5
  * `/subagents` — the human control path that does not depend on the model (spec 040 D6, polished
5
- * by spec 041). Mirrors `task-commands.ts`'s shape: pure functions returning markdown, no
6
+ * by spec 041). Mirrors `tasks/commands.ts`'s shape: pure functions returning markdown, no
6
7
  * bot/event coupling.
7
8
  */
8
9
  export interface HandleSubagentsCommandOptions {
@@ -4,8 +4,8 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
4
4
  import { capReply } from "../commands/reply-limits.js";
5
5
  import { formatElapsedZh } from "../shared/format.js";
6
6
  import { errorMessage, truncate } from "../shared/text-utils.js";
7
- import { readLastOutputAt, STALL_THRESHOLD_MS } from "../subagents/external/progress-tail.js";
8
- import { elapsedMs, formatCost, harnessLabel } from "../subagents/format.js";
7
+ import { readLastOutputAt, STALL_THRESHOLD_MS } from "./external/progress-tail.js";
8
+ import { elapsedMs, formatCost, harnessLabel } from "./format.js";
9
9
  function usage() {
10
10
  return `${renderSubcommandUsage("subagents")}\n\n\`runId\` 支持不带 \`run_\` 前缀的简写,只要能唯一匹配即可,例如 \`show a1b2c3\`。`;
11
11
  }
@@ -0,0 +1,17 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
2
+ import type { RunRecord } from "./run-record.js";
3
+ /** Chars of the reply text carried inline in the completion wake. P2-1: `output.md` bodies are
4
+ * routinely 3-10KB — a 2,000-char tail truncated most of them and regularly cost the reader an
5
+ * extra `read` round trip just to see the rest. */
6
+ export declare const WAKE_OUTPUT_TAIL_CHARS = 6000;
7
+ /**
8
+ * The completion wake for a settled run: who finished, how, the (untrusted) output tail, and where
9
+ * the full output lives. Pure: the manager supplies the sibling count it alone can compute.
10
+ */
11
+ export declare function buildRunCompletionWake(input: {
12
+ record: RunRecord;
13
+ outputText: string;
14
+ outputSaved: boolean;
15
+ /** Other runs of the same task (or, for a chat-level run, the same channel) still running. */
16
+ siblingCount: number;
17
+ }): ChannelEvent;