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