diff --git a/.github/actions/prefetch-ghostty/action.yml b/.github/actions/prefetch-ghostty/action.yml new file mode 100644 index 00000000000..cfa1419a791 --- /dev/null +++ b/.github/actions/prefetch-ghostty/action.yml @@ -0,0 +1,40 @@ +name: Prefetch Ghostty dependencies +description: Prepare the pinned source and Zig packages for process-daemon's native build +runs: + using: composite + steps: + - name: Check out pinned Ghostty source + id: pins + shell: bash + env: + GHOSTTY_SOURCE_DIR: ${{ runner.temp }}/ghostty + ZIG_GLOBAL_CACHE_DIR: ${{ github.workspace }}/.zig-cache + run: | + revision=$(git show HEAD:packages/process-daemon/ghostty-revision) + git init --quiet "$GHOSTTY_SOURCE_DIR" + git -C "$GHOSTTY_SOURCE_DIR" fetch --depth=1 https://github.com/ghostty-org/ghostty.git "$revision" + git -C "$GHOSTTY_SOURCE_DIR" -c core.longpaths=true checkout --detach "$revision" + echo "revision=$revision" >> "$GITHUB_OUTPUT" + echo "zig=$(zig version)" >> "$GITHUB_OUTPUT" + echo "GHOSTTY_SOURCE_DIR=$GHOSTTY_SOURCE_DIR" >> "$GITHUB_ENV" + echo "ZIG_GLOBAL_CACHE_DIR=$ZIG_GLOBAL_CACHE_DIR" >> "$GITHUB_ENV" + + # Zig 0.16 stores portable, content-addressed source tarballs in p/. + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: .zig-cache/p + key: ghostty-packages-${{ steps.pins.outputs.zig }}-${{ steps.pins.outputs.revision }} + enableCrossOsArchive: true + + - name: Fetch Zig packages + shell: bash + working-directory: ${{ env.GHOSTTY_SOURCE_DIR }} + run: | + for attempt in 1 2 3 4; do + echo "zig build --fetch=all (attempt $attempt/4)" + if zig build --fetch=all; then exit 0; fi + if [[ $attempt == 4 ]]; then exit 1; fi + delay=$((5 * 2 ** (attempt - 1))) + echo "Retrying in ${delay}s" + sleep "$delay" + done diff --git a/.github/workflows/check-process-daemon.yml b/.github/workflows/check-process-daemon.yml index b10e411bf68..b60f51ac1d3 100644 --- a/.github/workflows/check-process-daemon.yml +++ b/.github/workflows/check-process-daemon.yml @@ -4,11 +4,13 @@ on: pull_request: paths: - packages/process-daemon/** + - .github/actions/prefetch-ghostty/** - .github/workflows/check-process-daemon.yml push: branches: [dev] paths: - packages/process-daemon/** + - .github/actions/prefetch-ghostty/** - .github/workflows/check-process-daemon.yml workflow_dispatch: @@ -59,6 +61,8 @@ jobs: - uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5 with: version: 0.16.0 + use-cache: false + - uses: ./.github/actions/prefetch-ghostty - name: Install Rust run: rustup toolchain install 1.90.0 --profile minimal --component rustfmt --component clippy - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 @@ -79,7 +83,7 @@ jobs: windows: name: Windows (${{ matrix.arch }}) runs-on: ${{ matrix.runner }} - timeout-minutes: 30 + timeout-minutes: 45 strategy: fail-fast: false matrix: @@ -109,7 +113,7 @@ jobs: if: matrix.arch == 'x64' with: version: 0.16.0 - cache-key: ${{ matrix.target }} + use-cache: false # Zig 0.16 crashes when building Ghostty on the native ARM64 host. # Use x64-hosted compilers on this ARM64 runner, but execute ARM64 tests natively. - name: Install x64 Zig for ARM64 cross-compilation @@ -130,6 +134,33 @@ jobs: $old = '@ptrCast(try si.loadNtdllProc(@tagName(proc)))' if (!$source.Contains($old)) { throw 'Zig alignment workaround no longer matches; re-evaluate it' } [System.IO.File]::WriteAllText($file, $source.Replace($old, '@ptrCast(@alignCast(try si.loadNtdllProc(@tagName(proc))))')) + - name: Pin MSVC 14.51 for Zig's Clang 21 + timeout-minutes: 20 + run: | + $installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" + $vs = & "$installer\vswhere.exe" -latest -products * -property installationPath + $tools = "$vs\VC\Tools\MSVC" + $arch = '${{ matrix.arch }}' + $hasRuntimes = { + (Test-Path "$($_.FullName)\lib\x64\vcruntime.lib") -and + (Test-Path "$($_.FullName)\lib\$arch\vcruntime.lib") + } + if (!(Get-ChildItem $tools -Directory -Filter '14.51.*' | Where-Object $hasRuntimes)) { + $components = '--add Microsoft.VisualStudio.Component.VC.14.51.x86.x64' + if ($arch -eq 'arm64') { $components += ' --add Microsoft.VisualStudio.Component.VC.14.51.ARM64' } + $setup = Start-Process "$installer\setup.exe" -ArgumentList "modify --installPath `"$vs`" $components --quiet --norestart" -Wait -PassThru + if ($setup.ExitCode -notin 0, 3010) { throw "VS installer exited with $($setup.ExitCode)" } + Write-Output "MSVC 14.51 installer exited with $($setup.ExitCode) for $arch" + } + $toolset = Get-ChildItem $tools -Directory -Filter '14.51.*' | + Where-Object $hasRuntimes | + Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1 + if (!$toolset) { throw "Missing MSVC 14.51 for $arch" } + # Zig reads this file for both host and target tools on the disposable runner. + Set-Content "$vs\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" $toolset.Name -Encoding ascii + $libc = zig libc + $libc + if ($LASTEXITCODE -ne 0 -or $libc -inotcontains "sys_include_dir=$($toolset.FullName)\include") { throw 'Zig selected unexpected MSVC headers' } - name: Install Rust toolchain and target run: rustup toolchain install $env:RUSTUP_TOOLCHAIN --force-non-host --profile minimal --component rustfmt --component clippy --target $env:CARGO_BUILD_TARGET - name: Verify runner and compiler architecture @@ -145,6 +176,7 @@ jobs: if ($compiler -notcontains 'host: x86_64-pc-windows-msvc') { throw 'Unexpected Rust compiler host' } Write-Output "Executable target: $env:CARGO_BUILD_TARGET" zig version + - uses: ./.github/actions/prefetch-ghostty # No cache-on-failure: a timed-out run once saved a partial cache that broke re-runs. - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: diff --git a/.github/workflows/release-process-daemon.yml b/.github/workflows/release-process-daemon.yml index 04084b5d14a..fde87c1ed7a 100644 --- a/.github/workflows/release-process-daemon.yml +++ b/.github/workflows/release-process-daemon.yml @@ -10,8 +10,10 @@ on: - "process-daemon-v*" pull_request: paths: + - .github/actions/prefetch-ghostty/** - .github/workflows/release-process-daemon.yml - packages/process-daemon/build.rs + - packages/process-daemon/ghostty-revision - packages/process-daemon/npm/** - packages/process-daemon/script/npm-packages.mjs workflow_dispatch: @@ -39,6 +41,8 @@ jobs: - uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5 with: version: ${{ env.ZIG_VERSION }} + use-cache: false + - uses: ./.github/actions/prefetch-ghostty - name: Configure baseline Zig builds run: | chmod +x "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin/zig" @@ -94,7 +98,8 @@ jobs: - uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5 with: version: ${{ env.ZIG_VERSION }} - cache-key: ${{ matrix.target }} + use-cache: false + - uses: ./.github/actions/prefetch-ghostty - name: Configure baseline Zig builds run: | chmod +x "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin/zig" @@ -187,7 +192,7 @@ jobs: if: matrix.arch == 'x64' with: version: ${{ env.ZIG_VERSION }} - cache-key: release-${{ matrix.target }} + use-cache: false # Zig 0.16 crashes when building Ghostty on the native ARM64 host, so use # the x64-hosted compiler there (matching check-process-daemon.yml). - name: Install x64 Zig for ARM64 cross-compilation @@ -206,8 +211,36 @@ jobs: $old = '@ptrCast(try si.loadNtdllProc(@tagName(proc)))' if (!$source.Contains($old)) { throw 'Zig alignment workaround no longer matches; re-evaluate it' } [System.IO.File]::WriteAllText($file, $source.Replace($old, '@ptrCast(@alignCast(try si.loadNtdllProc(@tagName(proc))))')) + - name: Pin MSVC 14.51 for Zig's Clang 21 + timeout-minutes: 20 + run: | + $installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" + $vs = & "$installer\vswhere.exe" -latest -products * -property installationPath + $tools = "$vs\VC\Tools\MSVC" + $arch = '${{ matrix.arch }}' + $hasRuntimes = { + (Test-Path "$($_.FullName)\lib\x64\vcruntime.lib") -and + (Test-Path "$($_.FullName)\lib\$arch\vcruntime.lib") + } + if (!(Get-ChildItem $tools -Directory -Filter '14.51.*' | Where-Object $hasRuntimes)) { + $components = '--add Microsoft.VisualStudio.Component.VC.14.51.x86.x64' + if ($arch -eq 'arm64') { $components += ' --add Microsoft.VisualStudio.Component.VC.14.51.ARM64' } + $setup = Start-Process "$installer\setup.exe" -ArgumentList "modify --installPath `"$vs`" $components --quiet --norestart" -Wait -PassThru + if ($setup.ExitCode -notin 0, 3010) { throw "VS installer exited with $($setup.ExitCode)" } + Write-Output "MSVC 14.51 installer exited with $($setup.ExitCode) for $arch" + } + $toolset = Get-ChildItem $tools -Directory -Filter '14.51.*' | + Where-Object $hasRuntimes | + Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1 + if (!$toolset) { throw "Missing MSVC 14.51 for $arch" } + # Zig reads this file for both host and target tools on the disposable runner. + Set-Content "$vs\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" $toolset.Name -Encoding ascii + $libc = zig libc + $libc + if ($LASTEXITCODE -ne 0 -or $libc -inotcontains "sys_include_dir=$($toolset.FullName)\include") { throw 'Zig selected unexpected MSVC headers' } - name: Install Rust toolchain and target run: rustup toolchain install $env:RUSTUP_TOOLCHAIN --force-non-host --profile minimal --target $env:CARGO_BUILD_TARGET + - uses: ./.github/actions/prefetch-ghostty - name: Build run: cargo build --locked --release - name: Smoke test diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 38b128fb430..324ede83bce 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1566,17 +1566,12 @@ test.describe("compaction", () => { await expect(page.locator('[data-component="session-working"]')).toBeVisible() }) - test("shows an automatic compaction as one quiet divider with background compaction on", async ({ page }) => { - const config = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/config") - + test("shows an automatic compaction as one quiet divider", async ({ page }) => { const timeline = await setupTimeline(page, { sessionMessages: [user, completed], sessionStatus: { [sessionID]: { type: "busy" } }, - configEntries: [{ type: "document", info: { experimental: { background_compaction: true } } }], }) - await config - await timeline.send(compactionStarted({ sessionID, reason: "auto" })) await timeline.send(compactionDelta({ sessionID, text: "Partial automatic summary." })) const compaction = page.locator('[data-component="session-compaction-message"]') @@ -1640,11 +1635,17 @@ test.describe("compaction", () => { await timeline.send(compactionDelta({ sessionID, text: outcome.partial })) await expect(compactions).toHaveCount(index + 1) const compaction = compactions.nth(index) - await expect(compaction).toContainText(outcome.partial) + + // An automatic compaction runs as one quiet divider; a manual one streams its summary. + if (outcome.reason === "auto") + await expect(compaction.locator('[data-slot="session-compaction-divider"]')).toHaveAttribute( + "data-state", + "running", + ) + + if (outcome.reason === "manual") await expect(compaction).toContainText(outcome.partial) if (name === "interrupted") { - await expect(compaction.getByRole("status").getByLabel("Compacting", { exact: true })).toBeVisible() - const request = page.waitForRequest( (request) => request.method() === "POST" && new URL(request.url()).pathname === `/api/session/${sessionID}/interrupt`, diff --git a/packages/app/src/session/timeline/cache.ts b/packages/app/src/session/timeline/cache.ts index 63f6c8da8f6..d73922409da 100644 --- a/packages/app/src/session/timeline/cache.ts +++ b/packages/app/src/session/timeline/cache.ts @@ -84,18 +84,6 @@ export function createTimelineCache( const sessionMenu = select(() => markdown?.sessionMenu) const turnDiff = select(() => data.turnDiff) - // The Location's config is a query: read it in the reader and only while selected, so a pending config - // suspends that reader as the live provider would rather than this view's owner, the whole screen. - let compaction = false - - const backgroundCompaction = () => { - if (!active()) return compaction - - compaction = data.backgroundCompaction - - return compaction - } - const view = () => render( { @@ -135,9 +123,6 @@ export function createTimelineCache( get copyAlwaysVisible() { return data.copyAlwaysVisible }, - get backgroundCompaction() { - return backgroundCompaction() - }, navigateToSession: data.navigateToSession, sessionHref: data.sessionHref, readMedia: data.readMedia, diff --git a/packages/app/src/shell/routes/session-ui-provider.tsx b/packages/app/src/shell/routes/session-ui-provider.tsx index 71fad9ef94b..8df23d77b0b 100644 --- a/packages/app/src/shell/routes/session-ui-provider.tsx +++ b/packages/app/src/shell/routes/session-ui-provider.tsx @@ -1,7 +1,6 @@ import { DataProvider, type TurnDiffInput } from "@opencode/session-ui/context" import { MarkdownProvider, type ReadMarkdownImage } from "@opencode/session-ui/context/markdown" import { useNavigate, useParams } from "@solidjs/router" -import { useQuery } from "@tanstack/solid-query" import { createEffect, createMemo, createSignal, on, onCleanup, untrack, type ParentProps } from "solid-js" import { useProviders } from "@/providers/catalog/providers" import { LocalProvider } from "@/providers/models/selection" @@ -197,25 +196,6 @@ export function SessionUIProvider( const providers = useProviders(directory) - const config = useQuery(() => ({ - queryKey: [serverSDK.scope, "session-ui-config", directory()], - enabled: serverSDK.connection.status() === "connected", - queryFn: () => serverSDK.api.config.get({ location: { directory: directory() } }), - })) - - onCleanup( - serverSDK.event.on("config.updated", (event) => { - if (event.location && event.location.directory !== directory()) return - void config.refetch() - }), - ) - - // Matches the server: the highest-priority document that sets `experimental` decides. - const backgroundCompaction = () => - config.data - ?.flatMap((entry) => (entry.type === "document" && entry.info.experimental ? [entry.info.experimental] : [])) - .at(-1)?.background_compaction === true - // Turn diffs live in the routed tab's in-memory state, so they outlast timeline remounts and go when the tab closes. // A cached timeline keeps the source it had while routed, so a child keeps its tab's diffs after the tab returns to // the parent. A route without an open tab, such as one whose tab is closing, loads into a loose cache rather than @@ -268,7 +248,6 @@ export function SessionUIProvider( turnDiff={turnDiff()} onNavigateToSession={navigateToSession} onSessionHref={href} - backgroundCompaction={backgroundCompaction()} > { @@ -477,8 +473,8 @@ test("a view first reading its providers while another Location is selected read input.cache() input.setState("deferred", true) expect(input.deferredReads).toEqual({ - "ses_a in /repo": ["/repo", "/repo", "/repo", "/repo"], - "ses_b in /other": ["/other", "/other", "/other", "/other"], + "ses_a in /repo": ["/repo", "/repo", "/repo"], + "ses_b in /other": ["/other", "/other", "/other"], }) } finally { input.dispose() diff --git a/packages/client/script/generate.ts b/packages/client/script/generate.ts index 4d262aadfd6..53a82bee26e 100644 --- a/packages/client/script/generate.ts +++ b/packages/client/script/generate.ts @@ -3,6 +3,7 @@ import { compile, emitEffectImported, emitEffectShape, emitPromise, write } from import { ClientApi, clientNamespace, + deprecatedClientPaths, effectOmitEndpoints, groupNames, promiseOmitEndpoints, @@ -57,13 +58,13 @@ const promiseContract = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints, namespace: clientNamespace, - aliases: true, + aliases: deprecatedClientPaths, }) const effectContract = compile(ClientApi, { groupNames, omitEndpoints: effectOmitEndpoints, namespace: clientNamespace, - aliases: true, + aliases: deprecatedClientPaths, }) const effectTypeReferences = [ ...namespaceTypes("Agent", "@opencode/schema/agent", Agent), diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index f65ec052c2b..d34ae5a5895 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -1520,6 +1520,28 @@ export type ExperimentalGenerateImageOperation = ( input: ExperimentalGenerateImageInput, ) => Effect.Effect +export type ExperimentalGenerateVideoCreateInput = { + readonly model: Model.Ref + readonly prompt: string + readonly start?: Generate.ImageFile | undefined + readonly end?: Generate.ImageFile | undefined + readonly references?: ReadonlyArray | undefined + readonly duration?: number | undefined + readonly aspect?: Generate.VideoAspect | undefined + readonly resolution?: Generate.VideoResolution | undefined + readonly sound?: boolean | undefined +} +export type ExperimentalGenerateVideoCreateOutput = Generate.VideoRunning +export type ExperimentalGenerateVideoCreateOperation = ( + input: ExperimentalGenerateVideoCreateInput, +) => Effect.Effect + +export type ExperimentalGenerateVideoGetInput = { readonly id: Generate.VideoID } +export type ExperimentalGenerateVideoGetOutput = Generate.VideoJob +export type ExperimentalGenerateVideoGetOperation = ( + input: ExperimentalGenerateVideoGetInput, +) => Effect.Effect + export type ExperimentalGenerateDecisionsInput = { readonly model: Model.Ref readonly input: ReadonlyArray @@ -1533,6 +1555,10 @@ export type ExperimentalGenerateDecisionsOperation = ( export interface ExperimentalGenerateApi { readonly text: ExperimentalGenerateTextOperation readonly image: ExperimentalGenerateImageOperation + readonly video: { + readonly create: ExperimentalGenerateVideoCreateOperation + readonly get: ExperimentalGenerateVideoGetOperation + } readonly decisions: ExperimentalGenerateDecisionsOperation } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index 2631efc70d2..972e07c8f74 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -119,6 +119,10 @@ import type { ExperimentalGenerateTextOutput, ExperimentalGenerateImageInput, ExperimentalGenerateImageOutput, + ExperimentalGenerateVideoCreateInput, + ExperimentalGenerateVideoCreateOutput, + ExperimentalGenerateVideoGetInput, + ExperimentalGenerateVideoGetOutput, ExperimentalGenerateDecisionsInput, ExperimentalGenerateDecisionsOutput, ExperimentalVoiceModelsOutput, @@ -950,6 +954,36 @@ const EndpointExperimentalGenerateImage = ), ) +const EndpointExperimentalGenerateVideoCreate = + (raw: RawClient["server.generate"]) => (input: ExperimentalGenerateVideoCreateInput) => + preserveEffect()( + raw["generate.video.create"]({ + payload: { + model: input["model"], + prompt: input["prompt"], + start: input["start"], + end: input["end"], + references: input["references"], + duration: input["duration"], + aspect: input["aspect"], + resolution: input["resolution"], + sound: input["sound"], + }, + }).pipe( + Effect.mapError(mapClientError), + Effect.map((value) => value.data), + ), + ) + +const EndpointExperimentalGenerateVideoGet = + (raw: RawClient["server.generate"]) => (input: ExperimentalGenerateVideoGetInput) => + preserveEffect()( + raw["generate.video.get"]({ params: { id: input["id"] } }).pipe( + Effect.mapError(mapClientError), + Effect.map((value) => value.data), + ), + ) + const EndpointExperimentalGenerateDecisions = (raw: RawClient["server.generate"]) => (input: ExperimentalGenerateDecisionsInput) => preserveEffect()( @@ -964,6 +998,7 @@ const EndpointExperimentalGenerateDecisions = const adaptGroupExperimentalGenerate = (raw: RawClient["server.generate"]) => ({ text: EndpointExperimentalGenerateText(raw), image: EndpointExperimentalGenerateImage(raw), + video: { create: EndpointExperimentalGenerateVideoCreate(raw), get: EndpointExperimentalGenerateVideoGet(raw) }, decisions: EndpointExperimentalGenerateDecisions(raw), }) diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index a8bad141bd4..e69d72501d5 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -113,6 +113,10 @@ import type { ExperimentalGenerateTextOutput, ExperimentalGenerateImageInput, ExperimentalGenerateImageOutput, + ExperimentalGenerateVideoCreateInput, + ExperimentalGenerateVideoCreateOutput, + ExperimentalGenerateVideoGetInput, + ExperimentalGenerateVideoGetOutput, ExperimentalGenerateDecisionsInput, ExperimentalGenerateDecisionsOutput, ExperimentalVoiceModelsOutput, @@ -245,6 +249,8 @@ import type { ExperimentalMediaGetOutput, ExperimentalPreviewReadInput, ExperimentalPreviewReadOutput, + ExperimentalBlobGetInput, + ExperimentalBlobGetOutput, ExperimentalScheduleCreateInput, ExperimentalScheduleCreateOutput, ExperimentalScheduleListInput, @@ -1207,6 +1213,41 @@ export function make(options: ClientOptions) { }, requestOptions, ).then((value) => value.data), + video: { + create: (input: ExperimentalGenerateVideoCreateInput, requestOptions?: RequestOptions) => + request<{ readonly data: ExperimentalGenerateVideoCreateOutput }>( + { + method: "POST", + path: `/api/experimental/generate/video`, + body: { + model: input["model"], + prompt: input["prompt"], + start: input["start"], + end: input["end"], + references: input["references"], + duration: input["duration"], + aspect: input["aspect"], + resolution: input["resolution"], + sound: input["sound"], + }, + successStatus: 200, + declaredStatuses: [400, 401, 403, 404, 422, 502, 503], + empty: false, + }, + requestOptions, + ).then((value) => value.data), + get: (input: ExperimentalGenerateVideoGetInput, requestOptions?: RequestOptions) => + request<{ readonly data: ExperimentalGenerateVideoGetOutput }>( + { + method: "GET", + path: `/api/experimental/generate/video/${encodeURIComponent(input.id)}`, + successStatus: 200, + declaredStatuses: [400, 401, 403, 404], + empty: false, + }, + requestOptions, + ).then((value) => value.data), + }, decisions: (input: ExperimentalGenerateDecisionsInput, requestOptions?: RequestOptions) => request<{ readonly data: ExperimentalGenerateDecisionsOutput }>( { @@ -1529,6 +1570,20 @@ export function make(options: ClientOptions) { requestOptions, ), }, + blob: { + get: (input: ExperimentalBlobGetInput, requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/experimental/blob/${encodeURIComponent(input.id)}`, + successStatus: 200, + declaredStatuses: [400, 401, 404], + empty: false, + binary: true, + }, + requestOptions, + ), + }, schedule: { create: (input: ExperimentalScheduleCreateInput, requestOptions?: RequestOptions) => request<{ readonly data: ExperimentalScheduleCreateOutput }>( diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index fb3aad6f646..06418e6c9dc 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -178,7 +178,7 @@ export type SessionMessageToolStateRunning1 = { metadata: { [x: string]: JsonValue } } -export type ModelType = "chat" | "decision" | "image" | (string & {}) +export type ModelType = "chat" | "decision" | "image" | "video" | (string & {}) export type ModelReasoningField = "reasoning" | "reasoning_content" | "reasoning_text" | (string & {}) @@ -198,6 +198,12 @@ export type GenerateUsage = { input?: number; output?: number } export type GenerateNative = { [x: string]: JsonValue } +export type GenerateVideoID = string + +export type BlobID = string + +export type GenerateVideoErrorReason = "failed" | "cancelled" | "expired" | "unknown" + export type GeneratePredicateAnswer = { type: "predicate"; name: string; probability: number } export type GenerateChoiceValue = string | boolean @@ -730,6 +736,17 @@ export type ModelCost = { cache: { read: MoneyUSDPerMillionTokens; write: MoneyUSDPerMillionTokens } } +export type GenerateVideoRunning = { id: GenerateVideoID; status: "running" } + +export type BlobInfo = { id: BlobID; mime: string; bytes: number; expiresAt: number } + +export type GenerateVideoError = { + id: GenerateVideoID + status: "error" + error: string + reason: GenerateVideoErrorReason +} + export type GenerateChoiceAnswer = { type: "choice" name: string @@ -2195,6 +2212,10 @@ export type SessionMessageToolStateError1 = { metadata?: { [x: string]: JsonValue } } +export type GenerateVideoCreateResponse = { data: GenerateVideoRunning } + +export type GenerateVideoCompleted = { id: GenerateVideoID; status: "completed"; blobs: Array } + export type GenerateDecisionAnswer = | GeneratePredicateAnswer | GenerateChoiceAnswer @@ -2513,7 +2534,12 @@ export type ConfigEntry = } } } - compaction?: { auto?: boolean; keep?: { tokens?: number }; buffer?: ConfigCompactionPercent | number } + compaction?: { + auto?: boolean + background?: boolean + keep?: { tokens?: number } + buffer?: ConfigCompactionPercent | number + } skills?: Array commands?: { [x: string]: { @@ -2589,10 +2615,10 @@ export type ConfigEntry = codemode_vm?: boolean all_flags?: boolean todo?: boolean - background_compaction?: boolean media_blob?: boolean schedules?: boolean artifacts?: boolean + video_generate?: boolean console_watches?: boolean mcp_events?: boolean full_codemode?: boolean @@ -2671,6 +2697,8 @@ export type SessionMessageAssistantTool1 = { time: { created: number; ran?: number; completed?: number } } +export type GenerateVideoJob = GenerateVideoRunning | GenerateVideoCompleted | GenerateVideoError + export type GenerateDecisionResult = { answers: Array cost?: MoneyUSD @@ -2779,6 +2807,8 @@ export type SessionMessageAssistantContentEncoded = | SessionMessageAssistantReasoning1 | SessionMessageAssistantTool1 +export type GenerateVideoGetResponse = { data: GenerateVideoJob } + export type GenerateDecisionsResponse = { data: GenerateDecisionResult } export type FormInfo1 = { id: FormID; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields1 } @@ -3175,6 +3205,18 @@ export type ProviderRequestError = { export const isProviderRequestError = (value: unknown): value is ProviderRequestError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ProviderRequestError" +export type ForbiddenError = { readonly _tag: "ForbiddenError"; readonly message: string } +export const isForbiddenError = (value: unknown): value is ForbiddenError => + typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ForbiddenError" + +export type VideoNotFoundError = { + readonly _tag: "VideoNotFoundError" + readonly videoID: string + readonly message: string +} +export const isVideoNotFoundError = (value: unknown): value is VideoNotFoundError => + typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "VideoNotFoundError" + export type IntegrationNotFoundError = { readonly _tag: "IntegrationNotFoundError" readonly integrationID: string @@ -3209,10 +3251,6 @@ export type McpServerNotFoundError = { export const isMcpServerNotFoundError = (value: unknown): value is McpServerNotFoundError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "McpServerNotFoundError" -export type ForbiddenError = { readonly _tag: "ForbiddenError"; readonly message: string } -export const isForbiddenError = (value: unknown): value is ForbiddenError => - typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ForbiddenError" - export type ProjectNotFoundError = { readonly _tag: "ProjectNotFoundError" readonly projectID: string @@ -3271,6 +3309,14 @@ export type PtyFeatureUnsupportedError = { export const isPtyFeatureUnsupportedError = (value: unknown): value is PtyFeatureUnsupportedError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "PtyFeatureUnsupportedError" +export type BlobNotFoundError = { + readonly _tag: "BlobNotFoundError" + readonly blobID: string + readonly message: string +} +export const isBlobNotFoundError = (value: unknown): value is BlobNotFoundError => + typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "BlobNotFoundError" + export type ScheduleNotFoundError = { readonly _tag: "ScheduleNotFoundError" readonly scheduleID: string @@ -3965,7 +4011,7 @@ export type MessageListOutput = SessionMessagesResponse export type ModelListInput = { readonly location?: { readonly directory?: string | undefined } | undefined - readonly types?: ReadonlyArray<"chat" | "decision" | "image" | (string & {})> | undefined + readonly types?: ReadonlyArray<"chat" | "decision" | "image" | "video" | (string & {})> | undefined } export type ModelListOutput = { location: LocationPublicRef; data: Array } @@ -3992,6 +4038,26 @@ export type ExperimentalGenerateImageInput = { export type ExperimentalGenerateImageOutput = GenerateImageResponse["data"] +export type ExperimentalGenerateVideoCreateInput = { + readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } + readonly prompt: string + readonly start?: { readonly data: string; readonly mime: string; readonly name?: string } | undefined + readonly end?: { readonly data: string; readonly mime: string; readonly name?: string } | undefined + readonly references?: + | ReadonlyArray<{ readonly data: string; readonly mime: string; readonly name?: string }> + | undefined + readonly duration?: number | undefined + readonly aspect?: (`${number}${":"}${number}` | "auto") | undefined + readonly resolution?: ("480p" | "720p" | "1080p" | "4k" | (string & {})) | undefined + readonly sound?: boolean | undefined +} + +export type ExperimentalGenerateVideoCreateOutput = GenerateVideoCreateResponse["data"] + +export type ExperimentalGenerateVideoGetInput = { readonly id: string } + +export type ExperimentalGenerateVideoGetOutput = GenerateVideoGetResponse["data"] + export type ExperimentalGenerateDecisionsInput = { readonly model: { readonly id: string; readonly providerID: string; readonly variant?: string } readonly input: ReadonlyArray< @@ -4605,6 +4671,10 @@ export type ExperimentalPreviewReadInput = { export type ExperimentalPreviewReadOutput = globalThis.Uint8Array +export type ExperimentalBlobGetInput = { readonly id: string } + +export type ExperimentalBlobGetOutput = globalThis.Uint8Array + export type ExperimentalScheduleCreateInput = { readonly sessionID: string readonly name?: string | undefined diff --git a/packages/client/test/deprecated-aliases.test.ts b/packages/client/test/deprecated-aliases.test.ts index 465e8c1aa68..0f649105905 100644 --- a/packages/client/test/deprecated-aliases.test.ts +++ b/packages/client/test/deprecated-aliases.test.ts @@ -3,6 +3,7 @@ import { compile } from "@opencode/httpapi-codegen" import { ClientApi, clientNamespace, + deprecatedClientPaths, effectOmitEndpoints, groupNames, promiseOmitEndpoints, @@ -14,7 +15,7 @@ import { OpenCode as PromiseOpenCode } from "../src/promise/index" // The pre-experimental paths stay until the next minor. const aliases = (omitEndpoints: ReadonlySet) => - compile(ClientApi, { groupNames, omitEndpoints, namespace: clientNamespace, aliases: true }).aliases ?? [] + compile(ClientApi, { groupNames, omitEndpoints, namespace: clientNamespace, aliases: deprecatedClientPaths }).aliases ?? [] const at = (root: unknown, path: ReadonlyArray) => path.reduce((parent, key) => (parent as Record | undefined)?.[key], root) diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 1c23b4c035a..0e7ca8f4a41 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -62,6 +62,7 @@ test("exposes every standard HTTP API group", () => { "persistentPty", "media", "preview", + "blob", "schedule", "artifacts", "job", diff --git a/packages/core/src/blob-store.ts b/packages/core/src/blob-store.ts new file mode 100644 index 00000000000..53e9d7685cc --- /dev/null +++ b/packages/core/src/blob-store.ts @@ -0,0 +1,126 @@ +export * as BlobStore from "./blob-store.js" + +import path from "path" +import { Media } from "@opencode/ai/effect" +import { BlobStore } from "@opencode/schema/blob-store" +import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { FSUtil } from "@opencode/util/fs-util" +import { Global } from "@opencode/util/global" +import { Context, Duration, Effect, Layer, Option, Schedule, Schema, Stream } from "effect" +import { FileRetention } from "./file-retention.js" + +export const ID = BlobStore.ID +export type ID = BlobStore.ID +export type Info = BlobStore.Info + +export class NotFoundError extends Schema.TaggedError()("BlobStore.NotFoundError", { + id: Schema.String, + message: Schema.String, +}) {} + +export class UnavailableError extends Schema.TaggedError()("BlobStore.UnavailableError", { + message: Schema.String, +}) {} + +export const RETENTION = Duration.days(7) +/** Blobs are files named by their ID, with no extension; their type is read from their first bytes. */ +export const DIRECTORY = "blobs" + +/** A stored blob and where its file is. */ +export interface Content extends Info { + readonly path: string +} + +export interface Interface { + /** Stores the stream as the blob `id`, replacing any earlier one. The file appears only once it's whole. */ + readonly write: (id: ID, stream: Stream.Stream) => Effect.Effect + readonly read: (id: ID) => Effect.Effect + readonly remove: (id: ID) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/BlobStore") {} + +/** + * Files under `/blobs/`, deleted 7 days after they're written, at startup and hourly. Nothing tracks who uses a + * blob, so a caller that keeps one longer copies it. + */ +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const fs = yield* FSUtil.Service + const global = yield* Global.Service + const directory = path.join(global.data, DIRECTORY) + const file = (id: ID) => path.join(directory, id) + + const read = Effect.fn("BlobStore.read")(function* (id: ID) { + const missing = new NotFoundError({ id, message: `Blob not found: ${id}` }) + const info = yield* fs.stat(file(id)).pipe(Effect.mapError(() => missing)) + const written = Option.getOrUndefined(info.mtime)?.getTime() ?? 0 + const head = yield* fs.stream(file(id), { bytesToRead: 64 }).pipe( + Stream.runCollect, + Effect.mapError(() => missing), + ) + return { + id, + path: file(id), + mime: Media.detectMediaType(Buffer.concat([...head])) ?? "application/octet-stream", + bytes: Number(info.size), + expiresAt: written + Duration.toMillis(RETENTION), + } + }) + + // Written to `.part`, synced, then renamed, so a stored blob is always whole. + const write = (id: ID, stream: Stream.Stream) => + Effect.gen(function* () { + const part = `${file(id)}.part` + const unavailable = (cause: unknown) => + new UnavailableError({ message: `Could not store blob ${id}: ${String(cause)}` }) + yield* fs.makeDirectory(directory, { recursive: true }).pipe(Effect.mapError(unavailable)) + yield* Effect.scoped( + Effect.gen(function* () { + const handle = yield* fs.open(part, { flag: "w", mode: 0o600 }).pipe(Effect.mapError(unavailable)) + yield* stream.pipe(Stream.runForEach((chunk) => handle.writeAll(chunk).pipe(Effect.mapError(unavailable)))) + yield* handle.sync.pipe(Effect.mapError(unavailable)) + }), + ).pipe(Effect.onError(() => fs.remove(part, { force: true }).pipe(Effect.ignore))) + yield* fs.rename(part, file(id)).pipe(Effect.mapError(unavailable)) + const stored = yield* read(id).pipe(Effect.mapError(unavailable)) + return { id, mime: stored.mime, bytes: stored.bytes, expiresAt: stored.expiresAt } satisfies Info + }).pipe(Effect.withSpan("BlobStore.write")) + + const remove = (id: ID) => fs.remove(file(id), { force: true }).pipe(Effect.ignore) + + // Blobs and leftover `.part` files are deleted once older than the retention. + yield* fs.readDirectory(directory).pipe( + Effect.orElseSucceed((): string[] => []), + Effect.flatMap((entries) => + FileRetention.cleanup( + fs, + entries.filter((entry) => entry.startsWith("video_")).map((entry) => path.join(directory, entry)), + RETENTION, + ), + ), + Effect.ignoreCause({ log: "Error", message: "Blob cleanup failed" }), + Effect.repeat(Schedule.spaced(Duration.hours(1))), + Effect.forkScoped, + ) + + return Service.of({ write, read, remove }) + }), +) + +/** Blobs need a local disk, which Durable Objects don't have. */ +export const unsupportedLayer = Layer.succeed( + Service, + Service.of({ + write: () => Effect.fail(new UnavailableError({ message: "Blob storage is not supported in this runtime" })), + read: (id) => Effect.fail(new NotFoundError({ id, message: `Blob not found: ${id}` })), + remove: () => Effect.void, + }), +) + +export const node = makeGlobalNode({ + service: Service, + layer, + deps: [FSUtil.node, Global.node], +}) diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index e3f3ab1e2e1..d107546df59 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -11,7 +11,9 @@ import type { Namespace as ToolNamespace, Result, } from "@opencode/schema/tool" -import { Clock, Context, Effect, Ref, Schema, Semaphore } from "effect" +import { Identifier } from "@opencode/schema/identifier" +import { CallID } from "@opencode/schema/tool" +import { Clock, Context, Effect, Ref, Schema, Scope, Semaphore } from "effect" import { toSessionError } from "../session/to-session-error.js" import { definition, normalizedName } from "../tool/runtime.js" import { Permission } from "../permission.js" @@ -131,9 +133,14 @@ export const create = ( executeTool: (name, tool, input) => Effect.gen(function* () { const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) + // Its own ID, so plugin hooks and traces can tell the program's calls apart. It has no row, so + // until the program ends its permission requests show on this call's. + const id = CallID.make(`call_${Identifier.ascending()}`) + yield* permission.nested(id, context.id).pipe(Scope.provide(scope)) // The program sees the same failure text the model gets for a direct call. const executed = yield* executeTool(name, tool, input, { ...context, + id, // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. progress: () => Effect.void, // A stop is the execute call's to handle: a nested call never fails it with its own error. diff --git a/packages/core/src/config/normalize.ts b/packages/core/src/config/normalize.ts index 891e6418f66..a3138bd5da9 100644 --- a/packages/core/src/config/normalize.ts +++ b/packages/core/src/config/normalize.ts @@ -353,14 +353,15 @@ function normalizeCompaction( unsupportedIfPresent(input.compaction, "tail_turns", ["compaction", "tail_turns"], diagnostics) unsupportedIfPresent(input.compaction, "prune", ["compaction", "prune"], diagnostics) const result: Record = {} - if (own(input.compaction, "auto")) { + for (const key of ["auto", "background"] as const) { + if (!own(input.compaction, key)) continue const value = decodeEncoded( - ConfigCompaction.Info.fields.auto, - input.compaction.auto, - ["compaction", "auto"], + ConfigCompaction.Info.fields[key], + input.compaction[key], + ["compaction", key], diagnostics, ) - if (value !== undefined) result.auto = value + if (value !== undefined) result[key] = value } const legacyTokens = own(input.compaction, "preserve_recent_tokens") ? decodeEncoded( diff --git a/packages/core/src/config/plugin/compaction.ts b/packages/core/src/config/plugin/compaction.ts index 28a4cc49652..cc7d0dfbda9 100644 --- a/packages/core/src/config/plugin/compaction.ts +++ b/packages/core/src/config/plugin/compaction.ts @@ -3,7 +3,6 @@ export * as ConfigCompactionPlugin from "./compaction.js" import { define } from "@opencode/plugin/effect/plugin" import { Effect } from "effect" import { Config } from "../../config.js" -import { Flag } from "../../flag.js" import { SessionCompaction } from "../../session/compaction.js" import { ConfigEntryObserver } from "./entry-observer.js" @@ -12,14 +11,13 @@ export const Plugin = define({ effect: Effect.fn(function* (ctx) { const config = yield* Config.Service const compaction = yield* SessionCompaction.Service - const flags = yield* Flag.Service const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, compaction.reload()) yield* compaction.transform((editor) => { - editor.configure({ precompute: flags.resolve(loaded.entries).background_compaction.enabled }) for (const entry of loaded.entries) { if (entry.type !== "document" || !entry.info.compaction) continue editor.configure({ ...(entry.info.compaction.auto === undefined ? {} : { auto: entry.info.compaction.auto }), + ...(entry.info.compaction.background === undefined ? {} : { background: entry.info.compaction.background }), ...(entry.info.compaction.buffer === undefined ? {} : { buffer: entry.info.compaction.buffer }), ...(entry.info.compaction.keep?.tokens === undefined ? {} : { keep: entry.info.compaction.keep.tokens }), }) diff --git a/packages/core/src/generate.ts b/packages/core/src/generate.ts index a28ab6b3264..2ef8d81ca79 100644 --- a/packages/core/src/generate.ts +++ b/packages/core/src/generate.ts @@ -1,10 +1,21 @@ export * as Generate from "./generate.js" -import { ai, AIError, DecisionClient, ImageClient, LLMClient, Media } from "@opencode/ai/effect" +import { + ai, + AIError, + DecisionClient, + ImageClient, + LLMClient, + Media, + VideoClient, + type VideoAspectRatio, + type VideoModel, + type VideoStatus, +} from "@opencode/ai/effect" import type { DecisionRequest, DecisionResult, ImageRequest, ImageResult } from "@opencode/schema/generate" import { Money } from "@opencode/schema/money" import { SessionID } from "@opencode/schema/session-id" -import { Context, Effect, Layer, Schema } from "effect" +import { Context, Effect, Layer, Schema, Stream } from "effect" import { RequestExecutor } from "@opencode/ai/route" import { makeLocationNode } from "@opencode/util/effect/app-node" import { llmClient, requestExecutor } from "./effect/app-node-platform.js" @@ -18,6 +29,26 @@ export interface TextInput { readonly model?: Model.Ref } +export interface VideoInput { + readonly model: Model.Ref + readonly prompt: string + readonly start?: Media.ImageAsset + readonly end?: Media.ImageAsset + readonly references?: readonly Media.Asset[] + readonly duration?: number + readonly aspect?: VideoAspectRatio + readonly resolution?: string + readonly sound?: boolean +} + +/** A finished video. `stream` downloads it as it is read, so a long video is never held in memory. */ +export interface VideoFile { + readonly mime: string + readonly width?: number + readonly height?: number + readonly stream: Stream.Stream +} + export class UnavailableError extends Schema.TaggedError()("Generate.UnavailableError", { message: Schema.String, service: Schema.optional(Schema.String), @@ -74,6 +105,15 @@ export interface Interface { readonly text: (input: TextInput) => Effect.Effect readonly image: (input: ImageRequest) => Effect.Effect readonly decisions: (input: DecisionRequest) => Effect.Effect + /** + * A video is a job: `start` submits it and returns the provider's job ID, which `status` and `result` read. `result` + * returns every video the job made, at least one. + */ + readonly video: { + readonly start: (input: VideoInput) => Effect.Effect<{ readonly id: string }, Error> + readonly status: (model: Model.Ref, id: string) => Effect.Effect + readonly result: (model: Model.Ref, id: string) => Effect.Effect + } } export class Service extends Context.Service()("@opencode/Generate") {} @@ -88,26 +128,29 @@ export const layer = Layer.effect( const executor = yield* RequestExecutor.Service const images = yield* ImageClient.Service const decisionClient = yield* DecisionClient.Service + const videos = yield* VideoClient.Service const runText = Effect.fn("Generate.text")(function* (input: TextInput) { - const resolved = yield* resolver.resolve(input.model).pipe( - Effect.catchTag( - [ - "SessionRunnerModel.VariantUnavailableError", - "SessionRunnerModel.UnsupportedPackageError", - "SessionRunnerModel.ModelConfigurationError", - "SessionRunnerModel.ModelInitializationError", - "SessionRunnerModel.UnresolvedProviderVariablesError", - "SessionRunnerModel.UnsupportedCompactionError", - ], - (error) => - Effect.fail( - input.model - ? resolutionError(input.model, "chat", error) - : new UnavailableError({ message: error.message, service: error.providerID }), - ), - ), - ) + const resolved = yield* resolver + .resolve(input.model) + .pipe( + Effect.catchTag( + [ + "SessionRunnerModel.VariantUnavailableError", + "SessionRunnerModel.UnsupportedPackageError", + "SessionRunnerModel.ModelConfigurationError", + "SessionRunnerModel.ModelInitializationError", + "SessionRunnerModel.UnresolvedProviderVariablesError", + "SessionRunnerModel.UnsupportedCompactionError", + ], + (error) => + Effect.fail( + input.model + ? resolutionError(input.model, "chat", error) + : new UnavailableError({ message: error.message, service: error.providerID }), + ), + ), + ) if (!resolved && input.model) return yield* missing(input.model, "chat") if (!resolved) return yield* new UnavailableError({ message: "No model specified and no supported model is available" }) @@ -129,7 +172,7 @@ export const layer = Layer.effect( // A ref no model of this type has: another type's model (422) or no model at all (404). const missing = Effect.fnUntraced(function* (ref: Model.Ref, type: Model.Type) { - const other = (yield* models.available(["chat", "image", "decision"])).find( + const other = (yield* models.available(["chat", "image", "video", "decision"])).find( (model) => model.providerID === ref.providerID && model.id === ref.id, ) if (other) @@ -152,18 +195,20 @@ export const layer = Layer.effect( .pipe(Effect.mapError((error) => resolutionError(input.model, "image", error))) if (!model) return yield* missing(input.model, "image") // `ai.image.generate` turns an invalid request into a typed error; building it with `ai.image.request` would throw. - const response = yield* ai.image.generate({ - model, - prompt: input.prompt, - images: input.images?.map((file) => Media.base64(file.data, file.mime)), - n: input.n, - aspect: input.aspect, - resolution: input.resolution, - }).pipe( - Effect.provideService(ImageClient.Service, images), - ModelRetry.retryOneShot, - Effect.mapError((error) => providerError(input.model, error)), - ) + const response = yield* ai.image + .generate({ + model, + prompt: input.prompt, + images: input.images?.map((file) => Media.base64(file.data, file.mime)), + n: input.n, + aspect: input.aspect, + resolution: input.resolution, + }) + .pipe( + Effect.provideService(ImageClient.Service, images), + ModelRetry.retryOneShot, + Effect.mapError((error) => providerError(input.model, error)), + ) // URL results are downloaded so every image comes back inline, like the request's own files. // Materializing also detects the type of a downloaded image from its bytes when the URL didn't say. const outputs = yield* Effect.forEach(response.images, (asset) => @@ -190,19 +235,21 @@ export const layer = Layer.effect( .resolveDecision(input.model) .pipe(Effect.mapError((error) => resolutionError(input.model, "decision", error))) if (!model) return yield* missing(input.model, "decision") - const response = yield* ai.decision.generate({ - model, - input: input.input.map((part) => - part.type === "file" - ? { type: "media" as const, media: Media.base64(part.data, part.mime), filename: part.name } - : part, - ), - questions: input.questions, - }).pipe( - Effect.provideService(DecisionClient.Service, decisionClient), - ModelRetry.retryOneShot, - Effect.mapError((error) => providerError(input.model, error)), - ) + const response = yield* ai.decision + .generate({ + model, + input: input.input.map((part) => + part.type === "file" + ? { type: "media" as const, media: Media.base64(part.data, part.mime), filename: part.name } + : part, + ), + questions: input.questions, + }) + .pipe( + Effect.provideService(DecisionClient.Service, decisionClient), + ModelRetry.retryOneShot, + Effect.mapError((error) => providerError(input.model, error)), + ) const usage = response.usage return { answers: response.answers, @@ -214,6 +261,41 @@ export const layer = Layer.effect( } satisfies DecisionResult }) + const video = Effect.fnUntraced(function* ( + ref: Model.Ref, + run: (model: VideoModel) => Effect.Effect, + ) { + const model = yield* resolver + .resolveVideo(ref) + .pipe(Effect.mapError((error) => resolutionError(ref, "video", error))) + if (!model) return yield* missing(ref, "video") + return yield* run(model).pipe( + Effect.provideService(VideoClient.Service, videos), + Effect.mapError((error) => providerError(ref, error)), + ) + }) + + const videoResult = Effect.fnUntraced(function* (ref: Model.Ref, id: string) { + const response = yield* video(ref, (model) => ai.video.result(model, id)) + if (response.videos.length === 0) + return yield* new ProviderRequestError({ + providerID: ref.providerID, + reason: "provider", + message: `${ref.providerID}/${ref.id} returned no video`, + }) + return response.videos.map( + (file): VideoFile => ({ + mime: file.mediaType, + width: file.info?.width, + height: file.info?.height, + stream: file.stream().pipe( + Stream.provideService(RequestExecutor.Service, executor), + Stream.mapError((error) => providerError(ref, error)), + ), + }), + ) + }) + const credentials = (effect: Effect.Effect) => effect.pipe( Effect.catchTag( @@ -226,9 +308,24 @@ export const layer = Layer.effect( text: (input) => credentials(runText(input)), image: (input) => credentials(image(input)), decisions: (input) => credentials(decisions(input)), + video: { + // Submitting is paid and not idempotent, so it is never retried. + start: (input) => + credentials( + video(input.model, (model) => + ai.video.start({ + ...input, + model, + duration: input.duration === undefined ? undefined : (`${input.duration} seconds` as const), + }), + ), + ), + status: (model, id) => credentials(video(model, (resolved) => ai.video.status(resolved, id))), + result: (model, id) => credentials(videoResult(model, id)), + }, }) }), -).pipe(Layer.provide([ImageClient.layer, DecisionClient.layer])) +).pipe(Layer.provide([ImageClient.layer, DecisionClient.layer, VideoClient.layer])) // Provider metadata may hold undefined fields, which the JSON response schema rejects. function plainJson(value: Record): Record { diff --git a/packages/core/src/model-resolver.ts b/packages/core/src/model-resolver.ts index 75c622c0df2..ae4307a23d0 100644 --- a/packages/core/src/model-resolver.ts +++ b/packages/core/src/model-resolver.ts @@ -10,6 +10,8 @@ import { LanguageModel, ProviderConfigurationError, type ProviderPackage, + VideoModel, + VideoModelSchema, } from "@opencode/ai/effect" import { Auth, mergeTransport } from "@opencode/ai/route" import { Context, Effect, Layer, Schema, Struct } from "effect" @@ -152,6 +154,8 @@ export interface Interface { readonly resolveModel: (model: Info, variant?: VariantID) => Effect.Effect /** An enabled image model by ref, or undefined when no image model has that ref. */ readonly resolveImage: (ref: Ref) => Effect.Effect + /** An enabled video model by ref, or undefined when no video model has that ref. */ + readonly resolveVideo: (ref: Ref) => Effect.Effect /** An enabled decision model by ref, or undefined when no decision model has that ref. */ readonly resolveDecision: (ref: Ref) => Effect.Effect } @@ -351,6 +355,7 @@ const constructionError = (model: RuntimeInfo, cause: unknown) => const isImageModel = Schema.is(ImageModelSchema) const isDecisionModel = Schema.is(DecisionModelSchema) +const isVideoModel = Schema.is(VideoModelSchema) function prepareRuntimeModel(model: RuntimeInfo) { if (model.settings?.apiKey !== "") return model @@ -555,6 +560,9 @@ export const layer = Layer.effect( resolveImage: Effect.fn("ModelResolver.resolveImage")(function* (ref) { return yield* loadMedia(ref, "image", isImageModel) }), + resolveVideo: Effect.fn("ModelResolver.resolveVideo")(function* (ref) { + return yield* loadMedia(ref, "video", isVideoModel) + }), resolveDecision: Effect.fn("ModelResolver.resolveDecision")(function* (ref) { return yield* loadMedia(ref, "decision", isDecisionModel) }), diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 7d35d783cee..3b1e6ba6caa 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -133,7 +133,7 @@ const SourceProvider = Schema.Struct({ }) // The model types opencode keeps. Only chat models are offered for sessions; the others are listed on request. -const TYPES: readonly string[] = ["chat", "decision", "image"] +const TYPES: readonly string[] = ["chat", "decision", "image", "video"] const ContextCondition = Schema.Struct({ gt: Schema.optional(Schema.Finite), gte: Schema.optional(Schema.Finite) }) const decodeModel = Schema.decodeUnknownResult(SourceModel) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 80547e04f74..53176171e35 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -1,7 +1,7 @@ export * as Permission from "./permission.js" import { makeLocationNode } from "@opencode/util/effect/app-node" -import { Context, Deferred, Effect, Layer, Schema } from "effect" +import { Context, Deferred, Effect, Layer, Schema, Scope } from "effect" import { Permission } from "@opencode/schema/permission" import type { Tool } from "@opencode/schema/tool" import { Bus } from "./bus.js" @@ -157,6 +157,11 @@ export interface Interface { readonly get: (id: ID) => Effect.Effect readonly forSession: (sessionID: SessionSchema.ID) => Effect.Effect> readonly list: () => Effect.Effect> + /** + * Marks `call` as made by `parent`, such as a call inside a Code Mode program. It has an ID of its own but no row, + * so until the scope closes, requests naming it as their source show on `parent`'s row. + */ + readonly nested: (call: Tool.CallID, parent: Tool.CallID) => Effect.Effect } export class Service extends Context.Service()("@opencode/Permission") {} @@ -177,6 +182,7 @@ const layer = Layer.effect( const saved = yield* PermissionSaved.Service const hooks = yield* PluginHooks.Service const pending = new Map() + const parents = new Map() let closed = false const close = Effect.gen(function* () { @@ -218,6 +224,17 @@ const layer = Layer.effect( return rules.filter((rule) => Wildcard.match(input.action, rule.action)) } + const nested: Interface["nested"] = (call, parent) => + Effect.acquireRelease( + Effect.sync(() => void parents.set(call, parent)), + () => Effect.sync(() => void parents.delete(call)), + ) + + function row(source: AssertInput["source"]) { + const parent = source && parents.get(source.id) + return parent ? { ...source, id: parent } : source + } + const evaluateInput = Effect.fnUntraced(function* (input: AssertInput, requireConfiguredAllow = false) { const rules = yield* configured(input.sessionID, input.agent) if (denied(input, rules)) return { effect: "deny" as const, rules } @@ -234,7 +251,7 @@ const layer = Layer.effect( action: input.action, resources: input.resources, metadata: input.metadata, - source: input.source, + source: row(input.source), effect, experimental: { approved: input.resources.every((resource) => evaluate(input.action, resource, saved).effect === "allow"), @@ -266,7 +283,7 @@ const layer = Layer.effect( metadata: input.metadata && Object.fromEntries(Object.entries(input.metadata).filter(([, value]) => value !== undefined)), - source: input.source, + source: row(input.source), message, } } @@ -422,7 +439,7 @@ const layer = Layer.effect( return Array.from(pending.values(), (item) => item.request).filter((request) => request.sessionID === sessionID) }) - return Service.of({ ask, assert, assertNotDenied, allows, reply, get, forSession, list, close }) + return Service.of({ ask, assert, assertNotDenied, allows, reply, get, forSession, list, nested, close }) }), ) diff --git a/packages/core/src/project.ts b/packages/core/src/project.ts index 63a523b5fb0..5a6356926e5 100644 --- a/packages/core/src/project.ts +++ b/packages/core/src/project.ts @@ -309,7 +309,7 @@ const layer = Layer.effect( const cached = Effect.fnUntraced(function* (dir: string) { return yield* fs.readFileString(path.join(dir, "opencode")).pipe( Effect.map((value) => value.trim()), - Effect.map((value) => (value ? ID.make(value) : undefined)), + Effect.map((value) => (value && !/[\u0000-\u001f\u007f]/.test(value) ? ID.make(value) : undefined)), Effect.orElseSucceed(() => undefined), ) }) diff --git a/packages/core/src/ripgrep.ts b/packages/core/src/ripgrep.ts index 2055f7f6685..9e9dd4495dd 100644 --- a/packages/core/src/ripgrep.ts +++ b/packages/core/src/ripgrep.ts @@ -21,16 +21,19 @@ const ERROR_BYTES = 8 * 1024 const MAX_SUBMATCHES = 100 const MAX_LINE_CHARS = 2_000 +// rg reports data that is not valid UTF-8 as base64 `bytes` instead of `text`. +const RawData = Schema.Union([Schema.Struct({ text: Schema.String }), Schema.Struct({ bytes: Schema.String })]) + const RawMatch = Schema.Struct({ type: Schema.Literal("match"), data: Schema.Struct({ - path: Schema.Struct({ text: Schema.String }), - lines: Schema.Struct({ text: Schema.String }), + path: RawData, + lines: RawData, line_number: PositiveInt, absolute_offset: NonNegativeInt, submatches: Schema.Array( Schema.Struct({ - match: Schema.Struct({ text: Schema.String }), + match: RawData, start: NonNegativeInt, end: NonNegativeInt, }), @@ -39,7 +42,8 @@ const RawMatch = Schema.Struct({ }) const decodeJsonRecord = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)) -type RawMatchData = (typeof RawMatch.Type)["data"] +const rawText = (data: typeof RawData.Type) => + "text" in data ? data.text : Buffer.from(data.bytes, "base64").toString("utf8") export class Error extends Schema.TaggedError()("Ripgrep.Error", { message: Schema.String, @@ -226,7 +230,7 @@ const layer = Layer.effect( onItem: input.onEntry, }).pipe(Effect.catchTag("Ripgrep.InvalidPatternError", (cause) => Effect.fail(failure(cause.message, cause)))), grep: (input) => - run({ + run({ ...input, args: [ "--no-config", @@ -248,17 +252,23 @@ const layer = Layer.effect( if (!json || typeof json !== "object" || !("type" in json) || json.type !== "match") return Effect.undefined return Schema.decodeUnknownEffect(RawMatch)(json).pipe( - Effect.map((match) => ({ - ...match.data, - lines: { - text: - match.data.lines.text.length > MAX_LINE_CHARS - ? TextBoundary.head(match.data.lines.text, MAX_LINE_CHARS) + "..." - : match.data.lines.text, - }, - path: { text: normalizePath(match.data.path.text) }, - submatches: match.data.submatches.slice(0, MAX_SUBMATCHES), - })), + Effect.map((match) => { + const lines = rawText(match.data.lines) + return { + ...match.data, + lines: { + text: + lines.length > MAX_LINE_CHARS + ? TextBoundary.head(lines, MAX_LINE_CHARS) + "..." + : lines, + }, + path: { text: normalizePath(rawText(match.data.path)) }, + submatches: match.data.submatches.slice(0, MAX_SUBMATCHES).map((submatch) => ({ + ...submatch, + match: { text: rawText(submatch.match) }, + })), + } + }), Effect.mapError((cause) => failure("Invalid ripgrep match output", cause)), ) }), diff --git a/packages/core/src/schedule/check.ts b/packages/core/src/schedule/check.ts index 754eadd4aa4..2b01d51d74d 100644 --- a/packages/core/src/schedule/check.ts +++ b/packages/core/src/schedule/check.ts @@ -30,6 +30,8 @@ const CODE_LIMITS: CodeMode.ExecutionLimits = { } const FORBIDDEN_CODE_TOOLS = new Set([ + // Shell conditions approve the parsed commands; a code condition would approve any command it runs. + "shell", "opencode.schedule_create", "opencode.schedule_pause", "opencode.schedule_resume", diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index e1df47e7eaf..62ff2dfd84f 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -23,7 +23,6 @@ import { Agent } from "../agent.js" import { Bus } from "../bus.js" import { Database } from "../database/database.js" import { llmClient } from "../effect/app-node-platform.js" -import { Instructions } from "../instructions/index.js" import { Model } from "../model.js" import { State } from "../state.js" import { Token } from "../util/token.js" @@ -46,7 +45,7 @@ export type Settings = { /** Tokens of recent conversation kept verbatim beside the summary. */ keep: number /** Summarize in the background as the context nears the threshold, so automatic compaction can swap it in. */ - precompute: boolean + background: boolean } export type Editor = { @@ -112,8 +111,6 @@ type Background = { type Precomputed = { readonly firstID: SessionMessage.ID | undefined readonly keepID: SessionMessage.ID - readonly model: SessionContext.Loaded["model"]["ref"] - readonly initial: string /** The longest tail since `keepID` that compaction still accepts beside this summary. */ readonly tailLimit: number /** Background summaries that failed since the last compaction, this one included once it has. */ @@ -266,7 +263,7 @@ export const layer = Layer.effect( const state = State.create({ name: "session-compaction", - initial: () => ({ auto: true, keep: 15_000, precompute: false }), + initial: () => ({ auto: true, keep: 15_000, background: true }), editor: (settings) => ({ configure: (update) => { Object.assign(settings, update) @@ -324,7 +321,7 @@ export const layer = Layer.effect( // opens here, before any wait, so a background summary still being written shows as a running compaction. if (trigger.reason !== "manual") yield* bus.publish(SessionEvent.Compaction.Started, { sessionID: context.session.id, reason: "auto" }) - const swapped = held ? yield* usePrecomputed(selected, held, budget, settings) : undefined + const swapped = held ? yield* usePrecomputed(selected, held, budget, native) : undefined const compaction = swapped ? Effect.succeed(swapped) : native @@ -353,13 +350,13 @@ export const layer = Layer.effect( given?: Estimate, ) { const settings = state.get() - if (!settings.precompute || !settings.auto) return + if (!settings.background || !settings.auto) return const context = yield* load if (context.model.compaction?.type === "native") return + // An unknown window has an infinite ceiling, which this never reaches. Past the ceiling it still starts: at the + // end of a turn, the next prompt then swaps it in instead of waiting for a summary. const ceiling = calculateCeiling(context.model.limit, settings.buffer) - if (!Number.isFinite(ceiling)) return const estimate = given ?? estimatePrompt(context) - if (due(context, ceiling, estimate)) return const first = context.messages.find((message) => hasMeasuredPrompt(message, context.model.ref)) const cycleStart = first?.type === "assistant" && first.tokens ? promptTokens(first.tokens) : 0 if (total(estimate) < ceiling - Math.min(PRECOMPUTE_LEAD, (ceiling - cycleStart) / 2)) return @@ -397,8 +394,6 @@ export const layer = Layer.effect( precomputed.set(sessionID, { firstID: context.messages[0]?.id, keepID: anchor.id, - model: context.model.ref, - initial: Instructions.join(context.initial), tailLimit: tailLimit(model.cap), failures, usage, @@ -409,23 +404,18 @@ export const layer = Layer.effect( /** * The held summary plus everything since it, kept verbatim, when it still describes this conversation and that * tail is short. Waits for a summary still being written. Undefined, after stopping the background work, when it - * cannot be used; compaction then summarizes as usual. + * cannot be used; compaction then summarizes as usual. A summary is plain text, so it serves any model, but a + * session that switched to native compaction compacts natively. */ const usePrecomputed = Effect.fnUntraced(function* ( trigger: Trigger, held: Precomputed, budget: number, - settings: Settings, + native: boolean, ): Effect.fn.Return { const context = trigger.context const index = heldIndex(held, context) - const usable = - settings.precompute && - trigger.reason !== "overflow" && - context.model.compaction?.type !== "native" && - index >= 0 && - tailTokens(context, index) <= tailLimit(budget) - if (!usable) { + if (native || index < 0 || tailTokens(context, index) > tailLimit(budget)) { yield* Fiber.interrupt(held.fiber) return undefined } @@ -966,12 +956,10 @@ export const node = makeLocationNode({ /** * Where the messages kept beside a held summary start, or -1 when the summary no longer describes this - * conversation: a compaction or revert since replaced its start, or the model or instructions changed. + * conversation: a compaction or revert since replaced its start. */ const heldIndex = (held: Precomputed, context: SessionContext.Loaded) => { - if (held.firstID !== context.messages[0]?.id || held.initial !== Instructions.join(context.initial)) return -1 - if (held.model.providerID !== context.model.ref.providerID || held.model.id !== context.model.ref.id) return -1 - if (held.model.variant !== context.model.ref.variant) return -1 + if (held.firstID !== context.messages[0]?.id) return -1 return context.messages.findIndex((message) => message.id === held.keepID) } diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index e88aa73b0af..4f4327dba1e 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -180,8 +180,19 @@ const layer = Layer.effect( } }) - const run = (tool: Tool.Info, name: string, input: unknown, context: Tool.Context) => - beforeExecute(name, input, context).pipe(Effect.flatMap((event) => executeTool(tool, name, event.input, context))) + // A plugin may rename a call in a Code Mode program, as it may a direct call, to another of the program's tools. + const run = Effect.fnUntraced(function* ( + tools: ReadonlyMap, + tool: Tool.Info, + name: string, + input: unknown, + context: Tool.Context, + ) { + const event = yield* beforeExecute(name, input, context) + const selected = event.tool === name ? tool : tools.get(event.tool) + if (!selected) return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` }) + return yield* executeTool(selected, event.tool, event.input, context) + }) // Keyed by the visible tool names. Sessions whose agents see different tool sets, such as one denied the browser // and one not, alternate steps; with one entry each step rebuilt a large catalog (about 90 ms for 3,000 tools). @@ -277,7 +288,7 @@ const layer = Layer.effect( const codeModeTool = codeModeEnabled ? CodeModeTool.create( codeModeInventory, - (name, tool, input, context) => run(tool, name, input, context), + (name, tool, input, context) => run(codeModeInventory.tools, tool, name, input, context), permission, ) : undefined @@ -361,7 +372,7 @@ const layer = Layer.effect( ...input.context, id: Tool.CallID.make(`call_${input.context.messageID}_${index}`), } - return yield* run(tool, name, toolInput, context) + return yield* run(tools, tool, name, toolInput, context) }), ) }), diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 0fa456f60a6..d4f8db5598f 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -7,7 +7,10 @@ import type { ShellCreateBefore } from "@opencode/plugin/effect/shell" import type { Shell as ShellSchema } from "@opencode/schema/shell" import type { Tool } from "@opencode/schema/tool" import { Clock, Deferred, Effect, Fiber, Option, Schema, Struct } from "effect" +import { Config } from "../../config.js" +import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" import { Environment } from "../../environment/index.js" +import { Flag } from "../../flag.js" import { Job } from "../../job.js" import { FileAccess } from "../../file-access.js" import { Permission } from "../../permission.js" @@ -280,6 +283,11 @@ export const Plugin = { const shellSelect = yield* ShellSelect.Service const compatibleShell = shellSelect.resolve({ priority: "compat" }) const permission = yield* Permission.Service + const config = yield* Config.Service + // Internal plugins are not re-run on config changes, so reload the tool transform instead. + const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.tool.reload()) + const flags = yield* Flag.Service + const fullCodeMode = () => flags.resolve(loaded.entries).full_codemode.enabled const prepare = Effect.fn("ShellTool.prepare")(function* (invocation: ShellCreateBefore, context: Tool.Context) { const target = yield* access.resolve({ path: invocation.cwd, kind: "directory" }) @@ -346,7 +354,8 @@ export const Plugin = { .transform((editor) => editor.add({ name, - options: { codemode: false }, + // With full_codemode, shell is called as `tools.shell` inside `execute` instead of as a direct tool. + options: { codemode: fullCodeMode() }, description: description(), input: Input, output: StructuredOutput, diff --git a/packages/core/src/video-generation.ts b/packages/core/src/video-generation.ts new file mode 100644 index 00000000000..3ded463ab4e --- /dev/null +++ b/packages/core/src/video-generation.ts @@ -0,0 +1,192 @@ +export * as VideoGeneration from "./video-generation.js" + +import { Media } from "@opencode/ai/effect" +import { VideoID, type VideoJob, type VideoRequest, type VideoRunning } from "@opencode/schema/generate" +import type { Model } from "@opencode/schema/model" +import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { Global } from "@opencode/util/global" +import { Context, Deferred, Duration, Effect, Exit, FiberMap, Layer, Option, Schedule, Schema } from "effect" +import { BlobStore } from "./blob-store.js" +import { Generate } from "./generate.js" +import { Location } from "./location.js" +import { LocationServiceMap } from "./location-service-map.js" +import { AbsolutePath } from "./schema.js" + +export class NotFoundError extends Schema.TaggedError()("VideoGeneration.NotFoundError", { + id: Schema.String, + message: Schema.String, +}) {} + +const INTERVAL = Duration.seconds(5) +const DEADLINE = Duration.hours(2) + +export interface Interface { + /** Returns once the provider accepted the job; the server then polls it and stores the video as a blob. */ + readonly start: (input: VideoRequest) => Effect.Effect + readonly get: (id: VideoID) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/VideoGeneration") {} + +/** + * Running and failed jobs live in memory only: a restart forgets them, and a running job's videos are never collected. + * A finished job is read from its blobs, so it outlives a restart until they expire. + * + * TODO: record jobs durably, so a restart resumes polling them. + */ +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const global = yield* Global.Service + const locations = yield* LocationServiceMap.Service + const blobs = yield* BlobStore.Service + // The same base-config Location the generate routes use. + const base = locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) })) + const fibers = yield* FiberMap.make() + const jobs = new Map() + + const generate = (run: (generate: Generate.Interface) => Effect.Effect) => + Generate.Service.pipe( + Effect.flatMap(run), + Effect.provide(base), + Effect.catchTag("FileSystem.DirectoryNotFoundError", (error) => + Effect.fail(new Generate.UnavailableError({ message: `Location not found: ${error.directory}` })), + ), + ) + + // Each video becomes blob `_`, so a restarted server finds them from the job's ID alone. + const blobID = (id: VideoID, index: number) => BlobStore.ID.make(`${id}_${index}`) + + const store = Effect.fnUntraced(function* (id: VideoID, model: Model.Ref, providerID: string) { + const videos = yield* generate((service) => service.video.result(model, providerID)) + const stored = yield* Effect.forEach(videos, (video, index) => + blobs.write(blobID(id, index), video.stream).pipe( + Effect.flatMap((blob) => + blob.bytes > 0 + ? Effect.succeed(blob) + : Effect.fail( + new Generate.ProviderRequestError({ + providerID: model.providerID, + reason: "provider", + message: "The provider returned an empty video", + }), + ), + ), + ), + ).pipe( + // All or nothing: a job never reports only some of its videos. + Effect.onError(() => Effect.forEach(videos, (_, index) => blobs.remove(blobID(id, index)), { discard: true })), + ) + return { id, status: "completed", blobs: stored } satisfies VideoJob + }) + + // A finished job outlives a restart through its blobs: `_0`, `_1`, … up to the first missing one. + const stored = (id: VideoID): Effect.Effect => + Effect.gen(function* () { + const found: BlobStore.Info[] = [] + while (true) { + const blob = yield* blobs.read(blobID(id, found.length)).pipe(Effect.option) + if (Option.isNone(blob)) return found + found.push({ + id: blob.value.id, + mime: blob.value.mime, + bytes: blob.value.bytes, + expiresAt: blob.value.expiresAt, + }) + } + }) + + // A status read that fails is retried at the next interval: the provider may be briefly unavailable. + const poll = (id: VideoID, model: Model.Ref, providerID: string) => + generate((service) => service.video.status(model, providerID)).pipe( + Effect.map((status) => (status.status === "running" ? undefined : status)), + Effect.catch((error) => + Effect.logWarning("video status read failed", { id, error: error.message }).pipe(Effect.as(undefined)), + ), + Effect.repeat({ schedule: Schedule.spaced(INTERVAL), until: (status) => status !== undefined }), + Effect.timeoutOption(DEADLINE), + ) + + const settle = Effect.fnUntraced(function* (id: VideoID, model: Model.Ref, providerID: string) { + const settled = yield* poll(id, model, providerID) + if (Option.isNone(settled) || settled.value === undefined) + return { + id, + status: "error", + reason: "unknown", + error: `The provider had no result ${Duration.format(DEADLINE)} after submission`, + } satisfies VideoJob + if (settled.value.status === "error") { + const reason = settled.value.reason ?? "failed" + return { id, status: "error", reason, error: `The provider reported the job as ${reason}` } satisfies VideoJob + } + return yield* store(id, model, providerID).pipe( + Effect.retry({ times: 2, schedule: Schedule.exponential("1 second") }), + Effect.catch((error) => + Effect.succeed({ id, status: "error", reason: "failed", error: error.message } satisfies VideoJob), + ), + ) + }) + + const start = Effect.fn("VideoGeneration.start")(function* (input: VideoRequest) { + const id = VideoID.create() + const submitted = yield* Deferred.make() + // Runs in the server's fibers, so a client that disconnects can't interrupt a paid submission midway. + yield* FiberMap.run( + fibers, + id, + Effect.gen(function* () { + const started = yield* generate((service) => + service.video.start({ + ...input, + start: input.start && Media.image(Media.base64(input.start.data, input.start.mime)), + end: input.end && Media.image(Media.base64(input.end.data, input.end.mime)), + references: input.references?.map((file) => Media.base64(file.data, file.mime)), + }), + ) + const running = { id, status: "running" } as const + jobs.set(id, running) + yield* Deferred.succeed(submitted, running) + const settled = yield* settle(id, input.model, started.id) + // A finished job's blobs are its record from here on. + if (settled.status === "completed") return jobs.delete(id) + // A failure is kept as long as a blob would be, so the map holds at most one retention's worth of jobs. + jobs.set(id, settled) + yield* Effect.sleep(BlobStore.RETENTION) + jobs.delete(id) + }).pipe( + // Once the submission succeeded, this does nothing. + Effect.onExit((exit) => (Exit.isFailure(exit) ? Deferred.failCause(submitted, exit.cause) : Effect.void)), + Effect.ignore, + ), + ) + return yield* Deferred.await(submitted) + }) + + const get = Effect.fn("VideoGeneration.get")(function* (id: VideoID) { + const job = jobs.get(id) + if (job) return job + const found = yield* stored(id) + if (found.length === 0) return yield* new NotFoundError({ id, message: `Video not found: ${id}` }) + return { id, status: "completed", blobs: found } satisfies VideoJob + }) + + return Service.of({ start, get }) + }), +) + +/** Videos are stored as blobs, which need a local disk that Durable Objects don't have. */ +export const unsupportedLayer = Layer.succeed( + Service, + Service.of({ + start: () => + Effect.fail(new Generate.UnavailableError({ message: "Video generation is not supported in this runtime" })), + get: (id) => Effect.fail(new NotFoundError({ id, message: `Video not found: ${id}` })), + }), +) + +export const node = makeGlobalNode({ + service: Service, + layer, + deps: [BlobStore.node, Global.node, LocationServiceMap.node], +}) diff --git a/packages/core/test/config/normalization.test.ts b/packages/core/test/config/normalization.test.ts index aa32eea379f..59ee7b46d0f 100644 --- a/packages/core/test/config/normalization.test.ts +++ b/packages/core/test/config/normalization.test.ts @@ -567,7 +567,6 @@ describe("ConfigNormalize", () => { experimental: { portable_shell_scanner: true, todo: true, - background_compaction: true, media_blob: true, part_rows: true, image_generate: { model: "openai/gpt-image-2" }, @@ -580,7 +579,6 @@ describe("ConfigNormalize", () => { experimental: { portable_shell_scanner: true, todo: true, - background_compaction: true, media_blob: true, part_rows: true, image_generate: { model: { providerID: "openai", model: "gpt-image-2" } }, diff --git a/packages/core/test/lib/permission.ts b/packages/core/test/lib/permission.ts index 447c778da8b..2b6cfeeb5ee 100644 --- a/packages/core/test/lib/permission.ts +++ b/packages/core/test/lib/permission.ts @@ -2,7 +2,7 @@ import { Permission } from "@opencode/core/permission" import { Effect, Layer } from "effect" export const permissionLayer = (overrides: Partial = {}) => - Layer.mock(Permission.Service, { close: Effect.void, ...overrides }) + Layer.mock(Permission.Service, { close: Effect.void, nested: () => Effect.void, ...overrides }) export const permissionService = (overrides: Partial = {}) => Effect.runSync( diff --git a/packages/core/test/mcp-attach.test.ts b/packages/core/test/mcp-attach.test.ts index 44825d0147f..51094d629af 100644 --- a/packages/core/test/mcp-attach.test.ts +++ b/packages/core/test/mcp-attach.test.ts @@ -21,6 +21,7 @@ import { hostEnvironmentLayer } from "./fixture/environment" import { tempLocationLayer } from "./fixture/location" import { testEffect } from "./lib/effect" import { imagePassthrough } from "./lib/image" +import { permissionLayer } from "./lib/permission" import { executeTool, toolIdentity } from "./lib/tool" // Attached clients are never OAuth integrations. @@ -48,7 +49,7 @@ const it = testEffect( }), ), Credential.node.replace(Layer.mock(Credential.Service, {})), - Permission.node.replace(Layer.mock(Permission.Service, { assert: () => Effect.void })), + Permission.node.replace(permissionLayer({ assert: () => Effect.void })), Image.node.replace(imagePassthrough), ]), ) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index e87f03e6aee..a92da76daa6 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -77,6 +77,7 @@ import { isRecord } from "@opencode/util/record" import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" import { advance, drain } from "./lib/clock" import { testEffect } from "./lib/effect" +import { permissionLayer } from "./lib/permission" import { registerIntegrationPolicy, setOrganizationPolicy } from "./fixture/policy" import { location } from "./fixture/location" import { host } from "./plugin/host" @@ -619,7 +620,7 @@ const mcp = Layer.mock(Mcp.Service, { } satisfies Mcp.ToolResult }), }) -const permissions = Layer.mock(Permission.Service, { +const permissions = permissionLayer({ assert: (input) => Effect.gen(function* () { if (!assertion) return yield* Effect.die("Permission test is not initialized") @@ -1787,7 +1788,8 @@ it.live("discovers and reads MCP resources through Code Mode", () => metadata: { server: "resources", uri: "docs://readme" }, sessionID, agent: toolIdentity.agent, - source: { type: "tool", messageID: toolIdentity.messageID, id: "call_resource" }, + // The call's own ID. The real service shows the request on the execute call's row. + source: { type: "tool", messageID: toolIdentity.messageID, id: expect.not.stringMatching(/^call_resource$/) }, }) server.state.contents = [{ uri: "docs://readme", text: "line\n".repeat(20_000), mimeType: "text/plain" }] @@ -2683,7 +2685,7 @@ testEffect(Layer.empty).live("preserves plugin transforms through MCP catalog up Effect.provide( Layer.fresh( AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [ - ...toolNodeReplacements(Layer.mock(Permission.Service, { assert: () => Effect.void })), + ...toolNodeReplacements(permissionLayer({ assert: () => Effect.void })), Mcp.node.replace( Layer.mock(Mcp.Service, { awaitStartup: () => Effect.void, @@ -2734,7 +2736,7 @@ testEffect(Layer.empty).effect("coalesces queued MCP tool notifications after in }).pipe( Effect.provide( AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [ - ...toolNodeReplacements(Layer.mock(Permission.Service, { assert: () => Effect.void })), + ...toolNodeReplacements(permissionLayer({ assert: () => Effect.void })), Mcp.node.replace( Layer.mock(Mcp.Service, { awaitStartup: () => Effect.void, @@ -3069,7 +3071,7 @@ it.effect("waits for permission before calling an MCP tool", () => source: { type: "tool", messageID: toolIdentity.messageID, - id: "call_mcp_permission", + id: expect.not.stringMatching(/^call_mcp_permission$/), }, }) expect(calls).toBe(0) diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 31897029c7d..2746756b78e 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -721,7 +721,7 @@ describe("ModelsDev Service", () => { ) const [beta] = yield* ModelsDev.Service.use((service) => service.get()).pipe(Effect.provide(layer)) expect(urls).toEqual([ - "https://mirror.example/experimental/v2.0/api.json?type=chat,decision,image", + "https://mirror.example/experimental/v2.0/api.json?type=chat,decision,image,video", "https://mirror.example/api.json", ]) expect(beta?.models.map((model) => model.id)).toEqual([Model.ID.make("beta-1")]) @@ -802,7 +802,7 @@ describe("ModelsDev Service", () => { Effect.provide(buildLayer(state, cache, { url: "", fetch: true, snapshot: false })), ) expect((yield* Ref.get(state)).calls[0]?.url).toBe( - "https://models.opencode.ai/experimental/v2.0/api.json?type=chat,decision,image", + "https://models.opencode.ai/experimental/v2.0/api.json?type=chat,decision,image,video", ) }), ) diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index b2d2fdf744f..9cfa86b0382 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -17,6 +17,7 @@ import { Session } from "@opencode/core/session" import { SessionTable } from "@opencode/core/session/sql" import { SessionStore } from "@opencode/core/session/store" import { ShellParse } from "@opencode/core/shell/parse" +import { Tool } from "@opencode/core/tool" import { eq } from "drizzle-orm" import { location } from "./fixture/location" import { testEffect } from "./lib/effect" @@ -360,6 +361,21 @@ describe("Permission", () => { }), ) + it.effect("shows a nested call's request on its parent's row until the scope closes", () => + Effect.gen(function* () { + yield* setup() + const service = yield* Permission.Service + const source = { type: "tool" as const, messageID: "msg_test", id: "call_child" } + const ask = (id: string) => service.ask(assertion({ id: Permission.ID.create(id), source })) + yield* service + .nested(Tool.CallID.make("call_child"), Tool.CallID.make("call_parent")) + .pipe(Effect.andThen(ask("per_nested")), Effect.scoped) + yield* ask("per_after") + expect((yield* service.get(Permission.ID.create("per_nested")))?.source).toEqual({ ...source, id: "call_parent" }) + expect((yield* service.get(Permission.ID.create("per_after")))?.source).toEqual(source) + }), + ) + it.effect("drops undefined metadata values so pending requests encode as JSON", () => Effect.gen(function* () { yield* setup() diff --git a/packages/core/test/plugin/fixture.ts b/packages/core/test/plugin/fixture.ts index 269afcfd81f..a8d6dd316ca 100644 --- a/packages/core/test/plugin/fixture.ts +++ b/packages/core/test/plugin/fixture.ts @@ -68,6 +68,11 @@ const generateLayer = Layer.succeed( text: () => Effect.succeed(""), image: () => Effect.die("unused"), decisions: () => Effect.die("unused"), + video: { + start: () => Effect.die("unused"), + status: () => Effect.die("unused"), + result: () => Effect.die("unused"), + }, }), ) @@ -85,6 +90,7 @@ const permissionLayer = Layer.succeed( get: () => Effect.succeed(undefined), forSession: () => Effect.succeed([]), list: () => Effect.succeed([]), + nested: () => Effect.void, }), ) diff --git a/packages/core/test/plugin/permission-assert.test.ts b/packages/core/test/plugin/permission-assert.test.ts index 3a4d2baa2bc..17079e78c37 100644 --- a/packages/core/test/plugin/permission-assert.test.ts +++ b/packages/core/test/plugin/permission-assert.test.ts @@ -32,6 +32,7 @@ const permission = Layer.succeed( get: () => Effect.succeed(undefined), forSession: () => Effect.succeed([]), list: () => Effect.succeed([]), + nested: () => Effect.void, }), ) diff --git a/packages/core/test/project.test.ts b/packages/core/test/project.test.ts index c2dd1b98f90..7825e05e448 100644 --- a/packages/core/test/project.test.ts +++ b/packages/core/test/project.test.ts @@ -478,10 +478,11 @@ describe("Project.resolve", () => { }), ) - it.live("falls back to root commit when origin is missing", () => + it.live("falls back to root commit when origin is missing and the cached id is corrupt", () => Effect.gen(function* () { const tmp = yield* tmpdirScoped() yield* Effect.promise(() => initRepo(tmp.path, { commit: true })) + yield* Effect.promise(() => Bun.write(path.join(tmp.path, ".git", "opencode"), "\u0000".repeat(40))) const project = yield* Project.Service const result = yield* project.resolve(abs(tmp.path)) diff --git a/packages/core/test/ripgrep.test.ts b/packages/core/test/ripgrep.test.ts index e0ebd2cc80e..02fcaebc323 100644 --- a/packages/core/test/ripgrep.test.ts +++ b/packages/core/test/ripgrep.test.ts @@ -94,6 +94,24 @@ describe("Ripgrep", () => { ), ) + it.live("greps lines that are not valid UTF-8", () => + withTempDir((tmp) => + Effect.gen(function* () { + yield* Effect.promise(() => fs.writeFile(path.join(tmp.path, "utf8.txt"), "needle\n")) + yield* Effect.promise(() => + fs.writeFile(path.join(tmp.path, "latin1.txt"), Buffer.from("needle café\n", "latin1")), + ) + + const ripgrep = yield* Ripgrep.Service + const result = yield* ripgrep.grep({ cwd: tmp.path, pattern: "needle", limit: 10 }) + expect(result.map((match) => [match.entry.path, match.text, match.submatches[0]?.text]).sort()).toEqual([ + [RelativePath.make("latin1.txt"), "needle caf\uFFFD\n", "needle"], + [RelativePath.make("utf8.txt"), "needle\n", "needle"], + ]) + }), + ), + ) + it.live("keeps ignored files out of catch-all find results", () => withTempDir((tmp) => Effect.gen(function* () { diff --git a/packages/core/test/session-compaction.test.ts b/packages/core/test/session-compaction.test.ts index 1b541314993..400768df67c 100644 --- a/packages/core/test/session-compaction.test.ts +++ b/packages/core/test/session-compaction.test.ts @@ -1025,12 +1025,6 @@ const precomputeHistory = () => { return { near: [...near, anchor], due, anchor } } -const enablePrecompute = Effect.gen(function* () { - const compaction = yield* SessionCompaction.Service - yield* compaction.transform((editor) => editor.configure({ precompute: true })) - return compaction -}) - const summaryWindow = resolved.limit.context const summaryBuffer = summaryWindow / 8 const summaryCeiling = summaryWindow - summaryBuffer @@ -1050,7 +1044,7 @@ const summaryFixture = Effect.fnUntraced(function* (messages: readonly SessionMe }, } const compaction = yield* SessionCompaction.Service - yield* compaction.transform((editor) => editor.configure({ buffer: summaryBuffer, precompute: true })) + yield* compaction.transform((editor) => editor.configure({ buffer: summaryBuffer })) return { context, compaction, @@ -1211,10 +1205,11 @@ it.effect("summary measured recovery reuses usage only for the matching agent", }), ) -it.effect("background summaries stay off unless enabled", () => +it.effect("background summaries stay off when disabled", () => Effect.gen(function* () { requests = [] const compaction = yield* SessionCompaction.Service + yield* compaction.transform((editor) => editor.configure({ background: false })) const session = yield* insertSession(Session.ID.make("ses_precompute_off")) const history = precomputeHistory() @@ -1232,7 +1227,7 @@ it.effect("automatic compaction swaps in the background summary without another requests = [] const db = (yield* Database.Service).db const store = yield* SessionStore.Service - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const sessionID = Session.ID.make("ses_precompute_swap") const session = yield* insertSession(sessionID) const history = precomputeHistory() @@ -1284,7 +1279,7 @@ it.effect("automatic compaction waits for a background summary still being writt const release = yield* Deferred.make() beforeResponse = Deferred.await(release) const bus = yield* Bus.Service - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_join")) const history = precomputeHistory() const started = yield* bus @@ -1309,7 +1304,7 @@ it.effect("automatic compaction waits for a background summary still being writt it.effect("a model switch waits for the new model's first response before summarizing in the background", () => Effect.gen(function* () { requests = [] - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_switch")) const history = precomputeHistory() const switched = (messages: readonly SessionMessage.Info[]) => ({ @@ -1330,7 +1325,7 @@ it.effect("a model switch waits for the new model's first response before summar it.effect("a background summary that fell too far behind is replaced from a newer response", () => Effect.gen(function* () { requests = [] - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_behind")) const history = precomputeHistory() // About 75k tokens arrived after the summarized prefix, past the 68k (40% of the 170k budget) that may stay @@ -1354,7 +1349,7 @@ it.effect("a background summary that fell too far behind is replaced from a newe it.effect("a failed background summary is retried from a newer response, then left until compaction", () => Effect.gen(function* () { requests = [] - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_failed")) const history = precomputeHistory() const later = [...history.near, textUser("Third question"), measured("Third answer", 160_000)] @@ -1386,35 +1381,87 @@ it.effect("a failed background summary is retried from a newer response, then le it.effect("compaction summarizes as usual when the background summary no longer fits the conversation", () => Effect.gen(function* () { - const compaction = yield* enablePrecompute + requests = [] + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_stale")) const history = precomputeHistory() - const compactAfterPrecompute = (due: readonly SessionMessage.Info[], context = loaded(session, due)) => - Effect.gen(function* () { - requests = [] - yield* compaction.precompute(Effect.succeed(loaded(session, history.near))) - expect(yield* compaction.compact({ reason: "auto", context })).toEqual({ status: "completed" }) - // The background summary is stopped; the summary that is kept covers the whole conversation. - return JSON.stringify(requests.at(-1)?.messages) - }) - // About 75k tokens arrived after the summarized prefix, past the 68k that may stay verbatim beside it. const burst = [...history.near, textUser("x".repeat(300_000)), measured("Burst handled", 182_000)] - expect(yield* compactAfterPrecompute(burst)).toContain("Burst handled") - // A different model would replay a summary written for the previous one. + yield* compaction.precompute(Effect.succeed(loaded(session, history.near))) + expect(yield* compaction.compact({ reason: "auto", context: loaded(session, burst) })).toEqual({ + status: "completed", + }) + // The background summary is stopped; the summary that is kept covers the whole conversation. + expect(JSON.stringify(requests.at(-1)?.messages)).toContain("Burst handled") + }), +) + +// The summary is plain text, so it still serves after a model switch, and after the compaction agent's own model +// stands in for the session's. +it.effect("a background summary is swapped in for a different model", () => + Effect.gen(function* () { + requests = [] + const compaction = yield* SessionCompaction.Service + const session = yield* insertSession(Session.ID.make("ses_precompute_other_model")) + const history = precomputeHistory() + + yield* compaction.precompute(Effect.succeed(loaded(session, history.near))) const switched = { ...loaded(session, history.due), model: { ...resolved, ref: { ...resolved.ref, id: Model.ID.make("other") } }, } - expect(yield* compactAfterPrecompute(history.due, switched)).toContain("Third answer") + expect(yield* compaction.compact({ reason: "auto", context: switched })).toEqual({ status: "completed" }) + + // The one request ended before the response the summary started from. + expect(requests).toHaveLength(1) + expect(JSON.stringify(requests[0].messages)).not.toContain("Second answer") + }), +) + +it.effect("an overflow compaction swaps in the background summary", () => + Effect.gen(function* () { + requests = [] + const compaction = yield* SessionCompaction.Service + const session = yield* insertSession(Session.ID.make("ses_precompute_overflow")) + const history = precomputeHistory() + + yield* compaction.precompute(Effect.succeed(loaded(session, history.near))) + expect(yield* compaction.compact({ reason: "overflow", context: loaded(session, history.due) })).toEqual({ + status: "completed", + }) + + // The one request ended before the response the summary started from. + expect(requests).toHaveLength(1) + expect(JSON.stringify(requests[0].messages)).not.toContain("Second answer") + }), +) + +it.effect("a background summary starts when the latest response already passed the threshold", () => + Effect.gen(function* () { + requests = [] + const compaction = yield* SessionCompaction.Service + const session = yield* insertSession(Session.ID.make("ses_precompute_past")) + const history = precomputeHistory() + + // The turn ended past the threshold; the summary is written while the session is idle. + yield* compaction.precompute(Effect.succeed(loaded(session, history.due))) + const next = [...history.due, textUser("Fourth question")] + expect(yield* compaction.compact({ reason: "auto", context: loaded(session, next) })).toEqual({ + status: "completed", + }) + + expect(requests).toHaveLength(1) + const summarized = JSON.stringify(requests[0].messages) + expect(summarized).toContain("Third question") + expect(summarized).not.toContain("Third answer") }), ) it.effect("a background summary keeps a tail longer than twice keep while it stays under 40% of the budget", () => Effect.gen(function* () { requests = [] - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_long_tail")) const history = precomputeHistory() // About 35k tokens arrived after the summarized prefix: more than twice keep, less than 68k. @@ -1438,7 +1485,7 @@ it.effect("a background summary keeps a tail longer than twice keep while it sta it.effect("a background summary starts a fixed lead before the threshold, not at a share of it", () => Effect.gen(function* () { requests = [] - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_lead")) // A 1M window compacts at 850k, so a background summary starts 60k before that, at 790k. const large = (messages: readonly SessionMessage.Info[]) => ({ @@ -1465,7 +1512,7 @@ it.effect("a background summary starts a fixed lead before the threshold, not at it.effect("a background summary starts on a window whose threshold is under 64k", () => Effect.gen(function* () { requests = [] - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const session = yield* insertSession(Session.ID.make("ses_precompute_small")) // A 64k window compacts at 48k. The first response measured 20k, so half that room, 14k, sets the start at 34k. const small = (messages: readonly SessionMessage.Info[]) => ({ @@ -1490,7 +1537,7 @@ it.effect("a background summary starts on a window whose threshold is under 64k" it.effect("a background summary waits for a response whose prompt is still cached", () => Effect.gen(function* () { - const compaction = yield* enablePrecompute + const compaction = yield* SessionCompaction.Service const history = precomputeHistory() const later = (created: number) => [ ...history.near, diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index be3f89a8ff3..e39df55267f 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -2923,6 +2923,10 @@ describe("SessionRunnerLLM", () => { scenario(`preserves the session request prefix during ${reason} compaction (${route.id})`, function* (s) { const agents = yield* Agent.Service const hooks = yield* PluginHooks.Service + const compaction = yield* SessionCompaction.Service + // The idle step past the threshold would start a background summary, which keeps the next prompt verbatim + // instead of summarizing it; this covers the summary written when compaction is due. + yield* compaction.transform((editor) => editor.configure({ background: false })) const agentID = Agent.ID.make("reviewer") const variant = Model.VariantID.make("test-variant") s.currentModel = LanguageModel.make({ diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index a071e8692b8..8de5fc3d8ac 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -418,6 +418,29 @@ test("execute supports callable namespace tools", async () => { expect(result.content).toEqual([{ type: "text", text: '["admin","created"]' }]) }) +test("each call in a program gets its own ID and is marked as nested in execute", async () => { + const ids: string[] = [] + const nested: Array<[string, string]> = [] + const input = Schema.Struct({}) + const record = { + name: "record", + description: "Record the call", + input, + execute: (_, context) => Effect.sync(() => ids.push(context.id)).pipe(Effect.as({ content: "ok" })), + } satisfies Info + await Effect.runPromise( + createCodeMode( + new Map([["record", record]]), + permissionService({ + nested: (call, parent) => Effect.sync(() => void nested.push([call, parent])), + }), + ).execute({ code: "await Promise.all([tools.record({}), tools.record({})])" }, context), + ) + expect(new Set(ids).size).toBe(2) + expect(ids).not.toContain(context.id) + expect(nested.toSorted()).toEqual(ids.toSorted().map((id) => [id, context.id])) +}) + test("executions share the prepared runtime of an inventory while keeping per-call state", async () => { let conversions = 0 const echo: Info = { @@ -437,7 +460,7 @@ test("executions share the prepared runtime of an inventory while keeping per-ca }, }, }, - execute: (input, context) => Effect.succeed({ content: `${context.id}:${(input as { value: string }).value}` }), + execute: (input) => Effect.succeed({ content: (input as { value: string }).value }), } const inventory = { tools: new Map([["echo", echo]]) } const codeMode = CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context), allowAll) @@ -457,14 +480,14 @@ test("executions share the prepared runtime of an inventory while keeping per-ca expect(CodeModeTool.catalog(inventory).tools).toHaveLength(1) expect(results).toEqual( ["first", "second"].map((id) => ({ - output: `${id}:${id}`, + output: id, progress: [{ toolCalls: [{ tool: "echo", status: "running", input: { value: id } }] }], })), ) expect( (await Effect.runPromise(codeMode.execute({ code: 'return await tools.echo({ value: "x" })' }, context))).output .output, - ).toBe("call_execute:x") + ).toBe("x") expect(conversions).toBe(1) await Effect.runPromise( diff --git a/packages/core/test/tool-image-generate.test.ts b/packages/core/test/tool-image-generate.test.ts index ddc16f83f3a..1bafcd53027 100644 --- a/packages/core/test/tool-image-generate.test.ts +++ b/packages/core/test/tool-image-generate.test.ts @@ -68,6 +68,11 @@ const it = testEffect( ), ), decisions: () => Effect.die("unused"), + video: { + start: () => Effect.die("unused"), + status: () => Effect.die("unused"), + result: () => Effect.die("unused"), + }, }), ), ), diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 7439d0fbfe9..efe92790d8f 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -984,6 +984,82 @@ describe("Tool", () => { ) }) + it.effect("a hook can rename a call inside a Code Mode program to another of its tools", () => + Effect.gen(function* () { + const service = yield* Tool.Service + const hooks = yield* PluginHooks.Service + yield* transform(service, { echo: make(), constant: constant("renamed") }) + yield* transform(service, { direct: constant("direct") }, { codemode: false }) + const seen: string[] = [] + yield* hooks.register("tool", "execute.before", (event) => + Effect.sync(() => { + if (event.tool !== "echo") return + event.tool = Schema.is(Schema.Struct({ text: Schema.String }))(event.input) ? event.input.text : event.tool + }), + ) + yield* hooks.register("tool", "execute.after", (event) => Effect.sync(() => void seen.push(event.tool))) + const snapshot = yield* service.snapshot() + const program = (code: string) => + snapshot.execute({ + sessionID, + ...identity, + call: { type: "tool-call", id: "call-program", name: "execute", input: { code } }, + }) + + expect((yield* program('return await tools.echo({ text: "constant" })')).output).toMatchObject({ + output: JSON.stringify({ text: "renamed" }), + }) + expect(seen).toContain("constant") + // A program can only reach its own tools, however the call is renamed. + for (const name of ["direct", "missing"]) + expect( + (yield* program(`try { await tools.echo({ text: "${name}" }) } catch (e) { return e.message }`)).output, + ).toMatchObject({ output: `Tool is not available for this request: ${name}` }) + + const check = (tools: string[]) => + service.check({ + code: 'return await tools.echo({ text: "constant" })', + tools, + bindings: {}, + permissions: [], + limits: {}, + context: { sessionID, ...identity, progress: () => Effect.void }, + }) + expect(yield* check(["echo"])).toMatchObject({ ok: false }) + expect(yield* check(["echo", "constant"])).toMatchObject({ ok: true, value: { text: "renamed" } }) + }), + ) + + it.effect("hooks see one ID per call inside a Code Mode program", () => + Effect.gen(function* () { + const service = yield* Tool.Service + const hooks = yield* PluginHooks.Service + yield* transform(service, { echo: make() }) + const before: string[] = [] + const after: string[] = [] + yield* hooks.register("tool", "execute.before", (event) => + Effect.sync(() => void (event.tool === "echo" && before.push(event.id))), + ) + yield* hooks.register("tool", "execute.after", (event) => + Effect.sync(() => void (event.tool === "echo" && after.push(event.id))), + ) + const snapshot = yield* service.snapshot() + yield* snapshot.execute({ + sessionID, + ...identity, + call: { + type: "tool-call", + id: "call-program", + name: "execute", + input: { code: 'await Promise.all([tools.echo({ text: "a" }), tools.echo({ text: "b" })])' }, + }, + }) + expect(new Set(before).size).toBe(2) + expect(before).not.toContain("call-program") + expect(after.toSorted()).toEqual(before.toSorted()) + }), + ) + it.effect("normalizes image tool output once and drops unresizable images", () => Effect.gen(function* () { const service = yield* Tool.Service diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 881dc514e00..2518b6bf3f4 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -52,7 +52,7 @@ import { offlineModels } from "./fixture/models" import { testEffect } from "./lib/effect" import { permissionLayer } from "./lib/permission" import { Expected } from "./lib/session-message" -import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool" +import { codeModeListings, toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool" const sessionID = Session.ID.make("ses_shell_tool_test") const sessionModel = Model.Ref.make({ id: Model.ID.make("test"), providerID: Provider.ID.make("test") }) @@ -870,34 +870,38 @@ describe("ShellTool ordinary shell syntax", () => { }) describe("ShellTool", () => { - it.live("returns both parallel CodeMode shell results", () => + it.live("moves shell into Code Mode with full_codemode and returns both parallel results", () => withTempDir((tmp) => { reset() - return withSession(tmp.path, (registry) => - Effect.gen(function* () { - yield* registry.transform((editor) => - editor.update("shell", (tool) => { - tool.options = { ...tool.options, codemode: true } + return Effect.promise(() => + Bun.write(path.join(tmp.path, "opencode.json"), JSON.stringify({ experimental: { full_codemode: true } })), + ).pipe( + Effect.andThen( + withSession(tmp.path, (registry) => + Effect.gen(function* () { + const snapshot = yield* registry.snapshot() + expect(snapshot.definitions.map((tool) => tool.name)).toEqual(["execute"]) + expect(codeModeListings(snapshot.codeModeCatalog!).map((entry) => entry.path)).toEqual(["shell"]) + const command = isWindows ? helloCommand : `${helloCommand}; sleep 0.1` + const inputs = ["one", "two"].map((text) => JSON.stringify({ command: command.replace("hello", text) })) + const result = yield* executeTool(registry, { + sessionID, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-parallel-shells", + name: "execute", + input: { code: `return await Promise.all([tools.shell(${inputs[0]}), tools.shell(${inputs[1]})])` }, + }, + }).pipe(Effect.timeout("3 seconds")) + expect(result.status).toBe("completed") + expect(JSON.parse(result.output.output)).toEqual([ + { output: "one", exitCode: 0, wallTimeSeconds: expect.any(Number) }, + { output: "two", exitCode: 0, wallTimeSeconds: expect.any(Number) }, + ]) }), - ) - const command = isWindows ? helloCommand : `${helloCommand}; sleep 0.1` - const inputs = ["one", "two"].map((text) => JSON.stringify({ command: command.replace("hello", text) })) - const result = yield* executeTool(registry, { - sessionID, - ...toolIdentity, - call: { - type: "tool-call", - id: "call-parallel-shells", - name: "execute", - input: { code: `return await Promise.all([tools.shell(${inputs[0]}), tools.shell(${inputs[1]})])` }, - }, - }).pipe(Effect.timeout("3 seconds")) - expect(result.status).toBe("completed") - expect(JSON.parse(result.output.output)).toEqual([ - { output: "one", exitCode: 0, wallTimeSeconds: expect.any(Number) }, - { output: "two", exitCode: 0, wallTimeSeconds: expect.any(Number) }, - ]) - }), + ), + ), ) }), ) @@ -1241,6 +1245,7 @@ describe("ShellTool", () => { }), ), deps: [ + Config.node, Environment.node, FileAccess.node, Flag.node, diff --git a/packages/core/test/video-generation.test.ts b/packages/core/test/video-generation.test.ts new file mode 100644 index 00000000000..8e037a14240 --- /dev/null +++ b/packages/core/test/video-generation.test.ts @@ -0,0 +1,172 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { expect } from "bun:test" +import { type Duration, Effect, Layer, Stream } from "effect" +import { TestClock } from "effect/testing" +import type { VideoStatus } from "@opencode/ai/effect" +import { Database } from "@opencode/core/database/database" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Watcher } from "@opencode/core/filesystem/watcher" +import { Generate } from "@opencode/core/generate" +import { BlobStore } from "@opencode/core/blob-store" +import { VideoGeneration } from "@opencode/core/video-generation" +import { LocationServiceMap } from "@opencode/core/location-service-map" +import type { VideoID, VideoJob } from "@opencode/schema/generate" +import { Model } from "@opencode/schema/model" +import { Provider } from "@opencode/schema/provider" +import { makeLocationNode } from "@opencode/util/effect/app-node" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Global } from "@opencode/util/global" +import { offlineModels } from "./fixture/models" +import { tmpdirScoped } from "./fixture/tmpdir" +import { it } from "./lib/effect" +import { eventually } from "./lib/eventually" + +const model = Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make("video") }) +const providerError = (message: string, status?: number) => + new Generate.ProviderRequestError({ providerID: "test", reason: "provider", message, status }) + +// The start of an MP4: a `ftyp` box, so its type is read from its bytes. +const mp4 = Uint8Array.from([0, 0, 0, 0x14, ...new TextEncoder().encode("ftypmp42"), 0, 0, 0, 0, 1, 2, 3, 4]) + +/** A provider the test drives. */ +const provider = () => ({ + status: { status: "running" } as VideoStatus, + /** The videos a finished job returns. */ + results: [Stream.make(mp4)] as Stream.Stream[], + start: Effect.succeed({ id: "provider_1" }) as Effect.Effect<{ readonly id: string }, Generate.Error>, + /** Status reads that fail before one succeeds. */ + failReads: 0, +}) +type State = ReturnType + +const app = (dir: string, state: State) => + AppNodeBuilder.build( + LayerNode.group([VideoGeneration.node, BlobStore.node, Database.node, LocationServiceMap.node]), + [ + Global.node.replace(Global.layerWith({ data: path.join(dir, "data"), config: path.join(dir, "config") })), + Database.node.replace(Database.configured({ path: "opencode.db" })), + offlineModels, + Watcher.node.replace(Watcher.configured({ enabled: false })), + Generate.node.replace( + makeLocationNode({ + service: Generate.Service, + layer: Layer.succeed( + Generate.Service, + Generate.Service.of({ + text: () => Effect.die("unused"), + image: () => Effect.die("unused"), + decisions: () => Effect.die("unused"), + video: { + start: () => Effect.suspend(() => state.start), + status: () => + Effect.suspend(() => + state.failReads-- > 0 ? Effect.fail(providerError("reset")) : Effect.succeed(state.status), + ), + result: () => Effect.sync(() => state.results.map((stream) => ({ mime: "video/mp4", stream }))), + }, + }), + ), + deps: [], + }), + ), + ], + ) + +const settled = (id: VideoID, step: Duration.Input = "5 seconds") => + eventually( + VideoGeneration.Service.pipe( + Effect.tap(() => TestClock.adjust(step)), + Effect.flatMap((generations) => generations.get(id)), + ), + (job: VideoJob) => job.status !== "running", + ) + +const blobs = (dir: string) => path.join(dir, "data", "blobs") +const listed = (dir: string) => Effect.promise(() => fs.readdir(blobs(dir)).catch(() => [] as string[])) + +it.effect("stores each finished video as a blob, read back after a restart until it's 7 days old", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-generation-")).path + const state = provider() + state.results = [Stream.make(mp4), Stream.make(mp4, mp4)] + const job = yield* Effect.gen(function* () { + const generations = yield* VideoGeneration.Service + const started = yield* generations.start({ model, prompt: "a cat" }) + expect(yield* generations.get(started.id)).toEqual({ id: started.id, status: "running" }) + + state.status = { status: "completed" } + // A failed status read is retried at the next interval. + state.failReads = 1 + const job = yield* settled(started.id) + if (job.status !== "completed") throw new Error(`expected completed, got ${job.status}`) + expect(job.blobs).toMatchObject([ + { id: `${started.id}_0`, mime: "video/mp4", bytes: mp4.length }, + { id: `${started.id}_1`, mime: "video/mp4", bytes: mp4.length * 2 }, + ]) + expect(job.blobs[0].expiresAt).toBeGreaterThan(Date.now() + 6 * 24 * 60 * 60 * 1000) + expect( + new Uint8Array(yield* Effect.promise(() => fs.readFile(path.join(blobs(dir), `${started.id}_0`)))), + ).toEqual(mp4) + expect((yield* listed(dir)).toSorted()).toEqual([`${started.id}_0`, `${started.id}_1`]) + return job + }).pipe(Effect.provide(app(dir, state))) + + yield* Effect.gen(function* () { + const generations = yield* VideoGeneration.Service + // A new process knows nothing of the job, but finds its blobs from its ID. + expect(yield* generations.get(job.id)).toEqual(job) + const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) + yield* Effect.forEach(job.blobs, (blob) => + Effect.promise(() => fs.utimes(path.join(blobs(dir), blob.id), old, old)), + ) + yield* TestClock.adjust("1 hour") + yield* eventually(listed(dir), (files) => files.length === 0) + expect(yield* generations.get(job.id).pipe(Effect.flip)).toMatchObject({ _tag: "VideoGeneration.NotFoundError" }) + }).pipe(Effect.provide(app(dir, state))) + }), +) + +it.effect("keeps none of a job's videos when one of their downloads keeps failing", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-generation-fail-")).path + const state = provider() + state.results = [ + Stream.make(mp4), + Stream.make(mp4).pipe(Stream.concat(Stream.fail(providerError("connection reset")))), + ] + yield* Effect.gen(function* () { + const generations = yield* VideoGeneration.Service + const started = yield* generations.start({ model, prompt: "a bird" }) + state.status = { status: "completed" } + expect(yield* settled(started.id, "1 second")).toEqual({ + id: started.id, + status: "error", + reason: "failed", + error: "connection reset", + }) + expect(yield* listed(dir)).toEqual([]) + }).pipe(Effect.provide(app(dir, state))) + }), +) + +it.effect("reports the provider's failure reason, a job past its deadline and a rejected submission", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-generation-errors-")).path + const state = provider() + yield* Effect.gen(function* () { + const generations = yield* VideoGeneration.Service + const expired = yield* generations.start({ model, prompt: "a fish" }) + state.status = { status: "error", reason: "expired" } + expect(yield* settled(expired.id)).toMatchObject({ status: "error", reason: "expired" }) + + state.status = { status: "running" } + const slow = yield* generations.start({ model, prompt: "a snail" }) + expect(yield* settled(slow.id, "30 minutes")).toMatchObject({ status: "error", reason: "unknown" }) + + state.start = Effect.fail(providerError("bad", 400)) + const rejected = yield* generations.start({ model, prompt: "a crab" }).pipe(Effect.flip) + expect(rejected).toMatchObject({ _tag: "Generate.ProviderRequestError", message: "bad" }) + }).pipe(Effect.provide(app(dir, state))) + }), +) diff --git a/packages/httpapi-codegen/src/index.ts b/packages/httpapi-codegen/src/index.ts index 47e944dcda1..8afd612de1d 100644 --- a/packages/httpapi-codegen/src/index.ts +++ b/packages/httpapi-codegen/src/index.ts @@ -124,10 +124,11 @@ export function compile string | undefined /** - * Keeps each namespaced endpoint's pre-namespace client path and generated type names as deprecated aliases of - * the namespaced ones, so moving an endpoint into a namespace does not break callers. + * Pre-namespace client paths that shipped, such as `generate.text`. Each keeps its path and generated type names + * as deprecated aliases of the namespaced endpoint, so moving it into a namespace does not break callers. + * Endpoints added after the move have no old path to keep. */ - readonly aliases?: boolean + readonly aliases?: ReadonlySet }, ): Contract { const endpoints: Array = [] @@ -334,14 +335,17 @@ export function compile group.endpoints.flatMap((endpoint): Array => { const previous = unnamespaced.get(endpoint) if (previous === undefined) return [] + const from = [...previous.path, ...endpoint.clientPath] + if (!shipped.has(from.join("."))) return [] return [ { - from: [...previous.path, ...endpoint.clientPath], + from, to: [...group.path, ...endpoint.clientPath], fromGroup: previous.group, group, @@ -524,7 +528,7 @@ function renderEffectShape( if (groups.some((group) => group.identifier === fromGroup)) continue const moved = aliases.filter((alias) => alias.fromGroup === fromGroup) const target = moved[0].group - if (moved.some((alias) => alias.group !== target) || moved.length !== target.endpoints.length) continue + if (moved.some((alias) => alias.group !== target)) continue aliasTypes.push({ name: `${identifierPart(fromGroup)}Api`, target: groupShapeName(target), generic: true }) } const takenNames = new Set([...externalNames, ...generatedNames]) diff --git a/packages/httpapi-codegen/test/generate.test.ts b/packages/httpapi-codegen/test/generate.test.ts index 8e4b68d9c0a..b7e621c461a 100644 --- a/packages/httpapi-codegen/test/generate.test.ts +++ b/packages/httpapi-codegen/test/generate.test.ts @@ -493,12 +493,20 @@ describe("HttpApiCodegen.generate", () => { ), ) .add( - HttpApiGroup.make("server.generate").add( - HttpApiEndpoint.post("text", "/experimental/generate/text", { - payload: Schema.Struct({ prompt: Schema.String }), - success: Schema.String, - }), - ), + HttpApiGroup.make("server.generate") + .add( + HttpApiEndpoint.post("text", "/experimental/generate/text", { + payload: Schema.Struct({ prompt: Schema.String }), + success: Schema.String, + }), + ) + // Added after the move, so it never had an old path to alias. + .add( + HttpApiEndpoint.post("video", "/experimental/generate/video", { + payload: Schema.Struct({ prompt: Schema.String }), + success: Schema.String, + }), + ), ) const options = { groupNames: { "server.session": "session", "server.generate": "generate" }, @@ -512,7 +520,7 @@ describe("HttpApiCodegen.generate", () => { .join(""), ).not.toContain("@deprecated") - const contract = compileContract(source, { ...options, aliases: true }) + const contract = compileContract(source, { ...options, aliases: new Set(["session.stats", "generate.text"]) }) expect(contract.aliases?.map((alias) => [alias.from.join("."), alias.to.join(".")])).toEqual([ ["session.stats", "experimental.session.stats"], ["generate.text", "experimental.generate.text"], @@ -532,6 +540,7 @@ describe("HttpApiCodegen.generate", () => { expect(Object.keys(client.session)).toEqual(["get", "stats"]) expect(client.session.stats).toBe(client.experimental.session.stats) expect(client.generate.text).toBe(client.experimental.generate.text) + expect(Object.keys(client.generate)).toEqual(["text"]) expect(await client.session.stats({ sessionID: "a" })).toBe("ok") expect(paths).toEqual(["/experimental/session/a/stats"]) const promiseFile = (path: string) => promise.files.find((file) => file.path === path)?.content @@ -571,7 +580,7 @@ describe("HttpApiCodegen.generate", () => { endpoint.path.startsWith("/experimental/") ? "experimental" : undefined expect(() => compileContract(source, { namespace })).not.toThrow() - expect(() => compileContract(source, { namespace, aliases: true })).toThrow("Client alias collision: session.stats") + expect(() => compileContract(source, { namespace, aliases: new Set(["session.stats"]) })).toThrow("Client alias collision: session.stats") }) test("derives nested paths from OpenAPI operation IDs", () => { diff --git a/packages/plugin/src/effect/plugin.ts b/packages/plugin/src/effect/plugin.ts index 32004d4d7d8..61971725229 100644 --- a/packages/plugin/src/effect/plugin.ts +++ b/packages/plugin/src/effect/plugin.ts @@ -35,8 +35,8 @@ export interface Context { readonly event: EventDomain readonly experimental: { readonly terminal: Pick["persistentPty"], "read"> - /** Stateless generation with a model and a prompt: no session, history or tools. */ - readonly generate: ExperimentalGenerateApi + /** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */ + readonly generate: Omit, "video"> readonly artifact: ExperimentalArtifactDomain } readonly integration: IntegrationDomain diff --git a/packages/plugin/src/promise/plugin.ts b/packages/plugin/src/promise/plugin.ts index 6e22d0547e8..cce3aa8ed28 100644 --- a/packages/plugin/src/promise/plugin.ts +++ b/packages/plugin/src/promise/plugin.ts @@ -35,8 +35,8 @@ export interface Context { readonly event: EventDomain readonly experimental: { readonly terminal: Pick - /** Stateless generation with a model and a prompt: no session, history or tools. */ - readonly generate: ExperimentalGenerateApi + /** Stateless generation with a model and a prompt: no session, history or tools. Video jobs are server-only for now. */ + readonly generate: Omit readonly artifact: ExperimentalArtifactDomain } readonly integration: IntegrationDomain diff --git a/packages/process-daemon/Cargo.lock b/packages/process-daemon/Cargo.lock index 45e56cbf5b2..c3c2da00389 100644 --- a/packages/process-daemon/Cargo.lock +++ b/packages/process-daemon/Cargo.lock @@ -184,11 +184,12 @@ dependencies = [ [[package]] name = "opencode-pty" -version = "0.5.2" +version = "0.6.0" dependencies = [ "anyhow", "base64", "crossbeam-channel", + "crossbeam-utils", "fs2", "libc", "nix", diff --git a/packages/process-daemon/Cargo.toml b/packages/process-daemon/Cargo.toml index 136a2b8fadc..ffef45521da 100644 --- a/packages/process-daemon/Cargo.toml +++ b/packages/process-daemon/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencode-pty" -version = "0.5.2" +version = "0.6.0" edition = "2024" rust-version = "1.90" description = "Persistent PTY service for OpenCode" @@ -20,6 +20,7 @@ serde_json = "1.0" shell-words = "1.1" [target.'cfg(unix)'.dependencies] +crossbeam-utils = "0.8" libc = "0.2" nix = { version = "0.28", features = ["poll", "process", "term", "user"] } sha2 = "0.10" diff --git a/packages/process-daemon/README.md b/packages/process-daemon/README.md index 2b28271794b..8c3d6a3a3a3 100644 --- a/packages/process-daemon/README.md +++ b/packages/process-daemon/README.md @@ -17,7 +17,7 @@ terminals. Observer commands connect to an existing daemon without taking owners The service uses a private authenticated local byte stream (Unix socket or Windows named pipe) and an atomic registration file. -Integrations launch `opencode-pty daemon --name NAME [--runtime-dir DIR]` (protocol 8). +Integrations launch `opencode-pty daemon --name NAME [--runtime-dir DIR]` (protocol 9). The server must claim the daemon within 5 seconds by sending the authenticated framed envelope `{"token":"...","request":{"op":"own","instance_id":"..."}}`. The response is `{"type":"owned"}`; that connection stays open as the sole @@ -70,7 +70,7 @@ socket pair until a connection arrives, a stop or ownership change wakes it, an ownership deadline is due, or a two-second safety net elapses. Windows still polls every 25 ms. -The Windows named-pipe backend keeps protocol 8 and the registration fields +The Windows named-pipe backend uses protocol 9 and the registration fields `instance_id`, `pid`, `protocol`, `socket`, `token`, and `features`. Treat `socket` as an opaque local endpoint: on Windows it is `\\.\pipe\opencode-pty-`, not a filesystem socket. A random per-instance name, exclusive first pipe instance, @@ -111,7 +111,7 @@ so the runtime directory must be on a local NTFS volume (Windows 10 1709 or later); there is no non-atomic fallback. The Windows Rust `TerminalClient` and interactive CLI are not ported. Integrations -can use protocol 8 directly and the minimal `daemon::PipeConnection` byte-stream +can use protocol 9 directly and the minimal `daemon::PipeConnection` byte-stream helper. Connect with `PipeConnection::connect_to(socket, pid)`, which rejects a pipe whose server is not the registered daemon process: after a crash the stale registration's pipe name is free for another local user to create. Integrations @@ -211,7 +211,7 @@ return all available rows. Soft-wrapped rows stay separate, trailing whitespace is trimmed, and blank rows (including trailing blank rows) are empty strings. The alternate screen never exposes primary-screen history. -The protocol 8 request is `{"op":"read_rows","id":1,"rows":30}`; +The protocol 9 request is `{"op":"read_rows","id":1,"rows":30}`; omitted or `null` `rows` uses the current height. Its response is `{"type":"rows","process":{...},"lines":[...],"cursor_x":0,"cursor_y":0}`. Metadata, lines, and zero-based active-screen cursor coordinates come from one diff --git a/packages/process-daemon/SPEC.md b/packages/process-daemon/SPEC.md index bb1d679a6b8..8dd4aed4700 100644 --- a/packages/process-daemon/SPEC.md +++ b/packages/process-daemon/SPEC.md @@ -181,14 +181,16 @@ starts a pipe process: any command without a terminal. Both return `"SIGTERM"`, when a signal ended the process (on Windows, when the daemon signalled it); `exit_code` is then null. `signal` is left out when there is none. -- On Unix an exited pipe process stays listed, as a zombie, until `terminate`. - The zombie keeps its PID and process group ID reserved, so killing the group - can never reach an unrelated process. On Windows the process object and job - handle stay open until `terminate`, so the PID is not reused either. - `terminate` kills the whole tree (SIGKILL on Unix; the job on Windows), - reaps it and removes the process; it never waits on a descendant that left - the process group or job and still holds the pipe. The daemon never deletes - output files. +- A successful command may leave background processes running untracked. + On Unix a non-zero exit code sends SIGTERM to the process group before the + waiter reaps the leader, then SIGKILL after three seconds if the group + survives. A signal death has no numeric exit code and does not trigger this + cleanup. On Windows a non-zero exit terminates the job immediately. The + waiter clears kill-on-close and releases the job and process handles at exit. +- The finished record (including exit status, output path and metadata) stays + listed until `terminate`. Its PID is historical metadata. `terminate` kills + a running tree and removes its record; after exit it only removes the record. + The daemon never deletes output files. ### Line count @@ -225,9 +227,8 @@ process group and the child, as a real signal. **On Windows every signal is a hard kill** of the job: there is no console, so SIGTERM and SIGINT cannot be caught, and the exit reports the signal that was sent, not a platform exit code. Unlike `terminate`, `signal` keeps the process: `wait` then gets a normal -`Exited` with `signal`. Signalling an exited process is allowed and reaches -whatever is left of its group or job (an empty group is not an error); after -`terminate` the process is gone and `signal` fails. +`Exited` with `signal`. Signalling an exited process returns `Ok` without +sending a signal; after `terminate` the record is gone and `signal` fails. If an outer job refuses the child (`ERROR_ACCESS_DENIED`, for example a job with UI restrictions), the daemon runs the command anyway without a job, logs @@ -256,7 +257,7 @@ connected owner; the superseded connection can no longer prepare handoffs or stop the daemon, and its disconnect does not affect the new owner. The playground holds ownership until it exits; other CLI commands only observe or operate an existing daemon and never start one. -Protocol v8 uses four-byte big-endian framing with bounded UTF-8 JSON control +Protocol v9 uses four-byte big-endian framing with bounded UTF-8 JSON control frames and tagged raw binary output frames. Requests (`op`): `ping`, `own`, `prepare_handoff`, `create_pty`, `create_pipe`, `list`, `get`, `wait`, `signal`, `set_metadata`, `write`, `resize`, `control` (atomic interaction @@ -271,7 +272,7 @@ connection, once the token has been checked. Clients can therefore probe for a request. `Pong` and the registration carry `features` (required), the daemon's additive -capabilities. Protocol 8 needs none, so the list is empty. Later additive +capabilities. Protocol 9 needs none, so the list is empty. Later additive changes, such as a new request or field older clients can ignore, extend `features` and keep the protocol version. Only breaking changes bump `PROTOCOL_VERSION`, which clients reject on mismatch. @@ -310,3 +311,8 @@ the database. It starts the daemon only when the first terminal or pipe process is created. Only an explicit restart handoff descriptor lets a replacement server reuse the previous daemon's runtime directory and claim its ownership. + +On upgrade to protocol 9, OpenCode discovers protocol-8 daemons under its +runtime root and in its inherited handoff directory. It authenticates each +live instance and requests shutdown. This one-time replacement ends its +running commands and persistent terminals. A new daemon still starts lazily. diff --git a/packages/process-daemon/npm/package.json b/packages/process-daemon/npm/package.json index 19e9c44e5a2..df64597ad5e 100644 --- a/packages/process-daemon/npm/package.json +++ b/packages/process-daemon/npm/package.json @@ -1,6 +1,6 @@ { "name": "@opencode/pty", - "version": "0.5.2", + "version": "0.6.0", "description": "Persistent PTY service for OpenCode", "type": "module", "license": "MIT", @@ -25,14 +25,14 @@ "index.js" ], "optionalDependencies": { - "@opencode/pty-darwin-arm64": "0.5.2", - "@opencode/pty-darwin-x64": "0.5.2", - "@opencode/pty-linux-arm64-gnu": "0.5.2", - "@opencode/pty-linux-arm64-musl": "0.5.2", - "@opencode/pty-linux-x64-gnu": "0.5.2", - "@opencode/pty-linux-x64-musl": "0.5.2", - "@opencode/pty-win32-arm64": "0.5.2", - "@opencode/pty-win32-x64": "0.5.2" + "@opencode/pty-darwin-arm64": "0.6.0", + "@opencode/pty-darwin-x64": "0.6.0", + "@opencode/pty-linux-arm64-gnu": "0.6.0", + "@opencode/pty-linux-arm64-musl": "0.6.0", + "@opencode/pty-linux-x64-gnu": "0.6.0", + "@opencode/pty-linux-x64-musl": "0.6.0", + "@opencode/pty-win32-arm64": "0.6.0", + "@opencode/pty-win32-x64": "0.6.0" }, "publishConfig": { "access": "public" diff --git a/packages/process-daemon/src/client.rs b/packages/process-daemon/src/client.rs index df85c0f4c48..1336b5fa04b 100644 --- a/packages/process-daemon/src/client.rs +++ b/packages/process-daemon/src/client.rs @@ -894,7 +894,7 @@ mod tests { let _ = std::fs::remove_dir_all(&directory); assert_eq!( error.to_string(), - "opencode-pty protocol mismatch: service=7, client=8" + "opencode-pty protocol mismatch: service=7, client=9" ); } } diff --git a/packages/process-daemon/src/protocol.rs b/packages/process-daemon/src/protocol.rs index 6dc841aea71..95752d4e9f9 100644 --- a/packages/process-daemon/src/protocol.rs +++ b/packages/process-daemon/src/protocol.rs @@ -9,9 +9,9 @@ use crate::service::{ PipeMetadata, ProcessExit, ProcessInfo, ProcessMode, ProcessSignal, TerminalId, }; -pub const PROTOCOL_VERSION: u32 = 8; +pub const PROTOCOL_VERSION: u32 = 9; /// Additive capabilities of this daemon. Breaking changes bump -/// `PROTOCOL_VERSION`; everything in protocol 8 needs no feature. +/// `PROTOCOL_VERSION`; everything in protocol 9 needs no feature. pub const FEATURES: &[&str] = &[]; pub fn features() -> Vec { @@ -363,18 +363,18 @@ mod tests { } #[test] - fn version_8_has_no_features() { - assert_eq!(PROTOCOL_VERSION, 8); + fn version_9_has_no_features() { + assert_eq!(PROTOCOL_VERSION, 9); assert!(features().is_empty()); // `features` is required. assert!( serde_json::from_value::( - json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 8}) + json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 9}) ) .is_err() ); round_trip::( - json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 8, "features": []}), + json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 9, "features": []}), ); } diff --git a/packages/process-daemon/src/service.rs b/packages/process-daemon/src/service.rs index be54f6f84fe..15b37c002fc 100644 --- a/packages/process-daemon/src/service.rs +++ b/packages/process-daemon/src/service.rs @@ -11,6 +11,8 @@ use std::time::{Duration, Instant}; use anyhow::{Context, Result, anyhow, bail}; use crossbeam_channel::{Receiver, Sender, bounded}; +#[cfg(unix)] +use crossbeam_utils::sync::WaitGroup; use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system}; use serde::{Deserialize, Serialize}; @@ -284,6 +286,9 @@ pub struct CreatePipe { pub struct TerminalService { terminals: Mutex>>, + /// Failed-command escalation outlives record deletion. Shutdown waits for it. + #[cfg(unix)] + escalations: WaitGroup, created: AtomicU64, replay_capacity: usize, } @@ -298,6 +303,8 @@ impl TerminalService { pub fn new(replay_capacity: usize) -> Self { Self { terminals: Mutex::new(HashMap::new()), + #[cfg(unix)] + escalations: WaitGroup::new(), created: AtomicU64::new(0), replay_capacity, } @@ -322,7 +329,15 @@ impl TerminalService { bail!("output_path must be absolute"); } validate_metadata(&request.metadata)?; - self.insert(|id, order| TerminalHandle::spawn_pipe(id, order, request)) + self.insert(|id, order| { + TerminalHandle::spawn_pipe( + id, + order, + request, + #[cfg(unix)] + self.escalations.clone(), + ) + }) } fn insert( @@ -393,7 +408,7 @@ impl TerminalService { } /// Signals a pipe process and its process group. The process stays - /// listed; signalling one that already exited is allowed. + /// listed; signalling one that already exited is a no-op. pub fn signal(&self, id: TerminalId, signal: ProcessSignal) -> Result<()> { self.pipe(id)? .process @@ -615,6 +630,8 @@ impl TerminalService { impl Drop for TerminalService { fn drop(&mut self) { self.shutdown(); + #[cfg(unix)] + std::mem::take(&mut self.escalations).wait(); } } @@ -630,8 +647,6 @@ struct TerminalHandle { /// Dropped at shutdown, before the joins, to cancel a pipe reader that a /// surviving descendant would otherwise keep blocked. cancel: Mutex>>, - /// Runs after the joins; reaps a pipe process kept as a zombie until now. - reap: Mutex>>, /// Pipe only: the child, for `signal`. process: Option>, info: Arc>, @@ -867,7 +882,6 @@ impl TerminalHandle { shutdown_tx: Mutex::new(Some(actor.shutdown_tx)), killer: Mutex::new(killer), cancel: Mutex::new(None), - reap: Mutex::new(None), process: None, info, joins: Mutex::new(Some(vec![ @@ -929,14 +943,6 @@ impl TerminalHandle { for join in handles { let _ = join.join(); } - if let Some(reap) = self - .reap - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .take() - { - reap(); - } Ok(()) } } @@ -2270,7 +2276,6 @@ mod tests { shutdown_tx: Mutex::new(Some(shutdown_tx)), killer: Mutex::new(Box::new(TestKiller)), cancel: Mutex::new(None), - reap: Mutex::new(None), process: None, info, joins: Mutex::new(Some(vec![ diff --git a/packages/process-daemon/src/service/pipe.rs b/packages/process-daemon/src/service/pipe.rs index f2a39135c58..8b494e8cc8e 100644 --- a/packages/process-daemon/src/service/pipe.rs +++ b/packages/process-daemon/src/service/pipe.rs @@ -1,10 +1,8 @@ //! Non-PTY ("pipe") processes: a command with no terminal, stdin closed and //! stdout and stderr sharing one pipe so their bytes keep their order. //! -//! The platform modules own the child, its process tree and the output pipe: -//! Unix keeps a zombie so the PID and process group stay reserved, and Windows -//! keeps the process and its kill-on-close job. Everything the two must do the -//! same way lives here: +//! The platform waiters clean up a failed command's tree and release the +//! child at exit. The actor keeps its record available for late waiters. //! //! - The reader writes every byte to the output file before handing it to the //! actor, which keeps no replay buffer: the file is the only copy of the @@ -105,7 +103,7 @@ impl OutputSink { /// How a pipe child ended. enum Exit { Code(u32), - /// The daemon terminated the process; the value is the signal it sent. + /// The Unix terminating signal, or the signal sent by the daemon on Windows. Signal(String), } @@ -149,16 +147,8 @@ fn new_pipe_info(id: TerminalId, pid: u32, request: CreatePipe) -> ProcessInfo { } } -/// The waiter's result, and something dropped only after the exit message is -/// sent (Unix starts the reader's drain by dropping a pipe writer). -struct Waiter { - exit: io::Result, - after: Box, -} - /// Registers a spawned pipe process with its actor, then runs the platform's -/// reader and waiter. Both are started in that order, and the waiter last, so -/// it is joined before the process is reaped. +/// reader and waiter. If startup fails before the waiter starts, reap here. fn start_pipe( id: TerminalId, order: u64, @@ -166,7 +156,7 @@ fn start_pipe( process: Arc, cancel: Box, reader: impl FnOnce(Sender) + Send + 'static, - waiter: impl FnOnce() -> Waiter + Send + 'static, + waiter: impl FnOnce(Sender) + Send + 'static, ) -> Result { let info = Arc::new(RwLock::new(new_pipe_info(id, process.pid(), request))); // Nothing is ever written to a pipe process; a disconnected queue @@ -213,11 +203,7 @@ fn start_pipe( let wait_actor_tx = actor_tx.clone(); let waiter = thread::Builder::new() .name(format!("opencode-pty-wait-{id}")) - .spawn(move || { - let Waiter { exit, after } = waiter(); - let _ = wait_actor_tx.send(exit_message(exit)); - drop(after); - }) + .spawn(move || waiter(wait_actor_tx)) .context("failed to spawn terminal child waiter"); let waiter = match waiter { Ok(waiter) => waiter, @@ -227,7 +213,6 @@ fn start_pipe( } }; joins.push(waiter); - let reap = Arc::clone(&process); Ok(TerminalHandle { order, mode: ProcessMode::Pipe, @@ -236,7 +221,6 @@ fn start_pipe( shutdown_tx: Mutex::new(Some(shutdown_tx)), killer: Mutex::new(Box::new(ProcessKiller(Arc::clone(&process)))), cancel: Mutex::new(Some(cancel)), - reap: Mutex::new(Some(Box::new(move || reap.reap()))), process: Some(process), info, joins: Mutex::new(Some(joins)), diff --git a/packages/process-daemon/src/service/pipe/unix.rs b/packages/process-daemon/src/service/pipe/unix.rs index 5b701625760..af3b2487647 100644 --- a/packages/process-daemon/src/service/pipe/unix.rs +++ b/packages/process-daemon/src/service/pipe/unix.rs @@ -3,10 +3,8 @@ //! The child runs in its own process group with stdin on `/dev/null`. Three //! choices keep the daemon safe from what the child leaves behind: //! -//! - The waiter observes the exit with `WNOWAIT` and leaves the child as a -//! zombie until shutdown. While the zombie exists, its PID and process group -//! ID cannot be reused, so killing the group can never hit an unrelated -//! process, even long after the exit. +//! - The waiter observes the exit with `WNOWAIT` so it can signal a failed +//! command's group while the leader still reserves its ID, then reaps it. //! - The reader polls a cancel pipe as well as the output pipe, so shutdown //! never waits on a pipe that a descendant which left the process group //! still holds open. @@ -18,15 +16,16 @@ use std::io::{self, PipeReader, PipeWriter, Read}; use std::os::fd::AsFd; use std::os::unix::fs::OpenOptionsExt; use std::os::unix::process::CommandExt; -use std::process::{Command, Stdio}; +use std::process::{Child, Command, Stdio}; use std::sync::{Arc, Mutex, PoisonError, RwLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result}; +use crossbeam_utils::sync::WaitGroup; use nix::errno::Errno; use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; -use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, start_pipe}; +use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe}; use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId}; /// Serializes pipe creation against `spawn`. macOS has no `pipe2`, so std @@ -72,6 +71,7 @@ impl TerminalHandle { id: TerminalId, order: u64, request: CreatePipe, + escalations: WaitGroup, ) -> Result { let Pipes { output, @@ -121,12 +121,9 @@ impl TerminalHandle { drop(command); let process = Arc::new(Process { pid: child.id(), - reaped: Mutex::new(false), + child: Mutex::new(Some(child)), }); - // Dropping `Child` neither waits nor kills; `Process` reaps it. - drop(child); - let pid = process.pid; start_pipe( id, order, @@ -134,10 +131,9 @@ impl TerminalHandle { Arc::clone(&process), Box::new(cancel_writer), move |actor| read_output(output, OutputSink::new(sink, actor), cancel, exited), - move || super::Waiter { - exit: wait_exit(pid), - // Starts the reader's drain deadline, after the exit message. - after: Box::new(exited_writer), + move |actor| { + let _ = actor.send(exit_message(process.wait(escalations))); + drop(exited_writer); // start the reader's drain deadline }, ) } @@ -170,11 +166,11 @@ fn reset_signals() -> io::Result<()> { Ok(()) } -/// A pipe child that stays a zombie after it exits, until `reap`. +/// The PID is metadata. Only the live child under the lock can be signalled. #[derive(Debug)] pub(in crate::service) struct Process { pid: u32, - reaped: Mutex, + child: Mutex>, } impl Process { @@ -182,11 +178,31 @@ impl Process { self.pid } + fn wait(&self, escalations: WaitGroup) -> io::Result { + let exit = wait_exit(self.pid); + // Like the old spawner, leave background processes alone on a signal + // death (no numeric code). Only a non-zero exit code stops them. + let failed = matches!(exit, Ok(Exit::Code(code)) if code != 0); + let pgid = self.pid as libc::pid_t; + if failed { + // SAFETY: the unreaped leader still reserves its group ID. + unsafe { libc::killpg(pgid, libc::SIGTERM) }; + } + self.reap(); + if failed && unsafe { libc::killpg(pgid, 0) } == 0 { + escalate(pgid, escalations); + } + exit + } + /// Kills the whole process group. Never signals after `reap`, when the /// group ID may belong to someone else. pub(super) fn kill(&self) { - let reaped = self.reaped.lock().unwrap_or_else(PoisonError::into_inner); - if !*reaped && let Ok(pid) = i32::try_from(self.pid) { + let child = self.child.lock().unwrap_or_else(PoisonError::into_inner); + if child.is_some() + && !has_exited(self.pid) + && let Ok(pid) = i32::try_from(self.pid) + { // SAFETY: the unreaped child keeps its PID and group ID reserved. // Signal the child directly too, in case it moved to another group. unsafe { @@ -196,17 +212,16 @@ impl Process { } } - /// Sends `signal` to the process group and the child. Allowed after the - /// exit, to reach what is left of the group; refused after `reap`. + /// Sends `signal` to the process group and the child until the waiter reaps it. pub(in crate::service) fn signal(&self, signal: ProcessSignal) -> Result<()> { let signal = match signal { ProcessSignal::Term => libc::SIGTERM, ProcessSignal::Int => libc::SIGINT, ProcessSignal::Kill => libc::SIGKILL, }; - let reaped = self.reaped.lock().unwrap_or_else(PoisonError::into_inner); - if *reaped { - bail!("process has been reaped"); + let child = self.child.lock().unwrap_or_else(PoisonError::into_inner); + if child.is_none() || has_exited(self.pid) { + return Ok(()); } let pid = i32::try_from(self.pid).context("invalid pid")?; // SAFETY: the unreaped child keeps its PID and group ID reserved. @@ -216,24 +231,31 @@ impl Process { check_signal(unsafe { libc::kill(pid, signal) }, self.pid) } - /// Call only after the waiter has returned: kill the group first, so the - /// child has exited and this does not block. + /// Called by the waiter after observing exit, or after a startup failure + /// has killed the child. Serialize waitpid with all client signals. pub(super) fn reap(&self) { - let mut reaped = self.reaped.lock().unwrap_or_else(PoisonError::into_inner); - if *reaped { - return; + let mut child = self.child.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(mut child) = child.take() { + let _ = child.wait(); } - let Ok(pid) = i32::try_from(self.pid) else { - return; - }; - loop { - // SAFETY: waits only for this daemon's own child. - let result = unsafe { libc::waitpid(pid, std::ptr::null_mut(), 0) }; - if result != -1 || Errno::last() != Errno::EINTR { - break; - } - } - *reaped = true; + } +} + +/// Like the spawner after Node reaped its child, escalate by numeric PGID. +/// The PGID stays reserved while the original group has members. If it empties +/// during the grace, killpg gives ESRCH unless the number has been recycled. +fn escalate(pgid: libc::pid_t, pending: WaitGroup) { + let deadline = Instant::now() + Duration::from_secs(3); + if let Err(error) = std::thread::Builder::new() + .name(format!("opencode-pty-escalate-{pgid}")) + .spawn(move || { + std::thread::sleep(deadline.saturating_duration_since(Instant::now())); + unsafe { libc::killpg(pgid, libc::SIGKILL) }; + drop(pending); + }) + { + eprintln!("process group {pgid}: cannot schedule SIGKILL: {error}"); + unsafe { libc::killpg(pgid, libc::SIGKILL) }; } } diff --git a/packages/process-daemon/src/service/pipe/windows.rs b/packages/process-daemon/src/service/pipe/windows.rs index 2d55e6768dd..1941090a96b 100644 --- a/packages/process-daemon/src/service/pipe/windows.rs +++ b/packages/process-daemon/src/service/pipe/windows.rs @@ -54,14 +54,14 @@ use windows_sys::Win32::System::Threading::{ WaitForSingleObject, }; -use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, Waiter, start_pipe}; +use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe}; use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId}; use crate::transport::retained::Retained; use crate::transport::windows::{event, owned_handle, security::PrivateSecurity, wide}; /// Cancel is first so a pipe that is always readable cannot starve it. const CANCEL_READY: u32 = WAIT_OBJECT_0; -/// The read event, and the process handle after it. +/// The read event, and the exit event after it. const READ_READY: u32 = WAIT_OBJECT_0 + 1; const PROCESS_READY: u32 = WAIT_OBJECT_0 + 2; @@ -81,10 +81,11 @@ impl TerminalHandle { // clean up; the reader is the file's only writer. let sink = open_output(&request.output_path)?; let job = Job::new(id); - let cancel = CancelOnDrop::new()?; + let cancel = SignalOnDrop::new()?; + let exited = SignalOnDrop::new()?; let process = Arc::new(spawn(id, &request, job, client)?); let reader_cancel = Arc::clone(&cancel.0); - let reader_process = Arc::clone(&process); + let reader_exited = Arc::clone(&exited.0); start_pipe( id, order, @@ -96,12 +97,12 @@ impl TerminalHandle { server, OutputSink::new(sink, actor), reader_cancel, - reader_process, + reader_exited, ) }, - move || Waiter { - exit: wait_exit(process), - after: Box::new(()), + move |actor| { + let _ = actor.send(exit_message(wait_exit(&process))); + drop(exited); }, ) } @@ -117,7 +118,7 @@ pub(in crate::service) struct Process { #[derive(Debug)] struct State { - /// Taken by `reap`, which closes both handles. + /// Taken by the waiter at exit, or by `reap` if startup failed. handles: Option, /// The signal recorded by `kill`/`signal` before terminating the tree. killed: Option<&'static str>, @@ -126,7 +127,7 @@ struct State { #[derive(Debug)] struct Handles { process: Arc, - job: Option, + job: Option, } impl Process { @@ -138,7 +139,7 @@ impl Process { self.state.lock().unwrap_or_else(PoisonError::into_inner) } - /// The process object, kept open until `reap` so its PID cannot be reused. + /// Borrows the process object for the wait without holding the state lock. fn process_handle(&self) -> Option> { self.lock() .handles @@ -156,8 +157,6 @@ impl Process { } /// Hard-kills the process tree and records the signal the client will see. - /// Allowed after the exit, to reach what is left of the job; refused after - /// `reap`. pub(in crate::service) fn signal(&self, signal: ProcessSignal) -> Result<()> { let name = match signal { ProcessSignal::Term => "SIGTERM", @@ -166,33 +165,27 @@ impl Process { }; let mut state = self.lock(); let Some(handles) = record_kill(&mut state, name) else { - bail!("process has been reaped"); + return Ok(()); }; terminate(handles).context("failed to signal process") } - /// Call only after the waiter has returned: closes the process and job - /// handles. Closing the job alone kills anything still in it. + /// Releases a partially started command whose waiter never started. pub(super) fn reap(&self) { self.lock().handles.take(); } - - fn take_signal(&self) -> Option<&'static str> { - self.lock().killed.take() - } } -/// Records the signal while the process still runs, so a process that exited on -/// its own keeps its exit code, and returns the handles, or `None` after -/// `reap`. +/// A process that exited on its own keeps its exit code and its waiter's +/// cleanup policy, even if a signal races the waiter. fn record_kill<'a>(state: &'a mut State, name: &'static str) -> Option<&'a Handles> { let handles = state.handles.as_ref()?; // SAFETY: the state lock keeps the process handle open. - if !is_signalled(&handles.process) { - // Termination is asynchronous: the first signal that reached the - // running process is the one the client should see. - state.killed.get_or_insert(name); + if is_signalled(&handles.process) { + return None; } + // Termination is asynchronous: report the first signal. + state.killed.get_or_insert(name); Some(handles) } @@ -201,7 +194,7 @@ fn terminate(handles: &Handles) -> io::Result<()> { // SAFETY: the handles stay open while they are borrowed here. let terminated = unsafe { match &handles.job { - Some(job) => TerminateJobObject(job.as_raw_handle(), 1), + Some(job) => TerminateJobObject(job.handle(), 1), None => TerminateProcess(handles.process.as_raw_handle(), 1), } }; @@ -247,7 +240,7 @@ fn spawn( state: Mutex::new(State { handles: Some(Handles { process: Arc::new(created.process), - job: job.map(|job| job.0), + job, }), killed: None, }), @@ -319,7 +312,7 @@ fn create_process( /// Waits for the child to exit, then reports the exit code, or the signal the /// daemon sent when it terminated the tree. -fn wait_exit(process: Arc) -> io::Result { +fn wait_exit(process: &Process) -> io::Result { let Some(handle) = process.process_handle() else { return Err(io::Error::other("process has been reaped")); }; @@ -327,27 +320,34 @@ fn wait_exit(process: Arc) -> io::Result { if unsafe { WaitForSingleObject(handle.as_raw_handle(), INFINITE) } != WAIT_OBJECT_0 { return Err(io::Error::last_os_error()); } + let mut state = process.lock(); + let handles = state.handles.take(); let mut code = 0; // SAFETY: a signalled process object has a final exit code. if unsafe { GetExitCodeProcess(handle.as_raw_handle(), &mut code) } == 0 { return Err(io::Error::last_os_error()); } - Ok(match process.take_signal() { + if let Some(job) = handles.and_then(|handles| handles.job) + && let Err(error) = job.finish(code != 0 && state.killed.is_none()) + { + eprintln!("pipe process {}: job cleanup failed: {error}", process.pid); + } + Ok(match state.killed.take() { Some(name) => Exit::Signal(name.to_string()), None => Exit::Code(code), }) } -/// Sets the reader's cancel event when dropped. -struct CancelOnDrop(Arc); +/// Wakes the reader on shutdown or once the waiter has published the exit. +struct SignalOnDrop(Arc); -impl CancelOnDrop { +impl SignalOnDrop { fn new() -> io::Result { event().map(|event| Self(Arc::new(event))) } } -impl Drop for CancelOnDrop { +impl Drop for SignalOnDrop { fn drop(&mut self) { // SAFETY: the shared event stays open through the call. unsafe { @@ -477,12 +477,9 @@ fn read_output( pipe: OwnedHandle, sink: OutputSink, cancel: Arc, - process: Arc, + exit_event: Arc, ) { let mut sink = sink; - let Some(process_object) = process.process_handle() else { - return; - }; let mut read = match Read::new(pipe) { Ok(read) => read, Err(error) => { @@ -491,7 +488,7 @@ fn read_output( } }; // The process may have exited before the reader started. - let mut exited = is_signalled(&process_object); + let mut exited = is_signalled(&exit_event); let mut deadline = exited.then(|| Instant::now() + DRAIN_AFTER_EXIT); loop { // Cancellation and the exit win over output, so a descendant that @@ -500,7 +497,7 @@ fn read_output( // Like Unix, shutdown is not an EOF the actor needs to observe. return; } - if !exited && is_signalled(&process_object) { + if !exited && is_signalled(&exit_event) { exited = true; deadline = Some(Instant::now() + DRAIN_AFTER_EXIT); } @@ -524,7 +521,7 @@ fn read_output( let handles = [ cancel.as_raw_handle(), read.event(), - process_object.as_raw_handle(), + exit_event.as_raw_handle(), ]; // Once the exit is seen, stop waiting on its signalled handle. let count = if exited { 2 } else { 3 }; @@ -654,21 +651,30 @@ fn output_pipe() -> Result { /// A kill-on-close job: terminating it kills every descendant, and a crashed /// daemon closes it and kills them too. +#[derive(Debug)] struct Job(OwnedHandle); impl Job { fn new(id: TerminalId) -> Option { // SAFETY: an unnamed job with default attributes, adopted on success. let job = match owned_handle(unsafe { CreateJobObjectW(null(), null()) }) { - Ok(job) => job, + Ok(job) => Self(job), Err(error) => { warn_no_job(id, &error); return None; } }; + if let Err(error) = job.set_limits(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) { + warn_no_job(id, &error); + return None; + } + Some(job) + } + + fn set_limits(&self, flags: u32) -> io::Result<()> { let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION { - LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + LimitFlags: flags, ..Default::default() }, ..Default::default() @@ -677,22 +683,31 @@ impl Job { // the extended-information class. if unsafe { SetInformationJobObject( - job.as_raw_handle(), + self.handle(), JobObjectExtendedLimitInformation, (&raw const limits).cast(), size_of_val(&limits) as u32, ) } == 0 { - warn_no_job(id, &io::Error::last_os_error()); - return None; + return Err(io::Error::last_os_error()); } - Some(Self(job)) + Ok(()) } fn handle(&self) -> HANDLE { self.0.as_raw_handle() } + + fn finish(self, failed: bool) -> io::Result<()> { + // No console and no SIGTERM grace. If termination fails, closing the + // still-armed job is the fallback. For a successful command disarm + // kill-on-close before releasing the handle. + if failed && unsafe { TerminateJobObject(self.handle(), 1) } == 0 { + return Err(io::Error::last_os_error()); + } + self.set_limits(0) + } } fn warn_no_job(id: TerminalId, error: &io::Error) { @@ -1071,10 +1086,10 @@ mod tests { assert!(!is_signalled(&process.process_handle().unwrap())); process.signal(ProcessSignal::Kill).unwrap(); assert!(matches!( - wait_exit(Arc::clone(&process)).unwrap(), + wait_exit(&process).unwrap(), Exit::Signal(name) if name == "SIGKILL" )); - process.reap(); + assert!(process.process_handle().is_none()); } /// A duplicate of `job` with only query access: joining it needs @@ -1110,7 +1125,7 @@ mod tests { let OutputPipe { client, .. } = output_pipe().unwrap(); let process = Arc::new(spawn(2, &request, Some(restricted), client).unwrap()); let mut in_job = 0; - // SAFETY: the process handle stays open until `reap` and the job is live. + // SAFETY: the process and job handles stay open through this call. assert_ne!( unsafe { IsProcessInJob( @@ -1122,10 +1137,7 @@ mod tests { 0 ); assert_eq!(in_job, 0, "the restricted job must have been refused"); - assert!(matches!( - wait_exit(Arc::clone(&process)).unwrap(), - Exit::Code(5) - )); - process.reap(); + assert!(matches!(wait_exit(&process).unwrap(), Exit::Code(5))); + assert!(process.process_handle().is_none()); } } diff --git a/packages/process-daemon/tests/ownership.rs b/packages/process-daemon/tests/ownership.rs index e1c17ee5396..70c7ecf7517 100644 --- a/packages/process-daemon/tests/ownership.rs +++ b/packages/process-daemon/tests/ownership.rs @@ -52,7 +52,7 @@ impl Daemon { } thread::sleep(Duration::from_millis(10)); }; - assert_eq!(registration.protocol, 8); + assert_eq!(registration.protocol, 9); Self { child, root, @@ -317,7 +317,7 @@ fn rename_is_served() { assert!(daemon.registration.features.is_empty()); assert!(matches!( daemon.request(Request::Ping), - Response::Pong { protocol: 8, features, .. } if features.is_empty() + Response::Pong { protocol: 9, features, .. } if features.is_empty() )); let (owner, response) = daemon.own(None); assert!(matches!(response, Response::Owned)); diff --git a/packages/process-daemon/tests/pipe.rs b/packages/process-daemon/tests/pipe.rs index ee10d1ce1b8..97f40b16258 100644 --- a/packages/process-daemon/tests/pipe.rs +++ b/packages/process-daemon/tests/pipe.rs @@ -82,8 +82,8 @@ fn alive(pid: i32) -> bool { unsafe { libc::kill(pid, 0) == 0 } } -fn wait_dead(pid: i32) { - let deadline = Instant::now() + Duration::from_secs(5); +fn wait_dead(pid: i32, timeout: Duration) { + let deadline = Instant::now() + timeout; while alive(pid) { assert!(Instant::now() < deadline, "process {pid} is still running"); std::thread::sleep(Duration::from_millis(10)); @@ -150,11 +150,16 @@ fn sigpipe_is_not_inherited_as_ignored() { #[test] fn reports_the_signal_that_ended_the_process() { let service = TerminalService::default(); - let (info, file) = start(&service, "kill -TERM $$"); + let (info, file) = start( + &service, + "sleep 30 >/dev/null 2>&1 & echo $!; kill -TERM $$", + ); let finished = run(&service, info.id, &file); + let sleeper = KillOnDrop(finished.output.trim().parse().unwrap()); assert_eq!(finished.exit.exit_code, None); assert_eq!(finished.exit.signal.as_deref(), Some("SIGTERM")); service.terminate(info.id).unwrap(); + assert!(alive(sleeper.0)); } #[test] @@ -185,11 +190,15 @@ fn a_descendant_holding_the_pipe_delays_the_exit_by_at_most_the_drain() { "{:?}", finished.elapsed ); - let sleeper: i32 = finished.output.lines().next().unwrap().parse().unwrap(); - assert!(alive(sleeper)); - // Terminate kills the rest of the process group. + let sleeper = KillOnDrop(finished.output.lines().next().unwrap().parse().unwrap()); + assert!(alive(sleeper.0)); + // The leader has already been reaped, but its record can still be read. + assert!(!alive(info.pid.unwrap() as i32)); + assert_eq!(service.list(ProcessMode::Pipe).unwrap()[0].id, info.id); + service.signal(info.id, ProcessSignal::Kill).unwrap(); service.terminate(info.id).unwrap(); - wait_dead(sleeper); + assert!(service.list(ProcessMode::Pipe).unwrap().is_empty()); + assert!(alive(sleeper.0)); } /// Kills a test descendant even when an assertion fails first. @@ -218,17 +227,15 @@ fn terminate_does_not_wait_for_a_descendant_that_left_the_group() { } #[test] -fn an_exited_process_is_kept_until_terminate() { +fn a_failed_command_stops_its_background_processes_at_exit() { let service = TerminalService::default(); - let (info, file) = start(&service, "exit 0"); - run(&service, info.id, &file); - let pid = info.pid.unwrap() as i32; - // The zombie keeps the PID and process group reserved. - assert!(alive(pid)); - assert_eq!(service.list(ProcessMode::Pipe).unwrap().len(), 1); - service.terminate(info.id).unwrap(); - assert!(!alive(pid)); - assert!(service.list(ProcessMode::Pipe).unwrap().is_empty()); + let (info, file) = start(&service, "sleep 30 & echo $!; exit 3"); + let finished = run(&service, info.id, &file); + assert_eq!(finished.exit.exit_code, Some(3)); + wait_dead( + finished.output.trim().parse().unwrap(), + Duration::from_secs(1), + ); } #[test] @@ -237,7 +244,7 @@ fn terminate_kills_the_process_group() { let (info, file) = start(&service, "sleep 30 & echo $!; wait"); let child: i32 = first_line(&file).parse().unwrap(); service.terminate(info.id).unwrap(); - wait_dead(child); + wait_dead(child, Duration::from_secs(5)); assert!(!alive(info.pid.unwrap() as i32)); } @@ -537,7 +544,7 @@ fn signal_stops_a_process_and_keeps_its_record() { signal: Some("SIGTERM".into()) } ); - // Nothing is left in the group (macOS reports ESRCH); still fine. + // While its record exists, a late signal succeeds. service.signal(info.id, ProcessSignal::Kill).unwrap(); service.terminate(info.id).unwrap(); assert!(service.signal(info.id, ProcessSignal::Kill).is_err()); @@ -574,7 +581,7 @@ fn signal_reaches_a_backgrounded_child_in_the_group() { let child: i32 = first_line(&file).parse().unwrap(); // Not SIGINT: a non-interactive shell starts background jobs ignoring it. service.signal(info.id, ProcessSignal::Term).unwrap(); - wait_dead(child); + wait_dead(child, Duration::from_secs(5)); let exit = service.wait(info.id).unwrap().recv().unwrap(); assert!(exit.signal.is_some() || exit.exit_code.is_some()); assert_eq!(service.list(ProcessMode::Pipe).unwrap().len(), 1); @@ -582,15 +589,20 @@ fn signal_reaches_a_backgrounded_child_in_the_group() { } #[test] -fn signal_after_exit_reaches_leftover_group_members() { +fn a_failed_commands_background_process_that_ignores_term_is_killed() { let service = TerminalService::default(); - let (info, file) = start(&service, "sleep 30 & echo $!"); - let exit = run(&service, info.id, &file); - let sleeper = KillOnDrop(exit.output.trim().parse().unwrap()); - assert!(alive(sleeper.0)); - service.signal(info.id, ProcessSignal::Kill).unwrap(); - wait_dead(sleeper.0); + // The sleeper inherits SIG_IGN even if the leader exits before it execs. + let (info, file) = start( + &service, + "trap '' TERM; sleep 30 >/dev/null 2>&1 & echo $!; exit 1", + ); + let finished = run(&service, info.id, &file); + let pid = finished.output.trim().parse().unwrap(); + assert!(!alive(info.pid.unwrap() as i32)); service.terminate(info.id).unwrap(); + // Forgetting the record neither kills the sleeper nor cancels escalation. + assert!(alive(pid)); + wait_dead(pid, Duration::from_secs(5)); } #[test] diff --git a/packages/process-daemon/tests/pipe_windows.rs b/packages/process-daemon/tests/pipe_windows.rs index 8589c5c9d87..04360afa14e 100644 --- a/packages/process-daemon/tests/pipe_windows.rs +++ b/packages/process-daemon/tests/pipe_windows.rs @@ -21,7 +21,7 @@ use opencode_pty::service::{ }; use windows_sys::Win32::Foundation::{ERROR_PRIVILEGE_NOT_HELD, WAIT_OBJECT_0}; use windows_sys::Win32::System::Threading::{ - OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject, + OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject, }; /// A unique temporary path, removed when dropped even if a test fails. @@ -188,6 +188,23 @@ fn wait_dead(pid: u32) { } } +/// Kills a test descendant even when an assertion fails first. +struct KillOnDrop(u32); + +impl Drop for KillOnDrop { + fn drop(&mut self) { + // SAFETY: the PID belongs to this test's own descendant. + let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, self.0) }; + if handle.is_null() { + return; + } + // SAFETY: OpenProcess returned a new, uniquely owned handle. + let handle = unsafe { OwnedHandle::from_raw_handle(handle) }; + // SAFETY: the owned handle has PROCESS_TERMINATE access and is still valid. + unsafe { TerminateProcess(handle.as_raw_handle(), 1) }; + } +} + fn newlines(bytes: &[u8]) -> u64 { bytes.iter().filter(|&&byte| byte == b'\n').count() as u64 } @@ -223,7 +240,7 @@ impl GrandchildTree { } } -fn grandchild_tree(name: &str, keep_parent_alive: bool) -> GrandchildTree { +fn grandchild_tree(name: &str, exit_code: Option) -> GrandchildTree { let pid_file = TempPath::new(&format!("{name}-pid")); let inner = Script::powershell( &format!("{name}-grandchild"), @@ -242,7 +259,14 @@ fn grandchild_tree(name: &str, keep_parent_alive: bool) -> GrandchildTree { inner.0.0.display() ), ]; - if keep_parent_alive { + if let Some(code) = exit_code { + lines.extend([ + ":wait".to_string(), + format!("if exist \"{}\" exit /b {code}", pid_file.0.display()), + "ping -n 2 127.0.0.1 >nul".to_string(), + "goto wait".to_string(), + ]); + } else { lines.push("ping -n 60 127.0.0.1".to_string()); } GrandchildTree { @@ -534,7 +558,7 @@ fn signal_stops_a_process_and_keeps_its_record() { signal: Some("SIGTERM".into()) } ); - // What is left of the job is killed again without an error. + // A late signal succeeds while the record is still listed. service.signal(info.id, ProcessSignal::Kill).unwrap(); service.terminate(info.id).unwrap(); assert!(service.signal(info.id, ProcessSignal::Kill).is_err()); @@ -543,7 +567,7 @@ fn signal_stops_a_process_and_keeps_its_record() { #[test] fn signal_reaches_a_grandchild_in_the_job() { let service = TerminalService::default(); - let tree = grandchild_tree("grandchild", true); + let tree = grandchild_tree("grandchild", None); let (info, _file) = tree.start(&service); let grandchild = read_pid(&tree.pid_file.0); assert!(alive(grandchild)); @@ -557,7 +581,7 @@ fn signal_reaches_a_grandchild_in_the_job() { #[test] fn terminate_does_not_hang_on_a_grandchild() { let service = TerminalService::default(); - let tree = grandchild_tree("terminate", true); + let tree = grandchild_tree("terminate", None); let (info, _file) = tree.start(&service); let grandchild = read_pid(&tree.pid_file.0); assert!(alive(grandchild)); @@ -582,8 +606,9 @@ fn a_noisy_grandchild_still_exits_after_the_drain() { # Prove the pipe is live before the parent exits. [Console]::Out.Write('x') [Console]::Out.Flush() - [System.IO.File]::WriteAllText('{}', 'started') - while ($true) {{ + $marker = '{}' + [System.IO.File]::WriteAllText($marker, "$PID") + while ([System.IO.File]::Exists($marker)) {{ [Console]::Out.Write('x') }} "#, @@ -609,6 +634,7 @@ fn a_noisy_grandchild_still_exits_after_the_drain() { ], ); let (info, file) = start(&service, |file| cmd(&outer.0.display().to_string(), file)); + let _grandchild = KillOnDrop(read_pid(&marker.0)); let finished = run(&service, info.id, &file); assert_eq!(finished.exit.exit_code, Some(0)); assert!( @@ -620,11 +646,11 @@ fn a_noisy_grandchild_still_exits_after_the_drain() { } #[test] -fn signal_after_a_normal_exit_kills_a_leftover_grandchild() { +fn signal_and_terminate_after_a_successful_exit_spare_the_grandchild() { let service = TerminalService::default(); - let tree = grandchild_tree("leftover", false); + let tree = grandchild_tree("leftover", Some(0)); let (info, _file) = tree.start(&service); - let grandchild = read_pid(&tree.pid_file.0); + let grandchild = KillOnDrop(read_pid(&tree.pid_file.0)); // A descendant holds the pipe, so the exit waits for at most the drain. let started = Instant::now(); let exit = service.wait(info.id).unwrap().recv().unwrap(); @@ -636,7 +662,7 @@ fn signal_after_a_normal_exit_kills_a_leftover_grandchild() { assert_eq!(exit.exit_code, Some(0)); assert_eq!(exit.signal, None); // The process keeps its record after the exit; the grandchild still runs. - assert!(alive(grandchild)); + assert!(alive(grandchild.0)); assert_eq!( service.get(info.id).unwrap().lifecycle, TerminalLifecycle::Exited { @@ -646,9 +672,23 @@ fn signal_after_a_normal_exit_kills_a_leftover_grandchild() { ); assert_eq!(service.list(ProcessMode::Pipe).unwrap().len(), 1); service.signal(info.id, ProcessSignal::Kill).unwrap(); - wait_dead(grandchild); service.terminate(info.id).unwrap(); assert!(service.list(ProcessMode::Pipe).unwrap().is_empty()); + let pid = grandchild.0; + assert!(alive(pid)); + drop(grandchild); + wait_dead(pid); +} + +#[test] +fn a_failed_exit_terminates_the_grandchild() { + let service = TerminalService::default(); + let tree = grandchild_tree("failed", Some(3)); + let (info, _file) = tree.start(&service); + let grandchild = read_pid(&tree.pid_file.0); + let exit = service.wait(info.id).unwrap().recv().unwrap(); + assert_eq!(exit.exit_code, Some(3)); + wait_dead(grandchild); } #[test] diff --git a/packages/process-daemon/tests/rows.rs b/packages/process-daemon/tests/rows.rs index a747e0a580b..412367aff70 100644 --- a/packages/process-daemon/tests/rows.rs +++ b/packages/process-daemon/tests/rows.rs @@ -53,7 +53,7 @@ fn daemon_client_read_rows_roundtrip() { ); let registration = opencode_pty::daemon::read_registration(&directory).unwrap(); - assert_eq!(registration.protocol, 8); + assert_eq!(registration.protocol, 9); // Exercise omitted rows independently of the Rust client's null encoding. let mut stream = std::os::unix::net::UnixStream::connect(registration.socket).unwrap(); write_frame( diff --git a/packages/process-daemon/tests/service.rs b/packages/process-daemon/tests/service.rs index 8c7b92ef30b..53d0706f97a 100644 --- a/packages/process-daemon/tests/service.rs +++ b/packages/process-daemon/tests/service.rs @@ -447,7 +447,7 @@ fn bursty_output_does_not_disconnect_a_healthy_observer() { fn controller_switches_without_disconnecting_observers() { let service = TerminalService::new(64 * 1024); let terminal = service - .create_pty(command("sleep 0.05; printf 'streamed\\n'; sleep 0.2")) + .create_pty(command("cat")) .expect("terminal created"); let controller = service .attach( @@ -493,12 +493,12 @@ fn controller_switches_without_disconnecting_observers() { .resize_for(terminal.id, Some("controller-a".to_string()), 90, 25) .expect("controller resizes"); - let saw_output = |events: &crossbeam_channel::Receiver| { + let saw_reclaimed = |events: &crossbeam_channel::Receiver| { let deadline = Instant::now() + Duration::from_secs(2); while Instant::now() < deadline { match events.recv_timeout(Duration::from_millis(50)) { Ok(StreamEvent::Output { bytes, .. }) - if bytes.windows(8).any(|value| value == b"streamed") => + if bytes.windows(9).any(|value| value == b"reclaimed") => { return true; } @@ -508,8 +508,6 @@ fn controller_switches_without_disconnecting_observers() { } false }; - assert!(saw_output(&controller.events)); - assert!(saw_output(&observer.events)); let takeover = service .attach( @@ -539,6 +537,8 @@ fn controller_switches_without_disconnecting_observers() { b"reclaimed\n".to_vec(), ) .expect("former controller reclaims control and writes"); + assert!(saw_reclaimed(&controller.events)); + assert!(saw_reclaimed(&observer.events)); assert!( service .write_for( diff --git a/packages/process-daemon/tests/windows-daemon.rs b/packages/process-daemon/tests/windows-daemon.rs index abc42353d7e..2aa05273e09 100644 --- a/packages/process-daemon/tests/windows-daemon.rs +++ b/packages/process-daemon/tests/windows-daemon.rs @@ -196,7 +196,7 @@ fn registration(child: &mut Child, directory: &Path) -> Registration { if let Ok(registration) = opencode_pty::daemon::read_registration(directory) && registration.pid == child.id() { - assert_eq!(registration.protocol, 8); + assert_eq!(registration.protocol, 9); assert_eq!( registration.socket, PathBuf::from(format!( @@ -658,7 +658,7 @@ fn observer_disconnect_and_control_input_preserve_independent_terminals() { matches!(daemon.request(Request::List { mode: ProcessMode::Pty }), Response::Processes { processes: terminals } if terminals.len() == 2) ); assert!( - matches!(daemon.request(Request::Ping), Response::Pong { instance_id, pid, protocol: 8, .. } + matches!(daemon.request(Request::Ping), Response::Pong { instance_id, pid, protocol: 9, .. } if instance_id == daemon.registration.instance_id && pid == daemon.registration.pid) ); assert!(matches!(daemon.own(None).1, Response::Error { .. })); diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index e61ba0e61c0..475200016fa 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -5469,6 +5469,196 @@ } } }, + "/api/experimental/generate/video": { + "post": { + "tags": ["generate"], + "operationId": "experimental.generate.video.create", + "parameters": [], + "security": [], + "responses": { + "200": { + "description": "GenerateVideoCreateResponse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenerateVideoCreateResponse" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "ProviderNotFoundError | ModelNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProviderNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/ModelNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + }, + "422": { + "description": "UnsupportedModelError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnsupportedModelErrorEncoded" + } + } + } + }, + "502": { + "description": "ProviderRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProviderRequestErrorEncoded" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished video as a blob for 7 days; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + "summary": "Create a video generation", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Generate.VideoRequest" + } + } + }, + "required": true + } + } + }, + "/api/experimental/generate/video/{id}": { + "get": { + "tags": ["generate"], + "operationId": "experimental.generate.video.get", + "parameters": [ + { + "name": "id", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Generate.VideoID" + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "GenerateVideoGetResponse", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenerateVideoGetResponse" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "403": { + "description": "ForbiddenError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenErrorEncoded" + } + } + } + }, + "404": { + "description": "VideoNotFoundError | LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/VideoNotFoundErrorEncoded" + }, + { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + ] + } + } + } + } + }, + "description": "Read a video job: running, completed with the video's blob, or error with a reason. Jobs are kept in memory, so a server restart forgets them; a finished video's blob stays readable. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + "summary": "Read a video generation" + } + }, "/api/experimental/generate/decisions": { "post": { "tags": ["generate"], @@ -12204,6 +12394,68 @@ "summary": "Read a session preview file" } }, + "/api/experimental/blob/{id}": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.blob.get", + "parameters": [ + { + "name": "id", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Blob.ID" + }, + "required": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "404": { + "description": "BlobNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlobNotFoundErrorEncoded" + } + } + } + } + }, + "description": "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are deleted 7 days after they're written. Experimental: may change without compatibility guarantees.", + "summary": "Read a blob" + } + }, "/api/experimental/schedule": { "post": { "tags": ["experimental"], @@ -16164,6 +16416,47 @@ "required": ["_tag", "artifactID", "message"], "additionalProperties": false }, + "Blob.ID": { + "type": "string", + "pattern": "^video_[0-9a-f]{12}[0-9A-Za-z]{14}_(0|[1-9][0-9]{0,2})$" + }, + "Blob.Info": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Blob.ID" + }, + "mime": { + "type": "string" + }, + "bytes": { + "type": "number" + }, + "expiresAt": { + "type": "number", + "description": "Epoch milliseconds after which the blob may be deleted. Read it with GET /api/experimental/blob/:id" + } + }, + "required": ["id", "mime", "bytes", "expiresAt"], + "additionalProperties": false + }, + "BlobNotFoundErrorEncoded": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": ["BlobNotFoundError"] + }, + "blobID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": ["_tag", "blobID", "message"], + "additionalProperties": false + }, "Command.Info": { "type": "object", "properties": { @@ -16658,6 +16951,9 @@ "auto": { "type": "boolean" }, + "background": { + "type": "boolean" + }, "keep": { "type": "object", "properties": { @@ -16776,9 +17072,6 @@ "todo": { "type": "boolean" }, - "background_compaction": { - "type": "boolean" - }, "media_blob": { "type": "boolean" }, @@ -16788,6 +17081,9 @@ "artifacts": { "type": "boolean" }, + "video_generate": { + "type": "boolean" + }, "console_watches": { "type": "boolean" }, @@ -19056,6 +19352,22 @@ "pattern": "^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?:[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?$", "description": "Aspect ratio as width:height, for example 16:9" }, + "Generate.ImageFile": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Prompt.Base64" + }, + "mime": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": ["data", "mime"], + "additionalProperties": false + }, "Generate.ImageOutput": { "type": "object", "properties": { @@ -19289,6 +19601,145 @@ "additionalProperties": false, "description": "Token counts, when the provider reports them" }, + "Generate.VideoAspect": { + "anyOf": [ + { + "$ref": "#/components/schemas/Generate.ImageAspect" + }, + { + "type": "string", + "enum": ["auto"] + } + ], + "description": "Aspect ratio as width:height, or auto to follow the start image" + }, + "Generate.VideoCompleted": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Generate.VideoID" + }, + "status": { + "type": "string", + "enum": ["completed"] + }, + "blobs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Blob.Info" + }, + "description": "The finished videos, usually one. Read each with GET /api/experimental/blob/:id" + } + }, + "required": ["id", "status", "blobs"], + "additionalProperties": false + }, + "Generate.VideoError": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Generate.VideoID" + }, + "status": { + "type": "string", + "enum": ["error"] + }, + "error": { + "type": "string" + }, + "reason": { + "$ref": "#/components/schemas/Generate.VideoErrorReason" + } + }, + "required": ["id", "status", "error", "reason"], + "additionalProperties": false + }, + "Generate.VideoErrorReason": { + "type": "string", + "enum": ["failed", "cancelled", "expired", "unknown"], + "description": "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time" + }, + "Generate.VideoID": { + "type": "string", + "pattern": "^video_[0-9a-f]{12}[0-9A-Za-z]{14}$" + }, + "Generate.VideoJob": { + "anyOf": [ + { + "$ref": "#/components/schemas/Generate.VideoRunning" + }, + { + "$ref": "#/components/schemas/Generate.VideoCompleted" + }, + { + "$ref": "#/components/schemas/Generate.VideoError" + } + ] + }, + "Generate.VideoRequest": { + "type": "object", + "properties": { + "model": { + "$ref": "#/components/schemas/Model.Ref" + }, + "prompt": { + "type": "string" + }, + "start": { + "$ref": "#/components/schemas/Generate.ImageFile" + }, + "end": { + "$ref": "#/components/schemas/Generate.ImageFile" + }, + "references": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Generate.File" + } + }, + "duration": { + "type": "integer", + "maximum": 9007199254740991, + "exclusiveMinimum": 0 + }, + "aspect": { + "$ref": "#/components/schemas/Generate.VideoAspect" + }, + "resolution": { + "$ref": "#/components/schemas/Generate.VideoResolution" + }, + "sound": { + "type": "boolean" + } + }, + "required": ["model", "prompt"], + "additionalProperties": false + }, + "Generate.VideoResolution": { + "anyOf": [ + { + "type": "string", + "enum": ["480p", "720p", "1080p", "4k"] + }, + { + "type": "string" + } + ] + }, + "Generate.VideoRunning": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Generate.VideoID" + }, + "status": { + "type": "string", + "enum": ["running"] + } + }, + "required": ["id", "status"], + "additionalProperties": false + }, "GenerateDecisionsResponse": { "type": "object", "properties": { @@ -19326,6 +19777,26 @@ "required": ["data"], "additionalProperties": false }, + "GenerateVideoCreateResponse": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Generate.VideoRunning" + } + }, + "required": ["data"], + "additionalProperties": false + }, + "GenerateVideoGetResponse": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Generate.VideoJob" + } + }, + "required": ["data"], + "additionalProperties": false + }, "Instruction.Hash": { "type": "string", "pattern": "^[a-f0-9]{64}$" @@ -20923,7 +21394,7 @@ "anyOf": [ { "type": "string", - "enum": ["chat", "decision", "image"] + "enum": ["chat", "decision", "image", "video"] }, { "type": "string" @@ -25961,6 +26432,23 @@ "required": ["_tag", "providerID", "message"], "additionalProperties": false }, + "VideoNotFoundErrorEncoded": { + "type": "object", + "properties": { + "_tag": { + "type": "string", + "enum": ["VideoNotFoundError"] + }, + "videoID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": ["_tag", "videoID", "message"], + "additionalProperties": false + }, "VoiceModel": { "type": "object", "properties": { diff --git a/packages/protocol/src/client.ts b/packages/protocol/src/client.ts index 990c1a16d0d..df9281e145a 100644 --- a/packages/protocol/src/client.ts +++ b/packages/protocol/src/client.ts @@ -74,6 +74,37 @@ export const groupNames = { export const clientNamespace = (endpoint: { readonly path: string }) => endpoint.path === "/api/experimental" || endpoint.path.startsWith("/api/experimental/") ? "experimental" : undefined +// The client paths that shipped before experimental methods moved under `client.experimental`. Each keeps a +// deprecated alias until the next minor. Frozen: endpoints added since never had another path. +export const deprecatedClientPaths = new Set([ + "config.update", + "file.unwatch", + "file.watch", + "file.write", + "generate.decisions", + "generate.image", + "generate.text", + "integration.wellknown.add", + "mcp.add", + "mcp.client.token", + "mcp.connect", + "mcp.disconnect", + "mcp.remove", + "migration.v1.status", + "session.export", + "session.import", + "session.instructions.entry.list", + "session.instructions.entry.put", + "session.instructions.entry.remove", + "session.log", + "session.skill", + "session.stats", + "session.wait", + "usage.limits", + "voice.models", + "voice.session", +]) + export const promiseOmitEndpoints = new Set([ "pty.connect", "persistentPty.connect", @@ -85,6 +116,7 @@ export const effectOmitEndpoints = new Set([ "fs.read", "fs.write", "media.get", + "blob.get", "artifacts.view", "pty.connect", "persistentPty.connect", diff --git a/packages/protocol/src/errors.ts b/packages/protocol/src/errors.ts index 5b9937c646f..9590d7673a3 100644 --- a/packages/protocol/src/errors.ts +++ b/packages/protocol/src/errors.ts @@ -343,6 +343,24 @@ export class ScheduleNotFoundError extends Schema.TaggedError()( + "VideoNotFoundError", + { + videoID: Schema.String, + message: Schema.String, + }, + { httpApiStatus: 404 }, +) {} + +export class BlobNotFoundError extends Schema.TaggedError()( + "BlobNotFoundError", + { + blobID: Schema.String, + message: Schema.String, + }, + { httpApiStatus: 404 }, +) {} + export class ArtifactNotFoundError extends Schema.TaggedError()( "ArtifactNotFoundError", { diff --git a/packages/protocol/src/groups/blob.ts b/packages/protocol/src/groups/blob.ts new file mode 100644 index 00000000000..3c4d76440cd --- /dev/null +++ b/packages/protocol/src/groups/blob.ts @@ -0,0 +1,20 @@ +import { BlobStore } from "@opencode/schema/blob-store" +import { Schema } from "effect" +import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api" +import { BlobNotFoundError } from "../errors.js" + +/** Lives in the `server.experimental` group (see `groups/experimental.ts`). */ +export const BlobGetEndpoint = HttpApiEndpoint.get("blob.get", "/api/experimental/blob/:id", { + params: { id: BlobStore.ID }, + success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()), + error: [BlobNotFoundError], +}).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.blob.get", + summary: "Read a blob", + description: + "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are deleted 7 days after they're written. Experimental: may change without compatibility guarantees.", + // The route shares the `server.experimental` group with the persistent PTY prototype; tag it on its own. + transform: (operation) => ({ ...operation, tags: ["experimental"] }), + }), +) diff --git a/packages/protocol/src/groups/experimental.ts b/packages/protocol/src/groups/experimental.ts index 7e97b171839..86b87d31a74 100644 --- a/packages/protocol/src/groups/experimental.ts +++ b/packages/protocol/src/groups/experimental.ts @@ -1,4 +1,5 @@ import { ArtifactEndpoints } from "./artifact.js" +import { BlobGetEndpoint } from "./blob.js" import { JobEndpoints } from "./job.js" import { MediaGetEndpoint } from "./media.js" import { PersistentPtyGroup } from "./persistent-pty.js" @@ -27,6 +28,7 @@ export const ExperimentalGroup = PersistentPtyGroup.add( transform: (operation) => ({ ...operation, tags: ["experimental"] }), }), ), + BlobGetEndpoint, ...ScheduleEndpoints, ...ArtifactEndpoints, ...JobEndpoints, diff --git a/packages/protocol/src/groups/generate.ts b/packages/protocol/src/groups/generate.ts index f462b75d07d..388502dc040 100644 --- a/packages/protocol/src/groups/generate.ts +++ b/packages/protocol/src/groups/generate.ts @@ -3,6 +3,8 @@ import { Model } from "@opencode/schema/model" import { Schema } from "effect" import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api" import { + ForbiddenError, + VideoNotFoundError, InvalidRequestError, LocationNotFoundError, ModelNotFoundError, @@ -69,6 +71,34 @@ export const GenerateGroup = HttpApiGroup.make("server.generate") }), ), ) + .add( + HttpApiEndpoint.post("generate.video.create", "/api/experimental/generate/video", { + payload: Generate.VideoRequest, + success: Schema.Struct({ data: Generate.VideoRunning }).annotate({ identifier: "GenerateVideoCreateResponse" }), + error: [...errors, ForbiddenError], + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.generate.video.create", + summary: "Create a video generation", + description: + "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished video as a blob for 7 days; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + }), + ), + ) + .add( + HttpApiEndpoint.get("generate.video.get", "/api/experimental/generate/video/:id", { + params: { id: Generate.VideoID }, + success: Schema.Struct({ data: Generate.VideoJob }).annotate({ identifier: "GenerateVideoGetResponse" }), + error: [VideoNotFoundError, ForbiddenError, LocationNotFoundError], + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.generate.video.get", + summary: "Read a video generation", + description: + "Read a video job: running, completed with the video's blob, or error with a reason. Jobs are kept in memory, so a server restart forgets them; a finished video's blob stays readable. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + }), + ), + ) .add( HttpApiEndpoint.post("generate.decisions", "/api/experimental/generate/decisions", { payload: Generate.DecisionRequest, diff --git a/packages/schema/src/blob-store.ts b/packages/schema/src/blob-store.ts new file mode 100644 index 00000000000..eebe00161d4 --- /dev/null +++ b/packages/schema/src/blob-store.ts @@ -0,0 +1,22 @@ +export * as BlobStore from "./blob-store.js" + +import { Schema } from "effect" + +/** + * The ID of what made the blob and the blob's position among its outputs: `video__0` is a video job's first + * video. The prefix says what kind of blob it is. Strict, because the server names files after it. + */ +export const ID = Schema.String.check( + Schema.isPattern(/^video_[0-9a-f]{12}[0-9A-Za-z]{14}_(0|[1-9][0-9]{0,2})$/u), +).pipe(Schema.brand("Blob.ID"), Schema.annotate({ identifier: "Blob.ID" })) +export type ID = typeof ID.Type + +export interface Info extends Schema.Schema.Type {} +export const Info = Schema.Struct({ + id: ID, + mime: Schema.String, + bytes: Schema.Finite, + expiresAt: Schema.Finite.annotate({ + description: "Epoch milliseconds after which the blob may be deleted. Read it with GET /api/experimental/blob/:id", + }), +}).annotate({ identifier: "Blob.Info" }) diff --git a/packages/schema/src/config/compaction.ts b/packages/schema/src/config/compaction.ts index e1d4f650a43..9af68bd1c6d 100644 --- a/packages/schema/src/config/compaction.ts +++ b/packages/schema/src/config/compaction.ts @@ -15,6 +15,10 @@ export type Percent = typeof Percent.Type export class Info extends Schema.Class("Config.Compaction")({ auto: Schema.Boolean.pipe(optional), + background: Schema.Boolean.pipe(optional).annotate({ + description: + "Write the summary in the background as the session nears automatic compaction, so it does not wait for one (default: true). A summary that is never used still costs tokens.", + }), keep: Keep.pipe(optional), buffer: Schema.Union([Percent, NonNegativeInt]).pipe(optional).annotate({ description: diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index 22001a1ae53..ff4ea57ffbe 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -9,11 +9,10 @@ export const wildcard = "all" */ export const registry = { todo: "Enable the experimental todowrite tool.", - background_compaction: - "Enable experimental background compaction: summarize the conversation in the background as it nears the compaction threshold, so automatic compaction does not wait for the summary. Background summaries that are never used still cost tokens.", media_blob: "Store new session media once in a deduplicated blob table instead of inline in every message row.", schedules: "Enable experimental scheduled tasks that wake a session with a prompt.", artifacts: "Enable experimental artifacts backed by pluggable providers.", + video_generate: "Enable the experimental video generation API.", console_watches: "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console, and wake sessions when they change.", mcp_events: diff --git a/packages/schema/src/generate.ts b/packages/schema/src/generate.ts index 67f33a1dad8..89cf69c0b42 100644 --- a/packages/schema/src/generate.ts +++ b/packages/schema/src/generate.ts @@ -1,10 +1,12 @@ export * as Generate from "./generate.js" import { Schema } from "effect" +import { BlobStore } from "./blob-store.js" +import { descending } from "./identifier.js" import { Model } from "./model.js" import { Money } from "./money.js" import { Base64 } from "./prompt.js" -import { PositiveInt, optional } from "./schema.js" +import { PositiveInt, optional, statics } from "./schema.js" const description = (text: string) => ({ description: text }) @@ -19,6 +21,12 @@ export const File = Schema.Struct({ name: Schema.String.pipe(optional), }).annotate({ identifier: "Generate.File" }) +export interface ImageFile extends Schema.Schema.Type {} +export const ImageFile = Schema.Struct({ + ...File.fields, + mime: Schema.String.check(Schema.isPattern(/^image\//iu)), +}).annotate({ identifier: "Generate.ImageFile" }) + export interface Usage extends Schema.Schema.Type {} export const Usage = Schema.Struct({ input: Schema.Finite.pipe(optional), @@ -77,6 +85,84 @@ export const ImageResult = Schema.Struct({ native: Native.pipe(optional), }).annotate({ identifier: "Generate.ImageResult" }) +// --------------------------------------------------------------------------- +// Video +// --------------------------------------------------------------------------- + +// Strict, because the server names files after it. +export const VideoID = Schema.String.check(Schema.isPattern(/^video_[0-9a-f]{12}[0-9A-Za-z]{14}$/u)).pipe( + Schema.brand("Generate.VideoID"), + Schema.annotate({ identifier: "Generate.VideoID" }), + statics((schema) => ({ + create: () => schema.make("video_" + descending()), + })), +) +export type VideoID = typeof VideoID.Type + +export type VideoAspect = `${number}:${number}` | "auto" +export const VideoAspect: Schema.Codec = Schema.Union([ImageAspect, Schema.Literal("auto")]).annotate({ + identifier: "Generate.VideoAspect", + description: "Aspect ratio as width:height, or auto to follow the start image", +}) + +export type VideoResolution = "480p" | "720p" | "1080p" | "4k" | (string & {}) +export const VideoResolution: Schema.Codec = Schema.Union([ + Schema.Literals(["480p", "720p", "1080p", "4k"]), + Schema.String, +]).annotate({ identifier: "Generate.VideoResolution" }) + +export interface VideoRequest extends Schema.Schema.Type {} +export const VideoRequest = Schema.Struct({ + model: Model.Ref, + prompt: Schema.String, + start: ImageFile.pipe(optional).annotate(description("Image the video starts on exactly")), + end: ImageFile.pipe(optional).annotate(description("Image the video ends on exactly")), + references: Schema.Array(File) + .pipe(optional) + .annotate(description("Images, videos or audio that guide the subject or style without pinning a frame")), + duration: PositiveInt.pipe(optional).annotate(description("Length in seconds")), + aspect: VideoAspect.pipe(optional), + resolution: VideoResolution.pipe(optional), + sound: Schema.Boolean.pipe(optional).annotate( + description("Whether the video has a generated soundtrack; unset leaves the model's default"), + ), +}).annotate({ identifier: "Generate.VideoRequest" }) + +export const VideoErrorReason = Schema.Literals(["failed", "cancelled", "expired", "unknown"]).annotate({ + identifier: "Generate.VideoErrorReason", + description: + "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time", +}) +export type VideoErrorReason = typeof VideoErrorReason.Type + +export interface VideoRunning extends Schema.Schema.Type {} +export const VideoRunning = Schema.Struct({ + id: VideoID, + status: Schema.Literal("running"), +}).annotate({ identifier: "Generate.VideoRunning" }) + +export interface VideoCompleted extends Schema.Schema.Type {} +export const VideoCompleted = Schema.Struct({ + id: VideoID, + status: Schema.Literal("completed"), + blobs: Schema.Array(BlobStore.Info).annotate( + description("The finished videos, usually one. Read each with GET /api/experimental/blob/:id"), + ), +}).annotate({ identifier: "Generate.VideoCompleted" }) + +export interface VideoError extends Schema.Schema.Type {} +export const VideoError = Schema.Struct({ + id: VideoID, + status: Schema.Literal("error"), + error: Schema.String, + reason: VideoErrorReason, +}).annotate({ identifier: "Generate.VideoError" }) + +export type VideoJob = VideoRunning | VideoCompleted | VideoError +export const VideoJob = Schema.Union([VideoRunning, VideoCompleted, VideoError]).annotate({ + identifier: "Generate.VideoJob", +}) + // --------------------------------------------------------------------------- // Decisions // --------------------------------------------------------------------------- diff --git a/packages/schema/src/model.ts b/packages/schema/src/model.ts index f3e464197d2..dd896134967 100644 --- a/packages/schema/src/model.ts +++ b/packages/schema/src/model.ts @@ -50,9 +50,9 @@ export const Family = Schema.String.pipe(Schema.brand("Model.Family")) export type Family = typeof Family.Type /** What a model produces, from models.dev. Open-ended: new types keep being added. Only chat models are offered for sessions; an unset type means chat. */ -export type Type = "chat" | "decision" | "image" | (string & {}) +export type Type = "chat" | "decision" | "image" | "video" | (string & {}) export const Type: Schema.Codec = Schema.Union([ - Schema.Literals(["chat", "decision", "image"]), + Schema.Literals(["chat", "decision", "image", "video"]), Schema.String, ]).annotate({ identifier: "Model.Type" }) diff --git a/packages/server/src/handlers/blob.ts b/packages/server/src/handlers/blob.ts new file mode 100644 index 00000000000..98d3bddb13b --- /dev/null +++ b/packages/server/src/handlers/blob.ts @@ -0,0 +1,55 @@ +import { BlobStore } from "@opencode/core/blob-store" +import { BlobNotFoundError } from "@opencode/protocol/errors" +import { FSUtil } from "@opencode/util/fs-util" +import { Effect } from "effect" +import { type HttpServerRequest, HttpServerResponse } from "effect/http" +import { ContentHeaders } from "../content-headers" +import { ByteRange } from "../range" + +/** `blob.get` in the `server.experimental` group. Raw, so it can stream the file and answer Range and 304 itself. */ +export const makeBlobGet = Effect.gen(function* () { + const blobs = yield* BlobStore.Service + const fs = yield* FSUtil.Service + return (id: BlobStore.ID, request: HttpServerRequest.HttpServerRequest) => + Effect.gen(function* () { + const blob = yield* blobs + .read(id) + .pipe(Effect.mapError((error) => new BlobNotFoundError({ blobID: error.id, message: error.message }))) + // The ID names one immutable blob. + const etag = `"${id}"` + const headers = { + ...ContentHeaders.download({ mime: blob.mime }), + "cache-control": "private, max-age=604800, immutable", + etag, + "accept-ranges": "bytes", + } + if ( + request.headers["if-none-match"] + ?.split(",") + .some((tag) => tag.trim() === "*" || tag.trim().replace(/^w\//i, "") === etag) + ) + return HttpServerResponse.empty({ status: 304, headers }) + // If-Range takes only a strong match (RFC 9110 13.1.5); anything else serves the whole body. + const ifRange = request.headers["if-range"] + const range = + ifRange === undefined || ifRange.trim() === etag + ? ByteRange.parse(request.headers["range"], blob.bytes) + : undefined + if (range === "unsatisfiable") + return HttpServerResponse.empty({ + status: 416, + headers: { ...headers, "content-range": `bytes */${blob.bytes}` }, + }) + const offset = range?.start ?? 0 + const length = range === undefined ? blob.bytes : range.end - range.start + 1 + return HttpServerResponse.stream(fs.stream(blob.path, { offset, bytesToRead: length }), { + status: range === undefined ? 200 : 206, + contentType: headers["content-type"], + contentLength: length, + headers: + range === undefined + ? headers + : { ...headers, "content-range": `bytes ${range.start}-${range.end}/${blob.bytes}` }, + }) + }) +}) diff --git a/packages/server/src/handlers/fs.ts b/packages/server/src/handlers/fs.ts index 77c6515d44d..b0c5def6f56 100644 --- a/packages/server/src/handlers/fs.ts +++ b/packages/server/src/handlers/fs.ts @@ -10,6 +10,7 @@ import path from "path" import { Api } from "../api" import { ContentHeaders } from "../content-headers" import { response } from "../location" +import { ByteRange } from "../range" export const FileSystemHandler = HttpApiBuilder.group(Api, "server.fs", (handlers) => Effect.gen(function* () { @@ -125,7 +126,7 @@ function serveFile( const rangeHeader = request.method === "GET" ? request.headers["range"] : undefined const range = rangeHeader !== undefined && matchesIfRange(request.headers["if-range"], etag, lastModified) - ? parseRange(rangeHeader, file.size) + ? ByteRange.parse(rangeHeader, file.size) : undefined if (range === "unsatisfiable") return HttpServerResponse.empty({ @@ -168,17 +169,3 @@ function matchesIfRange(ifRange: string | undefined, etag: string, lastModified: function stripWeak(etag: string) { return etag.trim().replace(/^w\//i, "") } - -export function parseRange(header: string, size: number) { - const match = /^bytes=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(header.trim()) - if (match === null || (match[1] === "" && match[2] === "")) return undefined - if (match[1] === "") { - const suffix = Number(match[2]) - if (suffix === 0 || size === 0) return "unsatisfiable" - return { start: Math.max(size - suffix, 0), end: size - 1 } - } - const start = Number(match[1]) - const end = match[2] === "" ? size - 1 : Number(match[2]) - if (start > end || start >= size) return "unsatisfiable" - return { start, end: Math.min(end, size - 1) } -} diff --git a/packages/server/src/handlers/generate.ts b/packages/server/src/handlers/generate.ts index 73b916fea9d..ba6545ff96a 100644 --- a/packages/server/src/handlers/generate.ts +++ b/packages/server/src/handlers/generate.ts @@ -1,15 +1,19 @@ +import { Flag } from "@opencode/core/flag" import { Generate } from "@opencode/core/generate" +import { VideoGeneration } from "@opencode/core/video-generation" import { Location } from "@opencode/core/location" import { LocationServiceMap } from "@opencode/core/location-services" import { AbsolutePath } from "@opencode/core/schema" import { + ForbiddenError, + VideoNotFoundError, InvalidRequestError, ModelNotFoundError, ProviderRequestError, ServiceUnavailableError, UnsupportedModelError, } from "@opencode/protocol/errors" -import type { DecisionRequest, ImageRequest } from "@opencode/schema/generate" +import type { DecisionRequest, VideoID, ImageRequest, VideoRequest } from "@opencode/schema/generate" import { Global } from "@opencode/util/global" import { Model } from "@opencode/schema/model" import { Effect } from "effect" @@ -21,6 +25,7 @@ export const GenerateHandler = HttpApiBuilder.group(Api, "server.generate", (han Effect.gen(function* () { const global = yield* Global.Service const locations = yield* LocationServiceMap.Service + const videos = yield* VideoGeneration.Service const services = locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) })) const text = Effect.fn("server.generate.text")( function* (request: { readonly payload: { readonly prompt: string; readonly model?: Model.Ref } }) { @@ -55,11 +60,38 @@ export const GenerateHandler = HttpApiBuilder.group(Api, "server.generate", (han Effect.provide(services), locationErrors, ) + // The flag is read from the same base configuration generation runs on. + const videoEnabled = Effect.gen(function* () { + if (yield* Flag.enabled("video_generate")) return + return yield* new ForbiddenError({ message: "Video generation is disabled; enable experimental.video_generate" }) + }) + const videoCreate = Effect.fn("server.generate.video.create")( + function* (request: { readonly payload: VideoRequest }) { + yield* videoEnabled + yield* awaitPlugins + return { data: yield* videos.start(request.payload).pipe(Effect.mapError(generateError)) } + }, + Effect.provide(services), + locationErrors, + ) + const videoGet = Effect.fn("server.generate.video.get")( + function* (request: { readonly params: { readonly id: VideoID } }) { + yield* videoEnabled + const job = yield* videos + .get(request.params.id) + .pipe(Effect.mapError((error) => new VideoNotFoundError({ videoID: error.id, message: error.message }))) + return { data: job } + }, + Effect.provide(services), + locationErrors, + ) return handlers .handle("generate.text", text) .handle("generate.textLegacy", text) .handle("generate.image", image) .handle("generate.decisions", decisions) + .handle("generate.video.create", videoCreate) + .handle("generate.video.get", videoGet) }), ) diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index bce1e19edb2..12a75bd661a 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -19,6 +19,7 @@ import { Api } from "../api" import { CorsConfig, isAllowedRequestOrigin } from "../cors" import { makeArtifact } from "./artifact" import { makePreviewRead } from "./preview" +import { makeBlobGet } from "./blob" import { makeJob } from "./job" import { makeMediaGet } from "./media" import { type Outbound, runPtySocket } from "./pty-socket" @@ -33,11 +34,13 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment const previewRead = yield* makePreviewRead const job = yield* makeJob const mediaGet = yield* makeMediaGet + const blobGet = yield* makeBlobGet const schedule = yield* makeSchedule return handlers .handleRaw("media.get", (ctx) => mediaGet(ctx.params.hash, ctx.request)) .handleRaw("preview.read", (ctx) => previewRead(ctx.query, ctx.request)) + .handleRaw("blob.get", (ctx) => blobGet(ctx.params.id, ctx.request)) .handle("job.list", (ctx) => job.list(ctx.query)) .handle("artifacts.providers", (ctx) => artifact.providers(ctx.query, ctx.request)) .handle("artifacts.list", (ctx) => artifact.list(ctx.query, ctx.request)) diff --git a/packages/server/src/handlers/preview.ts b/packages/server/src/handlers/preview.ts index 5b7f649de5c..277d7408ee4 100644 --- a/packages/server/src/handlers/preview.ts +++ b/packages/server/src/handlers/preview.ts @@ -10,7 +10,7 @@ import { Effect, Stream } from "effect" import path from "node:path" import { type HttpServerRequest, HttpServerResponse } from "effect/http" import { ContentHeaders } from "../content-headers" -import { parseRange } from "./fs" +import { ByteRange } from "../range" import { missingSession } from "./session-error" export const makePreviewRead = Effect.gen(function* () { @@ -83,7 +83,7 @@ export const makePreviewRead = Effect.gen(function* () { }).pipe(Effect.provide(locations.get(session.location)), Effect.orElseSucceed(() => false)) if (!allowed) return HttpServerResponse.empty({ status: 404, headers: { ...headers, "x-opencode-preview-denied": "1" } }) } - const range = req.headers.range ? parseRange(req.headers.range, opened.size) : undefined + const range = req.headers.range ? ByteRange.parse(req.headers.range, opened.size) : undefined if (range === "unsatisfiable") return HttpServerResponse.empty({ status: 416, diff --git a/packages/server/src/range.ts b/packages/server/src/range.ts new file mode 100644 index 00000000000..e79f844bf9a --- /dev/null +++ b/packages/server/src/range.ts @@ -0,0 +1,16 @@ +export * as ByteRange from "./range" + +/** A single `bytes=` range of a `size`-byte body, inclusive. Undefined serves the whole body. */ +export function parse(header: string | undefined, size: number) { + const match = header === undefined ? null : /^bytes=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(header.trim()) + if (match === null || (match[1] === "" && match[2] === "")) return undefined + if (match[1] === "") { + const suffix = Number(match[2]) + if (suffix === 0 || size === 0) return "unsatisfiable" + return { start: Math.max(size - suffix, 0), end: size - 1 } + } + const start = Number(match[1]) + const end = match[2] === "" ? size - 1 : Number(match[2]) + if (start > end || start >= size) return "unsatisfiable" + return { start, end: Math.min(end, size - 1) } +} diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 1b9f033a64a..f288a6b63cf 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -14,6 +14,8 @@ import { PermissionSaved } from "@opencode/core/permission/saved" import { PtyTicket } from "@opencode/core/pty/ticket" import { PersistentPty } from "@opencode/core/persistent-pty" import { Project } from "@opencode/core/project" +import { BlobStore } from "@opencode/core/blob-store" +import { VideoGeneration } from "@opencode/core/video-generation" import { Worktree } from "@opencode/core/worktree" import { Session } from "@opencode/core/session" import { Instance } from "@opencode/core/instance/service" @@ -88,6 +90,10 @@ const applicationServiceNodes = [ LocationActivity.node, SessionRestart.node, Schedule.node, + // Its hourly cleanup belongs to the server. + BlobStore.node, + // Its polling fibers belong to the server, not to the request that started them. + VideoGeneration.node, Workspace.node, FileWatch.node, ] as const diff --git a/packages/server/src/workerd.ts b/packages/server/src/workerd.ts index 258650a4be8..e2948d8ff78 100644 --- a/packages/server/src/workerd.ts +++ b/packages/server/src/workerd.ts @@ -8,6 +8,8 @@ import type { DurableObjectStorage } from "@opencode/core/database/sqlite.worker import { EnvironmentUnavailable } from "@opencode/core/environment/unavailable" import { FileSystem } from "@opencode/core/filesystem" import { FileSystemSearch } from "@opencode/core/filesystem/search" +import { BlobStore } from "@opencode/core/blob-store" +import { VideoGeneration } from "@opencode/core/video-generation" import { Pty } from "@opencode/core/pty" import { Snapshot } from "@opencode/core/snapshot" import { Vcs } from "@opencode/core/vcs" @@ -30,6 +32,7 @@ import type { ServerOptions } from "./options" * FileSystemSearch, and Pty fail with a clear defect until a remote sandbox * backs them; Npm fails package installs with a typed workerd error; Snapshot * and Vcs degrade to no-op results. + * - Blob storage and video generation report themselves unsupported: blobs are files on a local disk. * - Config is injected as a string (no filesystem); plugin discovery is * precompiled-only, and stdio MCP reports the same no-plane failure as Shell. * @@ -88,6 +91,9 @@ export function replacements(options: Options): LayerNode.Replacements { FileSystemSearch.node.replace(fileSystemSearchLayer), Pty.node.replace(ptyLayer), Npm.node.replace(npmLayer), + // Blobs need a local `blobs/` folder, which a Durable Object doesn't have. + BlobStore.node.replace(BlobStore.unsupportedLayer), + VideoGeneration.node.replace(VideoGeneration.unsupportedLayer), // Precompiled (internal and SDK) plugins only: no plugin-directory scan, npm // install, or import of plugin code from disk. ConfigPluginSource.node.replace(ConfigPluginSource.empty), diff --git a/packages/server/test/generate.test.ts b/packages/server/test/generate.test.ts index b11418fb74e..772fed39cc2 100644 --- a/packages/server/test/generate.test.ts +++ b/packages/server/test/generate.test.ts @@ -26,6 +26,11 @@ const generate = makeLocationNode({ ), image: () => Effect.die("unused"), decisions: () => Effect.die("unused"), + video: { + start: () => Effect.die("unused"), + status: () => Effect.die("unused"), + result: () => Effect.die("unused"), + }, }) }), ), diff --git a/packages/server/test/schema-error.test.ts b/packages/server/test/schema-error.test.ts index fb65c5cde46..7ad2f9d6c85 100644 --- a/packages/server/test/schema-error.test.ts +++ b/packages/server/test/schema-error.test.ts @@ -15,6 +15,11 @@ const generate = makeLocationNode({ text: () => Effect.succeed(42 as unknown as string), image: () => Effect.die("unused"), decisions: () => Effect.die("unused"), + video: { + start: () => Effect.die("unused"), + status: () => Effect.die("unused"), + result: () => Effect.die("unused"), + }, }), ), deps: [], diff --git a/packages/server/test/video-generate.test.ts b/packages/server/test/video-generate.test.ts new file mode 100644 index 00000000000..cb174eca88e --- /dev/null +++ b/packages/server/test/video-generate.test.ts @@ -0,0 +1,147 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { expect } from "bun:test" +import { Generate } from "@opencode/core/generate" +import { makeLocationNode } from "@opencode/util/effect/app-node" +import { Global } from "@opencode/util/global" +import { Effect, Layer, Stream } from "effect" +import { tmpdirScoped } from "../../core/test/fixture/tmpdir" +import { it } from "../../core/test/lib/effect" +import { eventually } from "../../core/test/lib/eventually" +import { ServerFetch } from "../src/fetch" + +// An MP4 `ftyp` box, so the type is read from the bytes: "0123456789" are the first ten bytes. +const video = Uint8Array.from([0, 0, 0, 0x14, ...new TextEncoder().encode("ftypmp42"), 0, 0, 0, 0, 1, 2, 3, 4]) + +// A provider whose jobs finish on the first status read. +const generate = makeLocationNode({ + service: Generate.Service, + layer: Layer.succeed( + Generate.Service, + Generate.Service.of({ + text: () => Effect.die("unused"), + image: () => Effect.die("unused"), + decisions: () => Effect.die("unused"), + video: { + start: () => Effect.succeed({ id: "provider_1" }), + status: () => Effect.succeed({ status: "completed" }), + result: () => Effect.succeed([{ mime: "video/mp4", stream: Stream.make(video) }]), + }, + }), + ), + deps: [], +}) + +const serve = (dir: string, enabled: boolean) => + ServerFetch.make( + { + app: { version: "test" }, + database: { path: path.join(dir, "opencode.db") }, + config: { + directory: dir, + project: false, + content: JSON.stringify({ experimental: { video_generate: enabled } }), + }, + models: { fetch: false }, + fs: { filewatcher: false }, + }, + // Blobs go under the test's own data directory. + { + overrides: [ + Global.node.replace(Global.layerWith({ data: path.join(dir, "data"), config: dir })), + Generate.node.replace(generate), + ], + }, + ) + +const base = "http://opencode.local/api/experimental" +const unknown = `video_${"0".repeat(12)}${"A".repeat(14)}` + +it.live("generates a video in the background and serves its blob with Range and ETag support", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-video-route-")).path + const handler = yield* serve(dir, true) + const call = (url: string, init?: RequestInit) => Effect.promise(() => handler(new Request(url, init))) + + const started = yield* call(`${base}/generate/video`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: { providerID: "test", id: "video" }, prompt: "a cat" }), + }) + expect(started.status).toBe(200) + const { data } = (yield* Effect.promise(() => started.json())) as { data: { id: string; status: string } } + expect(data).toMatchObject({ status: "running" }) + expect(data.id.startsWith("video_")).toBe(true) + + const completed = yield* eventually( + call(`${base}/generate/video/${data.id}`).pipe( + Effect.flatMap((response) => Effect.promise(() => response.json())), + ), + (body: { data: Record }) => body.data.status !== "running", + ) + const blob = `${data.id}_0` + expect(completed.data).toEqual({ + id: data.id, + status: "completed", + blobs: [{ id: blob, mime: "video/mp4", bytes: 20, expiresAt: expect.any(Number) }], + }) + const route = `${base}/blob/${blob}` + + const full = yield* call(route) + expect(full.status).toBe(200) + expect(full.headers.get("content-type")).toBe("video/mp4") + expect(full.headers.get("accept-ranges")).toBe("bytes") + expect(full.headers.get("etag")).toBe(`"${blob}"`) + expect(full.headers.get("content-disposition")).toBe("attachment") + expect(new Uint8Array(yield* Effect.promise(() => full.arrayBuffer()))).toEqual(video) + + const slice = yield* call(route, { headers: { range: "bytes=2-5" } }) + expect(slice.status).toBe(206) + expect(slice.headers.get("content-range")).toBe("bytes 2-5/20") + expect(new Uint8Array(yield* Effect.promise(() => slice.arrayBuffer()))).toEqual(video.slice(2, 6)) + const suffix = yield* call(route, { headers: { range: "bytes=-3" } }) + expect(new Uint8Array(yield* Effect.promise(() => suffix.arrayBuffer()))).toEqual(video.slice(17)) + const unsatisfiable = yield* call(route, { headers: { range: "bytes=20-" } }) + expect(unsatisfiable.status).toBe(416) + expect(unsatisfiable.headers.get("content-range")).toBe("bytes */20") + // A Range for another version of the bytes gets the whole body. + const stale = yield* call(route, { headers: { range: "bytes=2-5", "if-range": '"other"' } }) + expect(stale.status).toBe(200) + + const cached = yield* call(route, { headers: { "if-none-match": `"${blob}"` } }) + expect(cached.status).toBe(304) + expect((yield* Effect.promise(() => cached.arrayBuffer())).byteLength).toBe(0) + + // A restarted server reads the finished job back from its blobs. + const restarted = yield* serve(dir, true) + const reread = yield* Effect.promise(() => restarted(new Request(`${base}/generate/video/${data.id}`))) + expect(((yield* Effect.promise(() => reread.json())) as { data: unknown }).data).toEqual(completed.data) + + // Once its file is gone, the blob and the job are gone. + yield* Effect.promise(() => fs.rm(path.join(dir, "data", "blobs", blob))) + expect((yield* call(route)).status).toBe(404) + expect((yield* call(`${base}/generate/video/${data.id}`)).status).toBe(404) + + expect((yield* call(`${base}/generate/video/${unknown}`)).status).toBe(404) + // An ID that isn't one never reaches the disk. + expect((yield* call(`${base}/blob/video_..%2F..%2Fsecret`)).status).toBe(400) + }).pipe(Effect.scoped), +) + +it.live("rejects video routes while experimental.video_generate is off", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-video-off-")).path + const handler = yield* serve(dir, false) + const start = yield* Effect.promise(() => + handler( + new Request(`${base}/generate/video`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: { providerID: "test", id: "video" }, prompt: "a cat" }), + }), + ), + ) + expect(start.status).toBe(403) + expect((yield* Effect.promise(() => handler(new Request(`${base}/generate/video/${unknown}`)))).status).toBe(403) + }).pipe(Effect.scoped), +) diff --git a/packages/session-ui/component-tests/session-compaction.spec.ts b/packages/session-ui/component-tests/session-compaction.spec.ts index 946d96b1824..52524f986d4 100644 --- a/packages/session-ui/component-tests/session-compaction.spec.ts +++ b/packages/session-ui/component-tests/session-compaction.spec.ts @@ -127,27 +127,6 @@ story("warms the label only once the gathering light reaches it", async ({ mount expect(cooled).toEqual([0, 0]) }) -story("keeps the full record for a running automatic compaction with background compaction off", async ({ mount }) => { - const timeline = await mount(`${rows}--compaction-in-progress`, { args: { backgroundCompaction: false } }) - const message = timeline.locator('[data-component="session-compaction-message"]') - - await expect(message).not.toHaveAttribute("data-quiet") - await expect(message.locator('[data-slot="session-compaction-divider"]')).toHaveCount(0) - await expect(message).toContainText("Session compaction started") - await expect(message.getByRole("status")).toBeVisible() -}) - -story("keeps the full record for a finished automatic compaction with background compaction off", async ({ mount }) => { - const timeline = await mount(`${rows}--compaction-and-continuation`, { args: { backgroundCompaction: false } }) - const message = timeline.locator('[data-component="session-compaction-message"]') - - await expect(message).not.toHaveAttribute("data-quiet") - await expect(message.locator('[data-slot="session-compaction-divider"]')).toHaveCount(0) - await expect(message).toContainText("Session compaction started") - await expect(message).toContainText("The Session timeline now consumes current nested assistant content.") - await expect(message).toContainText("Session compacted · 11.9K in · 508 out") -}) - story("keeps the full record for a manual compaction", async ({ mount }) => { const timeline = await mount(`${rows}--compaction-manual`) const message = timeline.locator('[data-component="session-compaction-message"]') diff --git a/packages/session-ui/src/context/data.tsx b/packages/session-ui/src/context/data.tsx index c1ba20b9097..a35f082710e 100644 --- a/packages/session-ui/src/context/data.tsx +++ b/packages/session-ui/src/context/data.tsx @@ -81,8 +81,6 @@ export const { peekMedia?: PeekMediaUrlFn onNavigateToSession?: NavigateToSessionFn onSessionHref?: SessionHrefFn - /** Whether `experimental.background_compaction` is on for this location; automatic compactions then show quietly. */ - backgroundCompaction?: boolean }) => { return { get store() { @@ -100,9 +98,6 @@ export const { get copyAlwaysVisible() { return props.copyAlwaysVisible === true }, - get backgroundCompaction() { - return props.backgroundCompaction === true - }, navigateToSession: props.onNavigateToSession, sessionHref: props.onSessionHref, shellRunning: props.shellRunning, diff --git a/packages/session-ui/src/message/message-content.tsx b/packages/session-ui/src/message/message-content.tsx index 0db7c12e580..4096aab8aaf 100644 --- a/packages/session-ui/src/message/message-content.tsx +++ b/packages/session-ui/src/message/message-content.tsx @@ -935,7 +935,6 @@ function CompactionDivider(props: { label: string }) { export function SessionCompactionMessage(props: { message: SessionMessageCompaction; error: string }) { const i18n = useI18n() - const data = useData() const summary = () => (props.message.status === "failed" ? "" : props.message.summary) const error = () => { @@ -982,7 +981,7 @@ export function SessionCompactionMessage(props: { message: SessionMessageCompact return ( {(revision) => (
- + (props.message.status === "failed" ? "" : props.message.summary) const error = () => { @@ -81,7 +79,7 @@ export function CompactionMessage(props: { message: SessionMessageCompaction; er return (
- + @@ -444,7 +444,7 @@ function CompactSessionStory() { Cancel next compaction - + @@ -453,34 +453,24 @@ function CompactSessionStory() { const CompactSession = { render: () => } -// Automatic compactions only show quietly with experimental.background_compaction on; turn it off to see today's record. -const backgroundCompaction = { - args: { backgroundCompaction: true }, - argTypes: { backgroundCompaction: { control: "boolean" } }, -} - export const CompactionInProgress = { - ...backgroundCompaction, - render: (args: { backgroundCompaction: boolean }) => ( + render: () => ( ), } export const CompactionAndContinuation = { - ...backgroundCompaction, - render: (args: { backgroundCompaction: boolean }) => ( + render: () => ( ), } @@ -492,7 +482,6 @@ export const CompactionManual = { description="A /compact keeps the full record: started divider, summary and usage." document={compactionManualDocument} width="600px" - backgroundCompaction /> ), } @@ -542,7 +531,7 @@ function CompactionReplayStory(props: { duration: number }) { Replay - + @@ -568,7 +557,6 @@ export const CompactionFailed = { description="A failed compaction keeps the production divider and shows the provider error." document={compactionFailedDocument} width="600px" - backgroundCompaction /> ), } @@ -580,7 +568,6 @@ export const CompactionCancelled = { description="An interrupted compaction keeps the production divider without an empty error block." document={compactionCancelledDocument} width="600px" - backgroundCompaction /> ), } diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index 8f04fb09387..09a7bea6de9 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -13,7 +13,7 @@ import { type Accessor, } from "solid-js" import path from "node:path" -import { EOL } from "node:os" +import { EOL, tmpdir } from "node:os" import { mkdir, writeFile } from "node:fs/promises" import { useRoute, useRouteData } from "../../context/route" import { createStore } from "solid-js/store" @@ -1378,7 +1378,7 @@ export function Session(props: { } const filepath = path.join( - paths.cwd, + options.location === "temp" ? tmpdir() : paths.cwd, `session-${crypto.randomUUID()}.${options.format === "markdown" ? "md" : "json"}`, ) await writeExport(filepath, content) diff --git a/packages/tui/src/ui/dialog-export-options.tsx b/packages/tui/src/ui/dialog-export-options.tsx index 014e76b7bb5..7b4cb36a3f1 100644 --- a/packages/tui/src/ui/dialog-export-options.tsx +++ b/packages/tui/src/ui/dialog-export-options.tsx @@ -7,12 +7,14 @@ import { createStore } from "solid-js/store" import { createMemo, createSignal, For, Show } from "solid-js" export type ExportFormat = "markdown" | "json" +export type ExportLocation = "project" | "temp" export type DialogExportOptionsProps = { defaultThinking: boolean onConfirm?: (options: { action: "copy" | "export" format: ExportFormat + location?: ExportLocation thinking: boolean tools: boolean sanitize: boolean @@ -31,12 +33,13 @@ export function DialogExportOptions(props: DialogExportOptionsProps) { ) } -type Row = "format" | "thinking" | "tools" | "sanitize" +type Row = "format" | "location" | "thinking" | "tools" | "sanitize" /** Export options as a list of values, under the "new-designs" experiment: ↑/↓ moves, ←/→ or space changes. */ function DialogExportOptionsList(props: DialogExportOptionsProps) { const [store, setStore] = createStore({ format: "markdown" as ExportFormat, + location: "project" as ExportLocation, thinking: props.defaultThinking, tools: true, sanitize: false, @@ -47,6 +50,7 @@ function DialogExportOptionsList(props: DialogExportOptionsProps) { props.onConfirm?.({ action, format: store.format, + location: store.location, thinking: store.thinking, tools: store.tools, sanitize: store.sanitize, @@ -54,6 +58,7 @@ function DialogExportOptionsList(props: DialogExportOptionsProps) { const change = (row: Row) => { if (row === "format") return setStore("format", store.format === "markdown" ? "json" : "markdown") + if (row === "location") return setStore("location", store.location === "project" ? "temp" : "project") setStore(row, !store[row]) } @@ -66,6 +71,13 @@ function DialogExportOptionsList(props: DialogExportOptionsProps) { footerOverhang: 2, footer: , }, + { + title: "Location", + value: "location" as Row, + onSelect: () => change("location"), + footerOverhang: 2, + footer: , + }, ...(store.format === "markdown" ? [ { @@ -286,6 +298,7 @@ DialogExportOptions.show = (dialog: DialogContext, defaultThinking: boolean) => return new Promise<{ action: "copy" | "export" format: ExportFormat + location?: ExportLocation thinking: boolean tools: boolean sanitize: boolean diff --git a/services/site/src/docs/content/compaction.mdx b/services/site/src/docs/content/compaction.mdx index 47a373834cd..4f73e220780 100644 --- a/services/site/src/docs/content/compaction.mdx +++ b/services/site/src/docs/content/compaction.mdx @@ -83,6 +83,7 @@ Add `compaction` to any [OpenCode configuration file](/config): | Field | Default | Behavior | | --- | ---: | --- | | `auto` | `true` | Compact automatically near the context limit, and recover once when a provider rejects a request as too long. Manual compaction always works. | +| `background` | `true` | Write the summary ahead of time so automatic compaction doesn't wait for it. See [Background compaction](#background-compaction). | | `keep.tokens` | `15000` | Approximate recent conversation kept beside the summary. Larger values preserve more detail but leave less room for new work. | | `buffer` | `"15%"`, at least 16k | Share of the model's context window kept free. Automatic compaction starts once the conversation reaches the rest. Larger values compact earlier. | @@ -120,21 +121,8 @@ If that model cannot be resolved, OpenCode falls back to the session's model. ## Background compaction - - Experimental. This may change, break, or be removed in any release without notice. - - -Automatic compaction normally pauses the session while the summary is written. With background compaction, OpenCode -writes the summary ahead of time and swaps it in when compaction is due: - -```jsonc title="opencode.jsonc" -{ - "$schema": "https://opencode.ai/config.json", - "experimental": { - "background_compaction": true, - }, -} -``` +OpenCode writes the summary ahead of time, while the session keeps going, and swaps it in when compaction is due. +Automatic compaction then doesn't pause the session to write one: ```text 60k tokens before the threshold summary of the conversation so far starts in the background @@ -149,10 +137,21 @@ and the threshold. | --- | --- | | Cost | The summary request reuses the prompt cache. A summary that is never used, for example because the session ends before the threshold, still costs tokens. | | Waits | If the summary is still being written when compaction is due, the session waits for it to finish. | -| Falls back | Compaction summarizes as usual if the conversation since the held summary grew past about 40% of the threshold, or if the model, instructions, or start of the conversation changed. | -| Skipped | Not used for native compaction, right after a model switch, or when a provider rejects a request as too long. After a break longer than the prompt cache lifetime, it starts from the next response instead. | +| Falls back | Compaction summarizes as usual if the conversation since the held summary grew past about 40% of the threshold, or if the start of the conversation changed. | +| Skipped | Not used for native compaction. Right after a model switch, or after a break longer than the prompt cache lifetime, it starts from the next response instead. | | Storage | Held summaries live in memory and are lost on restart. | +Turn it off to write the summary only when compaction is due: + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "compaction": { + "background": false, + }, +} +``` + ## Providers Some providers can compact the conversation on their side instead. Enable it per diff --git a/services/site/src/docs/content/config.mdx b/services/site/src/docs/content/config.mdx index 0cded3ea2da..3a6cf47e547 100644 --- a/services/site/src/docs/content/config.mdx +++ b/services/site/src/docs/content/config.mdx @@ -629,7 +629,6 @@ All experimental settings live under the `experimental` key: "experimental": { "todo": true, "subagent_depth": 2, - "background_compaction": true, "image_generate": { "model": "openai/gpt-image-2" }, "location_idle_timeout": "4 hours", }, @@ -645,20 +644,6 @@ Set `todo` to `true` to give agents a `todowrite` tool for tracking multi-step w `subagent_depth` sets how deeply subagents can start their own subagents. Defaults to `1`, so a subagent cannot start another subagent. -### Background compaction - -Set `background_compaction` to `true` to write the compaction summary in the background before it is needed, so -automatic compaction doesn't pause the session. Defaults to `false`. See -[Compaction](/compaction#background-compaction) for how it works. - -```jsonc -{ - "experimental": { - "background_compaction": true, - }, -} -``` - ### Image generation `image_generate` sets the default model for the [`experimental_image_generate`](/tools#image-generate) tool, as diff --git a/services/site/src/docs/content/console/go.mdx b/services/site/src/docs/content/console/go.mdx index 4fe6f1252a9..15f1bbe5504 100644 --- a/services/site/src/docs/content/console/go.mdx +++ b/services/site/src/docs/content/console/go.mdx @@ -5,11 +5,11 @@ description: "Reliable access to open coding models with three plans, for one pe OpenCode Go gives you reliable access to popular open coding models, with three monthly plans: -| Plan | Price | Included usage | -| ------------ | -------------------- | -------------------------------------------------------------------------- | -| **Go** | **$10/month** | Lower-cost access to the models below | -| **Go Plus** | **$40/month** | Higher usage limits across the models below | -| **Go Teams** | **$20/member/month** | Every member gets their own limits, $5/month higher than Go on every model | +| Plan | Price | Included usage | +| ------------ | -------------------------------------- | -------------------------------------------------------------------------- | +| **Go** | **$10/month** | Lower-cost access to the models below | +| **Go Plus** | **$40/month** | Higher usage limits across the models below | +| **Go Teams** | **$20/member/month**, 2-member minimum | Every member gets their own limits, $5/month higher than Go on every model | Go works like any other provider in OpenCode. You subscribe to OpenCode Go and get your API key. It's **completely optional** and you don't need it to use OpenCode. @@ -31,50 +31,14 @@ The service is designed primarily for international users and provides stable gl ``` - Go and Go Plus are for workspaces with a single member, such as the **Personal** workspace created when you sign up. - Either can upgrade to Go Teams at any time, with the unused part of the month's allowance credited. Go Teams covers - every member of a workspace with several members, at $20 per member per month. A member who joins mid-period is - charged $20 and gets a full monthly allowance. Service accounts are not covered by Go Teams. + Go and Go Plus cover the member who subscribes and the workspace's API keys. Other members you invite use free models + or the workspace balance. Either can upgrade to Go Teams at any time, with the unused part of the month's allowance + credited. Go Teams covers every member of the workspace at $20 per member per month, with a 2-member minimum + ($40/month). The second seat covers the next member who joins at no extra charge; after that, a member who joins + mid-period is charged $20 and gets a full monthly allowance. Service accounts are not covered by Go Teams. -The current list of models includes: - -- **Grok 4.7** -- **GLM-5.3-Flash** -- **GLM-5.3** -- **GLM-5.2** -- **GPT 6 Luna** -- **GPT 5.6 Luna** -- **Claude Haiku 5.5** -- **Gemini 4 Argon** -- **Kimi K3.1 Pro** -- **Kimi K3** -- **Kimi K2.7 Code** -- **LongCat-2.0** -- **Step 5 Preview** -- **Beam Free** (limited time, limited regions) -- **Iceman Contributor Free** (limited time) -- **LongCat 2.5 Free** (limited time) -- **Hy4 flash Free** (limited time) -- **MiMo-V2.6-Flash** -- **MiMo-V2.6-Pro** -- **MiMo-V2.5** -- **MiMo-V2.5-Pro** -- **MiniMax M3.1 Flash** -- **MiniMax M3** -- **Muse Spark 1.3 Contributor** ([limited regions](https://ai.developer.meta.com/legal/geographic-use-policy)) -- **Muse Spark 1.2 Contributor** ([limited regions](https://ai.developer.meta.com/legal/geographic-use-policy)) -- **Qwen4 Max** -- **Qwen3.8 Max** -- **Qwen3.8 Flash** -- **Qwen3.7 Plus** -- **DeepSeek V4.1 Flash** -- **DeepSeek V4 Pro** -- **Hy4** -- **Hy4 preview** -- **Hy3** - -The list of models may change as we test and add new ones. +See the [current list of models](https://opencode.ai/console/go#models). It may change as we test and add new ones. ### Enable restricted models @@ -157,329 +121,20 @@ The paid models you use on Go share one allowance. On Go Teams, each member has Switching models draws from the same allowance. If you reach a limit, you can use a free model or turn on [Extra Usage](#usage-beyond-limits) to use your Console credits until you have allowance available again. -The **Monthly limit** column shows how much usage your plan covers if you use only that model over the month. +Each model's [monthly limit](https://opencode.ai/console/go#limits) shows how much usage your plan covers if you use only that model over the month. For example, $1.50 of usage on a model with a $15 limit uses 10% of your monthly allowance. So does $6 on a model with a $60 limit. Go responses report how much each request counted in [`opencode.allowance`](/console/api/inference#cost). -Token prices are per 1M tokens and are the same for Go, Go Plus, and Go Teams. - - -
- - | Model | Input | Output | Cached Read | Cached Write | Monthly limit | - | -------------------------------- | --------------- | ----------------- | --------------- | ------------ | ---------------------------------------------- | - | GLM-5.3-Flash | $0.15 | $0.50 | $0.03 | - | **$60** | - | GLM-5.3 | $1.40 | $4.40 | $0.26 | - | **$15** | - | GLM-5.2 | $1.40 | $4.40 | $0.26 | - | **$60** | - | Kimi K3.1 Pro | $2.00 | $10.00 | $0.20 | $2.00 | **$15** | - | Kimi K3 | $3.00 | $15.00 | $0.30 | $3.00 | **$15** | - | Kimi K2.7 Code | $0.95 | $4.00 | $0.19 | - | **$60** | - | LongCat-2.0 | $0.30 | $1.20 | $0.006 | - | **$60** | - | Step 5 Preview | $1.00 | $2.70 | $0.10 | - | **$15** | - | Beam Free | Free | Free | Free | - | **Unlimited**
limited time | - | Iceman Contributor Free | Free | Free | Free | - | **Unlimited**
limited time | - | LongCat 2.5 Free | Free | Free | Free | - | **Unlimited**
limited time | - | Hy4 flash Free | Free | Free | Free | - | **Unlimited**
limited time | - | MiMo-V2.6-Flash | $0.14 | $0.28 | $0.0028 | - | **$60** | - | MiMo-V2.6-Pro | $0.435 | $0.87 | $0.003625 | - | **$15** | - | MiMo-V2.5 | $0.14 | $0.28 | $0.0028 | - | **$60** | - | MiMo-V2.5-Pro | $0.435 | $0.87 | $0.003625 | - | **$15** | - | MiniMax M3.1 Flash | $0.15 | $0.60 | $0.015 | - | **$20** | - | MiniMax M3 (≤ 512K tokens) | $0.30 | $1.20 | $0.06 | - | **$60** | - | MiniMax M3 (> 512K tokens) | $0.60 | $2.40 | $0.12 | - | **$60** | - | Muse Spark 1.3 Contributor | $0.10 | $0.20 | $0.002 | - | **$60** | - | Muse Spark 1.2 Contributor | $0.10 | $0.20 | $0.002 | - | **$60** | - | Qwen4 Max | $1.50 | $4.50 | $0.075 | $1.875 | **$15** | - | Qwen3.8 Max | $2.00 | $6.00 | $0.25 | $2.50 | **$15** | - | Qwen3.8 Flash | $0.15 | $0.47 | $0.016 | $0.20 | **$30** | - | Qwen3.7 Plus (≤ 256K tokens) | $0.40 | $1.60 | $0.04 | $0.50 | **$60** | - | Qwen3.7 Plus (> 256K tokens) | $1.20 | $4.80 | $0.12 | $1.50 | **$60** | - | DeepSeek V4.1 Flash (Off-Peak) | $0.15 | $0.60 | $0.003 | - | **$100** | - | DeepSeek V4.1 Flash (Peak) | $0.30 | $1.20 | $0.006 | - | **$100** | - | DeepSeek V4 Pro (Off-Peak) | $0.66 | $1.98 | $0.022 | - | **$15** | - | DeepSeek V4 Pro (Peak) | $1.32 | $3.96 | $0.044 | - | **$15** | - | Hy4 | $0.834 | $2.501 | $0.042 | - | **$60** | - | Hy4 preview | $0.834 | $2.501 | $0.042 | - | **$30** | - | Hy3 | $0.14 | $0.58 | $0.035 | - | **$60** | - | Grok 4.7 (≤ 200K tokens) | $2.00 | $6.00 | $0.50 | - | **$15** | - | Grok 4.7 (> 200K tokens) | $4.00 | $12.00 | $1.00 | - | **$15** | - | GPT 6 Luna (≤ 272K tokens) | $0.10 | $0.50 | $0.01 | $0.125 | **$15** | - | GPT 6 Luna (> 272K tokens) | $0.20 | $0.75 | $0.02 | $0.25 | **$15** | - | GPT 5.6 Luna (≤ 272K tokens) | $0.20 | $1.20 | $0.02 | $0.25 | **$15** | - | GPT 5.6 Luna (> 272K tokens) | $0.40 | $1.80 | $0.04 | $0.50 | **$15** | - | Claude Haiku 5.5 (≤ 100K tokens) | $0.10 | $0.50 | $0.01 | $0.125 | **$15** | - | Claude Haiku 5.5 (> 100K tokens) | $0.50 | $2.50 | $0.05 | $0.625 | **$15** | - | Gemini 4 Argon (50% off) | ~~$4.00~~ $2.00 | ~~$20.00~~ $10.00 | ~~$0.20~~ $0.10 | - | **$30** | - -
-
- - | Model | Input | Output | Cached Read | Cached Write | Monthly limit | - | -------------------------------- | --------------- | ----------------- | --------------- | ------------ | ---------------------------------------------- | - | GLM-5.3-Flash | $0.15 | $0.50 | $0.03 | - | **$180** | - | GLM-5.3 | $1.40 | $4.40 | $0.26 | - | **$120** | - | GLM-5.2 | $1.40 | $4.40 | $0.26 | - | **$180** | - | Kimi K3.1 Pro | $2.00 | $10.00 | $0.20 | $2.00 | **$60** | - | Kimi K3 | $3.00 | $15.00 | $0.30 | $3.00 | **$60** | - | Kimi K2.7 Code | $0.95 | $4.00 | $0.19 | - | **$180** | - | LongCat-2.0 | $0.30 | $1.20 | $0.006 | - | **$240** | - | Step 5 Preview | $1.00 | $2.70 | $0.10 | - | **$60** | - | Beam Free | Free | Free | Free | - | **Unlimited**
limited time | - | Iceman Contributor Free | Free | Free | Free | - | **Unlimited**
limited time | - | LongCat 2.5 Free | Free | Free | Free | - | **Unlimited**
limited time | - | Hy4 flash Free | Free | Free | Free | - | **Unlimited**
limited time | - | MiMo-V2.6-Flash | $0.14 | $0.28 | $0.0028 | - | **$120** | - | MiMo-V2.6-Pro | $0.435 | $0.87 | $0.003625 | - | **$60** | - | MiMo-V2.5 | $0.14 | $0.28 | $0.0028 | - | **$120** | - | MiMo-V2.5-Pro | $0.435 | $0.87 | $0.003625 | - | **$60** | - | MiniMax M3.1 Flash | $0.15 | $0.60 | $0.015 | - | **$80** | - | MiniMax M3 (≤ 512K tokens) | $0.30 | $1.20 | $0.06 | - | **$180** | - | MiniMax M3 (> 512K tokens) | $0.60 | $2.40 | $0.12 | - | **$180** | - | Muse Spark 1.3 Contributor | $0.10 | $0.20 | $0.002 | - | **$120** | - | Muse Spark 1.2 Contributor | $0.10 | $0.20 | $0.002 | - | **$120** | - | Qwen4 Max | $1.50 | $4.50 | $0.075 | $1.875 | **$60** | - | Qwen3.8 Max | $2.00 | $6.00 | $0.25 | $2.50 | **$60** | - | Qwen3.8 Flash | $0.15 | $0.47 | $0.016 | $0.20 | **$90** | - | Qwen3.7 Plus (≤ 256K tokens) | $0.40 | $1.60 | $0.04 | $0.50 | **$180** | - | Qwen3.7 Plus (> 256K tokens) | $1.20 | $4.80 | $0.12 | $1.50 | **$180** | - | DeepSeek V4.1 Flash (Off-Peak) | $0.15 | $0.60 | $0.003 | - | **$200** | - | DeepSeek V4.1 Flash (Peak) | $0.30 | $1.20 | $0.006 | - | **$200** | - | DeepSeek V4 Pro (Off-Peak) | $0.66 | $1.98 | $0.022 | - | **$60** | - | DeepSeek V4 Pro (Peak) | $1.32 | $3.96 | $0.044 | - | **$60** | - | Hy4 | $0.834 | $2.501 | $0.042 | - | **$240** | - | Hy4 preview | $0.834 | $2.501 | $0.042 | - | **$120** | - | Hy3 | $0.14 | $0.58 | $0.035 | - | **$240** | - | Grok 4.7 (≤ 200K tokens) | $2.00 | $6.00 | $0.50 | - | **$60** | - | Grok 4.7 (> 200K tokens) | $4.00 | $12.00 | $1.00 | - | **$60** | - | GPT 6 Luna (≤ 272K tokens) | $0.10 | $0.50 | $0.01 | $0.125 | **$60** | - | GPT 6 Luna (> 272K tokens) | $0.20 | $0.75 | $0.02 | $0.25 | **$60** | - | GPT 5.6 Luna (≤ 272K tokens) | $0.20 | $1.20 | $0.02 | $0.25 | **$60** | - | GPT 5.6 Luna (> 272K tokens) | $0.40 | $1.80 | $0.04 | $0.50 | **$60** | - | Claude Haiku 5.5 (≤ 100K tokens) | $0.10 | $0.50 | $0.01 | $0.125 | **$60** | - | Claude Haiku 5.5 (> 100K tokens) | $0.50 | $2.50 | $0.05 | $0.625 | **$60** | - | Gemini 4 Argon (50% off) | ~~$4.00~~ $2.00 | ~~$20.00~~ $10.00 | ~~$0.20~~ $0.10 | - | **$120** | - -
-
- - | Model | Input | Output | Cached Read | Cached Write | Monthly limit | - | -------------------------------- | --------------- | ----------------- | --------------- | ------------ | ---------------------------------------------- | - | GLM-5.3-Flash | $0.15 | $0.50 | $0.03 | - | **$65** | - | GLM-5.3 | $1.40 | $4.40 | $0.26 | - | **$20** | - | GLM-5.2 | $1.40 | $4.40 | $0.26 | - | **$65** | - | Kimi K3.1 Pro | $2.00 | $10.00 | $0.20 | $2.00 | **$20** | - | Kimi K3 | $3.00 | $15.00 | $0.30 | $3.00 | **$20** | - | Kimi K2.7 Code | $0.95 | $4.00 | $0.19 | - | **$65** | - | LongCat-2.0 | $0.30 | $1.20 | $0.006 | - | **$65** | - | Step 5 Preview | $1.00 | $2.70 | $0.10 | - | **$20** | - | Beam Free | Free | Free | Free | - | **Unlimited**
limited time | - | Iceman Contributor Free | Free | Free | Free | - | **Unlimited**
limited time | - | LongCat 2.5 Free | Free | Free | Free | - | **Unlimited**
limited time | - | Hy4 flash Free | Free | Free | Free | - | **Unlimited**
limited time | - | MiMo-V2.6-Flash | $0.14 | $0.28 | $0.0028 | - | **$65** | - | MiMo-V2.6-Pro | $0.435 | $0.87 | $0.003625 | - | **$20** | - | MiMo-V2.5 | $0.14 | $0.28 | $0.0028 | - | **$65** | - | MiMo-V2.5-Pro | $0.435 | $0.87 | $0.003625 | - | **$20** | - | MiniMax M3.1 Flash | $0.15 | $0.60 | $0.015 | - | **$25** | - | MiniMax M3 (≤ 512K tokens) | $0.30 | $1.20 | $0.06 | - | **$65** | - | MiniMax M3 (> 512K tokens) | $0.60 | $2.40 | $0.12 | - | **$65** | - | Muse Spark 1.3 Contributor | $0.10 | $0.20 | $0.002 | - | **$65** | - | Muse Spark 1.2 Contributor | $0.10 | $0.20 | $0.002 | - | **$65** | - | Qwen4 Max | $1.50 | $4.50 | $0.075 | $1.875 | **$20** | - | Qwen3.8 Max | $2.00 | $6.00 | $0.25 | $2.50 | **$20** | - | Qwen3.8 Flash | $0.15 | $0.47 | $0.016 | $0.20 | **$35** | - | Qwen3.7 Plus (≤ 256K tokens) | $0.40 | $1.60 | $0.04 | $0.50 | **$65** | - | Qwen3.7 Plus (> 256K tokens) | $1.20 | $4.80 | $0.12 | $1.50 | **$65** | - | DeepSeek V4.1 Flash (Off-Peak) | $0.15 | $0.60 | $0.003 | - | **$105** | - | DeepSeek V4.1 Flash (Peak) | $0.30 | $1.20 | $0.006 | - | **$105** | - | DeepSeek V4 Pro (Off-Peak) | $0.66 | $1.98 | $0.022 | - | **$20** | - | DeepSeek V4 Pro (Peak) | $1.32 | $3.96 | $0.044 | - | **$20** | - | Hy4 | $0.834 | $2.501 | $0.042 | - | **$65** | - | Hy4 preview | $0.834 | $2.501 | $0.042 | - | **$35** | - | Hy3 | $0.14 | $0.58 | $0.035 | - | **$65** | - | Grok 4.7 (≤ 200K tokens) | $2.00 | $6.00 | $0.50 | - | **$20** | - | Grok 4.7 (> 200K tokens) | $4.00 | $12.00 | $1.00 | - | **$20** | - | GPT 6 Luna (≤ 272K tokens) | $0.10 | $0.50 | $0.01 | $0.125 | **$20** | - | GPT 6 Luna (> 272K tokens) | $0.20 | $0.75 | $0.02 | $0.25 | **$20** | - | GPT 5.6 Luna (≤ 272K tokens) | $0.20 | $1.20 | $0.02 | $0.25 | **$20** | - | GPT 5.6 Luna (> 272K tokens) | $0.40 | $1.80 | $0.04 | $0.50 | **$20** | - | Claude Haiku 5.5 (≤ 100K tokens) | $0.10 | $0.50 | $0.01 | $0.125 | **$20** | - | Claude Haiku 5.5 (> 100K tokens) | $0.50 | $2.50 | $0.05 | $0.625 | **$20** | - | Gemini 4 Argon (50% off) | ~~$4.00~~ $2.00 | ~~$20.00~~ $10.00 | ~~$0.20~~ $0.10 | - | **$35** | - -
-
+[Token prices](https://opencode.ai/console/go#pricing) are per 1M tokens and are the same for Go, Go Plus, and Go Teams. **Beam Free:** Free for a limited time. Not available in Angola, Belarus, Cambodia, China (including Hong Kong and Macau), Cuba, the Democratic Republic of the Congo, Equatorial Guinea, Iran, Iraq, Laos, Libya, Nigeria, North Korea, Russia, Syria, Turkmenistan, Uzbekistan, Venezuela, or the Crimea, Donetsk, and Luhansk regions of Ukraine. -**Iceman Contributor Free:** Free for a limited time. - -**LongCat 2.5 Free:** Free for a limited time. - -**Hy4 flash Free:** Free for a limited time. - **Gemini 4 Argon:** The 50% discount applies through November 30, 2026. -**DeepSeek V4.1 Flash / V4 Pro:** Peak hours are 01:00-04:00 and 06:00-10:00 UTC, Monday through Friday; all other hours, including weekends, are Off-Peak. [Learn more](https://api-docs.deepseek.com/quick_start/pricing/). - ### Estimated requests -The tables below estimate request counts based on typical Go usage patterns. Go -Plus and Go Teams estimates scale with each model's higher usage limit. - - -
- - | Model | Requests per 5 hours | Requests per week | Requests per month | - | -------------------------- | -------------------- | ----------------- | ------------------ | - | GLM-5.3-Flash | 6,320 | 15,790 | 31,580 | - | GLM-5.3 | 220 | 540 | 1,080 | - | GLM-5.2 | 880 | 2,150 | 4,300 | - | Kimi K3.1 Pro | 147 | 368 | 735 | - | Kimi K3 | 110 | 250 | 490 | - | Kimi K2.7 Code | 1,350 | 3,380 | 6,750 | - | LongCat-2.0 | 11,400 | 28,600 | 57,200 | - | Step 5 Preview | 430 | 1,070 | 2,130 | - | Beam Free | Unlimited | Unlimited | Unlimited | - | Iceman Contributor Free | Unlimited | Unlimited | Unlimited | - | LongCat 2.5 Free | Unlimited | Unlimited | Unlimited | - | Hy4 flash Free | Unlimited | Unlimited | Unlimited | - | MiMo-V2.6-Flash | 30,100 | 75,200 | 150,400 | - | MiMo-V2.6-Pro | 3,250 | 8,150 | 16,300 | - | MiMo-V2.5 | 30,100 | 75,200 | 150,400 | - | MiMo-V2.5-Pro | 3,250 | 8,150 | 16,300 | - | MiniMax M3.1 Flash | 3,880 | 9,690 | 19,380 | - | MiniMax M3 | 3,200 | 8,000 | 16,000 | - | Muse Spark 1.3 Contributor | 45,300 | 113,300 | 226,600 | - | Muse Spark 1.2 Contributor | 45,300 | 113,300 | 226,600 | - | Qwen4 Max | 460 | 1,160 | 2,310 | - | Qwen3.8 Max | 160 | 400 | 810 | - | Qwen3.8 Flash | 5,400 | 13,500 | 27,000 | - | Qwen3.7 Plus | 4,300 | 10,800 | 21,600 | - | DeepSeek V4.1 Flash | 43,330 | 108,330 | 216,670 | - | DeepSeek V4 Pro | 1,050 | 2,600 | 5,200 | - | Hy4 | 2,710 | 6,770 | 13,500 | - | Hy4 preview | 1,350 | 3,380 | 6,770 | - | Hy3 | 4,300 | 10,750 | 21,500 | - | Grok 4.7 | 169 | 423 | 845 | - | GPT 6 Luna | 4,230 | 10,560 | 21,130 | - | GPT 5.6 Luna | 2,050 | 5,100 | 10,250 | - | Claude Haiku 5.5 | 3,850 | 9,620 | 19,230 | - | Gemini 4 Argon | 440 | 1,080 | 2,120 | - -
-
- - | Model | Requests per 5 hours | Requests per week | Requests per month | - | -------------------------- | -------------------- | ----------------- | ------------------ | - | GLM-5.3-Flash | 18,960 | 47,370 | 94,740 | - | GLM-5.3 | 1,760 | 4,320 | 8,640 | - | GLM-5.2 | 2,640 | 6,450 | 12,900 | - | Kimi K3.1 Pro | 588 | 1,471 | 2,941 | - | Kimi K3 | 440 | 1,000 | 1,960 | - | Kimi K2.7 Code | 4,050 | 10,140 | 20,250 | - | LongCat-2.0 | 45,600 | 114,400 | 228,800 | - | Step 5 Preview | 1,720 | 4,280 | 8,520 | - | Beam Free | Unlimited | Unlimited | Unlimited | - | Iceman Contributor Free | Unlimited | Unlimited | Unlimited | - | LongCat 2.5 Free | Unlimited | Unlimited | Unlimited | - | Hy4 flash Free | Unlimited | Unlimited | Unlimited | - | MiMo-V2.6-Flash | 60,200 | 150,400 | 300,800 | - | MiMo-V2.6-Pro | 13,000 | 32,600 | 65,200 | - | MiMo-V2.5 | 60,200 | 150,400 | 300,800 | - | MiMo-V2.5-Pro | 13,000 | 32,600 | 65,200 | - | MiniMax M3.1 Flash | 15,500 | 38,760 | 77,520 | - | MiniMax M3 | 9,600 | 24,000 | 48,000 | - | Muse Spark 1.3 Contributor | 90,600 | 226,600 | 453,200 | - | Muse Spark 1.2 Contributor | 90,600 | 226,600 | 453,200 | - | Qwen4 Max | 1,840 | 4,640 | 9,240 | - | Qwen3.8 Max | 640 | 1,600 | 3,240 | - | Qwen3.8 Flash | 16,200 | 40,500 | 81,000 | - | Qwen3.7 Plus | 12,900 | 32,400 | 64,800 | - | DeepSeek V4.1 Flash | 86,670 | 216,670 | 433,330 | - | DeepSeek V4 Pro | 4,200 | 10,400 | 20,800 | - | Hy4 | 10,840 | 27,080 | 54,000 | - | Hy4 preview | 5,400 | 13,520 | 27,080 | - | Hy3 | 17,200 | 43,000 | 86,000 | - | Grok 4.7 | 676 | 1,692 | 3,380 | - | GPT 6 Luna | 16,920 | 42,240 | 84,520 | - | GPT 5.6 Luna | 8,200 | 20,400 | 41,000 | - | Claude Haiku 5.5 | 15,380 | 38,460 | 76,920 | - | Gemini 4 Argon | 1,760 | 4,320 | 8,480 | - -
-
- - | Model | Requests per 5 hours | Requests per week | Requests per month | - | -------------------------- | -------------------- | ----------------- | ------------------ | - | GLM-5.3-Flash | 6,847 | 17,110 | 34,210 | - | GLM-5.3 | 293 | 720 | 1,440 | - | GLM-5.2 | 953 | 2,330 | 4,660 | - | Kimi K3.1 Pro | 196 | 491 | 980 | - | Kimi K3 | 147 | 333 | 653 | - | Kimi K2.7 Code | 1,462 | 3,660 | 7,310 | - | LongCat-2.0 | 12,350 | 30,980 | 61,970 | - | Step 5 Preview | 573 | 1,430 | 2,840 | - | Beam Free | Unlimited | Unlimited | Unlimited | - | Iceman Contributor Free | Unlimited | Unlimited | Unlimited | - | LongCat 2.5 Free | Unlimited | Unlimited | Unlimited | - | Hy4 flash Free | Unlimited | Unlimited | Unlimited | - | MiMo-V2.6-Flash | 32,608 | 81,470 | 162,930 | - | MiMo-V2.6-Pro | 4,333 | 10,870 | 21,730 | - | MiMo-V2.5 | 32,608 | 81,470 | 162,930 | - | MiMo-V2.5-Pro | 4,333 | 10,870 | 21,730 | - | MiniMax M3.1 Flash | 4,850 | 12,110 | 24,230 | - | MiniMax M3 | 3,467 | 8,670 | 17,330 | - | Muse Spark 1.3 Contributor | 49,075 | 122,740 | 245,480 | - | Muse Spark 1.2 Contributor | 49,075 | 122,740 | 245,480 | - | Qwen4 Max | 613 | 1,550 | 3,080 | - | Qwen3.8 Max | 213 | 530 | 1,080 | - | Qwen3.8 Flash | 6,300 | 15,750 | 31,500 | - | Qwen3.7 Plus | 4,658 | 11,700 | 23,400 | - | DeepSeek V4.1 Flash | 45,500 | 113,750 | 227,500 | - | DeepSeek V4 Pro | 1,400 | 3,470 | 6,930 | - | Hy4 | 2,936 | 7,330 | 14,630 | - | Hy4 preview | 1,575 | 3,940 | 7,900 | - | Hy3 | 4,658 | 11,650 | 23,290 | - | Grok 4.7 | 225 | 564 | 1,130 | - | GPT 6 Luna | 5,640 | 14,080 | 28,170 | - | GPT 5.6 Luna | 2,733 | 6,800 | 13,670 | - | Claude Haiku 5.5 | 5,133 | 12,830 | 25,640 | - | Gemini 4 Argon | 513 | 1,260 | 2,470 | - -
-
- -The estimates use the following token counts per request; actual usage varies. - -- Grok 4.7 — 390 input, 32,500 cached, 120 output tokens per request -- GLM-5.3-Flash — 1,000 input, 55,000 cached, 200 output tokens per request -- GLM-5.3/5.2 — 700 input, 52,000 cached, 150 output tokens per request -- GPT 6 Luna — 1,000 input, 50,000 cached, 220 output tokens per request -- GPT 5.6 Luna — 1,000 input, 50,000 cached, 220 output tokens per request -- Claude Haiku 5.5 — 1,100 input, 55,000 cached, 240 output tokens per request -- Kimi K3.1 Pro — 1,050 input, 76,500 cached, 300 output tokens per request -- Kimi K3 — 1,050 input, 76,500 cached, 300 output tokens per request -- Kimi K2.7 Code — 870 input, 55,000 cached, 200 output tokens per request -- LongCat-2.0 — 920 input, 88,900 cached, 200 output tokens per request -- Step 5 Preview — 1,000 input, 55,000 cached, 200 output tokens per request -- DeepSeek V4.1 Flash — 410 input, 71,300 cached, 310 output tokens per request -- DeepSeek V4 Pro — 750 input, 82,000 cached, 290 output tokens per request -- MiniMax M3.1 Flash — 500 input, 49,400 cached, 360 output tokens per request -- MiniMax M3 — 510 input, 56,000 cached, 190 output tokens per request -- Muse Spark 1.3 Contributor — 620 input, 71,400 cached, 300 output tokens per request -- Muse Spark 1.2 Contributor — 620 input, 71,400 cached, 300 output tokens per request -- MiMo-V2.6-Flash — 830 input, 71,500 cached, 295 output tokens per request -- MiMo-V2.6-Pro — 790 input, 86,000 cached, 305 output tokens per request -- MiMo-V2.5 — 830 input, 71,500 cached, 295 output tokens per request -- MiMo-V2.5-Pro — 790 input, 86,000 cached, 305 output tokens per request -- Qwen4 Max — 420 input, 66,000 cached, 200 output tokens per request -- Qwen3.8 Max — 420 input, 66,000 cached, 200 output tokens per request -- Qwen3.8 Flash — 600 input, 58,000 cached, 200 output tokens per request -- Qwen3.7 Plus — 500 input, 57,000 cached, 190 output tokens per request -- Hy4 — 830 input, 71,500 cached, 295 output tokens per request -- Hy4 preview — 830 input, 71,500 cached, 295 output tokens per request -- Hy3 — 830 input, 71,500 cached, 295 output tokens per request +Console's Go page [estimates requests per 5 hours](https://opencode.ai/console/go#limits) for each model, based on +typical Go usage patterns. Actual usage varies. You can track your current usage in the [console](https://opencode.ai/console). @@ -509,51 +164,11 @@ For these models, you still get a little more than if you paid the model provide ## Endpoints -You can also access Go models through the following API endpoints. Each model is listed with its native API, but every +You can also access Go models through the API at `https://opencode.ai/inference/go`. See each model's +[ID, path and AI SDK package](https://opencode.ai/console/go#api). Each model is listed with its native API, but every text model also works through the other APIs, which Console translates. See [Base URLs](/console/harnesses#base-urls) for the full set. -
- -| Model | Model ID | Endpoint | AI SDK Package | -| -------------------------- | -------------------------- | ---------------------------------------------------------------------- | --------------------------- | -| Grok 4.7 | grok-4.7 | `https://opencode.ai/inference/go/openai/v1/responses` | `@ai-sdk/openai` | -| GPT 6 Luna | gpt-6-luna | `https://opencode.ai/inference/go/openai/v1/responses` | `@ai-sdk/openai` | -| GPT 5.6 Luna | gpt-5.6-luna | `https://opencode.ai/inference/go/openai/v1/responses` | `@ai-sdk/openai` | -| Claude Haiku 5.5 | claude-haiku-5-5 | `https://opencode.ai/inference/go/anthropic/v1/messages` | `@ai-sdk/anthropic` | -| Gemini 4 Argon | gemini-4-argon | `https://opencode.ai/inference/go/google/v1beta/models/gemini-4-argon` | `@ai-sdk/google` | -| GLM-5.3-Flash | glm-5.3-flash | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| GLM-5.3 | glm-5.3 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| GLM-5.2 | glm-5.2 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Kimi K3.1 Pro | kimi-k3.1-pro | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Kimi K3 | kimi-k3 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Kimi K2.7 Code | kimi-k2.7-code | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| LongCat-2.0 | longcat-2.0 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| DeepSeek V4.1 Flash | deepseek-v4.1-flash | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| DeepSeek V4 Pro | deepseek-v4-pro | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| MiMo-V2.6-Flash | mimo-v2.6-flash | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| MiMo-V2.6-Pro | mimo-v2.6-pro | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| MiMo-V2.5 | mimo-v2.5 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| MiMo-V2.5-Pro | mimo-v2.5-pro | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| MiniMax M3.1 Flash | minimax-m3.1-flash | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| MiniMax M3 | minimax-m3 | `https://opencode.ai/inference/go/anthropic/v1/messages` | `@ai-sdk/anthropic` | -| Muse Spark 1.3 Contributor | muse-spark-1.3-contributor | `https://opencode.ai/inference/go/openai/v1/responses` | `@ai-sdk/openai` | -| Muse Spark 1.2 Contributor | muse-spark-1.2-contributor | `https://opencode.ai/inference/go/openai/v1/responses` | `@ai-sdk/openai` | -| Qwen4 Max | qwen4-max | `https://opencode.ai/inference/go/anthropic/v1/messages` | `@ai-sdk/anthropic` | -| Qwen3.8 Max | qwen3.8-max | `https://opencode.ai/inference/go/anthropic/v1/messages` | `@ai-sdk/anthropic` | -| Qwen3.8 Flash | qwen3.8-flash | `https://opencode.ai/inference/go/anthropic/v1/messages` | `@ai-sdk/anthropic` | -| Qwen3.7 Plus | qwen3.7-plus | `https://opencode.ai/inference/go/anthropic/v1/messages` | `@ai-sdk/anthropic` | -| Hy4 | hy4 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Hy4 preview | hy4-preview | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Hy3 | hy3 | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Step 5 Preview | step-5-preview | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Beam Free | beam-free | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Iceman Contributor Free | iceman-contributor-free | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| LongCat 2.5 Free | longcat-2.5-free | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | -| Hy4 flash Free | hy4-flash-free | `https://opencode.ai/inference/go/openai/v1/chat/completions` | `@ai-sdk/openai-compatible` | - -
- These AI SDK packages are for applications calling Go directly. To use Go in OpenCode, connect with `/connect` and set the [model](/models) using the format `opencode-go/`: @@ -574,42 +189,44 @@ curl https://opencode.ai/inference/go/v1/models ## Privacy -| Model | Model training | Data retention | -| -------------------------- | -------------- | -------------- | -| Grok 4.7 | Not used | 30 days | -| GPT 6 Luna | Not used | 30 days | -| GPT 5.6 Luna | Not used | 30 days | -| Claude Haiku 5.5 | Not used | 30 days | -| Gemini 4 Argon | Not used | 0 days | -| GLM-5.3-Flash | Not used | 0 days | -| GLM-5.3 | Not used | 0 days | -| GLM-5.2 | Not used | 0 days | -| Kimi K3.1 Pro | Not used | 0 days | -| Kimi K3 | Not used | 0 days | -| Kimi K2.7 Code | Not used | 0 days | -| LongCat-2.0 | Not used | 0 days | -| MiMo-V2.6-Pro | Not used | 0 days | -| MiMo-V2.6-Flash | Not used | 0 days | -| MiMo-V2.5-Pro | Not used | 0 days | -| MiMo-V2.5 | Not used | 0 days | -| Qwen4 Max | Not used | 0 days | -| Qwen3.8 Max | Not used | 0 days | -| Qwen3.8 Flash | Not used | 0 days | -| Qwen3.7 Plus | Not used | 0 days | -| MiniMax M3.1 Flash | Not used | 0 days | -| MiniMax M3 | Not used | 0 days | -| Muse Spark 1.3 Contributor | Yes | Not ZDR | -| Muse Spark 1.2 Contributor | Yes | Not ZDR | -| DeepSeek V4.1 Flash | Not used | 0 days\* | -| DeepSeek V4 Pro | Not used | 0 days\* | -| Hy4 | Not used | 0 days | -| Hy4 preview | Not used | 0 days | -| Hy3 | Not used | 0 days | -| Step 5 Preview | Not used | 0 days | -| Beam Free | Not used | 30 days | -| Iceman Contributor Free | Yes | Not ZDR | -| LongCat 2.5 Free | Not used | 0 days | -| Hy4 flash Free | Not used | 0 days | +See whether each model [trains on your data](https://opencode.ai/console/go#privacy). + +| Model | Data retention | +| -------------------------- | -------------- | +| Grok 4.7 | 30 days | +| GPT 6 Luna | 30 days | +| GPT 5.6 Luna | 30 days | +| Claude Haiku 5.5 | 30 days | +| Gemini 4 Argon | 0 days | +| GLM-5.3-Flash | 0 days | +| GLM-5.3 | 0 days | +| GLM-5.2 | 0 days | +| Kimi K3.1 Pro | 0 days | +| Kimi K3 | 0 days | +| Kimi K2.7 Code | 0 days | +| LongCat-2.0 | 0 days | +| MiMo-V2.6-Pro | 0 days | +| MiMo-V2.6-Flash | 0 days | +| MiMo-V2.5-Pro | 0 days | +| MiMo-V2.5 | 0 days | +| Qwen4 Max | 0 days | +| Qwen3.8 Max | 0 days | +| Qwen3.8 Flash | 0 days | +| Qwen3.7 Plus | 0 days | +| MiniMax M3.1 Flash | 0 days | +| MiniMax M3 | 0 days | +| Muse Spark 1.3 Contributor | Not ZDR | +| Muse Spark 1.2 Contributor | Not ZDR | +| DeepSeek V4.1 Flash | 0 days\* | +| DeepSeek V4 Pro | 0 days\* | +| Hy4 | 0 days | +| Hy4 preview | 0 days | +| Hy3 | 0 days | +| Step 5 Preview | 0 days | +| Beam Free | 30 days | +| Iceman Contributor Free | Not ZDR | +| LongCat 2.5 Free | 0 days | +| Hy4 flash Free | 0 days | - **Grok 4.7:** ZDR disables important API features that depend on stored data, including the stateful Responses API, Files and Collections, and the Batch API. [Learn more](https://docs.x.ai/developers/faq/security#what-is-zero-data-retention-zdr). - **GPT 6 Luna / GPT 5.6 Luna:** Abuse monitoring logs are generated for all API feature usage and retained for up to 30 days. [Learn more](https://developers.openai.com/api/docs/guides/your-data#data-retention-controls-for-abuse-monitoring). diff --git a/services/site/src/docs/content/console/members.mdx b/services/site/src/docs/content/console/members.mdx index 0cb7c48b42c..734806a35a8 100644 --- a/services/site/src/docs/content/console/members.mdx +++ b/services/site/src/docs/content/console/members.mdx @@ -16,9 +16,9 @@ Each person receives an email titled **Join Acme Inc. on OpenCode** with a **Joi Invitations expire after 7 days. Everyone joins as **Member**; [change their role](#change-a-role) after they join. - [OpenCode Go](/console/go) and Go Plus are for a single member. To invite teammates, upgrade to Go Teams ($20 per - member per month). On Go Teams, every member you invite or provision gets their own Go limits, charged $20 a month - from when they join. + On [OpenCode Go](/console/go) and Go Plus, people you invite use free models or the workspace balance. To give + everyone their own Go limits, upgrade to Go Teams ($20 per member per month, 2-member minimum). Each member after the + second is charged $20 a month from when they join. Members can also join automatically: