diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 737d0e03ef..97e1fb3ceb 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -44,6 +44,7 @@ Configuration is loaded from multiple sources, with later sources overriding ear | `$schema` | `string` | JSON schema URL for editor autocompletion | | `theme` | `string` | UI theme name | | `username` | `string` | Custom display username | +| `offline` | `boolean` | Restrict network access to the configured model endpoint | | `model` | `string` | Default model (`provider/model`) | | `small_model` | `string` | Smaller model for lightweight tasks | | `default_agent` | `string` | Default agent to use on startup | @@ -158,3 +159,60 @@ Control how context is managed when conversations grow long: !!! info Compaction automatically summarizes older messages to free up context window space, allowing longer conversations without losing important context. See [Context Management](context-management.md) for full details. + +## Offline / air-gapped mode + +Offline mode is for running Altimate Code against a local or self-hosted model with no other network access. Altimate Code then sends network requests only to the configured model endpoint and to services on this machine (loopback). Local work keeps running: tools, shell commands, local databases, language servers, local MCP servers and local Git. + +With offline mode off, nothing in this section applies and Altimate Code behaves exactly as before. + +### Turn it on + +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global, project, or organisation-managed JSON or JSONC configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those sources for the setting when it starts, so startup requests are covered too. If Altimate Code first sees `"offline": true` after the startup check, such as in macOS managed preferences (MDM), remote (well-known) configuration, account configuration, or the legacy TOML `config` file, it refuses to load the configuration and asks you to restart with `ALTIMATE_OFFLINE=1`. Any startup opt-in turns offline mode on for the whole process, regardless of a `false` value elsewhere. `ALTIMATE_OFFLINE` values of empty, `0`, `false`, `off` and `no` mean off. Once on, offline mode lasts for the rest of the process, including any server that loaded the project. + +Configure a provider with an explicit HTTP(S) `options.baseURL` and use one of its models (`provider/model`). For an OpenAI-compatible server, use the bundled `@ai-sdk/openai-compatible` provider, and define the model under the provider if it is not in the bundled or cached catalog. Model requests go only to a provider's explicit `baseURL`, never to a catalog URL, and are not redirected. They respect `HTTPS_PROXY` and `HTTP_PROXY`. A `small_model` is used only if its provider also has an explicit `baseURL`. + +### Before going offline + +While still online: + +- Run `altimate-code workspace refresh` to save the workspace skill snapshot. Offline runs use it as it is, without refreshing it. +- Install the warehouse drivers you need (the `warehouse_install_driver` tool), any language servers, and ripgrep. +- Run `dbt deps` for dbt projects, and install any DuckDB extensions your profiles use. + +### What keeps working + +- Local warehouses: DuckDB and SQLite files, and Postgres, Redshift, MySQL, MariaDB, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a host of `localhost`, `::1` or `127.x.x.x`. Postgres and Redshift also accept a Unix socket directory as the host. For MongoDB, set `direct_connection: true` or add `directConnection=true` to the connection URI. Other hosts, connection strings that cannot be parsed (including Oracle Easy Connect strings; set `host` instead), and account-addressed warehouses such as Snowflake, BigQuery and Databricks are refused. +- dbt commands whose selected profile and target are local. Values written as Jinja templates (for example `{{ env_var('DBT_HOST') }}`) cannot be checked and are refused; write them literally to use them offline. dbt-duckdb profiles can use extensions, local attachments and plugins; settings that point at remote storage, a remote server or a remote extension repository (`s3://`, `https://`, `gcs://`, `md:` and similar) are refused. Named extensions and plugins are not checked: install extensions while online, and do not configure plugins that call remote services. +- DuckDB loads extensions that are already installed and does not install new ones automatically. +- The shell tool, installed language servers, stdio MCP servers and MCP servers at `localhost`, `127.0.0.1`, `[::1]` or `0.0.0.0`, including `tool run --daemon`. +- Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and updates checked-out top-level submodules from local objects. Nested submodules keep their current commits, and uninitialized submodules remain uninitialized. Reset discards local changes in all checked-out submodules, including nested ones. Worktree create and reset leave Git LFS files as pointer files. +- `attach` and `run --attach` to a server on this machine. The attached server applies its own policy, so start it with offline mode too. + +### What is blocked + +Each of these fails with a one-line message or is skipped: + +- telemetry, account and remote configuration requests; +- model catalog downloads and update checks; +- workspace and workspace engine sync, and session sharing; +- the web fetch, web search, code search, `datamate_manager`, feedback and memory refresh tools; +- MCP servers at other URLs, and MCP sign-in; +- skills from remote skill URLs (`skills.urls`), including copies already cached; +- automatic installs of warehouse drivers, language servers, plugins and ripgrep; +- warehouse connections to other hosts, SSH tunnels, MongoDB SRV, replica-set discovery and MongoDB connection proxies, and cloud sign-in (SQL Server methods other than SQL or Windows login, MongoDB AWS/OIDC/Kerberos, dbt cloud methods); +- `dbt deps` and dbt's usage reporting and version check; +- `git clone`, `fetch`, `pull`, `push` and other Git commands that use a remote; +- commands that need a remote service, such as `github`, `pr`, `web`, `upgrade`, `review --post` and `attach` to another machine. + +### What offline mode does not police + +Programs you run or configure yourself keep their own network access and proxy settings: shell commands, language servers, local MCP servers and their child processes. Offline mode does not sandbox them. They inherit `ALTIMATE_OFFLINE=1`, so an `altimate-code` started from the shell is offline too, and `NO_PROXY` gains `localhost,127.0.0.1,[::1],0.0.0.0` so that local requests do not go through a proxy. + +Some network use happens inside programs Altimate Code starts and is not checked either: + +- Git in a partial (blobless or treeless) clone fetches missing objects on demand, even for local commands such as `diff`, and Git LFS can download missing objects during a checkout outside worktree reset. +- dbt reads libpq environment variables such as `PGHOSTADDR` and `PGSERVICE`, which can point a Postgres profile at another host. +- An offline TUI started with `--hostname` set to a LAN address or machine name cannot reach its own server; use the default or `0.0.0.0`. + +SQL that runs an explicit `INSTALL`, or loads an installed network extension (such as `httpfs`) and reads a remote path, is not blocked. The `altimate-dbt` command runs through the shell tool and is not policed either, although it turns off its own dependency installs and usage reporting. diff --git a/docs/mcp-workspaces.md b/docs/mcp-workspaces.md index f0bd32ab30..43253b2168 100644 --- a/docs/mcp-workspaces.md +++ b/docs/mcp-workspaces.md @@ -20,6 +20,8 @@ Workspace context adds bounded data to a client's prompt; skills load on demand. Verification covers unit contracts, a real stdio protocol fixture and existing SQLite MCP behavior. A non-empty cloud memory round trip and real workspace-engine SQL and knowledge calls are not covered by tests yet. +In [offline mode](docs/configure/config.md#offline-air-gapped-mode), Altimate Code sessions use the local workspace skill snapshot. Refresh it with `altimate-code workspace refresh` while online. The external workspace gateway requires an online run. + ## Automatic-client setup and stable gateway The opt-in workspace catalog is always `workspace_context`, `workspace_skill` and `workspace_execute`, including when initially unlinked. `workspace_context` reports `needs_auth`, `needs_workspace`, `disabled` or `unavailable` without returning raw credential errors. A ready context includes the workspace receipt. Context loads coalesce and cache for 30 seconds; identity is verified on every use. `refresh: true` bypasses that cache. diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index d85627f1b5..39df4a1229 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -20,6 +20,11 @@ export function env(key: string): string | undefined { return documented !== undefined && documented !== "" ? documented : process.env[key] } +export function offlineModeEnabled() { + const value = process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() + return killSwitchSet(value) && value !== "off" && value !== "no" +} + export function truthy(key: string) { const value = env(key)?.toLowerCase() return value === "true" || value === "1" diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 0041c3353f..aa12a99a51 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -7,6 +7,39 @@ import { AbsolutePath } from "./schema" import { FSUtil } from "./fs-util" import { AppProcess } from "./process" import { LayerNode } from "./effect/layer-node" +// altimate_change start — offline mode refuses Git commands that use the network +import { offlineModeEnabled } from "./flag/flag" + +const remoteCommands = new Set(["clone", "fetch", "pull", "push", "ls-remote", "send-pack", "fetch-pack", "submodule--helper"]) + +export function gitCommandUsesNetwork(args: string[]) { + let index = 0 + while (args[index]?.startsWith("-")) { + index += ["-c", "-C", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(args[index]) ? 2 : 1 + } + const [command, ...after] = args.slice(index) + // The operation is the first word after the subcommand's own options (`submodule --quiet update`). + const at = after.findIndex((arg) => !arg.startsWith("-")) + const operation = at === -1 ? "" : after[at] + const rest = at === -1 ? after : [...after.slice(0, at), ...after.slice(at + 1)] + // Git runs foreach through a shell. Allow only these literal local commands. + if (command === "submodule" && operation === "foreach") { + const nested = rest.findIndex((arg) => arg === "--" || !arg.startsWith("-")) + return nested === -1 || !["git reset --hard", "git clean -fdx", "git status"].includes(rest.slice(nested).join(" ")) + } + return ( + remoteCommands.has(command) || + (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) || + (command === "submodule" && ["update", "add"].includes(operation)) || + (command === "remote" && operation === "add" && rest.some((arg) => arg === "-f" || arg === "--fetch")) || + (command === "remote" && (operation === "prune" || (operation === "set-head" && rest.some((arg) => arg === "-a" || arg === "--auto")))) || + (command === "lfs" && ["fetch", "pull", "push", "clone"].includes(operation)) || + (command === "archive" && [operation, ...rest].some((arg) => arg?.startsWith("--remote"))) + ) +} + +export const GIT_OFFLINE_REFUSAL = "Git remote operations require an online run." +// altimate_change end export interface Repo { /** @@ -416,6 +449,10 @@ function run(cwd: string, proc: AppProcess.Interface) { function execute(cwd: string, proc: AppProcess.Interface) { return (args: string[]) => + // altimate_change start — offline mode refuses Git commands that use the network + offlineModeEnabled() && gitCommandUsesNetwork(args) + ? Effect.succeed({ exitCode: 1, text: "", stderr: GIT_OFFLINE_REFUSAL } satisfies Result) + : // altimate_change end proc .run( ChildProcess.make("git", args, { diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 3f9f670374..1c1fa09d63 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -2,7 +2,9 @@ import path from "path" import { Context, Duration, Effect, Layer, Option, Schedule, Schema } from "effect" import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" import { Global } from "./global" -import { Flag } from "./flag/flag" +// altimate_change start — offline mode +import { Flag, offlineModeEnabled } from "./flag/flag" +// altimate_change end import { Flock } from "./util/flock" import { Hash } from "./util/hash" import { FSUtil } from "./fs-util" @@ -201,7 +203,9 @@ export const layer = Layer.effect( if (fromDisk) return fromDisk const snapshot = yield* loadSnapshot if (snapshot) return snapshot - if (Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} + // altimate_change start — offline mode uses only the cached or bundled catalog + if (offlineModeEnabled() || Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} + // altimate_change end // Flock is cross-process: concurrent opencode CLIs can race on this cache file. const text = yield* Effect.scoped( Effect.gen(function* () { @@ -217,6 +221,9 @@ export const layer = Layer.effect( const get = (): Effect.Effect> => cachedGet const refresh = Effect.fn("ModelsDev.refresh")(function* (force = false) { + // altimate_change start — skip forced catalog refresh in offline mode + if (offlineModeEnabled()) return + // altimate_change end if (!force && (yield* fresh())) return yield* Effect.scoped( Effect.gen(function* () { @@ -234,7 +241,9 @@ export const layer = Layer.effect( ) }) - if (!Flag.OPENCODE_DISABLE_MODELS_FETCH && !process.argv.includes("--get-yargs-completions")) { + // altimate_change start — skip background refresh in offline mode + if (!offlineModeEnabled() && !Flag.OPENCODE_DISABLE_MODELS_FETCH && !process.argv.includes("--get-yargs-completions")) { + // altimate_change end // Schedule.spaced runs the effect once, then waits between completions. yield* Effect.forkScoped(refresh().pipe(Effect.repeat(Schedule.spaced("60 minutes")), Effect.ignore)) } diff --git a/packages/core/src/npm.ts b/packages/core/src/npm.ts index f3398e8391..3207466e66 100644 --- a/packages/core/src/npm.ts +++ b/packages/core/src/npm.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offlineModeEnabled } from "./flag/flag" +// altimate_change end export * as Npm from "./npm" import path from "path" @@ -126,6 +129,14 @@ export const layer = Layer.effect( return resolveEntryPoint(name, path.join(dir, "node_modules", name)) } + // altimate_change start — offline mode skips registry installs + if (offlineModeEnabled()) + return yield* new InstallFailedError({ + add: [pkg], + dir, + cause: new Error(`Install ${pkg} while online.`), + }) + // altimate_change end const tree = yield* reify({ dir, add: [pkg] }) const first = tree.edgesOut.values().next().value?.to if (!first) { @@ -137,6 +148,9 @@ export const layer = Layer.effect( }, Effect.scoped) const install: Interface["install"] = Effect.fn("Npm.install")(function* (dir, input) { + // altimate_change start — offline mode skips registry installs + if (offlineModeEnabled()) return + // altimate_change end const canWrite = yield* afs.access(dir, { writable: true }).pipe( Effect.as(true), Effect.orElseSucceed(() => false), @@ -225,6 +239,8 @@ export const layer = Layer.effect( return Option.some(path.join(binDir, bin.value)) } + // altimate_change — a missing offline binary should leave the cache untouched + if (offlineModeEnabled()) return Option.none() yield* fs.remove(path.join(dir, "package-lock.json")).pipe(Effect.orElseSucceed(() => {})) yield* add(pkg) diff --git a/packages/core/src/observability/otlp.ts b/packages/core/src/observability/otlp.ts index dd99ebc143..04d7c5fd55 100644 --- a/packages/core/src/observability/otlp.ts +++ b/packages/core/src/observability/otlp.ts @@ -1,6 +1,8 @@ import { Layer } from "effect" import { OtlpLogger } from "effect/unstable/observability" -import { Flag } from "../flag/flag" +// altimate_change start — offline mode +import { Flag, offlineModeEnabled } from "../flag/flag" +// altimate_change end import { InstallationChannel, InstallationVersion } from "../installation/version" import { runID } from "./shared" @@ -48,12 +50,16 @@ export function resource(): { serviceName: string; serviceVersion: string; attri } export function loggers() { - if (!endpoint) return [] + // altimate_change start — offline mode disables OTLP export + if (offlineModeEnabled() || !endpoint) return [] + // altimate_change end return [OtlpLogger.make({ url: `${endpoint}/v1/logs`, resource: resource(), headers })] } export async function tracingLayer() { - if (!endpoint) return Layer.empty + // altimate_change start — offline mode disables OTLP export + if (offlineModeEnabled() || !endpoint) return Layer.empty + // altimate_change end const NodeSdk = await import("@effect/opentelemetry/NodeSdk") const OTLP = await import("@opentelemetry/exporter-trace-otlp-http") const SdkBase = await import("@opentelemetry/sdk-trace-base") diff --git a/packages/core/src/ripgrep/binary.ts b/packages/core/src/ripgrep/binary.ts index 3f482ccb87..b8767f16cb 100644 --- a/packages/core/src/ripgrep/binary.ts +++ b/packages/core/src/ripgrep/binary.ts @@ -1,3 +1,6 @@ +// altimate_change start — prevent ripgrep downloads in offline mode +import { offlineModeEnabled } from "../flag/flag" +// altimate_change end import path from "path" import { Context, Effect, Layer, Stream } from "effect" import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" @@ -168,6 +171,10 @@ export namespace RipgrepBinary { const target = path.join(Global.Path.bin, `rg${process.platform === "win32" ? ".exe" : ""}`) if (yield* fs.isFile(target).pipe(Effect.orDie)) return target + // altimate_change start — preserve installed ripgrep and skip downloads offline + if (offlineModeEnabled()) + return yield* Effect.fail(new Error("Install ripgrep while online to use file search in offline mode.")) + // altimate_change end const platformKey = `${process.arch}-${process.platform}` as keyof typeof PLATFORM const config = PLATFORM[platformKey] diff --git a/packages/core/src/v1/config/config.ts b/packages/core/src/v1/config/config.ts index b6fe79e97a..a8e11fbf2c 100644 --- a/packages/core/src/v1/config/config.ts +++ b/packages/core/src/v1/config/config.ts @@ -65,6 +65,11 @@ export const Info = Schema.Struct({ autoshare: Schema.optional(Schema.Boolean).annotate({ description: "@deprecated Use 'share' field instead. Share newly created sessions automatically", }), + // altimate_change start — offline mode + offline: Schema.optional(Schema.Boolean).annotate({ + description: "Use the configured model endpoint and cached local resources without other network access", + }), + // altimate_change end autoupdate: Schema.optional(Schema.Union([Schema.Boolean, Schema.Literal("notify")])).annotate({ description: "Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications", diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index e09e3e1a5d..e9498bcff6 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -29,6 +29,28 @@ describe("Git", () => { ), ) + it.live("offline rejects clone and fetch while preserving local metadata", () => + withRemote((fixture) => + Effect.gen(function* () { + const git = yield* Git.Service + const target = path.join(fixture.root, "checkout") + expect((yield* git.clone({ remote: fixture.remote, target })).exitCode).toBe(0) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + expect(yield* git.head(target)).toBeString() + const rejected = path.join(fixture.root, "rejected") + expect((yield* git.clone({ remote: fixture.remote, target: rejected })).stderr).toContain("online run") + expect((yield* git.fetch(target)).stderr).toContain("online run") + expect((yield* git.fetchBranch(target, "main")).stderr).toContain("online run") + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), + ), + ) + it.live("fetches, checks out, and resets remote changes", () => withRemote((fixture) => Effect.gen(function* () { diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 31a3e57c10..d7cbd8fe85 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -126,6 +126,26 @@ const initialState: MockState = { } describe("ModelsDev Service", () => { + it.live("offline mode keeps the cached catalog even on forced refresh", () => + Effect.gen(function* () { + const original = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + yield* writeCache(fixture2) + const state = yield* Ref.make(initialState) + const result = yield* provided( + state, + ModelsDev.Service.use((s) => s.refresh(true).pipe(Effect.andThen(s.get()))), + ) + expect((yield* Ref.get(state)).calls).toEqual([]) + expect(result).toEqual(fixture2) + } finally { + if (original === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = original + } + }), + ) + it.live("get() returns providers from disk when cache file exists", () => Effect.gen(function* () { yield* writeCache(fixture) diff --git a/packages/core/test/npm.test.ts b/packages/core/test/npm.test.ts index c149116cd5..d221e61208 100644 --- a/packages/core/test/npm.test.ts +++ b/packages/core/test/npm.test.ts @@ -64,6 +64,36 @@ describe("Npm.add", () => { }) }) +test("offline npm uses the cache and skips installation", async () => { + await using tmp = await tmpdir() + const cache = path.join(tmp.path, "cache") + const dir = path.join(cache, "packages", "fixture", "node_modules", "fixture") + await writePackage(dir, { name: "fixture", main: "index.js" }) + await Bun.write(path.join(dir, "index.js"), "export const fixture = true\n") + const binary = path.join(path.dirname(dir), ".bin", "fixture") + await Bun.write(binary, "fixture") + const lock = path.join(cache, "packages", "not-in-cache", "package-lock.json") + await Bun.write(lock, "{}") + const before = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + await Effect.gen(function* () { + const npm = yield* Npm.Service + expect(Option.isSome((yield* npm.add("fixture")).entrypoint)).toBe(true) + expect(yield* npm.which("fixture")).toEqual(Option.some(binary)) + expect(yield* npm.which("not-in-cache")).toEqual(Option.none()) + expect(yield* Effect.promise(() => Bun.file(lock).exists())).toBe(true) + const missing = yield* Effect.flip(npm.add("not-in-cache")) + expect(missing.cause).toEqual(new Error("Install not-in-cache while online.")) + yield* npm.install(tmp.path, { add: [{ name: "not-in-cache" }] }) + }).pipe(Effect.scoped, Effect.provide(npmLayer(cache)), Effect.runPromise) + await expect(fs.stat(path.join(tmp.path, "node_modules"))).rejects.toThrow() + } finally { + if (before === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = before + } +}) + describe("Npm.install", () => { test("respects omit from project .npmrc", async () => { await using tmp = await tmpdir() diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 4786164c1a..42fca5af31 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -41,7 +41,7 @@ import type { RuntimePythonEnvironment, } from "@altimateai/dbt-integration" -function configuration(cfg: Config): DBTConfiguration { +function configuration(cfg: Config, options: CreateOptions): DBTConfiguration { return { getDbtCustomRunnerImport: () => DEFAULT_CONFIGURATION_VALUES.dbtCustomRunnerImport, getDbtIntegration: () => cfg.dbtIntegration ?? DEFAULT_CONFIGURATION_VALUES.dbtIntegration, @@ -52,7 +52,7 @@ function configuration(cfg: Config): DBTConfiguration { getQueryLimit: () => cfg.queryLimit ?? DEFAULT_CONFIGURATION_VALUES.queryLimit, getEnableNotebooks: () => DEFAULT_CONFIGURATION_VALUES.enableNotebooks, getDisableQueryHistory: () => DEFAULT_CONFIGURATION_VALUES.disableQueryHistory, - getInstallDepsOnProjectInitialization: () => DEFAULT_CONFIGURATION_VALUES.installDepsOnProjectInitialization, + getInstallDepsOnProjectInitialization: () => options.offline ? false : DEFAULT_CONFIGURATION_VALUES.installDepsOnProjectInitialization, getDisableDepthsCalculation: () => true, getWorkingDirectory: () => cfg.projectRoot, getAltimateUrl: () => "", @@ -83,6 +83,10 @@ function terminal(): DBTTerminal { /** What `create` needs besides the saved config. */ export type CreateOptions = { + /** Skip automatic dependency downloads and anonymous usage reporting. */ + offline?: boolean + /** The profiles directory dbt must read (given to dbt as DBT_PROFILES_DIR). */ + profilesDir?: string /** * The folder dbt writes its artifacts to (manifest.json, partial_parse.msgpack, run_results.json) for * every command this adapter runs, given to dbt as DBT_TARGET_PATH. Unset, dbt writes to the project's @@ -96,6 +100,12 @@ export type CreateOptions = { function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { const vars = { ...process.env } + if (options.offline) { + vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" + vars.DO_NOT_TRACK = "1" + vars.DBT_VERSION_CHECK = "false" + } + if (options.profilesDir) vars.DBT_PROFILES_DIR = options.profilesDir if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath return { pythonPath: cfg.pythonPath, @@ -113,7 +123,7 @@ export function hasModelLineage(adapter?: DBTProjectIntegrationAdapter): boolean } export async function create(cfg: Config, options: CreateOptions = {}): Promise { - const config = configuration(cfg) + const config = configuration(cfg, options) const term = terminal() const factory = new DBTCommandFactory(config) diff --git a/packages/dbt-tools/src/index.ts b/packages/dbt-tools/src/index.ts index 93875fbab3..b993b20b87 100644 --- a/packages/dbt-tools/src/index.ts +++ b/packages/dbt-tools/src/index.ts @@ -146,7 +146,9 @@ async function main() { let adapter try { const { create } = await import("./adapter") - adapter = await create(cfg) + // Inherited from an offline Altimate Code session (same parse as its kill switches). + const offline = !["", "0", "false", "off", "no"].includes(process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() ?? "") + adapter = await create(cfg, { offline }) } catch (err) { return failure(err) } diff --git a/packages/drivers/src/duckdb.ts b/packages/drivers/src/duckdb.ts index 19e9bb4ab4..4f3a0367b4 100644 --- a/packages/drivers/src/duckdb.ts +++ b/packages/drivers/src/duckdb.ts @@ -112,6 +112,8 @@ export async function connect( // altimate_change start — configurable open budget const { ms: openTimeoutMs, source: openTimeoutSource } = resolveOpenTimeoutMs(config) // altimate_change end + // altimate_change — offline mode turns off automatic DuckDB extension installs (explicit INSTALL still downloads) + const offline = !["", "0", "false", "off", "no"].includes(process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() ?? "") const engineOptions = { engine: "duckdb", label: "DuckDB", storePath: dbPath, cwd } as const // altimate_change start — preserve caller DuckDB state while keeping scratch secrets isolated const duckdbHome = path.join(process.env.HOME || process.env.USERPROFILE || os.homedir(), ".duckdb") @@ -209,7 +211,7 @@ export async function connect( const key = dbPath === ":memory:" ? undefined - : JSON.stringify([dbPath, accessMode ?? "READ_WRITE", config.sandbox_directory, cwd, extensionDirectory]) + : JSON.stringify([dbPath, accessMode ?? "READ_WRITE", config.sandbox_directory, cwd, extensionDirectory, offline]) let entry = key === undefined ? undefined : engines.get(key) while (entry?.closing) { await entry.closing @@ -231,6 +233,7 @@ export async function connect( extensionDirectory, secretDirectory, sandboxDirectory: config.sandbox_directory, + offline, }, // altimate_change end openTimeoutMs, diff --git a/packages/drivers/src/local-engine-child-source.ts b/packages/drivers/src/local-engine-child-source.ts index ad5684a4a4..3595e2f164 100644 --- a/packages/drivers/src/local-engine-child-source.ts +++ b/packages/drivers/src/local-engine-child-source.ts @@ -101,6 +101,8 @@ async function open(p) { temp_directory: process.env.TMPDIR + "/duckdb-" + process.pid, ...(p.accessMode ? { access_mode: p.accessMode } : {}), ...(p.extensionDirectory ? { extension_directory: p.extensionDirectory } : {}), + // altimate_change — offline mode never downloads extensions; installed ones still load + ...(p.offline ? { autoinstall_known_extensions: "false" } : {}), }; let instance; await new Promise((resolve, reject) => { diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 2d35a56241..611c496b94 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end // altimate_change start — debug report: gathers the facts `report.ts` analyses /** * Every probe here is read-only and independently guarded: a failing probe is @@ -407,9 +410,13 @@ export function readLogTail(file: string, maxBytes = LOG_READ_BYTES): string | u } export async function collect(opts: { network: boolean }): Promise { + // altimate_change — offline mode runs no network probes and does not start telemetry + if (offlineModeEnabled()) opts = { ...opts, network: false } const ctx = redactContext() const mcpServers = mcpFacts() - const [account, connections, telemetry] = await Promise.all([accountFacts(), connectionFacts(), telemetryFacts(opts.network)]) + const [account, connections, checked] = await Promise.all([accountFacts(), connectionFacts(), telemetryFacts(opts.network)]) + // altimate_change — offline mode reports its own reason rather than --no-network + const telemetry: Facts["telemetry"] = offlineModeEnabled() ? { enabled: false, checked: false, reason: "offline mode" } : checked const proxy = PROXY_VARS.some((k) => k.toLowerCase() !== "no_proxy" && process.env[k]) const network = opts.network ? await Promise.all(networkTargets(connections, account, telemetry).map((t) => probe(t.target, t.host, { proxy }))) diff --git a/packages/opencode/src/altimate/free/client.ts b/packages/opencode/src/altimate/free/client.ts index 34da580918..59399e6fc1 100644 --- a/packages/opencode/src/altimate/free/client.ts +++ b/packages/opencode/src/altimate/free/client.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy +import { Offline } from "@/config/offline" +// altimate_change end import { createHash, randomBytes } from "node:crypto" import fs from "node:fs/promises" import path from "node:path" @@ -401,6 +404,7 @@ async function registerOnce( export async function register( input: { origin: "picker" | "server"; signal?: AbortSignal } = { origin: "picker" }, ): Promise { + if (Offline.enabled()) throw new ConfigurationError("Register Altimate Base while online.") const startedAt = performance.now() let configuredGateway: string try { @@ -669,7 +673,7 @@ async function autoRegisterLocked(configuredGateway: string, signal: AbortSignal */ export async function autoRegister(signal?: AbortSignal): Promise { try { - if (autoRegisterDisabledByEnv()) return { status: "skipped", reason: "env" } + if (Offline.enabled() || autoRegisterDisabledByEnv()) return { status: "skipped", reason: "env" } let configuredGateway: string try { configuredGateway = gatewayUrl() diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts new file mode 100644 index 0000000000..af0272e3d3 --- /dev/null +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -0,0 +1,111 @@ +// altimate_change - new file +import { isLocalFilePath, normalizeConfig, type ConnectionConfig } from "@altimateai/drivers" +import { isLoopbackHost } from "@/config/offline" + +const DENIED = "Offline mode allows only local file databases and warehouses at a loopback host." +const MONGO_DIRECT = "Offline mode requires a direct MongoDB connection. Set direct_connection to true or directConnection=true in the connection URI." + +/** A local file path. Templates are rendered later, so they cannot be judged; UNC paths are network shares. */ +export function isLocalPath(value: unknown): boolean { + if (typeof value !== "string" || /\{[{%#]/.test(value) || /^(?:\\\\|\/\/)/.test(value)) return false + if (value === "" || value === ":memory:") return true + // file:////server/share is a UNC path written as a URL. + if (/^file:/i.test(value)) { + try { + const url = new URL(value) + return ["", "localhost"].includes(url.hostname) && !/^[\\/]{2}/.test(decodeURIComponent(url.pathname)) + } catch { + return false + } + } + // Rejects scheme:// URLs (s3, gcs, http and so on) and DuckDB's non-slash remote schemes such as md:. + return isLocalFilePath(value) +} + +/** Refuse a warehouse connection that does not stay on this machine. */ +export function assertLocalConnection(raw: ConnectionConfig): void { + const config = normalizeConfig(raw) + const type = String(config.type).toLowerCase() + const mongo = type === "mongodb" || type === "mongo" + // An SSH tunnel reaches another machine whatever the database type. + if (config.ssh_host) throw new Error(DENIED) + if (type === "duckdb" || type === "sqlite") { + if (!isLocalPath(config.path)) throw new Error(DENIED) + return + } + // Only types whose driver connects to the configured host can be judged; account- or project-addressed + // warehouses (Snowflake, BigQuery, Databricks and others) are refused. + if (!HOST_ADDRESSED.has(type) || config.replica_set) throw new Error(DENIED) + const { port } = config + if (port !== undefined) { + const numeric = typeof port === "string" && !/\D/.test(port) ? Number(port) : port + if (typeof numeric !== "number" || !Number.isInteger(numeric) || numeric < 1 || numeric > 65535) + throw new Error(DENIED) + } + if (config.direct_connection === false) throw new Error(mongo ? MONGO_DIRECT : DENIED) + // Trino and ClickHouse build `${protocol}://${host}`, so a protocol value could carry its own authority. + if ( + ["trino", "clickhouse"].includes(type) && + config.protocol !== undefined && + !["http", "https"].includes(String(config.protocol).trim().toLowerCase()) + ) + throw new Error(DENIED) + // A TNS alias or DSN names a host through tnsnames.ora or odbc.ini, which this check cannot see. + if (config.tns_name !== undefined || config.dsn !== undefined) throw new Error(DENIED) + // Cloud sign-in contacts an identity provider even for a loopback host. SQL Server's driver and dbt map many + // values (cli, default, msi, ActiveDirectory*, ServicePrincipal) to Azure AD, so only local methods pass. + if ( + ["sqlserver", "mssql"].includes(type) && + config.authentication !== undefined && + !["", "sql", "sqlpassword", "sql-password", "ntlm", "windows"].includes(String(config.authentication).trim().toLowerCase()) + ) + throw new Error(DENIED) + // A Unix socket is a local file. + if (config.socketPath !== undefined && !(typeof config.socketPath === "string" && config.socketPath.startsWith("/"))) + throw new Error(DENIED) + const postgres = ["postgres", "postgresql", "redshift"].includes(type) + // Postgres accepts a socket directory as its host; a comma-separated list names several hosts. + const socketDir = (host: string) => postgres && host.startsWith("/") && !host.includes(",") + const hosts = [config.host, config.server].filter((value) => value !== undefined) + for (const raw of hosts) { + // SQL Server names an instance as host\instance. + const host = typeof raw === "string" && ["sqlserver", "mssql"].includes(type) ? raw.split("\\")[0] : raw + if (typeof host === "string" && socketDir(host)) continue + if (!isLoopbackHost(host)) throw new Error(DENIED) + } + const url = config.connection_string ?? config.url + let direct = config.direct_connection === true + if (url !== undefined) { + let parsed: URL + try { + parsed = new URL(String(url)) + } catch { + throw new Error(DENIED) + } + // mongodb+srv:// and replica sets discover other hosts. + const param = (name: string) => [...parsed.searchParams].find(([key]) => key.toLowerCase() === name)?.[1] + const directParam = param("directconnection")?.toLowerCase() + if (parsed.protocol.endsWith("+srv:") || param("replicaset") !== undefined) throw new Error(DENIED) + if (directParam === "false") throw new Error(mongo ? MONGO_DIRECT : DENIED) + if (mongo && param("proxyhost") !== undefined) throw new Error(DENIED) + if (config.direct_connection === undefined) direct = directParam === "true" + const mechanism = [...parsed.searchParams].find(([key]) => key.toLowerCase() === "authmechanism")?.[1]?.toUpperCase() + if (mechanism && ["MONGODB-AWS", "MONGODB-OIDC", "GSSAPI"].includes(mechanism)) throw new Error(DENIED) + // A query parameter such as Postgres's ?host= or ?hostaddr= overrides the URL's host. + const overrides = [...parsed.searchParams].filter(([key]) => ["host", "hostaddr", "server"].includes(key.toLowerCase())) + if (!parsed.hostname && overrides.length === 0) throw new Error(DENIED) + for (const host of [parsed.hostname, ...overrides.map(([, value]) => value)].filter(Boolean)) + if (!socketDir(host) && !isLoopbackHost(host)) throw new Error(DENIED) + } + // A loopback seed can otherwise discover and connect to replica-set peers. + if (mongo && !direct) throw new Error(MONGO_DIRECT) + // Without a host these drivers connect to localhost; any other type names its server some other way. + if (hosts.length === 0 && url === undefined && config.socketPath === undefined && !LOCALHOST_BY_DEFAULT.has(type)) + throw new Error(DENIED) +} + +const HOST_ADDRESSED = new Set([ + "postgres", "postgresql", "redshift", "mysql", "mariadb", "sqlserver", "mssql", "clickhouse", "trino", "oracle", "mongodb", "mongo", +]) + +const LOCALHOST_BY_DEFAULT = new Set(["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "clickhouse", "mongodb", "mongo", "trino", "redshift"]) diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 39fcf6139f..1b521d83ab 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -1,3 +1,9 @@ +// altimate_change start — validate offline dbt profiles before starting adapters +import { Offline } from "@/config/offline" +import { assertLocalDbt } from "../dbt/offline" +const isOfflineRefusal = (error: unknown) => + Offline.enabled() && error instanceof Error && error.message.startsWith("Offline mode") +// altimate_change end /** * Register native connection handlers with the Dispatcher. * @@ -66,7 +72,7 @@ export const dbtAdapterInternals: { /** Replaces the dbt config read, so a test can hold an attempt open. */ readConfig?: () => Promise /** Replaces dbt-tools' adapter creation, so a test can see which integration modes were tried. */ - create?: (config: any, options?: { targetPath?: string }) => Promise + create?: (config: any, options?: { targetPath?: string; offline?: boolean; profilesDir?: string }) => Promise /** Replaces the check for dbt-integration's lineage, which a test's fake adapter provides itself. */ hasModelLineage?: (adapter?: unknown) => boolean /** Adapter creation attempts since the last reset — what single-flight bounds. */ @@ -124,6 +130,11 @@ async function ensureDbtAdapter(): Promise { return publish(null) } + // The integration reads profiles.yml relative to the project, so check from there. + const offline = Offline.enabled() + ? await assertLocalDbt(dbtConfig.projectRoot, ["--project-dir", dbtConfig.projectRoot], dbtConfig.dbtIntegration, dbtConfig.projectRoot) + : undefined + // Create the adapter. Its dbt commands write their artifacts to a folder of their own: the project's // target/manifest.json is the user's (and other tools'), and a tool's compile or show would rewrite // it with compiled SQL for only the nodes that command compiled. @@ -132,8 +143,15 @@ async function ensureDbtAdapter(): Promise { const options = SEPARATE_TARGET_MODES.has(dbtConfig.dbtIntegration || "core") ? { targetPath: await dbtToolTargetPath(dbtConfig.projectRoot) } : {} - return publish(await create(dbtConfig, options), dbtConfig.projectRoot) - } catch { + // Offline, dbt reads exactly the profiles directory that was checked. + const adapter = await create(dbtConfig, { + ...options, + ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}), + }) + return publish(adapter, dbtConfig.projectRoot) + } catch (error) { + // An offline refusal is the answer, not "dbt unavailable": falling back would run the query elsewhere. + if (isOfflineRefusal(error)) throw error // dbt-tools not available or config invalid — fall back to native return publish(null) } finally { @@ -289,7 +307,7 @@ async function tryExecuteViaDbt( } catch (e) { // A deadline or abort is not "dbt unavailable": the query may still be running, and // re-running it on the native driver would double the work and the wait. - if (isQueryTimeoutError(e) || context?.signal?.aborted || (e instanceof Error && e.name === "AbortError")) throw e + if (isOfflineRefusal(e) || isQueryTimeoutError(e) || context?.signal?.aborted || (e instanceof Error && e.name === "AbortError")) throw e // dbt execution failed — fall back to native driver silently return null } diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 98d455d648..99f3a7ca8d 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -1,3 +1,7 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +import { assertLocalConnection } from "./offline" +// altimate_change end /** * ConnectionRegistry — manages database connections. * @@ -446,6 +450,9 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) + // altimate_change start — validate the resolved target before any tunnel rewrites it + if (Offline.enabled()) assertLocalConnection(resolvedConfig) + // altimate_change end // altimate_change start — validate password is a string for drivers that require it // Prevents cryptic SASL/SCRAM errors from database drivers @@ -675,14 +682,14 @@ export async function get(name: string): Promise { if (cached) { // altimate_change start — a reused connection can reconnect and ask for a browser sign-in; route it here SignInNotice.rememberOrigin(accountOf(configs.get(name))) - // altimate_change end return cached + // altimate_change end } // If a connector is already being created, await the same Promise // altimate_change start — the slot holds the attempt - const inflight = pending.get(name)?.promise - if (inflight) return inflight + const inflight = pending.get(name) + if (inflight?.promise) return inflight.promise // altimate_change end const config = configs.get(name) diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts new file mode 100644 index 0000000000..c05d886e67 --- /dev/null +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -0,0 +1,89 @@ +// altimate_change - new file +import fs from "node:fs/promises" +import path from "node:path" +import os from "node:os" +import { parse } from "yaml" +import { assertLocalConnection, isLocalPath } from "../connections/offline" + +/** dbt searches the starting directory and its parents for the project file. */ +async function findProjectRoot(start: string): Promise { + let dir = path.resolve(start) + while (true) { + if (await fs.stat(path.join(dir, "dbt_project.yml")).then(() => true, () => false)) return dir + const parent = path.dirname(dir) + if (parent === dir) return path.resolve(start) + dir = parent + } +} + +function option(args: string[], ...names: string[]) { + let result: string | undefined + for (let i = 0; i < args.length; i++) { + const arg = args[i] + if (arg === "--") break + for (const name of names) { + if (arg === name) result = args[++i] + else if (arg.startsWith(name.startsWith("--") ? name + "=" : name) && arg !== name) + result = arg.slice(name.length + (name.startsWith("--") ? 1 : 0)) + } + } + return result +} + +/** DuckDB extensions, attachments and plugins that dbt-duckdb would fetch from the network. */ +function remoteDuckdbSetting(output: Record) { + const values = [ + output.external_root, + ...(Array.isArray(output.attach) ? output.attach.map((item: any) => item?.path) : []), + ...(Array.isArray(output.extensions) + ? output.extensions.map((item: any) => (typeof item === "string" ? undefined : item?.repo)) + : []), + ] + return ( + values.some((value) => value !== undefined && !isLocalPath(value)) || + output.remote !== undefined || + // Only DuckDB and SQLite files can be judged; other attachment types name a database server. + (Array.isArray(output.attach) && + output.attach.some((item: any) => item?.type !== undefined && !["duckdb", "sqlite"].includes(item.type))) || + (Array.isArray(output.filesystems) && output.filesystems.length > 0) || + (Array.isArray(output.secrets) && output.secrets.length > 0) + ) +} + +/** + * Refuse a dbt run whose selected profile and target leave this machine. + * `cwd` is where dbt runs; dbt reads `profiles.yml` from there before `~/.dbt`. + * Returns the profiles directory that was checked, so dbt can be pinned to it. + */ +export async function assertLocalDbt( + projectRoot: string, + args: string[] = [], + integration = "core", + cwd = process.cwd(), +): Promise<{ profilesDir: string }> { + if (!["core", "corecommand", "fusion"].includes(integration)) throw new Error("Offline mode disables cloud dbt integrations.") + const root = option(args, "--project-dir") ?? process.env.DBT_PROJECT_DIR ?? (await findProjectRoot(projectRoot)) + const project = parse(await fs.readFile(path.join(root, "dbt_project.yml"), "utf8")) + // dbt's order: --profiles-dir, DBT_PROFILES_DIR, the working directory, then ~/.dbt. + const explicit = (option(args, "--profiles-dir") ?? process.env.DBT_PROFILES_DIR)?.replace(/^~(?=$|[\\/])/, () => os.homedir()) + const profilesDir = path.resolve( + cwd, + explicit ?? (await fs.stat(path.join(cwd, "profiles.yml")).then(() => cwd, () => path.join(os.homedir(), ".dbt"))), + ) + const profiles = parse(await fs.readFile(path.join(profilesDir, "profiles.yml"), "utf8")) + const profile = profiles?.[option(args, "--profile") ?? process.env.DBT_PROFILE ?? project?.profile] + const output = profile?.outputs?.[option(args, "--target", "-t") ?? process.env.DBT_TARGET ?? profile?.target ?? "default"] + if (!output || typeof output.type !== "string") + throw new Error("Offline mode could not resolve a local dbt profile and target.") + // Cloud sign-in methods contact an identity provider. + if (output.method && !["database", "password", "none"].includes(output.method)) + throw new Error("Offline mode disables dbt cloud authentication.") + if (output.type === "sqlite" && output.schemas_and_paths) { + for (const store of Object.values(output.schemas_and_paths)) assertLocalConnection({ type: "sqlite", path: store as string }) + } else { + assertLocalConnection({ ...output, path: output.path ?? (output.type === "duckdb" ? ":memory:" : undefined) }) + } + if (output.type === "duckdb" && remoteDuckdbSetting(output)) + throw new Error("Offline mode refuses dbt-duckdb settings that use remote storage, a remote server or a remote extension repository.") + return { profilesDir } +} diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index b67a16887c..7686767941 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -1,3 +1,7 @@ +// altimate_change start — validate offline dbt targets before spawning dbt +import { Offline } from "@/config/offline" +import { assertLocalDbt } from "./offline" +// altimate_change end /** * dbt CLI wrapper — spawn dbt commands as subprocesses. * @@ -24,7 +28,37 @@ function ensureUpstreamSelector(select: string, command: string): string { /** * Run a dbt CLI command via subprocess. */ -export function runDbt(params: DbtRunParams): Promise { +export async function runDbt(params: DbtRunParams): Promise { + // Offline: dbt runs with the exact profiles directory checked here and without its + // usage-stats and PyPI version-check requests. + let offlineEnv: NodeJS.ProcessEnv | undefined + if (Offline.enabled()) { + try { + const command = params.command || "run" + if (command === "deps") throw new Error("Offline mode disables dbt dependency installation.") + if ((params.args ?? []).some((arg) => arg === "--send-anonymous-usage-stats" || arg.startsWith("--send-anonymous-usage-stats="))) + throw new Error("Offline mode disables dbt usage reporting.") + // dbt's version flags look up the latest release on PyPI whatever DBT_VERSION_CHECK says. + if ((params.args ?? []).some((arg) => ["--version", "-V", "-v"].includes(arg))) + throw new Error("Offline mode disables dbt version reporting.") + // `dbt init` creates a project and `dbt clean` deletes local folders; neither opens a connection. + const checked = command === "init" || command === "clean" + ? undefined + : await assertLocalDbt(params.project_dir || process.cwd(), [ + ...(params.args ?? []), + ...(params.project_dir ? ["--project-dir", params.project_dir] : []), + ]) + offlineEnv = { + ...process.env, + ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), + DBT_SEND_ANONYMOUS_USAGE_STATS: "false", + DO_NOT_TRACK: "1", + DBT_VERSION_CHECK: "false", + } + } catch (error) { + return { stdout: "", stderr: String(error), exit_code: 1 } + } + } return new Promise((resolve) => { const command = params.command || "run" const args: string[] = [command] @@ -42,7 +76,7 @@ export function runDbt(params: DbtRunParams): Promise { args.push("--project-dir", params.project_dir) } - execFile("dbt", args, { timeout: 300_000 }, (error, stdout, stderr) => { + execFile("dbt", args, { timeout: 300_000, env: offlineEnv ?? process.env }, (error, stdout, stderr) => { if (error) { if ((error as any).code === "ENOENT") { resolve({ diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 3ea8059b42..9e7be68c1a 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -1,4 +1,8 @@ import { execFile } from "node:child_process" +// altimate_change — offline mode +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +import { existsSync, readdirSync, realpathSync } from "node:fs" +import path from "node:path" // Direct cross-workspace import — `@altimateai/dbt-tools`'s `src/index.ts` is // a CLI entry (runs on import), so we bypass the package entrypoint and // consume the resolver from its file directly. This is the same pattern @@ -80,11 +84,42 @@ export function _resetDbtRuntimeCacheForTests() { cached = undefined } +// altimate_change start — offline mode finds dbt-duckdb in the environment dbt was installed into +function hasDuckdbAdapter(dbtPath: string): boolean { + // pipx, uv and Homebrew link dbt from their own environment, so follow the link first. + let binDir: string + try { + binDir = path.dirname(realpathSync(dbtPath)) + } catch { + return false + } + const lib = path.join(binDir, "..", process.platform === "win32" ? "Lib" : "lib") + const pythons = process.platform === "win32" ? [""] : readdirSafe(lib).filter((name) => name.startsWith("python")) + return pythons.some((python) => + ["site-packages", "dist-packages"].some((dir) => existsSync(path.join(lib, python, dir, "dbt", "adapters", "duckdb"))), + ) +} + +function readdirSafe(dir: string): string[] { + try { + return readdirSync(dir) + } catch { + return [] + } +} +// altimate_change end + async function probe(): Promise { // resolveDbt: multi-manager search (venv/uv/pyenv/conda/pipx/poetry/… // + PATH + explicit override via ALTIMATE_DBT_PATH). Returns the first // candidate that exists. const resolved = resolveDbt() + // altimate_change start — `dbt --version` asks PyPI for the latest release, so offline mode does not run it + if (offlineModeEnabled()) { + const dbt = resolved.source.startsWith("fallback") ? Bun.which("dbt", { PATH: process.env.PATH ?? "" }) : resolved.path + return { hasDbt: dbt !== null, hasDbtDuckdb: dbt !== null && hasDuckdbAdapter(dbt) } + } + // altimate_change end const env = buildDbtEnv(resolved) // Async --version invocation. Reads BOTH stdout AND stderr (some dbt 1.x diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5df4d68dc3..dd248bfe7b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -17,6 +17,7 @@ import fs from "fs" import path from "path" import os from "os" import { fileLog } from "@/altimate/util/file-log" +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" const log = Log.create({ service: "telemetry" }) @@ -2516,6 +2517,7 @@ export namespace Telemetry { // Deduplicates concurrent calls: non-awaited init() in middleware/worker // won't race with await init() in session prompt. export function init(): Promise { + if (offlineModeEnabled()) return Promise.resolve() // altimate_change start — never re-init across an in-flight shutdown. // // session/prompt.ts init()s at the start of every session loop and shutdown()s at the end, so a @@ -2980,6 +2982,7 @@ export namespace Telemetry { // running, now: the event is serialised at flush time, when that turn may be over. Only an // explicit per-event `session_id` is used — the process-global session can be another one. // Becomes the envelope's `ai.operation.id`, joining it to the extension's and backend's records. + if (offlineModeEnabled()) return const eventSession = (event as { session_id?: unknown }).session_id const operationId = typeof eventSession === "string" ? TraceContext.activeTraceId(eventSession) : undefined if (operationId) (event as any)._operation_id = operationId diff --git a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts index 7f4d14560b..4ff375709c 100644 --- a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts +++ b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // Whether the `tool` CLI exposes the linked-workspace tools, and the workspace section of `tool context`. // An explicit flag always wins; without one the tools are on exactly when the project is linked. @@ -22,6 +23,11 @@ export async function resolveWorkspaceTools( directory: string, linked: (directory: string) => Promise = projectIsLinked, ): Promise { + // Workspace tools call the workspace service, which offline mode does not reach. + if (Offline.enabled()) { + if (flag === true) process.stderr.write("Workspace tools are unavailable in offline mode.\n") + return false + } return flag ?? (await linked(directory)) } diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index ca0cb1551a..b0667c3b49 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -3,6 +3,8 @@ import { Tool } from "../../tool/tool" import { Dispatcher } from "../native" import { existsSync, readFileSync } from "fs" import path from "path" +// altimate_change — offline mode +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" import { Telemetry } from "@/telemetry" // altimate_change — onboarding funnel: environment_scan_completed import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding" @@ -484,6 +486,8 @@ export async function detectDataTools(skip: boolean): Promise { // non-zero" (binary present but the version check failed). const results = await Promise.all( DATA_TOOL_NAMES.map(async (tool): Promise => { + // altimate_change — `dbt --version` asks PyPI for the latest release, so offline mode only checks PATH + if (tool === "dbt" && offlineModeEnabled()) return { name: tool, installed: Bun.which(tool, { PATH: process.env.PATH ?? "" }) !== null } const result = safeSpawnSync([tool, "--version"], { timeout: 5000 }) if (result && result.exitCode === 0) { return { diff --git a/packages/opencode/src/altimate/tools/warehouse-install-driver.ts b/packages/opencode/src/altimate/tools/warehouse-install-driver.ts index 7a13871298..dcb7718f74 100644 --- a/packages/opencode/src/altimate/tools/warehouse-install-driver.ts +++ b/packages/opencode/src/altimate/tools/warehouse-install-driver.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import z from "zod" import path from "node:path" import { FSUtil } from "@opencode-ai/core/fs-util" @@ -85,6 +88,16 @@ export const WarehouseInstallDriverTool = Tool.define("warehouse_install_driver" } const packages = DRIVER_PACKAGES[driver].join(" ") + // altimate_change start — skip network work in offline mode + if (Offline.enabled()) { + const error = `Offline mode. Install the driver while online: npm install --prefix ${shellQuote(dir)} ${packages}` + return { + title: `${label} driver: offline`, + metadata: { success: false, driver, installed: false, alreadyPresent: false, dir, error }, + output: error, + } + } + // altimate_change end const externalPattern = FSUtil.normalizePathPattern(path.join(dir, "*")) // The cross-process install lock is a sibling of the managed directory, not // a child of it — it lives outside so npm never treats it as stray package diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 4af0971b40..d247d25ca4 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // Wire client for the workspace-binding endpoints in altimate-backend // (/datamate-project-bindings/*, added by AI-8398). Shared between the TUI @@ -429,6 +430,7 @@ async function req( // altimate_change end } = {}, ): Promise { + if (Offline.enabled()) throw new Error("Workspace API access requires an online run.") const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS const { url, instance, apiKey } = opts.actAs ?? (await creds()) const qs = opts.query ? "?" + new URLSearchParams(opts.query).toString() : "" diff --git a/packages/opencode/src/altimate/workspace/engine-offer.ts b/packages/opencode/src/altimate/workspace/engine-offer.ts index 5d2b83983f..6d424199f6 100644 --- a/packages/opencode/src/altimate/workspace/engine-offer.ts +++ b/packages/opencode/src/altimate/workspace/engine-offer.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // The install offer for a workspace whose engine is missing or too old. // @@ -80,6 +81,7 @@ export function installCommand(): string { * binding on disk and the engine on PATH. Null when there is nothing to offer: * unbound, or an engine that clears the floor. */ export async function describeOffer(directory: string): Promise { + if (Offline.enabled()) return null const binding = syncInternals.resolveBinding ? await syncInternals.resolveBinding(directory) : await readLocalBinding(directory).catch((err) => { @@ -232,6 +234,7 @@ export function runInstall( * usable engine — npm's global bin directory need not be on PATH — so the same * discovery the turn boundary does runs before success. */ export async function installEngine(): Promise { + if (Offline.enabled()) return { ok: false, error: "Install the workspace engine while online." } const spec = installSpec() if (syncInternals.install) return syncInternals.install(spec) const npm = process.platform === "win32" ? "npm.cmd" : "npm" @@ -367,6 +370,7 @@ export function toolsNeed(declared: number | undefined): string { /** Offer via the dialog surface when there is one; otherwise print (headless) * or toast (bus unavailable). Exactly one of these happens. */ export async function offerOrNotify(offer: EngineOffer, toast: Toast, sessionID: string): Promise { + if (Offline.enabled()) return // Telemetry: the offer was shown, on which surface, and whether Node was there to install with. const shown = (surface: "headless" | "dialog" | "bus" | "toast") => void nodeMajor() diff --git a/packages/opencode/src/altimate/workspace/engine-overlay.ts b/packages/opencode/src/altimate/workspace/engine-overlay.ts index 3d535c41ef..71bc3e473e 100644 --- a/packages/opencode/src/altimate/workspace/engine-overlay.ts +++ b/packages/opencode/src/altimate/workspace/engine-overlay.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // The workspace engine overlay. // @@ -230,7 +231,7 @@ export async function overlay( state.managed = opts.managed === true state.linked = null try { - if (!isEnabled() || isServe()) { + if (Offline.enabled() || !isEnabled() || isServe()) { state.current = null return } @@ -499,7 +500,7 @@ export async function beforeTurn(sessionID: string): Promise { * between this session's reconcile and its catalog snapshot. The hook's own * failures are logged and swallowed; `body`'s propagate. */ export async function atTurnStart(sessionID: string, body: () => Promise): Promise { - if (!isEnabled() || isServe()) { + if (Offline.enabled() || !isEnabled() || isServe()) { record(sessionID, { kind: "disabled" }) return body() } diff --git a/packages/opencode/src/altimate/workspace/identity.ts b/packages/opencode/src/altimate/workspace/identity.ts index 0490cbc40c..143f8164fd 100644 --- a/packages/opencode/src/altimate/workspace/identity.ts +++ b/packages/opencode/src/altimate/workspace/identity.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // Model-facing statement of Altimate Workspace identity: which workspace (if any) this // project is linked to, rendered UNCONDITIONALLY so "this/current/active workspace" has @@ -442,7 +443,7 @@ export async function systemSection(opts: { memoryTools?: MemoryTools } = {}): P // Behind the same opt-in as everything else about workspaces. A user outside // the pilot has no Altimate Workspace to be linked to, and must not be told // every turn that none is linked and how to link one. - if (!isEnabled()) return "" + if (Offline.enabled() || !isEnabled()) return "" try { const directory = Instance.directory const scope = await accountScope() diff --git a/packages/opencode/src/altimate/workspace/memory-sync.ts b/packages/opencode/src/altimate/workspace/memory-sync.ts index df928a7cd3..f85c79deb9 100644 --- a/packages/opencode/src/altimate/workspace/memory-sync.ts +++ b/packages/opencode/src/altimate/workspace/memory-sync.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // Mirrors Altimate Code memory blocks to the workspace memory store, and loads // a workspace's memory back into a session. @@ -119,7 +120,7 @@ function sessionState(sessionID: string): SessionMemory { /** The mirror follows the workspace kill switch and honours the memory opt-out. */ export function isEnabled(): boolean { - return !CoreFlag.ALTIMATE_DISABLE_WORKSPACE && !Flag.ALTIMATE_DISABLE_MEMORY + return !Offline.enabled() && !CoreFlag.ALTIMATE_DISABLE_WORKSPACE && !Flag.ALTIMATE_DISABLE_MEMORY } /** Test seam. Production leaves this unset and resolves the binding from the diff --git a/packages/opencode/src/altimate/workspace/review-notices.ts b/packages/opencode/src/altimate/workspace/review-notices.ts index 4393e67e54..5b11a77da3 100644 --- a/packages/opencode/src/altimate/workspace/review-notices.ts +++ b/packages/opencode/src/altimate/workspace/review-notices.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // Notices for the person's own workspace review requests (skills and knowledge bases): when the owner approves or // rejects one, it is kept and shown the same way a rule review is. Like a rule review notice (`state.notices` of the @@ -289,7 +290,7 @@ export async function poll(directory: string, deps: PollDeps = {}): Promise { - if (!workspacesOn()) return { status: "off" } + if (Offline.enabled() || !workspacesOn()) return { status: "off" } const [{ WorkspaceApi }, { resolveBindingOutcome, credentialDigest, accountDigest }, { RulesSync }] = await Promise.all([ import("./api-client"), import("./state"), diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index efa1dd7d44..1ae6738749 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -1,4 +1,5 @@ // altimate_change - new file +import { Offline } from "@/config/offline" // // Mirror a bound workspace's custom skill bundles onto disk, where the existing // skill discovery in ``@/skill`` finds them with no other change. @@ -1240,6 +1241,8 @@ class SupersededRunError extends Error { * failure path leaves whatever is already on disk in place, except the * deliberate purge described below. */ export async function syncSkills(directory: string): Promise { + // altimate_change — offline mode keeps the snapshot on disk as it is + if (Offline.enabled()) return { changed: false, skipped: [], error: "Run workspace refresh while online." } const canon = path.resolve(directory) // Joined BEFORE the flag is read, so the opt-out purge is serialised against // a sync too. Both paths write the same tree; with the purge outside this diff --git a/packages/opencode/src/bun/index.ts b/packages/opencode/src/bun/index.ts index d6c4538259..07a00333be 100644 --- a/packages/opencode/src/bun/index.ts +++ b/packages/opencode/src/bun/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import z from "zod" import { Global } from "../global" import { Log } from "../util/log" @@ -58,7 +61,7 @@ export namespace BunProc { const pkgjsonPath = path.join(Global.Path.cache, "package.json") const parsed = await Filesystem.readJson<{ dependencies: Record }>(pkgjsonPath).catch(async () => { const result = { dependencies: {} as Record } - await Filesystem.writeJson(pkgjsonPath, result) + if (!Offline.enabled()) await Filesystem.writeJson(pkgjsonPath, result) return result }) if (!parsed.dependencies) parsed.dependencies = {} as Record @@ -66,6 +69,13 @@ export namespace BunProc { const modExists = await Filesystem.exists(mod) const cachedVersion = dependencies[pkg] + // altimate_change start — use the cached package without checking the registry + if (Offline.enabled()) { + if (modExists && cachedVersion && (version === "latest" || cachedVersion === version)) return mod + throw new Error(`Install ${pkg} while online.`) + } + // altimate_change end + if (!modExists || !cachedVersion) { // continue to install } else if (version !== "latest" && cachedVersion === version) { diff --git a/packages/opencode/src/bun/registry.ts b/packages/opencode/src/bun/registry.ts index 90b7bbf5db..74b9dbe991 100644 --- a/packages/opencode/src/bun/registry.ts +++ b/packages/opencode/src/bun/registry.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import semver from "semver" import { Log } from "../util/log" import { Process } from "../util/process" @@ -10,6 +13,9 @@ export namespace PackageRegistry { } export async function info(pkg: string, field: string, cwd?: string): Promise { + // altimate_change start — do not query the package registry in offline mode + if (Offline.enabled()) return null + // altimate_change end const { code, stdout, stderr } = await Process.run([which(), "info", pkg, field], { cwd, env: { diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index c72bfe119a..eb713cec02 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import { cmd } from "./cmd" import { ConfigV1 } from "@opencode-ai/core/v1/config/config" import { effectCmd } from "../effect-cmd" @@ -137,8 +140,16 @@ export const McpServeCommand = cmd({ .option("workspace-tools", { type: "boolean", default: false, describe: "Expose linked workspace context, skills and read tools" }) .option("all-tools", { type: "boolean", default: false, describe: "Expose every tool on the allow-list, not just the default set" }), async handler(args) { + // The CLI middleware skips `mcp serve`, so offline mode starts here. + if (Offline.enabled() || (await Offline.optedIn(process.cwd()))) Offline.start() + if (Offline.enabled() && args.workspaceTools) process.stderr.write("Workspace tools are unavailable in offline mode.\n") const { serveStdio } = await import("../../altimate/mcp-server/server") - await serveStdio({ connections: args.connections, allowWrite: args.allowWrite, allTools: args.allTools, workspaceTools: args.workspaceTools }) + await serveStdio({ + connections: args.connections, + allowWrite: args.allowWrite, + allTools: args.allTools, + workspaceTools: !Offline.enabled() && args.workspaceTools, + }) }, }) // altimate_change end @@ -506,6 +517,9 @@ async function resolveConfigPath(baseDir: string, global = false) { } async function addMcpToConfig(name: string, mcpConfig: ConfigMCPV1.Info, configPath: string) { + // altimate_change start — offline mode refuses remote MCP servers + Offline.assertLocalMcp(mcpConfig) + // altimate_change end let text = "{}" if (await Filesystem.exists(configPath)) { text = await Filesystem.readText(configPath) @@ -877,6 +891,9 @@ export const McpDebugCommand = effectCmd({ return } + // altimate_change start — offline mode refuses remote MCP servers + Offline.assertLocalMcp(serverConfig) + // altimate_change end prompts.log.info(`Server: ${serverName}`) prompts.log.info(`URL: ${serverConfig.url}`) diff --git a/packages/opencode/src/cli/cmd/models.ts b/packages/opencode/src/cli/cmd/models.ts index b17293d333..19b612d1e6 100644 --- a/packages/opencode/src/cli/cmd/models.ts +++ b/packages/opencode/src/cli/cmd/models.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode reads the cached model catalog +import { Offline } from "@/config/offline" +// altimate_change end import { EOL } from "os" import { Effect } from "effect" import { ModelsDev } from "@opencode-ai/core/models-dev" @@ -27,7 +30,10 @@ export const ModelsCommand = effectCmd({ }), handler: Effect.fn("Cli.models")(function* (args) { const { Provider } = yield* Effect.promise(() => import("@/provider/provider")) - if (args.refresh) { + // altimate_change start — skip catalog refresh in offline mode + if (args.refresh && Offline.enabled()) UI.println("Model catalog refresh skipped in offline mode.") + if (args.refresh && !Offline.enabled()) { + // altimate_change end yield* ModelsDev.Service.use((s) => s.refresh(true)) UI.println(UI.Style.TEXT_SUCCESS_BOLD + "Models cache refreshed" + UI.Style.TEXT_NORMAL) } diff --git a/packages/opencode/src/cli/cmd/serve-upgrade-check.ts b/packages/opencode/src/cli/cmd/serve-upgrade-check.ts index 40ebb52c1a..7d069ab99b 100644 --- a/packages/opencode/src/cli/cmd/serve-upgrade-check.ts +++ b/packages/opencode/src/cli/cmd/serve-upgrade-check.ts @@ -1,6 +1,7 @@ // altimate_change start — self-update trigger for headless serve import { Instance } from "../../project/instance" import { InstanceBootstrap } from "../../project/bootstrap" +import { Offline } from "@/config/offline" import { upgrade } from "../upgrade" import { Log } from "../../util/log" @@ -63,6 +64,7 @@ export async function runStartupUpgradeCheck(deps: StartupUpgradeDeps = defaultD /** Schedules {@link runStartupUpgradeCheck} after a short settle delay; non-blocking. */ export function scheduleStartupUpgradeCheck(): void { + if (Offline.enabled()) return // Jitter the delay so a fleet of servers restarting in the same window (rolling // deploy, node drain, mass IDE update) doesn't stampede the unauthenticated // GitHub releases API (60 req/hr/IP) in the same instant. Spreads checks over diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index c1f25a6219..02999a5110 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -1,4 +1,5 @@ // altimate_change start — top-level `skill` command for managing skills and user tools +import { Offline } from "@/config/offline" import { EOL } from "os" import path from "path" import fs from "fs/promises" @@ -657,6 +658,9 @@ const SkillInstallCommand = cmd({ }), async handler(args) { let source = (args.source as string).trim().replace(/\.git$/, "") + // Offline mode: a URL or owner/repo shorthand is fetched from GitHub. A local directory such as ./owner/repo is fine. + if (Offline.enabled() && (/^https?:\/\//.test(source) || /^[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/.test(source))) + throw new Error("Install remote skills while online, or install a local skill directory.") const isGlobal = args.global as boolean if (!source) { diff --git a/packages/opencode/src/cli/network.ts b/packages/opencode/src/cli/network.ts index 3be88fe037..3960b7116d 100644 --- a/packages/opencode/src/cli/network.ts +++ b/packages/opencode/src/cli/network.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode skips multicast discovery +import { Offline } from "@/config/offline" +// altimate_change end import type { Argv, InferredOptionTypes } from "yargs" import { ConfigV1 } from "@opencode-ai/core/v1/config/config" import type { Config } from "@/config/config" @@ -52,7 +55,11 @@ export function resolveNetworkOptionsNoConfig(args: NetworkOptions, config?: Con const hostnameExplicitlySet = process.argv.includes("--hostname") const mdnsExplicitlySet = process.argv.includes("--mdns") const mdnsDomainExplicitlySet = process.argv.includes("--mdns-domain") - const mdns = mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns) + // altimate_change start — offline mode skips multicast discovery + const wantsMdns = mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns) + if (wantsMdns && Offline.enabled()) process.stderr.write("mDNS discovery skipped in offline mode.\n") + const mdns = wantsMdns && !Offline.enabled() + // altimate_change end const mdnsDomain = mdnsDomainExplicitlySet ? args["mdns-domain"] : (config?.server?.mdnsDomain ?? args["mdns-domain"]) const port = portExplicitlySet ? args.port : (config?.server?.port ?? args.port) const hostname = hostnameExplicitlySet diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index f0d8daa516..99545e7c43 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -4,6 +4,9 @@ // rationale (this is the systemic fix for the log-flood class that regresses on every upstream merge). import "./worker-console-guard" // altimate_change end +// altimate_change start — install inherited offline policy before the worker builds its runtime +import { Offline } from "@/config/offline" +// altimate_change end import { Server } from "@/server/server" import { InstanceRuntime } from "@/project/instance-runtime" import { Rpc } from "@/util/rpc" @@ -42,6 +45,8 @@ import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding" // (NOT here: at module top level Config.get() throws and doInit() proceeds as enabled, which // silently bypassed a `telemetry.disabled` config opt-out for the whole first session). Telemetry.startLoopMonitor() +// The worker inherits offline mode from its parent; install the fetch guard here too. +if (Offline.enabled()) Offline.start() // altimate_change end // altimate_change start — heal the datamate MCP entry at boot. `altimate serve` runs // this sync before listening (cli/cmd/serve.ts), but the TUI worker never did, so an diff --git a/packages/opencode/src/cli/upgrade.ts b/packages/opencode/src/cli/upgrade.ts index 81bfdb0e7f..da0c9afa37 100644 --- a/packages/opencode/src/cli/upgrade.ts +++ b/packages/opencode/src/cli/upgrade.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import { Config } from "@/config/config" import { AppRuntime } from "@/effect/app-runtime" import { Flag } from "@opencode-ai/core/flag/flag" @@ -96,6 +99,9 @@ export function isAutoupdateDisabledByEnv() { // altimate_change end export async function upgrade() { + // altimate_change start — skip automatic update checks in offline mode + if (Offline.enabled()) return + // altimate_change end // altimate_change start — skip the upgrade check for local / branch / dev builds. // These are never published to npm or GitHub releases, so the version lookup // 404s and spams the TUI bottom bar (e.g. a build off branch diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 345a4c2e87..6494016e3b 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/layer-node-platform" import { serviceUse } from "@opencode-ai/core/effect/service-use" @@ -51,6 +54,14 @@ import { withTransientReadRetry } from "@/util/effect-http-client" import { makeRuntime } from "@/effect/run-service" // altimate_change end +// altimate_change start — offline mode must be active before config loading +function requireOfflineStartup(offline: boolean | undefined) { + if (offline === true && !Offline.enabled()) { + throw new Error("Configuration requests offline mode. Restart Altimate Code with ALTIMATE_OFFLINE=1.") + } +} +// altimate_change end + // altimate_change start — bootstrap can inspect config already loaded by service initialization // without introducing another asynchronous dependency for opted-out learning capture. const loadedConfig = new Map() @@ -562,6 +573,9 @@ export const layer = Layer.effect( if (value.type === "wellknown") { const url = key.replace(/\/+$/, "") authEnv[value.key] = value.token + // altimate_change start — keep the local token available without fetching remote config + if (Offline.enabled()) continue + // altimate_change end const wellknownURL = `${url}/.well-known/opencode` yield* Effect.logDebug("fetching remote config", { url: wellknownURL }) const wellknown = yield* fetchRemoteJson(wellknownURL, undefined, ConfigV1.WellKnown, url) @@ -683,6 +697,8 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } + // altimate_change — refuse offline config missed by the startup probe + requireOfflineStartup(result.offline) const activeAccount = Option.getOrUndefined( yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none()))), ) @@ -691,6 +707,9 @@ export const layer = Layer.effect( const orgID = activeAccount.active_org_id const url = activeAccount.url yield* Effect.gen(function* () { + // altimate_change start — skip the remote account config and token lookup offline + if (Offline.enabled()) return + // altimate_change end const [configOpt, tokenOpt] = yield* Effect.all( [accountSvc.config(accountID, orgID), accountSvc.token(accountID)], { concurrency: 2 }, @@ -771,9 +790,10 @@ export const layer = Layer.effect( // altimate_change start — upstream_fix: decide installs only after every config source has // merged. Inline, account, managed, and later-directory configs can declare a file plugin // under any earlier directory. Keep the PURE skip and retain fibers for waitForDependencies. + requireOfflineStartup(result.offline) const deps: Fiber.Fiber[] = [] for (const dir of directories) { - if (ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { + if (!Offline.enabled() && ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { const dep = yield* npmSvc .install(dir, { add: [ @@ -835,6 +855,12 @@ export const layer = Layer.effect( } } + // altimate_change start — disable runtime sharing in offline mode + if (Offline.enabled()) { + result.offline = true + result.share = "disabled" + } + // altimate_change end if (result.autoshare === true && !result.share) { result.share = "auto" } @@ -885,7 +911,7 @@ export const layer = Layer.effect( // workspace's pinned local engine — derived here, after discovery, so it has // the last word over IDE-written, hosted and stale entries, and never written // to any file. See altimate/workspace/engine-overlay.ts. - if (!Flag.ALTIMATE_DISABLE_WORKSPACE) { + if (!Offline.enabled() && !Flag.ALTIMATE_DISABLE_WORKSPACE) { const { overlay } = yield* Effect.promise(() => import("../altimate/workspace/engine-overlay")) yield* Effect.promise(() => overlay(ctx.directory, result as { mcp?: Record }, { managed: managedOwnsDatamate }), diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts new file mode 100644 index 0000000000..18efecd4f0 --- /dev/null +++ b/packages/opencode/src/config/offline.ts @@ -0,0 +1,190 @@ +// altimate_change - new file +// +// Offline mode: Altimate Code sends network requests only to the configured model endpoint. +// It is on when ALTIMATE_OFFLINE is set or a config file has `"offline": true`. Startup requests (the model +// catalog, workspace and registration checks) run before the configuration loads, so the CLI checks config files +// for the setting first (`optedIn`). Without either, `start()` never runs and nothing changes. +export * as Offline from "./offline" + +import fs from "node:fs/promises" +import { isIP } from "node:net" +import path from "node:path" +import { Effect } from "effect" +import { Flag, env, offlineModeEnabled as enabled } from "@opencode-ai/core/flag/flag" +import { FSUtil } from "@opencode-ai/core/fs-util" +import type { ConfigV1 } from "@opencode-ai/core/v1/config/config" +import { Global } from "@/global" +import { ConfigManaged } from "./managed" +import { ConfigPaths } from "./paths" + +export { enabled } + +const CONFIG_NAMES = ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"] + +/** + * Whether a config file the instance will load sets `"offline": true`. Only text that mentions the key, or could + * produce it by substitution, is parsed. Config loaded only after this probe cannot activate offline mode. + */ +export async function optedIn(directory: string): Promise { + if (process.argv.includes("--get-yargs-completions")) return false + // Let the instance report config errors and reject any offline opt-in missed here. + return findOptIn(directory).catch(() => false) +} + +async function findOptIn(directory: string): Promise { + const sets = async (text: string | undefined, source: string | { source: string; dir: string }) => { + // A JSON escape (off\u006cine) or a substitution can produce the key without spelling it. + if (!text || (!text.includes("offline") && !/\{env:|\$\{|\{file:|\\u/.test(text))) return false + const config = await ConfigPaths.parseText(text, source, "empty", { track: false }).catch(() => undefined) + return config?.offline === true + } + if (await sets(env("OPENCODE_CONFIG_CONTENT"), { source: "OPENCODE_CONFIG_CONTENT", dir: directory })) return true + // Project config stops at the repository root, as the instance's does. + let worktree = path.resolve(directory) + while (!(await fs.stat(path.join(worktree, ".git")).catch(() => undefined))) { + const parent = path.dirname(worktree) + if (parent === worktree) break + worktree = parent + } + const [projectFiles, dirs] = await Effect.runPromise( + Effect.all([ + Flag.OPENCODE_DISABLE_PROJECT_CONFIG + ? Effect.succeed([] as string[]) + : Effect.all([ + ConfigPaths.files("opencode", directory, worktree), + ConfigPaths.files("altimate-code", directory, worktree), + ]).pipe(Effect.map((found) => found.flat())), + ConfigPaths.directories(directory, worktree), + ]).pipe(Effect.provide(FSUtil.defaultLayer)), + ) + const files = [ + ...projectFiles, + ...dirs.flatMap((dir) => CONFIG_NAMES.map((name) => path.join(dir, name))), + path.join(Global.Path.config, "config.json"), + Flag.OPENCODE_CONFIG, + ...CONFIG_NAMES.map((name) => path.join(ConfigManaged.managedConfigDir(), name)), + ] + for (const file of files) { + if (file && (await sets(await fs.readFile(file, "utf8").catch(() => undefined), file))) return true + } + return false +} + +/** Hosts the fetch guard accepts as this machine. Bun matches only these exact names in NO_PROXY. */ +const LOCAL_FETCH_HOSTS = ["localhost", "127.0.0.1", "[::1]", "0.0.0.0"] +const MAX_LOCAL_REDIRECTS = 5 + +let networkFetch: typeof fetch | undefined + +/** + * Turn offline mode on for the rest of this process and the workers and programs it starts. + * Installs a fetch guard that allows only loopback requests; model requests use `modelFetch`. + */ +export function start() { + // Workers and child processes inherit the switch. Shell commands see it too, so a nested + // altimate-code is offline as well. + process.env.ALTIMATE_OFFLINE = "1" + if (networkFetch) return + // Bun sends even loopback requests through HTTP(S)_PROXY. Exclude only the loopback hosts so a + // local request cannot leave the machine through a proxy; model requests still use the proxy. + // Both spellings get the same list, so programs that read either one keep the user's own exclusions. + const lists = [process.env.NO_PROXY, process.env.no_proxy] + if (lists.includes("*")) { + process.env.NO_PROXY = process.env.no_proxy = "*" + } else { + const entries = [...new Set(lists.flatMap((list) => (list ?? "").split(",").map((entry) => entry.trim()).filter(Boolean)))] + process.env.NO_PROXY = process.env.no_proxy = [...entries, ...LOCAL_FETCH_HOSTS.filter((host) => !entries.includes(host))].join(",") + } + networkFetch = globalThis.fetch + globalThis.fetch = Object.assign( + async (input: Parameters[0], init?: Parameters[1]) => { + let url = input instanceof Request ? input.url : input.toString() + if (!isLocalURL(url)) throw new Error("Offline mode allows network requests only to the configured model endpoint.") + const wanted = init?.redirect ?? (input instanceof Request ? input.redirect : "follow") + // A Request carries its own method and body, and a caller may ask not to follow: never follow for them. + if (wanted !== "follow" || input instanceof Request) + return networkFetch!(input, { ...init, redirect: wanted === "manual" ? "manual" : "error" }) + // Otherwise follow redirects only while they stay on this machine, as fetch would. + let request: RequestInit = { ...init, redirect: "manual" } + let response = await networkFetch!(input, request) + for (let hop = 0; [301, 302, 303, 307, 308].includes(response.status); hop++) { + const location = response.headers.get("location") + if (!location) return response + if (hop === MAX_LOCAL_REDIRECTS) throw new Error("Offline mode stopped after too many local redirects.") + const next = new URL(location, url) + if (!isLocalURL(next)) throw new Error("Offline mode blocked a redirect away from this machine.") + // Like fetch, do not send credentials on to a different origin. + if (next.origin !== new URL(url).origin) { + const headers = new Headers(request.headers) + for (const name of ["authorization", "cookie", "proxy-authorization"]) headers.delete(name) + request = { ...request, headers } + } + url = next.href + const method = (request.method ?? "GET").toUpperCase() + if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === "POST")) { + const headers = new Headers(request.headers) + for (const name of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) headers.delete(name) + request = { ...request, method: method === "HEAD" ? "HEAD" : "GET", body: undefined, headers } + } + response = await networkFetch!(url, request) + } + return response + }, + { preconnect: () => {} }, + ) +} + +type ModelConfig = Pick + +/** The provider's explicitly configured base URL: the only model endpoint offline mode uses. */ +export function endpoint(config: ModelConfig, providerID: string) { + if (config.enabled_providers && !config.enabled_providers.includes(providerID)) return undefined + if (config.disabled_providers?.includes(providerID)) return undefined + const url = config.provider?.[providerID]?.options?.baseURL + return typeof url === "string" && url.trim() ? url : undefined +} + +const httpSDKs = new Set(["@ai-sdk/openai-compatible", "@ai-sdk/openai", "@ai-sdk/anthropic"]) + +export function supportsSDK(npm: string) { + return httpSDKs.has(npm) +} + +/** Fetch for model requests: only below the configured base URL, never redirected, through the user's proxy. */ +export function modelFetch(baseURL: string | undefined): typeof fetch { + if (!baseURL) throw new Error("Offline mode requires a model provider with an explicit baseURL.") + const base = new URL(baseURL) + if (!["http:", "https:"].includes(base.protocol)) throw new Error("Offline mode requires an HTTP(S) model endpoint.") + const basePath = base.pathname.replace(/\/+$/, "") + return Object.assign( + async (input: Parameters[0], init?: Parameters[1]) => { + const target = new URL(input instanceof Request ? input.url : input.toString()) + if (target.origin !== base.origin || (target.pathname !== basePath && !target.pathname.startsWith(basePath + "/"))) + throw new Error("Offline mode blocked a request outside the configured model endpoint.") + return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error" }) + }, + { preconnect: () => {} }, + ) +} + +/** Literal loopback addresses only: no DNS lookups or hostname suffix matching. */ +export function isLoopbackHost(value: unknown): boolean { + if (typeof value !== "string") return false + const host = value.toLowerCase().replace(/^\[|\]$/g, "") + return host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")) +} + +/** An HTTP(S) URL the fetch guard sends directly to this machine. */ +export function isLocalURL(value: string | URL) { + try { + const url = new URL(value) + return ["http:", "https:"].includes(url.protocol) && LOCAL_FETCH_HOSTS.includes(url.hostname.toLowerCase()) + } catch { + return false + } +} + +export function assertLocalMcp(config: { type: string; url?: string }) { + if (enabled() && config.type === "remote" && !isLocalURL(config.url ?? "")) + throw new Error("Offline mode allows only stdio MCP servers or ones on this machine (localhost, 127.0.0.1, [::1] or 0.0.0.0).") +} diff --git a/packages/opencode/src/config/tui.ts b/packages/opencode/src/config/tui.ts index f8319951b9..26d728e3ce 100644 --- a/packages/opencode/src/config/tui.ts +++ b/packages/opencode/src/config/tui.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end export * as TuiConfig from "./tui" import path from "path" @@ -275,7 +278,7 @@ export const layer = Layer.effect( const deps = yield* Effect.forEach( // altimate_change start — upstream_fix: same lazy gate as Config; the unconditional in-process // arborist install froze fresh installs for minutes (see ConfigPlugin.needsDependencies). - data.dirs.filter((dir) => ConfigPlugin.shouldInstallDependencies(dir, data.config.plugin)), + data.dirs.filter((dir) => !Offline.enabled() && ConfigPlugin.shouldInstallDependencies(dir, data.config.plugin)), // altimate_change end (dir) => npm diff --git a/packages/opencode/src/effect/runtime-flags.ts b/packages/opencode/src/effect/runtime-flags.ts index 1d8d753df9..208c77daa6 100644 --- a/packages/opencode/src/effect/runtime-flags.ts +++ b/packages/opencode/src/effect/runtime-flags.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode prevents automatic LSP downloads +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end import { Config, ConfigProvider, Context, Effect, Layer, Option } from "effect" import { ConfigService } from "@/effect/config-service" @@ -25,7 +28,8 @@ export class Service extends ConfigService.Service()("@opencode/Runtime direct: bool("OPENCODE_DISABLE_EXTERNAL_SKILLS"), }).pipe(Config.map((flags) => flags.broad || flags.claudeCodeSkills || flags.direct)), // altimate_change end - disableLspDownload: bool("OPENCODE_DISABLE_LSP_DOWNLOAD"), + // altimate_change — apply to both Effect and legacy language server services + disableLspDownload: bool("OPENCODE_DISABLE_LSP_DOWNLOAD").pipe(Config.map((disabled) => disabled || offlineModeEnabled())), disableClaudeCodePrompt: Config.all({ broad: bool("OPENCODE_DISABLE_CLAUDE_CODE"), direct: bool("OPENCODE_DISABLE_CLAUDE_CODE_PROMPT"), diff --git a/packages/opencode/src/file/ripgrep.ts b/packages/opencode/src/file/ripgrep.ts index d2356219d6..2d161b2776 100644 --- a/packages/opencode/src/file/ripgrep.ts +++ b/packages/opencode/src/file/ripgrep.ts @@ -1,3 +1,6 @@ +// altimate_change start — prevent ripgrep downloads in offline mode +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end // altimate_change start — restore the fork's async-generator Ripgrep namespace // (files/tree/search/Match/filepath). Upstream v1.17.9 moved ripgrep to an // Effect Service (find/glob/grep) in @opencode-ai/core/ripgrep, but our tools @@ -96,6 +99,7 @@ export namespace Ripgrep { const filepath = path.join(Global.Path.bin, "rg" + (process.platform === "win32" ? ".exe" : "")) if (!(await Filesystem.exists(filepath))) { + if (offlineModeEnabled()) throw new Error("Install ripgrep while online to use file search in offline mode.") const platformKey = `${process.arch}-${process.platform}` as keyof typeof PLATFORM const config = PLATFORM[platformKey] if (!config) throw new UnsupportedPlatformError({ platform: platformKey }) diff --git a/packages/opencode/src/git/index.ts b/packages/opencode/src/git/index.ts index dda3a3bec1..9e52cf2ade 100644 --- a/packages/opencode/src/git/index.ts +++ b/packages/opencode/src/git/index.ts @@ -1,3 +1,7 @@ +// altimate_change start — offline mode refuses Git commands that use the network +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +import { GIT_OFFLINE_REFUSAL, gitCommandUsesNetwork } from "@opencode-ai/core/git" +// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { AppProcess } from "@opencode-ai/core/process" import { Effect, Layer, Context, Stream } from "effect" @@ -109,6 +113,9 @@ export const layer = Layer.effect( const run = Effect.fn("Git.run")( function* (args: string[], opts: Options) { + // altimate_change start — offline mode refuses Git commands that use the network + if (offlineModeEnabled() && gitCommandUsesNetwork(args)) return fail(new Error(GIT_OFFLINE_REFUSAL)) + // altimate_change end const result = yield* appProcess.run( ChildProcess.make("git", [...cfg, ...args], { cwd: opts.cwd, diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index f2a0152b03..5f7908a0da 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import yargs from "yargs" import { hideBin } from "yargs/helpers" // altimate_change start - stdin tool arguments @@ -169,6 +172,28 @@ let cli = yargs(args) if (opts._[0] === "mcp" && opts._[1] === "serve") return // altimate_change end + // altimate_change start — offline mode: install the fetch guard and refuse commands that need a remote service + const command = String(opts._[0] ?? "") + // `attach --dir` and `run --attach --dir` name a directory on the server, so they read the invoking project's setting. + const offlineTarget = command === "attach" || (command === "run" && opts.attach) ? undefined : (opts.dir ?? opts.cwd ?? opts.directory) + const offlineDir = typeof offlineTarget === "string" ? path.resolve(offlineTarget) : resolveThreadDirectory(opts.project as string | undefined) + if (Offline.enabled() || (await Offline.optedIn(offlineDir))) { + Offline.start() + const sub = String(opts._[1] ?? "") + const attach = command === "attach" ? opts.url : command === "run" ? opts.attach : undefined + if ( + ["github", "gitlab", "pr", "link", "workspace-client", "web", "integrations", "upgrade"].includes(command) || + (command === "review" && opts.post === true) || + (command === "learn" && sub === "import-reviews") || + (command === "console" && sub === "open") || + (["providers", "auth", "console"].includes(command) && sub === "login") || + (command === "mcp" && sub === "auth") || + (typeof attach === "string" && attach !== "" && !Offline.isLocalURL(attach)) + ) + throw new Error("This command requires network access. Run it while online.") + } + // altimate_change end + Heap.start() process.env.AGENT = "1" diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index af8bd64bd7..69337d7560 100644 --- a/packages/opencode/src/installation/index.ts +++ b/packages/opencode/src/installation/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/layer-node-platform" import { Effect, Layer, Schema, Context, Stream } from "effect" @@ -840,6 +843,9 @@ export const layer: Layer.Layer @@ -156,7 +158,8 @@ export const Vue: Info = { let binary = which("vue-language-server") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("@vue/language-server") if (!resolved) return binary = resolved @@ -497,7 +500,8 @@ export const Pyright: Info = { let binary = which("pyright-langserver") const args = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("pyright", "pyright-langserver") if (!resolved) return binary = resolved @@ -1081,7 +1085,8 @@ export const Svelte: Info = { let binary = which("svelteserver") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("svelte-language-server") if (!resolved) return binary = resolved @@ -1114,7 +1119,8 @@ export const Astro: Info = { let binary = which("astro-ls") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("@astrojs/language-server") if (!resolved) return binary = resolved @@ -1373,7 +1379,8 @@ export const YamlLS: Info = { let binary = which("yaml-language-server") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("yaml-language-server") if (!resolved) return binary = resolved @@ -1527,7 +1534,8 @@ export const PHPIntelephense: Info = { let binary = which("intelephense") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("intelephense") if (!resolved) return binary = resolved @@ -1608,7 +1616,8 @@ export const BashLS: Info = { let binary = which("bash-language-server") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("bash-language-server") if (!resolved) return binary = resolved @@ -1786,7 +1795,8 @@ export const DockerfileLS: Info = { let binary = which("docker-langserver") const args: string[] = [] if (!binary) { - if (flags.disableLspDownload) return + // altimate_change — the offline Npm service only reads the installed cache + if (flags.disableLspDownload && !offlineModeEnabled()) return const resolved = await Npm.which("dockerfile-language-server-nodejs") if (!resolved) return binary = resolved diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index da8e75a1ce..e9711ac138 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import path from "node:path" import { pathToFileURL } from "node:url" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -420,6 +423,15 @@ export const layer = Layer.effect( key: string, mcp: ConfigMCPV1.Info & { type: "remote" }, ) { + // altimate_change start — offline mode refuses remote MCP servers + if (Offline.enabled() && !Offline.isLocalURL(mcp.url)) { + return { + client: undefined as MCPClient | undefined, + status: { status: "failed" as const, error: "Offline mode allows only stdio MCP servers or ones on this machine (localhost, 127.0.0.1, [::1] or 0.0.0.0)." }, + transport: undefined as TransportLabel | undefined, + } + } + // altimate_change end const url = remoteURL(mcp.url) if (!url) { return { @@ -1375,6 +1387,7 @@ export const layer = Layer.effect( }) const beginAuth = Effect.fn("MCP.beginAuth")(function* (mcpName: string, token: number) { + if (Offline.enabled()) throw new Error("Authenticate MCP servers while online.") const lifecycle = yield* InstanceState.get(state) // altimate_change end const mcpConfig = yield* requireMcpConfig(mcpName) diff --git a/packages/opencode/src/plugin/index.ts b/packages/opencode/src/plugin/index.ts index 7bd2e7d5c8..2cfe1e6d53 100644 --- a/packages/opencode/src/plugin/index.ts +++ b/packages/opencode/src/plugin/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import type { Hooks, PluginInput, Plugin as PluginInstance } from "@opencode-ai/plugin" import { Config } from "../config/config" import { Bus } from "../bus" @@ -111,7 +114,10 @@ export namespace Plugin { $: Bun.$, } - for (const plugin of INTERNAL_PLUGINS) { + // altimate_change start — skip built-in authentication and telemetry plugins offline + const internal = Offline.enabled() ? [] : INTERNAL_PLUGINS + // altimate_change end + for (const plugin of internal) { log.info("loading internal plugin", { name: plugin.name }) const init = await plugin(input).catch((err) => { log.error("failed to load internal plugin", { name: plugin.name, error: err }) diff --git a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx index d5b52efdc9..b4cfe7059a 100644 --- a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx +++ b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx @@ -33,6 +33,7 @@ import { Flag } from "@opencode-ai/core/flag/flag" import { spawn } from "child_process" import os from "os" import path from "path" +import { Offline } from "@/config/offline" import fs from "fs/promises" const id = "altimate:skill-ops" @@ -191,6 +192,7 @@ async function installSkillDirect( // reach the installer without going through the UI's install-preview. const kind = classifyInstallSource(normalized) if (kind === "github-url" || kind === "owner-repo") { + if (Offline.enabled()) return { ok: false, message: "Install remote skills while online, or install a local skill directory." } // Branch on the already-computed `kind`, not on a `startsWith("http")` probe of the // normalized string. Two bugs are avoided that way: // 1. An owner whose name literally starts with `http` (e.g. `httpie/httpie`, diff --git a/packages/opencode/src/provider/models.ts b/packages/opencode/src/provider/models.ts index 99aec59b3e..672b52eb46 100644 --- a/packages/opencode/src/provider/models.ts +++ b/packages/opencode/src/provider/models.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import { Global } from "../global" import { Log } from "../util/log" import path from "path" @@ -126,7 +129,9 @@ export namespace ModelsDev { .then((m) => m.snapshot as Record) .catch(() => undefined) if (snapshot) return snapshot - if (Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} + // altimate_change start — use only the local model catalog in offline mode + if (Offline.enabled() || Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} + // altimate_change end return Flock.withLock(`models-dev:${filepath}`, async () => { const cachedUnderLock: unknown = await Filesystem.readJson(Flag.OPENCODE_MODELS_PATH ?? filepath).catch(() => {}) if (isCatalog(cachedUnderLock)) return cachedUnderLock @@ -164,6 +169,9 @@ export namespace ModelsDev { } export async function refresh(force = false) { + // altimate_change start — skip explicit model catalog refresh in offline mode + if (Offline.enabled()) return + // altimate_change end if (skip(force)) return ModelsDev.Data.reset() await Flock.withLock(`models-dev:${filepath}`, async () => { if (skip(force)) return ModelsDev.Data.reset() diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index f9c3a72ebf..fa54fb0643 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import z from "zod" import { Schema } from "effect" // altimate_change start — Effect Context.Service facade deps (added to existing namespace) @@ -632,6 +635,8 @@ export namespace Provider { return { autoload: false, async getModel(sdk: any, modelID: string, _options?: Record) { + // altimate_change — provider IDs can use a compatible SDK with no Responses API + if (Offline.enabled() && typeof sdk.responses !== "function") return sdk.languageModel(modelID) return sdk.responses(modelID) }, // altimate_change start — OpenAI API auth gets the v1.17.9 header-timeout default @@ -1393,6 +1398,15 @@ export namespace Provider { const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null function isProviderAllowed(providerID: ProviderID): boolean { + // altimate_change start — require a locally configured model endpoint in offline mode + if (Offline.enabled()) { + if ( + !Offline.endpoint(config, providerID) || + providerID === FreeTier.PROVIDER_ID || + providerID === ClaudeAgent.ID + ) return false + } + // altimate_change end if (enabled && !enabled.has(providerID)) return false if (disabled.has(providerID)) return false return true @@ -2004,12 +2018,19 @@ export namespace Provider { if (!isProviderAllowed(providerID)) continue // altimate_change end const data = database[providerID] + // altimate_change start — skip provider discovery and OAuth-backed loaders in offline mode + const permittedOfflineLoader = Offline.enabled() && (id === "openai" || id === "anthropic") && + Boolean(Offline.endpoint(config, providerID)) + if (Offline.enabled() && !permittedOfflineLoader) continue + // altimate_change end if (!data) { log.error("Provider does not exist in model list " + providerID) continue } const result = await fn(data) - if (result && (result.autoload || providers[providerID])) { + // altimate_change start — offline keeps the endpoint-bound loader + if (result && (result.autoload || providers[providerID] || permittedOfflineLoader)) { + // altimate_change end if (result.getModel) modelLoaders[providerID] = result.getModel if (result.vars) varsLoaders[providerID] = result.vars const opts = result.options ?? {} @@ -2114,9 +2135,18 @@ export namespace Provider { options["includeUsage"] = true } + // altimate_change start — use the explicit local endpoint without any catalog fallback + const offlineMode = Offline.enabled() + const localBaseURL = offlineMode ? Offline.endpoint(await Config.get(), model.providerID) : undefined + if (offlineMode && !localBaseURL) + throw new Error("Offline mode requires a locally configured model endpoint.") + // altimate_change end + const baseURL = iife(() => { - let url = - typeof options["baseURL"] === "string" && options["baseURL"] !== "" ? options["baseURL"] : model.api.url + // altimate_change start — keep the model request on its explicitly configured offline endpoint + let url = localBaseURL ?? + (typeof options["baseURL"] === "string" && options["baseURL"] !== "" ? options["baseURL"] : model.api.url) + // altimate_change end if (!url) return // some models/providers have variable urls, ex: "https://${AZURE_RESOURCE_NAME}.services.ai.azure.com/anthropic/v1" @@ -2146,11 +2176,17 @@ export namespace Provider { } // altimate_change end - const key = Hash.fast(JSON.stringify({ providerID: model.providerID, npm: model.api.npm, options })) + // altimate_change start — constrain offline model transport to its configured origin + if (offlineMode && !Offline.supportsSDK(model.api.npm)) + throw new Error("Offline mode requires a bundled HTTP model provider such as @ai-sdk/openai-compatible.") + const key = Hash.fast(JSON.stringify({ providerID: model.providerID, npm: model.api.npm, options, offlineMode })) + // altimate_change end const existing = s.sdk.get(key) if (existing) return existing - const customFetch = options["fetch"] + // altimate_change start — constrain offline model transport to its configured origin + const customFetch = offlineMode ? Offline.modelFetch(baseURL) : options["fetch"] + // altimate_change end // altimate_change start — environment override controls the single stream watchdog (0 disables) // Precedence: valid ALTIMATE_STREAM_IDLE_TIMEOUT_MS (0 disables), provider chunkTimeout, then 300000ms. const idleOverride = Env.get("ALTIMATE_STREAM_IDLE_TIMEOUT_MS")?.trim() @@ -2397,6 +2433,14 @@ export namespace Provider { export async function getSmallModel(providerID: ProviderID) { const cfg = await Config.get() + // altimate_change start — offline: only a small model on the configured endpoint; otherwise the caller's model + if (Offline.enabled()) { + if (!cfg.small_model) return undefined + const parsed = parseModel(cfg.small_model) + return Offline.endpoint(cfg, parsed.providerID) ? getModel(parsed.providerID, parsed.modelID) : undefined + } + // altimate_change end + if (cfg.small_model) { const parsed = parseModel(cfg.small_model) return getModel(parsed.providerID, parsed.modelID) diff --git a/packages/opencode/src/session/instruction.ts b/packages/opencode/src/session/instruction.ts index acf807d2d5..66958fdbe0 100644 --- a/packages/opencode/src/session/instruction.ts +++ b/packages/opencode/src/session/instruction.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end // altimate_change start — makeRuntime for the restored Promise-based InstructionPrompt facade (bottom of file) import { makeRuntime } from "@/effect/run-service" // altimate_change end @@ -98,6 +101,9 @@ export const layer: Layer.Layer< }) const fetch = Effect.fnUntraced(function* (url: string) { + // altimate_change start — skip network work in offline mode + if (Offline.enabled()) return "" + // altimate_change end const res = yield* http.execute(HttpClientRequest.get(url)).pipe( Effect.timeout(5000), Effect.catch(() => Effect.succeed(null)), diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 93187d0201..910efb008e 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import path from "path" import { Token } from "@/util/token" import { existsSync, readFileSync, statSync } from "node:fs" @@ -475,6 +478,12 @@ export namespace SessionPrompt { // snapshot is actually there keeps the tick off the path that regressed — // a user who never used workspaces has no directory, so this costs one `stat` and // does not even load the sync module. + // altimate_change start — offline mode uses the cached workspace skill snapshot as it is, without syncing + if (Offline.enabled()) { + const dir = Instance.directory + if (existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) await refreshSkillRegistry(dir) + } else + // altimate_change end if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { const dir = Instance.directory // Mirrors `MANAGED_DIR` in ./altimate/workspace/skill-sync. Inlined diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 65d75e9c05..a0793557f4 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import { Bus } from "@/bus" import { Account } from "@/account" import { Config } from "@/config/config" @@ -75,7 +78,9 @@ export namespace ShareNext { const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1" export async function init() { - if (disabled) return + // altimate_change start — offline mode does not sync shared sessions + if (Offline.enabled() || disabled) return + // altimate_change end Bus.subscribe(Session.Event.Updated, async (evt) => { await sync(evt.properties.info.id, [ { @@ -204,7 +209,9 @@ export namespace ShareNext { const queue = new Map }>() async function sync(sessionID: SessionID, data: Data[]) { - if (disabled) return + // altimate_change start — offline mode does not sync shared sessions + if (Offline.enabled() || disabled) return + // altimate_change end const existing = queue.get(sessionID) if (existing) { for (const item of data) { diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 06af06b5c9..ec0fc54f17 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end import { PlanExitTool } from "./plan" import { QuestionTool } from "./question" import { BashTool } from "./bash" @@ -428,6 +431,8 @@ export namespace ToolRegistry { // altimate_change start — v1.17.9: Tool.define returns an Effect; resolve the // built-in tool-definition effects against the AppRuntime layers (Truncate/Agent) before use. + // Offline sessions drop only the tools that contact remote services. + const offline = Offline.enabled() const builtins = [ InvalidTool, ...(question ? [QuestionTool] : []), @@ -438,11 +443,11 @@ export namespace ToolRegistry { EditTool, WriteTool, TaskTool, - WebFetchTool, + // These tools contact remote services; order unchanged with offline mode off. + ...(!offline ? [WebFetchTool] : []), TodoWriteTool, // TodoReadTool, - WebSearchTool, - CodeSearchTool, + ...(!offline ? [WebSearchTool, CodeSearchTool] : []), SkillTool, ApplyPatchTool, ...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [LspTool] : []), @@ -528,8 +533,8 @@ export namespace ToolRegistry { AltimateCoreParseDbtTool, ToolLookupTool, ProjectScanTool, - DatamateManagerTool, - FeedbackSubmitTool, + ...(!offline ? [DatamateManagerTool] : []), + ...(!offline ? [FeedbackSubmitTool] : []), SampleSetupTool, // altimate_change end // altimate_change start - register altimate persistent memory tools @@ -539,7 +544,7 @@ export namespace ToolRegistry { // Workspace-only: `refresh` no-ops with workspaces disabled, so // shipping its description then costs a tool slot and // invites a wasted call that can only answer "not enabled". - ...(CoreFlag.ALTIMATE_DISABLE_WORKSPACE ? [] : [MemoryRefreshTool]), + ...(offline || CoreFlag.ALTIMATE_DISABLE_WORKSPACE ? [] : [MemoryRefreshTool]), MemoryWriteTool, MemoryDeleteTool, MemoryAuditTool, diff --git a/packages/opencode/src/util/git.ts b/packages/opencode/src/util/git.ts index 731131357f..37defc18ba 100644 --- a/packages/opencode/src/util/git.ts +++ b/packages/opencode/src/util/git.ts @@ -1,4 +1,8 @@ import { Process } from "./process" +// altimate_change start — offline mode refuses Git commands that use the network +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +import { GIT_OFFLINE_REFUSAL, gitCommandUsesNetwork } from "@opencode-ai/core/git" +// altimate_change end export interface GitResult { exitCode: number @@ -14,6 +18,10 @@ export interface GitResult { * issues in embedded/client environments. */ export async function git(args: string[], opts: { cwd: string; env?: Record }): Promise { + // altimate_change start — offline mode refuses Git commands that use the network + if (offlineModeEnabled() && gitCommandUsesNetwork(args)) + return { exitCode: 1, text: () => "", stdout: Buffer.alloc(0), stderr: Buffer.from(GIT_OFFLINE_REFUSAL) } + // altimate_change end return Process.run(["git", ...args], { cwd: opts.cwd, env: opts.env, diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 70882ee814..3f38e0c1a5 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode resets from local Git objects +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { path } from "@opencode-ai/core/effect/layer-node-platform" import { Global } from "@opencode-ai/core/global" @@ -173,7 +176,13 @@ export const layer: Layer.Layer< const git = Effect.fnUntraced( function* (args: string[], opts?: { cwd?: string }) { const result = yield* appProcess.run( - ChildProcess.make("git", args, { cwd: opts?.cwd, extendEnv: true, stdin: "ignore" }), + // altimate_change — offline mode keeps Git LFS from downloading objects during checkout and reset + ChildProcess.make("git", args, { + cwd: opts?.cwd, + ...(offlineModeEnabled() ? { env: { GIT_LFS_SKIP_SMUDGE: "1" } } : {}), + extendEnv: true, + stdin: "ignore", + }), ) return { code: result.exitCode, @@ -573,7 +582,8 @@ export const layer: Layer.Layer< } const sep = base.ref.indexOf("/") - if (base.ref !== base.name && sep > 0) { + // altimate_change — offline mode resets to the locally cached base ref + if (!offlineModeEnabled() && base.ref !== base.name && sep > 0) { const remote = base.ref.slice(0, sep) const branch = base.ref.slice(sep + 1) yield* gitExpect( @@ -596,11 +606,29 @@ export const layer: Layer.Layer< }) } - yield* gitExpect( - ["submodule", "update", "--init", "--recursive", "--force"], - { cwd: worktreePath }, - (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), - ) + // altimate_change start — offline mode moves only checked-out top-level submodules, from objects already on + // disk (`submodule update` would clone the others); nested ones stay at their commits. `submodule status` + // prints " [ ()]" and marks a not-checked-out submodule with "-". + const checkedOut = offlineModeEnabled() + ? (yield* gitExpect( + ["submodule", "status"], + { cwd: worktreePath }, + (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to read submodules" }), + )).text + .split("\n") + .filter((line) => line.length > 1 && !line.startsWith("-")) + .map((line) => /^.[0-9a-f]+ (.+?)(?: \([^)]*\))?$/.exec(line)?.[1]) + .filter((entry): entry is string => Boolean(entry)) + : undefined + if (!checkedOut || checkedOut.length > 0) + yield* gitExpect( + checkedOut + ? ["submodule", "update", "--no-fetch", "--force", "--", ...checkedOut] + : ["submodule", "update", "--init", "--recursive", "--force"], + { cwd: worktreePath }, + (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), + ) + // altimate_change end yield* gitExpect( ["submodule", "foreach", "--recursive", "git", "reset", "--hard"], diff --git a/packages/opencode/test/altimate/mcp-server/stdio.test.ts b/packages/opencode/test/altimate/mcp-server/stdio.test.ts index 9e1cf510b3..e3b05cbf37 100644 --- a/packages/opencode/test/altimate/mcp-server/stdio.test.ts +++ b/packages/opencode/test/altimate/mcp-server/stdio.test.ts @@ -212,3 +212,32 @@ test("mcp serve skips CLI middleware before starting the agent heap service", as expect(starts).toBe(0) }) // altimate_change end + +// altimate_change start — offline mode keeps MCP stdio and drops workspace tools +test("offline CLI announces unavailable workspace tools on stderr and preserves MCP stdio", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "mcp-offline-notice-")) + const connections = path.join(dir, "connections.json") + await Bun.write(connections, "{}") + const child = Bun.spawn([ + process.execPath, "run", "--conditions=browser", CLI_ENTRY, + "mcp", "serve", "--workspace-tools", "--connections", connections, + ], { + cwd: dir, + env: { ...process.env, ALTIMATE_OFFLINE: "1", ALTIMATE_TELEMETRY_DISABLED: "1" }, + stdin: "pipe", stdout: "pipe", stderr: "pipe", + }) + const stderr = new Response(child.stderr).text() + const client = rpcClient(child) + try { + await client.connect() + const listed = await client.listTools() + expect(listed.tools.map((tool: { name: string }) => tool.name).filter((name: string) => name.startsWith("workspace_"))).toEqual([]) + await client.close() + expect(await stderr).toContain("Workspace tools are unavailable in offline mode.") + } finally { + child.kill() + await child.exited + await rm(dir, { recursive: true, force: true }) + } +}, 30000) +// altimate_change end diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts new file mode 100644 index 0000000000..3a83c0c5f0 --- /dev/null +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -0,0 +1,231 @@ +// altimate_change - new file +import { afterEach, beforeEach, expect, test } from "bun:test" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { assertLocalConnection } from "../../../src/altimate/native/connections/offline" +import { assertLocalDbt } from "../../../src/altimate/native/dbt/offline" + +const envKeys = ["DBT_TARGET", "DBT_PROFILE", "DBT_PROFILES_DIR", "DBT_PROJECT_DIR", "ALTIMATE_OFFLINE"] +let savedEnv: Record +beforeEach(() => { + savedEnv = Object.fromEntries(envKeys.map((key) => [key, process.env[key]])) + for (const key of envKeys) delete process.env[key] +}) +afterEach(() => { + for (const key of envKeys) { + if (savedEnv[key] === undefined) delete process.env[key] + else process.env[key] = savedEnv[key] + } +}) + +test("offline permits local files, loopback hosts and Unix sockets", () => { + for (const store of [":memory:", "/tmp/warehouse.db", "data.duckdb", "file:///tmp/local.db"]) + for (const type of ["duckdb", "sqlite"]) expect(() => assertLocalConnection({ type, path: store })).not.toThrow() + for (const config of [ + { type: "postgres", host: "localhost" }, + { type: "postgres", host: "127.0.1.2" }, + { type: "postgres", host: "::1" }, + { type: "postgres", host: "/var/run/postgresql" }, + { type: "redshift", host: "/var/run/postgresql" }, + { type: "postgres" }, + { type: "mysql", server: "127.0.0.1" }, + { type: "mysql", socketPath: "/tmp/mysql.sock" }, + { type: "postgres", connectionString: "postgres://localhost/test" }, + { type: "trino", server: "http://localhost:8080" }, + { type: "postgres", connection_string: "postgresql:///analytics?host=/var/run/postgresql" }, + { type: "sqlserver", host: "localhost\\SQLEXPRESS" }, + { type: "redshift" }, + { type: "clickhouse", host: "127.0.0.1", protocol: "HTTPS" }, + { type: "sqlserver", host: "localhost", authentication: "sql" }, + { type: "oracle", host: "localhost", protocol: "tcp" }, + { type: "mongo", host: "localhost", directConnection: true }, + { type: "mongodb", url: "mongodb://localhost/db?DIRECTCONNECTION=true" }, + { type: "mongodb", url: "mongodb://localhost/db?directConnection=True" }, + { type: "mongodb", url: "mongodb://localhost/db?DIRECTCONNECTION=TRUE" }, + { type: "mongodb", connection_string: "mongodb://localhost/db", direct_connection: true }, + ]) expect(() => assertLocalConnection(config)).not.toThrow() +}) + +test("offline refuses remote hosts, remote storage, SSH and what it cannot parse", () => { + for (const config of [ + { type: "duckdb", path: "md:cloud" }, + { type: "duckdb", path: "s3://bucket/db.duckdb" }, + { type: "duckdb", path: "https://example.com/db" }, + { type: "duckdb", path: "{{ 'md:cloud' }}" }, + { type: "sqlite", path: "file://example.com/share/db" }, + { type: "sqlite", path: "\\\\example.com\\share\\db" }, + { type: "postgres", host: "localhost.evil.test" }, + { type: "postgres", host: "127.0.0.1", ssh_host: "remote" }, + { type: "mysql", server: "db.example.com" }, + { type: "mysql", socketPath: "\\\\.\\pipe\\remote" }, + { type: "snowflake", account: "acme" }, + { type: "snowflake", account: "acme", host: "localhost" }, + { type: "bigquery", project: "p", host: "127.0.0.1" }, + { type: "databricks", host: "localhost" }, + { type: "trino", server: "https://example.com" }, + { type: "postgres", connection_string: "not a url" }, + { type: "oracle", connection_string: "db.example.com:1521/ORCL" }, + { type: "postgres", connection_string: "postgresql://localhost/db?host=db.example.com" }, + { type: "postgres", connection_string: "postgresql://localhost/db?hostaddr=10.0.0.5" }, + { type: "postgres", connection_string: "postgresql:///analytics" }, + { type: "sqlite", path: "file:////server/share/db.sqlite" }, + { type: "sqlite", path: "file:///%5Cserver/share/db.sqlite" }, + { type: "duckdb", path: "file:///tmp/%zz.duckdb" }, + { type: "sqlite", path: "file:///data/100%.db" }, + { type: "sqlite", path: "file:///%5Cserver/share/100%.db" }, + { type: "postgres", host: "/tmp,db.example.com" }, + { type: "mysql", host: "/tmp/mysql" }, + { type: "mongodb", connection_string: "mongodb+srv://localhost/db" }, + { type: "mongodb", connection_string: "mongodb://localhost/db?replicaSet=rs0" }, + { type: "sqlserver", host: "db.example.com\\SQLEXPRESS" }, + { type: "sqlserver", host: "localhost", authentication: "azure-active-directory-default" }, + { type: "sqlserver", host: "localhost", authentication: "cli" }, + { type: "sqlserver", host: "localhost", authentication: "ActiveDirectoryPassword" }, + { type: "mongodb", connection_string: "mongodb://localhost/db?authMechanism=MONGODB-AWS" }, + { type: "sqlite", path: "store.sqlite", ssh_host: "bastion.example.com" }, + { type: "clickhouse", host: "127.0.0.1", protocol: "http://evil.example/#" }, + { type: "trino", host: "localhost", protocol: "https://evil.example" }, + { type: "mongodb", host: "localhost", direct_connection: false }, + { type: "mongodb", host: "localhost" }, + { type: "mongo", connection_string: "mongodb://localhost/db" }, + { type: "mongodb", url: "mongodb://localhost/db?directConnection=true", direct_connection: false }, + { type: "mongodb", url: "mongodb://localhost/db?directConnection=true&proxyHost=proxy.example.com" }, + { type: "oracle", tns_name: "PROD_DB" }, + { type: "oracle" }, + ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") +}) + +test("offline host-addressed databases accept integers and digit-string ports in range", () => { + for (const type of [ + "postgres", "postgresql", "redshift", "mysql", "mariadb", "sqlserver", "mssql", + "clickhouse", "trino", "oracle", "mongodb", "mongo", + ]) { + const config = { type, host: "localhost", direct_connection: true } + for (const port of [undefined, 1, 65535, "1", "5432", "65535"]) + expect(() => assertLocalConnection({ ...config, port })).not.toThrow() + for (const port of [ + null, "", "0", "65536", "-1", "1.5", "1e3", " 5432", "5432\n", "27017,db.example.com:27017", + 0, -1, 1.5, 65536, NaN, Infinity, + ]) + expect(() => assertLocalConnection({ ...config, port })).toThrow("Offline mode") + } +}) + +test("offline MongoDB errors show how to enable direct connections", () => { + for (const config of [ + { type: "mongodb", host: "localhost" }, + { type: "mongo", host: "localhost", direct_connection: false }, + { type: "mongodb", url: "mongodb://localhost/db?directConnection=false" }, + { type: "mongodb", url: "mongodb://localhost/db?directConnection=False", direct_connection: true }, + { type: "mongo", url: "mongodb://localhost/db?DIRECTCONNECTION=FALSE", directConnection: true }, + ]) + expect(() => assertLocalConnection(config)).toThrow( + "Set direct_connection to true or directConnection=true in the connection URI.", + ) +}) + +test("dbt-duckdb settings are refused only when they point at something remote", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-duckdb-")) + const profile = (extra: string) => + fs.writeFile(path.join(root, "profiles.yml"), `test:\n outputs:\n default:\n type: duckdb\n path: local.duckdb\n ${extra}\n`) + try { + await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: test\n") + for (const extra of [ + "external_root: s3://bucket/x", + "external_root: \"{{ var('root') }}\"", + "attach:\n - path: md:shared", + "attach:\n - path: https://example.com/remote.duckdb", + "attach:\n - path: host=db.example.com dbname=x\n type: postgres", + "extensions:\n - name: custom\n repo: https://extensions.example.com", + "remote:\n host: db.example.com", + "filesystems:\n - fs: s3", + ]) { + await profile(extra) + await expect(assertLocalDbt(root, ["--profiles-dir", root])).rejects.toThrow("Offline mode") + } + for (const extra of [ + "external_root: out/parquet", + "extensions:\n - icu\n - spatial", + "attach:\n - path: other.duckdb\n alias: other", + "plugins:\n - module: excel", + ]) { + await profile(extra) + await expect(assertLocalDbt(root, ["--profiles-dir", root])).resolves.toEqual({ profilesDir: root }) + } + } finally { + await fs.rm(root, { recursive: true, force: true }) + } +}) + +test.skipIf(process.platform === "win32")("offline dbt runs with the checked profiles directory and no usage reporting", async () => { + const { runDbt } = await import("../../../src/altimate/native/dbt/runner") + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-run-")) + const previousPath = process.env.PATH + try { + const bin = path.join(root, "bin") + await fs.mkdir(bin) + await fs.writeFile(path.join(bin, "dbt"), '#!/bin/sh\necho "$DBT_PROFILES_DIR|$DBT_VERSION_CHECK|$DBT_SEND_ANONYMOUS_USAGE_STATS|$DO_NOT_TRACK"\n', { mode: 0o755 }) + await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: test\n") + await fs.writeFile(path.join(root, "profiles.yml"), "test:\n outputs:\n default:\n type: duckdb\n path: ':memory:'\n") + process.env.PATH = `${bin}${path.delimiter}${previousPath}` + process.env.ALTIMATE_OFFLINE = "1" + const result = await runDbt({ command: "ls", project_dir: root, args: ["--profiles-dir", root] }) + expect(result.stdout.trim()).toBe(`${root}|false|false|1`) + expect((await runDbt({ command: "deps", project_dir: root })).stderr).toContain("Offline mode disables dbt dependency installation.") + expect((await runDbt({ command: "ls", project_dir: root, args: ["--send-anonymous-usage-stats"] })).stderr).toContain( + "Offline mode disables dbt usage reporting.", + ) + } finally { + process.env.PATH = previousPath + await fs.rm(root, { recursive: true, force: true }) + } +}) + +test("dbt finds the project from a subdirectory and reads profiles from the working directory", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-discovery-")) + try { + const models = path.join(root, "models") + const runDir = path.join(root, "run") + await fs.mkdir(models) + await fs.mkdir(runDir) + await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: test\n") + // The project's own profiles.yml is local, but dbt run from runDir reads runDir/profiles.yml. + await fs.writeFile(path.join(root, "profiles.yml"), "test:\n outputs:\n default:\n type: duckdb\n path: ':memory:'\n") + await fs.writeFile(path.join(runDir, "profiles.yml"), "test:\n outputs:\n default:\n type: postgres\n host: example.com\n") + await expect(assertLocalDbt(models, [], "core", root)).resolves.toEqual({ profilesDir: root }) + await expect(assertLocalDbt(models, [], "core", runDir)).rejects.toThrow("Offline mode") + // dbt expands ~ in DBT_PROFILES_DIR. + process.env.DBT_PROFILES_DIR = "~/" + path.relative(os.homedir(), root) + await expect(assertLocalDbt(models, [], "core", runDir)).resolves.toEqual({ profilesDir: root }) + } finally { await fs.rm(root, { recursive: true, force: true }) } +}) + +test("dbt checks selected target and CLI overrides", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-")) + try { + await fs.writeFile(path.join(root, "dbt_project.yml"), "name: test\nprofile: test\n") + await fs.writeFile(path.join(root, "profiles.yml"), "test:\n target: local\n outputs:\n local:\n type: duckdb\n path: ':memory:'\n remote:\n type: postgres\n host: example.com\n") + const args = ["--profiles-dir", root] + await expect(assertLocalDbt(root, args)).resolves.toEqual({ profilesDir: root }) + await expect(assertLocalDbt(root, [...args, "--target=remote"])).rejects.toThrow("Offline mode") + await expect(assertLocalDbt(root, [...args, "--target", "local", "-t", "remote"])).rejects.toThrow("Offline mode") + await expect(assertLocalDbt(root, [...args, "-t", "remote", "--target", "local"])).resolves.toEqual({ profilesDir: root }) + await expect(assertLocalDbt(root, [...args, "--target", "local", "-tremote"])).rejects.toThrow("Offline mode") + await expect(assertLocalDbt(root, args, "cloud")).rejects.toThrow("Offline mode") + } finally { await fs.rm(root, { recursive: true, force: true }) } +}) + +test("dbt project directory follows environment and CLI precedence", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-project-")) + try { + const other = path.join(root, "other") + await fs.mkdir(other) + await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: local\n") + await fs.writeFile(path.join(other, "dbt_project.yml"), "profile: remote\n") + await fs.writeFile(path.join(root, "profiles.yml"), "local:\n outputs:\n default:\n type: duckdb\n path: ':memory:'\nremote:\n outputs:\n default:\n type: postgres\n host: example.com\n") + process.env.DBT_PROJECT_DIR = other + await expect(assertLocalDbt(root, ["--profiles-dir", root])).rejects.toThrow("Offline mode") + await expect(assertLocalDbt(root, ["--profiles-dir", root, "--project-dir", root])).resolves.toEqual({ profilesDir: root }) + } finally { await fs.rm(root, { recursive: true, force: true }) } +}) diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index bd20235f9f..9fffe7be1b 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -204,3 +204,46 @@ Plugins: expect(third.hasDbtDuckdb).toBe(false) }) }) + +// altimate_change start — offline mode does not run `dbt --version`, which asks PyPI for the latest release +test.skipIf(process.platform === "win32")("offline detection finds dbt without running it", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "offline-dbt-detect-")) + const previous = { offline: process.env.ALTIMATE_OFFLINE, dbt: process.env.ALTIMATE_DBT_PATH } + const previousPath = process.env.PATH + try { + const ran = path.join(dir, "ran") + // The stub sits in its own bin directory so the adapter lookup stays inside this fixture. + fs.mkdirSync(path.join(dir, "bin")) + fs.writeFileSync(path.join(dir, "bin", "dbt"), `#!/bin/sh\ntouch "${ran}"\n`, { mode: 0o755 }) + process.env.ALTIMATE_DBT_PATH = path.join(dir, "bin", "dbt") + process.env.ALTIMATE_OFFLINE = "1" + _resetDbtRuntimeCacheForTests() + expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: false }) + expect(fs.existsSync(ran)).toBe(false) + // dbt linked from a virtual environment (as pipx and uv install it) whose site-packages has dbt-duckdb. + const venvBin = path.join(dir, "venv", "bin") + fs.mkdirSync(venvBin, { recursive: true }) + fs.mkdirSync(path.join(dir, "venv", "lib", "python3.12", "site-packages", "dbt", "adapters", "duckdb"), { recursive: true }) + fs.renameSync(path.join(dir, "bin", "dbt"), path.join(venvBin, "dbt")) + fs.symlinkSync(path.join(venvBin, "dbt"), path.join(dir, "bin", "dbt")) + _resetDbtRuntimeCacheForTests() + expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true }) + expect(fs.existsSync(ran)).toBe(false) + + // Only the fixture binary is on PATH, so the resolver cannot launch external `which`. + delete process.env.ALTIMATE_DBT_PATH + process.env.PATH = path.join(dir, "bin") + expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true }) + expect(fs.existsSync(ran)).toBe(false) + } finally { + if (previousPath === undefined) delete process.env.PATH + else process.env.PATH = previousPath + for (const [key, value] of [["ALTIMATE_OFFLINE", previous.offline], ["ALTIMATE_DBT_PATH", previous.dbt]] as const) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + _resetDbtRuntimeCacheForTests() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) +// altimate_change end diff --git a/packages/opencode/test/altimate/tool-cli/offline.test.ts b/packages/opencode/test/altimate/tool-cli/offline.test.ts new file mode 100644 index 0000000000..7e7c9b8745 --- /dev/null +++ b/packages/opencode/test/altimate/tool-cli/offline.test.ts @@ -0,0 +1,23 @@ +// altimate_change - new file +import { expect, test } from "bun:test" +import path from "node:path" +import { tmpdir } from "../../fixture/fixture" + +// Offline.start replaces the process-wide fetch, so the check runs in its own process. +test("offline mode turns workspace tools off and says so when they were asked for", async () => { + await using tmp = await tmpdir() + const module = path.resolve(import.meta.dir, "../../../src/altimate/tool-cli/workspace-tools.ts") + const script = `const { resolveWorkspaceTools } = await import(${JSON.stringify(module)}) +console.log(JSON.stringify([await resolveWorkspaceTools(true, ${JSON.stringify(tmp.path)}, async () => true), await resolveWorkspaceTools(undefined, ${JSON.stringify(tmp.path)}, async () => true)]))` + const proc = Bun.spawn([process.execPath, "-e", script], { + cwd: path.resolve(import.meta.dir, "../../.."), + env: { ...process.env, ALTIMATE_OFFLINE: "1" }, + stdout: "pipe", + stderr: "pipe", + }) + const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]) + await proc.exited + expect(stdout.trim().split("\n").at(-1)).toBe("[false,false]") + // Only the explicit request gets the notice. + expect(stderr.match(/Workspace tools are unavailable in offline mode\./g)).toHaveLength(1) +}) diff --git a/packages/opencode/test/altimate/warehouse-install-driver-permission.test.ts b/packages/opencode/test/altimate/warehouse-install-driver-permission.test.ts index a844ad11a3..125845f7c1 100644 --- a/packages/opencode/test/altimate/warehouse-install-driver-permission.test.ts +++ b/packages/opencode/test/altimate/warehouse-install-driver-permission.test.ts @@ -95,6 +95,25 @@ describe("warehouse_install_driver permissions", () => { }) } + test("offline driver installation gives the online command without invoking npm", async () => { + const prior = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + spyOn(DriverResolve, "isDriverInstalled").mockReturnValue(false) + const install = spyOn(DriverResolve, "installOptionalDriver").mockRejectedValue(new Error("npm must not run")) + const ask = mock(async () => {}) + try { + const result = await tool.execute({ driver: "postgres" }, context(ask)) + expect(result.metadata.installed).toBe(false) + expect(result.output).toContain("Install the driver while online: npm install --prefix") + expect(result.output).toMatch(/ pg$/) + expect(ask).not.toHaveBeenCalled() + expect(install).not.toHaveBeenCalled() + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } + }) + test("an already-usable driver does not request mutation permissions", async () => { spyOn(DriverResolve, "isDriverInstalled").mockReturnValue(true) spyOn(DriverResolve, "loadOptionalDriver").mockResolvedValue({}) diff --git a/packages/opencode/test/bun.test.ts b/packages/opencode/test/bun.test.ts index d607ae4782..f64543222e 100644 --- a/packages/opencode/test/bun.test.ts +++ b/packages/opencode/test/bun.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test" import fs from "fs/promises" import path from "path" +import { tmpdir } from "./fixture/fixture" describe("BunProc registry configuration", () => { test("should not contain hardcoded registry parameters", async () => { @@ -51,3 +52,45 @@ describe("BunProc registry configuration", () => { } }) }) + +describe("BunProc offline cache", () => { + test("accepts latest and matching cached versions, rejects misses, and preserves malformed metadata", async () => { + const { BunProc } = await import("../src/bun") + const { Global } = await import("../src/global") + const { spyOn } = await import("bun:test") + const prior = process.env.ALTIMATE_OFFLINE + const originalCache = Global.Path.cache + await using tmp = await tmpdir() + const cache = tmp.path + Global.Path.cache = cache + process.env.ALTIMATE_OFFLINE = "1" + const run = spyOn(BunProc, "run").mockImplementation(async () => { + throw new Error("must not install") + }) + try { + const pkg = "@test/cached" + const mod = path.join(cache, "node_modules", pkg) + const metadata = path.join(cache, "package.json") + await fs.mkdir(mod, { recursive: true }) + await fs.writeFile(metadata, JSON.stringify({ dependencies: { [pkg]: "1.2.3" } })) + expect(await BunProc.install(pkg)).toBe(mod) + expect(await BunProc.install(pkg, "1.2.3")).toBe(mod) + await expect(BunProc.install(pkg, "2.0.0")).rejects.toThrow(`Install ${pkg} while online.`) + await expect(BunProc.install("missing")).rejects.toThrow("Install missing while online.") + await fs.rm(mod, { recursive: true }) + await expect(BunProc.install(pkg)).rejects.toThrow(`Install ${pkg} while online.`) + for (const content of [undefined, "{invalid json"]) { + if (content === undefined) await fs.rm(metadata) + else await fs.writeFile(metadata, content) + await expect(BunProc.install(pkg)).rejects.toThrow(`Install ${pkg} while online.`) + expect(await fs.readFile(metadata, "utf8").catch(() => undefined)).toBe(content) + } + expect(run).not.toHaveBeenCalled() + } finally { + run.mockRestore() + Global.Path.cache = originalCache + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } + }) +}) diff --git a/packages/opencode/test/cli/mcp-add.test.ts b/packages/opencode/test/cli/mcp-add.test.ts index cf9e547f04..f3e8b6ef63 100644 --- a/packages/opencode/test/cli/mcp-add.test.ts +++ b/packages/opencode/test/cli/mcp-add.test.ts @@ -8,7 +8,7 @@ const repoRoot = path.resolve(import.meta.dir, "..", "..", "..", "..") const opencodeDir = path.join(repoRoot, "packages", "opencode") const cliEntry = path.join(opencodeDir, "src", "index.ts") -function withIsolatedCli(fn: (ctx: { configDir: string; run: (args: string[]) => ReturnType }) => void) { +function withIsolatedCli(fn: (ctx: { configDir: string; run: (args: string[]) => ReturnType }) => void, offline = false) { const root = mkdtempSync(path.join(tmpdir(), "altimate-mcp-add-")) const home = path.join(root, "home") const configHome = path.join(root, "config") @@ -24,6 +24,7 @@ function withIsolatedCli(fn: (ctx: { configDir: string; run: (args: string[]) => timeout: 30_000, env: { ...process.env, + ALTIMATE_OFFLINE: offline ? "1" : "0", HOME: home, XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome, @@ -153,3 +154,27 @@ describe("opencode mcp add (non-interactive subprocess)", () => { }), ) }) + + +test("offline MCP add refuses remote configuration before writing it", () => { + withIsolatedCli(({ configDir, run }) => { + const configPath = path.join(configDir, "altimate-code.json") + mkdirSync(configDir, { recursive: true }) + const original = '{"mcp":{},"username":"unchanged"}\n' + writeFileSync(configPath, original) + const result = run(["mcp", "add", "--name", "remote", "--url", "https://example.com/mcp", "--global"]) + expect(result.status).not.toBe(0) + expect(`${result.stdout}${result.stderr}`).toContain("ones on this machine") + expect(readJson(configPath)).toMatchObject({ mcp: {}, username: "unchanged" }) + }, true) +}, 30_000) + +test("offline MCP add permits stdio and loopback configuration", () => { + withIsolatedCli(({ configDir, run }) => { + expectExit(run(["mcp", "add", "--name", "loopback", "--url", "http://127.0.0.1:9000/mcp", "--global"]), 0) + expectExit(run(["mcp", "add", "--name", "stdio", "--command", "local-server", "--global"]), 0) + const config = readJson(path.join(configDir, "altimate-code.json")) + expect(config.mcp.loopback.url).toBe("http://127.0.0.1:9000/mcp") + expect(config.mcp.stdio.command).toEqual(["local-server"]) + }, true) +}, 30_000) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts new file mode 100644 index 0000000000..5deaf146f6 --- /dev/null +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -0,0 +1,696 @@ +import { afterAll, beforeAll, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import fs from "node:fs/promises" +import net from "node:net" +import os from "node:os" +import path from "node:path" +import { gitCommandUsesNetwork } from "@opencode-ai/core/git" + +const CLI = path.resolve(import.meta.dir, "../../../src/index.ts") +const MODEL_ENDPOINT = "http://model.test:9000/v1" +const API = "https://workspace.test" +const TENANT = "offline-fixture" +const KEY = "fixture-key" +const SKILL = "This unique statement came from the cached offline skill." + +// Egress that does not go through fetch: every proxy variable points at a proxy that records and refuses each +// request, and PATH shims record each run of a program that can reach the network. +const proxyHits: string[] = [] +let denyProxy: net.Server +let PROXY = "" +const SHIMMED = ["git", "npm", "npx", "pnpm", "yarn", "dbt", "pip", "pip3", "uv", "curl", "wget", "ssh", "gh"] +const REAL = Object.fromEntries(SHIMMED.map((name) => [name, Bun.which(name)])) + +beforeAll(async () => { + denyProxy = net.createServer((socket) => { + socket.on("error", () => {}) + socket.once("data", (chunk) => { + proxyHits.push(chunk.toString("latin1").split("\r\n")[0]) + socket.end("HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n") + }) + }) + await new Promise((resolve) => denyProxy.listen(0, "127.0.0.1", resolve)) + PROXY = `http://127.0.0.1:${(denyProxy.address() as net.AddressInfo).port}` +}) +afterAll(() => denyProxy?.close()) + +async function writeShims(dir: string, log: string) { + await fs.mkdir(dir, { recursive: true }) + for (const name of SHIMMED) { + const real = REAL[name] + await Bun.write( + path.join(dir, name), + `#!/bin/sh\nprintf "%s\\n" "${name} $*" >> "${log}"\n${real ? `exec "${real}" "$@"` : "exit 127"}\n`, + ) + await fs.chmod(path.join(dir, name), 0o755) + } +} + +/** Programs that reached the network: any non-git network tool, or a git command that uses a remote. */ +async function networkSpawns(log: string) { + const lines = (await fs.readFile(log, "utf8").catch(() => "")).split("\n").filter(Boolean) + return lines.filter((line) => { + const [name, ...args] = line.split(" ") + return name !== "git" || gitCommandUsesNetwork(args) + }) +} + +async function fixture( + snapshot: boolean, + configMode: boolean | "managed", + disableWorkspace: boolean, + provider = "offline-test", +) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "altimate-offline-")) + const project = path.join(root, "project") + const config = path.join(root, "config", "altimate-code") + const data = path.join(root, "data", "altimate-code") + const managed = path.join(root, "managed") + const calls = path.join(root, "calls.jsonl") + const preload = path.join(root, "preload.ts") + const blocked = path.join(root, "blocked.jsonl") + const shims = path.join(root, "shims") + const spawns = path.join(root, "spawns.log") + await writeShims(shims, spawns) + await Promise.all([fs.mkdir(project), fs.mkdir(config, { recursive: true }), fs.mkdir(data, { recursive: true })]) + await Bun.write( + path.join(config, "altimate-code.json"), + JSON.stringify({ + model: `${provider}/fixture`, + provider: { + [provider]: { + npm: "@ai-sdk/openai-compatible", + options: { baseURL: MODEL_ENDPOINT, apiKey: "local-only" }, + models: { fixture: { name: "Offline fixture", limit: { context: 100000, output: 2000 } } }, + }, + }, + mcp: { remoteFixture: { type: "remote", url: "https://mcp.test" } }, + }), + ) + if (configMode === "managed") + await Bun.write(path.join(managed, "altimate-code.jsonc"), '{ // managed policy\n "offline": true }') + else if (configMode && !snapshot) + await Bun.write(path.join(project, "opencode.jsonc"), '{ // local policy\n "offline": true }') + await Bun.write( + path.join(data, "auth.json"), + JSON.stringify({ + "https://remote-config.test": { type: "wellknown", key: "FIXTURE_TOKEN", token: "fixture" }, + }), + ) + await Bun.write( + path.join(root, ".altimate", "altimate.json"), + JSON.stringify({ + altimateUrl: API, + altimateInstanceName: TENANT, + altimateApiKey: KEY, + }), + ) + const snapshotRoot = path.join(project, ".altimate-code", "skill", "_workspace") + const manifest = path.join(snapshotRoot, ".manifest.json") + const skill = path.join(snapshotRoot, "sk_local", "SKILL.md") + if (snapshot) { + await Bun.write( + manifest, + JSON.stringify({ + version: 2, + tenant: TENANT, + apiUrl: API, + datamateId: 1, + account: createHash("sha256").update(`${API}|${TENANT}|${KEY}`).digest("hex"), + skills: { sk_local: { updatedAt: "x", files: {} } }, + }), + ) + await Bun.write( + skill, + `---\nname: cached-offline\ndescription: Offline fixture skill\nalwaysApply: true\n---\n${SKILL}\n`, + ) + } + + await Bun.write( + preload, + ` + import { appendFileSync } from "node:fs" + const log = ${JSON.stringify(calls)} + let turn = 0 + globalThis.fetch = Object.assign(async (input, init) => { + const url = input instanceof Request ? input.url : String(input) + appendFileSync(log, JSON.stringify({ url, hasSkill: String(init?.body).includes(${JSON.stringify(SKILL)}) }) + "\\n") + if (url !== ${JSON.stringify(MODEL_ENDPOINT + "/chat/completions")}) { + return new Response("{}", { status: 503 }) + } + const request = JSON.parse(String(init?.body ?? "{}")) + const canRunShell = request.tools?.some((tool) => tool.function?.name === "bash") + const chunks = process.env.OFFLINE_TEST_BASH && canRunShell && turn++ === 0 + ? [ + { choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ + index: 0, id: "call_shell", type: "function", function: { + name: "bash", + arguments: JSON.stringify({ + command: 'printf "shell-ran:%s|%s|%s" "$NO_PROXY" "$HTTPS_PROXY" "$ALTIMATE_OFFLINE" > shell-marker', + description: "Write a local marker", + workdir: process.cwd(), + timeout: 5000, + }), + }, + }] }, finish_reason: null }] }, + { choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }, + ] + : [ + { choices: [{ index: 0, delta: { role: "assistant", content: "offline reply" }, finish_reason: null }] }, + { choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 20, completion_tokens: 2 } }, + ] + return new Response(chunks.map((chunk) => "data: " + JSON.stringify(chunk) + "\\n\\n").join("") + "data: [DONE]\\n\\n", + { headers: { "content-type": "text/event-stream" } }) + }, { preconnect() {} }) + let current = globalThis.fetch + Object.defineProperty(globalThis, "fetch", { + configurable: true, + get: () => current, + set(next) { + current = Object.assign(async (input, init) => { + const url = input instanceof Request ? input.url : String(input) + appendFileSync(${JSON.stringify(blocked)}, JSON.stringify(url) + "\\n") + return next(input, init) + }, { preconnect: next.preconnect }) + }, + }) + `, + ) + const env = { + PATH: `${shims}${path.delimiter}${process.env.PATH}`, + ...Object.fromEntries( + ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"].map((key) => [key, PROXY]), + ), + HOME: root, + OPENCODE_TEST_HOME: root, + OPENCODE_TEST_MANAGED_CONFIG_DIR: managed, + XDG_CONFIG_HOME: path.join(root, "config"), + XDG_DATA_HOME: path.join(root, "data"), + XDG_CACHE_HOME: path.join(root, "cache"), + XDG_STATE_HOME: path.join(root, "state"), + ALTIMATE_OFFLINE: configMode ? "" : "1", + ...(configMode && snapshot + ? { + OPENCODE_CONFIG_CONTENT: "{env:OFFLINE_CONFIG_VALUE}", + OFFLINE_CONFIG_VALUE: JSON.stringify({ offline: true }), + } + : {}), + // The environment switch must preserve the snapshot even when a deployment + // still has the old workspace opt-out set. + ALTIMATE_DISABLE_WORKSPACE: disableWorkspace ? "1" : "", + ALTIMATE_CODE_DISABLE_OS_CREDENTIAL_STORE: "1", + ALTIMATE_RUN_STDIN_WAIT_MS: "0", + NO_COLOR: "1", + } + return { root, project, preload, env, calls, blocked, manifest, skill, shims, spawns } +} + +for (const { scenario, snapshot, configMode, disableWorkspace } of [ + { + scenario: "environment switch with the workspace opt-out", + snapshot: true, + configMode: false, + disableWorkspace: true, + }, + { + scenario: "interpolated config switch with a cached snapshot", + snapshot: true, + configMode: true, + disableWorkspace: false, + }, + { scenario: "config switch without a snapshot", snapshot: false, configMode: true, disableWorkspace: false }, + { scenario: "managed config switch", snapshot: false, configMode: "managed", disableWorkspace: false }, +] as const) { + test(`offline ${scenario} keeps network traffic on the model endpoint`, async () => { + const f = await fixture(snapshot, configMode, disableWorkspace, snapshot ? "offline-test" : "openai") + proxyHits.length = 0 + try { + const before = snapshot ? await fs.readFile(f.manifest, "utf8") : undefined + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "Hello"], { + cwd: f.project, + // The snapshot must work on a cold host where ripgrep is absent: PATH holds only the shims. + env: snapshot ? { ...f.env, PATH: f.shims } : f.env, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(30_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + const payload = await fs.readFile(f.calls, "utf8").catch(() => "") + const calls: { url: string; hasSkill: boolean }[] = payload + .trim() + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line)) + expect({ code, stderr, nonModelCalls: calls.filter((call) => call.url !== MODEL_ENDPOINT + "/chat/completions") }).toMatchObject({ code: 0, nonModelCalls: [] }) + expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("offline reply") }) + expect(calls.length).toBeGreaterThan(0) + expect(calls.some((call) => call.hasSkill)).toBe(snapshot) + expect(stderr).not.toContain("Workspace skills not synced") + // Nothing left through a proxy or a network program either. + expect({ proxyHits, spawns: await networkSpawns(f.spawns) }).toEqual({ proxyHits: [], spawns: [] }) + if (snapshot) { + expect(await fs.readFile(f.manifest, "utf8")).toBe(before!) + expect(await fs.readFile(f.skill, "utf8")).toContain(SKILL) + } + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } + }, 40_000) +} + +test("offline model can execute a local bash command", async () => { + const f = await fixture(false, false, false) + try { + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "--yolo", "Run the local shell command"], { + cwd: f.project, + // The user's proxy settings reach their own commands; offline mode only adds the loopback hosts. + env: { ...f.env, OFFLINE_TEST_BASH: "1", ALTIMATE_CLI_YOLO: "true", NO_PROXY: "corp.example" }, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(25_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("offline reply") }) + const marker = await Bun.file(path.join(f.project, "shell-marker")).text().catch(() => "") + expect({ marker, stdout, stderr }).toMatchObject({ marker: `shell-ran:corp.example,localhost,127.0.0.1,[::1],0.0.0.0|${PROXY}|1` }) + expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 30_000) + +test("offline SQL tool queries a local DuckDB file", async () => { + const f = await fixture(false, false, false) + try { + const database = path.join(f.project, "warehouse.duckdb") + const connections = path.join(f.project, ".altimate-code", "connections.json") + const writeConnection = (create = false) => + Bun.write(connections, JSON.stringify({ local: { type: "duckdb", path: database, create } })) + const runSQL = async (query: string, allowWrite = false) => { + const proc = Bun.spawn([ + process.execPath, "--preload", f.preload, CLI, "tool", "run", "sql_execute", + ...(allowWrite ? ["--allow-write"] : []), + "--args", JSON.stringify({ warehouse: "local", query }), "--json", + ], { + cwd: f.project, + env: f.env, + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(25_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + return { code, stdout, stderr } + } + + await writeConnection(true) + const seed = await runSQL("create table fixture as select 42 as offline_answer", true) + expect(seed).toMatchObject({ code: 0, stdout: expect.stringContaining('"status":"ok"') }) + expect(await Bun.file(database).exists()).toBe(true) + await writeConnection() + const { code, stdout, stderr } = await runSQL("select offline_answer from fixture") + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("offline_answer") }) + expect(JSON.parse(stdout).status).toBe("ok") + expect(stdout).toContain("42") + expect(await fs.readFile(f.calls, "utf8").catch(() => "")).toBe("") + expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 55_000) + +test("offline SQL tool refuses a warehouse whose host is not loopback", async () => { + const f = await fixture(false, false, false) + try { + await Bun.write( + path.join(f.project, ".altimate-code", "connections.json"), + JSON.stringify({ remote: { type: "postgres", host: "db.example.com", database: "analytics", user: "analyst" } }), + ) + const proc = Bun.spawn([ + process.execPath, "--preload", f.preload, CLI, "tool", "run", "sql_execute", + "--args", JSON.stringify({ warehouse: "remote", query: "select 1" }), "--json", + ], { cwd: f.project, env: f.env, stdout: "pipe", stderr: "pipe", signal: AbortSignal.timeout(25_000) }) + const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]) + await proc.exited + expect(stdout + stderr).toContain("Offline mode allows only local file databases and warehouses at a loopback host.") + expect(await fs.readFile(f.calls, "utf8").catch(() => "")).toBe("") + expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 30_000) + +test("offline attach accepts a server on this machine and refuses a remote one", async () => { + const f = await fixture(false, false, false) + try { + const attach = async (url: string) => { + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "--attach", url, "Hello"], { + cwd: f.project, + env: f.env, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(20_000), + }) + const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]) + await proc.exited + return stdout + stderr + } + expect(await attach("https://remote-server.test")).toContain("This command requires network access") + // Nothing listens on port 9; the attempt fails on connection, not on the offline policy. + expect(await attach("http://127.0.0.1:9")).not.toContain("This command requires network access") + // The only requests made went to the local server. + const requests = (await fs.readFile(f.blocked, "utf8").catch(() => "")).trim().split("\n").filter(Boolean) + expect(requests.length).toBeGreaterThan(0) + expect(requests.filter((line) => !line.includes("http://127.0.0.1:9/"))).toEqual([]) + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 45_000) + +test("offline skill install refuses a remote repository before running git clone", async () => { + const f = await fixture(false, false, false) + const clone = path.join(f.root, "unexpected-clone") + try { + await fs.appendFile( + f.preload, + ` + const spawnSync = Bun.spawnSync + Bun.spawnSync = (args, options) => { + if (Array.isArray(args) && args[0] === "git" && args[1] === "clone") { + appendFileSync(${JSON.stringify(clone)}, "git clone ran") + return { exitCode: 1, stderr: Buffer.from("unexpected git clone") } + } + return spawnSync(args, options) + } + `, + ) + await fs.rm(path.join(f.root, "data", "altimate-code", "auth.json")) + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "skill", "install", "example/skill"], { + cwd: f.project, + env: f.env, + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(20_000), + }) + const [code, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]) + expect(await Bun.file(clone).exists()).toBe(false) + expect(code).toBe(1) + expect(stderr).toContain("Install remote skills while online") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 25_000) + +test("offline mode launches a configured local language server", async () => { + const f = await fixture(false, false, false) + const marker = path.join(f.root, "unexpected-lsp") + const stub = path.join(f.root, "language-server.ts") + const server = path.resolve(import.meta.dir, "../../fixture/lsp/fake-lsp-server.js") + const file = path.join(f.project, "test.offline-fixture") + try { + await fs.rm(path.join(f.root, "data", "altimate-code", "auth.json")) + await Bun.write(file, "test") + await Bun.write(stub, `await Bun.write(${JSON.stringify(marker)}, "server started"); await import(${JSON.stringify(server)})`) + await Bun.write( + path.join(f.project, "opencode.json"), + JSON.stringify({ lsp: { fixture: { command: [process.execPath, stub], extensions: [".offline-fixture"] } } }), + ) + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "debug", "lsp", "diagnostics", file], { + cwd: f.project, + env: f.env, + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(45_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect(await Bun.file(marker).exists()).toBe(true) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("{}") }) + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 50_000) + +test("offline mode never falls back from a blank endpoint to the provider catalog URL", async () => { + const f = await fixture(false, false, false) + try { + const configFile = path.join(f.root, "config", "altimate-code", "altimate-code.json") + const config = await Bun.file(configFile).json() + config.provider["offline-test"].options.baseURL = "" + config.provider["offline-test"].api = "https://fallback-model.test/v1" + await Bun.write(configFile, JSON.stringify(config)) + await fs.rm(path.join(f.root, "data", "altimate-code", "auth.json")) + + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "Hello"], { + cwd: f.project, + env: f.env, + stdin: "ignore", + stdout: "ignore", + stderr: "pipe", + signal: AbortSignal.timeout(20_000), + }) + const [code, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]) + expect(await fs.readFile(f.calls, "utf8").catch(() => "")).toBe("") + expect(code).toBe(1) + expect(stderr).toContain("offline-test") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 25_000) + +test.skipIf(process.platform === "win32")( + "offline integration detection and review import never launch gh", + async () => { + const f = await fixture(false, false, false) + const bin = path.join(f.root, "bin") + const ghCalls = path.join(f.root, "gh-calls") + try { + await fs.mkdir(bin) + const gh = path.join(bin, "gh") + await Bun.write(gh, '#!/bin/sh\nprintf "%s\\n" "$*" >> "$OFFLINE_TEST_GH_CALLS"\nprintf "fixture\\n"\n') + await fs.chmod(gh, 0o755) + await fs.rm(path.join(f.root, "data", "altimate-code", "auth.json")) + for (const args of [ + ["integrations", "detect"], + ["learn", "import-reviews", "--repo", "example/project", "--dry-run"], + ]) { + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, ...args], { + cwd: f.project, + env: { ...f.env, PATH: bin, OFFLINE_TEST_GH_CALLS: ghCalls }, + stdin: "ignore", + stdout: "ignore", + stderr: "pipe", + signal: AbortSignal.timeout(20_000), + }) + const [code, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]) + expect(await Bun.file(ghCalls).exists()).toBe(false) + expect(code).toBe(1) + expect(stderr).toContain("This command requires network access") + } + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } + }, + 45_000, +) + +test.skipIf(process.platform === "win32")( + "offline skill validation runs local paired tools", + async () => { + const f = await fixture(true, false, false) + const bin = path.join(f.root, "bin") + const marker = path.join(f.root, "paired-tool-ran") + try { + await fs.rm(path.join(f.root, "data", "altimate-code", "auth.json")) + await fs.mkdir(bin) + const tool = path.join(bin, "fixture-tool") + await Bun.write(tool, '#!/bin/sh\nprintf "paired executable ran\\n" > "$OFFLINE_TEST_TOOL_MARKER"\n') + await fs.chmod(tool, 0o755) + await fs.appendFile(f.skill, "\nTools used: `fixture-tool`\n") + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "skill", "test", "cached-offline"], { + cwd: f.project, + env: { ...f.env, PATH: bin, OFFLINE_TEST_TOOL_MARKER: marker }, + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(20_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + // A local executable is the user's own program: offline mode runs it like any other. + expect(await Bun.file(marker).exists()).toBe(true) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("fixture-tool") }) + expect(stdout).not.toContain("online mode") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } + }, + 25_000, +) + +test("standalone MCP initializes offline over stdio without network requests", async () => { + const f = await fixture(false, true, false) + try { + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "mcp", "serve"], { + cwd: f.project, + env: f.env, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(30_000), + }) + const stderr = new Response(proc.stderr).text() + proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { + protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "offline-test", version: "1" }, + } }) + "\n") + proc.stdin.flush() + const reader = proc.stdout.getReader() + let output = "" + while (!output.includes("\n")) { + const chunk = await reader.read() + if (chunk.done) break + output += new TextDecoder().decode(chunk.value) + } + proc.stdin.end() + const code = await proc.exited + expect({ code, stderr: await stderr }).toMatchObject({ code: 0 }) + expect(JSON.parse(output.trim())).toMatchObject({ id: 1, result: { serverInfo: { name: expect.any(String) } } }) + expect(await fs.readFile(f.calls, "utf8").catch(() => "")).toBe("") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 35_000) + +test("with offline mode off, fetch, proxy settings and the shell environment stay as they were", async () => { + // configMode leaves ALTIMATE_OFFLINE empty; removing the project file leaves no offline setting anywhere. + const f = await fixture(false, true, false) + try { + await fs.rm(path.join(f.project, "opencode.jsonc")) + await fs.rm(path.join(f.root, "data", "altimate-code", "auth.json")) + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "--yolo", "Run the local shell command"], { + cwd: f.project, + // Online startup work the fixture cannot answer is switched off with the existing switches. + env: { + ...f.env, + OFFLINE_TEST_BASH: "1", + ALTIMATE_CLI_YOLO: "true", + NO_PROXY: "corp.example", + OPENCODE_DISABLE_MODELS_FETCH: "1", + OPENCODE_DISABLE_AUTOUPDATE: "1", + ALTIMATE_TELEMETRY_DISABLED: "1", + ALTIMATE_DISABLE_WORKSPACE: "1", + }, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(25_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("offline reply") }) + const marker = await Bun.file(path.join(f.project, "shell-marker")).text().catch(() => "") + expect({ marker, stderr }).toMatchObject({ marker: `shell-ran:corp.example|${PROXY}|` }) + // The preload records every replacement of globalThis.fetch: none happened. + expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 30_000) + +test.skipIf(process.platform === "win32" || !Bun.which("openssl"))( + "offline model requests reach an HTTPS endpoint through HTTPS_PROXY, and nothing else does", + async () => { + const f = await fixture(false, false, false) + const tunnels: string[] = [] + let proxy: net.Server | undefined + let model: ReturnType | undefined + try { + const key = path.join(f.root, "key.pem") + const cert = path.join(f.root, "cert.pem") + const made = Bun.spawnSync(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-out", cert, + "-days", "1", "-subj", "/CN=model.test", "-addext", "subjectAltName=DNS:model.test"], { stderr: "pipe" }) + expect(made.exitCode).toBe(0) + model = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + tls: { key: Bun.file(key), cert: Bun.file(cert) }, + fetch: () => + new Response( + [ + { choices: [{ index: 0, delta: { role: "assistant", content: "proxied reply" }, finish_reason: null }] }, + { choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 20, completion_tokens: 2 } }, + ].map((chunk) => "data: " + JSON.stringify(chunk) + "\n\n").join("") + "data: [DONE]\n\n", + { headers: { "content-type": "text/event-stream" } }, + ), + }) + // A CONNECT proxy that tunnels model.test to the local TLS server and refuses everything else. + proxy = net.createServer((client) => { + client.once("data", (chunk) => { + const line = chunk.toString("latin1").split("\r\n")[0] + tunnels.push(line) + if (!line.startsWith("CONNECT model.test:443 ")) return client.end("HTTP/1.1 403 Forbidden\r\n\r\n") + const upstream = net.connect(Number(model!.port), "127.0.0.1", () => { + client.write("HTTP/1.1 200 Connection Established\r\n\r\n") + client.pipe(upstream).pipe(client) + }) + upstream.on("error", () => client.destroy()) + }) + }) + await new Promise((resolve) => proxy!.listen(0, "127.0.0.1", resolve)) + const proxyURL = `http://127.0.0.1:${(proxy.address() as net.AddressInfo).port}` + const configFile = path.join(f.root, "config", "altimate-code", "altimate-code.json") + const config = await Bun.file(configFile).json() + config.provider["offline-test"].options.baseURL = "https://model.test/v1" + await Bun.write(configFile, JSON.stringify(config)) + // No fetch-replacing preload: the CLI uses the real fetch. + const proc = Bun.spawn([process.execPath, CLI, "run", "Hello"], { + cwd: f.project, + env: { + ...f.env, + ...Object.fromEntries(["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"].map((k) => [k, proxyURL])), + NODE_EXTRA_CA_CERTS: cert, + }, + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(30_000), + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("proxied reply") }) + expect(tunnels.length).toBeGreaterThan(0) + expect(tunnels.filter((line) => !line.startsWith("CONNECT model.test:443 "))).toEqual([]) + } finally { + proxy?.close() + model?.stop(true) + await fs.rm(f.root, { recursive: true, force: true }) + } + }, + 40_000, +) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index f32e56f635..b9f5f0d184 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -1504,6 +1504,27 @@ it.instance("migrates legacy write tool to edit permission", () => // Managed settings tests // Note: preload.ts sets OPENCODE_TEST_MANAGED_CONFIG which Global.Path.managedConfig uses +// altimate_change start — config discovered after startup must not activate offline mode +it.instance("refuses offline mode when managed config is loaded without the startup probe", () => + Effect.gen(function* () { + const previous = process.env.ALTIMATE_OFFLINE + delete process.env.ALTIMATE_OFFLINE + try { + yield* writeManagedSettingsEffect({ offline: true }) + const error = yield* Config.use.get().pipe(Effect.catchDefect(Effect.succeed)) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + "Configuration requests offline mode. Restart Altimate Code with ALTIMATE_OFFLINE=1.", + ) + expect(process.env.ALTIMATE_OFFLINE).toBeUndefined() + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), +) +// altimate_change end + it.instance( "managed settings override user settings", Effect.gen(function* () { diff --git a/packages/opencode/test/installation/upgrade.test.ts b/packages/opencode/test/installation/upgrade.test.ts index ac2bc6a9bf..182a2ed852 100644 --- a/packages/opencode/test/installation/upgrade.test.ts +++ b/packages/opencode/test/installation/upgrade.test.ts @@ -54,6 +54,27 @@ describe("VERSION normalization", () => { // 2. Upgrade skip logic — version comparison // --------------------------------------------------------------------------- describe("upgrade version comparison", () => { + test("offline version lookup performs no HTTP requests", async () => { + const original = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + const seen: string[] = [] + const layer = Installation.layer.pipe( + Layer.provide(mockHttpClient((request) => { + seen.push(request.url) + return Response.json({ version: "0.4.1" }) + })), + Layer.provide(AppProcess.defaultLayer), + ) + try { + const result = await Effect.runPromise(Installation.use.latest("npm").pipe(Effect.provide(layer))) + expect(seen).toEqual([]) + expect(result).toBe(Installation.VERSION) + } finally { + if (original === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = original + } + }) + test("same version from GitHub API matches (no false upgrade)", async () => { const latest = await latestWith({ tag_name: "v0.4.1" }, "unknown") // If VERSION were "0.4.1" (normalized), they'd match → upgrade skipped diff --git a/packages/opencode/test/lsp/offline.test.ts b/packages/opencode/test/lsp/offline.test.ts new file mode 100644 index 0000000000..613b9c9174 --- /dev/null +++ b/packages/opencode/test/lsp/offline.test.ts @@ -0,0 +1,43 @@ +// altimate_change - new file +import { expect, test, spyOn } from "bun:test" +import fs from "fs/promises" +import path from "path" +import { Global } from "@opencode-ai/core/global" +import { Npm } from "@opencode-ai/core/npm" +import { Vue } from "../../src/lsp/server" +import type { RuntimeFlags } from "../../src/effect/runtime-flags" +import type { InstanceContext } from "../../src/project/instance-context" + +test.skipIf(process.platform === "win32")("offline LSP spawns an npm-cached server; standalone disableLspDownload returns early", async () => { + const prior = process.env.ALTIMATE_OFFLINE + const priorPath = process.env.PATH + const dir = path.join(Global.Path.cache, "packages", Npm.sanitize("@vue/language-server")) + const bin = path.join(dir, "node_modules", ".bin", "vue-language-server") + await fs.mkdir(path.dirname(bin), { recursive: true }) + await fs.writeFile(bin, `#!${process.execPath}\nprocess.exit(0)\n`, { mode: 0o755 }) + const flags = { disableLspDownload: true } as RuntimeFlags.Info + const ctx = { directory: dir, worktree: dir, project: {} } as InstanceContext + const which = spyOn(Npm, "which") + try { + process.env.PATH = "" + process.env.ALTIMATE_OFFLINE = "1" + const handle = await Vue.spawn(dir, ctx, flags) + expect(handle).toBeDefined() + expect(which).toHaveBeenCalledWith("@vue/language-server") + expect(await new Promise((resolve, reject) => { + handle!.process.once("error", reject) + handle!.process.once("exit", (code) => resolve(code)) + })).toBe(0) + which.mockClear() + process.env.ALTIMATE_OFFLINE = "0" + expect(await Vue.spawn(dir, ctx, flags)).toBeUndefined() + expect(which).not.toHaveBeenCalled() + } finally { + which.mockRestore() + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + if (priorPath === undefined) delete process.env.PATH + else process.env.PATH = priorPath + await fs.rm(dir, { recursive: true, force: true }) + } +}) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts new file mode 100644 index 0000000000..dea7a1a2fa --- /dev/null +++ b/packages/opencode/test/mcp/offline.test.ts @@ -0,0 +1,177 @@ +// altimate_change - new file +import { expect, test } from "bun:test" +import path from "node:path" +import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { Effect, Layer } from "effect" +import { Offline } from "../../src/config/offline" +import { MCP } from "../../src/mcp" +import { provideTmpdirInstance } from "../fixture/fixture" +import { testEffect } from "../lib/effect" + +const mcpTest = testEffect(MCP.defaultLayer.pipe(Layer.provideMerge(CrossSpawnSpawner.defaultLayer))) + +test("the offline config module self-exports before its imports", async () => { + const source = await Bun.file(new URL("../../src/config/offline.ts", import.meta.url)).text() + expect(source.match(/^(?:export \* as Offline from "\.\/offline"|import .*)$/m)?.[0]).toBe( + 'export * as Offline from "./offline"', + ) +}) + +test("the OAuth flow stays in the existing lifecycle marker", async () => { + const source = await Bun.file(new URL("../../src/mcp/index.ts", import.meta.url)).text() + const start = source.indexOf("// altimate_change start — a flow belongs to a lifecycle call") + const end = source.indexOf("// altimate_change end", start) + expect(start).toBeGreaterThan(-1) + const block = source.slice(start, end) + expect(block).toContain('const beginAuth = Effect.fn("MCP.beginAuth")') + expect(block.match(/\/\/ altimate_change start/g)).toHaveLength(1) +}) + +mcpTest.live("offline MCP auth refuses both entry points without contacting the server", () => + Effect.gen(function* () { + let requests = 0 + using server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch() { + requests++ + return new Response(null, { status: 500 }) + }, + }) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const mcp = yield* MCP.Service + for (const call of [Effect.asVoid(mcp.startAuth("oauth")), Effect.asVoid(mcp.authenticate("oauth"))]) { + const refusal = yield* call.pipe( + Effect.catchDefect((error) => Effect.succeed(error instanceof Error ? error.message : undefined)), + ) + expect(refusal).toBe("Authenticate MCP servers while online.") + } + }), + { config: { mcp: { oauth: { type: "remote", url: server.url.href, enabled: false } } } }, + ) + expect(requests).toBe(0) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), + 30_000, +) + +test("loopback checks accept only literal local addresses", () => { + for (const url of ["http://localhost:3000/mcp", "https://127.0.0.1/mcp", "http://[::1]:3000/mcp"]) + expect(Offline.isLocalURL(url)).toBe(true) + for (const url of ["https://example.com/mcp", "http://localhost.example.com", "http://192.168.0.1/mcp", "file://localhost/mcp", "http://localhost@evil.test/mcp", "invalid"]) + expect(Offline.isLocalURL(url)).toBe(false) + for (const host of ["localhost", "127.4.5.6", "::1", "[::1]"]) expect(Offline.isLoopbackHost(host)).toBe(true) + for (const host of ["localhost.evil.test", "10.0.0.1", "0.0.0.0", "", undefined]) expect(Offline.isLoopbackHost(host)).toBe(false) +}) + +// start() replaces the process-wide fetch, so it runs in its own process. +test("the fetch guard allows loopback, refuses everything else and keeps the user's proxy settings", async () => { + const module = path.resolve(import.meta.dir, "../../src/config/offline.ts") + const script = ` + const { Offline } = await import(${JSON.stringify(module)}) + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: (request) => { + const path = new URL(request.url).pathname + if (path === "/local-redirect") return Response.redirect(new URL("/", request.url).href, 307) + if (path === "/remote-redirect") return Response.redirect("https://example.com/", 302) + if (path === "/see-other") return Response.redirect(new URL("/method", request.url).href, 303) + if (path === "/method") return new Response(request.method + "|" + (request.headers.get("content-type") ?? "")) + if (path === "/hop") return Response.redirect("http://localhost:" + new URL(request.url).port + "/auth", 307) + if (path === "/auth") return new Response(request.headers.get("authorization") ?? "none") + if (path === "/loop") return Response.redirect(new URL("/loop", request.url).href, 302) + return new Response("local") + } }) + Offline.start() + const local = await (await fetch(server.url)).text() + const followed = await (await fetch(new URL("/local-redirect", server.url))).text() + const away = await fetch(new URL("/remote-redirect", server.url)).then(() => "sent", (error) => error.message) + const seeOther = await (await fetch(new URL("/see-other", server.url), { method: "POST", body: "x", headers: { "content-type": "text/plain" } })).text() + const auth = await (await fetch(new URL("/hop", server.url), { headers: { authorization: "Bearer t" } })).text() + const loop = await fetch(new URL("/loop", server.url)).then(() => "followed", (error) => error.message) + const manual = (await fetch(new Request(new URL("/local-redirect", server.url), { redirect: "manual" }))).status + const remote = await fetch("https://example.com/").then(() => "sent", (error) => error.message) + server.stop(true) + console.log(JSON.stringify({ local, followed, away, seeOther, manual, auth, loop, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_PROXY, process.env.NO_PROXY, process.env.no_proxy] }))` + const proc = Bun.spawn([process.execPath, "-e", script], { + env: { PATH: process.env.PATH, HOME: process.env.HOME, HTTPS_PROXY: "http://proxy.example:3128", NO_PROXY: "corp.example", no_proxy: "lower.example" }, + stdout: "pipe", + stderr: "pipe", + }) + const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]) + expect({ code: await proc.exited, stderr }).toMatchObject({ code: 0 }) + expect(JSON.parse(stdout.trim().split("\n").at(-1)!)).toEqual({ + local: "local", + followed: "local", + away: "Offline mode blocked a redirect away from this machine.", + seeOther: "GET|", + manual: 307, + auth: "none", + loop: "Offline mode stopped after too many local redirects.", + remote: "Offline mode allows network requests only to the configured model endpoint.", + env: ["1", "http://proxy.example:3128", "corp.example,lower.example,localhost,127.0.0.1,[::1],0.0.0.0", "corp.example,lower.example,localhost,127.0.0.1,[::1],0.0.0.0"], + }) +}) + +test.each(["NO_PROXY", "no_proxy"])("offline copies the %s wildcard to both proxy exclusions", async (wildcard) => { + const module = path.resolve(import.meta.dir, "../../src/config/offline.ts") + const script = ` + const { Offline } = await import(${JSON.stringify(module)}) + Offline.start() + console.log(JSON.stringify([process.env.NO_PROXY, process.env.no_proxy]))` + const proc = Bun.spawn([process.execPath, "-e", script], { + env: { PATH: process.env.PATH, HOME: process.env.HOME, NO_PROXY: "corp.example", no_proxy: "lower.example", [wildcard]: "*" }, + stdout: "pipe", + stderr: "pipe", + }) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect({ code, stderr, exclusions: stdout.trim() }).toEqual({ code: 0, stderr: "", exclusions: '["*","*"]' }) +}) + +test("ALTIMATE_OFFLINE accepts the usual off spellings", () => { + const previous = process.env.ALTIMATE_OFFLINE + try { + for (const value of ["", "0", "false", "off", "NO", " Off "]) { + process.env.ALTIMATE_OFFLINE = value + expect(Offline.enabled()).toBe(false) + } + for (const value of ["1", "true", "yes", "on"]) { + process.env.ALTIMATE_OFFLINE = value + expect(Offline.enabled()).toBe(true) + } + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } +}) + +test("model fetch stays below the configured base URL", async () => { + const fetch = Offline.modelFetch("http://model.test:9000/v1") + for (const url of ["http://model.test:9000/v2/chat", "http://model.test:9000/v1beta", "https://model.test:9000/v1/chat", "http://other.test:9000/v1/chat"]) + await expect(fetch(url)).rejects.toThrow("Offline mode blocked a request outside the configured model endpoint.") + expect(() => Offline.modelFetch(undefined)).toThrow("explicit baseURL") + expect(() => Offline.modelFetch("file:///tmp/model")).toThrow("HTTP(S)") +}) + +test("the startup check finds the setting in a project file, even written with a JSON escape", async () => { + const fs = await import("node:fs/promises") + const os = await import("node:os") + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "offline-optin-")) + try { + expect(await Offline.optedIn(dir)).toBe(false) + await fs.writeFile(path.join(dir, "opencode.json"), '{"off\\u006cine": true}') + expect(await Offline.optedIn(dir)).toBe(true) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) diff --git a/packages/opencode/test/project/vcs.test.ts b/packages/opencode/test/project/vcs.test.ts index 21620adaf0..3f2bd7c717 100644 --- a/packages/opencode/test/project/vcs.test.ts +++ b/packages/opencode/test/project/vcs.test.ts @@ -157,6 +157,33 @@ describe("Vcs", () => { }) describe("Vcs diff", () => { + worktreeIt.instance( + "offline VCS shows local changes and refuses remote Git operations", + Effect.gen(function* () { + const { directory } = yield* TestInstance + yield* write(path.join(directory, "data.txt"), "before\n") + yield* git(directory, ["add", "."]) + yield* git(directory, ["commit", "-m", "test offline fixture"]) + yield* write(path.join(directory, "data.txt"), "after\n") + const prior = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const vcs = yield* Vcs.Service + expect(yield* vcs.status()).not.toEqual([]) + expect(yield* vcs.diff("git")).not.toEqual([]) + const result = yield* Git.Service.use((git) => git.run( + ["-c", "core.quotepath=false", "fetch", "https://unreachable.invalid/repo"], + { cwd: directory }, + )) + expect(result.stderr.toString()).toContain("Git remote operations require an online run.") + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } + }), + { git: true }, + ) + afterEach(async () => { await disposeAllInstances() }) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index bbe2af3718..18b3aeaba8 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect } from "bun:test" import path from "path" +import { chmod, rename } from "node:fs/promises" import { FSUtil } from "@opencode-ai/core/fs-util" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Cause, Deferred, Effect, Exit, Fiber, Layer, Result } from "effect" @@ -82,6 +83,87 @@ const gitResult = Effect.fn("WorktreeTest.gitResult")(function* (cwd: string, ar describe("Worktree", () => { afterEach(() => disposeAllInstances()) + wintest( + "creates, resets, and removes a local worktree offline", + Effect.gen(function* () { + // The base branch is a cached remote-tracking ref whose remote cannot be reached: online, reset would fetch it. + const { directory } = yield* TestInstance + const run = (args: string[]) => { + const result = Bun.spawnSync(["git", ...args], { cwd: directory, stdout: "pipe", stderr: "pipe" }) + if (result.exitCode !== 0) throw new Error(result.stderr.toString()) + return result.stdout.toString().trim() + } + const branch = run(["rev-parse", "--abbrev-ref", "HEAD"]) + run(["remote", "add", "origin", path.join(directory, "missing-remote.git")]) + run(["update-ref", `refs/remotes/origin/${branch}`, "HEAD"]) + run(["symbolic-ref", "refs/remotes/origin/HEAD", `refs/remotes/origin/${branch}`]) + // A submodule the new worktree has not cloned, whose source is gone: online, reset would try to clone it. + const lib = path.join(directory, "lib-source") + const nested = path.join(directory, "nested-source") + const commit = ["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false", "commit", "-q"] + run(["init", "-q", lib]) + run(["init", "-q", nested]) + const fs = yield* FSUtil.Service + yield* fs.writeWithDirs(path.join(nested, "tracked"), "clean") + run(["-C", nested, "add", "tracked"]) + run(["-C", nested, ...commit, "-m", "nested"]) + run(["-C", lib, "-c", "protocol.file.allow=always", "submodule", "add", "-q", nested, "nested"]) + run(["-C", lib, ...commit, "-m", "lib"]) + run(["-c", "protocol.file.allow=always", "submodule", "add", "-q", lib, "lib"]) + run([...commit, "-m", "add submodule"]) + run(["update-ref", `refs/remotes/origin/${branch}`, "HEAD"]) + yield* Effect.promise(() => rename(lib, `${lib}-hidden`)) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const svc = yield* Worktree.Service + yield* withCreatedWorktree({ name: "offline" }, ({ info }) => + Effect.gen(function* () { + const file = path.join(info.directory, "offline-change") + yield* fs.writeWithDirs(file, "fixture") + expect(yield* svc.reset({ directory: info.directory })).toBe(true) + expect(yield* fs.existsSafe(file)).toBe(false) + expect(yield* fs.existsSafe(path.join(info.directory, "lib", ".git"))).toBe(false) + + yield* Effect.promise(() => rename(`${lib}-hidden`, lib)) + run(["-C", info.directory, "-c", "protocol.file.allow=always", "submodule", "update", "--init", "--recursive"]) + const nestedWorktree = path.join(info.directory, "lib", "nested") + const nestedCommit = run(["-C", nestedWorktree, "rev-parse", "HEAD"]) + const tracked = path.join(nestedWorktree, "tracked") + yield* fs.writeWithDirs(tracked, "modified") + expect(yield* svc.reset({ directory: info.directory })).toBe(true) + expect(run(["-C", nestedWorktree, "rev-parse", "HEAD"])).toBe(nestedCommit) + expect(yield* Effect.promise(() => Bun.file(tracked).text())).toBe("clean") + + const bin = path.join(directory, "test-bin") + const realGit = Bun.which("git")! + const previousPath = process.env.PATH + yield* fs.writeWithDirs( + path.join(bin, "git"), + `#!/bin/sh\nif [ "$1 $2" = "submodule status" ]; then\n echo 'fixture: submodule status failed' >&2\n exit 1\nfi\nexec ${JSON.stringify(realGit)} "$@"\n`, + ) + yield* Effect.promise(() => chmod(path.join(bin, "git"), 0o755)) + process.env.PATH = `${bin}:${previousPath ?? ""}` + try { + const result = yield* Effect.result(svc.reset({ directory: info.directory })) + expect(result).toMatchObject({ + _tag: "Failure", + failure: { _tag: "WorktreeResetFailedError", message: "fixture: submodule status failed\n" }, + }) + } finally { + if (previousPath === undefined) delete process.env.PATH + else process.env.PATH = previousPath + } + }), + ) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), + { git: true }, + ) + describe("makeWorktreeInfo", () => { it.instance( "returns info with name, branch, and directory", diff --git a/packages/opencode/test/provider/provider.test.ts b/packages/opencode/test/provider/provider.test.ts index 50d6df5f36..79a08af5be 100644 --- a/packages/opencode/test/provider/provider.test.ts +++ b/packages/opencode/test/provider/provider.test.ts @@ -1429,6 +1429,49 @@ test("getSmallModel respects config small_model override", async () => { }) }) +// altimate_change start — offline small model stays on the configured endpoint +for (const [smallModel, expected] of [ + ["anthropic/claude-sonnet-4-20250514", undefined], + ["local/small", "small"], +] as const) { + test(`offline getSmallModel honors ${smallModel} only on the configured endpoint`, async () => { + await using tmp = await tmpdir({ + init: async (dir) => { + await Bun.write( + path.join(dir, "opencode.json"), + JSON.stringify({ + $schema: "https://altimate.ai/config.json", + model: "local/main", + small_model: smallModel, + provider: { + local: { + npm: "@ai-sdk/openai-compatible", + options: { baseURL: "http://127.0.0.1:9/v1", apiKey: "local" }, + models: { main: { name: "Main" }, small: { name: "Small" } }, + }, + }, + }), + ) + }, + }) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + await provideProviderTestInstance({ + directory: tmp.path, + fn: async () => { + const model = await Provider.getSmallModel(ProviderID.make("local")) + expect(model?.id === undefined ? undefined : String(model.id)).toBe(expected) + }, + }) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) +} +// altimate_change end + test("provider.sort prioritizes preferred models", () => { const models = [ { id: "random-model", name: "Random" }, diff --git a/packages/opencode/test/skill/discovery.test.ts b/packages/opencode/test/skill/discovery.test.ts index f1a455d2d1..8765134cb1 100644 --- a/packages/opencode/test/skill/discovery.test.ts +++ b/packages/opencode/test/skill/discovery.test.ts @@ -65,6 +65,17 @@ describe("Discovery.pull", () => { }), ) + // altimate_change start — with offline mode off, the skill cache layout is unchanged + it.live("caches each skill directly under cache/skills/", () => + Effect.gen(function* () { + const discovery = yield* Discovery.Service + const dirs = yield* discovery.pull(CLOUDFLARE_SKILLS_URL) + expect(dirs.length).toBeGreaterThan(0) + for (const dir of dirs) expect(path.dirname(dir)).toBe(cacheDir) + }), + ) + // altimate_change end + it.live("url without trailing slash works", () => Effect.gen(function* () { const fsys = yield* FSUtil.Service diff --git a/packages/opencode/test/snapshot/snapshot.test.ts b/packages/opencode/test/snapshot/snapshot.test.ts index 208bc0e169..daf82e09cb 100644 --- a/packages/opencode/test/snapshot/snapshot.test.ts +++ b/packages/opencode/test/snapshot/snapshot.test.ts @@ -100,6 +100,32 @@ const withGitConfigGlobal = (config: string, self: Effect.Effect diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index fa79b98778..775ecd1a56 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1022,3 +1022,23 @@ describe("safeSpawnSync", () => { expect(result).not.toBeNull() }) }) + +// altimate_change start — offline mode does not run `dbt --version`, which asks PyPI for the latest release +test.skipIf(process.platform === "win32")("offline data tool detection finds dbt on PATH without running it", async () => { + const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "offline-scan-")) + const previous = { path: process.env.PATH, offline: process.env.ALTIMATE_OFFLINE } + try { + const ran = path.join(dir, "ran") + await fsp.writeFile(path.join(dir, "dbt"), `#!/bin/sh\ntouch "${ran}"\necho "dbt 1.9.3"\n`, { mode: 0o755 }) + process.env.PATH = `${dir}${path.delimiter}${previous.path}` + process.env.ALTIMATE_OFFLINE = "1" + expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true }) + expect(await fsp.stat(ran).then(() => true, () => false)).toBe(false) + } finally { + process.env.PATH = previous.path + if (previous.offline === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous.offline + await fsp.rm(dir, { recursive: true, force: true }) + } +}) +// altimate_change end diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index 02d1b7ef86..dff4bc494b 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -1,5 +1,6 @@ import { describe, test, expect } from "bun:test" import { tmpdir } from "../fixture/fixture" +import { gitCommandUsesNetwork } from "@opencode-ai/core/git" import { git } from "../../src/util/git" describe("git() utility", () => { @@ -48,4 +49,45 @@ describe("git() utility", () => { expect(result.exitCode).not.toBe(0) expect(result.stdout.length).toBe(0) }) + + // altimate_change start — offline mode refuses remote Git commands and keeps local ones + test("offline refuses remote commands without spawning git and still runs local ones", async () => { + await using tmp = await tmpdir({ git: true }) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const fetched = await git(["fetch", "origin"], { cwd: tmp.path }) + expect(fetched.exitCode).toBe(1) + expect(fetched.stdout.length).toBe(0) + expect(fetched.stderr.toString()).toContain("Git remote operations require an online run.") + const local = await git(["rev-parse", "--is-inside-work-tree"], { cwd: tmp.path }) + expect(local.text().trim()).toBe("true") + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) + + test("offline treats submodule clones, LFS transfers and remote archives as network commands", () => { + for (const args of [["submodule", "update", "--init"], ["submodule", "update", "--recursive", "--no-fetch"], ["submodule", "add", "url"], ["remote", "add", "-f", "o", "url"], ["remote", "prune", "origin"], ["submodule", "--quiet", "update"], ["submodule", "foreach", "git", "fetch"], ["remote", "-v", "update"], ["remote", "set-head", "origin", "--auto"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) + expect(gitCommandUsesNetwork(args)).toBe(true) + for (const args of [["submodule", "foreach", "git", "status"], ["remote", "add", "o", "url"], ["lfs", "ls-files"], ["archive", "HEAD"], ["status"], ["remote", "show", "-n", "origin"]]) + expect(gitCommandUsesNetwork(args)).toBe(false) + }) + + test("offline permits only literal local submodule foreach commands", () => { + for (const args of [ + ["git", "remote", "update"], + ["git submodule update --init"], + ['git fet"ch"'], + ["git lfs fetch"], + ["git reset --hard && git fetch"], + ]) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--recursive", "--quiet", ...args])).toBe(true) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--recursive", "git", "reset", "--hard"])).toBe(false) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--recursive", "git clean -fdx"])).toBe(false) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--quiet", "git status"])).toBe(false) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--quiet", "--recursive", "git status"])).toBe(false) + }) + // altimate_change end })