soraacode 0.1.0

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 (350) hide show
  1. package/AGENTS.md +131 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +15 -0
  4. package/bin/opencode +199 -0
  5. package/bin/soraacode +199 -0
  6. package/bunfig.toml +7 -0
  7. package/git +0 -0
  8. package/migration/20260511173437_session-metadata/migration.sql +1 -0
  9. package/migration/20260511173437_session-metadata/snapshot.json +1500 -0
  10. package/package.json +107 -0
  11. package/parsers-config.ts +1 -0
  12. package/script/bench-search.ts +94 -0
  13. package/script/bench-test-suite.ts +52 -0
  14. package/script/build-headless.ts +51 -0
  15. package/script/build.ts +245 -0
  16. package/script/generate.ts +14 -0
  17. package/script/httpapi-exercise.ts +1 -0
  18. package/script/postinstall.mjs +189 -0
  19. package/script/profile-test-files.ts +42 -0
  20. package/script/publish.ts +213 -0
  21. package/script/run-workspace-server +106 -0
  22. package/script/schema.ts +77 -0
  23. package/script/time.ts +6 -0
  24. package/script/trace-imports.ts +153 -0
  25. package/specs/effect/error-boundaries-plan.md +235 -0
  26. package/specs/effect/errors.md +207 -0
  27. package/specs/effect/facades.md +218 -0
  28. package/specs/effect/guide.md +247 -0
  29. package/specs/effect/instance-context.md +13 -0
  30. package/specs/effect/loose-ends.md +30 -0
  31. package/specs/effect/migration.md +62 -0
  32. package/specs/effect/routes.md +61 -0
  33. package/specs/effect/schema.md +88 -0
  34. package/specs/effect/server-package.md +58 -0
  35. package/specs/effect/todo.md +241 -0
  36. package/specs/effect/tools.md +88 -0
  37. package/specs/openapi-translation-cleanup.md +204 -0
  38. package/specs/tui-plugins.md +544 -0
  39. package/specs/v2/api.ts +67 -0
  40. package/specs/v2/message-shape.md +136 -0
  41. package/specs/v2/notifications.md +13 -0
  42. package/specs/v2/tui-command-shim.md +67 -0
  43. package/src/account/account.ts +481 -0
  44. package/src/account/repo.ts +171 -0
  45. package/src/account/schema.ts +99 -0
  46. package/src/account/url.ts +8 -0
  47. package/src/acp/agent.ts +95 -0
  48. package/src/acp/config-option.ts +206 -0
  49. package/src/acp/content.ts +269 -0
  50. package/src/acp/directory.ts +212 -0
  51. package/src/acp/error.ts +97 -0
  52. package/src/acp/event.ts +421 -0
  53. package/src/acp/permission.ts +254 -0
  54. package/src/acp/profile.ts +42 -0
  55. package/src/acp/service.ts +1226 -0
  56. package/src/acp/session.ts +232 -0
  57. package/src/acp/tool.ts +364 -0
  58. package/src/acp/usage.ts +243 -0
  59. package/src/agent/agent.ts +450 -0
  60. package/src/agent/generate.txt +75 -0
  61. package/src/agent/prompt/compaction.txt +5 -0
  62. package/src/agent/prompt/explore.txt +18 -0
  63. package/src/agent/prompt/summary.txt +11 -0
  64. package/src/agent/prompt/title.txt +44 -0
  65. package/src/agent/subagent-permissions.ts +27 -0
  66. package/src/audio.d.ts +14 -0
  67. package/src/auth/index.ts +97 -0
  68. package/src/background/job.ts +37 -0
  69. package/src/bus/global.ts +22 -0
  70. package/src/cli/bootstrap.ts +11 -0
  71. package/src/cli/cmd/cmd.ts +7 -0
  72. package/src/cli/cmd/serve.ts +24 -0
  73. package/src/cli/effect/prompt.ts +37 -0
  74. package/src/cli/effect-cmd.ts +96 -0
  75. package/src/cli/error.ts +130 -0
  76. package/src/cli/heap.ts +45 -0
  77. package/src/cli/logo.ts +2 -0
  78. package/src/cli/network.ts +80 -0
  79. package/src/cli/ui.ts +132 -0
  80. package/src/command/index.ts +177 -0
  81. package/src/command/template/initialize.txt +66 -0
  82. package/src/command/template/review.txt +101 -0
  83. package/src/config/agent.ts +59 -0
  84. package/src/config/command.ts +39 -0
  85. package/src/config/config.ts +707 -0
  86. package/src/config/entry-name.ts +19 -0
  87. package/src/config/managed.ts +69 -0
  88. package/src/config/markdown.ts +36 -0
  89. package/src/config/parse.ts +61 -0
  90. package/src/config/paths.ts +45 -0
  91. package/src/config/plugin.ts +79 -0
  92. package/src/config/v2-compat.ts +449 -0
  93. package/src/config/variable.ts +91 -0
  94. package/src/control-plane/adapters/index.ts +41 -0
  95. package/src/control-plane/adapters/worktree.ts +96 -0
  96. package/src/control-plane/dev/README.md +19 -0
  97. package/src/control-plane/dev/debug-workspace-plugin.ts +73 -0
  98. package/src/control-plane/types.ts +59 -0
  99. package/src/control-plane/util.ts +39 -0
  100. package/src/control-plane/workspace-adapter-runtime.ts +51 -0
  101. package/src/control-plane/workspace-context.ts +26 -0
  102. package/src/control-plane/workspace.ts +966 -0
  103. package/src/effect/app-node-builder-v1.ts +12 -0
  104. package/src/effect/app-runtime.ts +135 -0
  105. package/src/effect/bootstrap-runtime.ts +19 -0
  106. package/src/effect/bridge.ts +84 -0
  107. package/src/effect/config-service.ts +67 -0
  108. package/src/effect/instance-ref.ts +11 -0
  109. package/src/effect/instance-registry.ts +12 -0
  110. package/src/effect/instance-state.ts +69 -0
  111. package/src/effect/promise.ts +17 -0
  112. package/src/effect/run-service.ts +47 -0
  113. package/src/effect/runner.ts +217 -0
  114. package/src/effect/runtime-flags.ts +78 -0
  115. package/src/env/index.ts +41 -0
  116. package/src/event-manifest.ts +3 -0
  117. package/src/event-v2-bridge.ts +71 -0
  118. package/src/format/formatter.ts +404 -0
  119. package/src/format/index.ts +203 -0
  120. package/src/git/index.ts +348 -0
  121. package/src/id/id.ts +80 -0
  122. package/src/ide/index.ts +54 -0
  123. package/src/image/image.ts +172 -0
  124. package/src/index-headless.ts +89 -0
  125. package/src/index.ts +93 -0
  126. package/src/installation/index.ts +336 -0
  127. package/src/lsp/client.ts +650 -0
  128. package/src/lsp/diagnostic.ts +29 -0
  129. package/src/lsp/language.ts +121 -0
  130. package/src/lsp/launch.ts +21 -0
  131. package/src/lsp/lsp.ts +507 -0
  132. package/src/lsp/server.ts +1983 -0
  133. package/src/markdown.d.ts +4 -0
  134. package/src/mcp/auth.ts +163 -0
  135. package/src/mcp/browser.ts +37 -0
  136. package/src/mcp/catalog.ts +170 -0
  137. package/src/mcp/index.ts +1004 -0
  138. package/src/mcp/oauth-callback.ts +194 -0
  139. package/src/mcp/oauth-provider.ts +259 -0
  140. package/src/node.ts +4 -0
  141. package/src/patch/index.ts +686 -0
  142. package/src/permission/arity.ts +163 -0
  143. package/src/permission/evaluate.ts +1 -0
  144. package/src/permission/index.ts +223 -0
  145. package/src/plugin/github-copilot/copilot.ts +415 -0
  146. package/src/plugin/github-copilot/models.ts +261 -0
  147. package/src/plugin/index.ts +298 -0
  148. package/src/plugin/install.ts +439 -0
  149. package/src/plugin/loader.ts +237 -0
  150. package/src/plugin/meta.ts +188 -0
  151. package/src/plugin/openai/README.md +31 -0
  152. package/src/plugin/openai/codex.ts +575 -0
  153. package/src/plugin/openai/ws-pool.ts +271 -0
  154. package/src/plugin/openai/ws.ts +383 -0
  155. package/src/plugin/pty-environment.ts +24 -0
  156. package/src/plugin/shared.ts +323 -0
  157. package/src/project/bootstrap-service.ts +9 -0
  158. package/src/project/bootstrap.ts +58 -0
  159. package/src/project/instance-context.ts +24 -0
  160. package/src/project/instance-runtime.ts +16 -0
  161. package/src/project/instance-store.ts +213 -0
  162. package/src/project/project.ts +483 -0
  163. package/src/project/vcs.ts +423 -0
  164. package/src/provider/auth.ts +229 -0
  165. package/src/provider/error.ts +195 -0
  166. package/src/provider/model-status.ts +8 -0
  167. package/src/provider/provider.ts +1955 -0
  168. package/src/provider/transform.ts +1923 -0
  169. package/src/question/index.ts +161 -0
  170. package/src/question/schema.ts +4 -0
  171. package/src/server/auth.ts +48 -0
  172. package/src/server/event.ts +10 -0
  173. package/src/server/global-lifecycle.ts +28 -0
  174. package/src/server/mdns.ts +47 -0
  175. package/src/server/proxy-util.ts +48 -0
  176. package/src/server/routes/instance/httpapi/AGENTS.md +39 -0
  177. package/src/server/routes/instance/httpapi/api.ts +97 -0
  178. package/src/server/routes/instance/httpapi/errors.ts +193 -0
  179. package/src/server/routes/instance/httpapi/groups/config.ts +65 -0
  180. package/src/server/routes/instance/httpapi/groups/control-plane.ts +35 -0
  181. package/src/server/routes/instance/httpapi/groups/control.ts +76 -0
  182. package/src/server/routes/instance/httpapi/groups/event.ts +29 -0
  183. package/src/server/routes/instance/httpapi/groups/experimental.ts +275 -0
  184. package/src/server/routes/instance/httpapi/groups/file.ts +185 -0
  185. package/src/server/routes/instance/httpapi/groups/global.ts +139 -0
  186. package/src/server/routes/instance/httpapi/groups/instance.ts +206 -0
  187. package/src/server/routes/instance/httpapi/groups/mcp.ts +156 -0
  188. package/src/server/routes/instance/httpapi/groups/metadata.ts +18 -0
  189. package/src/server/routes/instance/httpapi/groups/permission.ts +61 -0
  190. package/src/server/routes/instance/httpapi/groups/project-copy.ts +32 -0
  191. package/src/server/routes/instance/httpapi/groups/project.ts +93 -0
  192. package/src/server/routes/instance/httpapi/groups/provider.ts +101 -0
  193. package/src/server/routes/instance/httpapi/groups/pty.ts +172 -0
  194. package/src/server/routes/instance/httpapi/groups/query.ts +12 -0
  195. package/src/server/routes/instance/httpapi/groups/question.ts +74 -0
  196. package/src/server/routes/instance/httpapi/groups/session.ts +462 -0
  197. package/src/server/routes/instance/httpapi/groups/sync.ts +113 -0
  198. package/src/server/routes/instance/httpapi/groups/tui.ts +208 -0
  199. package/src/server/routes/instance/httpapi/groups/workspace.ts +141 -0
  200. package/src/server/routes/instance/httpapi/handlers/config.ts +34 -0
  201. package/src/server/routes/instance/httpapi/handlers/control-plane.ts +37 -0
  202. package/src/server/routes/instance/httpapi/handlers/control.ts +43 -0
  203. package/src/server/routes/instance/httpapi/handlers/event.ts +99 -0
  204. package/src/server/routes/instance/httpapi/handlers/experimental.ts +193 -0
  205. package/src/server/routes/instance/httpapi/handlers/file.ts +139 -0
  206. package/src/server/routes/instance/httpapi/handlers/global.ts +126 -0
  207. package/src/server/routes/instance/httpapi/handlers/instance.ts +110 -0
  208. package/src/server/routes/instance/httpapi/handlers/mcp.ts +111 -0
  209. package/src/server/routes/instance/httpapi/handlers/permission.ts +41 -0
  210. package/src/server/routes/instance/httpapi/handlers/project-copy.ts +83 -0
  211. package/src/server/routes/instance/httpapi/handlers/project.ts +63 -0
  212. package/src/server/routes/instance/httpapi/handlers/provider.ts +116 -0
  213. package/src/server/routes/instance/httpapi/handlers/pty.ts +273 -0
  214. package/src/server/routes/instance/httpapi/handlers/question.ts +54 -0
  215. package/src/server/routes/instance/httpapi/handlers/session-errors.ts +21 -0
  216. package/src/server/routes/instance/httpapi/handlers/session.ts +442 -0
  217. package/src/server/routes/instance/httpapi/handlers/sync.ts +89 -0
  218. package/src/server/routes/instance/httpapi/handlers/tui.ts +131 -0
  219. package/src/server/routes/instance/httpapi/handlers/workspace.ts +102 -0
  220. package/src/server/routes/instance/httpapi/lifecycle.ts +54 -0
  221. package/src/server/routes/instance/httpapi/middleware/authorization.ts +150 -0
  222. package/src/server/routes/instance/httpapi/middleware/compression.ts +64 -0
  223. package/src/server/routes/instance/httpapi/middleware/cors-vary.ts +29 -0
  224. package/src/server/routes/instance/httpapi/middleware/error.ts +44 -0
  225. package/src/server/routes/instance/httpapi/middleware/fence.ts +25 -0
  226. package/src/server/routes/instance/httpapi/middleware/instance-context.ts +43 -0
  227. package/src/server/routes/instance/httpapi/middleware/proxy.ts +131 -0
  228. package/src/server/routes/instance/httpapi/middleware/schema-error.ts +41 -0
  229. package/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +250 -0
  230. package/src/server/routes/instance/httpapi/public.ts +537 -0
  231. package/src/server/routes/instance/httpapi/server.ts +325 -0
  232. package/src/server/routes/instance/httpapi/websocket-tracker.ts +60 -0
  233. package/src/server/server.ts +224 -0
  234. package/src/server/shared/fence.ts +60 -0
  235. package/src/server/shared/pty-ticket.ts +15 -0
  236. package/src/server/shared/public-ui.ts +12 -0
  237. package/src/server/shared/tui-control.ts +28 -0
  238. package/src/server/shared/ui.ts +108 -0
  239. package/src/server/shared/workspace-routing.ts +45 -0
  240. package/src/server/tui-event.ts +1 -0
  241. package/src/session/compaction.ts +608 -0
  242. package/src/session/instruction.ts +237 -0
  243. package/src/session/llm/AGENTS.md +90 -0
  244. package/src/session/llm/ai-sdk.ts +291 -0
  245. package/src/session/llm/native-request.ts +196 -0
  246. package/src/session/llm/native-runtime.ts +195 -0
  247. package/src/session/llm/request.ts +226 -0
  248. package/src/session/llm.ts +390 -0
  249. package/src/session/message-error.ts +14 -0
  250. package/src/session/message-v2.ts +742 -0
  251. package/src/session/message.ts +148 -0
  252. package/src/session/overflow.ts +34 -0
  253. package/src/session/processor.ts +732 -0
  254. package/src/session/prompt/build-switch.txt +5 -0
  255. package/src/session/prompt/default.txt +35 -0
  256. package/src/session/prompt/plan-mode.txt +70 -0
  257. package/src/session/prompt/plan.txt +26 -0
  258. package/src/session/prompt.ts +1631 -0
  259. package/src/session/reminders.ts +92 -0
  260. package/src/session/retry.ts +209 -0
  261. package/src/session/revert.ts +136 -0
  262. package/src/session/run-state.ts +151 -0
  263. package/src/session/schema.ts +26 -0
  264. package/src/session/session.ts +1016 -0
  265. package/src/session/status.ts +56 -0
  266. package/src/session/summary.ts +160 -0
  267. package/src/session/system.ts +123 -0
  268. package/src/session/todo.ts +74 -0
  269. package/src/session/tools.ts +590 -0
  270. package/src/share/session.ts +58 -0
  271. package/src/share/share-next.ts +371 -0
  272. package/src/skill/discovery.ts +140 -0
  273. package/src/skill/index.ts +354 -0
  274. package/src/snapshot/index.ts +807 -0
  275. package/src/sql.d.ts +4 -0
  276. package/src/storage/schema.ts +5 -0
  277. package/src/storage/storage.ts +327 -0
  278. package/src/sync/README.md +179 -0
  279. package/src/sync/schema.ts +11 -0
  280. package/src/temporary.ts +31 -0
  281. package/src/tool/apply_patch.ts +313 -0
  282. package/src/tool/apply_patch.txt +14 -0
  283. package/src/tool/code-mode.ts +310 -0
  284. package/src/tool/edit.ts +737 -0
  285. package/src/tool/edit.txt +13 -0
  286. package/src/tool/external-directory.ts +49 -0
  287. package/src/tool/glob.ts +76 -0
  288. package/src/tool/glob.txt +7 -0
  289. package/src/tool/grep.ts +115 -0
  290. package/src/tool/grep.txt +7 -0
  291. package/src/tool/invalid.ts +21 -0
  292. package/src/tool/json-schema.ts +164 -0
  293. package/src/tool/lsp.ts +113 -0
  294. package/src/tool/lsp.txt +1 -0
  295. package/src/tool/mcp-websearch.ts +96 -0
  296. package/src/tool/plan-enter.txt +1 -0
  297. package/src/tool/plan-exit.txt +1 -0
  298. package/src/tool/plan.ts +79 -0
  299. package/src/tool/question.ts +44 -0
  300. package/src/tool/question.txt +1 -0
  301. package/src/tool/read.ts +386 -0
  302. package/src/tool/read.txt +13 -0
  303. package/src/tool/registry.ts +455 -0
  304. package/src/tool/schema.ts +14 -0
  305. package/src/tool/shell/id.ts +19 -0
  306. package/src/tool/shell/prompt.ts +293 -0
  307. package/src/tool/shell/shell.txt +21 -0
  308. package/src/tool/shell.ts +645 -0
  309. package/src/tool/skill.ts +70 -0
  310. package/src/tool/skill.txt +1 -0
  311. package/src/tool/task.ts +371 -0
  312. package/src/tool/task.txt +11 -0
  313. package/src/tool/todo.ts +46 -0
  314. package/src/tool/todowrite.txt +11 -0
  315. package/src/tool/tool.ts +183 -0
  316. package/src/tool/truncate.ts +156 -0
  317. package/src/tool/truncation-dir.ts +4 -0
  318. package/src/tool/webfetch.ts +192 -0
  319. package/src/tool/webfetch.txt +9 -0
  320. package/src/tool/websearch.ts +143 -0
  321. package/src/tool/websearch.txt +9 -0
  322. package/src/tool/write.ts +104 -0
  323. package/src/tool/write.txt +11 -0
  324. package/src/util/archive.ts +17 -0
  325. package/src/util/bom.ts +27 -0
  326. package/src/util/data-url.ts +9 -0
  327. package/src/util/defer.ts +10 -0
  328. package/src/util/effect-http-client.ts +11 -0
  329. package/src/util/error.ts +16 -0
  330. package/src/util/filesystem.ts +251 -0
  331. package/src/util/html.ts +8 -0
  332. package/src/util/iife.ts +3 -0
  333. package/src/util/lazy.ts +20 -0
  334. package/src/util/local-context.ts +25 -0
  335. package/src/util/locale.ts +4 -0
  336. package/src/util/media.ts +26 -0
  337. package/src/util/process.ts +177 -0
  338. package/src/util/proxy-env.ts +72 -0
  339. package/src/util/queue.ts +32 -0
  340. package/src/util/record.ts +3 -0
  341. package/src/util/repository.ts +232 -0
  342. package/src/util/rpc.ts +66 -0
  343. package/src/util/signal.ts +12 -0
  344. package/src/util/timeout.ts +13 -0
  345. package/src/util/token.ts +1 -0
  346. package/src/util/wildcard.ts +59 -0
  347. package/src/worktree/index.ts +623 -0
  348. package/sst-env.d.ts +10 -0
  349. package/tsconfig.headless.json +13 -0
  350. package/tsconfig.json +16 -0
@@ -0,0 +1,1016 @@
1
+ import { LayerNode } from "@opencode-ai/core/effect/layer-node"
2
+ import { PermissionV1 } from "@opencode-ai/core/v1/permission"
3
+ import { Slug } from "@opencode-ai/core/util/slug"
4
+ import { SessionV1 } from "@opencode-ai/core/v1/session"
5
+ import { serviceUse } from "@opencode-ai/core/effect/service-use"
6
+ import path from "path"
7
+ import { BackgroundJob } from "@/background/job"
8
+ import { Decimal } from "decimal.js"
9
+ import type { ProviderMetadata, Usage } from "@opencode-ai/llm"
10
+ import { InstallationVersion } from "@opencode-ai/core/installation/version"
11
+ import { Database } from "@opencode-ai/core/database/database"
12
+ import { EventV2Bridge } from "@/event-v2-bridge"
13
+ import { SessionV2 } from "@opencode-ai/core/session"
14
+ import * as SessionExecutionLocal from "@opencode-ai/core/session/execution/local"
15
+ import { locationServiceMapLayer } from "@opencode-ai/core/location-services"
16
+
17
+ import { NotFoundError } from "@/storage/storage"
18
+ import { eq } from "drizzle-orm"
19
+ import { and } from "drizzle-orm"
20
+ import { gte } from "drizzle-orm"
21
+ import { isNull } from "drizzle-orm"
22
+ import { desc } from "drizzle-orm"
23
+ import { like } from "drizzle-orm"
24
+ import { sql } from "drizzle-orm"
25
+ import { inArray } from "drizzle-orm"
26
+ import { lt } from "drizzle-orm"
27
+ import { or } from "drizzle-orm"
28
+ import type { SQL } from "drizzle-orm"
29
+ import { PartTable, SessionTable } from "@opencode-ai/core/session/sql"
30
+ import { ProjectTable } from "@opencode-ai/core/project/sql"
31
+ import { MessageV2 } from "./message-v2"
32
+ import type { InstanceContext } from "../project/instance-context"
33
+ import { InstanceState } from "@/effect/instance-state"
34
+ import { Snapshot } from "@/snapshot"
35
+ import { ProjectV2 } from "@opencode-ai/core/project"
36
+ import { WorkspaceV2 } from "@opencode-ai/core/workspace"
37
+ import { SessionID, MessageID, PartID } from "./schema"
38
+
39
+ import type { Provider } from "@/provider/provider"
40
+ import { Global } from "@opencode-ai/core/global"
41
+ import { Effect, Layer, Option, Context, Schema, Types } from "effect"
42
+ import { NonNegativeInt, optional } from "@opencode-ai/core/schema"
43
+ import { RuntimeFlags } from "@/effect/runtime-flags"
44
+ import { ProviderV2 } from "@opencode-ai/core/provider"
45
+ import { ModelV2 } from "@opencode-ai/core/model"
46
+ import { SessionMessage } from "@opencode-ai/schema/session-message"
47
+
48
+ const parentTitlePrefix = "New session - "
49
+ const childTitlePrefix = "Child session - "
50
+
51
+ export function isDefaultTitle(title: string) {
52
+ return new RegExp(
53
+ `^(${parentTitlePrefix}|${childTitlePrefix})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$`,
54
+ ).test(title)
55
+ }
56
+
57
+ type SessionRow = typeof SessionTable.$inferSelect
58
+
59
+ export function fromRow(row: SessionRow): Info {
60
+ const summary =
61
+ row.summary_additions !== null || row.summary_deletions !== null || row.summary_files !== null
62
+ ? {
63
+ additions: row.summary_additions ?? 0,
64
+ deletions: row.summary_deletions ?? 0,
65
+ files: row.summary_files ?? 0,
66
+ diffs: row.summary_diffs ?? undefined,
67
+ }
68
+ : undefined
69
+ const share = row.share_url ? { url: row.share_url } : undefined
70
+ const revert = row.revert
71
+ ? {
72
+ messageID: MessageID.make(row.revert.messageID),
73
+ partID: row.revert.partID ? PartID.make(row.revert.partID) : undefined,
74
+ snapshot: row.revert.snapshot,
75
+ diff: row.revert.diff,
76
+ }
77
+ : undefined
78
+ return {
79
+ id: row.id,
80
+ slug: row.slug,
81
+ projectID: row.project_id,
82
+ workspaceID: row.workspace_id ?? undefined,
83
+ directory: row.directory,
84
+ path: row.path ?? undefined,
85
+ parentID: row.parent_id ?? undefined,
86
+ title: row.title,
87
+ agent: row.agent ?? undefined,
88
+ model: row.model
89
+ ? {
90
+ id: ModelV2.ID.make(row.model.id),
91
+ providerID: ProviderV2.ID.make(row.model.providerID),
92
+ variant: row.model.variant,
93
+ }
94
+ : undefined,
95
+ version: row.version,
96
+ summary,
97
+ cost: row.cost,
98
+ tokens: {
99
+ input: row.tokens_input,
100
+ output: row.tokens_output,
101
+ reasoning: row.tokens_reasoning,
102
+ cache: {
103
+ read: row.tokens_cache_read,
104
+ write: row.tokens_cache_write,
105
+ },
106
+ },
107
+ share,
108
+ metadata: row.metadata ?? undefined,
109
+ revert,
110
+ permission: row.permission ? [...row.permission] : undefined,
111
+ time: {
112
+ created: row.time_created,
113
+ updated: row.time_updated,
114
+ compacting: row.time_compacting ?? undefined,
115
+ archived: row.time_archived ?? undefined,
116
+ },
117
+ }
118
+ }
119
+
120
+ export function toRow(info: Info) {
121
+ return {
122
+ id: info.id,
123
+ project_id: info.projectID,
124
+ workspace_id: info.workspaceID,
125
+ parent_id: info.parentID,
126
+ slug: info.slug,
127
+ directory: info.directory,
128
+ path: info.path,
129
+ title: info.title,
130
+ agent: info.agent,
131
+ model: info.model,
132
+ version: info.version,
133
+ share_url: info.share?.url,
134
+ summary_additions: info.summary?.additions,
135
+ summary_deletions: info.summary?.deletions,
136
+ summary_files: info.summary?.files,
137
+ summary_diffs: info.summary?.diffs,
138
+ metadata: info.metadata,
139
+ cost: info.cost ?? 0,
140
+ tokens_input: (info.tokens ?? EmptyTokens).input,
141
+ tokens_output: (info.tokens ?? EmptyTokens).output,
142
+ tokens_reasoning: (info.tokens ?? EmptyTokens).reasoning,
143
+ tokens_cache_read: (info.tokens ?? EmptyTokens).cache.read,
144
+ tokens_cache_write: (info.tokens ?? EmptyTokens).cache.write,
145
+ revert: info.revert
146
+ ? {
147
+ messageID: SessionMessage.ID.make(info.revert.messageID),
148
+ partID: info.revert.partID,
149
+ snapshot: info.revert.snapshot,
150
+ diff: info.revert.diff,
151
+ }
152
+ : null,
153
+ permission: info.permission,
154
+ time_created: info.time.created,
155
+ time_updated: info.time.updated,
156
+ time_compacting: info.time.compacting,
157
+ time_archived: info.time.archived,
158
+ }
159
+ }
160
+
161
+ function getForkedTitle(title: string): string {
162
+ const match = title.match(/^(.+) \(fork #(\d+)\)$/)
163
+ if (match) {
164
+ const base = match[1]
165
+ const num = parseInt(match[2], 10)
166
+ return `${base} (fork #${num + 1})`
167
+ }
168
+ return `${title} (fork #1)`
169
+ }
170
+
171
+ function sessionPath(worktree: string, cwd: string) {
172
+ return path.relative(path.resolve(worktree), cwd).replaceAll("\\", "/")
173
+ }
174
+
175
+ const Summary = Schema.Struct({
176
+ additions: Schema.Finite,
177
+ deletions: Schema.Finite,
178
+ files: Schema.Finite,
179
+ diffs: optional(Schema.Array(Snapshot.FileDiff)),
180
+ })
181
+
182
+ const Tokens = Schema.Struct({
183
+ input: Schema.Finite,
184
+ output: Schema.Finite,
185
+ reasoning: Schema.Finite,
186
+ cache: Schema.Struct({
187
+ read: Schema.Finite,
188
+ write: Schema.Finite,
189
+ }),
190
+ })
191
+
192
+ const EmptyTokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
193
+
194
+ const Share = Schema.Struct({
195
+ url: Schema.String,
196
+ })
197
+
198
+ // Legacy HTTP accepted negative values here. Keep archive timestamps permissive
199
+ // while excluding non-finite values that cannot round-trip through JSON.
200
+ export const ArchivedTimestamp = Schema.Finite
201
+
202
+ const Time = Schema.Struct({
203
+ created: NonNegativeInt,
204
+ updated: NonNegativeInt,
205
+ compacting: optional(NonNegativeInt),
206
+ archived: optional(ArchivedTimestamp),
207
+ })
208
+
209
+ const Revert = Schema.Struct({
210
+ messageID: MessageID,
211
+ partID: optional(PartID),
212
+ snapshot: optional(Schema.String),
213
+ diff: optional(Schema.String),
214
+ })
215
+
216
+ const Model = Schema.Struct({
217
+ id: ModelV2.ID,
218
+ providerID: ProviderV2.ID,
219
+ variant: optional(Schema.String),
220
+ })
221
+
222
+ export const Metadata = Schema.Record(Schema.String, Schema.Any)
223
+
224
+ export const Info = Schema.Struct({
225
+ id: SessionID,
226
+ slug: Schema.String,
227
+ projectID: ProjectV2.ID,
228
+ workspaceID: optional(WorkspaceV2.ID),
229
+ directory: Schema.String,
230
+ path: optional(Schema.String),
231
+ parentID: optional(SessionID),
232
+ summary: optional(Summary),
233
+ cost: optional(Schema.Finite),
234
+ tokens: optional(Tokens),
235
+ share: optional(Share),
236
+ title: Schema.String,
237
+ agent: optional(Schema.String),
238
+ model: optional(Model),
239
+ version: Schema.String,
240
+ metadata: optional(Metadata),
241
+ time: Time,
242
+ permission: optional(PermissionV1.Ruleset),
243
+ revert: optional(Revert),
244
+ }).annotate({ identifier: "Session" })
245
+ export type Info = Types.DeepMutable<Schema.Schema.Type<typeof Info>>
246
+
247
+ export const ProjectInfo = Schema.Struct({
248
+ id: ProjectV2.ID,
249
+ name: optional(Schema.String),
250
+ worktree: Schema.String,
251
+ }).annotate({ identifier: "ProjectSummary" })
252
+ export type ProjectInfo = Types.DeepMutable<Schema.Schema.Type<typeof ProjectInfo>>
253
+
254
+ export const GlobalInfo = Schema.Struct({
255
+ ...Info.fields,
256
+ project: Schema.NullOr(ProjectInfo),
257
+ }).annotate({ identifier: "GlobalSession" })
258
+ export type GlobalInfo = Types.DeepMutable<Schema.Schema.Type<typeof GlobalInfo>>
259
+
260
+ export const CreateInput = Schema.optional(
261
+ Schema.Struct({
262
+ parentID: Schema.optional(SessionID),
263
+ title: Schema.optional(Schema.String),
264
+ agent: Schema.optional(Schema.String),
265
+ model: Schema.optional(Model),
266
+ metadata: Schema.optional(Metadata),
267
+ permission: Schema.optional(PermissionV1.Ruleset),
268
+ workspaceID: Schema.optional(WorkspaceV2.ID),
269
+ }),
270
+ )
271
+ export type CreateInput = Types.DeepMutable<Schema.Schema.Type<typeof CreateInput>>
272
+
273
+ export const ForkInput = Schema.Struct({
274
+ sessionID: SessionID,
275
+ messageID: Schema.optional(MessageID),
276
+ })
277
+ export const GetInput = SessionID
278
+ export const ChildrenInput = SessionID
279
+ export const RemoveInput = SessionID
280
+ export const SetTitleInput = Schema.Struct({ sessionID: SessionID, title: Schema.String })
281
+ export const SetArchivedInput = Schema.Struct({
282
+ sessionID: SessionID,
283
+ time: Schema.optional(ArchivedTimestamp),
284
+ })
285
+ export const SetMetadataInput = Schema.Struct({
286
+ sessionID: SessionID,
287
+ metadata: Metadata,
288
+ })
289
+ export const SetPermissionInput = Schema.Struct({
290
+ sessionID: SessionID,
291
+ permission: PermissionV1.Ruleset,
292
+ })
293
+ export const SetRevertInput = Schema.Struct({
294
+ sessionID: SessionID,
295
+ revert: Schema.optional(Revert),
296
+ summary: Schema.optional(Summary),
297
+ })
298
+ export const MessagesInput = Schema.Struct({
299
+ sessionID: SessionID,
300
+ limit: Schema.optional(NonNegativeInt),
301
+ })
302
+ export type ListInput = {
303
+ directory?: string
304
+ scope?: "project"
305
+ path?: string
306
+ workspaceID?: WorkspaceV2.ID
307
+ roots?: boolean
308
+ start?: number
309
+ search?: string
310
+ limit?: number
311
+ }
312
+
313
+ export type GlobalListInput = {
314
+ directory?: string
315
+ roots?: boolean
316
+ start?: number
317
+ cursor?: number
318
+ search?: string
319
+ limit?: number
320
+ archived?: boolean
321
+ }
322
+
323
+ export const Event = {
324
+ Created: SessionV1.Event.Created,
325
+ Updated: SessionV1.Event.Updated,
326
+ Deleted: SessionV1.Event.Deleted,
327
+ Diff: SessionV1.Event.Diff,
328
+ Error: SessionV1.Event.Error,
329
+ }
330
+
331
+ export function plan(input: { slug: string; time: { created: number } }, instance: InstanceContext) {
332
+ const base = instance.project.vcs
333
+ ? path.join(instance.worktree, ".opencode", "plans")
334
+ : path.join(Global.Path.data, "plans")
335
+ return path.join(base, [input.time.created, input.slug].join("-") + ".md")
336
+ }
337
+
338
+ export const getUsage = (input: { model: Provider.Model; usage: Usage; metadata?: ProviderMetadata }) => {
339
+ const finite = (value: number) => (Number.isFinite(value) ? value : 0)
340
+ const safe = (value: number) => Math.max(0, finite(value))
341
+ const inputTokens = safe(input.usage.inputTokens ?? 0)
342
+ const outputTokens = safe(input.usage.outputTokens ?? 0)
343
+ const reasoningTokens = safe(input.usage.reasoningTokens ?? 0)
344
+
345
+ const cacheReadInputTokens = safe(input.usage.cacheReadInputTokens ?? 0)
346
+ const cacheWriteInputTokens = safe(
347
+ Number(
348
+ input.usage.cacheWriteInputTokens ??
349
+ input.metadata?.["anthropic"]?.["cacheCreationInputTokens"] ??
350
+ // google-vertex-anthropic returns metadata under "vertex" key
351
+ // (AnthropicMessagesLanguageModel custom provider key from 'vertex.anthropic.messages')
352
+ input.metadata?.["vertex"]?.["cacheCreationInputTokens"] ??
353
+ // @ts-expect-error
354
+ input.metadata?.["bedrock"]?.["usage"]?.["cacheWriteInputTokens"] ??
355
+ // @ts-expect-error
356
+ input.metadata?.["venice"]?.["usage"]?.["cacheCreationInputTokens"] ??
357
+ 0,
358
+ ),
359
+ )
360
+
361
+ // AI SDK v6 normalized inputTokens to include cached tokens across all providers
362
+ // (including Anthropic/Bedrock which previously excluded them). Always subtract cache
363
+ // tokens to get the non-cached input count for separate cost calculation.
364
+ const adjustedInputTokens = safe(inputTokens - cacheReadInputTokens - cacheWriteInputTokens)
365
+
366
+ const total = input.usage.totalTokens
367
+
368
+ const tokens = {
369
+ total,
370
+ input: adjustedInputTokens,
371
+ output: safe(outputTokens - reasoningTokens),
372
+ reasoning: reasoningTokens,
373
+ cache: {
374
+ write: cacheWriteInputTokens,
375
+ read: cacheReadInputTokens,
376
+ },
377
+ }
378
+
379
+ const contextTokens = inputTokens
380
+ const costInfo =
381
+ input.model.cost?.tiers
382
+ ?.filter((item) => item.tier.type === "context" && contextTokens > item.tier.size)
383
+ .sort((a, b) => b.tier.size - a.tier.size)[0] ??
384
+ (input.model.cost?.experimentalOver200K && contextTokens > 200_000
385
+ ? input.model.cost.experimentalOver200K
386
+ : input.model.cost)
387
+ const totalNanoAiu = input.metadata?.["copilot"]?.["totalNanoAiu"]
388
+ return {
389
+ cost:
390
+ typeof totalNanoAiu === "number" && Number.isFinite(totalNanoAiu) && totalNanoAiu >= 0
391
+ ? new Decimal(totalNanoAiu).div(100_000_000_000).toNumber()
392
+ : safe(
393
+ new Decimal(0)
394
+ .add(new Decimal(tokens.input).mul(finite(costInfo?.input ?? 0)).div(1_000_000))
395
+ .add(new Decimal(tokens.output).mul(finite(costInfo?.output ?? 0)).div(1_000_000))
396
+ .add(new Decimal(tokens.cache.read).mul(finite(costInfo?.cache?.read ?? 0)).div(1_000_000))
397
+ .add(new Decimal(tokens.cache.write).mul(finite(costInfo?.cache?.write ?? 0)).div(1_000_000))
398
+ // TODO: update models.dev to have better pricing model, for now:
399
+ // charge reasoning tokens at the same rate as output tokens
400
+ .add(new Decimal(tokens.reasoning).mul(finite(costInfo?.output ?? 0)).div(1_000_000))
401
+ .toNumber(),
402
+ ),
403
+ tokens,
404
+ }
405
+ }
406
+
407
+ export class BusyError extends Schema.TaggedErrorClass<BusyError>()("SessionBusyError", {
408
+ sessionID: SessionID,
409
+ }) {}
410
+
411
+ export type NotFound = NotFoundError
412
+
413
+ export interface Interface {
414
+ readonly list: (input?: ListInput) => Effect.Effect<Info[]>
415
+ readonly listGlobal: (input?: GlobalListInput) => Effect.Effect<GlobalInfo[]>
416
+ readonly create: (input?: {
417
+ parentID?: SessionID
418
+ title?: string
419
+ agent?: string
420
+ model?: Schema.Schema.Type<typeof Model>
421
+ metadata?: typeof Metadata.Type
422
+ permission?: PermissionV1.Ruleset
423
+ workspaceID?: WorkspaceV2.ID
424
+ }) => Effect.Effect<Info>
425
+ readonly fork: (input: { sessionID: SessionID; messageID?: MessageID }) => Effect.Effect<Info, NotFound>
426
+ readonly touch: (sessionID: SessionID) => Effect.Effect<void>
427
+ readonly get: (id: SessionID) => Effect.Effect<Info, NotFound>
428
+ readonly setTitle: (input: { sessionID: SessionID; title: string }) => Effect.Effect<void>
429
+ readonly setArchived: (input: { sessionID: SessionID; time?: number }) => Effect.Effect<void>
430
+ readonly setMetadata: (input: typeof SetMetadataInput.Type) => Effect.Effect<void>
431
+ readonly setAgentModel: (input: {
432
+ sessionID: SessionID
433
+ agent: string
434
+ model: NonNullable<Info["model"]>
435
+ time: number
436
+ }) => Effect.Effect<void>
437
+ readonly setPermission: (input: { sessionID: SessionID; permission: PermissionV1.Ruleset }) => Effect.Effect<void>
438
+ readonly setRevert: (input: {
439
+ sessionID: SessionID
440
+ revert: Info["revert"]
441
+ summary: Info["summary"]
442
+ }) => Effect.Effect<void>
443
+ readonly clearRevert: (sessionID: SessionID) => Effect.Effect<void>
444
+ readonly setSummary: (input: { sessionID: SessionID; summary: Info["summary"] }) => Effect.Effect<void>
445
+ readonly setShare: (input: { sessionID: SessionID; share: Info["share"] }) => Effect.Effect<void>
446
+ readonly setWorkspace: (input: { sessionID: SessionID; workspaceID: Info["workspaceID"] }) => Effect.Effect<void>
447
+ readonly diff: (sessionID: SessionID) => Effect.Effect<Snapshot.FileDiff[]>
448
+ readonly messages: (input: { sessionID: SessionID; limit?: number }) => Effect.Effect<SessionV1.WithParts[], NotFound>
449
+ readonly children: (parentID: SessionID) => Effect.Effect<Info[]>
450
+ readonly remove: (sessionID: SessionID) => Effect.Effect<void, NotFound>
451
+ readonly updateMessage: <T extends SessionV1.Info>(msg: T) => Effect.Effect<T>
452
+ readonly removeMessage: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect<MessageID>
453
+ readonly removePart: (input: { sessionID: SessionID; messageID: MessageID; partID: PartID }) => Effect.Effect<PartID>
454
+ readonly getPart: (input: {
455
+ sessionID: SessionID
456
+ messageID: MessageID
457
+ partID: PartID
458
+ }) => Effect.Effect<SessionV1.Part | undefined>
459
+ readonly updatePart: <T extends SessionV1.Part>(part: T) => Effect.Effect<T>
460
+ readonly updatePartDelta: (input: {
461
+ sessionID: SessionID
462
+ messageID: MessageID
463
+ partID: PartID
464
+ field: string
465
+ delta: string
466
+ }) => Effect.Effect<void>
467
+ /** Finds the first message matching the predicate, searching newest-first. */
468
+ readonly findMessage: (
469
+ sessionID: SessionID,
470
+ predicate: (msg: SessionV1.WithParts) => boolean,
471
+ ) => Effect.Effect<Option.Option<SessionV1.WithParts>, NotFound>
472
+ }
473
+
474
+ export class Service extends Context.Service<Service, Interface>()("@opencode/Session") {}
475
+
476
+ export const use = serviceUse(Service)
477
+
478
+ export type Patch = Omit<Partial<Info>, "time" | "share" | "summary" | "revert" | "permission"> & {
479
+ time?: Partial<Info["time"]>
480
+ share?: Partial<NonNullable<Info["share"]>> | null
481
+ summary?: Info["summary"] | null
482
+ revert?: Info["revert"] | null
483
+ permission?: Info["permission"] | null
484
+ }
485
+
486
+ const layer: Layer.Layer<
487
+ Service,
488
+ never,
489
+ BackgroundJob.Service | RuntimeFlags.Service | Database.Service | EventV2Bridge.Service
490
+ > = Layer.effect(
491
+ Service,
492
+ Effect.gen(function* () {
493
+ const { db } = yield* Database.Service
494
+ const database = yield* Database.Service
495
+ const background = yield* BackgroundJob.Service
496
+ const events = yield* EventV2Bridge.Service
497
+ const flags = yield* RuntimeFlags.Service
498
+
499
+ const createNext = Effect.fn("Session.createNext")(function* (input: {
500
+ id?: SessionID
501
+ title?: string
502
+ agent?: string
503
+ model?: Schema.Schema.Type<typeof Model>
504
+ parentID?: SessionID
505
+ workspaceID?: WorkspaceV2.ID
506
+ directory: string
507
+ path?: string
508
+ metadata?: typeof Metadata.Type
509
+ permission?: PermissionV1.Ruleset
510
+ }) {
511
+ const ctx = yield* InstanceState.context
512
+ const result: Info = {
513
+ id: SessionID.descending(input.id),
514
+ slug: Slug.create(),
515
+ version: InstallationVersion,
516
+ projectID: ctx.project.id,
517
+ directory: input.directory,
518
+ path: input.path,
519
+ workspaceID: input.workspaceID,
520
+ parentID: input.parentID,
521
+ title: input.title ?? (input.parentID ? childTitlePrefix : parentTitlePrefix) + new Date().toISOString(),
522
+ agent: input.agent,
523
+ model: input.model,
524
+ metadata: input.metadata,
525
+ permission: input.permission ? [...input.permission] : undefined,
526
+ cost: 0,
527
+ tokens: EmptyTokens,
528
+ time: {
529
+ created: Date.now(),
530
+ updated: Date.now(),
531
+ },
532
+ }
533
+ yield* Effect.logInfo("created", result)
534
+
535
+ yield* events.publish(SessionV1.Event.Created, { sessionID: result.id, info: result })
536
+
537
+ return result
538
+ })
539
+
540
+ const get = Effect.fn("Session.get")(function* (id: SessionID) {
541
+ const row = yield* db.select().from(SessionTable).where(eq(SessionTable.id, id)).get().pipe(Effect.orDie)
542
+ if (!row) return yield* Effect.fail(new NotFoundError({ message: `Session not found: ${id}` }))
543
+ return fromRow(row)
544
+ })
545
+
546
+ const list = Effect.fn("Session.list")(function* (input?: ListInput) {
547
+ const ctx = yield* InstanceState.context
548
+ return yield* listByProject(db, {
549
+ projectID: ctx.project.id,
550
+ experimentalWorkspaces: flags.experimentalWorkspaces,
551
+ ...input,
552
+ })
553
+ })
554
+
555
+ const listGlobal = Effect.fn("Session.listGlobal")(function* (input?: GlobalListInput) {
556
+ const conditions: SQL[] = []
557
+ if (input?.directory) conditions.push(eq(SessionTable.directory, input.directory))
558
+ if (input?.roots) conditions.push(isNull(SessionTable.parent_id))
559
+ if (input?.start) conditions.push(gte(SessionTable.time_updated, input.start))
560
+ if (input?.cursor) conditions.push(lt(SessionTable.time_updated, input.cursor))
561
+ if (input?.search) conditions.push(like(SessionTable.title, `%${input.search}%`))
562
+ if (!input?.archived) conditions.push(isNull(SessionTable.time_archived))
563
+
564
+ const query =
565
+ conditions.length > 0
566
+ ? db
567
+ .select()
568
+ .from(SessionTable)
569
+ .where(and(...conditions))
570
+ : db.select().from(SessionTable)
571
+ const rows = yield* query
572
+ .orderBy(desc(SessionTable.time_updated), desc(SessionTable.id))
573
+ .limit(input?.limit ?? 100)
574
+ .all()
575
+ .pipe(Effect.orDie)
576
+ const ids = [...new Set(rows.map((row) => row.project_id))]
577
+ const projects = new Map<string, ProjectInfo>()
578
+ if (ids.length > 0) {
579
+ const items = yield* db
580
+ .select({ id: ProjectTable.id, name: ProjectTable.name, worktree: ProjectTable.worktree })
581
+ .from(ProjectTable)
582
+ .where(inArray(ProjectTable.id, ids))
583
+ .all()
584
+ .pipe(Effect.orDie)
585
+ for (const item of items) {
586
+ projects.set(item.id, {
587
+ id: item.id,
588
+ name: item.name ?? undefined,
589
+ worktree: item.worktree,
590
+ })
591
+ }
592
+ }
593
+ return rows.map((row) => ({ ...fromRow(row), project: projects.get(row.project_id) ?? null }))
594
+ })
595
+
596
+ const children = Effect.fn("Session.children")(function* (parentID: SessionID) {
597
+ const rows = yield* db
598
+ .select()
599
+ .from(SessionTable)
600
+ .where(and(eq(SessionTable.parent_id, parentID)))
601
+ .all()
602
+ .pipe(Effect.orDie)
603
+ return rows.map(fromRow)
604
+ })
605
+
606
+ const remove: Interface["remove"] = Effect.fnUntraced(function* (sessionID: SessionID) {
607
+ const session = yield* get(sessionID)
608
+ try {
609
+ // `remove` needs to work in all cases, such as broken sessions that
610
+ // run cleanup without instance state.
611
+ const hasInstance = yield* InstanceState.directory.pipe(
612
+ Effect.as(true),
613
+ Effect.catchCause(() => Effect.succeed(false)),
614
+ )
615
+
616
+ if (hasInstance) yield* cancelBackgroundJobs(background, sessionID)
617
+ const kids = yield* children(sessionID)
618
+ for (const child of kids) {
619
+ yield* remove(child.id)
620
+ }
621
+
622
+ yield* events.publish(SessionV1.Event.Deleted, { sessionID, info: session })
623
+ yield* events.remove(sessionID)
624
+ } catch (error) {
625
+ yield* Effect.logError("failed to remove session", { sessionID, error })
626
+ }
627
+ })
628
+
629
+ const updateMessage = <T extends SessionV1.Info>(msg: T): Effect.Effect<T> =>
630
+ Effect.gen(function* () {
631
+ yield* events.publish(SessionV1.Event.MessageUpdated, { sessionID: msg.sessionID, info: msg })
632
+ return msg
633
+ }).pipe(Effect.withSpan("Session.updateMessage"))
634
+
635
+ const updatePart = <T extends SessionV1.Part>(part: T): Effect.Effect<T> =>
636
+ Effect.gen(function* () {
637
+ yield* events.publish(SessionV1.Event.PartUpdated, {
638
+ sessionID: part.sessionID,
639
+ part: structuredClone(part),
640
+ time: Date.now(),
641
+ })
642
+ return part
643
+ }).pipe(Effect.withSpan("Session.updatePart"))
644
+
645
+ const getPart: Interface["getPart"] = Effect.fn("Session.getPart")(function* (input) {
646
+ const row = yield* db
647
+ .select()
648
+ .from(PartTable)
649
+ .where(
650
+ and(
651
+ eq(PartTable.session_id, input.sessionID),
652
+ eq(PartTable.message_id, input.messageID),
653
+ eq(PartTable.id, input.partID),
654
+ ),
655
+ )
656
+ .get()
657
+ .pipe(Effect.orDie)
658
+ if (!row) return
659
+ return {
660
+ ...row.data,
661
+ id: row.id,
662
+ sessionID: row.session_id,
663
+ messageID: row.message_id,
664
+ } as SessionV1.Part
665
+ })
666
+
667
+ const create = Effect.fn("Session.create")(function* (input?: {
668
+ parentID?: SessionID
669
+ title?: string
670
+ agent?: string
671
+ model?: Schema.Schema.Type<typeof Model>
672
+ metadata?: typeof Metadata.Type
673
+ permission?: PermissionV1.Ruleset
674
+ workspaceID?: WorkspaceV2.ID
675
+ }) {
676
+ const ctx = yield* InstanceState.context
677
+ const workspace = yield* InstanceState.workspaceID
678
+ return yield* createNext({
679
+ parentID: input?.parentID,
680
+ directory: ctx.directory,
681
+ path: sessionPath(ctx.worktree, ctx.directory),
682
+ title: input?.title,
683
+ agent: input?.agent,
684
+ model: input?.model,
685
+ metadata: input?.metadata,
686
+ permission: input?.permission,
687
+ workspaceID: input?.workspaceID ?? workspace,
688
+ })
689
+ })
690
+
691
+ const fork = Effect.fn("Session.fork")(function* (input: { sessionID: SessionID; messageID?: MessageID }) {
692
+ const ctx = yield* InstanceState.context
693
+ const original = yield* get(input.sessionID)
694
+ const title = getForkedTitle(original.title)
695
+ const session = yield* createNext({
696
+ directory: ctx.directory,
697
+ path: sessionPath(ctx.worktree, ctx.directory),
698
+ workspaceID: original.workspaceID,
699
+ title,
700
+ metadata: structuredClone(original.metadata),
701
+ })
702
+ const msgs = yield* messages({ sessionID: input.sessionID })
703
+ const idMap = new Map<string, MessageID>()
704
+ const target = input.messageID ? msgs.findIndex((msg) => msg.info.id === input.messageID) : msgs.length
705
+
706
+ for (const msg of msgs.slice(0, target < 0 ? msgs.length : target)) {
707
+ const newID = MessageID.ascending()
708
+ idMap.set(msg.info.id, newID)
709
+
710
+ const parentID = msg.info.role === "assistant" && msg.info.parentID ? idMap.get(msg.info.parentID) : undefined
711
+ const cloned = yield* updateMessage({
712
+ ...msg.info,
713
+ sessionID: session.id,
714
+ id: newID,
715
+ ...(parentID && { parentID }),
716
+ })
717
+
718
+ for (const part of msg.parts) {
719
+ const p: SessionV1.Part = {
720
+ ...part,
721
+ id: PartID.ascending(),
722
+ messageID: cloned.id,
723
+ sessionID: session.id,
724
+ }
725
+ if (p.type === "compaction" && p.tail_start_id) {
726
+ p.tail_start_id = idMap.get(p.tail_start_id)
727
+ }
728
+ yield* updatePart(p)
729
+ }
730
+ }
731
+ return session
732
+ })
733
+
734
+ const patch = (sessionID: SessionID, info: Patch) =>
735
+ Effect.gen(function* () {
736
+ const current = yield* get(sessionID)
737
+ const next = {
738
+ ...current,
739
+ ...info,
740
+ time: info.time ? { ...current.time, ...info.time } : current.time,
741
+ share: info.share === null ? undefined : info.share ? { ...current.share, ...info.share } : current.share,
742
+ summary: info.summary === null ? undefined : (info.summary ?? current.summary),
743
+ revert: info.revert === null ? undefined : (info.revert ?? current.revert),
744
+ permission: info.permission === null ? undefined : (info.permission ?? current.permission),
745
+ } as Info
746
+ yield* events.publish(SessionV1.Event.Updated, { sessionID, info: next })
747
+ })
748
+
749
+ const touch = Effect.fn("Session.touch")(function* (sessionID: SessionID) {
750
+ yield* patch(sessionID, { time: { updated: Date.now() } }).pipe(Effect.orDie)
751
+ })
752
+
753
+ const setTitle = Effect.fn("Session.setTitle")(function* (input: { sessionID: SessionID; title: string }) {
754
+ yield* patch(input.sessionID, { title: input.title }).pipe(Effect.orDie)
755
+ })
756
+
757
+ const setArchived = Effect.fn("Session.setArchived")(function* (input: { sessionID: SessionID; time?: number }) {
758
+ yield* patch(input.sessionID, { time: { archived: input.time } }).pipe(Effect.orDie)
759
+ })
760
+
761
+ const setMetadata = Effect.fn("Session.setMetadata")(function* (input: typeof SetMetadataInput.Type) {
762
+ yield* patch(input.sessionID, { metadata: input.metadata, time: { updated: Date.now() } }).pipe(Effect.orDie)
763
+ })
764
+
765
+ const setAgentModel = Effect.fn("Session.setAgentModel")(function* (input: {
766
+ sessionID: SessionID
767
+ agent: string
768
+ model: NonNullable<Info["model"]>
769
+ time: number
770
+ }) {
771
+ yield* patch(input.sessionID, {
772
+ agent: input.agent,
773
+ model: input.model,
774
+ time: { updated: input.time },
775
+ }).pipe(Effect.orDie)
776
+ })
777
+
778
+ const setPermission = Effect.fn("Session.setPermission")(function* (input: {
779
+ sessionID: SessionID
780
+ permission: PermissionV1.Ruleset
781
+ }) {
782
+ yield* patch(input.sessionID, { permission: [...input.permission], time: { updated: Date.now() } }).pipe(
783
+ Effect.orDie,
784
+ )
785
+ })
786
+
787
+ const setRevert = Effect.fn("Session.setRevert")(function* (input: {
788
+ sessionID: SessionID
789
+ revert: Info["revert"]
790
+ summary: Info["summary"]
791
+ }) {
792
+ yield* patch(input.sessionID, {
793
+ summary: input.summary,
794
+ time: { updated: Date.now() },
795
+ revert: input.revert,
796
+ }).pipe(Effect.orDie)
797
+ })
798
+
799
+ const clearRevert = Effect.fn("Session.clearRevert")(function* (sessionID: SessionID) {
800
+ yield* patch(sessionID, { time: { updated: Date.now() }, revert: null }).pipe(Effect.orDie)
801
+ })
802
+
803
+ const setSummary = Effect.fn("Session.setSummary")(function* (input: {
804
+ sessionID: SessionID
805
+ summary: Info["summary"]
806
+ }) {
807
+ yield* patch(input.sessionID, { time: { updated: Date.now() }, summary: input.summary }).pipe(Effect.orDie)
808
+ })
809
+
810
+ const setShare = Effect.fn("Session.setShare")(function* (input: { sessionID: SessionID; share: Info["share"] }) {
811
+ yield* patch(input.sessionID, { share: input.share ?? null, time: { updated: Date.now() } }).pipe(Effect.orDie)
812
+ })
813
+
814
+ const setWorkspace = Effect.fn("Session.setWorkspace")(function* (input: {
815
+ sessionID: SessionID
816
+ workspaceID: Info["workspaceID"]
817
+ }) {
818
+ yield* patch(input.sessionID, { workspaceID: input.workspaceID, time: { updated: Date.now() } }).pipe(
819
+ Effect.orDie,
820
+ )
821
+ })
822
+
823
+ const diff = Effect.fn("Session.diff")(function* (sessionID: SessionID) {
824
+ void sessionID
825
+ return [] as Snapshot.FileDiff[]
826
+ })
827
+
828
+ const messages: Interface["messages"] = Effect.fn("Session.messages")(function* (input) {
829
+ if (input.limit) {
830
+ return (yield* MessageV2.page({ sessionID: input.sessionID, limit: input.limit }).pipe(
831
+ Effect.provideService(Database.Service, database),
832
+ )).items
833
+ }
834
+
835
+ const size = 50
836
+ const result = [] as SessionV1.WithParts[]
837
+ let before: string | undefined
838
+ while (true) {
839
+ const page = yield* MessageV2.page({ sessionID: input.sessionID, limit: size, before }).pipe(
840
+ Effect.provideService(Database.Service, database),
841
+ )
842
+ if (page.items.length === 0) break
843
+ for (let i = page.items.length - 1; i >= 0; i--) {
844
+ const item = page.items[i]
845
+ if (item) result.push(item)
846
+ }
847
+ if (!page.more || !page.cursor) break
848
+ before = page.cursor
849
+ }
850
+ return result.reverse()
851
+ })
852
+
853
+ const removeMessage = Effect.fn("Session.removeMessage")(function* (input: {
854
+ sessionID: SessionID
855
+ messageID: MessageID
856
+ }) {
857
+ yield* events.publish(SessionV1.Event.MessageRemoved, {
858
+ sessionID: input.sessionID,
859
+ messageID: input.messageID,
860
+ })
861
+ return input.messageID
862
+ })
863
+
864
+ const removePart = Effect.fn("Session.removePart")(function* (input: {
865
+ sessionID: SessionID
866
+ messageID: MessageID
867
+ partID: PartID
868
+ }) {
869
+ yield* events.publish(SessionV1.Event.PartRemoved, {
870
+ sessionID: input.sessionID,
871
+ messageID: input.messageID,
872
+ partID: input.partID,
873
+ })
874
+ return input.partID
875
+ })
876
+
877
+ const updatePartDelta = Effect.fnUntraced(function* (input: {
878
+ sessionID: SessionID
879
+ messageID: MessageID
880
+ partID: PartID
881
+ field: string
882
+ delta: string
883
+ }) {
884
+ yield* events.publish(MessageV2.Event.PartDelta, input)
885
+ })
886
+
887
+ /** Finds the first message matching the predicate, searching newest-first. */
888
+ const findMessage: Interface["findMessage"] = Effect.fn("Session.findMessage")(function* (sessionID, predicate) {
889
+ const size = 50
890
+ let before: string | undefined
891
+ while (true) {
892
+ const page = yield* MessageV2.page({ sessionID, limit: size, before }).pipe(
893
+ Effect.provideService(Database.Service, database),
894
+ )
895
+ if (page.items.length === 0) break
896
+ for (let i = page.items.length - 1; i >= 0; i--) {
897
+ const item = page.items[i]
898
+ if (item && predicate(item)) return Option.some(item)
899
+ }
900
+ if (!page.more || !page.cursor) break
901
+ before = page.cursor
902
+ }
903
+ return Option.none<SessionV1.WithParts>()
904
+ })
905
+
906
+ return Service.of({
907
+ list,
908
+ listGlobal,
909
+ create,
910
+ fork,
911
+ touch,
912
+ get,
913
+ setTitle,
914
+ setArchived,
915
+ setMetadata,
916
+ setAgentModel,
917
+ setPermission,
918
+ setRevert,
919
+ clearRevert,
920
+ setSummary,
921
+ setShare,
922
+ setWorkspace,
923
+ diff,
924
+ messages,
925
+ children,
926
+ remove,
927
+ updateMessage,
928
+ removeMessage,
929
+ removePart,
930
+ updatePart,
931
+ getPart,
932
+ updatePartDelta,
933
+ findMessage,
934
+ })
935
+ }),
936
+ )
937
+
938
+ const cancelBackgroundJobs = Effect.fn("Session.cancelBackgroundJobs")(function* (
939
+ background: BackgroundJob.Interface,
940
+ sessionID: SessionID,
941
+ ) {
942
+ const jobs = yield* background.list()
943
+ yield* Effect.forEach(
944
+ jobs.filter((job) => {
945
+ if (job.status !== "running") return false
946
+ if (job.id === sessionID) return true
947
+ if (job.metadata?.sessionId === sessionID) return true
948
+ return job.metadata?.parentSessionId === sessionID
949
+ }),
950
+ (job) => background.cancel(job.id),
951
+ { concurrency: "unbounded", discard: true },
952
+ )
953
+ })
954
+
955
+ function listByProject(
956
+ db: Database.Interface["db"],
957
+ input: ListInput & {
958
+ projectID: ProjectV2.ID
959
+ experimentalWorkspaces: boolean
960
+ },
961
+ ) {
962
+ const conditions = [eq(SessionTable.project_id, input.projectID)]
963
+
964
+ if (input.workspaceID) {
965
+ conditions.push(eq(SessionTable.workspace_id, input.workspaceID))
966
+ }
967
+ if (input.path !== undefined) {
968
+ if (input.path) {
969
+ const conds = [
970
+ eq(SessionTable.path, input.path),
971
+ like(SessionTable.path, sql.param(`${input.path}/%`, SessionTable.path)),
972
+ ]
973
+
974
+ conditions.push(
975
+ input.directory
976
+ ? or(...conds, and(isNull(SessionTable.path), eq(SessionTable.directory, input.directory))!)!
977
+ : or(...conds)!,
978
+ )
979
+ }
980
+ } else if (input.scope !== "project") {
981
+ if (input.directory) {
982
+ conditions.push(eq(SessionTable.directory, input.directory))
983
+ }
984
+ }
985
+ if (input.roots) {
986
+ conditions.push(isNull(SessionTable.parent_id))
987
+ }
988
+ if (input.start) {
989
+ conditions.push(gte(SessionTable.time_updated, input.start))
990
+ }
991
+ if (input.search) {
992
+ conditions.push(like(SessionTable.title, `%${input.search}%`))
993
+ }
994
+
995
+ const limit = input.limit ?? 100
996
+
997
+ return db
998
+ .select()
999
+ .from(SessionTable)
1000
+ .where(and(...conditions))
1001
+ .orderBy(desc(SessionTable.time_updated))
1002
+ .limit(limit)
1003
+ .all()
1004
+ .pipe(
1005
+ Effect.orDie,
1006
+ Effect.map((rows) => rows.map(fromRow)),
1007
+ )
1008
+ }
1009
+
1010
+ export const node = LayerNode.make({
1011
+ service: Service,
1012
+ layer: layer,
1013
+ deps: [BackgroundJob.node, RuntimeFlags.node, Database.node, EventV2Bridge.node],
1014
+ })
1015
+
1016
+ export * as Session from "./session"