mirror of
https://github.com/anomalyco/opencode.git
synced 2026-09-14 04:46:23 +00:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b47f33993 | ||
|
|
aeed4b6375 | ||
|
|
82f713421f | ||
|
|
763cac8080 | ||
|
|
c2cf497e19 | ||
|
|
7784b3ee0d | ||
|
|
199aabe9e2 | ||
|
|
8905af5074 | ||
|
|
ce56111a4c | ||
|
|
5ab0167288 | ||
|
|
487e1bd76e | ||
|
|
1eeaaab7a6 | ||
|
|
b901cb28af | ||
|
|
13453f2da8 | ||
|
|
e16c56fe8b | ||
|
|
42ff564913 | ||
|
|
195158c34c | ||
|
|
7a31b5c0f7 | ||
|
|
fb3c10ca66 | ||
|
|
c43cfccc4e | ||
|
|
c5aa7d7e34 | ||
|
|
9c8a4ea4ff | ||
|
|
c82340a97b | ||
|
|
dbc63955b0 | ||
|
|
2816d1c849 | ||
|
|
61d812fcd6 | ||
|
|
e47b9b5453 | ||
|
|
21dac524f3 |
@@ -1,4 +1,4 @@
|
||||
name: typecheck
|
||||
name: check
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
typecheck:
|
||||
check:
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -17,5 +17,5 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: ./.github/actions/setup-bun
|
||||
|
||||
- name: Run typecheck
|
||||
run: bun typecheck
|
||||
- name: Run checks
|
||||
run: bun run check
|
||||
+1
-1
@@ -17,4 +17,4 @@ if (process.versions.bun !== expectedBunVersion) {
|
||||
console.warn(`Warning: Bun version ${process.versions.bun} differs from expected ${expectedBunVersion}`);
|
||||
}
|
||||
'
|
||||
bun typecheck
|
||||
bun run check
|
||||
|
||||
+14
-37
@@ -1,45 +1,22 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/nicolo-ribaudo/oxc-project.github.io/refs/heads/json-schema/src/public/.oxlintrc.schema.json",
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"categories": {
|
||||
"suspicious": "warn"
|
||||
"correctness": "off",
|
||||
"suspicious": "off",
|
||||
"pedantic": "off",
|
||||
"perf": "off",
|
||||
"style": "off",
|
||||
"restriction": "off",
|
||||
"nursery": "off"
|
||||
},
|
||||
"rules": {
|
||||
"typescript/no-base-to-string": "warn",
|
||||
// Effect uses `function*` with Effect.gen/Effect.fnUntraced that don't always yield
|
||||
"require-yield": "off",
|
||||
// SolidJS uses `let ref: T | undefined` for JSX ref bindings assigned at runtime
|
||||
"no-unassigned-vars": "off",
|
||||
// SolidJS tracks reactive deps by reading properties inside createEffect
|
||||
"no-unused-expressions": "off",
|
||||
// Intentional control char matching (ANSI escapes, null byte sanitization)
|
||||
"no-control-regex": "off",
|
||||
// SST and plugin tools require triple-slash references
|
||||
"triple-slash-reference": "off",
|
||||
|
||||
// Suspicious category: suppress noisy rules
|
||||
// Effect's nested function* closures inherently shadow outer scope
|
||||
"no-shadow": "off",
|
||||
// Namespace-heavy codebase makes this too noisy
|
||||
"unicorn/consistent-function-scoping": "off",
|
||||
// Opinionated — .sort()/.reverse() mutation is fine in this codebase
|
||||
"unicorn/no-array-sort": "off",
|
||||
"unicorn/no-array-reverse": "off",
|
||||
// Not relevant — this isn't a DOM event handler codebase
|
||||
"unicorn/prefer-add-event-listener": "off",
|
||||
// Bundler handles module resolution
|
||||
"unicorn/require-module-specifiers": "off",
|
||||
// postMessage target origin not relevant for this codebase
|
||||
"unicorn/require-post-message-target-origin": "off",
|
||||
// Side-effectful constructors are intentional in some places
|
||||
"no-new": "off",
|
||||
|
||||
// Type-aware: catch unhandled promises
|
||||
"typescript/no-floating-promises": "warn",
|
||||
// Warn when spreading non-plain objects (Headers, class instances, etc.)
|
||||
"typescript/no-misused-spread": "warn"
|
||||
"no-restricted-globals": [
|
||||
"error",
|
||||
{
|
||||
"name": "Reflect",
|
||||
"message": "Use typed property access or direct invocation. Suppress this rule only for genuine reflection."
|
||||
}
|
||||
]
|
||||
},
|
||||
"ignorePatterns": ["**/node_modules", "**/dist", "**/.build", "**/.sst", "**/*.d.ts", "**/sdk.gen.ts"]
|
||||
}
|
||||
|
||||
@@ -170,9 +170,10 @@ const table = sqliteTable("session", {
|
||||
- Test actual implementation, do not duplicate logic into tests
|
||||
- Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package directories such as `packages/core`.
|
||||
|
||||
## Type Checking
|
||||
## Checks
|
||||
|
||||
- Always run `bun typecheck` from package directories (for example, `packages/core`), never `tsc` directly.
|
||||
- Run `bun run check` from the repository root as the canonical full lint and type-check verification.
|
||||
- During focused iteration, run `bun typecheck` from the affected package directory (for example, `packages/core`). Never run `tsc` directly.
|
||||
|
||||
## V2 Session Core
|
||||
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
# V2 HTTP API audit checklist
|
||||
|
||||
**Source:** `packages/protocol/openapi.json`
|
||||
**Current endpoint count:** 139
|
||||
**Last regenerated:** 2026-09-13
|
||||
|
||||
## How to use this checklist
|
||||
|
||||
Review endpoints in document order. For each endpoint, select one disposition and capture rationale or follow-up work in Notes. Mark **Reviewed** only after the disposition is agreed.
|
||||
|
||||
### Review criteria
|
||||
|
||||
- Resource and operation naming
|
||||
- HTTP method and idempotency
|
||||
- Request parameters and location scope
|
||||
- Response shape and error taxonomy
|
||||
- Authentication and authorization
|
||||
- Current production consumers
|
||||
- Stability level: public, experimental, or internal
|
||||
- Whether the generated client API is intuitive
|
||||
|
||||
### Disposition legend
|
||||
|
||||
- **Keep:** ship unchanged as a supported V2 API
|
||||
- **Change:** retain after a defined contract change
|
||||
- **Remove:** exclude from the official V2 API
|
||||
- **Experimental-only:** retain outside the stable API commitment
|
||||
|
||||
## Progress
|
||||
|
||||
- [x] Group 1: Foundation and placement (4)
|
||||
- [ ] Group 2: Configuration and capability catalogs (16)
|
||||
- [ ] Group 3: Credentials, integrations, MCP, and web search (22)
|
||||
- [ ] Group 4: Session lifecycle (12)
|
||||
- [ ] Group 5: Session execution and inputs (11)
|
||||
- [ ] Group 6: Session history and recovery (13)
|
||||
- [ ] Group 7: Inbox, permissions, and forms (19)
|
||||
- [ ] Group 8: Filesystem, worktrees, and VCS (12)
|
||||
- [ ] Group 9: PTYs, persistent terminals, and shells (24)
|
||||
- [ ] Group 10: Events, RPC, and experimental operations (6)
|
||||
|
||||
## Resolved during audit
|
||||
|
||||
### [x] `POST /api/plugin/await-activation`
|
||||
|
||||
- **Decision:** Remove
|
||||
- **Notes:** Activation timing is an internal server concern. Catalog reads remain non-blocking.
|
||||
|
||||
### [x] Location response wrappers
|
||||
|
||||
- **Decision:** Reduce generic endpoint response locations to `{ directory }`.
|
||||
- **Notes:** Full project metadata remains available from `GET /api/location`; no consumers used it from wrapped responses.
|
||||
|
||||
### [x] `GET /api/health` and `GET /api/server`
|
||||
|
||||
- **Decision:** Merge and rename
|
||||
- **Replacement:** `GET /api/status` with operation ID `server.status`.
|
||||
- **Notes:** Returns `version`, `pid`, and connection `urls`; readiness is conveyed by HTTP status.
|
||||
|
||||
### [x] `GET /api/project/current`
|
||||
|
||||
- **Decision:** Remove
|
||||
- **Replacement:** `GET /api/location`, using `project` from the response.
|
||||
- **Notes:** The endpoint duplicated `Location.Info.project`; production callers were migrated.
|
||||
|
||||
### [x] `POST /api/workspace` and `DELETE /api/workspace/{workspaceID}`
|
||||
|
||||
- **Decision:** Remove
|
||||
- **Notes:** Provider-backed workspaces are not part of the V2 HTTP contract and can be introduced later. Core and the embedded SDK retain internal workspace support.
|
||||
|
||||
## Group 1: Foundation and placement
|
||||
|
||||
**Endpoints:** 4
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [x] 001–002 | `GET` | `/api/status` | `server.status` | Keep | Replaces the former health and server endpoints. |
|
||||
| [x] 003 | `GET` | `/api/location` | `location.get` | Keep | Workspace selectors and response fields removed until workspace support ships. |
|
||||
| [x] 004 | `GET` | `/api/project` | `project.list` | Keep | Removed unused `time.initialized`; the database column remains for migration data. |
|
||||
| [x] 005 | `PATCH` | `/api/project/{projectID}` | `project.update` | Keep | Request and response accepted as-is. |
|
||||
|
||||
## Group 2: Configuration and capability catalogs
|
||||
|
||||
**Endpoints:** 16
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [x] 008 | `GET` | `/api/agent` | `agent.list` | Keep | Request and response accepted as-is. |
|
||||
| [x] 009 | `GET` | `/api/agent/{agentID}` | `agent.get` | Keep | Request, response, and not-found error accepted as-is. |
|
||||
| [x] 010 | `GET` | `/api/plugin` | `plugin.list` | Keep | Request and response accepted as-is. |
|
||||
| [x] 012 | `POST` | `/api/plugin/check` | `plugin.check` | Keep | Request and response accepted as-is. |
|
||||
| [x] 013 | `POST` | `/api/plugin/update` | `plugin.update` | Keep | Request and errors accepted as-is. |
|
||||
| [x] 014 | `GET` | `/api/model` | `model.list` | Keep | Request and response accepted as-is. |
|
||||
| [x] 015 | `GET` | `/api/model/default` | `model.default` | Keep | Request and nullable response accepted as-is. |
|
||||
| [x] 016 | `GET` | `/api/provider` | `provider.list` | Keep | Request and response accepted as-is. |
|
||||
| [x] 017 | `GET` | `/api/provider/{providerID}` | `provider.get` | Keep | Request, response, and not-found error accepted as-is. |
|
||||
| [x] 018 | `GET` | `/api/command` | `command.list` | Keep | Request and response accepted as-is. |
|
||||
| [x] 019 | `GET` | `/api/skill` | `skill.list` | Keep | Renamed `location` to `path`; removed the skill-specific `slash` flag and slash-command behavior. |
|
||||
| [x] 020 | `GET` | `/api/reference` | `reference.list` | Keep | Removed duplicate `description` and `hidden` fields from nested `source`. |
|
||||
| [x] 021 | `GET` | `/api/config` | `config.get` | Keep | Compatibility entries removed; response now contains only documents and OpenCode directories. |
|
||||
| [x] 022 | `GET` | `/api/config/preferences` | `config.preferences` | Remove | Redundant special projection of global config. |
|
||||
| [x] 023 | `PATCH` | `/api/config/preferences` | `config.updatePreferences` | Remove | Redundant field-specific config mutation API. |
|
||||
| [ ] 024 | `GET` | `/api/config/shell` | `config.shells` | | |
|
||||
| [x] 024a | `PATCH` | `/api/experimental/config` | `experimental.config.update` | Change | Experimental global config mutation; initially accepts only `shell`. |
|
||||
|
||||
## Group 3: Credentials, integrations, MCP, and web search
|
||||
|
||||
**Endpoints:** 22
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [x] 025 | `GET` | `/api/integration` | `integration.list` | Keep | Full integration inventory is consumed by authentication and integration-selection clients. |
|
||||
| [x] 026 | `GET` | `/api/integration/{integrationID}` | `integration.get` | Change | Missing integration now returns typed `404` instead of optional data. |
|
||||
| [ ] 027 | `POST` | `/api/experimental/integration/wellknown` | `experimental.integration.wellknown.add` | | |
|
||||
| [ ] 028 | `POST` | `/api/integration/{integrationID}/connect/key` | `integration.connect.key` | | |
|
||||
| [ ] 029 | `POST` | `/api/integration/{integrationID}/connect/oauth` | `integration.oauth.connect` | | |
|
||||
| [ ] 030 | `GET` | `/api/integration/{integrationID}/connect/oauth/{attemptID}` | `integration.oauth.status` | | |
|
||||
| [ ] 031 | `DELETE` | `/api/integration/{integrationID}/connect/oauth/{attemptID}` | `integration.oauth.cancel` | | |
|
||||
| [ ] 032 | `POST` | `/api/integration/{integrationID}/connect/oauth/{attemptID}/complete` | `integration.oauth.complete` | | |
|
||||
| [ ] 033 | `POST` | `/api/integration/{integrationID}/connect/command` | `integration.command.connect` | | |
|
||||
| [ ] 034 | `GET` | `/api/integration/{integrationID}/connect/command/{attemptID}` | `integration.command.status` | | |
|
||||
| [ ] 035 | `DELETE` | `/api/integration/{integrationID}/connect/command/{attemptID}` | `integration.command.cancel` | | |
|
||||
| [ ] 036 | `GET` | `/api/mcp` | `mcp.list` | | |
|
||||
| [ ] 037 | `PUT` | `/api/mcp/{server}` | `mcp.add` | | |
|
||||
| [ ] 038 | `DELETE` | `/api/mcp/{server}` | `mcp.remove` | | |
|
||||
| [ ] 039 | `POST` | `/api/mcp/{server}/connect` | `mcp.connect` | | |
|
||||
| [ ] 040 | `POST` | `/api/mcp/{server}/disconnect` | `mcp.disconnect` | | |
|
||||
| [ ] 041 | `GET` | `/api/mcp/resource` | `mcp.resource.catalog` | | |
|
||||
| [ ] 042 | `PATCH` | `/api/credential/{credentialID}` | `credential.update` | | |
|
||||
| [ ] 043 | `DELETE` | `/api/credential/{credentialID}` | `credential.remove` | | |
|
||||
| [ ] 044 | `POST` | `/api/credential/{credentialID}/activate` | `credential.activate` | | |
|
||||
| [ ] 045 | `GET` | `/api/websearch/provider` | `websearch.providers` | | |
|
||||
| [ ] 046 | `POST` | `/api/websearch` | `websearch.query` | | |
|
||||
|
||||
## Group 4: Session lifecycle
|
||||
|
||||
**Endpoints:** 12
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 047 | `GET` | `/api/session` | `session.list` | | |
|
||||
| [ ] 048 | `POST` | `/api/session` | `session.create` | | |
|
||||
| [ ] 049 | `GET` | `/api/session/stats` | `session.stats` | | |
|
||||
| [ ] 050 | `GET` | `/api/session/active` | `session.active` | | |
|
||||
| [ ] 051 | `GET` | `/api/session/{sessionID}` | `session.get` | | |
|
||||
| [ ] 052 | `DELETE` | `/api/session/{sessionID}` | `session.remove` | | |
|
||||
| [ ] 053 | `POST` | `/api/session/{sessionID}/fork` | `session.fork` | | |
|
||||
| [ ] 054 | `POST` | `/api/session/{sessionID}/agent` | `session.switchAgent` | | |
|
||||
| [ ] 055 | `POST` | `/api/session/{sessionID}/model` | `session.switchModel` | | |
|
||||
| [ ] 056 | `POST` | `/api/session/{sessionID}/rename` | `session.rename` | | |
|
||||
| [ ] 057 | `POST` | `/api/session/{sessionID}/move` | `session.move` | | |
|
||||
| [ ] 058 | `POST` | `/api/session/{sessionID}/background` | `session.background` | | |
|
||||
|
||||
## Group 5: Session execution and inputs
|
||||
|
||||
**Endpoints:** 11
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 059 | `POST` | `/api/session/{sessionID}/prompt` | `session.prompt` | | |
|
||||
| [ ] 060 | `POST` | `/api/session/{sessionID}/command` | `session.command` | | |
|
||||
| [ ] 061 | `POST` | `/api/session/{sessionID}/skill` | `session.skill` | | |
|
||||
| [ ] 062 | `POST` | `/api/session/{sessionID}/synthetic` | `session.synthetic` | | |
|
||||
| [ ] 063 | `POST` | `/api/session/{sessionID}/shell` | `session.shell` | | |
|
||||
| [ ] 064 | `POST` | `/api/session/{sessionID}/compact` | `session.compact` | | |
|
||||
| [ ] 065 | `POST` | `/api/session/{sessionID}/wait` | `session.wait` | | |
|
||||
| [ ] 066 | `POST` | `/api/session/{sessionID}/generate` | `session.generate` | | |
|
||||
| [ ] 067 | `POST` | `/api/session/{sessionID}/interrupt` | `session.interrupt` | | |
|
||||
| [ ] 068 | `PUT` | `/api/session/{sessionID}/environment` | `session.environment` | | |
|
||||
| [ ] 069 | `POST` | `/api/session/{sessionID}/view` | `session.view` | | |
|
||||
|
||||
## Group 6: Session history and recovery
|
||||
|
||||
**Endpoints:** 13
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 070 | `POST` | `/api/session/import` | `session.import` | | |
|
||||
| [ ] 071 | `GET` | `/api/session/{sessionID}/export` | `session.export` | | |
|
||||
| [ ] 072 | `POST` | `/api/session/{sessionID}/revert/stage` | `session.revert.stage` | | |
|
||||
| [ ] 073 | `POST` | `/api/session/{sessionID}/revert/clear` | `session.revert.clear` | | |
|
||||
| [ ] 074 | `POST` | `/api/session/{sessionID}/revert/commit` | `session.revert.commit` | | |
|
||||
| [ ] 075 | `GET` | `/api/session/{sessionID}/context` | `session.context` | | |
|
||||
| [ ] 076 | `GET` | `/api/session/{sessionID}/diff` | `session.diff` | | |
|
||||
| [ ] 077 | `GET` | `/api/session/{sessionID}/instructions/entries` | `session.instructions.entry.list` | | |
|
||||
| [ ] 078 | `PUT` | `/api/session/{sessionID}/instructions/entries/{key}` | `session.instructions.entry.put` | | |
|
||||
| [ ] 079 | `DELETE` | `/api/session/{sessionID}/instructions/entries/{key}` | `session.instructions.entry.remove` | | |
|
||||
| [ ] 080 | `GET` | `/api/experimental/session/{sessionID}/log` | `session.log` | | |
|
||||
| [ ] 081 | `GET` | `/api/session/{sessionID}/message/{messageID}` | `session.message` | | |
|
||||
| [ ] 082 | `GET` | `/api/session/{sessionID}/message` | `message.list` | | |
|
||||
|
||||
## Group 7: Inbox, permissions, and forms
|
||||
|
||||
**Endpoints:** 19
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 083 | `GET` | `/api/session/{sessionID}/inbox` | `session.inbox.list` | | |
|
||||
| [ ] 084 | `DELETE` | `/api/session/{sessionID}/inbox/{inboxID}` | `session.inbox.cancel` | | |
|
||||
| [ ] 085 | `POST` | `/api/session/{sessionID}/inbox/{inboxID}/steer` | `session.inbox.steer` | | |
|
||||
| [ ] 086 | `POST` | `/api/session/{sessionID}/inbox/{inboxID}/queue` | `session.inbox.queue` | | |
|
||||
| [ ] 087 | `GET` | `/api/form/request` | `form.request.list` | | |
|
||||
| [ ] 088 | `GET` | `/api/session/{sessionID}/form` | `session.form.list` | | |
|
||||
| [ ] 089 | `POST` | `/api/session/{sessionID}/form` | `session.form.create` | | |
|
||||
| [ ] 090 | `GET` | `/api/session/{sessionID}/form/{formID}` | `session.form.get` | | |
|
||||
| [ ] 091 | `GET` | `/api/session/{sessionID}/form/{formID}/state` | `session.form.state` | | |
|
||||
| [ ] 092 | `POST` | `/api/session/{sessionID}/form/{formID}/reply` | `session.form.reply` | | |
|
||||
| [ ] 093 | `POST` | `/api/session/{sessionID}/form/{formID}/cancel` | `session.form.cancel` | | |
|
||||
| [ ] 094 | `GET` | `/api/permission/request` | `permission.request.list` | | |
|
||||
| [ ] 095 | `GET` | `/api/permission/saved` | `permission.saved.list` | | |
|
||||
| [ ] 096 | `DELETE` | `/api/permission/saved/{id}` | `permission.saved.remove` | | |
|
||||
| [ ] 097 | `POST` | `/api/session/{sessionID}/permission` | `session.permission.create` | | |
|
||||
| [ ] 098 | `GET` | `/api/session/{sessionID}/permission` | `session.permission.list` | | |
|
||||
| [ ] 099 | `GET` | `/api/session/{sessionID}/permission/{requestID}` | `session.permission.get` | | |
|
||||
| [ ] 100 | `POST` | `/api/session/{sessionID}/permission/{requestID}/reply` | `session.permission.reply` | | |
|
||||
| [ ] 101 | `PUT` | `/api/session/{sessionID}/permission/rules` | `session.permission.rules` | | |
|
||||
|
||||
## Group 8: Filesystem, worktrees, and VCS
|
||||
|
||||
**Endpoints:** 12
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 102 | `GET` | `/api/fs/read/*` | `fs.read` | | |
|
||||
| [ ] 103 | `GET` | `/api/fs/list` | `fs.list` | | |
|
||||
| [ ] 104 | `GET` | `/api/fs/find` | `fs.find` | | |
|
||||
| [ ] 105 | `GET` | `/api/worktree` | `worktree.list` | | |
|
||||
| [ ] 106 | `POST` | `/api/worktree` | `worktree.create` | | |
|
||||
| [ ] 107 | `DELETE` | `/api/worktree` | `worktree.remove` | | |
|
||||
| [ ] 108 | `POST` | `/api/worktree/refresh` | `worktree.refresh` | | |
|
||||
| [ ] 109 | `GET` | `/api/vcs` | `vcs.get` | | |
|
||||
| [ ] 110 | `GET` | `/api/vcs/base` | `vcs.base` | | |
|
||||
| [ ] 111 | `GET` | `/api/vcs/status` | `vcs.status` | | |
|
||||
| [ ] 112 | `GET` | `/api/vcs/branches` | `vcs.branches` | | |
|
||||
| [ ] 113 | `GET` | `/api/vcs/diff` | `vcs.diff` | | |
|
||||
|
||||
## Group 9: PTYs, persistent terminals, and shells
|
||||
|
||||
**Endpoints:** 24
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 114 | `GET` | `/api/pty` | `pty.list` | | |
|
||||
| [ ] 115 | `POST` | `/api/pty` | `pty.create` | | |
|
||||
| [ ] 116 | `GET` | `/api/pty/{ptyID}` | `pty.get` | | |
|
||||
| [ ] 117 | `PUT` | `/api/pty/{ptyID}` | `pty.update` | | |
|
||||
| [ ] 118 | `DELETE` | `/api/pty/{ptyID}` | `pty.remove` | | |
|
||||
| [ ] 119 | `POST` | `/api/pty/{ptyID}/connect-token` | `pty.connect.token` | | |
|
||||
| [ ] 120 | `GET` | `/api/pty/{ptyID}/connect` | `pty.connect` | | |
|
||||
| [ ] 121 | `GET` | `/api/experimental/session/{sessionID}/terminal/read` | `server.experimental.persistentPty.read` | | |
|
||||
| [ ] 122 | `GET` | `/api/experimental/session/{sessionID}/terminal` | `server.experimental.persistentPty.list` | | |
|
||||
| [ ] 123 | `POST` | `/api/experimental/session/{sessionID}/terminal` | `server.experimental.persistentPty.create` | | |
|
||||
| [ ] 124 | `POST` | `/api/experimental/persistent-pty/shutdown` | `server.experimental.persistentPty.shutdown` | | |
|
||||
| [ ] 125 | `POST` | `/api/experimental/persistent-pty/handoff` | `server.experimental.persistentPty.handoff` | | |
|
||||
| [ ] 126 | `GET` | `/api/experimental/persistent-pty/{ptyID}` | `server.experimental.persistentPty.get` | | |
|
||||
| [ ] 127 | `PUT` | `/api/experimental/persistent-pty/{ptyID}` | `server.experimental.persistentPty.update` | | |
|
||||
| [ ] 128 | `DELETE` | `/api/experimental/persistent-pty/{ptyID}` | `server.experimental.persistentPty.remove` | | |
|
||||
| [ ] 129 | `GET` | `/api/experimental/persistent-pty/{ptyID}/snapshot` | `server.experimental.persistentPty.snapshot` | | |
|
||||
| [ ] 130 | `POST` | `/api/experimental/persistent-pty/{ptyID}/connect-token` | `server.experimental.persistentPty.connectToken` | | |
|
||||
| [ ] 131 | `GET` | `/api/experimental/persistent-pty/{ptyID}/connect` | `persistentPty.connect` | | |
|
||||
| [ ] 132 | `GET` | `/api/shell` | `shell.list` | | |
|
||||
| [ ] 133 | `POST` | `/api/shell` | `shell.create` | | |
|
||||
| [ ] 134 | `GET` | `/api/shell/{id}` | `shell.get` | | |
|
||||
| [ ] 135 | `DELETE` | `/api/shell/{id}` | `shell.remove` | | |
|
||||
| [ ] 136 | `PATCH` | `/api/shell/{id}/timeout` | `shell.timeout` | | |
|
||||
| [ ] 137 | `GET` | `/api/shell/{id}/output` | `shell.output` | | |
|
||||
|
||||
## Group 10: Events, RPC, and experimental operations
|
||||
|
||||
**Endpoints:** 6
|
||||
|
||||
| Done | Method | Path | Operation ID | Decision | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| [ ] 138 | `POST` | `/api/generate` | `generate.text` | | |
|
||||
| [ ] 139 | `POST` | `/api/rpc/{rpcID}/{method}` | `rpc.call` | | |
|
||||
| [ ] 140 | `GET` | `/api/event` | `event.subscribe` | | |
|
||||
| [ ] 141 | `GET` | `/api/debug/location` | `debug.location.list` | | |
|
||||
| [ ] 142 | `DELETE` | `/api/debug/location` | `debug.location.evict` | | |
|
||||
| [ ] 143 | `GET` | `/api/experimental/migration/v1` | `experimental.migration.v1.status` | | |
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"packages/ai": {
|
||||
"name": "@opencode/ai",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@aws-sdk/credential-providers": "3.1057.0",
|
||||
"@opencode/schema": "workspace:*",
|
||||
@@ -53,7 +53,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@opencode/app",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@corvu/drawer": "catalog:",
|
||||
"@dnd-kit/abstract": "0.5.0",
|
||||
@@ -112,7 +112,7 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@opencode/cli",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"bin": {
|
||||
"opencode2": "./bin/opencode2.cjs",
|
||||
},
|
||||
@@ -176,7 +176,7 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@opencode/client",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/protocol": "workspace:*",
|
||||
"@opencode/schema": "workspace:*",
|
||||
@@ -202,7 +202,7 @@
|
||||
},
|
||||
"packages/codemode": {
|
||||
"name": "@opencode/codemode",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"acorn": "8.15.0",
|
||||
"effect": "catalog:",
|
||||
@@ -216,7 +216,7 @@
|
||||
},
|
||||
"packages/console/app": {
|
||||
"name": "@opencode/console-app",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "1.15.2",
|
||||
"@ibm/plex": "6.4.1",
|
||||
@@ -252,7 +252,7 @@
|
||||
},
|
||||
"packages/console/core": {
|
||||
"name": "@opencode/console-core",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-sts": "3.782.0",
|
||||
"@jsx-email/render": "1.1.1",
|
||||
@@ -279,7 +279,7 @@
|
||||
},
|
||||
"packages/console/function": {
|
||||
"name": "@opencode/console-function",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@openauthjs/openauth": "0.0.0-20250322224806",
|
||||
"@opencode/console-core": "workspace:*",
|
||||
@@ -296,7 +296,7 @@
|
||||
},
|
||||
"packages/console/mail": {
|
||||
"name": "@opencode/console-mail",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@jsx-email/all": "2.2.3",
|
||||
"@jsx-email/cli": "1.4.3",
|
||||
@@ -320,7 +320,7 @@
|
||||
},
|
||||
"packages/console/support": {
|
||||
"name": "@opencode/console-support",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "1.15.2",
|
||||
"@opencode/console-core": "workspace:*",
|
||||
@@ -340,7 +340,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@opencode/core",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@ai-sdk/alibaba": "1.0.17",
|
||||
"@ai-sdk/anthropic": "3.0.82",
|
||||
@@ -412,7 +412,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@opencode/desktop",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@zip.js/zip.js": "2.7.62",
|
||||
"electron-context-menu": "4.1.2",
|
||||
@@ -464,7 +464,7 @@
|
||||
},
|
||||
"packages/enterprise": {
|
||||
"name": "@opencode/enterprise",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@hono/standard-validator": "catalog:",
|
||||
"@opencode-ai/sdk": "1.18.21",
|
||||
@@ -501,7 +501,7 @@
|
||||
},
|
||||
"packages/function": {
|
||||
"name": "@opencode/function",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@octokit/auth-app": "8.0.1",
|
||||
"@octokit/rest": "catalog:",
|
||||
@@ -517,7 +517,7 @@
|
||||
},
|
||||
"packages/http-recorder": {
|
||||
"name": "@opencode/http-recorder",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@effect/platform-node-shared": "4.0.0-rc.112",
|
||||
},
|
||||
@@ -536,7 +536,7 @@
|
||||
},
|
||||
"packages/httpapi-codegen": {
|
||||
"name": "@opencode/httpapi-codegen",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"prettier": "3.6.2",
|
||||
@@ -549,7 +549,7 @@
|
||||
},
|
||||
"packages/latex": {
|
||||
"name": "@opencode/latex",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
@@ -563,7 +563,7 @@
|
||||
},
|
||||
"packages/merman": {
|
||||
"name": "@opencode/merman",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
@@ -578,7 +578,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@opencode/plugin",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@ai-sdk/provider": "3.0.8",
|
||||
"@opencode/ai": "workspace:*",
|
||||
@@ -617,7 +617,7 @@
|
||||
},
|
||||
"packages/plugin-browser": {
|
||||
"name": "@opencode/plugin-browser",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/plugin": "workspace:*",
|
||||
"@opencode/schema": "workspace:*",
|
||||
@@ -647,7 +647,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@opencode/protocol",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/schema": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
@@ -662,7 +662,7 @@
|
||||
},
|
||||
"packages/schema": {
|
||||
"name": "@opencode/schema",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "catalog:",
|
||||
"effect": "catalog:",
|
||||
@@ -686,7 +686,7 @@
|
||||
},
|
||||
"packages/sdk": {
|
||||
"name": "@opencode/sdk",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/client": "workspace:*",
|
||||
"@opencode/core": "workspace:*",
|
||||
@@ -707,7 +707,7 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@opencode/server",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
@@ -729,7 +729,7 @@
|
||||
},
|
||||
"packages/session-ui": {
|
||||
"name": "@opencode/session-ui",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@kobalte/core": "catalog:",
|
||||
"@opencode/client": "workspace:*",
|
||||
@@ -764,7 +764,7 @@
|
||||
},
|
||||
"packages/simulation": {
|
||||
"name": "@opencode/simulation",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/ai": "workspace:*",
|
||||
"@opencode/core": "workspace:*",
|
||||
@@ -784,7 +784,7 @@
|
||||
},
|
||||
"packages/stats/app": {
|
||||
"name": "@opencode/stats-app",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@ibm/plex": "6.4.1",
|
||||
"@kobalte/core": "catalog:",
|
||||
@@ -818,7 +818,7 @@
|
||||
},
|
||||
"packages/stats/core": {
|
||||
"name": "@opencode/stats-core",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-athena": "3.933.0",
|
||||
"@planetscale/database": "1.19.0",
|
||||
@@ -837,7 +837,7 @@
|
||||
},
|
||||
"packages/stats/server": {
|
||||
"name": "@opencode/stats-server",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-firehose": "3.933.0",
|
||||
"@effect/platform-node": "catalog:",
|
||||
@@ -883,7 +883,7 @@
|
||||
},
|
||||
"packages/theme": {
|
||||
"name": "@opencode/theme",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opentui/core": "catalog:",
|
||||
"effect": "catalog:",
|
||||
@@ -897,7 +897,7 @@
|
||||
},
|
||||
"packages/tui": {
|
||||
"name": "@opencode/tui",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@opencode/client": "workspace:*",
|
||||
"@opencode/core": "workspace:*",
|
||||
@@ -932,7 +932,7 @@
|
||||
},
|
||||
"packages/ui": {
|
||||
"name": "@opencode/ui",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@kobalte/core": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -967,7 +967,7 @@
|
||||
},
|
||||
"packages/util": {
|
||||
"name": "@opencode/util",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@effect/opentelemetry": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
@@ -1000,7 +1000,7 @@
|
||||
},
|
||||
"packages/web": {
|
||||
"name": "@opencode/web",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "12.6.3",
|
||||
"@astrojs/markdown-remark": "6.3.1",
|
||||
@@ -1041,7 +1041,7 @@
|
||||
},
|
||||
"services/update": {
|
||||
"name": "@opencode/update",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"dependencies": {
|
||||
"jose": "6.0.11",
|
||||
"semver": "catalog:",
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "opencode",
|
||||
"description": "AI-powered development tool",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "bun@1.4.2",
|
||||
@@ -24,6 +24,7 @@
|
||||
"test:lint-rules": "ast-grep test -c script/ast-grep/sgconfig.yml",
|
||||
"test:effect-simplification-rules": "ast-grep test -c script/ast-grep/effect-simplifications/sgconfig.yml",
|
||||
"typecheck": "bun turbo typecheck --concurrency=3",
|
||||
"check": "bun run lint && bun run typecheck",
|
||||
"typecheck:profile": "bun script/profile-typecheck.ts",
|
||||
"typecheck:profile:packages": "bun script/profile-typecheck-packages.ts",
|
||||
"upgrade-opentui": "bun run script/upgrade-opentui.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"name": "@opencode/ai",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -986,7 +986,7 @@ const lowerMessages = Effect.fn("AnthropicMessages.lowerMessages")(function* (
|
||||
else messages.push({ role: "user", content })
|
||||
}
|
||||
|
||||
return messages
|
||||
return ProviderShared.trimAssistantPrefill(messages)
|
||||
})
|
||||
|
||||
const resolveOptions = Effect.fn("AnthropicMessages.resolveOptions")(function* (request: LLMRequest) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import { BedrockAuth } from "./utils/bedrock-auth.js"
|
||||
import { BedrockCache } from "./utils/bedrock-cache.js"
|
||||
import { BedrockMedia } from "./utils/bedrock-media.js"
|
||||
import { Lifecycle } from "./utils/lifecycle.js"
|
||||
import { MistralToolID } from "./utils/mistral-tool-id.js"
|
||||
import { ToolSchemaProjection } from "./utils/tool-schema.js"
|
||||
import { ToolStream } from "./utils/tool-stream.js"
|
||||
|
||||
@@ -279,15 +280,19 @@ const removeEmptyToolInputKeys = (input: unknown): unknown => {
|
||||
)
|
||||
}
|
||||
|
||||
const lowerToolCall = (part: ToolCallPart): BedrockToolUseBlock => ({
|
||||
const lowerToolCall = (part: ToolCallPart, normalizeID: (id: string) => string): BedrockToolUseBlock => ({
|
||||
toolUse: {
|
||||
toolUseId: part.id,
|
||||
name: part.name,
|
||||
toolUseId: normalizeID(part.id),
|
||||
// Models can emit names that Converse rejects when replayed in history.
|
||||
name: part.name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "_",
|
||||
input: removeEmptyToolInputKeys(part.input),
|
||||
},
|
||||
})
|
||||
|
||||
const lowerToolResultContent = Effect.fn("BedrockConverse.lowerToolResultContent")(function* (part: ToolResultPart) {
|
||||
const lowerToolResultContent = Effect.fn("BedrockConverse.lowerToolResultContent")(function* (
|
||||
part: ToolResultPart,
|
||||
documentNames: Set<string>,
|
||||
) {
|
||||
if (part.result.type === "text" || part.result.type === "error")
|
||||
return [{ text: ProviderShared.toolResultText(part) }]
|
||||
if (part.result.type === "json") return [{ json: part.result.value }]
|
||||
@@ -298,22 +303,29 @@ const lowerToolResultContent = Effect.fn("BedrockConverse.lowerToolResultContent
|
||||
content.push({ text: item.text })
|
||||
continue
|
||||
}
|
||||
const media = yield* BedrockMedia.lower({
|
||||
type: "media",
|
||||
mediaType: item.mime,
|
||||
data: item.uri,
|
||||
filename: item.name,
|
||||
})
|
||||
content.push(media)
|
||||
const media = yield* BedrockMedia.lower(
|
||||
{
|
||||
type: "media",
|
||||
mediaType: item.mime,
|
||||
data: item.uri,
|
||||
filename: item.name,
|
||||
},
|
||||
documentNames,
|
||||
)
|
||||
content.push(...media)
|
||||
}
|
||||
return content
|
||||
})
|
||||
|
||||
const lowerToolResult = Effect.fn("BedrockConverse.lowerToolResult")(function* (part: ToolResultPart) {
|
||||
const lowerToolResult = Effect.fn("BedrockConverse.lowerToolResult")(function* (
|
||||
part: ToolResultPart,
|
||||
documentNames: Set<string>,
|
||||
normalizeID: (id: string) => string,
|
||||
) {
|
||||
return {
|
||||
toolResult: {
|
||||
toolUseId: part.id,
|
||||
content: yield* lowerToolResultContent(part),
|
||||
toolUseId: normalizeID(part.id),
|
||||
content: yield* lowerToolResultContent(part, documentNames),
|
||||
status: part.result.type === "error" ? "error" : "success",
|
||||
},
|
||||
} satisfies BedrockToolResultBlock
|
||||
@@ -324,6 +336,9 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
breakpoints: BedrockCache.Breakpoints,
|
||||
) {
|
||||
const messages: BedrockMessage[] = []
|
||||
const documentNames = new Set<string>()
|
||||
// Mistral can reject replay IDs even when they satisfy Converse's broader ID syntax.
|
||||
const normalizeID = request.model.id.includes("mistral.") ? MistralToolID.normalizer(request) : (id: string) => id
|
||||
const providerMetadataKey = request.model.route.providerMetadataKey ?? String(request.model.provider)
|
||||
|
||||
for (const message of request.messages) {
|
||||
@@ -347,7 +362,7 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
continue
|
||||
}
|
||||
if (part.type === "media") {
|
||||
content.push(yield* BedrockMedia.lower(part))
|
||||
content.push(...(yield* BedrockMedia.lower(part, documentNames)))
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -368,6 +383,7 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
"tool-call",
|
||||
])
|
||||
if (part.type === "text") {
|
||||
if (part.text.length === 0) continue
|
||||
content.push(...textWithCache(breakpoints, part.text, part.cache))
|
||||
continue
|
||||
}
|
||||
@@ -388,7 +404,7 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
continue
|
||||
}
|
||||
if (part.type === "tool-call") {
|
||||
content.push(lowerToolCall(part))
|
||||
content.push(lowerToolCall(part, normalizeID))
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -400,7 +416,7 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
for (const part of message.content) {
|
||||
if (!ProviderShared.supportsContent(part, ["tool-result"]))
|
||||
return yield* ProviderShared.unsupportedContent("Bedrock Converse", "tool", ["tool-result"])
|
||||
content.push(yield* lowerToolResult(part))
|
||||
content.push(yield* lowerToolResult(part, documentNames, normalizeID))
|
||||
const cachePoint = BedrockCache.block(breakpoints, part.cache)
|
||||
if (cachePoint) content.push(cachePoint)
|
||||
}
|
||||
@@ -410,7 +426,7 @@ const lowerMessages = Effect.fn("BedrockConverse.lowerMessages")(function* (
|
||||
else messages.push({ role: "user", content })
|
||||
}
|
||||
|
||||
return messages
|
||||
return ProviderShared.trimAssistantPrefill(messages)
|
||||
})
|
||||
|
||||
// System prompts share the cache-point convention: emit the text block, then
|
||||
|
||||
@@ -21,11 +21,11 @@ import {
|
||||
import { classifyProviderFailure } from "../provider-error.js"
|
||||
import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
|
||||
import { Lifecycle } from "./utils/lifecycle.js"
|
||||
import { MistralToolID } from "./utils/mistral-tool-id.js"
|
||||
import { ToolStream } from "./utils/tool-stream.js"
|
||||
|
||||
const ADAPTER = "mistral-chat"
|
||||
const DONE = "[DONE]" as const
|
||||
const TOOL_ID = /^[A-Za-z0-9]{9}$/
|
||||
export const DEFAULT_BASE_URL = "https://api.mistral.ai/v1"
|
||||
export const PATH = "/chat/completions"
|
||||
|
||||
@@ -223,34 +223,6 @@ const MistralEvent = Schema.StructWithRest(
|
||||
type MistralEvent = Schema.Schema.Type<typeof MistralEvent>
|
||||
const MistralStreamEvent = Schema.Union([Schema.Literal(DONE), Protocol.jsonEvent(MistralEvent)])
|
||||
|
||||
const hashID = (value: string) => {
|
||||
const hash = (seed: number) => {
|
||||
let result = seed
|
||||
for (const char of value) result = Math.imul(result ^ char.charCodeAt(0), 16777619)
|
||||
return (result >>> 0).toString(36)
|
||||
}
|
||||
return `${hash(2166136261).padStart(7, "0")}${hash(2246822519).padStart(7, "0")}`.slice(-9)
|
||||
}
|
||||
|
||||
const toolIDNormalizer = (request: LLMRequest) => {
|
||||
const ids = request.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => (part.type === "tool-call" || part.type === "tool-result" ? [part.id] : [])),
|
||||
)
|
||||
const used = new Set(ids.filter((id) => TOOL_ID.test(id)))
|
||||
const normalized = new Map<string, string>()
|
||||
return (id: string) => {
|
||||
if (TOOL_ID.test(id)) return id
|
||||
const previous = normalized.get(id)
|
||||
if (previous) return previous
|
||||
let attempt = 0
|
||||
let candidate = hashID(id)
|
||||
while (used.has(candidate)) candidate = hashID(`${id}:${++attempt}`)
|
||||
used.add(candidate)
|
||||
normalized.set(id, candidate)
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
const lowerMedia = Effect.fn("MistralChat.lowerMedia")(function* (part: MediaPart) {
|
||||
const media = ProviderShared.normalizeMedia(part)
|
||||
const url = typeof part.data === "string" && /^(?:https?:|data:)/.test(part.data) ? part.data : media.dataUrl
|
||||
@@ -359,7 +331,7 @@ const lowerToolResults = Effect.fn("MistralChat.lowerToolResults")(function* (
|
||||
})
|
||||
|
||||
const lowerMessages = Effect.fn("MistralChat.lowerMessages")(function* (request: LLMRequest) {
|
||||
const normalizeID = toolIDNormalizer(request)
|
||||
const normalizeID = MistralToolID.normalizer(request)
|
||||
const messages: MistralMessage[] =
|
||||
request.system.length === 0 ? [] : [{ role: "system", content: ProviderShared.joinText(request.system) }]
|
||||
for (const message of request.messages) {
|
||||
@@ -582,13 +554,13 @@ const appendContent = (
|
||||
}
|
||||
|
||||
const normalizeStreamToolID = (state: ParserState, source: string) => {
|
||||
if (TOOL_ID.test(source))
|
||||
if (MistralToolID.valid.test(source))
|
||||
return { id: source, state: { ...state, usedToolIDs: new Set([...state.usedToolIDs, source]) } }
|
||||
const previous = state.toolIDs.get(source)
|
||||
if (previous) return { id: previous, state }
|
||||
let attempt = 0
|
||||
let id = hashID(source)
|
||||
while (state.usedToolIDs.has(id)) id = hashID(`${source}:${++attempt}`)
|
||||
let id = MistralToolID.hash(source)
|
||||
while (state.usedToolIDs.has(id)) id = MistralToolID.hash(`${source}:${++attempt}`)
|
||||
return {
|
||||
id,
|
||||
state: {
|
||||
|
||||
@@ -766,7 +766,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||
supportsStrictMode,
|
||||
),
|
||||
),
|
||||
tool_choice: request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
|
||||
tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
|
||||
stream: true as const,
|
||||
...(supportsUsageInStreaming ? { stream_options: { include_usage: true } } : {}),
|
||||
...(zaiToolStream && hasActiveTools ? { tool_stream: true } : {}),
|
||||
|
||||
@@ -199,8 +199,10 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
|
||||
? undefined
|
||||
: yield* Effect.forEach(request.tools, (tool) => lowerToolEntry(tool, toolSchemaCompatibility)),
|
||||
tool_choice:
|
||||
OpenResponses.allowedToolChoice(request) ??
|
||||
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined),
|
||||
request.tools.length === 0
|
||||
? undefined
|
||||
: (OpenResponses.allowedToolChoice(request) ??
|
||||
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined)),
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -122,6 +122,41 @@ export const parseJson = (route: string, input: string, message: string) =>
|
||||
*/
|
||||
export const joinText = (parts: ReadonlyArray<{ readonly text: string }>) => parts.map((part) => part.text).join("\n")
|
||||
|
||||
// Anthropic and Converse reject trailing whitespace in assistant prefills.
|
||||
// Work on lowered copies so filtering and cache markers cannot hide the final text.
|
||||
export const trimAssistantPrefill = <
|
||||
T extends {
|
||||
readonly role: string
|
||||
readonly content: ReadonlyArray<{ readonly text?: string; readonly [key: string]: unknown }>
|
||||
},
|
||||
>(
|
||||
messages: ReadonlyArray<T>,
|
||||
): T[] => {
|
||||
const result = [...messages]
|
||||
while (result.at(-1)?.role === "assistant") {
|
||||
const message = result[result.length - 1]
|
||||
const content = [...message.content]
|
||||
while (content.length > 0) {
|
||||
const index = content.findLastIndex((part) => !("cachePoint" in part))
|
||||
const part = content[index]
|
||||
if (part?.text === undefined) break
|
||||
const text = part.text.trimEnd()
|
||||
if (text.length > 0) {
|
||||
content[index] = { ...part, text }
|
||||
break
|
||||
}
|
||||
// Remove the blank suffix and any cache marker belonging to it.
|
||||
content.splice(index)
|
||||
}
|
||||
if (content.length > 0) {
|
||||
result[result.length - 1] = { ...message, content }
|
||||
break
|
||||
}
|
||||
result.pop()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const escapeSystemUpdateText = (text: string) =>
|
||||
text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
|
||||
|
||||
|
||||
@@ -57,6 +57,25 @@ const documentBlock = (name: string, format: DocumentFormat, bytes: string): Doc
|
||||
},
|
||||
})
|
||||
|
||||
function documentName(filename: string | undefined, names: Set<string>) {
|
||||
const base =
|
||||
(filename ?? "")
|
||||
.replace(/\.[^.]*$/, "")
|
||||
.replace(/[^a-zA-Z0-9 ()[\]-]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, 200)
|
||||
.trim() || "document"
|
||||
let name = base
|
||||
// Converse requires labels to be unique across the entire request, including tool results.
|
||||
for (let index = 2; names.has(name); index++) {
|
||||
const suffix = ` ${index}`
|
||||
name = `${base.slice(0, 200 - suffix.length).trimEnd()}${suffix}`
|
||||
}
|
||||
names.add(name)
|
||||
return name
|
||||
}
|
||||
|
||||
const mediaBase64 = Effect.fn("BedrockMedia.mediaBase64")(function* (part: MediaPart) {
|
||||
const media = ProviderShared.normalizeMedia(part)
|
||||
const bytes = yield* Effect.fromResult(Encoding.decodeBase64(media.base64)).pipe(
|
||||
@@ -72,19 +91,26 @@ const mediaBase64 = Effect.fn("BedrockMedia.mediaBase64")(function* (part: Media
|
||||
// document block. Image MIME types not in `IMAGE_FORMATS` (e.g. `image/svg+xml`)
|
||||
// get an image-specific error so the caller knows it's a format-support issue,
|
||||
// not a kind-detection issue.
|
||||
export const lower = Effect.fn("BedrockMedia.lower")(function* (part: MediaPart) {
|
||||
export const lower = Effect.fn("BedrockMedia.lower")(function* (part: MediaPart, documentNames: Set<string>) {
|
||||
const mime = part.mediaType.toLowerCase()
|
||||
const imageFormat = IMAGE_FORMATS[mime as keyof typeof IMAGE_FORMATS]
|
||||
if (imageFormat) {
|
||||
return { image: { format: imageFormat, source: { bytes: yield* mediaBase64(part) } } } satisfies ImageBlock
|
||||
return [{ image: { format: imageFormat, source: { bytes: yield* mediaBase64(part) } } } satisfies ImageBlock]
|
||||
}
|
||||
if (mime.startsWith("image/"))
|
||||
return yield* ProviderShared.invalidRequest(`Bedrock Converse does not support image media type ${part.mediaType}`)
|
||||
const documentFormat = DOCUMENT_FORMATS[mime as keyof typeof DOCUMENT_FORMATS]
|
||||
if (documentFormat) {
|
||||
if (!part.filename)
|
||||
return yield* ProviderShared.invalidRequest("Bedrock Converse document media requires a filename")
|
||||
return documentBlock(part.filename, documentFormat, yield* mediaBase64(part))
|
||||
const name = documentName(part.filename, documentNames)
|
||||
const block = documentBlock(name, documentFormat, yield* mediaBase64(part))
|
||||
return part.filename !== undefined && part.filename !== name
|
||||
? [
|
||||
{
|
||||
text: `Attached file ${ProviderShared.encodeJson(part.filename)} has document label ${ProviderShared.encodeJson(name)}.`,
|
||||
},
|
||||
block,
|
||||
]
|
||||
: [block]
|
||||
}
|
||||
return yield* ProviderShared.invalidRequest(`Bedrock Converse does not support media type ${part.mediaType}`)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { LLMRequest } from "../../schema/index.js"
|
||||
|
||||
export const valid = /^[A-Za-z0-9]{9}$/
|
||||
|
||||
export const hash = (value: string) => {
|
||||
const hash = (seed: number) => {
|
||||
let result = seed
|
||||
for (const char of value) result = Math.imul(result ^ char.charCodeAt(0), 16777619)
|
||||
return (result >>> 0).toString(36)
|
||||
}
|
||||
return `${hash(2166136261).padStart(7, "0")}${hash(2246822519).padStart(7, "0")}`.slice(-9)
|
||||
}
|
||||
|
||||
export const normalizer = (request: LLMRequest) => {
|
||||
const ids = request.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => (part.type === "tool-call" || part.type === "tool-result" ? [part.id] : [])),
|
||||
)
|
||||
// Reserve valid IDs before projecting any history, including IDs encountered later.
|
||||
const used = new Set(ids.filter((id) => valid.test(id)))
|
||||
const normalized = new Map<string, string>()
|
||||
return (id: string) => {
|
||||
if (valid.test(id)) return id
|
||||
const previous = normalized.get(id)
|
||||
if (previous) return previous
|
||||
let attempt = 0
|
||||
let candidate = hash(id)
|
||||
while (used.has(candidate)) candidate = hash(`${id}:${++attempt}`)
|
||||
used.add(candidate)
|
||||
normalized.set(id, candidate)
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
export * as MistralToolID from "./mistral-tool-id.js"
|
||||
@@ -325,6 +325,7 @@ describe("provider package entrypoints", () => {
|
||||
test("requires an Anthropic-compatible base URL at runtime", async () => {
|
||||
const AnthropicCompatible = await import("@opencode/ai/providers/anthropic-compatible")
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally bypasses static required-option checks.
|
||||
Reflect.apply(AnthropicCompatible.model, undefined, ["compatible-model", { apiKey: "fixture" }]),
|
||||
).toThrow(configuration("anthropic-compatible", "Anthropic-compatible providers require a baseURL"))
|
||||
})
|
||||
@@ -333,6 +334,7 @@ describe("provider package entrypoints", () => {
|
||||
const Anthropic = await import("@opencode/ai/providers/anthropic")
|
||||
const AnthropicCompatible = await import("@opencode/ai/providers/anthropic-compatible")
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes a statically invalid option combination.
|
||||
Reflect.apply(AnthropicCompatible.model, undefined, [
|
||||
"compatible-model",
|
||||
{
|
||||
@@ -343,6 +345,7 @@ describe("provider package entrypoints", () => {
|
||||
]),
|
||||
).toThrow(configuration("anthropic-compatible", "Anthropic-compatible apiKey cannot be combined with authToken"))
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes a statically invalid option combination.
|
||||
Reflect.apply(Anthropic.model, undefined, ["claude-sonnet-4-6", { apiKey: "fixture", authToken: "token" }]),
|
||||
).toThrow(configuration("anthropic", "Anthropic apiKey cannot be combined with authToken"))
|
||||
})
|
||||
@@ -490,11 +493,13 @@ describe("provider package entrypoints", () => {
|
||||
const GoogleVertexResponses = await import("@opencode/ai/providers/google-vertex/responses")
|
||||
const Providers = await import("@opencode/ai/providers")
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes a statically invalid option combination.
|
||||
Reflect.apply(GoogleVertex.model, undefined, [
|
||||
"gemini-3.5-flash",
|
||||
{ accessToken: "token", apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
).toThrow(configuration("google-vertex", "Google Vertex apiKey cannot be combined with accessToken or auth"))
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes a statically invalid option combination.
|
||||
const configured = Reflect.apply(GoogleVertex.configure, undefined, [
|
||||
{ accessToken: "token", auth: {}, project: "vertex-project" },
|
||||
])
|
||||
@@ -502,34 +507,40 @@ describe("provider package entrypoints", () => {
|
||||
configuration("google-vertex", "Google Vertex accessToken cannot be combined with auth"),
|
||||
)
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes an unsupported authentication option.
|
||||
Reflect.apply(GoogleVertexMessages.model, undefined, [
|
||||
"claude-sonnet-4-6",
|
||||
{ apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
).toThrow(configuration("google-vertex", "Google Vertex Messages does not support API keys"))
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes an unsupported authentication option.
|
||||
Reflect.apply(Providers.GoogleVertexMessages.configure, undefined, [
|
||||
{ apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
).toThrow(configuration("google-vertex", "Google Vertex Messages does not support API keys"))
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes an unsupported authentication option.
|
||||
Reflect.apply(GoogleVertexChat.model, undefined, [
|
||||
"deepseek-ai/deepseek-v3.2-maas",
|
||||
{ apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
).toThrow(configuration("google-vertex", "Google Vertex Chat does not support API keys"))
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes an unsupported authentication option.
|
||||
Reflect.apply(Providers.GoogleVertexChat.configure, undefined, [
|
||||
{ apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
).toThrow(configuration("google-vertex", "Google Vertex Chat does not support API keys"))
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes an unsupported authentication option.
|
||||
Reflect.apply(GoogleVertexResponses.model, undefined, [
|
||||
"xai/grok-4.20-reasoning",
|
||||
{ apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
).toThrow(configuration("google-vertex", "Google Vertex Responses does not support API keys"))
|
||||
expect(() =>
|
||||
// oxlint-disable-next-line no-restricted-globals -- This test intentionally passes an unsupported authentication option.
|
||||
Reflect.apply(Providers.GoogleVertexResponses.configure, undefined, [
|
||||
{ apiKey: "fixture", project: "vertex-project" },
|
||||
]),
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { CacheHint, LLM, Message, ToolCallPart } from "../../src/index.js"
|
||||
import { AnthropicMessages } from "../../src/protocols/anthropic-messages.js"
|
||||
import { BedrockConverse } from "../../src/protocols/bedrock-converse.js"
|
||||
import { compileRequest } from "../../src/route/client.js"
|
||||
import { Auth } from "../../src/route/auth.js"
|
||||
import { it } from "../lib/effect.js"
|
||||
|
||||
const bedrockRoute = BedrockConverse.route.with({
|
||||
endpoint: { baseURL: "https://bedrock.test" },
|
||||
auth: Auth.bearer("test"),
|
||||
})
|
||||
|
||||
for (const route of [AnthropicMessages.route, bedrockRoute]) {
|
||||
const bedrock = route.id === "bedrock-converse"
|
||||
const model = route.model({
|
||||
id: bedrock ? "global.anthropic.claude-haiku-4-5-20251001-v1:0" : "claude-haiku-4-5-20251001",
|
||||
})
|
||||
const text = (value: string) => (bedrock ? { text: value } : { type: "text", text: value })
|
||||
const cache = new CacheHint({ type: "ephemeral" })
|
||||
|
||||
it.effect(`${route.id} trims only the effective assistant prefill suffix`, () =>
|
||||
Effect.gen(function* () {
|
||||
const messages = [
|
||||
Message.user("Keep the formatting. "),
|
||||
Message.assistant("Historical text. \n"),
|
||||
Message.user("Continue."),
|
||||
Message.assistant([
|
||||
{ type: "text", text: " Leading and middle " },
|
||||
{ type: "text", text: "spacing \n" },
|
||||
{ type: "text", text: " \n", cache },
|
||||
{ type: "text", text: "", cache },
|
||||
]),
|
||||
Message.assistant(""),
|
||||
Message.assistant([]),
|
||||
]
|
||||
const before = structuredClone(messages)
|
||||
const request = LLM.request({ model, messages, cache: "none" })
|
||||
const prepared = yield* compileRequest(request)
|
||||
expect(prepared.body.messages).toEqual([
|
||||
{ role: "user", content: [text("Keep the formatting. ")] },
|
||||
{ role: "assistant", content: [text("Historical text. \n")] },
|
||||
{ role: "user", content: [text("Continue.")] },
|
||||
{ role: "assistant", content: [text(" Leading and middle "), text("spacing")] },
|
||||
])
|
||||
expect((yield* compileRequest(request)).body).toEqual(prepared.body)
|
||||
expect(structuredClone(messages)).toEqual(before)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect(`${route.id} preserves a surviving prefill cache marker`, () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
messages: [Message.user("Continue."), Message.assistant([{ type: "text", text: " Answer \t", cache }])],
|
||||
cache: "none",
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.messages).toEqual([
|
||||
{ role: "user", content: [text("Continue.")] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: bedrock
|
||||
? [text(" Answer"), { cachePoint: { type: "default" } }]
|
||||
: [{ type: "text", text: " Answer", cache_control: { type: "ephemeral" } }],
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect(`${route.id} drops blank-only terminal assistants and their cache markers`, () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
messages: [
|
||||
Message.user("Continue. "),
|
||||
Message.assistant("Prefix \n"),
|
||||
Message.assistant([{ type: "text", text: " \n\t", cache }]),
|
||||
],
|
||||
cache: "none",
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.messages).toEqual([
|
||||
{ role: "user", content: [text("Continue. ")] },
|
||||
{ role: "assistant", content: [text("Prefix")] },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect(`${route.id} preserves signed reasoning and does not trim text before a tool call`, () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
messages: [
|
||||
Message.user("Look it up."),
|
||||
Message.assistant([
|
||||
{ type: "reasoning", text: " Signed thinking \n", encrypted: "sig_1" },
|
||||
{ type: "text", text: "", cache },
|
||||
{ type: "text", text: "Calling the tool. \n" },
|
||||
ToolCallPart.make({ id: "call_1", name: "lookup", input: {} }),
|
||||
]),
|
||||
],
|
||||
cache: "none",
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.messages).toEqual([
|
||||
{ role: "user", content: [text("Look it up.")] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
bedrock
|
||||
? { reasoningContent: { reasoningText: { text: " Signed thinking \n", signature: "sig_1" } } }
|
||||
: { type: "thinking", thinking: " Signed thinking \n", signature: "sig_1" },
|
||||
text("Calling the tool. \n"),
|
||||
bedrock
|
||||
? { toolUse: { toolUseId: "call_1", name: "lookup", input: {} } }
|
||||
: { type: "tool_use", id: "call_1", name: "lookup", input: {} },
|
||||
],
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
it.effect("Bedrock drops empty historical assistant text while retaining non-empty whitespace", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model: bedrockRoute.model({ id: "global.anthropic.claude-haiku-4-5-20251001-v1:0" }),
|
||||
messages: [
|
||||
Message.user("First."),
|
||||
Message.assistant([{ type: "text", text: "", cache: new CacheHint({ type: "ephemeral" }) }]),
|
||||
Message.user("Second."),
|
||||
Message.assistant([
|
||||
{ type: "text", text: "" },
|
||||
{ type: "text", text: " \n\t" },
|
||||
{ type: "text", text: "READY \n" },
|
||||
]),
|
||||
Message.user("Continue."),
|
||||
],
|
||||
cache: "none",
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.messages).toEqual([
|
||||
{ role: "user", content: [{ text: "First." }, { text: "Second." }] },
|
||||
{ role: "assistant", content: [{ text: " \n\t" }, { text: "READY \n" }] },
|
||||
{ role: "user", content: [{ text: "Continue." }] },
|
||||
])
|
||||
}),
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EventStreamCodec } from "@smithy/eventstream-codec"
|
||||
import { fromUtf8, toUtf8 } from "@smithy/util-utf8"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Encoding, Ref, Stream } from "effect"
|
||||
import { Effect, Encoding, Ref, Schema, Stream } from "effect"
|
||||
import { HttpClientRequest } from "effect/unstable/http"
|
||||
import {
|
||||
CacheHint,
|
||||
@@ -11,9 +11,11 @@ import {
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
Message,
|
||||
Tool,
|
||||
ToolCallPart,
|
||||
ToolChoice,
|
||||
ToolDefinition,
|
||||
ToolRuntime,
|
||||
} from "../../src/index.js"
|
||||
import { LLMClient } from "../../src/route.js"
|
||||
import { compileRequest } from "../../src/route/client.js"
|
||||
@@ -394,6 +396,45 @@ describe("Bedrock Converse route", () => {
|
||||
})
|
||||
}),
|
||||
)
|
||||
;[
|
||||
{ name: "browser.tabs.open", expected: "browser_tabs_open" },
|
||||
{ name: "$lookup", expected: "_lookup" },
|
||||
{ name: "", expected: "_" },
|
||||
{ name: " ", expected: "___" },
|
||||
{ name: "a".repeat(65), expected: "a".repeat(64) },
|
||||
{ name: "lookup_123-ABC", expected: "lookup_123-ABC" },
|
||||
{ name: "a".repeat(64), expected: "a".repeat(64) },
|
||||
].forEach((item) => {
|
||||
it.effect(`replays historical tool name ${JSON.stringify(item.name)} within Bedrock constraints`, () =>
|
||||
Effect.gen(function* () {
|
||||
const call = ToolCallPart.make({ id: "call_unknown", name: item.name, input: { query: "weather" } })
|
||||
const error = `No tool named "${item.name}" is currently available. Please use a tool from the available tool list.`
|
||||
const request = LLM.request({
|
||||
model,
|
||||
cache: "none",
|
||||
tools: [ToolDefinition.make({ name: "execute", description: "Run code", inputSchema: { type: "object" } })],
|
||||
messages: [
|
||||
Message.user("Check the weather"),
|
||||
Message.assistant([call]),
|
||||
Message.tool({ id: call.id, name: call.name, result: error, resultType: "error" }),
|
||||
Message.user("Say OK"),
|
||||
],
|
||||
})
|
||||
const prepared = yield* compileRequest(request)
|
||||
|
||||
expect(prepared.body.messages[1].content).toEqual([
|
||||
{ toolUse: { toolUseId: call.id, name: item.expected, input: call.input } },
|
||||
])
|
||||
expect(prepared.body.messages[2].content).toEqual([
|
||||
{ toolResult: { toolUseId: call.id, content: [{ text: error }], status: "error" } },
|
||||
{ text: "Say OK" },
|
||||
])
|
||||
expect(prepared.body.toolConfig.tools.map((tool) => tool.toolSpec.name)).toEqual(["execute"])
|
||||
expect(request.messages[1].content[0]).toEqual(call)
|
||||
expect(call.name).toBe(item.name)
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it.effect("removes empty keys recursively from outbound tool inputs without mutating history", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -797,6 +838,57 @@ describe("Bedrock Converse route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects a provider-emitted dotted name before normalizing its replay", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* LLMClient.generate(baseRequest).pipe(
|
||||
Effect.provide(
|
||||
fixedBytes(
|
||||
eventStreamBody(
|
||||
[
|
||||
"contentBlockStart",
|
||||
{ contentBlockIndex: 0, start: { toolUse: { toolUseId: "call_unknown", name: "browser.tabs.open" } } },
|
||||
],
|
||||
["contentBlockDelta", { contentBlockIndex: 0, delta: { toolUse: { input: "{}" } } }],
|
||||
["contentBlockStop", { contentBlockIndex: 0 }],
|
||||
["messageStop", { stopReason: "tool_use" }],
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
const call = response.toolCalls[0]
|
||||
if (!call) throw new Error("Expected a tool call")
|
||||
expect(call.name).toBe("browser.tabs.open")
|
||||
const dispatched = yield* ToolRuntime.dispatch(
|
||||
{
|
||||
browser_tabs_open: Tool.make({
|
||||
description: "Open a tab",
|
||||
parameters: Schema.Struct({}),
|
||||
success: Schema.String,
|
||||
execute: () => Effect.die("A normalized replay name must not select an executor"),
|
||||
}),
|
||||
},
|
||||
call,
|
||||
)
|
||||
expect(dispatched.result).toEqual({
|
||||
type: "error",
|
||||
value:
|
||||
'No tool named "browser.tabs.open" is currently available. Please use a tool from the available tool list.',
|
||||
})
|
||||
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
cache: "none",
|
||||
messages: [response.message, Message.tool({ id: call.id, name: call.name, result: dispatched.result })],
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.messages[0].content).toEqual([
|
||||
{ toolUse: { toolUseId: call.id, name: "browser_tabs_open", input: {} } },
|
||||
])
|
||||
expect(response.toolCalls[0]?.name).toBe("browser.tabs.open")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("ignores tool deltas without an open tool block", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = eventStreamBody(
|
||||
@@ -1673,29 +1765,141 @@ describe("Bedrock Converse route", () => {
|
||||
role: "user",
|
||||
content: [
|
||||
{ text: "Summarize these documents." },
|
||||
{ document: { format: "pdf", name: "report.pdf", source: { bytes: "UERGREFUQQ==" } } },
|
||||
{ document: { format: "csv", name: "data.csv", source: { bytes: "Q1NWREFUQQ==" } } },
|
||||
{ text: 'Attached file "report.pdf" has document label "report".' },
|
||||
{ document: { format: "pdf", name: "report", source: { bytes: "UERGREFUQQ==" } } },
|
||||
{ text: 'Attached file "data.csv" has document label "data".' },
|
||||
{ document: { format: "csv", name: "data", source: { bytes: "Q1NWREFUQQ==" } } },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
}),
|
||||
)
|
||||
;[
|
||||
{
|
||||
label: "filename punctuation",
|
||||
filename: "report_v1.2?.pdf",
|
||||
expected: "report v1 2",
|
||||
duplicate: "report v1 2 2",
|
||||
},
|
||||
{
|
||||
label: "repeated whitespace",
|
||||
filename: " Quarterly\t \n report.txt",
|
||||
expected: "Quarterly report",
|
||||
duplicate: "Quarterly report 2",
|
||||
},
|
||||
{
|
||||
label: "allowed characters",
|
||||
filename: "Report - Final (v2) [2026]",
|
||||
expected: "Report - Final (v2) [2026]",
|
||||
duplicate: "Report - Final (v2) [2026] 2",
|
||||
},
|
||||
{ label: "accented filename", filename: "résumé.pdf", expected: "r sum", duplicate: "r sum 2" },
|
||||
{ label: "non-Latin filename", filename: "報告書.pdf", expected: "document", duplicate: "document 2" },
|
||||
{ label: "missing filename", filename: undefined, expected: "document", duplicate: "document 2" },
|
||||
{ label: "empty filename", filename: "", expected: "document", duplicate: "document 2" },
|
||||
{ label: "blank filename", filename: " \t\n", expected: "document", duplicate: "document 2" },
|
||||
{ label: "extension-only filename", filename: ".pdf", expected: "document", duplicate: "document 2" },
|
||||
{ label: "symbols-only filename", filename: "@@@.pdf", expected: "document", duplicate: "document 2" },
|
||||
{
|
||||
label: "overlong filename",
|
||||
filename: `${"a".repeat(201)}.txt`,
|
||||
expected: "a".repeat(200),
|
||||
duplicate: `${"a".repeat(198)} 2`,
|
||||
},
|
||||
{
|
||||
label: "maximum-length label",
|
||||
filename: "a".repeat(200),
|
||||
expected: "a".repeat(200),
|
||||
duplicate: `${"a".repeat(198)} 2`,
|
||||
},
|
||||
{
|
||||
label: "whitespace at truncation",
|
||||
filename: `${"a".repeat(199)} b.txt`,
|
||||
expected: "a".repeat(199),
|
||||
duplicate: `${"a".repeat(198)} 2`,
|
||||
},
|
||||
].forEach((item) => {
|
||||
it.effect(`normalizes ${item.label} in user and tool-result documents`, () =>
|
||||
Effect.gen(function* () {
|
||||
const request = LLM.request({
|
||||
model,
|
||||
cache: "none",
|
||||
messages: [
|
||||
Message.user([
|
||||
{ type: "text", text: "Read this document" },
|
||||
{ type: "media", mediaType: "application/pdf", data: "UERGREFUQQ==", filename: item.filename },
|
||||
]),
|
||||
Message.assistant([ToolCallPart.make({ id: "call_read", name: "read", input: {} })]),
|
||||
Message.tool({
|
||||
id: "call_read",
|
||||
name: "read",
|
||||
result: {
|
||||
type: "content",
|
||||
value: [
|
||||
{ type: "text", text: "Read successfully" },
|
||||
{
|
||||
type: "file",
|
||||
uri: "data:application/pdf;base64,UERGREFUQQ==",
|
||||
mime: "application/pdf",
|
||||
name: item.filename,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
const original = JSON.stringify(request.messages)
|
||||
const first = yield* compileRequest(request)
|
||||
const second = yield* compileRequest(request)
|
||||
const expected = { format: "pdf", name: item.expected, source: { bytes: "UERGREFUQQ==" } }
|
||||
|
||||
it.effect("requires names for document media", () =>
|
||||
expect(first.body.messages[0].content.find((part) => "document" in part)?.document).toEqual(expected)
|
||||
expect(
|
||||
first.body.messages[2].content[0].toolResult.content.find((part) => "document" in part)?.document,
|
||||
).toEqual({
|
||||
...expected,
|
||||
name: item.duplicate,
|
||||
})
|
||||
expect(second.body).toEqual(first.body)
|
||||
expect(JSON.stringify(request.messages)).toBe(original)
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it.effect("keeps colliding document labels distinct within a request", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* compileRequest(
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
messages: [Message.user({ type: "media", mediaType: "application/pdf", data: "UERGREFUQQ==" })],
|
||||
cache: "none",
|
||||
messages: [
|
||||
Message.user([
|
||||
{ type: "text", text: "Read these documents" },
|
||||
...["report_v1.txt", "report#v1.txt", "report v1 2.txt", "report v1.txt"].map((filename) => ({
|
||||
type: "media" as const,
|
||||
mediaType: "text/plain",
|
||||
data: "SGVsbG8=",
|
||||
filename,
|
||||
})),
|
||||
]),
|
||||
],
|
||||
}),
|
||||
).pipe(Effect.flip)
|
||||
|
||||
expect(error.message).toContain("document media requires a filename")
|
||||
)
|
||||
expect(prepared.body.messages[0].content.slice(1)).toEqual([
|
||||
{ text: 'Attached file "report_v1.txt" has document label "report v1".' },
|
||||
{ document: { format: "txt", name: "report v1", source: { bytes: "SGVsbG8=" } } },
|
||||
{ text: 'Attached file "report#v1.txt" has document label "report v1 2".' },
|
||||
{ document: { format: "txt", name: "report v1 2", source: { bytes: "SGVsbG8=" } } },
|
||||
{ text: 'Attached file "report v1 2.txt" has document label "report v1 2 2".' },
|
||||
{ document: { format: "txt", name: "report v1 2 2", source: { bytes: "SGVsbG8=" } } },
|
||||
{ text: 'Attached file "report v1.txt" has document label "report v1 3".' },
|
||||
{ document: { format: "txt", name: "report v1 3", source: { bytes: "SGVsbG8=" } } },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("passes named document-only messages through for provider validation", () =>
|
||||
it.effect("annotates renamed document-only messages with their original filename", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
@@ -1715,12 +1919,44 @@ describe("Bedrock Converse route", () => {
|
||||
expect(prepared.body.messages).toEqual([
|
||||
{
|
||||
role: "user",
|
||||
content: [{ document: { format: "pdf", name: "report.pdf", source: { bytes: "UERGREFUQQ==" } } }],
|
||||
content: [
|
||||
{ text: 'Attached file "report.pdf" has document label "report".' },
|
||||
{ document: { format: "pdf", name: "report", source: { bytes: "UERGREFUQQ==" } } },
|
||||
],
|
||||
},
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("quotes original filenames in annotations and omits redundant mappings", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
cache: "none",
|
||||
messages: [
|
||||
Message.user([
|
||||
{ type: "text", text: "Read these documents" },
|
||||
...["report", undefined, 'report "final"\n.pdf'].map((filename) => ({
|
||||
type: "media" as const,
|
||||
mediaType: "text/plain",
|
||||
data: "SGVsbG8=",
|
||||
filename,
|
||||
})),
|
||||
]),
|
||||
],
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.messages[0].content).toEqual([
|
||||
{ text: "Read these documents" },
|
||||
{ document: { format: "txt", name: "report", source: { bytes: "SGVsbG8=" } } },
|
||||
{ document: { format: "txt", name: "document", source: { bytes: "SGVsbG8=" } } },
|
||||
{ text: 'Attached file "report \\"final\\"\\n.pdf" has document label "report final".' },
|
||||
{ document: { format: "txt", name: "report final", source: { bytes: "SGVsbG8=" } } },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("lowers document media in tool results", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
@@ -1740,7 +1976,7 @@ describe("Bedrock Converse route", () => {
|
||||
type: "file",
|
||||
uri: "data:application/pdf;base64,UERGREFUQQ==",
|
||||
mime: "application/pdf",
|
||||
name: "report",
|
||||
name: "report.pdf",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -1763,6 +1999,7 @@ describe("Bedrock Converse route", () => {
|
||||
status: "success",
|
||||
content: [
|
||||
{ text: "Read successfully" },
|
||||
{ text: 'Attached file "report.pdf" has document label "report".' },
|
||||
{ document: { format: "pdf", name: "report", source: { bytes: "UERGREFUQQ==" } } },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { expect } from "bun:test"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { LLM, Message, ToolCallPart } from "../../src/index.js"
|
||||
import { AmazonBedrock } from "../../src/providers.js"
|
||||
import { BedrockConverse } from "../../src/protocols/bedrock-converse.js"
|
||||
import { compileRequest } from "../../src/route/client.js"
|
||||
import { it } from "../lib/effect.js"
|
||||
|
||||
const bedrock = AmazonBedrock.configure({ baseURL: "https://bedrock.test", apiKey: "test-key" })
|
||||
const history = (ids: string[]) => [
|
||||
Message.user("Read every label"),
|
||||
Message.assistant(ids.map((id, index) => ToolCallPart.make({ id, name: "lookup", input: { label: index } }))),
|
||||
...ids.map((id, index) => Message.tool({ id, name: "lookup", result: `value-${index}` })).toReversed(),
|
||||
]
|
||||
|
||||
for (const model of [
|
||||
"mistral.mistral-large-2407-v1:0",
|
||||
"us.mistral.pixtral-large-2502-v1:0",
|
||||
"arn:aws:bedrock:us-east-1::foundation-model/mistral.pixtral-large-2502-v1:0",
|
||||
]) {
|
||||
it.effect(`preserves distinct call/result pairs and history for ${model}`, () =>
|
||||
Effect.gen(function* () {
|
||||
const request = LLM.request({ model: bedrock.model(model), messages: history(["a"]), cache: "none" })
|
||||
const first = Schema.decodeUnknownSync(BedrockConverse.protocol.body.schema)(
|
||||
(yield* compileRequest(request)).body,
|
||||
)
|
||||
const reserved = first.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => ("toolUse" in part ? [part.toolUse.toolUseId] : [])),
|
||||
)[0]
|
||||
if (!reserved) throw new Error("Expected projected tool call")
|
||||
const ids = [
|
||||
"a",
|
||||
"b",
|
||||
"tooluse_GQn7COr2AN8bw2oVKYyYzZ",
|
||||
"tooluse_abcdefghi111111111",
|
||||
"tooluse_abcdefghi222222222",
|
||||
"call_other-provider-id",
|
||||
"Ab12Cd34E",
|
||||
reserved,
|
||||
]
|
||||
const messages = history(ids)
|
||||
const before = structuredClone(messages)
|
||||
const input = LLM.request({ model: bedrock.model(model), messages, cache: "none" })
|
||||
const prepared = yield* compileRequest(input)
|
||||
const body = Schema.decodeUnknownSync(BedrockConverse.protocol.body.schema)(prepared.body)
|
||||
const calls = body.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => ("toolUse" in part ? [part.toolUse.toolUseId] : [])),
|
||||
)
|
||||
const results = body.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => ("toolResult" in part ? [part.toolResult.toolUseId] : [])),
|
||||
)
|
||||
expect(calls).toHaveLength(ids.length)
|
||||
expect(new Set(calls).size).toBe(ids.length)
|
||||
calls.forEach((id) => expect(id).toMatch(/^[A-Za-z0-9]{9}$/))
|
||||
expect(results).toEqual(calls.toReversed())
|
||||
expect(calls[0]).not.toBe(reserved)
|
||||
expect(calls.slice(-2)).toEqual(ids.slice(-2))
|
||||
expect((yield* compileRequest(input)).body).toEqual(prepared.body)
|
||||
expect(structuredClone(messages)).toEqual(before)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
it.effect("leaves non-Mistral Bedrock IDs unchanged", () =>
|
||||
Effect.gen(function* () {
|
||||
const ids = ["a", "tooluse_abcdefghi111111111", "tooluse_abcdefghi222222222", "Ab12Cd34E"]
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model: bedrock.model("global.anthropic.claude-haiku-4-5-20251001-v1:0"),
|
||||
messages: history(ids),
|
||||
cache: "none",
|
||||
}),
|
||||
)
|
||||
const body = Schema.decodeUnknownSync(BedrockConverse.protocol.body.schema)(prepared.body)
|
||||
expect(
|
||||
body.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => ("toolUse" in part ? [part.toolUse.toolUseId] : [])),
|
||||
),
|
||||
).toEqual(ids)
|
||||
expect(
|
||||
body.messages.flatMap((message) =>
|
||||
message.content.flatMap((part) => ("toolResult" in part ? [part.toolResult.toolUseId] : [])),
|
||||
),
|
||||
).toEqual(ids.toReversed())
|
||||
}),
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
import { expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { LLM, Message, ToolCallPart } from "../../src/index.js"
|
||||
import { OpenAIChat } from "../../src/protocols/openai-chat.js"
|
||||
import { OpenAIResponses } from "../../src/protocols/openai-responses.js"
|
||||
import { Auth } from "../../src/route/auth.js"
|
||||
import { compileRequest } from "../../src/route/client.js"
|
||||
import { it } from "../lib/effect.js"
|
||||
|
||||
const tool = { name: "lookup", description: "Look up a value", inputSchema: { type: "object", properties: {} } }
|
||||
|
||||
for (const route of [OpenAIChat.route, OpenAIResponses.route]) {
|
||||
const model = route
|
||||
.with({ endpoint: { baseURL: "https://api.openai.test/v1" }, auth: Auth.bearer("test") })
|
||||
.model({ id: "gpt-4.1-mini" })
|
||||
|
||||
for (const choice of [
|
||||
{ type: "auto" },
|
||||
{ type: "none" },
|
||||
{ type: "required" },
|
||||
{ type: "tool", name: "lookup" },
|
||||
] as const) {
|
||||
it.effect(`${route.id} omits ${choice.type} tool choice without active tools`, () =>
|
||||
Effect.gen(function* () {
|
||||
for (const messages of [
|
||||
[Message.user("Say OK.")],
|
||||
[
|
||||
Message.user("Look up the value."),
|
||||
Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
|
||||
Message.tool({ id: "call_1", name: "lookup", result: "OK", resultType: "text" }),
|
||||
],
|
||||
]) {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({ model, messages, tools: [], toolChoice: choice, cache: "none" }),
|
||||
)
|
||||
expect(prepared.body.tool_choice).toBeUndefined()
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect(`${route.id} preserves ${choice.type} tool choice with active tools`, () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({ model, prompt: "Look up the value.", tools: [tool], toolChoice: choice }),
|
||||
)
|
||||
expect(prepared.body.tool_choice).toEqual(
|
||||
choice.type !== "tool"
|
||||
? choice.type
|
||||
: route.id === "openai-chat"
|
||||
? { type: "function", function: { name: "lookup" } }
|
||||
: { type: "function", name: "lookup" },
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
it.effect("OpenAI Responses omits allowed tool choice without tool definitions", () =>
|
||||
Effect.gen(function* () {
|
||||
const model = OpenAIResponses.route
|
||||
.with({ endpoint: { baseURL: "https://api.openai.test/v1" }, auth: Auth.bearer("test") })
|
||||
.model({ id: "gpt-4.1-mini" })
|
||||
for (const tools of [[], [tool]]) {
|
||||
const prepared = yield* compileRequest(
|
||||
LLM.request({
|
||||
model,
|
||||
prompt: "Look up the value.",
|
||||
tools,
|
||||
toolChoice: "required",
|
||||
providerOptions: { allowedTools: { mode: "required", toolNames: ["lookup"] } },
|
||||
}),
|
||||
)
|
||||
expect(prepared.body.tool_choice).toEqual(
|
||||
tools.length === 0
|
||||
? undefined
|
||||
: { type: "allowed_tools", mode: "required", tools: [{ type: "function", name: "lookup" }] },
|
||||
)
|
||||
}
|
||||
}),
|
||||
)
|
||||
@@ -120,16 +120,16 @@ describe("LLMClient tools", () => {
|
||||
|
||||
const second = bodies[1]
|
||||
if (!second || typeof second !== "object") throw new Error("Expected second request body")
|
||||
const messages = Reflect.get(second, "messages")
|
||||
const tools = Reflect.get(second, "tools")
|
||||
const messages = "messages" in second ? second.messages : undefined
|
||||
const tools = "tools" in second ? second.tools : undefined
|
||||
|
||||
expect(Reflect.get(second, "max_completion_tokens")).toBe(50)
|
||||
expect(Reflect.get(second, "tool_choice")).toBe("auto")
|
||||
expect("max_completion_tokens" in second ? second.max_completion_tokens : undefined).toBe(50)
|
||||
expect("tool_choice" in second ? second.tool_choice : undefined).toBe("auto")
|
||||
expect(tools).toHaveLength(1)
|
||||
expect(
|
||||
Array.isArray(messages)
|
||||
? messages.map((message) =>
|
||||
message && typeof message === "object" ? Reflect.get(message, "role") : undefined,
|
||||
message && typeof message === "object" && "role" in message ? message.role : undefined,
|
||||
)
|
||||
: undefined,
|
||||
).toEqual(["user", "assistant", "tool"])
|
||||
@@ -398,7 +398,9 @@ describe("LLMClient tools", () => {
|
||||
required: ["temperature", "condition"],
|
||||
additionalProperties: false,
|
||||
})
|
||||
expect(Reflect.get(Reflect.get(typed?.outputSchema ?? {}, "properties") as object, "temperature")).toBeDefined()
|
||||
const properties =
|
||||
typed?.outputSchema && "properties" in typed.outputSchema ? typed.outputSchema.properties : undefined
|
||||
expect(properties && "temperature" in properties ? properties.temperature : undefined).toBeDefined()
|
||||
expect(dynamic?.outputSchema).toEqual(schema)
|
||||
})
|
||||
|
||||
|
||||
@@ -63,20 +63,20 @@ for (const size of ["typical", "large"]) {
|
||||
const source = page.locator(`[data-timeline-part-id="${sourcePart}"] [data-component="markdown"]`)
|
||||
await expect(source).toHaveAttribute("data-markdown-ready", "")
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${stressSessionHref(fixture.targetID)}"]`).click()
|
||||
await page.waitForFunction(() => Reflect.get(window, "markdownGate").held)
|
||||
await page.waitForFunction(() => window.markdownGate.held)
|
||||
await expect(page.locator(`[data-timeline-part-id="${targetPart}"]`)).toBeAttached()
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
const before = await cdp.send("Performance.getMetrics")
|
||||
await page.evaluate(() => Reflect.get(window, "markdownGate").arm())
|
||||
await page.evaluate(() => window.markdownGate.arm())
|
||||
await page.locator(`[data-slot="titlebar-tabs"] a[href="${stressSessionHref(fixture.sourceID)}"]`).click()
|
||||
await expect(source).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(source.getByRole("heading", { name: "Current destination" })).toBeVisible()
|
||||
await expect(page.locator(`[data-timeline-part-id="${targetPart}"]`)).toHaveCount(0)
|
||||
await page.waitForFunction(() => Reflect.get(window, "markdownGate").settled > 0)
|
||||
await page.waitForFunction(() => window.markdownGate.settled > 0)
|
||||
const after = await cdp.send("Performance.getMetrics")
|
||||
const stats = await page.evaluate(() => {
|
||||
const value = Reflect.get(window, "markdownGate")
|
||||
const value = window.markdownGate
|
||||
return {
|
||||
admitted: value.admitted,
|
||||
responses: value.responses,
|
||||
|
||||
@@ -4,6 +4,23 @@ import type {
|
||||
MarkdownWorkerResponse,
|
||||
} from "../../../../session-ui/src/components/markdown-worker-protocol"
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
markdownGate: {
|
||||
admitted: number
|
||||
responses: number
|
||||
held: boolean
|
||||
started: number
|
||||
ready: number
|
||||
released: number
|
||||
settled: number
|
||||
sanitizeCalls: number
|
||||
sanitizeChars: number
|
||||
arm: () => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function installMarkdownGate(
|
||||
page: Page,
|
||||
input: { answer: string; sourcePart: string; targetPart: string; href: string },
|
||||
|
||||
@@ -51,7 +51,7 @@ Terminal.prototype.open = function (element) {
|
||||
context.drawImage = function (...args: unknown[]) {
|
||||
probe.draws++
|
||||
if (hidden) probe.hiddenDraws++
|
||||
Reflect.apply(draw, this, args)
|
||||
draw.apply(this, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ for (const scenario of ["visible-output", "hidden-output", "full-scrollback-tear
|
||||
window.terminalProbe.draws++
|
||||
if (!this.canvas.checkVisibility()) window.terminalProbe.hiddenDraws++
|
||||
}
|
||||
Reflect.apply(fill, this, args)
|
||||
fill.apply(this, args)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ export async function installTimelineStreamProbe(
|
||||
}
|
||||
if (state.scroll.lastCallFrame === state.scroll.frame) state.scroll.sameFrameCalls += 1
|
||||
state.scroll.lastCallFrame = state.scroll.frame
|
||||
Reflect.apply(scrollTo, this, typeof first === "number" ? [first, second] : [first])
|
||||
scrollTo.apply(this, typeof first === "number" ? [first, second] : [first])
|
||||
}
|
||||
Element.prototype.scrollTo = measuredScrollTo
|
||||
Object.defineProperty(Element.prototype, "scrollTop", {
|
||||
|
||||
@@ -13,8 +13,8 @@ test("loads home and the directory picker without newer browser APIs", async ({
|
||||
})
|
||||
await page.addInitScript((directory) => {
|
||||
// Safari 16.6 has neither API. Remove them before the web entry runs.
|
||||
Reflect.deleteProperty(Map, "groupBy")
|
||||
Reflect.deleteProperty(Promise, "withResolvers")
|
||||
delete (Map as Partial<typeof Map>).groupBy
|
||||
delete (Promise as Partial<typeof Promise>).withResolvers
|
||||
localStorage.setItem(
|
||||
"opencode.global.dat:server",
|
||||
JSON.stringify({
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
import { expect, test, type Page } from "@playwright/test"
|
||||
import { base64Encode } from "@opencode/util/encode"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
|
||||
const directory = "/repo/slash-skills"
|
||||
const projectID = "proj_slash_skills"
|
||||
const sessionID = "ses_slash_skills"
|
||||
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
|
||||
|
||||
async function setup(page: Page, queued = false) {
|
||||
const prompts: Record<string, unknown>[] = []
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
id: projectID,
|
||||
worktree: directory,
|
||||
vcs: "git",
|
||||
name: "slash-skills",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
sandboxes: [],
|
||||
},
|
||||
provider: {
|
||||
all: [
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode",
|
||||
models: { test: { id: "test", name: "Test", limit: { context: 200_000 } } },
|
||||
},
|
||||
],
|
||||
connected: ["opencode"],
|
||||
default: { providerID: "opencode", modelID: "test" },
|
||||
},
|
||||
sessions: [
|
||||
{
|
||||
id: sessionID,
|
||||
projectID,
|
||||
directory,
|
||||
title: "Slash skills",
|
||||
version: "dev",
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
sessionStatus: queued ? { [sessionID]: { type: "running" } } : {},
|
||||
inbox: queued
|
||||
? [
|
||||
{
|
||||
id: "inb_slash_skill",
|
||||
sessionID,
|
||||
timeCreated: 1700000000000,
|
||||
type: "user",
|
||||
payload: { text: "Explain caching" },
|
||||
delivery: "queue",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
findFiles: ({ query }) =>
|
||||
query.includes("cache")
|
||||
? [
|
||||
{
|
||||
name: "cache.ts",
|
||||
path: "src/cache.ts",
|
||||
absolute: `${directory}/src/cache.ts`,
|
||||
type: "file",
|
||||
ignored: false,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
onPrompt: ({ body }) => prompts.push(body),
|
||||
})
|
||||
await page.route("**/api/skill?*", (route) =>
|
||||
route.fulfill({
|
||||
json: {
|
||||
location: { directory, project: { id: projectID, directory, canonical: directory } },
|
||||
data: [
|
||||
{ id: "show-me", slash: true, autoinvoke: false },
|
||||
{ id: "hidden", slash: false },
|
||||
{ id: "implicit" },
|
||||
{ id: "review", slash: true },
|
||||
{ id: "model", slash: true },
|
||||
].map((skill) => ({
|
||||
name: skill.id === "show-me" ? "Show Me" : skill.id,
|
||||
description: "Explain the current topic visually",
|
||||
location: `/skills/${skill.id}/SKILL.md`,
|
||||
content: "Explain visually",
|
||||
...skill,
|
||||
})),
|
||||
},
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
}),
|
||||
)
|
||||
await page.route("**/api/command?*", (route) =>
|
||||
route.fulfill({
|
||||
json: {
|
||||
location: { directory, project: { id: projectID, directory, canonical: directory } },
|
||||
data: [{ name: "review", description: "Review changes" }],
|
||||
},
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
}),
|
||||
)
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionID}`)
|
||||
const composer = page.locator('[data-component="composer"]')
|
||||
const editor = composer.locator('[data-component="composer-editor"]')
|
||||
await expect(editor).toBeEditable()
|
||||
return { prompts, composer, editor }
|
||||
}
|
||||
|
||||
for (const selection of ["keyboard", "pointer"]) {
|
||||
test(`selects and submits a manual-only slash skill with ${selection}`, async ({ page }) => {
|
||||
const { prompts, editor } = await setup(page)
|
||||
await editor.fill("/show")
|
||||
const skill = page.locator('[data-suggestion-id="skill:show-me"]')
|
||||
await expect(skill).toContainText("/show-me")
|
||||
await page.screenshot({ path: test.info().outputPath("slash-menu.png") })
|
||||
if (selection === "keyboard") await editor.press("Enter")
|
||||
if (selection === "pointer") await skill.click()
|
||||
await expect(editor).toHaveText("/show-me ")
|
||||
await expect(editor).toBeFocused()
|
||||
await editor.pressSequentially("explain caching")
|
||||
await editor.press("Enter")
|
||||
await expect.poll(() => prompts.length).toBe(1)
|
||||
expect(prompts[0]).toMatchObject({
|
||||
text: "/show-me explain caching",
|
||||
skills: [{ id: "show-me", mention: { start: 0, end: 8, text: "/show-me" } }],
|
||||
})
|
||||
await expect(editor).toBeEmpty()
|
||||
})
|
||||
}
|
||||
|
||||
test("respects slash flags and command precedence without hiding context skills", async ({ page }) => {
|
||||
const { editor } = await setup(page)
|
||||
await editor.fill("/")
|
||||
await expect(page.locator('[data-suggestion-id="skill:show-me"]')).toBeVisible()
|
||||
await expect(page.locator('[data-suggestion-id="custom.review"]')).toBeVisible()
|
||||
await expect(page.locator('[data-suggestion-id="model.choose"]')).toBeVisible()
|
||||
for (const id of ["hidden", "implicit", "review", "model"]) {
|
||||
await expect(page.locator(`[data-suggestion-id="skill:${id}"]`)).toHaveCount(0)
|
||||
}
|
||||
await editor.press("Escape")
|
||||
await expect(page.locator('[data-suggestion-id="skill:show-me"]')).toHaveCount(0)
|
||||
await expect(editor).toBeFocused()
|
||||
await editor.fill("@hidden")
|
||||
const hidden = page.locator('[data-suggestion-id="skill:hidden"]')
|
||||
await expect(hidden).toContainText("@hidden")
|
||||
await hidden.click()
|
||||
await expect(editor).toHaveText("@hidden ")
|
||||
await expect(editor).toBeFocused()
|
||||
})
|
||||
|
||||
test("preserves structured attachments when adding a slash skill from the command menu", async ({ page }) => {
|
||||
const { prompts, composer, editor } = await setup(page)
|
||||
await editor.fill("explain @cache")
|
||||
const file = page.locator('[data-suggestion-id="file:src/cache.ts"]')
|
||||
await expect(file).toBeVisible()
|
||||
await file.click()
|
||||
await expect(editor).toHaveText("explain @src/cache.ts ")
|
||||
await composer.getByRole("button", { name: "Add images and files" }).click()
|
||||
await page.getByRole("menuitem", { name: "Commands" }).click()
|
||||
const skill = page.locator('[data-suggestion-id="skill:show-me"]')
|
||||
await expect(skill).toBeVisible()
|
||||
await skill.click()
|
||||
await expect(editor).toHaveText("/show-me explain @src/cache.ts ")
|
||||
await expect(editor).toBeFocused()
|
||||
await editor.press("Enter")
|
||||
await expect.poll(() => prompts.length).toBe(1)
|
||||
expect(prompts[0]).toMatchObject({
|
||||
skills: [{ id: "show-me", mention: { start: 0, end: 8, text: "/show-me" } }],
|
||||
files: [{ name: "cache.ts", mention: { start: 17, end: 30, text: "@src/cache.ts" } }],
|
||||
})
|
||||
})
|
||||
|
||||
for (const select of [true, false]) {
|
||||
test(`keeps slash skills in queued edits (${select ? "selected" : "typed"})`, async ({ page }) => {
|
||||
const { prompts, editor } = await setup(page, true)
|
||||
const row = page.locator('[data-component="session-queue-row"]')
|
||||
await row.getByText("Explain caching", { exact: true }).click()
|
||||
await expect(editor).toHaveText("Explain caching")
|
||||
if (select) {
|
||||
await editor.fill("/show")
|
||||
const skill = page.locator('[data-suggestion-id="skill:show-me"]')
|
||||
await expect(skill).toBeVisible()
|
||||
await skill.click()
|
||||
await expect(editor).toHaveText("/show-me ")
|
||||
await editor.pressSequentially("explain caching")
|
||||
}
|
||||
if (!select) await editor.fill("/show-me explain caching")
|
||||
await editor.press("Enter")
|
||||
await expect.poll(() => prompts.length).toBe(1)
|
||||
expect(prompts[0]).toMatchObject({
|
||||
delivery: "queue",
|
||||
text: "/show-me explain caching",
|
||||
skills: [{ id: "show-me", mention: { start: 0, end: 8, text: "/show-me" } }],
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -62,7 +62,7 @@ async function mockServers(page: Page, requests: string[]) {
|
||||
const current = url.origin === serverA ? sessionA : sessionB
|
||||
const directory = url.searchParams.get("directory")
|
||||
if (directory && directory !== current.directory) return json(route, { name: "InvalidDirectory" }, 500)
|
||||
if (url.pathname === "/api/health") return json(route, { pid: 1 })
|
||||
if (url.pathname === "/api/status") return json(route, { version: "test", pid: 1, urls: [url.origin] })
|
||||
if (url.pathname === "/api/session") return json(route, { data: [currentSession(current)], cursor: {} })
|
||||
if (url.pathname === "/api/session/active") return json(route, { data: {} })
|
||||
if (url.pathname === `/api/session/${current.id}`) return json(route, { data: currentSession(current) })
|
||||
@@ -76,7 +76,7 @@ async function mockServers(page: Page, requests: string[]) {
|
||||
if (url.pathname === "/api/mcp") return json(route, { location: { directory: current.directory }, data: [] })
|
||||
if (url.pathname === "/api/mcp/resource")
|
||||
return json(route, { location: { directory: current.directory }, data: { resources: [], templates: [] } })
|
||||
if (url.pathname === "/api/project" || url.pathname === "/api/project/current") {
|
||||
if (url.pathname === "/api/project") {
|
||||
const project = {
|
||||
id: current.projectID,
|
||||
canonical: current.directory,
|
||||
@@ -84,7 +84,7 @@ async function mockServers(page: Page, requests: string[]) {
|
||||
time: { created: 1, updated: 1 },
|
||||
sandboxes: [],
|
||||
}
|
||||
return json(route, url.pathname === "/api/project" ? [project] : { id: project.id, directory: current.directory })
|
||||
return json(route, [project])
|
||||
}
|
||||
if (url.pathname === "/api/location")
|
||||
return json(route, {
|
||||
|
||||
@@ -404,7 +404,7 @@ async function openDraft(page: Page, worktree = "main", options: { git?: boolean
|
||||
{
|
||||
id: "summary-skill",
|
||||
name: "summary-skill",
|
||||
location: "/skills/summary/SKILL.md",
|
||||
path: "/skills/summary/SKILL.md",
|
||||
content: "Summary skill",
|
||||
},
|
||||
],
|
||||
|
||||
@@ -20,7 +20,6 @@ test("session settings use the remote server context", async ({ page }) => {
|
||||
// one toggle sweeps every connected server, not just the focused one.
|
||||
await mockServers(page, permissionRequests, permissionResponses, {
|
||||
pending: { [serverA]: [pendingPermission("permission-pending-a", sessionA.id)] },
|
||||
preferencesUnavailable: true,
|
||||
})
|
||||
await configureServers(page)
|
||||
|
||||
@@ -326,7 +325,6 @@ type MockServerOptions = {
|
||||
listFailures?: Record<string, number>
|
||||
// Records /api/session/:id GETs so tests can assert session resyncs.
|
||||
sessionGets?: string[]
|
||||
preferencesUnavailable?: boolean
|
||||
}
|
||||
|
||||
async function mockServers(
|
||||
@@ -398,8 +396,6 @@ async function mockServers(
|
||||
},
|
||||
])
|
||||
}
|
||||
if (url.pathname === "/api/project/current")
|
||||
return json(route, { id: remote ? sessionB.projectID : "project-server-a", directory, canonical: directory })
|
||||
if (url.pathname === "/api/session")
|
||||
return json(route, { data: sessions.map((session) => currentSession(session)), cursor: {} })
|
||||
if (url.pathname === "/api/session/active")
|
||||
@@ -418,11 +414,8 @@ async function mockServers(
|
||||
directory,
|
||||
project: { id: remote ? sessionB.projectID : "project-server-a", directory, canonical: directory },
|
||||
})
|
||||
if (url.pathname === "/api/config/preferences") return json(route, {}, options.preferencesUnavailable ? 404 : 200)
|
||||
if (url.pathname === "/api/config/shell")
|
||||
return json(route, options.preferencesUnavailable ? {} : [], options.preferencesUnavailable ? 404 : 200)
|
||||
if (url.pathname === "/api/websearch/provider")
|
||||
return json(route, { location: { directory }, data: [] }, options.preferencesUnavailable ? 404 : 200)
|
||||
if (url.pathname === "/api/config/shell") return json(route, [])
|
||||
if (url.pathname === "/api/websearch/provider") return json(route, { location: { directory }, data: [] })
|
||||
if (url.pathname === "/api/worktree") return json(route, [{ directory }])
|
||||
if (url.pathname === "/api/vcs")
|
||||
return json(route, { location: { directory }, data: { branch: "main", defaultBranch: "main" } })
|
||||
|
||||
@@ -16,8 +16,8 @@ test("server dialog keeps focus above fullscreen settings", async ({ page }) =>
|
||||
body: 'data: {"id":"evt_connected","type":"server.connected","data":{}}\n\n',
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/api/global/health" || url.pathname === "/api/health") {
|
||||
return json(route, { healthy: true, version: "2.0.0" })
|
||||
if (url.pathname === "/api/status") {
|
||||
return json(route, { version: "2.0.0", pid: 1, urls: [url.origin] })
|
||||
}
|
||||
return json(route, {})
|
||||
})
|
||||
|
||||
@@ -137,7 +137,9 @@ test("MCP authentication starts before a slow resource catalog finishes", async
|
||||
|
||||
test("multiple desktop connections show the session's server name", async ({ page }) => {
|
||||
await mockStressTimeline(page)
|
||||
await page.route("http://secondary.test/**", (route) => route.fulfill({ json: { healthy: true, version: "2.0.0" } }))
|
||||
await page.route("http://secondary.test/**", (route) =>
|
||||
route.fulfill({ json: { version: "2.0.0", pid: 1, urls: ["http://secondary.test"] } }),
|
||||
)
|
||||
await page.addInitScript(
|
||||
({ directory, server }) => {
|
||||
const current = { type: "http", http: { url: server }, displayName: "Design server" }
|
||||
|
||||
@@ -42,7 +42,7 @@ for (const service of services) {
|
||||
state: { status: "active" },
|
||||
},
|
||||
]
|
||||
: [{ id: service.item, name: service.item, location: "/skills/summary/SKILL.md", content: "Summary" }]
|
||||
: [{ id: service.item, name: service.item, path: "/skills/summary/SKILL.md", content: "Summary" }]
|
||||
return route.fulfill({ json: { location: { directory: fixture.directory }, data: empty ? [] : items } })
|
||||
},
|
||||
)
|
||||
|
||||
@@ -235,11 +235,11 @@ test("catalog submenus show project plugins and skills, refresh on reopen, and d
|
||||
json: {
|
||||
location: { directory: fixture.directory },
|
||||
data: [
|
||||
{ id: "find-skills", name: "find-skills", location: "/skills/find/SKILL.md", content: "Find skills" },
|
||||
{ id: "find-skills", name: "find-skills", path: "/skills/find/SKILL.md", content: "Find skills" },
|
||||
{
|
||||
id: "review-animations",
|
||||
name: "review-animations",
|
||||
location: "/skills/review/SKILL.md",
|
||||
path: "/skills/review/SKILL.md",
|
||||
content: "Review animations",
|
||||
},
|
||||
],
|
||||
|
||||
@@ -109,11 +109,11 @@ test("passes through non-event fetches", async ({ page }) => {
|
||||
const timeline = await setupTimeline(page)
|
||||
|
||||
const health = await page.evaluate(async () => {
|
||||
const response = await fetch("/api/health")
|
||||
const response = await fetch("/api/status")
|
||||
return response.json()
|
||||
})
|
||||
|
||||
expect(health).toEqual({ healthy: true, version: "2.0.0", pid: 1 })
|
||||
expect(health).toEqual({ version: "2.0.0", pid: 1, urls: ["http://localhost"] })
|
||||
await expect.poll(async () => (await timeline.transport.connections()).length).toBe(1)
|
||||
})
|
||||
|
||||
|
||||
@@ -24,9 +24,14 @@ test.beforeEach(async ({ page }) => {
|
||||
sandboxes,
|
||||
},
|
||||
provider: { all: [], connected: [], default: {} },
|
||||
preferences: { shell: "zsh", websearch: { provider: "exa" } },
|
||||
shells: [{ path: "/bin/zsh", name: "zsh", acceptable: true }],
|
||||
websearchProviders: [{ id: "exa", name: "Exa" }],
|
||||
configEntries: [
|
||||
{ type: "document", path: "/home/test/.config/opencode/opencode.jsonc", info: { shell: "/bin/zsh" } },
|
||||
{ type: "directory", path: "/home/test/.config/opencode" },
|
||||
],
|
||||
shells: [
|
||||
{ path: "/bin/zsh", name: "zsh", acceptable: true },
|
||||
{ path: "/bin/bash", name: "bash", acceptable: true },
|
||||
],
|
||||
sessions: sandboxes.map((directory, index) => ({
|
||||
id: `ses_settings_${index + 1}`,
|
||||
title: `Workspace ${index + 1} session`,
|
||||
@@ -78,38 +83,20 @@ test("single-server settings expose scoped pages without a server picker", async
|
||||
await settings.getByRole("tab", { name: "Server", exact: true }).click()
|
||||
await expect(settings.getByRole("button", { name: "Add server", exact: true })).toBeVisible()
|
||||
await expect(settings.getByRole("heading", { name: "Connection", exact: true })).toBeVisible()
|
||||
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeVisible()
|
||||
await expect(settings.getByText("Terminal shell", { exact: true })).toBeVisible()
|
||||
await expect(settings.getByText("Third-party search", { exact: true })).toBeVisible()
|
||||
await expect(settings.getByText("zsh", { exact: true })).toBeVisible()
|
||||
await expect(settings.getByText("Exa", { exact: true })).toBeVisible()
|
||||
|
||||
await settings.getByText("Exa", { exact: true }).click()
|
||||
const updated = page.waitForRequest(
|
||||
(request) => request.method() === "PATCH" && new URL(request.url()).pathname === "/api/config/preferences",
|
||||
)
|
||||
await page.getByRole("option", { name: "Any", exact: true }).click()
|
||||
expect((await updated).postDataJSON()).toEqual({ websearch: { provider: "random" } })
|
||||
})
|
||||
|
||||
test("server details tolerate unavailable preference endpoints", async ({ page }) => {
|
||||
await page.route(
|
||||
(url) =>
|
||||
url.pathname === "/api/config/preferences" ||
|
||||
url.pathname === "/api/config/shell" ||
|
||||
url.pathname === "/api/websearch/provider",
|
||||
(route) => route.fulfill({ status: 404, json: {} }),
|
||||
)
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
await settings.getByRole("tab", { name: "Server", exact: true }).click()
|
||||
|
||||
const connection = settings.locator('[data-component="settings-server-connection"]')
|
||||
await expect(connection.getByRole("heading", { name: "Connection", exact: true })).toBeVisible()
|
||||
await expect(connection.locator('[data-component="settings-list"]')).toHaveCSS("padding-left", "16px")
|
||||
await expect(connection.locator(".settings-servers-row")).toHaveCSS("padding-top", "20px")
|
||||
await expect(connection.locator(".settings-servers-lead")).toHaveCSS("column-gap", "4px")
|
||||
await expect(connection.locator(".settings-servers-copy")).toHaveCSS("row-gap", "6px")
|
||||
await expect(page.getByText("Server request failed", { exact: true })).toHaveCount(0)
|
||||
await expect(settings.getByRole("heading", { name: "Preferences", exact: true })).toBeVisible()
|
||||
await expect(settings.getByText("Terminal shell", { exact: true })).toBeVisible()
|
||||
await settings.getByText("zsh", { exact: true }).click()
|
||||
const updated = page.waitForRequest(
|
||||
(request) => request.method() === "PATCH" && new URL(request.url()).pathname === "/api/experimental/config",
|
||||
)
|
||||
await page.getByRole("option", { name: "bash", exact: true }).click()
|
||||
expect((await updated).postDataJSON()).toEqual({ shell: "/bin/bash" })
|
||||
})
|
||||
|
||||
test("project settings open as a nested autosaving view", async ({ page }) => {
|
||||
|
||||
@@ -592,7 +592,7 @@ async function mockServer(page: Page) {
|
||||
if (url.pathname === "/api/mcp") return json(route, { location: { directory: sessionA.directory }, data: [] })
|
||||
if (url.pathname === "/api/mcp/resource")
|
||||
return json(route, { location: { directory: sessionA.directory }, data: { resources: [], templates: [] } })
|
||||
if (url.pathname === "/api/project" || url.pathname === "/api/project/current") {
|
||||
if (url.pathname === "/api/project") {
|
||||
const project = {
|
||||
id: sessionA.projectID,
|
||||
canonical: sessionA.directory,
|
||||
@@ -600,10 +600,7 @@ async function mockServer(page: Page) {
|
||||
time: { created: 1, updated: 1 },
|
||||
sandboxes: [],
|
||||
}
|
||||
return json(
|
||||
route,
|
||||
url.pathname === "/api/project" ? [project] : { id: project.id, directory: sessionA.directory },
|
||||
)
|
||||
return json(route, [project])
|
||||
}
|
||||
if (url.pathname === "/api/location")
|
||||
return json(route, {
|
||||
|
||||
@@ -75,13 +75,16 @@ const fixture = test.extend<{ site: Site }, { builds: Record<string, Record<stri
|
||||
const blocked: ServerResponse[] = []
|
||||
const release = () => blocked.splice(0).forEach((response) => response.end(builds.new["/large.bin"]))
|
||||
const server = createServer((request, response) => {
|
||||
const path = new URL(request.url ?? "/", "http://localhost").pathname
|
||||
const url = new URL(request.url ?? "/", "http://localhost")
|
||||
const path = url.pathname
|
||||
requests.push(path)
|
||||
response.setHeader("cache-control", "no-store")
|
||||
if (path === "/observer.html")
|
||||
return void response.writeHead(200, { "content-type": "text/html" }).end("<title>Worker observer</title>")
|
||||
if (path === "/api/health")
|
||||
return void response.writeHead(200, { "content-type": "application/json" }).end('{"healthy":true}')
|
||||
if (path === "/api/status")
|
||||
return void response
|
||||
.writeHead(200, { "content-type": "application/json" })
|
||||
.end(`{"version":"test","pid":1,"urls":["${url.origin}"]}`)
|
||||
if (path === "/sw.js" && state.legacy && state.version === "old") {
|
||||
// Model the shipped worker's shared precache name and cache-first navigation behavior.
|
||||
const urls = Object.keys(builds.old).filter(
|
||||
@@ -331,8 +334,8 @@ fixture("upgrades the legacy shared precache only after old tabs close", async (
|
||||
|
||||
fixture("does not substitute cached HTML for API or missing asset navigations", async ({ page, site }) => {
|
||||
await install(page, site.url)
|
||||
const api = await page.goto(`${site.url}/api/health`)
|
||||
expect(await api?.json()).toEqual({ healthy: true })
|
||||
const api = await page.goto(`${site.url}/api/status`)
|
||||
expect(await api?.json()).toEqual({ version: "test", pid: 1, urls: [site.url] })
|
||||
expect(api?.fromServiceWorker()).toBe(false)
|
||||
const asset = await page.goto(`${site.url}/_assets/missing.js`)
|
||||
expect(asset?.status()).toBe(404)
|
||||
|
||||
@@ -32,7 +32,7 @@ export class MockBadRequest extends Schema.TaggedError<MockBadRequest>()("MockBa
|
||||
}) {}
|
||||
|
||||
const Group = HttpApiGroup.make("mock")
|
||||
.add(HttpApiEndpoint.get("health", "/api/health", { success: Json }))
|
||||
.add(HttpApiEndpoint.get("status", "/api/status", { success: Json }))
|
||||
.add(
|
||||
HttpApiEndpoint.get("event", "/api/event", {
|
||||
success: Schema.String.pipe(HttpApiSchema.asText({ contentType: "text/event-stream" })),
|
||||
@@ -77,15 +77,13 @@ const Group = HttpApiGroup.make("mock")
|
||||
success: Json,
|
||||
}),
|
||||
)
|
||||
.add(HttpApiEndpoint.get("projectCurrent", "/api/project/current", { success: Json }))
|
||||
.add(HttpApiEndpoint.get("configPreferences", "/api/config/preferences", { success: Json }))
|
||||
.add(HttpApiEndpoint.get("configShells", "/api/config/shell", { success: Json }))
|
||||
.add(
|
||||
HttpApiEndpoint.patch("configUpdatePreferences", "/api/config/preferences", {
|
||||
payload: JsonPayload,
|
||||
success: Json,
|
||||
HttpApiEndpoint.patch("configUpdate", "/api/experimental/config", {
|
||||
payload: Schema.Struct({ shell: Schema.NullOr(Schema.String) }),
|
||||
success: HttpApiSchema.NoContent,
|
||||
}),
|
||||
)
|
||||
.add(HttpApiEndpoint.get("configShells", "/api/config/shell", { success: Json }))
|
||||
.add(HttpApiEndpoint.get("websearchProviders", "/api/websearch/provider", { success: Json }))
|
||||
.add(
|
||||
HttpApiEndpoint.get("worktreeList", "/api/worktree", {
|
||||
|
||||
@@ -10,8 +10,8 @@ export interface MockServerConfig {
|
||||
provider: unknown | (() => unknown)
|
||||
integrationMethods?: Record<string, unknown[]>
|
||||
onConnectKey?: (input: { integrationID: string; body: unknown }) => void
|
||||
preferences?: Record<string, unknown>
|
||||
shells?: unknown[]
|
||||
configEntries?: unknown[]
|
||||
websearchProviders?: unknown[]
|
||||
directory: string
|
||||
project: unknown
|
||||
@@ -198,7 +198,7 @@ const corsHeaders = {
|
||||
function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, string>; nextCursor: number }) {
|
||||
const noContent = Effect.succeed(HttpApiSchema.NoContent.make())
|
||||
const delay = config.messageDelay === undefined ? Effect.void : Effect.sleep(Duration.millis(config.messageDelay))
|
||||
const preferences = { current: config.preferences ?? {} }
|
||||
const configEntries = config.configEntries ?? []
|
||||
return HttpApiBuilder.group(MockApi, "mock", (handlers) =>
|
||||
handlers
|
||||
.handleRaw("event", () => {
|
||||
@@ -219,8 +219,8 @@ function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, st
|
||||
}),
|
||||
)
|
||||
.handleAll({
|
||||
health: () => Effect.succeed({ healthy: true, version: "2.0.0", pid: 1 }),
|
||||
config: () => Effect.succeed([]),
|
||||
status: () => Effect.succeed({ version: "2.0.0", pid: 1, urls: config.server ? [config.server] : [] }),
|
||||
config: () => Effect.succeed(configEntries),
|
||||
reference: () =>
|
||||
Effect.succeed({
|
||||
location: {
|
||||
@@ -285,19 +285,8 @@ function mockHandlers(config: MockServerConfig, state: { cursors: Map<string, st
|
||||
canonical: project.canonical ?? config.directory,
|
||||
})
|
||||
},
|
||||
projectCurrent: () =>
|
||||
Effect.succeed({
|
||||
id: (config.project as { id?: string }).id,
|
||||
directory: config.directory,
|
||||
canonical: config.directory,
|
||||
}),
|
||||
configPreferences: () => Effect.succeed(preferences.current),
|
||||
configUpdatePreferences: (ctx) =>
|
||||
Effect.sync(() => {
|
||||
preferences.current = { ...preferences.current, ...ctx.payload }
|
||||
return preferences.current
|
||||
}),
|
||||
configShells: () => Effect.succeed(config.shells ?? []),
|
||||
configUpdate: () => noContent,
|
||||
websearchProviders: () => Effect.succeed({ location: location(config), data: config.websearchProviders ?? [] }),
|
||||
worktreeList: () =>
|
||||
Effect.succeed([
|
||||
@@ -658,11 +647,6 @@ export function currentSession(session: { id: string } & Record<string, unknown>
|
||||
: typeof session.directory === "string"
|
||||
? session.directory
|
||||
: fallbackDirectory,
|
||||
...(typeof session.workspaceID === "string"
|
||||
? { workspaceID: session.workspaceID }
|
||||
: "workspaceID" in location && typeof location.workspaceID === "string"
|
||||
? { workspaceID: location.workspaceID }
|
||||
: {}),
|
||||
},
|
||||
subpath: session.subpath ?? session.path,
|
||||
revert: session.revert,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/app",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -99,7 +99,7 @@ describe("Composer store", () => {
|
||||
expect(prompt.state.prompt).toEqual([{ type: "text", content: "old", start: 0, end: 3 }])
|
||||
})
|
||||
|
||||
test("prepends a slash skill to an attachment-only draft without flattening it", () => {
|
||||
test("prepends a skill mention to an attachment-only draft without flattening it", () => {
|
||||
const prompt = createPromptStore()
|
||||
prompt.setPrompt([{ type: "file", path: "one", content: "@one", start: 0, end: 4 }], 4)
|
||||
prompt.addMention(
|
||||
@@ -107,14 +107,14 @@ describe("Composer store", () => {
|
||||
type: "skill",
|
||||
id: Skill.ID.make("show-me"),
|
||||
name: Skill.Name.make("Show Me"),
|
||||
content: "/show-me",
|
||||
content: "@show-me",
|
||||
start: 0,
|
||||
end: 0,
|
||||
},
|
||||
{ start: 0, end: 0 },
|
||||
)
|
||||
expect(prompt.state.prompt).toMatchObject([
|
||||
{ type: "skill", id: "show-me", content: "/show-me", start: 0, end: 8 },
|
||||
{ type: "skill", id: "show-me", content: "@show-me", start: 0, end: 8 },
|
||||
{ type: "text", content: " ", start: 8, end: 9 },
|
||||
{ type: "file", path: "one", content: "@one", start: 9, end: 13 },
|
||||
])
|
||||
|
||||
@@ -21,7 +21,7 @@ import type { ImageAttachmentPart } from "./state"
|
||||
import type { PromptHistoryComment } from "./history/entry"
|
||||
import { createComposerHistory } from "./history/store"
|
||||
import { composerPlaceholder } from "./placeholder"
|
||||
import { createComposerSubmit, withSlashSkill } from "./submit"
|
||||
import { createComposerSubmit } from "./submit"
|
||||
|
||||
export type ComposerModel = ComposerEditorModel & {
|
||||
readonly model: ComposerControls["model"]
|
||||
@@ -243,9 +243,6 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
type: "builtin" as const,
|
||||
})),
|
||||
])
|
||||
const slashSkills = createMemo(() =>
|
||||
skills().filter((skill) => skill.slash === true && !slashCommands().some((item) => item.trigger === skill.id)),
|
||||
)
|
||||
const commands = createMemo<ComposerSuggestion[]>(() => [
|
||||
...slashCommands().map((item) => ({
|
||||
id: item.id,
|
||||
@@ -256,29 +253,12 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
description: item.description,
|
||||
keybind: command.keybindParts(item.id),
|
||||
})),
|
||||
...slashSkills().map((skill) => ({
|
||||
id: `skill:${skill.id}`,
|
||||
kind: "skill" as const,
|
||||
label: `/${skill.id}`,
|
||||
trigger: skill.id,
|
||||
title: skill.name,
|
||||
description: skill.description,
|
||||
mention: {
|
||||
type: "skill" as const,
|
||||
id: Skill.ID.make(skill.id),
|
||||
name: Skill.Name.make(skill.name),
|
||||
content: `/${skill.id}`,
|
||||
start: 0,
|
||||
end: 0,
|
||||
},
|
||||
})),
|
||||
])
|
||||
const variants = createMemo(() => ["default", ...adapter.controls().model.selection.variant.list()])
|
||||
const submission = createComposerSubmit({
|
||||
adapter,
|
||||
mode,
|
||||
commands: () => data.location.command.list({ directory: sdk().directory }),
|
||||
skills: slashSkills,
|
||||
editor: () => editor,
|
||||
queueScroll: () => requestAnimationFrame(() => editor?.scrollIntoView({ block: "nearest" })),
|
||||
addToHistory: (value, mode) => controller.addHistory(value, mode),
|
||||
@@ -407,7 +387,6 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
// the composer value as a new prompt. Enter keeps it queued in
|
||||
// place; the alternate action sends it as a steer.
|
||||
if (queue?.editing()) {
|
||||
prompt.set(withSlashSkill(prompt.current(), slashSkills()))
|
||||
queue.confirmEdit(submitOptions?.alternate ? "steer" : "queue")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { describe, expect, test } from "bun:test"
|
||||
import type { ModelSelection } from "@/providers/models/selection"
|
||||
import type { SessionMessageUser } from "@opencode/client/promise"
|
||||
import { Skill } from "@opencode/schema/skill"
|
||||
import { AbsolutePath } from "@opencode/schema/schema"
|
||||
import type { ActiveComposerAdapter, ComposerControls, ComposerSession, NewSessionComposerAdapter } from "./adapter"
|
||||
import { createMemoryComposerState } from "./state"
|
||||
import { createComposerSubmit } from "./submit"
|
||||
@@ -32,16 +31,6 @@ const selection = {
|
||||
},
|
||||
} satisfies ModelSelection
|
||||
|
||||
const slashSkill = Skill.Info.make({
|
||||
id: Skill.ID.make("show-me"),
|
||||
name: Skill.Name.make("Show Me"),
|
||||
description: "Explain visually",
|
||||
slash: true,
|
||||
autoinvoke: false,
|
||||
location: AbsolutePath.make("/skills/show-me/SKILL.md"),
|
||||
content: "Explain visually",
|
||||
})
|
||||
|
||||
function controls(): ComposerControls {
|
||||
return {
|
||||
agents: {
|
||||
@@ -64,13 +53,11 @@ function submitInput(
|
||||
notify = { missingSelection() {}, failed(_kind: "shell" | "command" | "prompt", _error: unknown) {} },
|
||||
mode: "normal" | "shell" = "normal",
|
||||
commands: () => readonly { name: string }[] | undefined = () => [],
|
||||
skills: () => readonly Skill.Info[] | undefined = () => [],
|
||||
) {
|
||||
return createComposerSubmit({
|
||||
adapter,
|
||||
mode: () => mode,
|
||||
commands,
|
||||
skills,
|
||||
editor: () => undefined,
|
||||
queueScroll() {},
|
||||
addToHistory() {},
|
||||
@@ -268,107 +255,6 @@ describe("Composer submission", () => {
|
||||
expect(state.current()[0]).toMatchObject({ content: "/review changes" })
|
||||
})
|
||||
|
||||
test("submits a slash skill with its trailing text and attachments", async () => {
|
||||
const state = createMemoryComposerState({ prompt: "/show-me explain " }).capture()
|
||||
state.set([
|
||||
{ type: "text", content: "/show-me explain ", start: 0, end: 17 },
|
||||
{ type: "file", path: "src/cache.ts", content: "@src/cache.ts", start: 17, end: 30 },
|
||||
])
|
||||
const admitted = Promise.withResolvers<Parameters<ComposerSession["data"]["session"]["prompt"]>[0]>()
|
||||
const target = session({ calls: [], prompt: async (value) => admitted.resolve(value) })
|
||||
const adapter: ActiveComposerAdapter = {
|
||||
kind: "active-session",
|
||||
state,
|
||||
ready: () => true,
|
||||
controls,
|
||||
working: () => false,
|
||||
session: () => target,
|
||||
interrupt: async () => undefined,
|
||||
submitted() {},
|
||||
setEditor() {},
|
||||
}
|
||||
|
||||
await submitInput(
|
||||
adapter,
|
||||
undefined,
|
||||
"normal",
|
||||
() => [],
|
||||
() => [slashSkill],
|
||||
).submit(new Event("submit"))
|
||||
const request = await admitted.promise
|
||||
expect(request.text).toBe("/show-me explain @src/cache.ts")
|
||||
expect(request.skills).toEqual([
|
||||
expect.objectContaining({ id: "show-me", mention: { start: 0, end: 8, text: "/show-me" } }),
|
||||
])
|
||||
expect(request.files).toEqual([
|
||||
{ uri: "file:///C:/repo/src/cache.ts", name: "cache.ts", mention: { start: 17, end: 30, text: "@src/cache.ts" } },
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ text: "/show-me", slash: true, expected: ["show-me"] },
|
||||
{ text: "/show-me\nexplain caching", slash: true, expected: ["show-me"] },
|
||||
{ text: "/show-me\texplain caching", slash: true, expected: ["show-me"] },
|
||||
{ text: "/show-me", slash: false, expected: [] },
|
||||
{ text: "/show-me", slash: undefined, expected: [] },
|
||||
{ text: "/show-me-extra", slash: true, expected: [] },
|
||||
{ text: "Explain /show-me", slash: true, expected: [] },
|
||||
])("resolves raw slash skill input $text with slash=$slash", async ({ text, slash, expected }) => {
|
||||
const state = createMemoryComposerState({ prompt: text }).capture()
|
||||
const admitted = Promise.withResolvers<Parameters<ComposerSession["data"]["session"]["prompt"]>[0]>()
|
||||
const target = session({ calls: [], prompt: async (value) => admitted.resolve(value) })
|
||||
const adapter: ActiveComposerAdapter = {
|
||||
kind: "active-session",
|
||||
state,
|
||||
ready: () => true,
|
||||
controls,
|
||||
working: () => false,
|
||||
session: () => target,
|
||||
interrupt: async () => undefined,
|
||||
submitted() {},
|
||||
setEditor() {},
|
||||
}
|
||||
await submitInput(
|
||||
adapter,
|
||||
undefined,
|
||||
"normal",
|
||||
() => [],
|
||||
() => [{ ...slashSkill, slash }],
|
||||
).submit(new Event("submit"))
|
||||
const request = await admitted.promise
|
||||
expect(request.text).toBe(text)
|
||||
expect(request.skills?.map((skill) => skill.id)).toEqual([...expected])
|
||||
})
|
||||
|
||||
test("captures slash skills before creating a session in a new worktree", async () => {
|
||||
const state = createMemoryComposerState({ prompt: "/show-me" }).capture()
|
||||
let skills: readonly Skill.Info[] | undefined = [slashSkill]
|
||||
const admitted = Promise.withResolvers<Parameters<ComposerSession["data"]["session"]["prompt"]>[0]>()
|
||||
const target = session({ calls: [], prompt: async (value) => admitted.resolve(value) })
|
||||
const adapter: NewSessionComposerAdapter = {
|
||||
kind: "new-session",
|
||||
state,
|
||||
ready: () => true,
|
||||
controls,
|
||||
working: () => false,
|
||||
submitted() {},
|
||||
async start() {
|
||||
skills = undefined
|
||||
return { session: target, cleanupReady: Promise.resolve() }
|
||||
},
|
||||
}
|
||||
await submitInput(
|
||||
adapter,
|
||||
undefined,
|
||||
"normal",
|
||||
() => [],
|
||||
() => skills,
|
||||
).submit(new Event("submit"))
|
||||
expect((await admitted.promise).skills).toEqual([
|
||||
expect.objectContaining({ id: "show-me", mention: { start: 0, end: 8, text: "/show-me" } }),
|
||||
])
|
||||
})
|
||||
|
||||
test("sends one captured value with explicit delivery after selection switches", async () => {
|
||||
const state = createMemoryComposerState({ prompt: "ship it" }).capture()
|
||||
const calls: string[] = []
|
||||
@@ -652,7 +538,6 @@ describe("Composer submission", () => {
|
||||
notify,
|
||||
"normal",
|
||||
() => [],
|
||||
() => [slashSkill],
|
||||
)
|
||||
|
||||
await submission.submit(new Event("submit"))
|
||||
@@ -744,7 +629,6 @@ describe("Composer submission", () => {
|
||||
undefined,
|
||||
"normal",
|
||||
() => catalog,
|
||||
() => [{ ...slashSkill, id: Skill.ID.make("review") }],
|
||||
).submit(new Event("submit"))
|
||||
|
||||
expect(await sent.promise).toBe("command")
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
import type { SessionMessageUser, SkillInfo } from "@opencode/client/promise"
|
||||
import { Skill } from "@opencode/schema/skill"
|
||||
import type { SessionMessageUser } from "@opencode/client/promise"
|
||||
import { Event } from "@opencode/schema/event"
|
||||
import type { Accessor } from "solid-js"
|
||||
import type { PromptHistoryComment } from "./history/entry"
|
||||
@@ -30,7 +29,6 @@ type ComposerSubmitInput = {
|
||||
adapter: ComposerAdapter
|
||||
mode: Accessor<"normal" | "shell">
|
||||
commands: Accessor<readonly { name: string }[] | undefined>
|
||||
skills: Accessor<readonly Pick<SkillInfo, "id" | "name" | "slash">[] | undefined>
|
||||
editor: () => HTMLDivElement | undefined
|
||||
queueScroll: () => void
|
||||
addToHistory: (prompt: Prompt, mode: "normal" | "shell") => void
|
||||
@@ -71,7 +69,6 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
|
||||
const comments = input.comments.capture()
|
||||
// Capture command intent before starting a session in a worktree whose catalog has not loaded.
|
||||
const command = value.mode === "normal" ? findCommand(input.commands(), value.text) : undefined
|
||||
if (value.mode === "normal" && !command) value.prompt = withSlashSkill(value.prompt, input.skills())
|
||||
|
||||
try {
|
||||
const started =
|
||||
@@ -292,26 +289,6 @@ function findCommand(commands: ReturnType<ComposerSubmitInput["commands"]>, text
|
||||
return { command, arguments: arguments_.join(" ") }
|
||||
}
|
||||
|
||||
export function withSlashSkill(prompt: Prompt, skills: ReturnType<ComposerSubmitInput["skills"]>): Prompt {
|
||||
const first = prompt[0]
|
||||
if (first?.type !== "text") return prompt
|
||||
const name = /^\/(\S+)(?:\s|$)/.exec(first.content)?.[1]
|
||||
const skill = skills?.find((item) => item.slash === true && item.id === name)
|
||||
if (!skill || prompt.some((part) => part.type === "skill" && part.id === skill.id)) return prompt
|
||||
const content = `/${skill.id}`
|
||||
return [
|
||||
{
|
||||
type: "skill",
|
||||
id: Skill.ID.make(skill.id),
|
||||
name: Skill.Name.make(skill.name),
|
||||
content,
|
||||
start: 0,
|
||||
end: content.length,
|
||||
},
|
||||
{ ...first, content: first.content.slice(content.length), start: content.length },
|
||||
...prompt.slice(1),
|
||||
]
|
||||
}
|
||||
|
||||
async function sendCommand(
|
||||
session: ComposerSession,
|
||||
|
||||
@@ -110,7 +110,7 @@ export function createHomeController() {
|
||||
.list({ path: ".", location })
|
||||
.then(async (files) => {
|
||||
// TODO: Initialize empty directories when V2 exposes a native Git init API.
|
||||
return ctx.sdk.api.project.current({ location })
|
||||
return ctx.sdk.api.location.get({ location }).then((result) => result.project)
|
||||
})
|
||||
.then((project) => ctx.sync.child(item, { bootstrap: false })[1]("project", project.id))
|
||||
.catch(() => undefined)
|
||||
|
||||
@@ -90,7 +90,7 @@ test("rotates HTTP and PTY clients together", async () => {
|
||||
const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input, init)
|
||||
requests.push({ url: request.url, authorization: request.headers.get("authorization") })
|
||||
return Response.json({ healthy: true, version: "2.0.0-test", pid: 1 })
|
||||
return Response.json({ version: "2.0.0-test", pid: 1, urls: [request.url] })
|
||||
}) as typeof globalThis.fetch
|
||||
const transport = createServerTransport({
|
||||
http: { url: "http://127.0.0.1:4100", password: "first" },
|
||||
@@ -98,23 +98,23 @@ test("rotates HTTP and PTY clients together", async () => {
|
||||
})
|
||||
const initialPty = transport.pty
|
||||
|
||||
await transport.api.health.get()
|
||||
await transport.api.server.status()
|
||||
const replacement = transport.update({
|
||||
url: "http://127.0.0.1:4200",
|
||||
password: "second",
|
||||
})
|
||||
await transport.api.health.get()
|
||||
await transport.api.server.status()
|
||||
|
||||
expect(replacement).toBe(transport.api)
|
||||
expect(transport.pty).not.toBe(initialPty)
|
||||
expect(transport.url).toBe("http://127.0.0.1:4200")
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
url: "http://127.0.0.1:4100/api/health",
|
||||
url: "http://127.0.0.1:4100/api/status",
|
||||
authorization: `Basic ${btoa("opencode:first")}`,
|
||||
},
|
||||
{
|
||||
url: "http://127.0.0.1:4200/api/health",
|
||||
url: "http://127.0.0.1:4200/api/status",
|
||||
authorization: `Basic ${btoa("opencode:second")}`,
|
||||
},
|
||||
])
|
||||
|
||||
@@ -2,8 +2,6 @@ import type { Config, Path, Project, ProviderAuthResponse } from "@/runtime/serv
|
||||
import type {
|
||||
LocationGetInput,
|
||||
LocationGetOutput,
|
||||
ProjectCurrentInput,
|
||||
ProjectCurrentOutput,
|
||||
ProjectListOutput,
|
||||
} from "@opencode/client/promise"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
@@ -61,7 +59,6 @@ export const loadGlobalConfigQuery = (scope: ServerScope) =>
|
||||
|
||||
type ProjectApi = {
|
||||
readonly list: () => Promise<ProjectListOutput>
|
||||
readonly current: (input?: ProjectCurrentInput) => Promise<ProjectCurrentOutput>
|
||||
}
|
||||
type LocationApi = { readonly get: (input?: LocationGetInput) => Promise<LocationGetOutput> }
|
||||
|
||||
@@ -132,6 +129,7 @@ export async function bootstrapDirectory(input: {
|
||||
mcp: boolean
|
||||
api: {
|
||||
readonly project: ProjectApi
|
||||
readonly location: LocationApi
|
||||
}
|
||||
store: Store<State>
|
||||
setStore: SetStoreFunction<State>
|
||||
@@ -155,8 +153,8 @@ export async function bootstrapDirectory(input: {
|
||||
seededProject
|
||||
? undefined
|
||||
: () =>
|
||||
retry(() => input.api.project.current({ location: { directory: input.directory } })).then((project) =>
|
||||
input.setStore("project", project.id),
|
||||
retry(() => input.api.location.get({ location: { directory: input.directory } })).then((location) =>
|
||||
input.setStore("project", location.project.id),
|
||||
),
|
||||
].filter((task): task is () => Promise<void> => !!task)
|
||||
|
||||
|
||||
@@ -17,11 +17,10 @@ describe("checkServerHealth", () => {
|
||||
const headers: Array<string | null> = []
|
||||
const fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
headers.push(new Headers(init?.headers).get("authorization"))
|
||||
return Response.json({ healthy: true, version: "2.0.0" })
|
||||
return Response.json({ version: "2.0.0", pid: 1, urls: [server.url] })
|
||||
}) as typeof globalThis.fetch
|
||||
|
||||
const legacy = { ...server, username: "legacy", password }
|
||||
expect(await checkServerHealth(legacy, fetch)).toEqual({ healthy: true, version: "2.0.0" })
|
||||
expect(await checkServerHealth({ ...server, password }, fetch)).toEqual({ healthy: true, version: "2.0.0" })
|
||||
expect(headers).toEqual([password ? `Basic ${btoa(`opencode:${password}`)}` : null])
|
||||
})
|
||||
|
||||
@@ -29,7 +28,7 @@ describe("checkServerHealth", () => {
|
||||
let request: URL | undefined
|
||||
const fetch = (async (input: RequestInfo | URL) => {
|
||||
request = input instanceof URL ? input : new URL(input instanceof Request ? input.url : input)
|
||||
return new Response(JSON.stringify({ healthy: true, version: "1.2.3" }), {
|
||||
return new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
@@ -38,27 +37,7 @@ describe("checkServerHealth", () => {
|
||||
const result = await checkServerHealth(server, fetch)
|
||||
|
||||
expect(result).toEqual({ healthy: true, version: "1.2.3" })
|
||||
expect(request?.pathname).toBe("/api/health")
|
||||
})
|
||||
|
||||
test("identifies a V1 server without a version as incompatible", async () => {
|
||||
const requests: string[] = []
|
||||
const fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = input instanceof URL ? input : new URL(input instanceof Request ? input.url : input)
|
||||
requests.push(url.pathname)
|
||||
return new Response(
|
||||
JSON.stringify(url.pathname === "/global/health" ? { version: "1.18.15" } : { healthy: true }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
)
|
||||
}) as unknown as typeof globalThis.fetch
|
||||
|
||||
const result = await checkServerHealth(server, fetch)
|
||||
|
||||
expect(result).toEqual({ healthy: false, version: "1.18.15", incompatible: true })
|
||||
expect(requests).toEqual(["/api/health", "/global/health"])
|
||||
expect(request?.pathname).toBe("/api/status")
|
||||
})
|
||||
|
||||
test("allows slow servers thirty seconds by default", async () => {
|
||||
@@ -73,14 +52,14 @@ describe("checkServerHealth", () => {
|
||||
})
|
||||
|
||||
const fetch = (async () =>
|
||||
new Response(JSON.stringify({ healthy: true, version: "1.2.3" }), {
|
||||
new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof globalThis.fetch
|
||||
|
||||
await checkServerHealth(server, fetch).finally(() => {
|
||||
if (timeout) Object.defineProperty(AbortSignal, "timeout", timeout)
|
||||
if (!timeout) Reflect.deleteProperty(AbortSignal, "timeout")
|
||||
if (!timeout) delete (AbortSignal as Partial<typeof AbortSignal>).timeout
|
||||
})
|
||||
|
||||
expect(timeoutMs).toBe(30_000)
|
||||
@@ -121,7 +100,7 @@ describe("checkServerHealth", () => {
|
||||
timeoutMs: 10,
|
||||
}).finally(() => {
|
||||
if (timeout) Object.defineProperty(AbortSignal, "timeout", timeout)
|
||||
if (!timeout) Reflect.deleteProperty(AbortSignal, "timeout")
|
||||
if (!timeout) delete (AbortSignal as Partial<typeof AbortSignal>).timeout
|
||||
})
|
||||
|
||||
expect(aborted).toBe(true)
|
||||
@@ -132,7 +111,7 @@ describe("checkServerHealth", () => {
|
||||
let signal: AbortSignal | undefined
|
||||
const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
signal = abortFromInput(input, init)
|
||||
return new Response(JSON.stringify({ healthy: true, version: "1.2.3" }), {
|
||||
return new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
@@ -151,7 +130,7 @@ describe("checkServerHealth", () => {
|
||||
const fetch = (async () => {
|
||||
count += 1
|
||||
if (count < 3) throw new TypeError("network")
|
||||
return new Response(JSON.stringify({ healthy: true, version: "1.2.3" }), {
|
||||
return new Response(JSON.stringify({ version: "1.2.3", pid: 1, urls: [server.url] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
|
||||
@@ -95,23 +95,10 @@ export async function checkServerHealth(
|
||||
fetch,
|
||||
headers,
|
||||
})
|
||||
.health.get({ signal })
|
||||
.then(async (x) => {
|
||||
if (typeof x.healthy !== "boolean") return { error: new Error("Invalid health response") }
|
||||
if (x.healthy && typeof x.version !== "string") {
|
||||
const legacy = await fetch(new URL("/global/health", server.url), { headers, signal })
|
||||
.then((response) => response.json())
|
||||
.catch(() => undefined)
|
||||
const version =
|
||||
typeof legacy === "object" && legacy !== null && "version" in legacy && typeof legacy.version === "string"
|
||||
? legacy.version
|
||||
: "1"
|
||||
return { data: { healthy: false, version, incompatible: true } }
|
||||
}
|
||||
return { data: { healthy: x.healthy, version: x.version } }
|
||||
})
|
||||
.server.status({ signal })
|
||||
.then((status) => ({ data: { healthy: true as const, version: status.version } }))
|
||||
.catch((error) => ({ error }))
|
||||
if ("data" in current && current.data) return current.data
|
||||
if ("data" in current) return current.data
|
||||
if (signal?.aborted) return { healthy: false }
|
||||
|
||||
return next(count, current.error)
|
||||
|
||||
@@ -195,7 +195,7 @@ describe("createRequestQueue", () => {
|
||||
input.tick(50)
|
||||
input.queue.fetch("http://server/api/worktree?location[directory]=%2Fc").catch(() => undefined)
|
||||
input.tick(100)
|
||||
input.queue.fetch("http://server/api/health").catch(() => undefined)
|
||||
input.queue.fetch("http://server/api/status").catch(() => undefined)
|
||||
expect(input.logs).toEqual([])
|
||||
input.tick(2_000)
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
@@ -210,7 +210,7 @@ describe("createRequestQueue", () => {
|
||||
],
|
||||
queued: [
|
||||
{ method: "GET", url: "http://server/api/worktree?location[directory]=%2Fc", ms: 2_100 },
|
||||
{ method: "GET", url: "http://server/api/health", ms: 2_000 },
|
||||
{ method: "GET", url: "http://server/api/status", ms: 2_000 },
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -60,7 +60,7 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
|
||||
const listed = await Promise.all(
|
||||
inventory.locations.map((location) =>
|
||||
input.sdk.api.permission.request
|
||||
.list({ location: { directory: location.directory, workspace: location.workspaceID } })
|
||||
.list({ location: { directory: location.directory } })
|
||||
.then((pending) => {
|
||||
if (!state.disposed) pending.data.forEach((request) => approve(request))
|
||||
return true
|
||||
@@ -103,7 +103,7 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
|
||||
]
|
||||
return {
|
||||
locations: [
|
||||
...new Map(locations.map((item) => [`${item.directory}\u0000${item.workspaceID ?? ""}`, item])).values(),
|
||||
...new Map(locations.map((item) => [item.directory, item])).values(),
|
||||
],
|
||||
complete: active !== undefined && synced.every(Boolean),
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export function createSessionRequestModel() {
|
||||
providers: async (sessionID) => {
|
||||
const session = data.session.get(sessionID) ?? (await serverSDK.api.session.get({ sessionID }))
|
||||
const result = await serverSDK.api.websearch.providers({
|
||||
location: { directory: session.location.directory, workspace: session.location.workspaceID },
|
||||
location: { directory: session.location.directory },
|
||||
})
|
||||
return result.data.map((provider) => ({ value: provider.id, label: provider.name }))
|
||||
},
|
||||
|
||||
@@ -136,7 +136,7 @@ function ResolvedTargetSessionRoute() {
|
||||
>
|
||||
<Show when={directory()} fallback={<PendingSessionState sessionID={params.id} />}>
|
||||
{(value) => (
|
||||
<LocationProvider directory={value} workspaceID={() => current()?.location.workspaceID}>
|
||||
<LocationProvider directory={value}>
|
||||
<SessionUIProvider directory={value()} server={server.key}>
|
||||
<TargetSessionPage />
|
||||
</SessionUIProvider>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createMemo, createResource, onMount, type Accessor } from "solid-js"
|
||||
import type { ConfigPreferences, ConfigUpdatePreferencesInput } from "@opencode/client/promise"
|
||||
import type { ColorScheme } from "@opencode/ui/theme/context"
|
||||
import { useTheme } from "@opencode/ui/theme/context"
|
||||
import {
|
||||
@@ -24,91 +23,47 @@ import { showToast } from "@/shell/notifications/toast"
|
||||
export { createShellOptions, createSoundPreviewController } from "./behavior"
|
||||
export type { ShellOption, ShellSelectOption } from "./behavior"
|
||||
|
||||
export function createServerPreferencesController(server: Accessor<ServerConnection.Any>) {
|
||||
export function createServerShellController(server: Accessor<ServerConnection.Any>) {
|
||||
const language = useLanguage()
|
||||
const serverCtx = useServerCtx(server)
|
||||
const source = () => ServerConnection.key(server())
|
||||
const [preferences, preferencesActions] = createResource<ConfigPreferences, ServerConnection.Key>(
|
||||
const [state, actions] = createResource(
|
||||
source,
|
||||
() =>
|
||||
serverCtx()
|
||||
.sdk.api.config.preferences()
|
||||
.catch(() => ({})),
|
||||
{ initialValue: {} },
|
||||
async () => {
|
||||
const context = serverCtx()
|
||||
const [entries, shells] = await Promise.all([
|
||||
context.sdk.api.config.get().catch(() => []),
|
||||
context.sdk.api.config.shells().catch(() => []),
|
||||
])
|
||||
const boundary = entries.findIndex((entry) => entry.type === "directory")
|
||||
const global = boundary === -1 ? entries : entries.slice(0, boundary)
|
||||
return {
|
||||
shells,
|
||||
shell: global
|
||||
.flatMap((entry) => (entry.type === "document" && entry.info.shell !== undefined ? [entry.info.shell] : []))
|
||||
.at(-1),
|
||||
}
|
||||
},
|
||||
{ initialValue: { shells: [], shell: undefined } },
|
||||
)
|
||||
const [shells] = createResource(
|
||||
source,
|
||||
() =>
|
||||
serverCtx()
|
||||
.sdk.api.config.shells()
|
||||
.catch(() => []),
|
||||
{ initialValue: [] },
|
||||
)
|
||||
const [providers] = createResource(
|
||||
source,
|
||||
() =>
|
||||
serverCtx()
|
||||
.sdk.api.websearch.providers()
|
||||
.then((result) => result.data)
|
||||
.catch(() => []),
|
||||
{ initialValue: [] },
|
||||
)
|
||||
|
||||
const update = async (patch: ConfigUpdatePreferencesInput) => {
|
||||
const context = serverCtx()
|
||||
const previous = preferences.latest
|
||||
preferencesActions.mutate({
|
||||
...previous,
|
||||
...(patch.shell === undefined ? {} : { shell: patch.shell ?? undefined }),
|
||||
...(patch.websearch === undefined ? {} : { websearch: patch.websearch ?? undefined }),
|
||||
})
|
||||
await context.sdk.api.config
|
||||
.updatePreferences(patch)
|
||||
.then(preferencesActions.mutate)
|
||||
.catch((error: unknown) => {
|
||||
preferencesActions.mutate(previous)
|
||||
showToast({
|
||||
variant: "error",
|
||||
title: language.t("common.requestFailed"),
|
||||
description: error instanceof Error ? error.message : language.t("common.requestFailed"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const websearchOptions = createMemo(() => {
|
||||
const options = providers.latest.map((provider) => ({ value: provider.id, label: provider.name }))
|
||||
const selected = preferences.latest.websearch
|
||||
const configured = selected && selected.provider !== "random" ? selected.provider : undefined
|
||||
return [
|
||||
{ value: "random" as const, label: language.t("session.websearch.any") },
|
||||
...options,
|
||||
...(configured && !options.some((option) => option.value === configured)
|
||||
? [{ value: configured, label: configured }]
|
||||
: []),
|
||||
{ value: false as const, label: language.t("session.websearch.disable") },
|
||||
]
|
||||
})
|
||||
const websearchCurrent = createMemo(() => {
|
||||
const selection = preferences.latest.websearch
|
||||
const value = selection === false ? false : (selection?.provider ?? "random")
|
||||
return websearchOptions().find((option) => option.value === value) ?? websearchOptions()[0]
|
||||
})
|
||||
|
||||
return {
|
||||
shell: {
|
||||
shells: () => shells.latest,
|
||||
current: () => preferences.latest.shell ?? "",
|
||||
select: (value: string) => {
|
||||
if (value === (preferences.latest.shell ?? "")) return
|
||||
void update({ shell: value || null })
|
||||
},
|
||||
},
|
||||
websearch: {
|
||||
options: websearchOptions,
|
||||
current: websearchCurrent,
|
||||
select: (value: string | false) => {
|
||||
void update({ websearch: value === false ? false : { provider: value } })
|
||||
},
|
||||
shells: () => state.latest.shells,
|
||||
current: () => state.latest.shell ?? "",
|
||||
select: (value: string) => {
|
||||
if (value === (state.latest.shell ?? "")) return
|
||||
const previous = state.latest
|
||||
actions.mutate({ ...previous, shell: value || undefined })
|
||||
void serverCtx()
|
||||
.sdk.api.config.update({ shell: value || null })
|
||||
.catch((error: unknown) => {
|
||||
actions.mutate(previous)
|
||||
showToast({
|
||||
variant: "error",
|
||||
title: language.t("common.requestFailed"),
|
||||
description: error instanceof Error ? error.message : language.t("common.requestFailed"),
|
||||
})
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -208,6 +163,7 @@ export function createSoundSettingsController() {
|
||||
}
|
||||
}
|
||||
|
||||
export type ShellSettingsController = ReturnType<typeof createServerPreferencesController>["shell"]
|
||||
export type ShellSettingsController = ReturnType<typeof createServerShellController>
|
||||
|
||||
export type AppearanceSettingsController = ReturnType<typeof createAppearanceSettingsController>
|
||||
export type SoundSettingsController = ReturnType<typeof createSoundSettingsController>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Badge } from "@opencode/ui/badge"
|
||||
import { Select } from "@opencode/ui/select"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { createMemo, Show, type Component } from "solid-js"
|
||||
import { ServerRowMenu } from "@/servers/registry/row-menu"
|
||||
@@ -11,35 +10,11 @@ import { DialogServer } from "@/servers/connect/dialog"
|
||||
import { AddServerMenu, WslServerSettings } from "@/servers/wsl/settings"
|
||||
import { SshServerSettings } from "@/servers/ssh/settings"
|
||||
import { SettingsList } from "@/settings/list"
|
||||
import { SettingsRow } from "@/settings/row"
|
||||
import { ShellSetting } from "@/settings/general/general"
|
||||
import { createServerPreferencesController } from "@/settings/general/controllers"
|
||||
import { createServerShellController } from "@/settings/general/controllers"
|
||||
import type { SettingsServer } from "./inventory"
|
||||
import "@/settings/settings.css"
|
||||
|
||||
const WebSearchSetting: Component<{
|
||||
controller: ReturnType<typeof createServerPreferencesController>["websearch"]
|
||||
}> = (props) => {
|
||||
const language = useLanguage()
|
||||
return (
|
||||
<SettingsRow
|
||||
title={language.t("settings.server.preferences.websearch.title")}
|
||||
description={language.t("settings.server.preferences.websearch.description")}
|
||||
>
|
||||
<Select
|
||||
data-action="settings-websearch"
|
||||
options={props.controller.options()}
|
||||
current={props.controller.current()}
|
||||
value={(option) => String(option.value)}
|
||||
label={(option) => option.label}
|
||||
placement="bottom-end"
|
||||
gutter={6}
|
||||
onSelect={(option) => option && props.controller.select(option.value)}
|
||||
/>
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
|
||||
export const SettingsServerGeneral: Component<{
|
||||
entry: SettingsServer
|
||||
nested?: boolean
|
||||
@@ -118,22 +93,21 @@ export const SettingsServerGeneral: Component<{
|
||||
</section>
|
||||
|
||||
<Show when={props.entry.connection} keyed>
|
||||
{(server) => <ServerPreferences server={server} />}
|
||||
{(server) => <ServerShell server={server} />}
|
||||
</Show>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ServerPreferences(props: { server: ServerConnection.Any }) {
|
||||
function ServerShell(props: { server: ServerConnection.Any }) {
|
||||
const language = useLanguage()
|
||||
const preferences = createServerPreferencesController(() => props.server)
|
||||
const controller = createServerShellController(() => props.server)
|
||||
return (
|
||||
<section class="settings-section">
|
||||
<h3 class="settings-section-title">{language.t("settings.tab.preferences")}</h3>
|
||||
<SettingsList>
|
||||
<ShellSetting controller={preferences.shell} />
|
||||
<WebSearchSetting controller={preferences.websearch} />
|
||||
<ShellSetting controller={controller} />
|
||||
</SettingsList>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -27,10 +27,10 @@ import "./project.css"
|
||||
|
||||
type SkillItem = {
|
||||
name: string
|
||||
location: string
|
||||
path: string
|
||||
}
|
||||
|
||||
const skillKey = (item: SkillItem) => `${item.name}\n${item.location}`
|
||||
const skillKey = (item: SkillItem) => `${item.name}\n${item.path}`
|
||||
|
||||
const ExtensionCard: Component<{ children: JSX.Element }> = (props) => (
|
||||
<SettingsList variant="catalog">{props.children}</SettingsList>
|
||||
|
||||
@@ -77,7 +77,7 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
const home = createMemo(() => sync.data.path.home || "")
|
||||
const location = createMemo(() => {
|
||||
const current = props.location ?? fallbackPath()
|
||||
return current ? { directory: current.directory, workspace: current.workspaceID } : undefined
|
||||
return current ? { directory: current.directory } : undefined
|
||||
})
|
||||
const start = createMemo(
|
||||
() =>
|
||||
|
||||
@@ -27,7 +27,7 @@ test("detects iOS home-screen apps when the standalone media query does not matc
|
||||
expect(isStandalone()).toBe(true)
|
||||
} finally {
|
||||
if (descriptor) Object.defineProperty(navigator, "standalone", descriptor)
|
||||
if (!descriptor) Reflect.deleteProperty(navigator, "standalone")
|
||||
if (!descriptor) delete (navigator as Navigator & { standalone?: boolean }).standalone
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -219,6 +219,7 @@ test("snapshots materialize only measured rows and restore their current geometr
|
||||
new Proxy(measurements, {
|
||||
get(target, key, receiver) {
|
||||
if (typeof key === "string" && /^\d+$/.test(key)) reads.push(Number(key))
|
||||
// oxlint-disable-next-line no-restricted-globals -- Proxy forwarding requires receiver-aware property access.
|
||||
return Reflect.get(target, key, receiver)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode/cli",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { NodeFileSystem } from "@effect/platform-node"
|
||||
import { Service } from "@opencode/client/effect/service"
|
||||
import { ServiceStatus } from "@opencode/protocol/groups/health"
|
||||
import { ServerStatus } from "@opencode/protocol/groups/server"
|
||||
import { Effect, Schema } from "effect"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
@@ -42,12 +42,12 @@ try {
|
||||
const credential = btoa(`opencode:${info.password}`)
|
||||
const headers = { authorization: "Basic " + credential }
|
||||
const token = encodeURIComponent(credential)
|
||||
const health = await waitForReady(info.url, headers)
|
||||
if (health.pid !== info.pid) throw new Error("Health process does not match registration")
|
||||
const tokenHealth = await fetch(new URL(`/api/health?auth_token=${token}`, info.url), {
|
||||
const status = await waitForReady(info.url, headers)
|
||||
if (status.pid !== info.pid) throw new Error("Status process does not match registration")
|
||||
const tokenStatus = await fetch(new URL(`/api/status?auth_token=${token}`, info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
if (tokenHealth.status !== 200) throw new Error("Compiled service rejected query authentication")
|
||||
if (tokenStatus.status !== 200) throw new Error("Compiled service rejected query authentication")
|
||||
const tokenOpenApi = await fetch(new URL(`/openapi.json?auth_token=${token}`, info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
@@ -58,10 +58,10 @@ try {
|
||||
await fs.writeFile(plugin, pluginSource())
|
||||
await waitForPlugin(info.url, headers)
|
||||
|
||||
const unauthorizedHealth = await fetch(new URL("/api/health", info.url), {
|
||||
const unauthorizedStatus = await fetch(new URL("/api/status", info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
if (unauthorizedHealth.status !== 401) throw new Error("Compiled service exposed health without authentication")
|
||||
if (unauthorizedStatus.status !== 401) throw new Error("Compiled service exposed status without authentication")
|
||||
const unauthorizedOpenApi = await fetch(new URL("/openapi.json", info.url), {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
@@ -129,11 +129,11 @@ async function waitForRegistration() {
|
||||
async function waitForReady(url: string, headers: HeadersInit) {
|
||||
const deadline = Date.now() + 20_000
|
||||
while (Date.now() < deadline) {
|
||||
const response = await fetch(new URL("/api/health", url), {
|
||||
const response = await fetch(new URL("/api/status", url), {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
}).catch(() => undefined)
|
||||
if (response?.ok) return Schema.decodeUnknownPromise(ServiceStatus.Health)(await response.json())
|
||||
if (response?.ok) return Schema.decodeUnknownPromise(ServerStatus)(await response.json())
|
||||
await Bun.sleep(25)
|
||||
}
|
||||
throw new Error("Compiled service did not become ready")
|
||||
|
||||
@@ -78,7 +78,7 @@ export async function syncEditedFiles(input: {
|
||||
const files = Array.isArray(input.metadata.files)
|
||||
? input.metadata.files.flatMap((file): string[] => {
|
||||
if (!file || typeof file !== "object") return []
|
||||
const path = Reflect.get(file, "file")
|
||||
const path = "file" in file ? file.file : undefined
|
||||
return typeof path === "string" ? [path] : []
|
||||
})
|
||||
: []
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type OpenCodeClient,
|
||||
type SessionInfo,
|
||||
type SessionMessageInfo,
|
||||
type SkillInfo,
|
||||
} from "@opencode/client/promise"
|
||||
import { withTimestampedFallback } from "@opencode/util/session-title-fallback"
|
||||
import type {
|
||||
@@ -71,7 +70,6 @@ type Catalog = {
|
||||
readonly modes: Array<{ id: string; name: string; description?: string }>
|
||||
readonly defaultModeID: string
|
||||
readonly commands: CommandInfo[]
|
||||
readonly skills: SkillInfo[]
|
||||
}
|
||||
|
||||
type Attached = {
|
||||
@@ -90,7 +88,6 @@ type PreparedPrompt = {
|
||||
readonly synthetic: ReadonlyArray<string>
|
||||
readonly slash?: { readonly name: string; readonly args: string }
|
||||
readonly command?: CommandInfo
|
||||
readonly skill?: SkillInfo
|
||||
}
|
||||
|
||||
export interface Interface {
|
||||
@@ -157,11 +154,8 @@ export function make(input: { readonly client: OpenCodeClient; readonly connecti
|
||||
update: {
|
||||
sessionUpdate: "available_commands_update",
|
||||
availableCommands: [
|
||||
...state.catalog.commands,
|
||||
...state.catalog.skills.filter(
|
||||
(skill) => !state.catalog.commands.some((command) => command.name === skill.name),
|
||||
),
|
||||
].map((command) => ({ name: command.name, description: command.description ?? "" })),
|
||||
...state.catalog.commands.map((command) => ({ name: command.name, description: command.description ?? "" })),
|
||||
],
|
||||
},
|
||||
})
|
||||
return state
|
||||
@@ -365,9 +359,8 @@ function preparePrompt(catalog: Catalog, prompt: PromptRequest["prompt"], messag
|
||||
const files = visible.flatMap((part) => (part.type === "file" ? [{ uri: part.url, name: part.filename }] : []))
|
||||
const slash = detectSlashCommand(text)
|
||||
const command = slash ? catalog.commands.find((item) => item.name === slash.name) : undefined
|
||||
const skill = slash ? catalog.skills.find((item) => item.name === slash.name) : undefined
|
||||
const start = turnStart(messageID, slash, skill)
|
||||
return { start, text, files, synthetic, slash, command, skill }
|
||||
const start = turnStart(messageID, slash)
|
||||
return { start, text, files, synthetic, slash, command }
|
||||
}
|
||||
|
||||
async function submitPrompt(client: OpenCodeClient, session: Attached, prompt: PreparedPrompt, signal: AbortSignal) {
|
||||
@@ -381,7 +374,6 @@ async function submitPrompt(client: OpenCodeClient, session: Attached, prompt: P
|
||||
})
|
||||
}
|
||||
if (prompt.start.type === "compaction") return client.session.compact({ sessionID: session.id, id: prompt.start.id })
|
||||
if (prompt.skill) return client.session.skill({ sessionID: session.id, id: prompt.start.id, skill: prompt.skill.id })
|
||||
if (prompt.command) {
|
||||
return client.session.command(
|
||||
{
|
||||
@@ -400,25 +392,22 @@ async function submitPrompt(client: OpenCodeClient, session: Attached, prompt: P
|
||||
)
|
||||
}
|
||||
|
||||
function turnStart(messageID: string, slash: PreparedPrompt["slash"], skill: SkillInfo | undefined): TurnStart {
|
||||
function turnStart(messageID: string, slash: PreparedPrompt["slash"]): TurnStart {
|
||||
if (slash?.name === "compact") return { type: "compaction", id: messageID }
|
||||
if (skill) return { type: "skill", id: messageID }
|
||||
return { type: "input", id: messageID }
|
||||
}
|
||||
|
||||
async function loadCatalog(client: OpenCodeClient, cwd: string): Promise<Catalog> {
|
||||
const location = { directory: cwd }
|
||||
await client.plugin.awaitActivation({ location })
|
||||
// Some providers discover models in the background after activation has settled.
|
||||
// Some providers discover models in the background after plugin startup begins.
|
||||
const deadline = Date.now() + 5_000
|
||||
let missing = "No models are available"
|
||||
while (Date.now() < deadline) {
|
||||
const [modelResult, defaultResult, agentResult, commandResult, skillResult] = await Promise.all([
|
||||
const [modelResult, defaultResult, agentResult, commandResult] = await Promise.all([
|
||||
client.model.list({ location }),
|
||||
client.model.default({ location }),
|
||||
client.agent.list({ location }),
|
||||
client.command.list({ location }),
|
||||
client.skill.list({ location }),
|
||||
])
|
||||
const models = modelResult.data.filter((model) => model.enabled)
|
||||
const preferred = defaultResult.data
|
||||
@@ -440,7 +429,6 @@ async function loadCatalog(client: OpenCodeClient, cwd: string): Promise<Catalog
|
||||
modes: agents.map((agent) => ({ id: agent.id, name: agent.name, description: agent.description })),
|
||||
defaultModeID: defaultAgent.id,
|
||||
commands: commandResult.data,
|
||||
skills: skillResult.data.filter((skill) => skill.slash !== false),
|
||||
}
|
||||
}
|
||||
missing = defaultModel ? "No primary agents are available" : "No models are available"
|
||||
|
||||
@@ -8,11 +8,11 @@ describe("api request resolution", () => {
|
||||
{
|
||||
paths: {
|
||||
"/api/session/{sessionID}": {
|
||||
get: { operationId: "v2.session.get" },
|
||||
get: { operationId: "session.get" },
|
||||
},
|
||||
},
|
||||
},
|
||||
"v2.session.get",
|
||||
"session.get",
|
||||
{ sessionID: "ses/a", workspace: "work" },
|
||||
),
|
||||
).toEqual({ method: "GET", path: "/api/session/ses%2Fa?workspace=work" })
|
||||
@@ -21,8 +21,8 @@ describe("api request resolution", () => {
|
||||
test("rejects a missing path parameter", () => {
|
||||
expect(() =>
|
||||
resolveOperation(
|
||||
{ paths: { "/api/session/{sessionID}": { get: { operationId: "v2.session.get" } } } },
|
||||
"v2.session.get",
|
||||
{ paths: { "/api/session/{sessionID}": { get: { operationId: "session.get" } } } },
|
||||
"session.get",
|
||||
{},
|
||||
),
|
||||
).toThrow("Missing path parameter: sessionID")
|
||||
@@ -30,6 +30,6 @@ describe("api request resolution", () => {
|
||||
|
||||
test("resolves curl-like method and path input", () => {
|
||||
expect(rawRequest(["post", "/api/foo"])).toEqual({ method: "POST", path: "/api/foo" })
|
||||
expect(rawRequest(["v2.session.list"])).toBeUndefined()
|
||||
expect(rawRequest(["session.list"])).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,7 +15,7 @@ export default Runtime.handler(
|
||||
const urls = Option.isSome(input.url)
|
||||
? [input.url.value]
|
||||
: (yield* Effect.tryPromise(() =>
|
||||
OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.get(),
|
||||
OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }).server.status(),
|
||||
)).urls
|
||||
const info = { urls, username: "opencode", password }
|
||||
process.stdout.write(
|
||||
|
||||
@@ -36,7 +36,6 @@ export default Runtime.handler(
|
||||
try: () =>
|
||||
client.session.list({
|
||||
directory: location.directory,
|
||||
workspace: location.workspaceID,
|
||||
parentID: null,
|
||||
order: "desc",
|
||||
limit: 50,
|
||||
|
||||
@@ -44,7 +44,7 @@ export default Runtime.handler(
|
||||
headers: { ...Service.headers(server.endpoint), "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...encoded,
|
||||
location: { directory: location.directory, workspaceID: location.workspaceID },
|
||||
location: { directory: location.directory },
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -81,7 +81,7 @@ export async function runMini(input: MiniCommandInput) {
|
||||
const create = (
|
||||
client: OpenCodeClient,
|
||||
next: {
|
||||
location: { directory: string; workspaceID?: string }
|
||||
location: { directory: string }
|
||||
agent: string | undefined
|
||||
model: Model
|
||||
variant: string | undefined
|
||||
@@ -90,7 +90,7 @@ export async function runMini(input: MiniCommandInput) {
|
||||
) =>
|
||||
resolveSessionTarget({
|
||||
client,
|
||||
location: { directory: next.location.directory, workspace: next.location.workspaceID },
|
||||
location: { directory: next.location.directory },
|
||||
agent: next.agent,
|
||||
environment,
|
||||
model: next.model
|
||||
|
||||
@@ -700,7 +700,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
||||
? Promise.resolve(undefined)
|
||||
: input.client.form.request
|
||||
.list({
|
||||
location: { directory: input.location.directory, workspace: input.location.workspaceID },
|
||||
location: { directory: input.location.directory },
|
||||
})
|
||||
.catch(() => undefined),
|
||||
])
|
||||
@@ -745,7 +745,7 @@ export async function runNonInteractivePrompt(input: Input) {
|
||||
}
|
||||
|
||||
function sameLocation(left: LocationRef | undefined, right: LocationRef) {
|
||||
return !!left && left.directory === right.directory && left.workspaceID === right.workspaceID
|
||||
return !!left && left.directory === right.directory
|
||||
}
|
||||
|
||||
function formRequestOptions(location: LocationRef | undefined): [] | [{ headers: Record<string, string> }] {
|
||||
@@ -754,14 +754,13 @@ function formRequestOptions(location: LocationRef | undefined): [] | [{ headers:
|
||||
{
|
||||
headers: {
|
||||
"x-opencode-directory": encodeURIComponent(location.directory),
|
||||
...(location.workspaceID ? { "x-opencode-workspace": location.workspaceID } : {}),
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function formAlreadySettled(error: unknown) {
|
||||
return !!error && typeof error === "object" && Reflect.get(error, "_tag") === "FormAlreadySettledError"
|
||||
return !!error && typeof error === "object" && "_tag" in error && error._tag === "FormAlreadySettledError"
|
||||
}
|
||||
|
||||
function partID(eventID: string) {
|
||||
|
||||
@@ -105,7 +105,7 @@ async function execute(input: RunCommandInput, prepared: Prepared, endpoint: End
|
||||
next.model ??
|
||||
(options.variant
|
||||
? await client.model
|
||||
.default({ location: { directory: next.location.directory, workspace: next.location.workspaceID } })
|
||||
.default({ location: { directory: next.location.directory } })
|
||||
.then((result) => result.data)
|
||||
: undefined)
|
||||
const model = selected
|
||||
|
||||
@@ -29,7 +29,7 @@ export const resolve = Effect.fn("cli.server-connection.resolve")(function* (arg
|
||||
} satisfies Endpoint
|
||||
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
|
||||
const health = yield* Effect.tryPromise({
|
||||
try: () => client.health.get({ signal: AbortSignal.timeout(5_000) }),
|
||||
try: () => client.server.status({ signal: AbortSignal.timeout(5_000) }),
|
||||
catch: (cause) => connectError(endpoint, cause),
|
||||
})
|
||||
if (health.version !== OPENCODE_VERSION)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
// Split-footer status shown while a freshly launched CLI replaces a
|
||||
// version-mismatched background service before the TUI attaches.
|
||||
import { createCliRenderer, RGBA, TextAttributes, type CliRenderer, type ThemeMode } from "@opentui/core"
|
||||
import { createCliRenderer, RGBA, TextAttributes, type CliRenderer } from "@opentui/core"
|
||||
import { render, useTerminalDimensions } from "@opentui/solid"
|
||||
import { OPENCODE_VERSION } from "../version"
|
||||
import { registerOpencodeSpinner } from "@opencode/tui/component/register-spinner"
|
||||
@@ -30,17 +30,11 @@ const completionHold = 650
|
||||
export type Handle = {
|
||||
readonly begin: (from?: string) => boolean
|
||||
readonly loading: () => void
|
||||
readonly finish: () => Promise<Handoff | undefined>
|
||||
readonly finish: () => Promise<undefined>
|
||||
readonly fail: (message: string) => Promise<void>
|
||||
readonly close: () => Promise<void>
|
||||
}
|
||||
|
||||
export type Handoff = {
|
||||
readonly renderer: CliRenderer
|
||||
readonly mode: ThemeMode | null
|
||||
readonly complete: () => void
|
||||
}
|
||||
|
||||
export const make = (): Handle => {
|
||||
let session: Promise<Session | undefined> | undefined
|
||||
return {
|
||||
@@ -72,7 +66,7 @@ export const make = (): Handle => {
|
||||
|
||||
type Session = {
|
||||
readonly loading: () => Promise<void>
|
||||
readonly finish: () => Promise<Handoff>
|
||||
readonly finish: () => Promise<undefined>
|
||||
readonly fail: (message: string) => Promise<void>
|
||||
readonly close: () => Promise<void>
|
||||
}
|
||||
@@ -83,7 +77,6 @@ async function open(from?: string): Promise<Session> {
|
||||
const [outcome, setOutcome] = createSignal<"running" | "success" | "failure">("running")
|
||||
const [failure, setFailure] = createSignal("")
|
||||
const [animating, setAnimating] = createSignal(true)
|
||||
const [visible, setVisible] = createSignal(true)
|
||||
let resolveOutcome: (() => void) | undefined
|
||||
const renderer = await createCliRenderer({
|
||||
stdin: process.stdin,
|
||||
@@ -101,20 +94,17 @@ async function open(from?: string): Promise<Session> {
|
||||
externalOutputMode: "capture-stdout",
|
||||
consoleMode: "disabled",
|
||||
})
|
||||
const terminalMode = renderer.waitForThemeMode(1000).catch(() => null)
|
||||
await render(
|
||||
() => (
|
||||
<Show when={visible()}>
|
||||
<UpdateFooter
|
||||
from={from}
|
||||
active={active}
|
||||
outcome={outcome}
|
||||
failure={failure}
|
||||
animating={animating}
|
||||
renderer={renderer}
|
||||
onOutcomeSettled={() => resolveOutcome?.()}
|
||||
/>
|
||||
</Show>
|
||||
<UpdateFooter
|
||||
from={from}
|
||||
active={active}
|
||||
outcome={outcome}
|
||||
failure={failure}
|
||||
animating={animating}
|
||||
renderer={renderer}
|
||||
onOutcomeSettled={() => resolveOutcome?.()}
|
||||
/>
|
||||
),
|
||||
renderer,
|
||||
).catch((error) => {
|
||||
@@ -148,10 +138,8 @@ async function open(from?: string): Promise<Session> {
|
||||
if (completed) await setTimeout(hold)
|
||||
}
|
||||
let closing: Promise<void> | undefined
|
||||
let transferred = false
|
||||
const close = () =>
|
||||
(closing ??= (async () => {
|
||||
if (transferred) return
|
||||
setAnimating(false)
|
||||
if (renderer.isDestroyed) return
|
||||
renderer.pause()
|
||||
@@ -174,18 +162,8 @@ async function open(from?: string): Promise<Session> {
|
||||
await waitForStage()
|
||||
await transitionTo("success", completionHold)
|
||||
})
|
||||
const mode = await terminalMode
|
||||
renderer.externalOutputMode = "passthrough"
|
||||
renderer.screenMode = "alternate-screen"
|
||||
renderer.consoleMode = "console-overlay"
|
||||
renderer.requestRender()
|
||||
await Promise.race([renderer.idle(), setTimeout(500)])
|
||||
transferred = true
|
||||
return {
|
||||
renderer,
|
||||
mode,
|
||||
complete: () => setVisible(false),
|
||||
}
|
||||
await close()
|
||||
return undefined
|
||||
},
|
||||
fail: (message) =>
|
||||
settle(async () => {
|
||||
|
||||
@@ -46,7 +46,7 @@ export async function resolveSessionTarget(input: {
|
||||
selection.location ??
|
||||
(await resolveLocation(
|
||||
input.client,
|
||||
selected ? { directory: selected.location.directory, workspace: selected.location.workspaceID } : input.location,
|
||||
selected ? { directory: selected.location.directory } : input.location,
|
||||
input.signal,
|
||||
))
|
||||
const prepared = await input.prepare({
|
||||
@@ -64,14 +64,14 @@ export async function resolveSessionTarget(input: {
|
||||
{
|
||||
agent: prepared.agent,
|
||||
model: prepared.model,
|
||||
location: { directory: location.directory, workspaceID: location.workspaceID },
|
||||
location: { directory: location.directory },
|
||||
},
|
||||
...requestOptions(input.signal),
|
||||
)
|
||||
.catch((error) => {
|
||||
throw new SessionTargetMutationError(error)
|
||||
}))
|
||||
if (input.environment !== undefined && location.workspaceID === undefined)
|
||||
if (input.environment !== undefined)
|
||||
await input.client.session
|
||||
.environment({ sessionID: session.id, variables: input.environment }, ...requestOptions(input.signal))
|
||||
.catch((error) => {
|
||||
@@ -94,7 +94,7 @@ export function parseSessionTargetModel(value?: string): ModelRef | undefined {
|
||||
|
||||
async function selectSession(input: {
|
||||
client: OpenCodeClient
|
||||
location?: { directory?: string; workspace?: string }
|
||||
location?: { directory?: string }
|
||||
continue?: boolean
|
||||
session?: string
|
||||
fork?: boolean
|
||||
@@ -102,7 +102,7 @@ async function selectSession(input: {
|
||||
}) {
|
||||
const explicit = input.session
|
||||
? await input.client.session.get({ sessionID: input.session }, ...requestOptions(input.signal)).catch((error) => {
|
||||
if (error && typeof error === "object" && Reflect.get(error, "_tag") === "SessionNotFoundError")
|
||||
if (error && typeof error === "object" && "_tag" in error && error._tag === "SessionNotFoundError")
|
||||
return undefined
|
||||
throw error
|
||||
})
|
||||
@@ -143,7 +143,6 @@ async function latestSession(
|
||||
const page = await client.session.list(
|
||||
{
|
||||
directory: location.directory,
|
||||
workspace: location.workspaceID,
|
||||
parentID: null,
|
||||
limit: SESSION_PAGE_LIMIT,
|
||||
order: "desc",
|
||||
@@ -151,10 +150,7 @@ async function latestSession(
|
||||
},
|
||||
...requestOptions(signal),
|
||||
)
|
||||
const selected = page.data.find(
|
||||
(session) =>
|
||||
session.location.directory === location.directory && session.location.workspaceID === location.workspaceID,
|
||||
)
|
||||
const selected = page.data.find((session) => session.location.directory === location.directory)
|
||||
if (selected) return selected
|
||||
if (!page.cursor.next || page.data.length === 0) return
|
||||
return latestSession(client, location, page.cursor.next, signal)
|
||||
@@ -162,7 +158,7 @@ async function latestSession(
|
||||
|
||||
function resolveLocation(
|
||||
client: OpenCodeClient,
|
||||
location?: { directory?: string; workspace?: string },
|
||||
location?: { directory?: string },
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
if (!location && !signal) return client.location.get()
|
||||
|
||||
@@ -27,7 +27,7 @@ test("acp prompt resolves after ordered turn updates", async () => {
|
||||
if (!body || typeof body !== "object") {
|
||||
return new Response(null, { status: 400 })
|
||||
}
|
||||
const id = Reflect.get(body, "id")
|
||||
const id = "id" in body ? body.id : undefined
|
||||
if (typeof id !== "string") return new Response(null, { status: 400 })
|
||||
queueMicrotask(() => {
|
||||
if (!events) return
|
||||
|
||||
@@ -574,7 +574,7 @@ function permissionReplies(fixture: Fixture) {
|
||||
return fixture.requests.flatMap((request): Array<[string, string]> => {
|
||||
const match = /^\/api\/session\/[^/]+\/permission\/([^/]+)\/reply$/.exec(request.path)
|
||||
if (!match?.[1] || !request.body || typeof request.body !== "object") return []
|
||||
const reply = Reflect.get(request.body, "reply")
|
||||
const reply = "reply" in request.body ? request.body.reply : undefined
|
||||
return typeof reply === "string" ? [[decodeURIComponent(match[1]), reply]] : []
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,47 +4,6 @@ import { makeACPFixture, makeSession, secondModel, testModel } from "./service-f
|
||||
import { flattenSelectOptions, requireSelectOption } from "./subprocess"
|
||||
|
||||
describe("acp service directory behavior", () => {
|
||||
test("does not cache an available model before plugin activation settles", async () => {
|
||||
const requested = Promise.withResolvers<void>()
|
||||
const release = Promise.withResolvers<void>()
|
||||
let ready = false
|
||||
await using fixture = makeACPFixture({
|
||||
fetch(request) {
|
||||
requested.resolve()
|
||||
if (request.path === "/api/plugin/await-activation") {
|
||||
return release.promise.then(() => {
|
||||
ready = true
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
}
|
||||
if (!ready && request.path === "/api/model") {
|
||||
return Response.json({ data: [{ ...testModel, providerID: "ambient" }] })
|
||||
}
|
||||
if (!ready && request.path === "/api/model/default") {
|
||||
return Response.json({ data: { ...testModel, providerID: "ambient" } })
|
||||
}
|
||||
if (request.path === "/api/session" && request.method === "POST") {
|
||||
return Response.json({ data: { ...makeSession("ses_ready"), model: undefined } })
|
||||
}
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
const pending = fixture.service.newSession({ cwd: "/workspace", mcpServers: [] })
|
||||
try {
|
||||
await requested.promise
|
||||
expect(fixture.requests.map((request) => request.path)).toEqual(["/api/plugin/await-activation"])
|
||||
expect(fixture.requests[0]?.query["location[directory]"]).toBe("/workspace")
|
||||
release.resolve()
|
||||
expect(currentValue(await pending, "model")).toBe("test/test-model")
|
||||
expect(
|
||||
fixture.requests.find((request) => request.path === "/api/session" && request.method === "POST")?.body,
|
||||
).toMatchObject({ model: { providerID: "test", id: "test-model" } })
|
||||
} finally {
|
||||
release.resolve()
|
||||
await pending.catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
test("creates sessions from a catalog shared by concurrent callers in the same cwd", async () => {
|
||||
let created = 0
|
||||
await using fixture = makeACPFixture({
|
||||
@@ -69,12 +28,10 @@ describe("acp service directory behavior", () => {
|
||||
expect(currentValue(first[0], "mode")).toBe("build")
|
||||
expect(
|
||||
[
|
||||
"/api/plugin/await-activation",
|
||||
"/api/model",
|
||||
"/api/model/default",
|
||||
"/api/agent",
|
||||
"/api/command",
|
||||
"/api/skill",
|
||||
].map((path) =>
|
||||
fixture.requests
|
||||
.filter((request) => request.path === path)
|
||||
@@ -85,8 +42,6 @@ describe("acp service directory behavior", () => {
|
||||
["/workspace", "/other"],
|
||||
["/workspace", "/other"],
|
||||
["/workspace", "/other"],
|
||||
["/workspace", "/other"],
|
||||
["/workspace", "/other"],
|
||||
])
|
||||
expect(
|
||||
fixture.requests
|
||||
@@ -116,9 +71,9 @@ describe("acp service directory behavior", () => {
|
||||
: [],
|
||||
),
|
||||
).toEqual([
|
||||
["review", "verify"],
|
||||
["review", "verify"],
|
||||
["review", "verify"],
|
||||
["review"],
|
||||
["review"],
|
||||
["review"],
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type ModelInfo,
|
||||
type ModelRef,
|
||||
type SessionInfo,
|
||||
type SkillInfo,
|
||||
type TokenUsageInfo,
|
||||
} from "@opencode/client/promise"
|
||||
import { ACPService } from "../../src/acp/service"
|
||||
@@ -34,7 +33,6 @@ type FixtureOptions = {
|
||||
readonly defaultModel?: ModelInfo
|
||||
readonly agents?: readonly AgentInfo[]
|
||||
readonly commands?: readonly CommandInfo[]
|
||||
readonly skills?: readonly SkillInfo[]
|
||||
}
|
||||
|
||||
export const testModel = {
|
||||
@@ -89,15 +87,6 @@ export const reviewCommand = {
|
||||
description: "Review changes",
|
||||
} satisfies CommandInfo
|
||||
|
||||
export const verifySkill = {
|
||||
id: "verify",
|
||||
name: "verify",
|
||||
description: "Verify work",
|
||||
slash: true,
|
||||
location: "/skills/verify.md",
|
||||
content: "verify",
|
||||
} satisfies SkillInfo
|
||||
|
||||
export function makeSession(
|
||||
id: string,
|
||||
input: {
|
||||
@@ -152,7 +141,6 @@ export function makeACPFixture(options: FixtureOptions = {}) {
|
||||
|
||||
const directory = request.query["location[directory]"] ?? "/workspace"
|
||||
const location = { directory, project: { id: "global", directory } }
|
||||
if (request.path === "/api/plugin/await-activation") return new Response(null, { status: 204 })
|
||||
if (request.path === "/api/event") {
|
||||
let controller: ReadableStreamDefaultController<Uint8Array> | undefined
|
||||
return new Response(
|
||||
@@ -179,9 +167,6 @@ export function makeACPFixture(options: FixtureOptions = {}) {
|
||||
if (request.path === "/api/command") {
|
||||
return Response.json({ location, data: options.commands ?? [reviewCommand] })
|
||||
}
|
||||
if (request.path === "/api/skill") {
|
||||
return Response.json({ location, data: options.skills ?? [verifySkill] })
|
||||
}
|
||||
return new Response(null, { status: 404 })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
|
||||
import { makeACPFixture, makeSession, secondModel, type FixtureContext, type FixtureRequest } from "./service-fixture"
|
||||
|
||||
describe("acp service prompt routing and usage", () => {
|
||||
test("routes slash commands, skills, and compact through their session endpoints", async () => {
|
||||
test("routes slash commands and compact through their session endpoints", async () => {
|
||||
await using fixture = makeACPFixture({
|
||||
fetch(request, context) {
|
||||
if (request.method === "POST" && request.path === "/api/session") {
|
||||
@@ -14,15 +14,6 @@ describe("acp service prompt routing and usage", () => {
|
||||
if (request.method === "POST" && request.path === "/api/session/ses_routes/command") {
|
||||
return new Response(null, { status: 204 })
|
||||
}
|
||||
if (request.method === "POST" && request.path === "/api/session/ses_routes/skill") {
|
||||
const id = requestID(request)
|
||||
completeTurn(context, "ses_routes", {
|
||||
id: id.replace(/^msg_/, "evt_"),
|
||||
type: "session.skill.activated",
|
||||
data: { sessionID: "ses_routes", skill: "verify" },
|
||||
})
|
||||
return new Response(null, { status: 204 })
|
||||
}
|
||||
if (request.method === "POST" && request.path === "/api/session/ses_routes/compact") {
|
||||
const id = requestID(request)
|
||||
completeTurn(context, "ses_routes", {
|
||||
@@ -41,22 +32,13 @@ describe("acp service prompt routing and usage", () => {
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "/review now" }],
|
||||
})
|
||||
const skillResult = await fixture.service.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "/verify" }],
|
||||
})
|
||||
const compactResult = await fixture.service.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "/compact" }],
|
||||
})
|
||||
|
||||
expect([commandResult.stopReason, skillResult.stopReason, compactResult.stopReason]).toEqual([
|
||||
"end_turn",
|
||||
"end_turn",
|
||||
"end_turn",
|
||||
])
|
||||
expect([commandResult.stopReason, compactResult.stopReason]).toEqual(["end_turn", "end_turn"])
|
||||
const command = fixture.requests.find((request) => request.path === "/api/session/ses_routes/command")
|
||||
const skill = fixture.requests.find((request) => request.path === "/api/session/ses_routes/skill")
|
||||
const compact = fixture.requests.find((request) => request.path === "/api/session/ses_routes/compact")
|
||||
expect(command?.body).toMatchObject({
|
||||
command: "review",
|
||||
@@ -64,7 +46,6 @@ describe("acp service prompt routing and usage", () => {
|
||||
files: [],
|
||||
delivery: "steer",
|
||||
})
|
||||
expect(skill?.body).toMatchObject({ id: expect.any(String), skill: "verify" })
|
||||
expect(compact?.body).toMatchObject({ id: expect.any(String) })
|
||||
expect(fixture.requests.some((request) => request.path === "/api/session/ses_routes/prompt")).toBe(false)
|
||||
})
|
||||
@@ -237,7 +218,7 @@ describe("acp service prompt routing and usage", () => {
|
||||
|
||||
function requestID(request: FixtureRequest) {
|
||||
if (!request.body || typeof request.body !== "object") throw new Error(`missing body for ${request.path}`)
|
||||
const id = Reflect.get(request.body, "id")
|
||||
const id = "id" in request.body ? request.body.id : undefined
|
||||
if (typeof id !== "string") throw new Error(`missing prompt id for ${request.path}`)
|
||||
return id
|
||||
}
|
||||
|
||||
@@ -18,13 +18,11 @@ describe("acp service", () => {
|
||||
body: request.method === "GET" ? undefined : await request.json().catch(() => undefined),
|
||||
})
|
||||
const location = { directory: "/workspace", project: { id: "global", directory: "/workspace" } }
|
||||
if (url.pathname === "/api/plugin/await-activation") return new Response(null, { status: 204 })
|
||||
if (url.pathname === "/api/model") return Response.json({ location, data: [model] })
|
||||
if (url.pathname === "/api/model/default") return Response.json({ location, data: model })
|
||||
if (url.pathname === "/api/agent") return Response.json({ location, data: [agent] })
|
||||
if (url.pathname === "/api/command")
|
||||
return Response.json({ location, data: [{ name: "review", template: "" }] })
|
||||
if (url.pathname === "/api/skill") return Response.json({ location, data: [skill] })
|
||||
if (url.pathname === "/api/session" && request.method === "POST") return Response.json({ data: session })
|
||||
if (url.pathname === "/api/mcp/docs" && request.method === "PUT") return new Response(null, { status: 204 })
|
||||
return new Response(null, { status: 404 })
|
||||
@@ -64,7 +62,7 @@ describe("acp service", () => {
|
||||
sessionId: "ses_acp",
|
||||
update: {
|
||||
sessionUpdate: "available_commands_update",
|
||||
availableCommands: [{ name: "review" }, { name: "verify", description: "Verify work" }],
|
||||
availableCommands: [{ name: "review", description: "" }],
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
@@ -96,15 +94,6 @@ const agent = {
|
||||
permissions: [],
|
||||
}
|
||||
|
||||
const skill = {
|
||||
id: "verify",
|
||||
name: "verify",
|
||||
description: "Verify work",
|
||||
slash: true,
|
||||
location: "/skills/verify.md",
|
||||
content: "verify",
|
||||
}
|
||||
|
||||
const session = {
|
||||
id: "ses_acp",
|
||||
projectID: "global",
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { SessionNotification } from "@agentclientprotocol/sdk"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { createAcpFixture, initialize, newSession, verifierSkill } from "./subprocess"
|
||||
|
||||
describe("acp skills subprocess", () => {
|
||||
test("skill slash command appears through available_commands_update", async () => {
|
||||
await using fixture = await createAcpFixture({ skill: verifierSkill })
|
||||
const acp = fixture.spawn()
|
||||
await initialize(acp)
|
||||
const session = await newSession(acp, fixture.home)
|
||||
|
||||
const update = await acp.waitForNotification<SessionNotification>(
|
||||
"session/update",
|
||||
(params) =>
|
||||
params.sessionId === session.sessionId &&
|
||||
params.update.sessionUpdate === "available_commands_update" &&
|
||||
params.update.availableCommands.some(
|
||||
(command) => command.name === "verifier-skill" && command.description.length > 0,
|
||||
),
|
||||
)
|
||||
|
||||
expect(update.params.sessionId).toBe(session.sessionId)
|
||||
}, 60_000)
|
||||
})
|
||||
@@ -190,7 +190,7 @@ export async function withTimeout<Value>(promise: Promise<Value>, message: strin
|
||||
|
||||
function stringField(value: unknown, key: string) {
|
||||
if (!value || typeof value !== "object") return undefined
|
||||
const field = Reflect.get(value, key)
|
||||
const field = (value as Record<string, unknown>)[key]
|
||||
return typeof field === "string" ? field : undefined
|
||||
}
|
||||
|
||||
|
||||
@@ -272,15 +272,15 @@ function authServer(fetch: (request: Request, url: URL) => Response | Promise<Re
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
requests?.push(url.pathname)
|
||||
if (url.pathname === "/api/health") return health()
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/model/default") return Response.json(located(null))
|
||||
return fetch(request, url)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function health() {
|
||||
return Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid })
|
||||
function status() {
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
}
|
||||
|
||||
function located<T>(data: T) {
|
||||
|
||||
@@ -301,6 +301,7 @@ test("uses migrated keybinds when persistence fails", async () => {
|
||||
const fs = new Proxy(node, {
|
||||
get(target, property, receiver) {
|
||||
if (property === "rename") return () => Effect.die(new Error("read-only config"))
|
||||
// oxlint-disable-next-line no-restricted-globals -- Proxy forwarding requires receiver-aware property access.
|
||||
return Reflect.get(target, property, receiver)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -39,9 +39,9 @@ describe("debug config command", () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/health") {
|
||||
if (url.pathname === "/api/status") {
|
||||
healthProbes += 1
|
||||
return Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid })
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
}
|
||||
requested = url
|
||||
authorization.push(request.headers.get("authorization"))
|
||||
|
||||
@@ -21,6 +21,7 @@ const writeFileString: FileSystem.FileSystem["writeFileString"] = (target, data,
|
||||
const fs = new Proxy(node, {
|
||||
get(target, property, receiver) {
|
||||
if (property === "writeFileString") return writeFileString
|
||||
// oxlint-disable-next-line no-restricted-globals -- Proxy forwarding requires receiver-aware property access.
|
||||
return Reflect.get(target, property, receiver)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@ await Effect.runPromise(
|
||||
command: [process.execPath, path.join(import.meta.dir, "../../src/index.ts"), "serve"],
|
||||
})
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/health", endpoint.url), { headers: Service.headers(endpoint) }),
|
||||
fetch(new URL("/api/status", endpoint.url), { headers: Service.headers(endpoint) }),
|
||||
)
|
||||
console.log(`STANDALONE_READY ${endpoint.pid} ${endpoint.url} ${response.status}`)
|
||||
return yield* Effect.never
|
||||
|
||||
@@ -42,7 +42,7 @@ const sanitizedTransfer = {
|
||||
],
|
||||
}
|
||||
|
||||
const health = () => Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid })
|
||||
const status = () => Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
|
||||
function run(args: string[], stdin?: string) {
|
||||
const child = Bun.spawn([process.execPath, "run", "src/index.ts", ...args], {
|
||||
@@ -60,7 +60,7 @@ test("export is raw by default and supports explicit sanitization", async () =>
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/health") return health()
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === `/api/session/${info.id}`) return Response.json({ data: info })
|
||||
if (url.pathname === `/api/session/${info.id}/export`) {
|
||||
sanitization.push(url.searchParams.get("sanitize") ?? "")
|
||||
@@ -98,7 +98,7 @@ test("export requires a session outside an interactive terminal", async () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/health") return health()
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/location") {
|
||||
return Response.json({
|
||||
directory: "/project",
|
||||
@@ -127,7 +127,7 @@ test("export reports a missing session without a stack trace", async () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/health") return health()
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === `/api/session/${sessionID}/export`) {
|
||||
return Response.json(
|
||||
{ _tag: "SessionNotFoundError", sessionID, message: `Session not found: ${sessionID}` },
|
||||
@@ -158,7 +158,7 @@ test("import validates a file and sends it to the resolved location", async () =
|
||||
port: 0,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/health") return health()
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/location") {
|
||||
return Response.json({
|
||||
directory: root,
|
||||
@@ -201,7 +201,7 @@ test("import reports an existing session without a stack trace", async () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/api/health") return health()
|
||||
if (url.pathname === "/api/status") return status()
|
||||
if (url.pathname === "/api/location") {
|
||||
return Response.json({
|
||||
directory: root,
|
||||
|
||||
@@ -33,7 +33,7 @@ test("mini handler passes resolved CLI keybinds to the runtime", async () => {
|
||||
const handler = (await import("../src/commands/handlers/mini")).default
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid }),
|
||||
fetch: () => Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] }),
|
||||
})
|
||||
|
||||
try {
|
||||
|
||||
@@ -31,14 +31,14 @@ describe("mini command", () => {
|
||||
const initial = Bun.serve({
|
||||
port: 0,
|
||||
fetch() {
|
||||
return Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid })
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
},
|
||||
})
|
||||
const replacement = Bun.serve({
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
authorization.push(request.headers.get("authorization"))
|
||||
return Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid })
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
},
|
||||
})
|
||||
const controller = new AbortController()
|
||||
@@ -57,7 +57,7 @@ describe("mini command", () => {
|
||||
})
|
||||
const client = await connection.reconnect?.(controller.signal)
|
||||
if (!client) throw new Error("Expected a replacement client")
|
||||
await client.health.get()
|
||||
await client.server.status()
|
||||
|
||||
expect(client).not.toBe(connection.sdk)
|
||||
expect(signal).toBe(controller.signal)
|
||||
@@ -147,8 +147,8 @@ describe("mini command", () => {
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
requests.push(url.pathname)
|
||||
if (url.pathname === "/api/health")
|
||||
return Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid })
|
||||
if (url.pathname === "/api/status")
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
|
||||
if (url.pathname === "/api/location")
|
||||
return Response.json({ directory: process.cwd(), project: { id: "global", directory: process.cwd() } })
|
||||
if (url.pathname === "/api/session") {
|
||||
@@ -190,7 +190,7 @@ describe("mini command", () => {
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
if (new URL(request.url).pathname === "/api/session") return new Response("boom", { status: 500 })
|
||||
return Response.json({ healthy: true, version: "incompatible", pid: process.pid })
|
||||
return Response.json({ version: "incompatible", pid: process.pid, urls: [] })
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -424,14 +424,13 @@ describe("runNonInteractivePrompt", () => {
|
||||
const globalOptions = {
|
||||
headers: {
|
||||
"x-opencode-directory": "%2Fwork%20tree",
|
||||
"x-opencode-workspace": "wrk_1",
|
||||
},
|
||||
}
|
||||
expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, globalOptions)
|
||||
expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" })
|
||||
expect(sdk.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_pending_global" }, globalOptions)
|
||||
expect(sdk.form.request.list).toHaveBeenCalledWith({
|
||||
location: { directory: "/work tree", workspace: "wrk_1" },
|
||||
location: { directory: "/work tree" },
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -16,9 +16,9 @@ test("resolution groups Effect-native lifecycle operations only for the managed
|
||||
port: 0,
|
||||
fetch() {
|
||||
return Response.json({
|
||||
healthy: true,
|
||||
version: OPENCODE_VERSION,
|
||||
pid: process.pid,
|
||||
urls: [],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
@@ -256,13 +256,13 @@ test("concurrent service processes elect one server", async () => {
|
||||
expect((await Bun.file(config).json()).password).toBe(info.password)
|
||||
expect(await Bun.file(registration + ".lock").exists()).toBe(false)
|
||||
expect(
|
||||
await fetch(new URL("/api/health", info.url), {
|
||||
await fetch(new URL("/api/status", info.url), {
|
||||
headers: { authorization: "Basic " + btoa(`opencode:${info.password}`) },
|
||||
}).then((response) => response.json()),
|
||||
).toEqual({
|
||||
healthy: true,
|
||||
version: info.version,
|
||||
pid: info.pid,
|
||||
urls: [info.url],
|
||||
})
|
||||
const contender = Bun.spawn(command, { env, stderr: "pipe", stdout: "ignore" })
|
||||
try {
|
||||
@@ -337,7 +337,7 @@ test.each([
|
||||
const info = await waitForInfo(registration)
|
||||
await Promise.all(
|
||||
[...new Set([...cors, ...origins, "https://unlisted.example.com"])].map(async (origin) => {
|
||||
const response = await fetch(new URL("/api/health", info.url), {
|
||||
const response = await fetch(new URL("/api/status", info.url), {
|
||||
method: "OPTIONS",
|
||||
headers: { Origin: origin, "Access-Control-Request-Method": "GET" },
|
||||
})
|
||||
@@ -440,7 +440,7 @@ test("port contender recognizes an incumbent registered during the bind race", a
|
||||
fetch() {
|
||||
requests.count += 1
|
||||
if (requests.count === 2) recognizing.resolve()
|
||||
return Response.json({ healthy: true, version: OPENCODE_VERSION, pid: process.pid }, { status: 503 })
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] }, { status: 503 })
|
||||
},
|
||||
})
|
||||
const registration = path.join(root, "state", "opencode", "service-local.json")
|
||||
@@ -575,7 +575,7 @@ async function waitForInfo(file: string, accept: (info: Info) => boolean = () =>
|
||||
|
||||
async function waitForFailed(info: Info) {
|
||||
for (let attempt = 0; attempt < 400; attempt++) {
|
||||
const status = await fetch(new URL("/api/health", info.url), {
|
||||
const status = await fetch(new URL("/api/status", info.url), {
|
||||
headers: { authorization: "Basic " + btoa(`opencode:${info.password}`) },
|
||||
})
|
||||
.then((response) => response.status)
|
||||
|
||||
@@ -2,16 +2,16 @@ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"
|
||||
import { OpenCode, type LocationGetOutput, type ModelRef, type SessionInfo } from "@opencode/client/promise"
|
||||
import { resolveSessionTarget, SessionTargetMutationError } from "../src/session-target"
|
||||
|
||||
function location(directory: string, workspaceID?: string): LocationGetOutput {
|
||||
return { directory, workspaceID, project: { id: "project", directory, canonical: directory } }
|
||||
function location(directory: string): LocationGetOutput {
|
||||
return { directory, project: { id: "project", directory, canonical: directory } }
|
||||
}
|
||||
|
||||
function session(id: string, directory: string, workspaceID?: string, model?: ModelRef): SessionInfo {
|
||||
function session(id: string, directory: string, model?: ModelRef): SessionInfo {
|
||||
return {
|
||||
id,
|
||||
projectID: "project",
|
||||
title: id,
|
||||
location: { directory, workspaceID },
|
||||
location: { directory },
|
||||
model,
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
@@ -29,23 +29,23 @@ afterEach(() => mock.restore())
|
||||
describe("session target resolver", () => {
|
||||
test("adopts an explicit Session location and model", async () => {
|
||||
const client = OpenCode.make({ baseUrl: "https://opencode.test" })
|
||||
const selected = session("ses_resume", "/session", "work_1", { providerID: "openai", id: "gpt-5" })
|
||||
const selected = session("ses_resume", "/session", { providerID: "openai", id: "gpt-5" })
|
||||
spyOn(client.session, "get").mockResolvedValue(selected)
|
||||
spyOn(client.location, "get").mockResolvedValue(location("/session", "work_1"))
|
||||
spyOn(client.location, "get").mockResolvedValue(location("/session"))
|
||||
|
||||
const target = await resolveSessionTarget({ client, session: selected.id, prepare })
|
||||
expect(target).toMatchObject({
|
||||
session: { id: "ses_resume" },
|
||||
location: { directory: "/session", workspaceID: "work_1" },
|
||||
location: { directory: "/session" },
|
||||
model: { providerID: "openai", id: "gpt-5" },
|
||||
resume: true,
|
||||
})
|
||||
})
|
||||
|
||||
test("paginates to continue the exact implicit workspace", async () => {
|
||||
test("paginates to continue the exact directory", async () => {
|
||||
const client = OpenCode.make({ baseUrl: "https://opencode.test" })
|
||||
spyOn(client.location, "get").mockResolvedValue(location("/project"))
|
||||
const explicit = Array.from({ length: 50 }, (_, index) => session(`ses_${index}`, "/project", `work_${index}`))
|
||||
const explicit = Array.from({ length: 50 }, (_, index) => session(`ses_${index}`, `/other/${index}`))
|
||||
const list = spyOn(client.session, "list")
|
||||
.mockResolvedValueOnce({ data: explicit, cursor: { next: "page_2" } })
|
||||
.mockResolvedValueOnce({ data: [session("ses_implicit", "/project")], cursor: {} })
|
||||
@@ -78,11 +78,11 @@ describe("session target resolver", () => {
|
||||
test("prepares a fresh Session at the server Location before creation", async () => {
|
||||
const client = OpenCode.make({ baseUrl: "https://opencode.test" })
|
||||
const order: string[] = []
|
||||
spyOn(client.location, "get").mockResolvedValue(location("/server", "work_1"))
|
||||
spyOn(client.location, "get").mockResolvedValue(location("/server"))
|
||||
const create = spyOn(client.session, "create").mockImplementation(async (input) => {
|
||||
order.push("create")
|
||||
expect(input).toMatchObject({ agent: "prepared", location: { directory: "/server", workspaceID: "work_1" } })
|
||||
return session("ses_fresh", "/server", "work_1")
|
||||
expect(input).toMatchObject({ agent: "prepared", location: { directory: "/server" } })
|
||||
return session("ses_fresh", "/server")
|
||||
})
|
||||
|
||||
await resolveSessionTarget({
|
||||
@@ -90,7 +90,7 @@ describe("session target resolver", () => {
|
||||
agent: "requested",
|
||||
prepare: async (input) => {
|
||||
order.push("prepare")
|
||||
expect(input.location.workspaceID).toBe("work_1")
|
||||
expect(input.location.directory).toBe("/server")
|
||||
return { model: input.model, agent: "prepared" }
|
||||
},
|
||||
})
|
||||
|
||||
@@ -35,7 +35,8 @@ describe("web UI", () => {
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest
|
||||
const pathname = new URL(request.url, "http://localhost").pathname
|
||||
if (pathname === "/api/health") return HttpServerResponse.jsonUnsafe({ healthy: true })
|
||||
if (pathname === "/api/status")
|
||||
return HttpServerResponse.jsonUnsafe({ version: "test", pid: 1, urls: [origin] })
|
||||
return yield* Effect.fail(
|
||||
new HttpServerError.HttpServerError({
|
||||
reason: new HttpServerError.RouteNotFound({ request }),
|
||||
@@ -46,8 +47,8 @@ describe("web UI", () => {
|
||||
)
|
||||
const origin = HttpServer.formatAddress(http.address)
|
||||
|
||||
const health = yield* Effect.promise(() => fetch(`${origin}/api/health`))
|
||||
expect(yield* Effect.promise(() => health.json())).toEqual({ healthy: true })
|
||||
const status = yield* Effect.promise(() => fetch(`${origin}/api/status`))
|
||||
expect(yield* Effect.promise(() => status.json())).toEqual({ version: "test", pid: 1, urls: [origin] })
|
||||
|
||||
const missing = yield* Effect.promise(() => fetch(`${origin}/api/missing`))
|
||||
expect(missing.status).toBe(404)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode/client",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.3",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -35,7 +35,6 @@ import { Shell } from "@opencode/schema/shell"
|
||||
import { Skill } from "@opencode/schema/skill"
|
||||
import { Vcs } from "@opencode/schema/vcs"
|
||||
import { WebSearch } from "@opencode/schema/websearch"
|
||||
import { Workspace } from "@opencode/schema/workspace"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { fileURLToPath } from "url"
|
||||
|
||||
@@ -53,7 +52,8 @@ const effectTypeReferences = [
|
||||
...namespaceTypes("Form", "@opencode/schema/form", Form),
|
||||
...namespaceTypes("InstructionEntry", "@opencode/schema/instruction-entry", InstructionEntry),
|
||||
...namespaceTypes("Integration", "@opencode/schema/integration", Integration),
|
||||
...namespaceTypes("Location", "@opencode/schema/location", Location),
|
||||
typeReference("Location.PublicRef", "@opencode/schema/location", Location.PublicRef),
|
||||
typeReference("Location.PublicInfo", "@opencode/schema/location", Location.PublicInfo),
|
||||
...namespaceTypes("Mcp", "@opencode/schema/mcp", Mcp),
|
||||
...namespaceTypes("Model", "@opencode/schema/model", Model),
|
||||
...namespaceTypes("Permission", "@opencode/schema/permission", Permission),
|
||||
@@ -74,7 +74,6 @@ const effectTypeReferences = [
|
||||
...namespaceTypes("Skill", "@opencode/schema/skill", Skill),
|
||||
...namespaceTypes("Vcs", "@opencode/schema/vcs", Vcs),
|
||||
...namespaceTypes("WebSearch", "@opencode/schema/websearch", WebSearch),
|
||||
...namespaceTypes("Workspace", "@opencode/schema/workspace", Workspace),
|
||||
typeReference("Prompt", "@opencode/schema/prompt", Prompt),
|
||||
typeReference("PromptMention", "@opencode/schema/prompt", PromptMention),
|
||||
typeReference("FileAttachment", "@opencode/schema/prompt", FileAttachment),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user