soraacode 0.2.0 → 0.2.1

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 (353) hide show
  1. package/LICENSE +21 -0
  2. package/bin/soraacode.exe +10 -0
  3. package/package.json +17 -25
  4. package/{script/postinstall.mjs → postinstall.mjs} +5 -5
  5. package/AGENTS.md +0 -131
  6. package/Dockerfile +0 -18
  7. package/README.md +0 -15
  8. package/bin/opencode +0 -199
  9. package/bin/soraacode +0 -199
  10. package/bunfig.toml +0 -7
  11. package/git +0 -0
  12. package/migration/20260511173437_session-metadata/migration.sql +0 -1
  13. package/migration/20260511173437_session-metadata/snapshot.json +0 -1500
  14. package/parsers-config.ts +0 -1
  15. package/script/bench-search.ts +0 -94
  16. package/script/bench-test-suite.ts +0 -52
  17. package/script/build-headless.ts +0 -51
  18. package/script/build.ts +0 -245
  19. package/script/generate.ts +0 -14
  20. package/script/httpapi-exercise.ts +0 -1
  21. package/script/profile-test-files.ts +0 -42
  22. package/script/publish.ts +0 -213
  23. package/script/run-workspace-server +0 -106
  24. package/script/schema.ts +0 -77
  25. package/script/time.ts +0 -6
  26. package/script/trace-imports.ts +0 -153
  27. package/soraacode-0.1.7.tgz +0 -0
  28. package/specs/effect/error-boundaries-plan.md +0 -235
  29. package/specs/effect/errors.md +0 -207
  30. package/specs/effect/facades.md +0 -218
  31. package/specs/effect/guide.md +0 -247
  32. package/specs/effect/instance-context.md +0 -13
  33. package/specs/effect/loose-ends.md +0 -30
  34. package/specs/effect/migration.md +0 -62
  35. package/specs/effect/routes.md +0 -61
  36. package/specs/effect/schema.md +0 -88
  37. package/specs/effect/server-package.md +0 -58
  38. package/specs/effect/todo.md +0 -241
  39. package/specs/effect/tools.md +0 -88
  40. package/specs/openapi-translation-cleanup.md +0 -204
  41. package/specs/tui-plugins.md +0 -544
  42. package/specs/v2/api.ts +0 -67
  43. package/specs/v2/message-shape.md +0 -136
  44. package/specs/v2/notifications.md +0 -13
  45. package/specs/v2/tui-command-shim.md +0 -67
  46. package/src/account/account.ts +0 -481
  47. package/src/account/repo.ts +0 -171
  48. package/src/account/schema.ts +0 -99
  49. package/src/account/url.ts +0 -8
  50. package/src/acp/agent.ts +0 -95
  51. package/src/acp/config-option.ts +0 -206
  52. package/src/acp/content.ts +0 -269
  53. package/src/acp/directory.ts +0 -212
  54. package/src/acp/error.ts +0 -97
  55. package/src/acp/event.ts +0 -421
  56. package/src/acp/permission.ts +0 -254
  57. package/src/acp/profile.ts +0 -42
  58. package/src/acp/service.ts +0 -1226
  59. package/src/acp/session.ts +0 -232
  60. package/src/acp/tool.ts +0 -364
  61. package/src/acp/usage.ts +0 -243
  62. package/src/agent/agent.ts +0 -450
  63. package/src/agent/generate.txt +0 -75
  64. package/src/agent/prompt/compaction.txt +0 -5
  65. package/src/agent/prompt/explore.txt +0 -18
  66. package/src/agent/prompt/summary.txt +0 -11
  67. package/src/agent/prompt/title.txt +0 -44
  68. package/src/agent/subagent-permissions.ts +0 -27
  69. package/src/audio.d.ts +0 -14
  70. package/src/auth/index.ts +0 -97
  71. package/src/background/job.ts +0 -37
  72. package/src/bus/global.ts +0 -22
  73. package/src/cli/bootstrap.ts +0 -11
  74. package/src/cli/cmd/cmd.ts +0 -7
  75. package/src/cli/cmd/serve.ts +0 -24
  76. package/src/cli/effect/prompt.ts +0 -37
  77. package/src/cli/effect-cmd.ts +0 -96
  78. package/src/cli/error.ts +0 -130
  79. package/src/cli/heap.ts +0 -45
  80. package/src/cli/logo.ts +0 -2
  81. package/src/cli/network.ts +0 -80
  82. package/src/cli/ui.ts +0 -132
  83. package/src/command/index.ts +0 -177
  84. package/src/command/template/initialize.txt +0 -66
  85. package/src/command/template/review.txt +0 -101
  86. package/src/config/agent.ts +0 -59
  87. package/src/config/command.ts +0 -39
  88. package/src/config/config.ts +0 -707
  89. package/src/config/entry-name.ts +0 -19
  90. package/src/config/managed.ts +0 -69
  91. package/src/config/markdown.ts +0 -36
  92. package/src/config/parse.ts +0 -61
  93. package/src/config/paths.ts +0 -45
  94. package/src/config/plugin.ts +0 -79
  95. package/src/config/v2-compat.ts +0 -449
  96. package/src/config/variable.ts +0 -91
  97. package/src/control-plane/adapters/index.ts +0 -41
  98. package/src/control-plane/adapters/worktree.ts +0 -96
  99. package/src/control-plane/dev/README.md +0 -19
  100. package/src/control-plane/dev/debug-workspace-plugin.ts +0 -73
  101. package/src/control-plane/types.ts +0 -59
  102. package/src/control-plane/util.ts +0 -39
  103. package/src/control-plane/workspace-adapter-runtime.ts +0 -51
  104. package/src/control-plane/workspace-context.ts +0 -26
  105. package/src/control-plane/workspace.ts +0 -966
  106. package/src/effect/app-node-builder-v1.ts +0 -12
  107. package/src/effect/app-runtime.ts +0 -135
  108. package/src/effect/bootstrap-runtime.ts +0 -19
  109. package/src/effect/bridge.ts +0 -84
  110. package/src/effect/config-service.ts +0 -67
  111. package/src/effect/instance-ref.ts +0 -11
  112. package/src/effect/instance-registry.ts +0 -12
  113. package/src/effect/instance-state.ts +0 -69
  114. package/src/effect/promise.ts +0 -17
  115. package/src/effect/run-service.ts +0 -47
  116. package/src/effect/runner.ts +0 -217
  117. package/src/effect/runtime-flags.ts +0 -78
  118. package/src/env/index.ts +0 -41
  119. package/src/event-manifest.ts +0 -3
  120. package/src/event-v2-bridge.ts +0 -71
  121. package/src/format/formatter.ts +0 -404
  122. package/src/format/index.ts +0 -203
  123. package/src/git/index.ts +0 -348
  124. package/src/id/id.ts +0 -80
  125. package/src/ide/index.ts +0 -54
  126. package/src/image/image.ts +0 -172
  127. package/src/index-headless.ts +0 -89
  128. package/src/index.ts +0 -93
  129. package/src/installation/index.ts +0 -336
  130. package/src/lsp/client.ts +0 -650
  131. package/src/lsp/diagnostic.ts +0 -29
  132. package/src/lsp/language.ts +0 -121
  133. package/src/lsp/launch.ts +0 -21
  134. package/src/lsp/lsp.ts +0 -507
  135. package/src/lsp/server.ts +0 -1983
  136. package/src/markdown.d.ts +0 -4
  137. package/src/mcp/auth.ts +0 -163
  138. package/src/mcp/browser.ts +0 -37
  139. package/src/mcp/catalog.ts +0 -170
  140. package/src/mcp/index.ts +0 -1004
  141. package/src/mcp/oauth-callback.ts +0 -194
  142. package/src/mcp/oauth-provider.ts +0 -259
  143. package/src/node.ts +0 -4
  144. package/src/patch/index.ts +0 -686
  145. package/src/permission/arity.ts +0 -163
  146. package/src/permission/evaluate.ts +0 -1
  147. package/src/permission/index.ts +0 -223
  148. package/src/plugin/github-copilot/copilot.ts +0 -415
  149. package/src/plugin/github-copilot/models.ts +0 -261
  150. package/src/plugin/index.ts +0 -298
  151. package/src/plugin/install.ts +0 -439
  152. package/src/plugin/loader.ts +0 -237
  153. package/src/plugin/meta.ts +0 -188
  154. package/src/plugin/openai/README.md +0 -31
  155. package/src/plugin/openai/codex.ts +0 -575
  156. package/src/plugin/openai/ws-pool.ts +0 -271
  157. package/src/plugin/openai/ws.ts +0 -383
  158. package/src/plugin/pty-environment.ts +0 -24
  159. package/src/plugin/shared.ts +0 -323
  160. package/src/project/bootstrap-service.ts +0 -9
  161. package/src/project/bootstrap.ts +0 -58
  162. package/src/project/instance-context.ts +0 -24
  163. package/src/project/instance-runtime.ts +0 -16
  164. package/src/project/instance-store.ts +0 -213
  165. package/src/project/project.ts +0 -483
  166. package/src/project/vcs.ts +0 -423
  167. package/src/provider/auth.ts +0 -229
  168. package/src/provider/error.ts +0 -195
  169. package/src/provider/model-status.ts +0 -8
  170. package/src/provider/provider.ts +0 -1955
  171. package/src/provider/transform.ts +0 -1923
  172. package/src/question/index.ts +0 -161
  173. package/src/question/schema.ts +0 -4
  174. package/src/server/auth.ts +0 -48
  175. package/src/server/event.ts +0 -10
  176. package/src/server/global-lifecycle.ts +0 -28
  177. package/src/server/mdns.ts +0 -47
  178. package/src/server/proxy-util.ts +0 -48
  179. package/src/server/routes/instance/httpapi/AGENTS.md +0 -39
  180. package/src/server/routes/instance/httpapi/api.ts +0 -97
  181. package/src/server/routes/instance/httpapi/errors.ts +0 -193
  182. package/src/server/routes/instance/httpapi/groups/config.ts +0 -65
  183. package/src/server/routes/instance/httpapi/groups/control-plane.ts +0 -35
  184. package/src/server/routes/instance/httpapi/groups/control.ts +0 -76
  185. package/src/server/routes/instance/httpapi/groups/event.ts +0 -29
  186. package/src/server/routes/instance/httpapi/groups/experimental.ts +0 -275
  187. package/src/server/routes/instance/httpapi/groups/file.ts +0 -185
  188. package/src/server/routes/instance/httpapi/groups/global.ts +0 -139
  189. package/src/server/routes/instance/httpapi/groups/instance.ts +0 -206
  190. package/src/server/routes/instance/httpapi/groups/mcp.ts +0 -156
  191. package/src/server/routes/instance/httpapi/groups/metadata.ts +0 -18
  192. package/src/server/routes/instance/httpapi/groups/permission.ts +0 -61
  193. package/src/server/routes/instance/httpapi/groups/project-copy.ts +0 -32
  194. package/src/server/routes/instance/httpapi/groups/project.ts +0 -93
  195. package/src/server/routes/instance/httpapi/groups/provider.ts +0 -101
  196. package/src/server/routes/instance/httpapi/groups/pty.ts +0 -172
  197. package/src/server/routes/instance/httpapi/groups/query.ts +0 -12
  198. package/src/server/routes/instance/httpapi/groups/question.ts +0 -74
  199. package/src/server/routes/instance/httpapi/groups/session.ts +0 -462
  200. package/src/server/routes/instance/httpapi/groups/sync.ts +0 -113
  201. package/src/server/routes/instance/httpapi/groups/tui.ts +0 -208
  202. package/src/server/routes/instance/httpapi/groups/workspace.ts +0 -141
  203. package/src/server/routes/instance/httpapi/handlers/config.ts +0 -34
  204. package/src/server/routes/instance/httpapi/handlers/control-plane.ts +0 -37
  205. package/src/server/routes/instance/httpapi/handlers/control.ts +0 -43
  206. package/src/server/routes/instance/httpapi/handlers/event.ts +0 -99
  207. package/src/server/routes/instance/httpapi/handlers/experimental.ts +0 -193
  208. package/src/server/routes/instance/httpapi/handlers/file.ts +0 -139
  209. package/src/server/routes/instance/httpapi/handlers/global.ts +0 -126
  210. package/src/server/routes/instance/httpapi/handlers/instance.ts +0 -110
  211. package/src/server/routes/instance/httpapi/handlers/mcp.ts +0 -111
  212. package/src/server/routes/instance/httpapi/handlers/permission.ts +0 -41
  213. package/src/server/routes/instance/httpapi/handlers/project-copy.ts +0 -83
  214. package/src/server/routes/instance/httpapi/handlers/project.ts +0 -63
  215. package/src/server/routes/instance/httpapi/handlers/provider.ts +0 -116
  216. package/src/server/routes/instance/httpapi/handlers/pty.ts +0 -273
  217. package/src/server/routes/instance/httpapi/handlers/question.ts +0 -54
  218. package/src/server/routes/instance/httpapi/handlers/session-errors.ts +0 -21
  219. package/src/server/routes/instance/httpapi/handlers/session.ts +0 -442
  220. package/src/server/routes/instance/httpapi/handlers/sync.ts +0 -89
  221. package/src/server/routes/instance/httpapi/handlers/tui.ts +0 -131
  222. package/src/server/routes/instance/httpapi/handlers/workspace.ts +0 -102
  223. package/src/server/routes/instance/httpapi/lifecycle.ts +0 -54
  224. package/src/server/routes/instance/httpapi/middleware/authorization.ts +0 -150
  225. package/src/server/routes/instance/httpapi/middleware/compression.ts +0 -64
  226. package/src/server/routes/instance/httpapi/middleware/cors-vary.ts +0 -29
  227. package/src/server/routes/instance/httpapi/middleware/error.ts +0 -44
  228. package/src/server/routes/instance/httpapi/middleware/fence.ts +0 -25
  229. package/src/server/routes/instance/httpapi/middleware/instance-context.ts +0 -43
  230. package/src/server/routes/instance/httpapi/middleware/proxy.ts +0 -131
  231. package/src/server/routes/instance/httpapi/middleware/schema-error.ts +0 -41
  232. package/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +0 -250
  233. package/src/server/routes/instance/httpapi/public.ts +0 -537
  234. package/src/server/routes/instance/httpapi/server.ts +0 -325
  235. package/src/server/routes/instance/httpapi/websocket-tracker.ts +0 -60
  236. package/src/server/server.ts +0 -224
  237. package/src/server/shared/fence.ts +0 -60
  238. package/src/server/shared/pty-ticket.ts +0 -15
  239. package/src/server/shared/public-ui.ts +0 -12
  240. package/src/server/shared/tui-control.ts +0 -28
  241. package/src/server/shared/ui.ts +0 -108
  242. package/src/server/shared/workspace-routing.ts +0 -45
  243. package/src/server/tui-event.ts +0 -1
  244. package/src/session/compaction.ts +0 -608
  245. package/src/session/instruction.ts +0 -237
  246. package/src/session/llm/AGENTS.md +0 -90
  247. package/src/session/llm/ai-sdk.ts +0 -291
  248. package/src/session/llm/native-request.ts +0 -196
  249. package/src/session/llm/native-runtime.ts +0 -195
  250. package/src/session/llm/request.ts +0 -226
  251. package/src/session/llm.ts +0 -390
  252. package/src/session/message-error.ts +0 -14
  253. package/src/session/message-v2.ts +0 -742
  254. package/src/session/message.ts +0 -148
  255. package/src/session/overflow.ts +0 -34
  256. package/src/session/processor.ts +0 -732
  257. package/src/session/prompt/build-switch.txt +0 -5
  258. package/src/session/prompt/default.txt +0 -35
  259. package/src/session/prompt/plan-mode.txt +0 -70
  260. package/src/session/prompt/plan.txt +0 -26
  261. package/src/session/prompt.ts +0 -1631
  262. package/src/session/reminders.ts +0 -92
  263. package/src/session/retry.ts +0 -209
  264. package/src/session/revert.ts +0 -136
  265. package/src/session/run-state.ts +0 -151
  266. package/src/session/schema.ts +0 -26
  267. package/src/session/session.ts +0 -1016
  268. package/src/session/status.ts +0 -56
  269. package/src/session/summary.ts +0 -160
  270. package/src/session/system.ts +0 -123
  271. package/src/session/todo.ts +0 -74
  272. package/src/session/tools.ts +0 -590
  273. package/src/share/session.ts +0 -58
  274. package/src/share/share-next.ts +0 -371
  275. package/src/skill/discovery.ts +0 -140
  276. package/src/skill/index.ts +0 -354
  277. package/src/snapshot/index.ts +0 -807
  278. package/src/sql.d.ts +0 -4
  279. package/src/storage/schema.ts +0 -5
  280. package/src/storage/storage.ts +0 -327
  281. package/src/sync/README.md +0 -179
  282. package/src/sync/schema.ts +0 -11
  283. package/src/temporary.ts +0 -31
  284. package/src/tool/apply_patch.ts +0 -313
  285. package/src/tool/apply_patch.txt +0 -14
  286. package/src/tool/code-mode.ts +0 -310
  287. package/src/tool/edit.ts +0 -737
  288. package/src/tool/edit.txt +0 -13
  289. package/src/tool/external-directory.ts +0 -49
  290. package/src/tool/glob.ts +0 -76
  291. package/src/tool/glob.txt +0 -7
  292. package/src/tool/grep.ts +0 -115
  293. package/src/tool/grep.txt +0 -7
  294. package/src/tool/invalid.ts +0 -21
  295. package/src/tool/json-schema.ts +0 -164
  296. package/src/tool/lsp.ts +0 -113
  297. package/src/tool/lsp.txt +0 -1
  298. package/src/tool/mcp-websearch.ts +0 -96
  299. package/src/tool/plan-enter.txt +0 -1
  300. package/src/tool/plan-exit.txt +0 -1
  301. package/src/tool/plan.ts +0 -79
  302. package/src/tool/question.ts +0 -44
  303. package/src/tool/question.txt +0 -1
  304. package/src/tool/read.ts +0 -386
  305. package/src/tool/read.txt +0 -13
  306. package/src/tool/registry.ts +0 -455
  307. package/src/tool/schema.ts +0 -14
  308. package/src/tool/shell/id.ts +0 -19
  309. package/src/tool/shell/prompt.ts +0 -293
  310. package/src/tool/shell/shell.txt +0 -21
  311. package/src/tool/shell.ts +0 -645
  312. package/src/tool/skill.ts +0 -70
  313. package/src/tool/skill.txt +0 -1
  314. package/src/tool/task.ts +0 -371
  315. package/src/tool/task.txt +0 -11
  316. package/src/tool/todo.ts +0 -46
  317. package/src/tool/todowrite.txt +0 -11
  318. package/src/tool/tool.ts +0 -183
  319. package/src/tool/truncate.ts +0 -156
  320. package/src/tool/truncation-dir.ts +0 -4
  321. package/src/tool/webfetch.ts +0 -192
  322. package/src/tool/webfetch.txt +0 -9
  323. package/src/tool/websearch.ts +0 -143
  324. package/src/tool/websearch.txt +0 -9
  325. package/src/tool/write.ts +0 -104
  326. package/src/tool/write.txt +0 -11
  327. package/src/util/archive.ts +0 -17
  328. package/src/util/bom.ts +0 -27
  329. package/src/util/data-url.ts +0 -9
  330. package/src/util/defer.ts +0 -10
  331. package/src/util/effect-http-client.ts +0 -11
  332. package/src/util/error.ts +0 -16
  333. package/src/util/filesystem.ts +0 -251
  334. package/src/util/html.ts +0 -8
  335. package/src/util/iife.ts +0 -3
  336. package/src/util/lazy.ts +0 -20
  337. package/src/util/local-context.ts +0 -25
  338. package/src/util/locale.ts +0 -4
  339. package/src/util/media.ts +0 -26
  340. package/src/util/process.ts +0 -177
  341. package/src/util/proxy-env.ts +0 -72
  342. package/src/util/queue.ts +0 -32
  343. package/src/util/record.ts +0 -3
  344. package/src/util/repository.ts +0 -232
  345. package/src/util/rpc.ts +0 -66
  346. package/src/util/signal.ts +0 -12
  347. package/src/util/timeout.ts +0 -13
  348. package/src/util/token.ts +0 -1
  349. package/src/util/wildcard.ts +0 -59
  350. package/src/worktree/index.ts +0 -623
  351. package/sst-env.d.ts +0 -10
  352. package/tsconfig.headless.json +0 -13
  353. package/tsconfig.json +0 -16
@@ -1,1631 +0,0 @@
1
- import { LayerNode } from "@soraacode/core/effect/layer-node"
2
- import { PermissionV1 } from "@soraacode/core/v1/permission"
3
- import path from "path"
4
- import { SessionV1 } from "@soraacode/core/v1/session"
5
- import os from "os"
6
- import { SessionID, MessageID, PartID } from "./schema"
7
- import { MessageV2 } from "./message-v2"
8
- import { SessionRevert } from "./revert"
9
- import { Session } from "./session"
10
- import { Agent } from "../agent/agent"
11
- import { Provider } from "@/provider/provider"
12
-
13
- import { type Tool as AITool, tool, jsonSchema } from "ai"
14
- import type { JSONSchema7 } from "@ai-sdk/provider"
15
- import { SessionCompaction } from "./compaction"
16
- import { SystemPrompt } from "./system"
17
- import { Instruction } from "./instruction"
18
- import { Plugin } from "../plugin"
19
- import { MAX_STEPS_PROMPT } from "@soraacode/core/session/runner/max-steps"
20
- import { ToolRegistry } from "@/tool/registry"
21
- import { MCP } from "../mcp"
22
- import { LSP } from "@/lsp/lsp"
23
- import { ulid } from "ulid"
24
- import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
25
- import { CrossSpawnSpawner } from "@soraacode/core/cross-spawn-spawner"
26
- import * as Stream from "effect/Stream"
27
- import { Command } from "../command"
28
- import { pathToFileURL, fileURLToPath } from "url"
29
- import { Config } from "@/config/config"
30
- import { ConfigMarkdown } from "@/config/markdown"
31
- import { SessionSummary } from "./summary"
32
- import { NamedError } from "@soraacode/core/util/error"
33
- import { SessionProcessor } from "./processor"
34
- import { Tool } from "@/tool/tool"
35
- import { Permission } from "@/permission"
36
- import { SessionStatus } from "./status"
37
- import { LLM } from "./llm"
38
- import { Shell } from "@soraacode/core/shell"
39
- import { ShellID } from "@/tool/shell/id"
40
- import { FSUtil } from "@soraacode/core/fs-util"
41
- import { Truncate } from "@/tool/truncate"
42
- import { Image } from "@/image/image"
43
- import { decodeDataUrl } from "@/util/data-url"
44
- import { Process } from "@/util/process"
45
- import { Cause, Effect, Exit, Latch, Layer, Option, Scope, Context, Schema, Types } from "effect"
46
- import { InstanceState } from "@/effect/instance-state"
47
- import { TaskTool, type TaskPromptOps } from "@/tool/task"
48
- import { SessionRunState } from "./run-state"
49
- import { RuntimeFlags } from "@/effect/runtime-flags"
50
- import { EventV2Bridge } from "@/event-v2-bridge"
51
- import { Database } from "@soraacode/core/database/database"
52
- import { ModelV2 } from "@soraacode/core/model"
53
- import { ProviderV2 } from "@soraacode/core/provider"
54
- import { eq } from "drizzle-orm"
55
- import { SessionTable } from "@soraacode/core/session/sql"
56
- import { SessionReminders } from "./reminders"
57
- import { SessionTools } from "./tools"
58
- import { LLMEvent } from "@soraacode/llm"
59
-
60
- // @ts-ignore
61
- globalThis.AI_SDK_LOG_WARNINGS = false
62
-
63
- const decodeMessageInfo = Schema.decodeUnknownExit(SessionV1.Info)
64
- const decodeMessagePart = Schema.decodeUnknownExit(SessionV1.Part)
65
- const MAX_MCP_RESOURCE_BLOB_BYTES = 10 * 1024 * 1024
66
- const SUPPORTED_MCP_RESOURCE_ATTACHMENT_MIMES = new Set([
67
- "application/pdf",
68
- "image/gif",
69
- "image/jpeg",
70
- "image/png",
71
- "image/webp",
72
- ])
73
-
74
- const STRUCTURED_OUTPUT_DESCRIPTION = `Use this tool to return your final response in the requested structured format.
75
-
76
- IMPORTANT:
77
- - You MUST call this tool exactly once at the end of your response
78
- - The input must be valid JSON matching the required schema
79
- - Complete all necessary research and tool calls BEFORE calling this tool
80
- - This tool provides your final answer - no further actions are taken after calling it`
81
-
82
- const STRUCTURED_OUTPUT_SYSTEM_PROMPT = `IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.`
83
-
84
- function mcpResourceBase64Size(value: string) {
85
- const trimmed = value.replace(/\s/g, "")
86
- const padding = trimmed.endsWith("==") ? 2 : trimmed.endsWith("=") ? 1 : 0
87
- return Math.max(0, Math.floor((trimmed.length * 3) / 4) - padding)
88
- }
89
-
90
- function formatMcpResourceBytes(value: number) {
91
- if (value < 1024) return `${value} B`
92
- if (value < 1024 * 1024) return `${Math.ceil(value / 1024)} KB`
93
- return `${Math.ceil(value / (1024 * 1024))} MB`
94
- }
95
-
96
- function isOrphanedInterruptedTool(part: SessionV1.ToolPart) {
97
- // cleanup() marks abandoned tool_use blocks this way after retries/aborts.
98
- // They are not pending work and must not trigger an assistant-prefill request.
99
- return part.state.status === "error" && part.state.metadata?.interrupted === true
100
- }
101
-
102
- export interface Interface {
103
- readonly cancel: (sessionID: SessionID) => Effect.Effect<void>
104
- readonly prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error>
105
- readonly loop: (input: LoopInput) => Effect.Effect<SessionV1.WithParts>
106
- readonly shell: (input: ShellInput) => Effect.Effect<SessionV1.WithParts, Session.BusyError>
107
- readonly command: (input: CommandInput) => Effect.Effect<SessionV1.WithParts, Image.Error>
108
- readonly resolvePromptParts: (template: string) => Effect.Effect<PromptInput["parts"]>
109
- }
110
-
111
- export class Service extends Context.Service<Service, Interface>()("@opencode/SessionPrompt") {}
112
-
113
- const layer = Layer.effect(
114
- Service,
115
- Effect.gen(function* () {
116
- const status = yield* SessionStatus.Service
117
- const sessions = yield* Session.Service
118
- const agents = yield* Agent.Service
119
- const provider = yield* Provider.Service
120
- const processor = yield* SessionProcessor.Service
121
- const compaction = yield* SessionCompaction.Service
122
- const plugin = yield* Plugin.Service
123
- const commands = yield* Command.Service
124
- const config = yield* Config.Service
125
- const permission = yield* Permission.Service
126
- const fsys = yield* FSUtil.Service
127
- const mcp = yield* MCP.Service
128
- const lsp = yield* LSP.Service
129
- const registry = yield* ToolRegistry.Service
130
- const truncate = yield* Truncate.Service
131
- const image = yield* Image.Service
132
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
133
- const scope = yield* Scope.Scope
134
- const instruction = yield* Instruction.Service
135
- const state = yield* SessionRunState.Service
136
- const revert = yield* SessionRevert.Service
137
- const summary = yield* SessionSummary.Service
138
- const sys = yield* SystemPrompt.Service
139
- const llm = yield* LLM.Service
140
- const events = yield* EventV2Bridge.Service
141
- const flags = yield* RuntimeFlags.Service
142
- const database = yield* Database.Service
143
- const { db } = database
144
- const ops = Effect.fn("SessionPrompt.ops")(function* () {
145
- return {
146
- cancel: (sessionID: SessionID) => cancel(sessionID),
147
- resolvePromptParts: (template: string) => resolvePromptParts(template),
148
- prompt: (input: PromptInput) => prompt(input).pipe(Effect.catch(Effect.die)),
149
- } satisfies TaskPromptOps
150
- })
151
-
152
- const cancel = Effect.fn("SessionPrompt.cancel")(function* (sessionID: SessionID) {
153
- yield* Effect.logInfo("cancel", { "session.id": sessionID })
154
- yield* state.cancel(sessionID)
155
- })
156
-
157
- const resolvePromptParts = Effect.fn("SessionPrompt.resolvePromptParts")(function* (template: string) {
158
- const ctx = yield* InstanceState.context
159
- const parts: Types.DeepMutable<PromptInput["parts"]> = [{ type: "text", text: template }]
160
- const files = ConfigMarkdown.files(template)
161
- const seen = new Set<string>()
162
- yield* Effect.forEach(
163
- files,
164
- Effect.fnUntraced(function* (match) {
165
- const name = match[1]
166
- if (!name) return
167
- if (seen.has(name)) return
168
- seen.add(name)
169
-
170
- const filepath = name.startsWith("~/")
171
- ? path.join(os.homedir(), name.slice(2))
172
- : path.resolve(ctx.worktree, name)
173
-
174
- const info = yield* fsys.stat(filepath).pipe(Effect.option)
175
- if (Option.isNone(info)) {
176
- const found = yield* agents.get(name)
177
- if (found) parts.push({ type: "agent", name: found.name })
178
- return
179
- }
180
- const stat = info.value
181
- parts.push({
182
- type: "file",
183
- url: pathToFileURL(filepath).href,
184
- filename: name,
185
- mime: stat.type === "Directory" ? "application/x-directory" : "text/plain",
186
- })
187
- }),
188
- { concurrency: "unbounded", discard: true },
189
- )
190
- return parts
191
- })
192
-
193
- const title = Effect.fn("SessionPrompt.ensureTitle")(function* (input: {
194
- session: Session.Info
195
- history: SessionV1.WithParts[]
196
- providerID: ProviderV2.ID
197
- modelID: ModelV2.ID
198
- }) {
199
- if (input.session.parentID) return
200
- if (!Session.isDefaultTitle(input.session.title)) return
201
-
202
- const real = (m: SessionV1.WithParts) =>
203
- m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic)
204
- const idx = input.history.findIndex(real)
205
- if (idx === -1) return
206
- if (input.history.filter(real).length !== 1) return
207
-
208
- const context = input.history.slice(0, idx + 1)
209
- const firstUser = context[idx]
210
- if (!firstUser || firstUser.info.role !== "user") return
211
- const firstInfo = firstUser.info
212
-
213
- const subtasks = firstUser.parts.filter((p): p is SessionV1.SubtaskPart => p.type === "subtask")
214
- const onlySubtasks = subtasks.length > 0 && firstUser.parts.every((p) => p.type === "subtask")
215
-
216
- const ag = yield* agents.get("title")
217
- if (!ag) return
218
- const mdl = ag.model
219
- ? yield* provider.getModel(ag.model.providerID, ag.model.modelID)
220
- : ((yield* provider.getSmallModel(input.providerID)) ??
221
- (yield* provider.getModel(input.providerID, input.modelID)))
222
- const msgs = onlySubtasks
223
- ? [{ role: "user" as const, content: subtasks.map((p) => p.prompt).join("\n") }]
224
- : yield* MessageV2.toModelMessagesEffect(context, mdl)
225
- const text = yield* llm
226
- .stream({
227
- agent: ag,
228
- user: firstInfo,
229
- system: [],
230
- small: true,
231
- tools: {},
232
- model: mdl,
233
- sessionID: input.session.id,
234
- retries: 2,
235
- messages: [{ role: "user", content: "Generate a title for this conversation:\n" }, ...msgs],
236
- })
237
- .pipe(
238
- Stream.filter(LLMEvent.is.textDelta),
239
- Stream.map((e) => e.text),
240
- Stream.mkString,
241
- Effect.orDie,
242
- )
243
- const cleaned = text
244
- .replace(/<think>[\s\S]*?<\/think>\s*/g, "")
245
- .split("\n")
246
- .map((line) => line.trim())
247
- .find((line) => line.length > 0)
248
- if (!cleaned) return
249
- const t = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
250
- yield* sessions
251
- .setTitle({ sessionID: input.session.id, title: t })
252
- .pipe(Effect.catchCause((cause) => Effect.logError("failed to generate title", { error: Cause.squash(cause) })))
253
- })
254
-
255
- const handleSubtask = Effect.fn("SessionPrompt.handleSubtask")(function* (input: {
256
- task: SessionV1.SubtaskPart
257
- model: Provider.Model
258
- lastUser: SessionV1.User
259
- sessionID: SessionID
260
- session: Session.Info
261
- msgs: SessionV1.WithParts[]
262
- }) {
263
- const { task, model, lastUser, sessionID, session, msgs } = input
264
- const ctx = yield* InstanceState.context
265
- const promptOps = yield* ops()
266
- const { task: taskTool } = yield* registry.named()
267
- const taskModel = task.model ? yield* getModel(task.model.providerID, task.model.modelID, sessionID) : model
268
- const assistantMessage: SessionV1.Assistant = yield* sessions.updateMessage({
269
- id: MessageID.ascending(),
270
- role: "assistant",
271
- parentID: lastUser.id,
272
- sessionID,
273
- mode: task.agent,
274
- agent: task.agent,
275
- variant: lastUser.model.variant,
276
- path: { cwd: ctx.directory, root: ctx.worktree },
277
- cost: 0,
278
- tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
279
- modelID: taskModel.id,
280
- providerID: taskModel.providerID,
281
- time: { created: Date.now() },
282
- })
283
- let part: SessionV1.ToolPart = yield* sessions.updatePart({
284
- id: PartID.ascending(),
285
- messageID: assistantMessage.id,
286
- sessionID: assistantMessage.sessionID,
287
- type: "tool",
288
- callID: ulid(),
289
- tool: TaskTool.id,
290
- state: {
291
- status: "running",
292
- input: {
293
- prompt: task.prompt,
294
- description: task.description,
295
- subagent_type: task.agent,
296
- command: task.command,
297
- },
298
- time: { start: Date.now() },
299
- },
300
- })
301
- const taskArgs = {
302
- prompt: task.prompt,
303
- description: task.description,
304
- subagent_type: task.agent,
305
- command: task.command,
306
- }
307
- yield* plugin.trigger(
308
- "tool.execute.before",
309
- { tool: TaskTool.id, sessionID, callID: part.id },
310
- { args: taskArgs },
311
- )
312
-
313
- const taskAgent = yield* agents.get(task.agent)
314
- if (!taskAgent) {
315
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
316
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
317
- const error = new NamedError.Unknown({ message: `Agent not found: "${task.agent}".${hint}` })
318
- yield* events.publish(Session.Event.Error, { sessionID, error: error.toObject() })
319
- throw error
320
- }
321
-
322
- let error: Error | undefined
323
- const taskAbort = new AbortController()
324
- const result = yield* taskTool
325
- .execute(taskArgs, {
326
- agent: task.agent,
327
- messageID: assistantMessage.id,
328
- sessionID,
329
- abort: taskAbort.signal,
330
- callID: part.callID,
331
- extra: { bypassAgentCheck: true, promptOps },
332
- messages: msgs,
333
- metadata: (val: { title?: string; metadata?: Record<string, any> }) =>
334
- Effect.gen(function* () {
335
- part = yield* sessions.updatePart({
336
- ...part,
337
- type: "tool",
338
- state: { ...part.state, ...val },
339
- } satisfies SessionV1.ToolPart)
340
- }),
341
- ask: (req: any) =>
342
- permission
343
- .ask({
344
- ...req,
345
- sessionID,
346
- ruleset: Permission.merge(taskAgent.permission, session.permission ?? []),
347
- })
348
- .pipe(Effect.orDie),
349
- })
350
- .pipe(
351
- Effect.catchCause((cause) => {
352
- const defect = Cause.squash(cause)
353
- error = defect instanceof Error ? defect : new Error(String(defect))
354
- return Effect.logError("subtask execution failed", {
355
- error,
356
- agent: task.agent,
357
- description: task.description,
358
- })
359
- }),
360
- Effect.onInterrupt(() =>
361
- Effect.gen(function* () {
362
- taskAbort.abort()
363
- assistantMessage.finish = "tool-calls"
364
- assistantMessage.time.completed = Date.now()
365
- yield* sessions.updateMessage(assistantMessage)
366
- if (part.state.status === "running") {
367
- yield* sessions.updatePart({
368
- ...part,
369
- state: {
370
- status: "error",
371
- error: "Cancelled",
372
- time: { start: part.state.time.start, end: Date.now() },
373
- metadata: part.state.metadata,
374
- input: part.state.input,
375
- },
376
- } satisfies SessionV1.ToolPart)
377
- }
378
- }),
379
- ),
380
- )
381
-
382
- const attachments = result?.attachments?.map((attachment) => ({
383
- ...attachment,
384
- id: PartID.ascending(),
385
- sessionID,
386
- messageID: assistantMessage.id,
387
- }))
388
-
389
- yield* plugin.trigger(
390
- "tool.execute.after",
391
- { tool: TaskTool.id, sessionID, callID: part.id, args: taskArgs },
392
- result,
393
- )
394
-
395
- assistantMessage.finish = "tool-calls"
396
- assistantMessage.time.completed = Date.now()
397
- yield* sessions.updateMessage(assistantMessage)
398
-
399
- if (result && part.state.status === "running") {
400
- yield* sessions.updatePart({
401
- ...part,
402
- state: {
403
- status: "completed",
404
- input: part.state.input,
405
- title: result.title,
406
- metadata: result.metadata,
407
- output: result.output,
408
- attachments,
409
- time: { ...part.state.time, end: Date.now() },
410
- },
411
- } satisfies SessionV1.ToolPart)
412
- }
413
-
414
- if (!result) {
415
- yield* sessions.updatePart({
416
- ...part,
417
- state: {
418
- status: "error",
419
- error: error ? `Tool execution failed: ${error.message}` : "Tool execution failed",
420
- time: {
421
- start: part.state.status === "running" ? part.state.time.start : Date.now(),
422
- end: Date.now(),
423
- },
424
- metadata: part.state.status === "pending" ? undefined : part.state.metadata,
425
- input: part.state.input,
426
- },
427
- } satisfies SessionV1.ToolPart)
428
- }
429
-
430
- if (!task.command) return
431
-
432
- const summaryUserMsg: SessionV1.User = {
433
- id: MessageID.ascending(),
434
- sessionID,
435
- role: "user",
436
- time: { created: Date.now() },
437
- agent: lastUser.agent,
438
- model: lastUser.model,
439
- }
440
- yield* sessions.updateMessage(summaryUserMsg)
441
- yield* sessions.updatePart({
442
- id: PartID.ascending(),
443
- messageID: summaryUserMsg.id,
444
- sessionID,
445
- type: "text",
446
- text: "Summarize the task tool output above and continue with your task.",
447
- synthetic: true,
448
- } satisfies SessionV1.TextPart)
449
- })
450
-
451
- const shellImpl = Effect.fn("SessionPrompt.shellImpl")(function* (input: ShellInput, ready?: Latch.Latch) {
452
- return yield* Effect.uninterruptibleMask((restore) =>
453
- Effect.gen(function* () {
454
- const markReady = ready ? ready.open.pipe(Effect.asVoid) : Effect.void
455
- const { msg, part, cwd } = yield* Effect.gen(function* () {
456
- const ctx = yield* InstanceState.context
457
- const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
458
- if (session.revert) {
459
- yield* revert.cleanup(session)
460
- }
461
- const agent = yield* agents.get(input.agent)
462
- if (!agent) {
463
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
464
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
465
- const error = new NamedError.Unknown({ message: `Agent not found: "${input.agent}".${hint}` })
466
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
467
- throw error
468
- }
469
- const model = input.model ?? agent.model ?? (yield* currentModel(input.sessionID))
470
- const userMsg: SessionV1.User = {
471
- id: input.messageID ?? MessageID.ascending(),
472
- sessionID: input.sessionID,
473
- time: { created: Date.now() },
474
- role: "user",
475
- agent: input.agent,
476
- model: { providerID: model.providerID, modelID: model.modelID },
477
- }
478
- yield* sessions.updateMessage(userMsg)
479
- const userPart: SessionV1.Part = {
480
- type: "text",
481
- id: PartID.ascending(),
482
- messageID: userMsg.id,
483
- sessionID: input.sessionID,
484
- text: "The following tool was executed by the user",
485
- synthetic: true,
486
- }
487
- yield* sessions.updatePart(userPart)
488
-
489
- const msg: SessionV1.Assistant = {
490
- id: MessageID.ascending(),
491
- sessionID: input.sessionID,
492
- parentID: userMsg.id,
493
- mode: input.agent,
494
- agent: input.agent,
495
- cost: 0,
496
- path: { cwd: ctx.directory, root: ctx.worktree },
497
- time: { created: Date.now() },
498
- role: "assistant",
499
- tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
500
- modelID: model.modelID,
501
- providerID: model.providerID,
502
- }
503
- yield* sessions.updateMessage(msg)
504
- const started = Date.now()
505
- const part: SessionV1.ToolPart = {
506
- type: "tool",
507
- id: PartID.ascending(),
508
- messageID: msg.id,
509
- sessionID: input.sessionID,
510
- tool: ShellID.ToolID,
511
- callID: ulid(),
512
- state: {
513
- status: "running",
514
- time: { start: started },
515
- input: { command: input.command },
516
- },
517
- }
518
- yield* sessions.updatePart(part)
519
- return { msg, part, cwd: ctx.directory }
520
- }).pipe(Effect.ensuring(markReady))
521
-
522
- const cfg = yield* config.get()
523
- const sh = Shell.preferred(cfg.shell)
524
- const args = Shell.args(sh, input.command, cwd)
525
- let output = ""
526
- let aborted = false
527
-
528
- const finish = Effect.uninterruptible(
529
- Effect.gen(function* () {
530
- if (aborted) {
531
- output += "\n\n" + ["<metadata>", "User aborted the command", "</metadata>"].join("\n")
532
- }
533
- const completed = Date.now()
534
- if (!msg.time.completed) {
535
- msg.time.completed = completed
536
- yield* sessions.updateMessage(msg)
537
- }
538
- if (part.state.status === "running") {
539
- part.state = {
540
- status: "completed",
541
- time: { ...part.state.time, end: completed },
542
- input: part.state.input,
543
- title: "",
544
- metadata: { output },
545
- output,
546
- }
547
- yield* sessions.updatePart(part)
548
- }
549
- }),
550
- )
551
-
552
- const exit = yield* restore(
553
- Effect.gen(function* () {
554
- const shellEnv = yield* plugin.trigger(
555
- "shell.env",
556
- { cwd, sessionID: input.sessionID, callID: part.callID },
557
- { env: {} },
558
- )
559
- const cmd = ChildProcess.make(sh, args, {
560
- cwd,
561
- extendEnv: true,
562
- env: { ...shellEnv.env, TERM: "dumb" },
563
- stdin: "ignore",
564
- forceKillAfter: "3 seconds",
565
- })
566
- const handle = yield* spawner.spawn(cmd)
567
- yield* Stream.runForEach(Stream.decodeText(handle.all), (chunk) =>
568
- Effect.gen(function* () {
569
- output += chunk
570
- if (part.state.status === "running") {
571
- part.state.metadata = { output }
572
- yield* sessions.updatePart(part)
573
- }
574
- }),
575
- )
576
- yield* handle.exitCode
577
- }).pipe(Effect.scoped, Effect.orDie),
578
- ).pipe(Effect.exit)
579
-
580
- if (Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause) && !Cause.hasDies(exit.cause)) {
581
- aborted = true
582
- }
583
- yield* finish
584
-
585
- if (Exit.isFailure(exit) && !aborted && !Cause.hasInterruptsOnly(exit.cause)) {
586
- return yield* Effect.failCause(exit.cause)
587
- }
588
-
589
- return { info: msg, parts: [part] }
590
- }),
591
- )
592
- })
593
-
594
- const getModel = Effect.fn("SessionPrompt.getModel")(function* (
595
- providerID: ProviderV2.ID,
596
- modelID: ModelV2.ID,
597
- sessionID: SessionID,
598
- ) {
599
- const exit = yield* provider.getModel(providerID, modelID).pipe(Effect.exit)
600
- if (Exit.isSuccess(exit)) return exit.value
601
- const err = Cause.squash(exit.cause)
602
- if (Provider.ModelNotFoundError.isInstance(err)) {
603
- const hint = err.suggestions?.length ? ` Did you mean: ${err.suggestions.join(", ")}?` : ""
604
- yield* events.publish(Session.Event.Error, {
605
- sessionID,
606
- error: new NamedError.Unknown({
607
- message: `Model not found: ${err.providerID}/${err.modelID}.${hint}`,
608
- }).toObject(),
609
- })
610
- }
611
- return yield* Effect.die(err)
612
- })
613
-
614
- const currentModel = Effect.fnUntraced(function* (sessionID: SessionID) {
615
- const current = yield* db
616
- .select({ model: SessionTable.model })
617
- .from(SessionTable)
618
- .where(eq(SessionTable.id, sessionID))
619
- .get()
620
- .pipe(Effect.orDie)
621
- if (current?.model) {
622
- return {
623
- providerID: ProviderV2.ID.make(current.model.providerID),
624
- modelID: ModelV2.ID.make(current.model.id),
625
- ...(current.model.variant && current.model.variant !== "default" ? { variant: current.model.variant } : {}),
626
- }
627
- }
628
- const match = yield* sessions
629
- .findMessage(sessionID, (m) => m.info.role === "user" && !!m.info.model)
630
- .pipe(Effect.orDie)
631
- if (Option.isSome(match) && match.value.info.role === "user") return match.value.info.model
632
- return yield* provider.defaultModel().pipe(Effect.orDie)
633
- })
634
-
635
- const createUserMessage = Effect.fn("SessionPrompt.createUserMessage")(function* (input: PromptInput) {
636
- const agentName = input.agent
637
- const ag = agentName ? yield* agents.get(agentName) : yield* agents.defaultInfo()
638
- if (!ag) {
639
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
640
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
641
- const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
642
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
643
- throw error
644
- }
645
-
646
- const model = input.model ?? ag.model ?? (yield* currentModel(input.sessionID))
647
- const same = ag.model && model.providerID === ag.model.providerID && model.modelID === ag.model.modelID
648
- const full =
649
- !input.variant && ag.variant && same
650
- ? yield* provider
651
- .getModel(model.providerID, model.modelID)
652
- .pipe(Effect.catchIf(Provider.ModelNotFoundError.isInstance, () => Effect.succeed(undefined)))
653
- : undefined
654
- const variant = input.variant ?? (ag.variant && full?.variants?.[ag.variant] ? ag.variant : undefined)
655
-
656
- const info: SessionV1.User = {
657
- id: input.messageID ?? MessageID.ascending(),
658
- role: "user",
659
- sessionID: input.sessionID,
660
- time: { created: Date.now() },
661
- tools: input.tools,
662
- agent: ag.name,
663
- model: {
664
- providerID: model.providerID,
665
- modelID: model.modelID,
666
- variant,
667
- },
668
- system: input.system,
669
- format: input.format,
670
- }
671
-
672
- const current = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
673
- if (
674
- current.agent !== info.agent ||
675
- current.model?.providerID !== info.model.providerID ||
676
- current.model?.id !== info.model.modelID ||
677
- (current.model?.variant === "default" ? undefined : current.model?.variant) !== info.model.variant
678
- ) {
679
- yield* sessions.setAgentModel({
680
- sessionID: input.sessionID,
681
- agent: info.agent,
682
- model: {
683
- id: info.model.modelID,
684
- providerID: info.model.providerID,
685
- variant: info.model.variant ?? "default",
686
- },
687
- time: info.time.created,
688
- })
689
- }
690
-
691
- yield* Effect.addFinalizer(() => instruction.clear(info.id))
692
-
693
- type Draft<T> = T extends SessionV1.Part ? Omit<T, "id"> & { id?: string } : never
694
- const assign = (part: Draft<SessionV1.Part>): SessionV1.Part => ({
695
- ...part,
696
- id: part.id ? PartID.make(part.id) : PartID.ascending(),
697
- })
698
-
699
- const resolvePart: (part: PromptInput["parts"][number]) => Effect.Effect<Draft<SessionV1.Part>[]> = Effect.fn(
700
- "SessionPrompt.resolveUserPart",
701
- )(function* (part) {
702
- if (part.type === "file") {
703
- if (part.source?.type === "resource") {
704
- const { clientName, uri } = part.source
705
- yield* Effect.logInfo("mcp resource", { clientName, uri, mime: part.mime })
706
- const pieces: Draft<SessionV1.Part>[] = [
707
- {
708
- messageID: info.id,
709
- sessionID: input.sessionID,
710
- type: "text",
711
- synthetic: true,
712
- text: `Reading MCP resource: ${part.filename} (${uri})`,
713
- },
714
- ]
715
- const exit = yield* mcp.readResource(clientName, uri).pipe(Effect.exit)
716
- if (Exit.isSuccess(exit)) {
717
- const content = exit.value
718
- if (!content) throw new Error(`Resource not found: ${clientName}/${uri}`)
719
- const items = Array.isArray(content.contents) ? content.contents : [content.contents]
720
- for (const c of items) {
721
- if (!c || typeof c !== "object") continue
722
- if ("text" in c && typeof c.text === "string" && c.text) {
723
- pieces.push({
724
- messageID: info.id,
725
- sessionID: input.sessionID,
726
- type: "text",
727
- synthetic: true,
728
- text: c.text,
729
- })
730
- } else if ("blob" in c && typeof c.blob === "string" && c.blob) {
731
- const mime = "mimeType" in c && typeof c.mimeType === "string" ? c.mimeType : part.mime
732
- const filename = "uri" in c && typeof c.uri === "string" ? c.uri : part.filename
733
- const size = mcpResourceBase64Size(c.blob)
734
- if (!SUPPORTED_MCP_RESOURCE_ATTACHMENT_MIMES.has(mime)) {
735
- pieces.push({
736
- messageID: info.id,
737
- sessionID: input.sessionID,
738
- type: "text",
739
- synthetic: true,
740
- text: `[Binary MCP resource omitted: ${filename ?? uri} (${mime}, ${formatMcpResourceBytes(size)}) is not a supported attachment type]`,
741
- })
742
- continue
743
- }
744
- if (size > MAX_MCP_RESOURCE_BLOB_BYTES) {
745
- pieces.push({
746
- messageID: info.id,
747
- sessionID: input.sessionID,
748
- type: "text",
749
- synthetic: true,
750
- text: `[Binary MCP resource omitted: ${filename ?? uri} (${mime}, ${formatMcpResourceBytes(size)}) exceeds ${formatMcpResourceBytes(MAX_MCP_RESOURCE_BLOB_BYTES)}]`,
751
- })
752
- continue
753
- }
754
- pieces.push({
755
- messageID: info.id,
756
- sessionID: input.sessionID,
757
- type: "text",
758
- synthetic: true,
759
- text: `[Binary MCP resource attached: ${filename ?? uri} (${mime})]`,
760
- })
761
- pieces.push({
762
- messageID: info.id,
763
- sessionID: input.sessionID,
764
- type: "file",
765
- mime,
766
- filename,
767
- url: `data:${mime};base64,${c.blob}`,
768
- })
769
- }
770
- }
771
- } else {
772
- const error = Cause.squash(exit.cause)
773
- yield* Effect.logError("failed to read MCP resource", { error, clientName, uri })
774
- const message = error instanceof Error ? error.message : String(error)
775
- pieces.push({
776
- messageID: info.id,
777
- sessionID: input.sessionID,
778
- type: "text",
779
- synthetic: true,
780
- text: `Failed to read MCP resource ${part.filename}: ${message}`,
781
- })
782
- }
783
- return pieces
784
- }
785
- const url = new URL(part.url)
786
- switch (url.protocol) {
787
- case "data:":
788
- if (part.mime === "text/plain") {
789
- return [
790
- {
791
- messageID: info.id,
792
- sessionID: input.sessionID,
793
- type: "text",
794
- synthetic: true,
795
- text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
796
- },
797
- {
798
- messageID: info.id,
799
- sessionID: input.sessionID,
800
- type: "text",
801
- synthetic: true,
802
- text: decodeDataUrl(part.url),
803
- },
804
- { ...part, messageID: info.id, sessionID: input.sessionID },
805
- ]
806
- }
807
- break
808
- case "file:": {
809
- yield* Effect.logInfo("file", { mime: part.mime })
810
- const filepath = fileURLToPath(part.url)
811
- const mime = (yield* fsys.isDir(filepath)) ? "application/x-directory" : part.mime
812
-
813
- const { read } = yield* registry.named()
814
- const execRead = (args: Parameters<typeof read.execute>[0], extra?: Tool.Context["extra"]) => {
815
- const controller = new AbortController()
816
- return read
817
- .execute(args, {
818
- sessionID: input.sessionID,
819
- abort: controller.signal,
820
- agent: input.agent!,
821
- messageID: info.id,
822
- extra: { bypassCwdCheck: true, ...extra },
823
- messages: [],
824
- metadata: () => Effect.void,
825
- ask: () => Effect.void,
826
- })
827
- .pipe(Effect.onInterrupt(() => Effect.sync(() => controller.abort())))
828
- }
829
-
830
- if (mime === "text/plain") {
831
- let offset: number | undefined
832
- let limit: number | undefined
833
- const range = { start: url.searchParams.get("start"), end: url.searchParams.get("end") }
834
- if (range.start != null) {
835
- const filePathURI = part.url.split("?")[0]
836
- let start = parseInt(range.start)
837
- let end = range.end ? parseInt(range.end) : undefined
838
- if (start === end) {
839
- const symbols = yield* lsp.documentSymbol(filePathURI).pipe(Effect.catch(() => Effect.succeed([])))
840
- for (const symbol of symbols) {
841
- let r: LSP.Range | undefined
842
- if ("range" in symbol) r = symbol.range
843
- else if ("location" in symbol) r = symbol.location.range
844
- if (r?.start?.line && r?.start?.line === start) {
845
- start = r.start.line
846
- end = r?.end?.line ?? start
847
- break
848
- }
849
- }
850
- }
851
- offset = Math.max(start, 1)
852
- if (end) limit = end - (offset - 1)
853
- }
854
- const args = { filePath: filepath, offset, limit }
855
- const pieces: Draft<SessionV1.Part>[] = [
856
- {
857
- messageID: info.id,
858
- sessionID: input.sessionID,
859
- type: "text",
860
- synthetic: true,
861
- text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
862
- },
863
- ]
864
- const exit = yield* provider.getModel(info.model.providerID, info.model.modelID).pipe(
865
- Effect.flatMap((mdl) => execRead(args, { model: mdl })),
866
- Effect.exit,
867
- )
868
- if (Exit.isSuccess(exit)) {
869
- const result = exit.value
870
- pieces.push({
871
- messageID: info.id,
872
- sessionID: input.sessionID,
873
- type: "text",
874
- synthetic: true,
875
- text: result.output,
876
- })
877
- if (result.attachments?.length) {
878
- pieces.push(
879
- ...result.attachments.map((a) => ({
880
- ...a,
881
- synthetic: true,
882
- filename: a.filename ?? part.filename,
883
- messageID: info.id,
884
- sessionID: input.sessionID,
885
- })),
886
- )
887
- } else {
888
- pieces.push({ ...part, mime, messageID: info.id, sessionID: input.sessionID })
889
- }
890
- } else {
891
- const error = Cause.squash(exit.cause)
892
- yield* Effect.logError("failed to read file", { error, filepath })
893
- const message = error instanceof Error ? error.message : String(error)
894
- yield* events.publish(Session.Event.Error, {
895
- sessionID: input.sessionID,
896
- error: new NamedError.Unknown({ message }).toObject(),
897
- })
898
- pieces.push({
899
- messageID: info.id,
900
- sessionID: input.sessionID,
901
- type: "text",
902
- synthetic: true,
903
- text: `Read tool failed to read ${filepath} with the following error: ${message}`,
904
- })
905
- }
906
- return pieces
907
- }
908
-
909
- if (mime === "application/x-directory") {
910
- const args = { filePath: filepath }
911
- const exit = yield* execRead(args).pipe(Effect.exit)
912
- if (Exit.isFailure(exit)) {
913
- const error = Cause.squash(exit.cause)
914
- yield* Effect.logError("failed to read directory", { error, filepath })
915
- const message = error instanceof Error ? error.message : String(error)
916
- yield* events.publish(Session.Event.Error, {
917
- sessionID: input.sessionID,
918
- error: new NamedError.Unknown({ message }).toObject(),
919
- })
920
- return [
921
- {
922
- messageID: info.id,
923
- sessionID: input.sessionID,
924
- type: "text",
925
- synthetic: true,
926
- text: `Read tool failed to read ${filepath} with the following error: ${message}`,
927
- },
928
- ]
929
- }
930
- return [
931
- {
932
- messageID: info.id,
933
- sessionID: input.sessionID,
934
- type: "text",
935
- synthetic: true,
936
- text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
937
- },
938
- {
939
- messageID: info.id,
940
- sessionID: input.sessionID,
941
- type: "text",
942
- synthetic: true,
943
- text: exit.value.output,
944
- },
945
- { ...part, mime, messageID: info.id, sessionID: input.sessionID },
946
- ]
947
- }
948
-
949
- return [
950
- {
951
- messageID: info.id,
952
- sessionID: input.sessionID,
953
- type: "text",
954
- synthetic: true,
955
- text: `Called the Read tool with the following input: {"filePath":"${filepath}"}`,
956
- },
957
- {
958
- id: part.id,
959
- messageID: info.id,
960
- sessionID: input.sessionID,
961
- type: "file",
962
- url:
963
- `data:${mime};base64,` +
964
- Buffer.from(yield* fsys.readFile(filepath).pipe(Effect.catch(Effect.die))).toString("base64"),
965
- mime,
966
- filename: part.filename!,
967
- source: part.source,
968
- },
969
- ]
970
- }
971
- }
972
- }
973
-
974
- if (part.type === "agent") {
975
- const perm = Permission.evaluate("task", part.name, ag.permission)
976
- const hint = perm.action === "deny" ? " . Invoked by user; guaranteed to exist." : ""
977
- return [
978
- { ...part, messageID: info.id, sessionID: input.sessionID },
979
- {
980
- messageID: info.id,
981
- sessionID: input.sessionID,
982
- type: "text",
983
- synthetic: true,
984
- text:
985
- " Use the above message and context to generate a prompt and call the task tool with subagent: " +
986
- part.name +
987
- hint,
988
- },
989
- ]
990
- }
991
-
992
- return [{ ...part, messageID: info.id, sessionID: input.sessionID }]
993
- })
994
-
995
- const resolvedParts = yield* Effect.forEach(input.parts, resolvePart, { concurrency: "unbounded" }).pipe(
996
- Effect.map((x) => x.flat().map(assign)),
997
- )
998
-
999
- yield* plugin.trigger(
1000
- "chat.message",
1001
- {
1002
- sessionID: input.sessionID,
1003
- agent: input.agent,
1004
- model: input.model,
1005
- messageID: input.messageID,
1006
- variant: input.variant,
1007
- },
1008
- { message: info, parts: resolvedParts },
1009
- )
1010
-
1011
- const parts = yield* Effect.forEach(resolvedParts, (part) =>
1012
- part.type === "file" && part.mime.startsWith("image/")
1013
- ? image.normalize(part).pipe(
1014
- Effect.catchIf(
1015
- (error) => error instanceof Image.ResizerUnavailableError,
1016
- () => Effect.succeed(part),
1017
- ),
1018
- )
1019
- : Effect.succeed(part),
1020
- )
1021
-
1022
- const parsed = decodeMessageInfo(info, { errors: "all", propertyOrder: "original" })
1023
- if (Exit.isFailure(parsed)) {
1024
- yield* Effect.logError("invalid user message before save", {
1025
- sessionID: input.sessionID,
1026
- messageID: info.id,
1027
- agent: info.agent,
1028
- model: info.model,
1029
- cause: Cause.pretty(parsed.cause),
1030
- })
1031
- }
1032
- for (const [index, part] of parts.entries()) {
1033
- const p = decodeMessagePart(part, { errors: "all", propertyOrder: "original" })
1034
- if (Exit.isSuccess(p)) continue
1035
- yield* Effect.logError("invalid user part before save", {
1036
- sessionID: input.sessionID,
1037
- messageID: info.id,
1038
- partID: part.id,
1039
- partType: part.type,
1040
- index,
1041
- cause: Cause.pretty(p.cause),
1042
- part,
1043
- })
1044
- }
1045
-
1046
- yield* sessions.updateMessage(info)
1047
- for (const part of parts) yield* sessions.updatePart(part)
1048
-
1049
- return { info, parts }
1050
- }, Effect.scoped)
1051
-
1052
- const prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error> = Effect.fn(
1053
- "SessionPrompt.prompt",
1054
- )(function* (input: PromptInput) {
1055
- const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
1056
- yield* revert.cleanup(session)
1057
- const message = yield* createUserMessage(input)
1058
- yield* sessions.touch(input.sessionID)
1059
-
1060
- const permissions: PermissionV1.Rule[] = []
1061
- for (const [t, enabled] of Object.entries(input.tools ?? {})) {
1062
- permissions.push({ permission: t, action: enabled ? "allow" : "deny", pattern: "*" })
1063
- }
1064
- if (permissions.length > 0) {
1065
- session.permission = permissions
1066
- yield* sessions.setPermission({ sessionID: session.id, permission: permissions })
1067
- }
1068
-
1069
- if (input.noReply === true) return message
1070
- return yield* loop({ sessionID: input.sessionID })
1071
- })
1072
-
1073
- const lastAssistant = Effect.fnUntraced(function* (sessionID: SessionID) {
1074
- const match = yield* sessions.findMessage(sessionID, (m) => m.info.role !== "user").pipe(Effect.orDie)
1075
- if (Option.isSome(match)) return match.value
1076
- const msgs = yield* sessions.messages({ sessionID, limit: 1 }).pipe(Effect.orDie)
1077
- if (msgs.length > 0) return msgs[0]
1078
- throw new Error("Impossible")
1079
- })
1080
-
1081
- const runLoop: (sessionID: SessionID) => Effect.Effect<SessionV1.WithParts> = Effect.fn("SessionPrompt.run")(
1082
- function* (sessionID: SessionID) {
1083
- const ctx = yield* InstanceState.context
1084
- let structured: unknown
1085
- let step = 0
1086
- const session = yield* sessions.get(sessionID).pipe(Effect.orDie)
1087
-
1088
- while (true) {
1089
- yield* status.set(sessionID, { type: "busy" })
1090
- yield* Effect.logInfo("loop", { "session.id": sessionID, step })
1091
-
1092
- let msgs = yield* MessageV2.filterCompactedEffect(sessionID).pipe(
1093
- Effect.provideService(Database.Service, database),
1094
- )
1095
-
1096
- const { user: lastUser, assistant: lastAssistant, finished: lastFinished, tasks } = MessageV2.latest(msgs)
1097
-
1098
- if (!lastUser) throw new Error("No user message found in stream. This should never happen.")
1099
-
1100
- const lastAssistantMsg = msgs.findLast(
1101
- (msg) => msg.info.role === "assistant" && msg.info.id === lastAssistant?.id,
1102
- )
1103
- // Some providers return "stop" even when the assistant message contains
1104
- // tool calls. Keep the loop running so tool results can be sent back to
1105
- // the model, but ignore cleanup-marked interrupted orphans.
1106
- const hasToolCalls =
1107
- lastAssistantMsg?.parts.some(
1108
- (part) => part.type === "tool" && !part.metadata?.providerExecuted && !isOrphanedInterruptedTool(part),
1109
- ) ?? false
1110
-
1111
- if (
1112
- lastAssistant?.finish &&
1113
- !["tool-calls", "unknown"].includes(lastAssistant.finish) &&
1114
- !hasToolCalls &&
1115
- lastAssistant.parentID === lastUser.id
1116
- ) {
1117
- const orphan = lastAssistantMsg?.parts.find(
1118
- (part): part is SessionV1.ToolPart => part.type === "tool" && isOrphanedInterruptedTool(part),
1119
- )
1120
- if (orphan) {
1121
- yield* Effect.logWarning("loop exit with orphaned interrupted tool", {
1122
- "session.id": sessionID,
1123
- messageID: lastAssistant.id,
1124
- tool: orphan.tool,
1125
- callID: orphan.callID,
1126
- })
1127
- }
1128
- yield* Effect.logInfo("exiting loop", { "session.id": sessionID })
1129
- break
1130
- }
1131
-
1132
- step++
1133
- if (step === 1)
1134
- yield* title({
1135
- session,
1136
- modelID: lastUser.model.modelID,
1137
- providerID: lastUser.model.providerID,
1138
- history: msgs,
1139
- }).pipe(Effect.ignore, Effect.forkIn(scope))
1140
-
1141
- const model = yield* getModel(lastUser.model.providerID, lastUser.model.modelID, sessionID)
1142
- const task = tasks.pop()
1143
-
1144
- if (task?.type === "subtask") {
1145
- yield* handleSubtask({ task, model, lastUser, sessionID, session, msgs })
1146
- continue
1147
- }
1148
-
1149
- if (task?.type === "compaction") {
1150
- const result = yield* compaction.process({
1151
- messages: msgs,
1152
- parentID: lastUser.id,
1153
- sessionID,
1154
- auto: task.auto,
1155
- overflow: task.overflow,
1156
- })
1157
- if (result === "stop") break
1158
- continue
1159
- }
1160
-
1161
- if (
1162
- lastFinished &&
1163
- lastFinished.summary !== true &&
1164
- (yield* compaction.isOverflow({ tokens: lastFinished.tokens, model }))
1165
- ) {
1166
- yield* compaction.create({ sessionID, agent: lastUser.agent, model: lastUser.model, auto: true })
1167
- continue
1168
- }
1169
-
1170
- const agent = yield* agents.get(lastUser.agent)
1171
- if (!agent) {
1172
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
1173
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
1174
- const error = new NamedError.Unknown({ message: `Agent not found: "${lastUser.agent}".${hint}` })
1175
- yield* events.publish(Session.Event.Error, { sessionID, error: error.toObject() })
1176
- throw error
1177
- }
1178
- const maxSteps = agent.steps ?? Infinity
1179
- const isLastStep = step >= maxSteps
1180
- msgs = yield* SessionReminders.apply({ messages: msgs, agent, session }).pipe(
1181
- Effect.provideService(RuntimeFlags.Service, flags),
1182
- Effect.provideService(FSUtil.Service, fsys),
1183
- Effect.provideService(Session.Service, sessions),
1184
- )
1185
-
1186
- const msg: SessionV1.Assistant = {
1187
- id: MessageID.ascending(),
1188
- parentID: lastUser.id,
1189
- role: "assistant",
1190
- mode: agent.name,
1191
- agent: agent.name,
1192
- variant: lastUser.model.variant,
1193
- path: { cwd: ctx.directory, root: ctx.worktree },
1194
- cost: 0,
1195
- tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1196
- modelID: model.id,
1197
- providerID: model.providerID,
1198
- time: { created: Date.now() },
1199
- sessionID,
1200
- }
1201
- yield* sessions.updateMessage(msg)
1202
-
1203
- const finalizeInterruptedAssistant = Effect.gen(function* () {
1204
- if (msg.time.completed) return
1205
- msg.error ??= MessageV2.fromError(new DOMException("Aborted", "AbortError"), {
1206
- providerID: msg.providerID,
1207
- aborted: true,
1208
- })
1209
- msg.time.completed = Date.now()
1210
- yield* sessions.updateMessage(msg)
1211
- })
1212
-
1213
- const handle = yield* processor
1214
- .create({
1215
- assistantMessage: msg,
1216
- sessionID,
1217
- model,
1218
- })
1219
- .pipe(Effect.onInterrupt(() => finalizeInterruptedAssistant))
1220
-
1221
- const outcome: "break" | "continue" = yield* Effect.gen(function* () {
1222
- const lastUserMsg = msgs.findLast((m) => m.info.role === "user")
1223
- const bypassAgentCheck = lastUserMsg?.parts.some((p) => p.type === "agent") ?? false
1224
- const promptOps = yield* ops()
1225
-
1226
- const tools = yield* SessionTools.resolve({
1227
- agent,
1228
- session,
1229
- model,
1230
- processor: handle,
1231
- bypassAgentCheck,
1232
- messages: msgs,
1233
- promptOps,
1234
- }).pipe(
1235
- Effect.provideService(Plugin.Service, plugin),
1236
- Effect.provideService(Permission.Service, permission),
1237
- Effect.provideService(ToolRegistry.Service, registry),
1238
- Effect.provideService(MCP.Service, mcp),
1239
- Effect.provideService(Truncate.Service, truncate),
1240
- Effect.provideService(RuntimeFlags.Service, flags),
1241
- )
1242
-
1243
- if (lastUser.format?.type === "json_schema") {
1244
- tools["StructuredOutput"] = createStructuredOutputTool({
1245
- schema: lastUser.format.schema,
1246
- onSuccess(output) {
1247
- structured = output
1248
- },
1249
- })
1250
- }
1251
-
1252
- if (step === 1)
1253
- yield* summary.summarize({ sessionID, messageID: lastUser.id }).pipe(Effect.ignore, Effect.forkIn(scope))
1254
-
1255
- yield* plugin.trigger("experimental.chat.messages.transform", {}, { messages: msgs })
1256
-
1257
- const [skills, env, instructions, mcpInstructions, modelMsgs] = yield* Effect.all([
1258
- sys.skills(agent),
1259
- sys.environment(model),
1260
- instruction.system().pipe(Effect.orDie),
1261
- sys.mcp(agent, session.permission),
1262
- MessageV2.toModelMessagesEffect(msgs, model),
1263
- ])
1264
- const system = [
1265
- ...env,
1266
- ...instructions,
1267
- ...(mcpInstructions ? [mcpInstructions] : []),
1268
- ...(skills ? [skills] : []),
1269
- ]
1270
- const format = lastUser.format ?? { type: "text" as const }
1271
- if (format.type === "json_schema") system.push(STRUCTURED_OUTPUT_SYSTEM_PROMPT)
1272
- const result = yield* handle.process({
1273
- user: lastUser,
1274
- agent,
1275
- permission: session.permission,
1276
- sessionID,
1277
- parentSessionID: session.parentID,
1278
- system,
1279
- messages: [
1280
- ...modelMsgs,
1281
- ...(isLastStep ? [{ role: "assistant" as const, content: MAX_STEPS_PROMPT }] : []),
1282
- ],
1283
- tools,
1284
- model,
1285
- toolChoice: format.type === "json_schema" ? "required" : undefined,
1286
- })
1287
-
1288
- if (structured !== undefined) {
1289
- handle.message.structured = structured
1290
- handle.message.finish = handle.message.finish ?? "stop"
1291
- yield* sessions.updateMessage(handle.message)
1292
- return "break" as const
1293
- }
1294
-
1295
- const finished = handle.message.finish && !["tool-calls", "unknown"].includes(handle.message.finish)
1296
- if (finished && !handle.message.error) {
1297
- // Surface any content-filter finish (e.g. Anthropic stop_reason:
1298
- // refusal) as an error. These turns may have produced no visible
1299
- // output at all — previously the session went idle silently — or
1300
- // partial text that was cut off by the provider's filter.
1301
- if (handle.message.finish === "content-filter") {
1302
- handle.message.error = new SessionV1.ContentFilterError({
1303
- message: "The response was blocked by the provider's content filter",
1304
- }).toObject()
1305
- yield* sessions.updateMessage(handle.message)
1306
- yield* events.publish(Session.Event.Error, { sessionID, error: handle.message.error })
1307
- return "break" as const
1308
- }
1309
- if (format.type === "json_schema") {
1310
- handle.message.error = new SessionV1.StructuredOutputError({
1311
- message: "Model did not produce structured output",
1312
- retries: 0,
1313
- }).toObject()
1314
- yield* sessions.updateMessage(handle.message)
1315
- return "break" as const
1316
- }
1317
- }
1318
-
1319
- if (result === "stop") return "break" as const
1320
- if (result === "compact") {
1321
- yield* compaction.create({
1322
- sessionID,
1323
- agent: lastUser.agent,
1324
- model: lastUser.model,
1325
- auto: true,
1326
- overflow: !handle.message.finish,
1327
- })
1328
- }
1329
- return "continue" as const
1330
- }).pipe(
1331
- Effect.ensuring(instruction.clear(handle.message.id)),
1332
- Effect.onInterrupt(() => finalizeInterruptedAssistant),
1333
- )
1334
- if (outcome === "break") break
1335
- continue
1336
- }
1337
-
1338
- yield* compaction.prune({ sessionID }).pipe(Effect.ignore, Effect.forkIn(scope))
1339
- return yield* lastAssistant(sessionID)
1340
- },
1341
- )
1342
-
1343
- const loop: (input: LoopInput) => Effect.Effect<SessionV1.WithParts> = Effect.fn("SessionPrompt.loop")(function* (
1344
- input: LoopInput,
1345
- ) {
1346
- return yield* state.ensureRunning(input.sessionID, lastAssistant(input.sessionID), runLoop(input.sessionID))
1347
- })
1348
-
1349
- const shell: (input: ShellInput) => Effect.Effect<SessionV1.WithParts, Session.BusyError> = Effect.fn(
1350
- "SessionPrompt.shell",
1351
- )(function* (input: ShellInput) {
1352
- const ready = yield* Latch.make()
1353
- return yield* state.startShell(input.sessionID, lastAssistant(input.sessionID), shellImpl(input, ready), ready)
1354
- })
1355
-
1356
- const command = Effect.fn("SessionPrompt.command")(function* (input: CommandInput) {
1357
- yield* Effect.logInfo("command", {
1358
- "session.id": input.sessionID,
1359
- command: input.command,
1360
- agent: input.agent,
1361
- })
1362
- const cmd = yield* commands.get(input.command)
1363
- if (!cmd) {
1364
- const available = (yield* commands.list()).map((c) => c.name)
1365
- const hint = available.length ? ` Available commands: ${available.join(", ")}` : ""
1366
- const error = new NamedError.Unknown({ message: `Command not found: "${input.command}".${hint}` })
1367
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
1368
- throw error
1369
- }
1370
- const agentName = cmd.agent ?? input.agent
1371
-
1372
- const raw = input.arguments.match(argsRegex) ?? []
1373
- const args = raw.map((arg) => arg.replace(quoteTrimRegex, ""))
1374
- const templateCommand = yield* Effect.promise(async () => cmd.template)
1375
-
1376
- const placeholders = templateCommand.match(placeholderRegex) ?? []
1377
- let last = 0
1378
- for (const item of placeholders) {
1379
- const value = Number(item.slice(1))
1380
- if (value > last) last = value
1381
- }
1382
-
1383
- const withArgs = templateCommand.replaceAll(placeholderRegex, (_, index) => {
1384
- const position = Number(index)
1385
- const argIndex = position - 1
1386
- if (argIndex >= args.length) return ""
1387
- if (position === last) return args.slice(argIndex).join(" ")
1388
- return args[argIndex]
1389
- })
1390
- const usesArgumentsPlaceholder = templateCommand.includes("$ARGUMENTS")
1391
- let template = withArgs.replaceAll("$ARGUMENTS", input.arguments)
1392
-
1393
- if (placeholders.length === 0 && !usesArgumentsPlaceholder && input.arguments.trim()) {
1394
- template = template + "\n\n" + input.arguments
1395
- }
1396
-
1397
- const shellMatches = ConfigMarkdown.shell(template)
1398
- if (shellMatches.length > 0) {
1399
- const cfg = yield* config.get()
1400
- const sh = Shell.preferred(cfg.shell)
1401
- const results = yield* Effect.promise(() =>
1402
- Promise.all(
1403
- shellMatches.map(async ([, cmd]) => (await Process.text([cmd], { shell: sh, nothrow: true })).text),
1404
- ),
1405
- )
1406
- let index = 0
1407
- template = template.replace(bashRegex, () => results[index++])
1408
- }
1409
- template = template.trim()
1410
-
1411
- const taskModel = yield* Effect.gen(function* () {
1412
- if (cmd.model) return Provider.parseModel(cmd.model)
1413
- if (cmd.agent) {
1414
- const cmdAgent = yield* agents.get(cmd.agent)
1415
- if (cmdAgent?.model) return cmdAgent.model
1416
- }
1417
- if (input.model) return Provider.parseModel(input.model)
1418
- return yield* currentModel(input.sessionID)
1419
- })
1420
-
1421
- yield* getModel(taskModel.providerID, taskModel.modelID, input.sessionID)
1422
-
1423
- const agent = agentName ? yield* agents.get(agentName) : yield* agents.defaultInfo()
1424
- if (!agent) {
1425
- const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
1426
- const hint = available.length ? ` Available agents: ${available.join(", ")}` : ""
1427
- const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` })
1428
- yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() })
1429
- throw error
1430
- }
1431
-
1432
- const templateParts = yield* resolvePromptParts(template)
1433
- const inputFiles = new Set(
1434
- input.parts?.filter((part) => new URL(part.url).protocol === "file:").map((part) => fileURLToPath(part.url)),
1435
- )
1436
- const uniqueTemplateParts = templateParts.filter(
1437
- (part) => part.type !== "file" || !inputFiles.has(fileURLToPath(part.url)),
1438
- )
1439
- const isSubtask = (agent.mode === "subagent" && cmd.subtask !== false) || cmd.subtask === true
1440
- const parts = isSubtask
1441
- ? [
1442
- {
1443
- type: "subtask" as const,
1444
- agent: agent.name,
1445
- description: cmd.description ?? "",
1446
- command: input.command,
1447
- model: { providerID: taskModel.providerID, modelID: taskModel.modelID },
1448
- prompt: templateParts.find((y) => y.type === "text")?.text ?? "",
1449
- },
1450
- ]
1451
- : [...uniqueTemplateParts, ...(input.parts ?? [])]
1452
-
1453
- const userAgent = isSubtask ? (input.agent ?? (yield* agents.defaultInfo()).name) : agent.name
1454
- const userModel = isSubtask
1455
- ? input.model
1456
- ? Provider.parseModel(input.model)
1457
- : yield* currentModel(input.sessionID)
1458
- : taskModel
1459
-
1460
- yield* plugin.trigger(
1461
- "command.execute.before",
1462
- { command: input.command, sessionID: input.sessionID, arguments: input.arguments },
1463
- { parts },
1464
- )
1465
-
1466
- const result = yield* prompt({
1467
- sessionID: input.sessionID,
1468
- messageID: input.messageID,
1469
- model: userModel,
1470
- agent: userAgent,
1471
- parts,
1472
- variant: input.variant,
1473
- })
1474
- yield* events.publish(Command.Event.Executed, {
1475
- name: input.command,
1476
- sessionID: input.sessionID,
1477
- arguments: input.arguments,
1478
- messageID: result.info.id,
1479
- })
1480
- return result
1481
- })
1482
-
1483
- return Service.of({
1484
- cancel,
1485
- prompt,
1486
- loop,
1487
- shell,
1488
- command,
1489
- resolvePromptParts,
1490
- })
1491
- }),
1492
- )
1493
-
1494
- const ModelRef = Schema.Struct({
1495
- providerID: ProviderV2.ID,
1496
- modelID: ModelV2.ID,
1497
- })
1498
-
1499
- export const PromptInput = Schema.Struct({
1500
- sessionID: SessionID,
1501
- messageID: Schema.optional(MessageID),
1502
- model: Schema.optional(ModelRef),
1503
- agent: Schema.optional(Schema.String),
1504
- noReply: Schema.optional(Schema.Boolean),
1505
- tools: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)).annotate({
1506
- description:
1507
- "@deprecated tools and permissions have been merged, you can set permissions on the session itself now",
1508
- }),
1509
- format: Schema.optional(SessionV1.Format),
1510
- system: Schema.optional(Schema.String),
1511
- variant: Schema.optional(Schema.String),
1512
- parts: Schema.Array(
1513
- Schema.Union([
1514
- SessionV1.TextPartInput,
1515
- SessionV1.FilePartInput,
1516
- SessionV1.AgentPartInput,
1517
- SessionV1.SubtaskPartInput,
1518
- ]).annotate({ discriminator: "type" }),
1519
- ),
1520
- })
1521
- export type PromptInput = Schema.Schema.Type<typeof PromptInput>
1522
-
1523
- export class LoopInput extends Schema.Class<LoopInput>("SessionPrompt.LoopInput")({
1524
- sessionID: SessionID,
1525
- }) {}
1526
-
1527
- export const ShellInput = Schema.Struct({
1528
- sessionID: SessionID,
1529
- messageID: Schema.optional(MessageID),
1530
- agent: Schema.String,
1531
- model: Schema.optional(ModelRef),
1532
- command: Schema.String,
1533
- })
1534
- export type ShellInput = Schema.Schema.Type<typeof ShellInput>
1535
-
1536
- export const CommandInput = Schema.Struct({
1537
- messageID: Schema.optional(MessageID),
1538
- sessionID: SessionID,
1539
- agent: Schema.optional(Schema.String),
1540
- model: Schema.optional(Schema.String),
1541
- arguments: Schema.String,
1542
- command: Schema.String,
1543
- variant: Schema.optional(Schema.String),
1544
- // Inlined (no identifier annotation) to keep the original SDK output — the
1545
- // PromptInput call site below references FilePartInput by ref via the
1546
- // Schema export in message-v2.ts.
1547
- parts: Schema.optional(
1548
- Schema.Array(
1549
- Schema.Union([
1550
- Schema.Struct({
1551
- id: Schema.optional(PartID),
1552
- type: Schema.Literal("file"),
1553
- mime: Schema.String,
1554
- filename: Schema.optional(Schema.String),
1555
- url: Schema.String,
1556
- source: Schema.optional(SessionV1.FilePartSource),
1557
- }),
1558
- ]).annotate({ discriminator: "type" }),
1559
- ),
1560
- ),
1561
- })
1562
- export type CommandInput = Schema.Schema.Type<typeof CommandInput>
1563
-
1564
- /** @internal Exported for testing */
1565
- export function createStructuredOutputTool(input: {
1566
- schema: Record<string, any>
1567
- onSuccess: (output: unknown) => void
1568
- }): AITool {
1569
- // Remove $schema property if present (not needed for tool input)
1570
- const { $schema: _, ...toolSchema } = input.schema
1571
-
1572
- return tool({
1573
- description: STRUCTURED_OUTPUT_DESCRIPTION,
1574
- inputSchema: jsonSchema(toolSchema as JSONSchema7),
1575
- async execute(args) {
1576
- // AI SDK validates args against inputSchema before calling execute()
1577
- input.onSuccess(args)
1578
- return {
1579
- output: "Structured output captured successfully.",
1580
- title: "Structured Output",
1581
- metadata: { valid: true },
1582
- }
1583
- },
1584
- toModelOutput({ output }) {
1585
- return {
1586
- type: "text",
1587
- value: output.output,
1588
- }
1589
- },
1590
- })
1591
- }
1592
- const bashRegex = /!`([^`]+)`/g
1593
- // Match [Image N] as single token, quoted strings, or non-space sequences
1594
- const argsRegex = /(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi
1595
- const placeholderRegex = /\$(\d+)/g
1596
- const quoteTrimRegex = /^["']|["']$/g
1597
-
1598
- export const node = LayerNode.make({
1599
- service: Service,
1600
- layer: layer,
1601
- deps: [
1602
- SessionStatus.node,
1603
- Session.node,
1604
- Agent.node,
1605
- Provider.node,
1606
- SessionProcessor.node,
1607
- SessionCompaction.node,
1608
- Plugin.node,
1609
- Command.node,
1610
- Config.node,
1611
- Permission.node,
1612
- FSUtil.node,
1613
- MCP.node,
1614
- LSP.node,
1615
- ToolRegistry.node,
1616
- Truncate.node,
1617
- Image.node,
1618
- CrossSpawnSpawner.node,
1619
- Instruction.node,
1620
- SessionRunState.node,
1621
- SessionRevert.node,
1622
- SessionSummary.node,
1623
- SystemPrompt.node,
1624
- LLM.node,
1625
- EventV2Bridge.node,
1626
- RuntimeFlags.node,
1627
- Database.node,
1628
- ],
1629
- })
1630
-
1631
- export * as SessionPrompt from "./prompt"