From 8543a5be66e58bf0ce437ee8505c8d3d4ae21071 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:38:32 -0800 Subject: [PATCH 01/72] feat: add model-only offline mode --- docs/docs/configure/config.md | 13 ++ docs/mcp-workspaces.md | 2 + packages/core/src/models-dev.ts | 11 +- packages/core/src/npm.ts | 2 + packages/core/src/observability/otlp.ts | 4 +- packages/core/src/v1/config/config.ts | 5 + packages/core/test/models.test.ts | 20 +++ .../opencode/src/altimate/debug/collect.ts | 6 + .../altimate/native/connections/registry.ts | 11 ++ .../opencode/src/altimate/telemetry/index.ts | 5 + .../tools/warehouse-install-driver.ts | 13 ++ .../src/altimate/workspace/engine-offer.ts | 6 + .../src/altimate/workspace/engine-overlay.ts | 7 +- .../src/altimate/workspace/identity.ts | 3 +- .../src/altimate/workspace/skill-sync.ts | 4 + packages/opencode/src/bun/index.ts | 6 + packages/opencode/src/bun/registry.ts | 6 + packages/opencode/src/cli/cmd/models.ts | 7 +- .../src/cli/cmd/serve-upgrade-check.ts | 2 + packages/opencode/src/cli/network.ts | 7 +- packages/opencode/src/cli/upgrade.ts | 6 + packages/opencode/src/config/config.ts | 30 +++- packages/opencode/src/config/offline.ts | 113 +++++++++++++ packages/opencode/src/config/tui.ts | 9 +- packages/opencode/src/index.ts | 17 ++ packages/opencode/src/installation/index.ts | 9 ++ packages/opencode/src/lsp/index.ts | 7 +- packages/opencode/src/mcp/index.ts | 6 + packages/opencode/src/plugin/index.ts | 6 + packages/opencode/src/provider/models.ts | 10 +- packages/opencode/src/provider/provider.ts | 40 ++++- packages/opencode/src/session/instruction.ts | 6 + packages/opencode/src/session/prompt.ts | 11 +- packages/opencode/src/share/share-next.ts | 19 ++- packages/opencode/src/skill/discovery.ts | 6 + packages/opencode/src/tool/registry.ts | 11 ++ packages/opencode/src/worktree/index.ts | 6 + ...arehouse-install-driver-permission.test.ts | 19 +++ .../opencode/test/cli/run/offline.test.ts | 151 ++++++++++++++++++ .../test/installation/upgrade.test.ts | 21 +++ 40 files changed, 617 insertions(+), 26 deletions(-) create mode 100644 packages/opencode/src/config/offline.ts create mode 100644 packages/opencode/test/cli/run/offline.test.ts diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 737d0e03ef..76e00a9201 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,15 @@ 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 + +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a local config file such as `~/.config/altimate-code/altimate-code.json` or `.altimate-code/altimate-code.json` in the project. A local opt-in applies for the lifetime of the CLI process and its workers. + +Before going offline: + +1. Configure the model locally, including its `provider/model` ID and the provider's explicit `options.baseURL`. For a self-hosted OpenAI-compatible server, use the bundled `@ai-sdk/openai-compatible` provider. Define the model in your provider config if it is absent from the bundled or cached model catalog. +2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice if the snapshot is unavailable. +3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Network warehouse connections and automatic driver installs are disabled in offline mode. + +Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. It also limits the tool catalog to local operations. For example, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Install `ripgrep` ahead of time if you need file search on a fresh host. diff --git a/docs/mcp-workspaces.md b/docs/mcp-workspaces.md index f0bd32ab30..e8b3a163cf 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/models-dev.ts b/packages/core/src/models-dev.ts index 3f9f670374..a854c6ccb5 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -201,7 +201,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 (process.env.ALTIMATE_OFFLINE === "1" || 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 +219,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 (process.env.ALTIMATE_OFFLINE === "1") return + // altimate_change end if (!force && (yield* fresh())) return yield* Effect.scoped( Effect.gen(function* () { @@ -234,7 +239,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 (process.env.ALTIMATE_OFFLINE !== "1" && !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..b14eb213a8 100644 --- a/packages/core/src/npm.ts +++ b/packages/core/src/npm.ts @@ -126,6 +126,7 @@ export const layer = Layer.effect( return resolveEntryPoint(name, path.join(dir, "node_modules", name)) } + if (process.env.ALTIMATE_OFFLINE === "1") return yield* new InstallFailedError({ add: [pkg], dir }) const tree = yield* reify({ dir, add: [pkg] }) const first = tree.edgesOut.values().next().value?.to if (!first) { @@ -137,6 +138,7 @@ export const layer = Layer.effect( }, Effect.scoped) const install: Interface["install"] = Effect.fn("Npm.install")(function* (dir, input) { + if (process.env.ALTIMATE_OFFLINE === "1") return const canWrite = yield* afs.access(dir, { writable: true }).pipe( Effect.as(true), Effect.orElseSucceed(() => false), diff --git a/packages/core/src/observability/otlp.ts b/packages/core/src/observability/otlp.ts index dd99ebc143..abdbac3439 100644 --- a/packages/core/src/observability/otlp.ts +++ b/packages/core/src/observability/otlp.ts @@ -48,12 +48,12 @@ export function resource(): { serviceName: string; serviceVersion: string; attri } export function loggers() { - if (!endpoint) return [] + if (process.env.ALTIMATE_OFFLINE === "1" || !endpoint) return [] return [OtlpLogger.make({ url: `${endpoint}/v1/logs`, resource: resource(), headers })] } export async function tracingLayer() { - if (!endpoint) return Layer.empty + if (process.env.ALTIMATE_OFFLINE === "1" || !endpoint) return Layer.empty 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/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/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/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 2d35a56241..d4fb3e174b 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 { offline } from "@/config/offline" +// 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 @@ -310,6 +313,9 @@ export async function probe( opts: { proxy?: boolean; timeoutMs?: number } = {}, deps: ProbeDeps = defaultProbeDeps, ): Promise { + // altimate_change start — skip network work in offline mode + if (offline()) return { target, host, ok: false, detail: "Skipped in offline mode", ms: 0 } + // altimate_change end const timeoutMs = opts.timeoutMs ?? NETWORK_TIMEOUT_MS const started = Date.now() const deadline = AbortSignal.timeout(timeoutMs) diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 98d455d648..20038738f3 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline } from "@/config/offline" +// altimate_change end /** * ConnectionRegistry — manages database connections. * @@ -423,6 +426,11 @@ async function createConnector( attempt: Attempt, isCurrent: () => boolean, ): Promise { + // altimate_change end + // altimate_change start — skip network work in offline mode + if (offline()) { + throw new Error("Offline mode disables warehouse connections.") + } // altimate_change end const driverPath = DRIVER_MAP[config.type.toLowerCase()] if (!driverPath) { @@ -663,6 +671,9 @@ export function names(): string[] { /** Get a connector instance (creates lazily). */ export async function get(name: string): Promise { // altimate_change start — captured once, so a connect that finishes later lands in the project that started it + // altimate_change start — skip network work in offline mode + if (offline()) throw new Error("Offline mode disables warehouse connections.") + // altimate_change end const s = ensureLoaded() const { configs, connectors, tunnels, pending } = s // altimate_change end diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5df4d68dc3..ba270bcc4b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline } from "@/config/offline" +// altimate_change end import { Config } from "@/config/config" import { Flag } from "@/flag/flag" import { InstallationVersion } from "@opencode-ai/core/installation/version" @@ -2516,6 +2519,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 (offline()) 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 @@ -2973,6 +2977,7 @@ export namespace Telemetry { // altimate_change end export function track(event: Event) { + if (offline()) return // Before init completes: buffer (flushed once init enables, or cleared if disabled). // After init completed and disabled telemetry: drop silently. if (initDone && !enabled) 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..e479203891 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()) { + 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/engine-offer.ts b/packages/opencode/src/altimate/workspace/engine-offer.ts index 5d2b83983f..c489d40838 100644 --- a/packages/opencode/src/altimate/workspace/engine-offer.ts +++ b/packages/opencode/src/altimate/workspace/engine-offer.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline } from "@/config/offline" +// altimate_change end // altimate_change - new file // // The install offer for a workspace whose engine is missing or too old. @@ -80,6 +83,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()) return null const binding = syncInternals.resolveBinding ? await syncInternals.resolveBinding(directory) : await readLocalBinding(directory).catch((err) => { @@ -232,6 +236,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()) 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 +372,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()) 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..dd8dc18d55 100644 --- a/packages/opencode/src/altimate/workspace/engine-overlay.ts +++ b/packages/opencode/src/altimate/workspace/engine-overlay.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline } from "@/config/offline" +// altimate_change end // altimate_change - new file // // The workspace engine overlay. @@ -230,7 +233,7 @@ export async function overlay( state.managed = opts.managed === true state.linked = null try { - if (!isEnabled() || isServe()) { + if (offline() || !isEnabled() || isServe()) { state.current = null return } @@ -499,7 +502,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() || !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..6c916d27da 100644 --- a/packages/opencode/src/altimate/workspace/identity.ts +++ b/packages/opencode/src/altimate/workspace/identity.ts @@ -1,3 +1,4 @@ +import { offline } from "@/config/offline" // altimate_change - new file // // Model-facing statement of Altimate Workspace identity: which workspace (if any) this @@ -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() || !isEnabled()) return "" try { const directory = Instance.directory const scope = await accountScope() diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index efa1dd7d44..cbb245dd6f 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline } from "@/config/offline" +// altimate_change end // altimate_change - new file // // Mirror a bound workspace's custom skill bundles onto disk, where the existing @@ -1240,6 +1243,7 @@ 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 { + if (offline()) 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..9709e068a0 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" @@ -51,6 +54,9 @@ export namespace BunProc { ) export async function install(pkg: string, version = "latest") { + // altimate_change start — prevent package installs in offline mode + if (offline()) throw new Error("Offline mode disables package installation.") + // altimate_change end // Use lock to ensure only one install at a time using _ = await Lock.write("bun-install") diff --git a/packages/opencode/src/bun/registry.ts b/packages/opencode/src/bun/registry.ts index 90b7bbf5db..ab1870e394 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()) 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/models.ts b/packages/opencode/src/cli/cmd/models.ts index b17293d333..939a836d2e 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,9 @@ 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()) { + // 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..f8bf0545a1 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()) 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/network.ts b/packages/opencode/src/cli/network.ts index 3be88fe037..a07fd41949 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,9 @@ 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 mdns = !offline() && (mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns)) + // 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/upgrade.ts b/packages/opencode/src/cli/upgrade.ts index 81bfdb0e7f..8d5d1c9eed 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()) 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..25cd116df6 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, startOfflineMode } 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" @@ -499,6 +502,9 @@ export const layer = Layer.effect( const loadInstanceState = Effect.fn("Config.loadInstanceState")( function* (ctx: InstanceContext) { + // altimate_change start — skip network work in offline mode + yield* Effect.promise(() => startOfflineMode(ctx.directory)) + // altimate_change end const auth = yield* authSvc.all().pipe(Effect.orDie) let result: Info = {} @@ -559,6 +565,9 @@ export const layer = Layer.effect( } for (const [key, value] of Object.entries(auth)) { + // altimate_change start — skip well-known network config in offline mode + if (offline()) continue + // altimate_change end if (value.type === "wellknown") { const url = key.replace(/\/+$/, "") authEnv[value.key] = value.token @@ -683,9 +692,11 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } - const activeAccount = Option.getOrUndefined( - yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none()))), - ) + // altimate_change start — skip account network config in offline mode + const activeAccount = offline() + ? undefined + : Option.getOrUndefined(yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none())))) + // altimate_change end if (activeAccount?.active_org_id) { const accountID = activeAccount.id const orgID = activeAccount.active_org_id @@ -773,7 +784,7 @@ export const layer = Layer.effect( // under any earlier directory. Keep the PURE skip and retain fibers for waitForDependencies. const deps: Fiber.Fiber[] = [] for (const dir of directories) { - if (ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { + if (!offline() && ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { const dep = yield* npmSvc .install(dir, { add: [ @@ -835,6 +846,13 @@ export const layer = Layer.effect( } } + // altimate_change start — disable runtime sharing in offline mode + if (offline()) { + result.offline = true + result.share = "disabled" + result.formatter = false + } + // altimate_change end if (result.autoshare === true && !result.share) { result.share = "auto" } @@ -851,7 +869,7 @@ export const layer = Layer.effect( // may not yet be declared in the ConfigV1 experimental schema. const autoMcpDiscovery = (result.experimental as { auto_mcp_discovery?: boolean } | undefined) ?.auto_mcp_discovery - if (!Flag.OPENCODE_DISABLE_PROJECT_CONFIG && autoMcpDiscovery !== false) { + if (!offline() && !Flag.OPENCODE_DISABLE_PROJECT_CONFIG && autoMcpDiscovery !== false) { const { discoverExternalMcp, setDiscoveryResult, driftFields, setConfigDrift, discoveredSource } = yield* Effect.promise( () => import("../mcp/discover"), @@ -885,7 +903,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() && !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..b324c8a9f5 --- /dev/null +++ b/packages/opencode/src/config/offline.ts @@ -0,0 +1,113 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { parse } from "jsonc-parser" +import * as Effect from "effect/Effect" +import { Flag, env } 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" + +const configNames = ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"] + +export function offline() { + return process.env.ALTIMATE_OFFLINE === "1" +} + +async function localOptIn(directory: string) { + // The switch is an opt-in from any local config source. Read just this + // key so remote credentials and unrelated substitutions cannot affect it. + const enabled = (text: string | undefined) => text !== undefined && parse(text)?.offline === true + if (enabled(env("OPENCODE_CONFIG_CONTENT"))) return true + 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((sources) => sources.flat())), + ConfigPaths.directories(directory, worktree), + ]).pipe(Effect.provide(FSUtil.defaultLayer)), + ) + const files = [ + ...projectFiles, + ...[...dirs, ConfigManaged.managedConfigDir()].flatMap((dir) => configNames.map((name) => path.join(dir, name))), + path.join(Global.Path.config, "config.json"), + Flag.OPENCODE_CONFIG, + ] + for (const file of files) { + if (file && enabled(await fs.readFile(file, "utf8").catch(() => undefined))) return true + } + return enabled((await ConfigManaged.readManagedPreferences().catch(() => undefined))?.text) +} + +let networkFetch: typeof fetch | undefined + +export async function startOfflineMode(directory: string, model?: string) { + if (!offline() && !(await localOptIn(directory))) return + // Workers and core services must see the same policy before constructing + // their layers. Once enabled, keep it for the lifetime of the process. + process.env.ALTIMATE_OFFLINE = "1" + process.env.GIT_NO_LAZY_FETCH = "1" + if (model) process.env.ALTIMATE_OFFLINE_MODEL = model + if (networkFetch) return + networkFetch = globalThis.fetch + globalThis.fetch = Object.assign( + async () => { + throw new Error("Offline mode allows network requests only to the configured model endpoint.") + }, + { preconnect: () => {} }, + ) +} + +export function offlineProvider( + config: Pick, +) { + const model = process.env.ALTIMATE_OFFLINE_MODEL ?? config.model + if (model) return model.split("/")[0] + const candidates = Object.entries(config.provider ?? {}).filter( + ([id, provider]) => + typeof provider.options?.baseURL === "string" && + (!config.enabled_providers || config.enabled_providers.includes(id)) && + !config.disabled_providers?.includes(id), + ) + return candidates.length === 1 ? candidates[0][0] : undefined +} + +export function offlineModelFetch(baseURL: string | undefined): typeof fetch { + if (!baseURL) throw new Error("Offline mode requires a model provider with an explicit baseURL.") + const endpoint = new URL(baseURL) + if (!["http:", "https:"].includes(endpoint.protocol)) + throw new Error("Offline mode requires an HTTP(S) model endpoint.") + return Object.assign( + async (input: Parameters[0], init?: Parameters[1]) => { + const target = new URL(input instanceof Request ? input.url : input.toString()) + if (target.origin !== endpoint.origin) + throw new Error("Offline mode blocked a request outside the configured model endpoint.") + return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error", proxy: "" }) + }, + { preconnect: () => {} }, + ) +} + +let warned = false + +export async function warnOffline(hasSnapshot: boolean) { + if (warned) return + warned = true + const message = hasSnapshot + ? "Using cached workspace skills." + : "No usable workspace skill snapshot. Run altimate-code workspace refresh while online." + const { isHeadless } = await import("@/altimate/workspace/engine-seams") + const { notify, printLine } = await import("@/altimate/workspace/engine-probes") + if (isHeadless()) printLine(`Offline mode: ${message}`) + else await notify({ title: "Offline mode", message, variant: hasSnapshot ? "info" : "warning" }) +} diff --git a/packages/opencode/src/config/tui.ts b/packages/opencode/src/config/tui.ts index f8319951b9..9f4a76bff7 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" @@ -257,7 +260,9 @@ const loadState = Effect.fn("TuiConfig.loadState")(function* (ctx: { directory: return { config: result, - pluginOrigins: acc.plugin_origins, + // altimate_change start — skip local and installed TUI plugins in offline mode + pluginOrigins: offline() ? [] : acc.plugin_origins, + // altimate_change end dirs: result.plugin?.length ? dirs : [], } }) @@ -275,7 +280,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() && ConfigPlugin.shouldInstallDependencies(dir, data.config.plugin)), // altimate_change end (dir) => npm diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index f2a0152b03..182354d5cc 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline, startOfflineMode } from "@/config/offline" +// altimate_change end import yargs from "yargs" import { hideBin } from "yargs/helpers" // altimate_change start - stdin tool arguments @@ -165,6 +168,20 @@ let cli = yargs(args) if (opts.pure) { process.env.OPENCODE_PURE = "1" } + // altimate_change start — skip network work in offline mode + const command = String(opts._[0] ?? "") + const args = opts as { dir?: string; project?: string; attach?: string; model?: string } + const directory = command === "run" && !args.attach && args.dir + ? path.resolve(args.dir) + : args.project ? resolveThreadDirectory(args.project) : process.cwd() + await startOfflineMode(directory, args.model) + if (offline() && ( + ["attach", "github", "gitlab", "pr", "review", "workspace-client", "workspace-serve", "web"].includes(command) || + (command === "run" && args.attach) || + (command === "mcp" && opts._[1] === "serve") || + (["providers", "auth", "mcp", "console"].includes(command) && opts._.some((arg) => arg === "login" || arg === "auth")) + )) throw new Error("This command requires network access. Run it while online.") + // altimate_change end // altimate_change start — MCP stdio needs no banner, telemetry startup or agent initialization if (opts._[0] === "mcp" && opts._[1] === "serve") return // altimate_change end diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index af8bd64bd7..502523f98f 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 { 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 { Effect, Layer, Schema, Context, Stream } from "effect" @@ -840,6 +843,9 @@ export const layer: Layer.Layer(), diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index da8e75a1ce..60dd7c7594 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" @@ -670,6 +673,9 @@ export const layer = Layer.effect( const create = Effect.fn("MCP.create")( function* (key: string, mcp: ConfigMCPV1.Info) { + // altimate_change start — skip external MCP processes and servers in offline mode + if (offline()) return DISABLED_RESULT + // altimate_change end if (mcp.enabled === false) { return DISABLED_RESULT } diff --git a/packages/opencode/src/plugin/index.ts b/packages/opencode/src/plugin/index.ts index 7bd2e7d5c8..91310f9326 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,6 +114,9 @@ export namespace Plugin { $: Bun.$, } + // altimate_change start — skip network work in offline mode + if (offline()) return { hooks, input } + // altimate_change end for (const plugin of INTERNAL_PLUGINS) { log.info("loading internal plugin", { name: plugin.name }) const init = await plugin(input).catch((err) => { diff --git a/packages/opencode/src/provider/models.ts b/packages/opencode/src/provider/models.ts index 99aec59b3e..fe3d7f2f32 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() || 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()) 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..e876522d5e 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, offlineModelFetch, offlineProvider } 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) @@ -104,6 +107,10 @@ const FREE_TIER_HEADER_TIMEOUT_DEFAULT = 300_000 const FREE_TIER_HEADER_TIMEOUT_MIN = 1_000 // altimate_change end +// altimate_change start — HTTP-only SDKs supported without network credential discovery +const OFFLINE_SDKS = new Set(["@ai-sdk/openai-compatible", "@ai-sdk/openai", "@ai-sdk/anthropic"]) +// altimate_change end + export namespace Provider { const log = Log.create({ service: "provider" }) @@ -1392,7 +1399,21 @@ export namespace Provider { const disabled = new Set(config.disabled_providers ?? []) const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null + // altimate_change start — offline provider selection is independent of online fallback rules + const offlineProviderID = offline() ? offlineProvider(config) : undefined + // altimate_change end function isProviderAllowed(providerID: ProviderID): boolean { + // altimate_change start — require a locally configured model endpoint in offline mode + if (offline()) { + const options = config.provider?.[providerID]?.options + if ( + providerID !== offlineProviderID || + typeof options?.baseURL !== "string" || + 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,6 +2025,9 @@ 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 + if (offline()) continue + // altimate_change end if (!data) { log.error("Provider does not exist in model list " + providerID) continue @@ -2146,11 +2170,23 @@ 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 + const offlineMode = offline() + if (offlineMode) { + const config = await Config.get() + if (offlineProvider(config) !== model.providerID || typeof config.provider?.[model.providerID]?.options?.baseURL !== "string") + throw new Error("Offline mode requires a locally configured model endpoint.") + if (!OFFLINE_SDKS.has(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 ? offlineModelFetch(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() diff --git a/packages/opencode/src/session/instruction.ts b/packages/opencode/src/session/instruction.ts index acf807d2d5..24789f651a 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()) 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..14e09c6b89 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, warnOffline } from "@/config/offline" +// altimate_change end import path from "path" import { Token } from "@/util/token" import { existsSync, readFileSync, statSync } from "node:fs" @@ -475,7 +478,13 @@ 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. - if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { + if (offline()) { + const dir = Instance.directory + const { snapshotRoot, ownManifest } = await import("../altimate/workspace/skill-sync") + const snapshot = await ownManifest(dir) + await warnOffline(snapshot !== null) + if (existsSync(snapshotRoot(dir))) await refreshSkillRegistry(dir) + } else if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { const dir = Instance.directory // Mirrors `MANAGED_DIR` in ./altimate/workspace/skill-sync. Inlined // rather than imported so the opted-out path stays free of that module. diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 65d75e9c05..7528194018 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 — skip session sharing in offline mode + if (offline() || disabled) return + // altimate_change end Bus.subscribe(Session.Event.Updated, async (evt) => { await sync(evt.properties.info.id, [ { @@ -123,7 +128,9 @@ export namespace ShareNext { } export async function create(sessionID: SessionID) { - if (disabled) return { id: "", url: "", secret: "" } + // altimate_change start — skip session sharing in offline mode + if (offline() || disabled) return { id: "", url: "", secret: "" } + // altimate_change end log.info("creating share", { sessionID }) const req = await request() const response = await fetch(`${req.baseUrl}${req.api.create}`, { @@ -204,7 +211,9 @@ export namespace ShareNext { const queue = new Map }>() async function sync(sessionID: SessionID, data: Data[]) { - if (disabled) return + // altimate_change start — skip session sharing in offline mode + if (offline() || disabled) return + // altimate_change end const existing = queue.get(sessionID) if (existing) { for (const item of data) { @@ -249,7 +258,9 @@ export namespace ShareNext { } export async function remove(sessionID: SessionID) { - if (disabled) return + // altimate_change start — skip session sharing in offline mode + if (offline() || disabled) return + // altimate_change end log.info("removing share", { sessionID }) const share = get(sessionID) if (!share) return diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index 4699c10b51..9c6a2abbc4 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { offline } from "@/config/offline" +// altimate_change end import { NodePath } from "@effect/platform-node" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Effect, Layer, Path, Schema, Context } from "effect" @@ -55,6 +58,9 @@ export namespace Discovery { }) const pull = Effect.fn("Discovery.pull")(function* (url: string) { + // altimate_change start — skip network work in offline mode + if (offline()) return [] + // altimate_change end const base = url.endsWith("/") ? url : `${url}/` const index = new URL("index.json", base).href const host = base.slice(0, -1) diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 06af06b5c9..536cac7ef2 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" @@ -416,6 +419,14 @@ export namespace ToolRegistry { plugins?: Awaited>, configInput?: RegistryConfigInput, ): Promise { + // altimate_change start — offer only local tools in offline mode + if (offline()) { + return AppRuntime.runPromise(Effect.scoped(Effect.all([ + InvalidTool, QuestionTool, ReadTool, GlobTool, GrepTool, EditTool, WriteTool, + TaskTool, TodoWriteTool, SkillTool, ApplyPatchTool, WarehouseInstallDriverTool, + ]))) + } + // altimate_change end const custom = configInput?.matches ? await loadCustomTools(configInput.matches).then((x) => x.custom) : await state().then((x) => x.custom) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 70882ee814..6a7546d329 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode does not run project startup scripts +import { offline } from "@/config/offline" +// 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" @@ -491,6 +494,9 @@ export const layer: Layer.Layer< ) const runStartScript = Effect.fnUntraced(function* (directory: string, cmd: string, kind: string) { + // altimate_change start — keep worktree startup commands offline + if (offline()) return true + // altimate_change end const text = cmd.trim() if (!text) return true const result = yield* runStartCommand(directory, text) 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..183675c515 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).toContain("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/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts new file mode 100644 index 0000000000..d7b6cc45b9 --- /dev/null +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -0,0 +1,151 @@ +import { expect, test } from "bun:test" +import { createHash } from "node:crypto" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" + +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." + +async function fixture(snapshot: boolean, configMode: boolean) { + 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 calls = path.join(root, "calls.jsonl") + const preload = path.join(root, "preload.ts") + 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: "offline-test/fixture", + provider: { + "offline-test": { + npm: "@ai-sdk/openai-compatible", + options: { baseURL: MODEL_ENDPOINT, apiKey: "local-only" }, + models: { fixture: { name: "Offline fixture", limit: { context: 20000, output: 2000 } } }, + }, + }, + mcp: { remoteFixture: { type: "remote", url: "https://mcp.test" } }, + }), + ) + if (configMode) 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)} + 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 chunks = [ + { 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() {} }) + `, + ) + const env = { + PATH: process.env.PATH, + HOME: root, + OPENCODE_TEST_HOME: root, + OPENCODE_TEST_MANAGED_CONFIG_DIR: path.join(root, "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", + // The environment switch must preserve the snapshot even when a deployment + // still has the old workspace opt-out set. + ALTIMATE_DISABLE_WORKSPACE: configMode ? "" : "1", + ALTIMATE_CODE_DISABLE_OS_CREDENTIAL_STORE: "1", + ALTIMATE_RUN_STDIN_WAIT_MS: "0", + NO_COLOR: "1", + } + return { root, project, preload, env, calls, manifest, skill } +} + +for (const configMode of [false, true]) { + test(`offline ${configMode ? "config" : "environment"} keeps network traffic on the model endpoint`, async () => { + const f = await fixture(!configMode, configMode) + try { + const before = configMode ? undefined : await fs.readFile(f.manifest, "utf8") + const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "Hello"], { + cwd: f.project, + env: 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(calls.filter((call) => call.url !== MODEL_ENDPOINT + "/chat/completions")).toEqual([]) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("offline reply") }) + expect(calls.length).toBeGreaterThan(0) + expect(calls.some((call) => call.hasSkill)).toBe(!configMode) + expect(stderr.match(/Offline mode:/g)).toHaveLength(1) + expect(stderr).not.toContain("Workspace skills not synced") + if (configMode) expect(stderr).toContain("No usable workspace skill snapshot") + else { + 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) +} 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 From 1fb55276f04f56ec5494d6703d13a84ad0c76dbd Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:40:50 -0800 Subject: [PATCH 02/72] fix: bypass inherited proxies in offline mode --- packages/opencode/src/config/offline.ts | 6 +- .../opencode/test/cli/run/offline.test.ts | 71 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index b324c8a9f5..86eae06680 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -57,6 +57,10 @@ export async function startOfflineMode(directory: string, model?: string) { // their layers. Once enabled, keep it for the lifetime of the process. process.env.ALTIMATE_OFFLINE = "1" process.env.GIT_NO_LAZY_FETCH = "1" + // Bun consults proxy environment variables even when fetch sets proxy: "". + // Offline traffic must go directly to the one configured endpoint. + process.env.NO_PROXY = "*" + process.env.no_proxy = "*" if (model) process.env.ALTIMATE_OFFLINE_MODEL = model if (networkFetch) return networkFetch = globalThis.fetch @@ -92,7 +96,7 @@ export function offlineModelFetch(baseURL: string | undefined): typeof fetch { const target = new URL(input instanceof Request ? input.url : input.toString()) if (target.origin !== endpoint.origin) throw new Error("Offline mode blocked a request outside the configured model endpoint.") - return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error", proxy: "" }) + return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error" }) }, { preconnect: () => {} }, ) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index d7b6cc45b9..05fffe0dab 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -149,3 +149,74 @@ for (const configMode of [false, true]) { } }, 40_000) } + +test("offline model transport bypasses proxy settings and refuses redirects", async () => { + let proxyCalls = 0 + const proxy = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch() { + proxyCalls++ + return new Response("unexpected proxy") + }, + }) + const model = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request) { + if (new URL(request.url).pathname === "/redirect") return Response.redirect(proxy.url, 302) + return new Response("direct model response") + }, + }) + try { + const source = path.resolve(import.meta.dir, "../../../src/config/offline.ts") + const proc = Bun.spawn( + [ + process.execPath, + "-e", + ` + import { startOfflineMode, offlineModelFetch } from ${JSON.stringify(source)} + await startOfflineMode(process.cwd()) + const request = offlineModelFetch(process.env.OFFLINE_TEST_MODEL) + console.log(await (await request(process.env.OFFLINE_TEST_MODEL)).text()) + try { + await request(new URL("/redirect", process.env.OFFLINE_TEST_MODEL)) + throw new Error("redirect was accepted") + } catch (error) { + if (error.message === "redirect was accepted") throw error + console.log("redirect refused") + } + `, + ], + { + cwd: path.resolve(import.meta.dir, "../../.."), + env: { + ...process.env, + ALTIMATE_OFFLINE: "1", + OFFLINE_TEST_MODEL: model.url.href, + HTTP_PROXY: proxy.url.href, + http_proxy: proxy.url.href, + NO_PROXY: "", + no_proxy: "", + }, + stdout: "pipe", + stderr: "pipe", + signal: AbortSignal.timeout(15_000), + }, + ) + const [code, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]) + expect({ code, stdout, stderr }).toEqual({ + code: 0, + stdout: "direct model response\nredirect refused\n", + stderr: "", + }) + expect(proxyCalls).toBe(0) + } finally { + model.stop(true) + proxy.stop(true) + } +}) From b1245bd8f4448349ee374d71b3d2a942c7d0194c Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:42:07 -0800 Subject: [PATCH 03/72] fix: gate direct shell entry points in offline mode --- packages/opencode/src/config/offline.ts | 2 +- packages/opencode/src/index.ts | 2 +- packages/opencode/src/pty/index.ts | 6 ++++++ packages/opencode/src/session/prompt.ts | 6 ++++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 86eae06680..269da33446 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -96,7 +96,7 @@ export function offlineModelFetch(baseURL: string | undefined): typeof fetch { const target = new URL(input instanceof Request ? input.url : input.toString()) if (target.origin !== endpoint.origin) throw new Error("Offline mode blocked a request outside the configured model endpoint.") - return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error" }) + return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error", proxy: undefined }) }, { preconnect: () => {} }, ) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 182354d5cc..57fce28f12 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -176,7 +176,7 @@ let cli = yargs(args) : args.project ? resolveThreadDirectory(args.project) : process.cwd() await startOfflineMode(directory, args.model) if (offline() && ( - ["attach", "github", "gitlab", "pr", "review", "workspace-client", "workspace-serve", "web"].includes(command) || + ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web"].includes(command) || (command === "run" && args.attach) || (command === "mcp" && opts._[1] === "serve") || (["providers", "auth", "mcp", "console"].includes(command) && opts._.some((arg) => arg === "login" || arg === "auth")) diff --git a/packages/opencode/src/pty/index.ts b/packages/opencode/src/pty/index.ts index 166d9f4213..a3a8c3941a 100644 --- a/packages/opencode/src/pty/index.ts +++ b/packages/opencode/src/pty/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode skips terminal subprocesses +import { offline } from "@/config/offline" +// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" // altimate_change start — upstream moved the pty spawn backend into @opencode-ai/core @@ -123,6 +126,9 @@ export namespace Pty { } export async function create(input: CreateInput) { + // altimate_change start — offline mode skips terminal subprocesses + if (offline()) throw new Error("Terminal sessions are disabled in offline mode.") + // altimate_change end const id = PtyID.ascending() const command = input.command || Shell.preferred() const args = input.args || [] diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 14e09c6b89..f859e5dca4 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -4331,6 +4331,9 @@ NOTE: At any point in time through this workflow you should feel free to ask the }) export type ShellInput = z.infer export async function shell(input: ShellInput) { + // altimate_change start — prevent direct shell execution in offline sessions + if (offline()) throw new Error("Shell commands are disabled in offline mode.") + // altimate_change end const abort = start(input.sessionID) if (!abort) { throw new Session.BusyError(input.sessionID) @@ -4838,6 +4841,9 @@ NOTE: At any point in time through this workflow you should feel free to ask the const shell = ConfigMarkdown.shell(template) if (shell.length > 0) { + // altimate_change start — template expansion can invoke an arbitrary program + if (offline()) throw new Error("Shell commands are disabled in offline mode.") + // altimate_change end // altimate_change start — upstream_fix: command template shell // expansion must honor configured shell instead of Bun's default parser. const sh = Shell.preferred((await Config.get()).shell) From c4d318c1dbf774a9ed74ea1e31e5034e19eafa26 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:42:57 -0800 Subject: [PATCH 04/72] fix: keep offline tool runs out of online daemons --- packages/opencode/src/cli/cmd/tool.ts | 7 +++++-- packages/opencode/src/index.ts | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index 43389f4e3d..ae389caa69 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -1,3 +1,4 @@ +import { offline } from "@/config/offline" // altimate_change - new file // // Model-free access to the data tools: `tool list`, `tool run` and the optional `tool daemon` @@ -215,9 +216,11 @@ const ToolRunCommand = cmd({ try { const toolArgs = await readArgs(args) const directory = process.cwd() - const workspaceTools = await resolveWorkspaceTools(args["workspace-tools"], directory) + if (offline() && name !== "warehouse_install_driver") + throw new Error("This tool is disabled in offline mode.") + const workspaceTools = !offline() && (await resolveWorkspaceTools(args["workspace-tools"], directory)) const daemon = await import("../../altimate/tool-cli/daemon") - const reply = args.daemon && !daemon.daemonDisabled() + const reply = !offline() && args.daemon && !daemon.daemonDisabled() ? await daemon.runViaDaemon(directory, InstallationVersion, { id: randomUUID(), name, diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 57fce28f12..17198db821 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -179,6 +179,7 @@ let cli = yargs(args) ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web"].includes(command) || (command === "run" && args.attach) || (command === "mcp" && opts._[1] === "serve") || + (command === "tool" && opts._[1] === "daemon") || (["providers", "auth", "mcp", "console"].includes(command) && opts._.some((arg) => arg === "login" || arg === "auth")) )) throw new Error("This command requires network access. Run it while online.") // altimate_change end From e749ec6d08a944821eb2cf74f758154563a13124 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:51:18 -0800 Subject: [PATCH 05/72] fix: close offline startup and subprocess gaps --- docs/docs/configure/config.md | 8 +- packages/core/src/flag/flag.ts | 6 + packages/core/src/models-dev.ts | 8 +- packages/core/src/npm.ts | 5 +- packages/core/src/observability/otlp.ts | 6 +- .../opencode/src/altimate/debug/collect.ts | 4 +- packages/opencode/src/altimate/free/client.ts | 6 +- .../altimate/native/connections/registry.ts | 10 +- .../opencode/src/altimate/telemetry/index.ts | 6 +- .../tools/warehouse-install-driver.ts | 4 +- .../src/altimate/workspace/engine-offer.ts | 8 +- .../src/altimate/workspace/engine-overlay.ts | 6 +- .../src/altimate/workspace/identity.ts | 4 +- .../src/altimate/workspace/skill-sync.ts | 4 +- packages/opencode/src/bun/index.ts | 4 +- packages/opencode/src/bun/registry.ts | 4 +- packages/opencode/src/cli/cmd/acp.ts | 12 ++ packages/opencode/src/cli/cmd/models.ts | 4 +- .../src/cli/cmd/serve-upgrade-check.ts | 4 +- packages/opencode/src/cli/cmd/skill.ts | 7 +- packages/opencode/src/cli/cmd/tool.ts | 8 +- packages/opencode/src/cli/cmd/tui.ts | 10 +- packages/opencode/src/cli/network.ts | 4 +- packages/opencode/src/cli/tui/worker.ts | 12 +- packages/opencode/src/cli/upgrade.ts | 4 +- packages/opencode/src/config/config.ts | 17 +-- packages/opencode/src/config/offline.ts | 28 +++-- packages/opencode/src/config/tui.ts | 6 +- packages/opencode/src/index.ts | 22 ++-- packages/opencode/src/installation/index.ts | 6 +- packages/opencode/src/lsp/index.ts | 4 +- packages/opencode/src/mcp/index.ts | 7 +- packages/opencode/src/plugin/index.ts | 4 +- packages/opencode/src/plugin/tui/runtime.ts | 7 +- packages/opencode/src/provider/models.ts | 6 +- packages/opencode/src/provider/provider.ts | 14 +-- packages/opencode/src/pty/index.ts | 4 +- packages/opencode/src/session/instruction.ts | 4 +- packages/opencode/src/session/prompt.ts | 10 +- packages/opencode/src/share/share-next.ts | 10 +- packages/opencode/src/skill/discovery.ts | 4 +- packages/opencode/src/tool/registry.ts | 8 +- packages/opencode/src/worktree/index.ts | 4 +- .../opencode/test/cli/run/offline.test.ts | 110 +++++++++++++++--- 44 files changed, 292 insertions(+), 141 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 76e00a9201..a9558c5374 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -162,12 +162,12 @@ Control how context is managed when conversations grow long: ## Offline / air-gapped mode -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a local config file such as `~/.config/altimate-code/altimate-code.json` or `.altimate-code/altimate-code.json` in the project. A local opt-in applies for the lifetime of the CLI process and its workers. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a local config file such as `~/.config/altimate-code/altimate-code.json` or `.altimate-code/altimate-code.json` in the project. The switch is read when Altimate Code starts and applies to all projects served by that process and its workers. To use a project opt-in from an existing shared server, start a separate Altimate Code process in that project. Before going offline: 1. Configure the model locally, including its `provider/model` ID and the provider's explicit `options.baseURL`. For a self-hosted OpenAI-compatible server, use the bundled `@ai-sdk/openai-compatible` provider. Define the model in your provider config if it is absent from the bundled or cached model catalog. -2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice if the snapshot is unavailable. -3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Network warehouse connections and automatic driver installs are disabled in offline mode. +2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice indicating whether cached skills are available. +3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Offline mode disables all warehouse connections, including local DuckDB and SQLite, and automatic driver installs. -Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. It also limits the tool catalog to local operations. For example, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Install `ripgrep` ahead of time if you need file search on a fresh host. +Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Install `ripgrep` ahead of time if you need file search on a fresh host. diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index d85627f1b5..26e13479c3 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -20,6 +20,12 @@ export function env(key: string): string | undefined { return documented !== undefined && documented !== "" ? documented : process.env[key] } +// altimate_change start — read offline policy after the CLI startup config preflight +export function offlineModeEnabled() { + return process.env.ALTIMATE_OFFLINE === "1" +} +// altimate_change end + export function truthy(key: string) { const value = env(key)?.toLowerCase() return value === "true" || value === "1" diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index a854c6ccb5..9962a469a7 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -2,7 +2,7 @@ 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" +import { Flag, offlineModeEnabled } from "./flag/flag" import { Flock } from "./util/flock" import { Hash } from "./util/hash" import { FSUtil } from "./fs-util" @@ -202,7 +202,7 @@ export const layer = Layer.effect( const snapshot = yield* loadSnapshot if (snapshot) return snapshot // altimate_change start — offline mode uses only the cached or bundled catalog - if (process.env.ALTIMATE_OFFLINE === "1" || Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} + 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( @@ -220,7 +220,7 @@ export const layer = Layer.effect( const refresh = Effect.fn("ModelsDev.refresh")(function* (force = false) { // altimate_change start — skip forced catalog refresh in offline mode - if (process.env.ALTIMATE_OFFLINE === "1") return + if (offlineModeEnabled()) return // altimate_change end if (!force && (yield* fresh())) return yield* Effect.scoped( @@ -240,7 +240,7 @@ export const layer = Layer.effect( }) // altimate_change start — skip background refresh in offline mode - if (process.env.ALTIMATE_OFFLINE !== "1" && !Flag.OPENCODE_DISABLE_MODELS_FETCH && !process.argv.includes("--get-yargs-completions")) { + 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 b14eb213a8..b7f4159c0d 100644 --- a/packages/core/src/npm.ts +++ b/packages/core/src/npm.ts @@ -1,3 +1,4 @@ +import { offlineModeEnabled } from "./flag/flag" export * as Npm from "./npm" import path from "path" @@ -126,7 +127,7 @@ export const layer = Layer.effect( return resolveEntryPoint(name, path.join(dir, "node_modules", name)) } - if (process.env.ALTIMATE_OFFLINE === "1") return yield* new InstallFailedError({ add: [pkg], dir }) + if (offlineModeEnabled()) return yield* new InstallFailedError({ add: [pkg], dir }) const tree = yield* reify({ dir, add: [pkg] }) const first = tree.edgesOut.values().next().value?.to if (!first) { @@ -138,7 +139,7 @@ export const layer = Layer.effect( }, Effect.scoped) const install: Interface["install"] = Effect.fn("Npm.install")(function* (dir, input) { - if (process.env.ALTIMATE_OFFLINE === "1") return + if (offlineModeEnabled()) return const canWrite = yield* afs.access(dir, { writable: true }).pipe( Effect.as(true), Effect.orElseSucceed(() => false), diff --git a/packages/core/src/observability/otlp.ts b/packages/core/src/observability/otlp.ts index abdbac3439..38a2daf921 100644 --- a/packages/core/src/observability/otlp.ts +++ b/packages/core/src/observability/otlp.ts @@ -1,6 +1,6 @@ import { Layer } from "effect" import { OtlpLogger } from "effect/unstable/observability" -import { Flag } from "../flag/flag" +import { Flag, offlineModeEnabled } from "../flag/flag" import { InstallationChannel, InstallationVersion } from "../installation/version" import { runID } from "./shared" @@ -48,12 +48,12 @@ export function resource(): { serviceName: string; serviceVersion: string; attri } export function loggers() { - if (process.env.ALTIMATE_OFFLINE === "1" || !endpoint) return [] + if (offlineModeEnabled() || !endpoint) return [] return [OtlpLogger.make({ url: `${endpoint}/v1/logs`, resource: resource(), headers })] } export async function tracingLayer() { - if (process.env.ALTIMATE_OFFLINE === "1" || !endpoint) return Layer.empty + if (offlineModeEnabled() || !endpoint) return Layer.empty 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/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index d4fb3e174b..0cf1517825 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end // altimate_change start — debug report: gathers the facts `report.ts` analyses /** @@ -314,7 +314,7 @@ export async function probe( deps: ProbeDeps = defaultProbeDeps, ): Promise { // altimate_change start — skip network work in offline mode - if (offline()) return { target, host, ok: false, detail: "Skipped in offline mode", ms: 0 } + if (Offline.enabled()) return { target, host, ok: false, detail: "Skipped in offline mode", ms: 0 } // altimate_change end const timeoutMs = opts.timeoutMs ?? NETWORK_TIMEOUT_MS const started = Date.now() diff --git a/packages/opencode/src/altimate/free/client.ts b/packages/opencode/src/altimate/free/client.ts index 34da580918..8dda346ef6 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 Error("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/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 20038738f3..557e7242f0 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end /** * ConnectionRegistry — manages database connections. @@ -428,7 +428,7 @@ async function createConnector( ): Promise { // altimate_change end // altimate_change start — skip network work in offline mode - if (offline()) { + if (Offline.enabled()) { throw new Error("Offline mode disables warehouse connections.") } // altimate_change end @@ -670,10 +670,10 @@ export function names(): string[] { /** Get a connector instance (creates lazily). */ export async function get(name: string): Promise { - // altimate_change start — captured once, so a connect that finishes later lands in the project that started it - // altimate_change start — skip network work in offline mode - if (offline()) throw new Error("Offline mode disables warehouse connections.") + // altimate_change start — reject warehouse execution before accessing the connector cache + if (Offline.enabled()) throw new Error("Offline mode disables warehouse connections.") // altimate_change end + // altimate_change start — captured once, so a connect that finishes later lands in the project that started it const s = ensureLoaded() const { configs, connectors, tunnels, pending } = s // altimate_change end diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index ba270bcc4b..6d789c8fbe 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { Config } from "@/config/config" import { Flag } from "@/flag/flag" @@ -2519,7 +2519,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 (offline()) return Promise.resolve() + if (Offline.enabled()) 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 @@ -2977,7 +2977,7 @@ export namespace Telemetry { // altimate_change end export function track(event: Event) { - if (offline()) return + if (Offline.enabled()) return // Before init completes: buffer (flushed once init enables, or cleared if disabled). // After init completed and disabled telemetry: drop silently. if (initDone && !enabled) return diff --git a/packages/opencode/src/altimate/tools/warehouse-install-driver.ts b/packages/opencode/src/altimate/tools/warehouse-install-driver.ts index e479203891..dcb7718f74 100644 --- a/packages/opencode/src/altimate/tools/warehouse-install-driver.ts +++ b/packages/opencode/src/altimate/tools/warehouse-install-driver.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import z from "zod" import path from "node:path" @@ -89,7 +89,7 @@ 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()) { + if (Offline.enabled()) { const error = `Offline mode. Install the driver while online: npm install --prefix ${shellQuote(dir)} ${packages}` return { title: `${label} driver: offline`, diff --git a/packages/opencode/src/altimate/workspace/engine-offer.ts b/packages/opencode/src/altimate/workspace/engine-offer.ts index c489d40838..888a7c97d5 100644 --- a/packages/opencode/src/altimate/workspace/engine-offer.ts +++ b/packages/opencode/src/altimate/workspace/engine-offer.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end // altimate_change - new file // @@ -83,7 +83,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()) return null + if (Offline.enabled()) return null const binding = syncInternals.resolveBinding ? await syncInternals.resolveBinding(directory) : await readLocalBinding(directory).catch((err) => { @@ -236,7 +236,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()) return { ok: false, error: "Install the workspace engine while online." } + 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" @@ -372,7 +372,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()) return + 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 dd8dc18d55..f29c2eeb20 100644 --- a/packages/opencode/src/altimate/workspace/engine-overlay.ts +++ b/packages/opencode/src/altimate/workspace/engine-overlay.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end // altimate_change - new file // @@ -233,7 +233,7 @@ export async function overlay( state.managed = opts.managed === true state.linked = null try { - if (offline() || !isEnabled() || isServe()) { + if (Offline.enabled() || !isEnabled() || isServe()) { state.current = null return } @@ -502,7 +502,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 (offline() || !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 6c916d27da..101fa953e0 100644 --- a/packages/opencode/src/altimate/workspace/identity.ts +++ b/packages/opencode/src/altimate/workspace/identity.ts @@ -1,4 +1,4 @@ -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change - new file // // Model-facing statement of Altimate Workspace identity: which workspace (if any) this @@ -443,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 (offline() || !isEnabled()) return "" + if (Offline.enabled() || !isEnabled()) return "" try { const directory = Instance.directory const scope = await accountScope() diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index cbb245dd6f..61b7f48892 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end // altimate_change - new file // @@ -1243,7 +1243,7 @@ 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 { - if (offline()) return { changed: false, skipped: [], error: "Run workspace refresh while online." } + 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 9709e068a0..b8b46ec629 100644 --- a/packages/opencode/src/bun/index.ts +++ b/packages/opencode/src/bun/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import z from "zod" import { Global } from "../global" @@ -55,7 +55,7 @@ export namespace BunProc { export async function install(pkg: string, version = "latest") { // altimate_change start — prevent package installs in offline mode - if (offline()) throw new Error("Offline mode disables package installation.") + if (Offline.enabled()) throw new Error("Offline mode disables package installation.") // altimate_change end // Use lock to ensure only one install at a time using _ = await Lock.write("bun-install") diff --git a/packages/opencode/src/bun/registry.ts b/packages/opencode/src/bun/registry.ts index ab1870e394..74b9dbe991 100644 --- a/packages/opencode/src/bun/registry.ts +++ b/packages/opencode/src/bun/registry.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import semver from "semver" import { Log } from "../util/log" @@ -14,7 +14,7 @@ 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()) return null + if (Offline.enabled()) return null // altimate_change end const { code, stdout, stderr } = await Process.run([which(), "info", pkg, field], { cwd, diff --git a/packages/opencode/src/cli/cmd/acp.ts b/packages/opencode/src/cli/cmd/acp.ts index 1a728f4483..1a623660b9 100644 --- a/packages/opencode/src/cli/cmd/acp.ts +++ b/packages/opencode/src/cli/cmd/acp.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy +import { Offline } from "@/config/offline" +// altimate_change end import { Effect } from "effect" import { effectCmd } from "../effect-cmd" import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk" @@ -42,6 +45,15 @@ export const AcpCommand = effectCmd({ const sdk = createOpencodeClient({ baseUrl: `http://${server.hostname}:${server.port}`, headers: ServerAuth.headers(), + // altimate_change start — route the offline ACP client to the in-process API + fetch: Offline.enabled() + ? Object.assign( + async (input: Parameters[0], init?: Parameters[1]) => + Server.Default().fetch(new Request(input, init)), + { preconnect: () => {} }, + ) + : undefined, + // altimate_change end }) const input = new WritableStream({ diff --git a/packages/opencode/src/cli/cmd/models.ts b/packages/opencode/src/cli/cmd/models.ts index 939a836d2e..bcb8c4770e 100644 --- a/packages/opencode/src/cli/cmd/models.ts +++ b/packages/opencode/src/cli/cmd/models.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode reads the cached model catalog -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { EOL } from "os" import { Effect } from "effect" @@ -31,7 +31,7 @@ export const ModelsCommand = effectCmd({ handler: Effect.fn("Cli.models")(function* (args) { const { Provider } = yield* Effect.promise(() => import("@/provider/provider")) // altimate_change start — skip catalog refresh in offline mode - if (args.refresh && !offline()) { + 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 f8bf0545a1..7d069ab99b 100644 --- a/packages/opencode/src/cli/cmd/serve-upgrade-check.ts +++ b/packages/opencode/src/cli/cmd/serve-upgrade-check.ts @@ -1,7 +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 { Offline } from "@/config/offline" import { upgrade } from "../upgrade" import { Log } from "../../util/log" @@ -64,7 +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()) return + 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..84f0043e7b 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,10 @@ const SkillInstallCommand = cmd({ }), async handler(args) { let source = (args.source as string).trim().replace(/\.git$/, "") + const githubShorthand = /^[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/ + if (Offline.enabled() && (/^https?:\/\//.test(source) || githubShorthand.test(source))) { + throw new Error("Install remote skills while online, or install a local skill directory.") + } const isGlobal = args.global as boolean if (!source) { @@ -693,7 +698,7 @@ const SkillInstallCommand = cmd({ process.exit(1) } skillDir = tmpDir - } else if (source.match(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/)) { + } else if (githubShorthand.test(source)) { // GitHub shorthand: owner/repo const url = `https://github.com/${source}.git` process.stdout.write(`Fetching from github.com/${source}...` + EOL) diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index ae389caa69..558f3fb6cc 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -1,4 +1,4 @@ -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change - new file // // Model-free access to the data tools: `tool list`, `tool run` and the optional `tool daemon` @@ -216,11 +216,11 @@ const ToolRunCommand = cmd({ try { const toolArgs = await readArgs(args) const directory = process.cwd() - if (offline() && name !== "warehouse_install_driver") + if (Offline.enabled() && name !== "warehouse_install_driver") throw new Error("This tool is disabled in offline mode.") - const workspaceTools = !offline() && (await resolveWorkspaceTools(args["workspace-tools"], directory)) + const workspaceTools = !Offline.enabled() && (await resolveWorkspaceTools(args["workspace-tools"], directory)) const daemon = await import("../../altimate/tool-cli/daemon") - const reply = !offline() && args.daemon && !daemon.daemonDisabled() + const reply = !Offline.enabled() && args.daemon && !daemon.daemonDisabled() ? await daemon.runViaDaemon(directory, InstallationVersion, { id: randomUUID(), name, diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 05cdde12ce..7cb89486ac 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy +import { Offline } from "@/config/offline" +// altimate_change end import { cmd } from "@/cli/cmd/cmd" import { Rpc } from "@/util/rpc" import { type rpc } from "../tui/worker" @@ -246,9 +249,12 @@ export const TuiThreadCommand = cmd({ network.port !== 0 || network.hostname !== "127.0.0.1" - const transport = external + // altimate_change start — keep the TUI's own requests inside its offline worker + const listener = external ? await client.call("server", network) : undefined + const transport = listener && !Offline.enabled() ? { - url: (await client.call("server", network)).url, + url: listener.url, + // altimate_change end fetch: undefined, events: undefined, } diff --git a/packages/opencode/src/cli/network.ts b/packages/opencode/src/cli/network.ts index a07fd41949..886ab195e9 100644 --- a/packages/opencode/src/cli/network.ts +++ b/packages/opencode/src/cli/network.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode skips multicast discovery -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import type { Argv, InferredOptionTypes } from "yargs" import { ConfigV1 } from "@opencode-ai/core/v1/config/config" @@ -56,7 +56,7 @@ export function resolveNetworkOptionsNoConfig(args: NetworkOptions, config?: Con const mdnsExplicitlySet = process.argv.includes("--mdns") const mdnsDomainExplicitlySet = process.argv.includes("--mdns-domain") // altimate_change start — offline mode skips multicast discovery - const mdns = !offline() && (mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns)) + const mdns = !Offline.enabled() && (mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns)) // 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) diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index f0d8daa516..946d69ac28 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" @@ -41,7 +44,10 @@ import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding" // its events buffer until Telemetry.init() runs inside the Instance context in traceReady below // (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() +// altimate_change start — the parent has already selected the process-wide policy +if (Offline.enabled()) await Offline.start(process.cwd()) +else Telemetry.startLoopMonitor() +// altimate_change end // 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 @@ -69,7 +75,9 @@ Heap.start() // InstanceRuntime.load/Config.get() would otherwise race it (transiently truncated // read) or cache the pre-heal entry, making the first session spawn the broken // config anyway. Errors are swallowed: a failed sync must never block the TUI. -const datamateSyncReady: Promise = syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) +const datamateSyncReady: Promise = Offline.enabled() + ? Promise.resolve() + : syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) // altimate_change end const traceConsumer = new TraceConsumer() diff --git a/packages/opencode/src/cli/upgrade.ts b/packages/opencode/src/cli/upgrade.ts index 8d5d1c9eed..da0c9afa37 100644 --- a/packages/opencode/src/cli/upgrade.ts +++ b/packages/opencode/src/cli/upgrade.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { Config } from "@/config/config" import { AppRuntime } from "@/effect/app-runtime" @@ -100,7 +100,7 @@ export function isAutoupdateDisabledByEnv() { export async function upgrade() { // altimate_change start — skip automatic update checks in offline mode - if (offline()) return + 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 diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 25cd116df6..eb902d69a7 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline, startOfflineMode } from "@/config/offline" +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" @@ -503,7 +503,7 @@ export const layer = Layer.effect( const loadInstanceState = Effect.fn("Config.loadInstanceState")( function* (ctx: InstanceContext) { // altimate_change start — skip network work in offline mode - yield* Effect.promise(() => startOfflineMode(ctx.directory)) + yield* Effect.promise(() => Offline.assertStartupPolicy(ctx.directory)) // altimate_change end const auth = yield* authSvc.all().pipe(Effect.orDie) @@ -566,7 +566,7 @@ export const layer = Layer.effect( for (const [key, value] of Object.entries(auth)) { // altimate_change start — skip well-known network config in offline mode - if (offline()) continue + if (Offline.enabled()) continue // altimate_change end if (value.type === "wellknown") { const url = key.replace(/\/+$/, "") @@ -693,7 +693,7 @@ export const layer = Layer.effect( } // altimate_change start — skip account network config in offline mode - const activeAccount = offline() + const activeAccount = Offline.enabled() ? undefined : Option.getOrUndefined(yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none())))) // altimate_change end @@ -784,7 +784,7 @@ export const layer = Layer.effect( // under any earlier directory. Keep the PURE skip and retain fibers for waitForDependencies. const deps: Fiber.Fiber[] = [] for (const dir of directories) { - if (!offline() && ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { + if (!Offline.enabled() && ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { const dep = yield* npmSvc .install(dir, { add: [ @@ -847,10 +847,11 @@ export const layer = Layer.effect( } // altimate_change start — disable runtime sharing in offline mode - if (offline()) { + if (Offline.enabled()) { result.offline = true result.share = "disabled" result.formatter = false + result.lsp = false } // altimate_change end if (result.autoshare === true && !result.share) { @@ -869,7 +870,7 @@ export const layer = Layer.effect( // may not yet be declared in the ConfigV1 experimental schema. const autoMcpDiscovery = (result.experimental as { auto_mcp_discovery?: boolean } | undefined) ?.auto_mcp_discovery - if (!offline() && !Flag.OPENCODE_DISABLE_PROJECT_CONFIG && autoMcpDiscovery !== false) { + if (!Offline.enabled() && !Flag.OPENCODE_DISABLE_PROJECT_CONFIG && autoMcpDiscovery !== false) { const { discoverExternalMcp, setDiscoveryResult, driftFields, setConfigDrift, discoveredSource } = yield* Effect.promise( () => import("../mcp/discover"), @@ -903,7 +904,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 (!offline() && !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 index 269da33446..a2246f0230 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -2,7 +2,7 @@ import fs from "node:fs/promises" import path from "node:path" import { parse } from "jsonc-parser" import * as Effect from "effect/Effect" -import { Flag, env } from "@opencode-ai/core/flag/flag" +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" @@ -11,9 +11,7 @@ import { ConfigPaths } from "./paths" const configNames = ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"] -export function offline() { - return process.env.ALTIMATE_OFFLINE === "1" -} +export { enabled } async function localOptIn(directory: string) { // The switch is an opt-in from any local config source. Read just this @@ -49,10 +47,18 @@ async function localOptIn(directory: string) { return enabled((await ConfigManaged.readManagedPreferences().catch(() => undefined))?.text) } +export async function assertStartupPolicy(directory: string) { + if (!enabled() && (await localOptIn(directory))) { + throw new Error( + "This project requests offline mode. Start Altimate Code from the project to apply its offline policy.", + ) + } +} + let networkFetch: typeof fetch | undefined -export async function startOfflineMode(directory: string, model?: string) { - if (!offline() && !(await localOptIn(directory))) return +export async function start(directory: string, model?: string) { + if (!enabled() && !(await localOptIn(directory))) return // Workers and core services must see the same policy before constructing // their layers. Once enabled, keep it for the lifetime of the process. process.env.ALTIMATE_OFFLINE = "1" @@ -72,7 +78,7 @@ export async function startOfflineMode(directory: string, model?: string) { ) } -export function offlineProvider( +export function provider( config: Pick, ) { const model = process.env.ALTIMATE_OFFLINE_MODEL ?? config.model @@ -86,7 +92,7 @@ export function offlineProvider( return candidates.length === 1 ? candidates[0][0] : undefined } -export function offlineModelFetch(baseURL: string | undefined): typeof fetch { +export function modelFetch(baseURL: string | undefined): typeof fetch { if (!baseURL) throw new Error("Offline mode requires a model provider with an explicit baseURL.") const endpoint = new URL(baseURL) if (!["http:", "https:"].includes(endpoint.protocol)) @@ -104,14 +110,16 @@ export function offlineModelFetch(baseURL: string | undefined): typeof fetch { let warned = false -export async function warnOffline(hasSnapshot: boolean) { +export async function announce(hasSnapshot: boolean) { if (warned) return warned = true const message = hasSnapshot ? "Using cached workspace skills." - : "No usable workspace skill snapshot. Run altimate-code workspace refresh while online." + : "No usable workspace skill snapshot. To use workspace skills, run altimate-code workspace refresh while online." const { isHeadless } = await import("@/altimate/workspace/engine-seams") const { notify, printLine } = await import("@/altimate/workspace/engine-probes") if (isHeadless()) printLine(`Offline mode: ${message}`) else await notify({ title: "Offline mode", message, variant: hasSnapshot ? "info" : "warning" }) } + +export * as Offline from "./offline" diff --git a/packages/opencode/src/config/tui.ts b/packages/opencode/src/config/tui.ts index 9f4a76bff7..a959ae6bd5 100644 --- a/packages/opencode/src/config/tui.ts +++ b/packages/opencode/src/config/tui.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end export * as TuiConfig from "./tui" @@ -261,7 +261,7 @@ const loadState = Effect.fn("TuiConfig.loadState")(function* (ctx: { directory: return { config: result, // altimate_change start — skip local and installed TUI plugins in offline mode - pluginOrigins: offline() ? [] : acc.plugin_origins, + pluginOrigins: Offline.enabled() ? [] : acc.plugin_origins, // altimate_change end dirs: result.plugin?.length ? dirs : [], } @@ -280,7 +280,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) => !offline() && 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/index.ts b/packages/opencode/src/index.ts index 17198db821..c4b94bae03 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline, startOfflineMode } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import yargs from "yargs" import { hideBin } from "yargs/helpers" @@ -170,12 +170,20 @@ let cli = yargs(args) } // altimate_change start — skip network work in offline mode const command = String(opts._[0] ?? "") - const args = opts as { dir?: string; project?: string; attach?: string; model?: string } - const directory = command === "run" && !args.attach && args.dir - ? path.resolve(args.dir) - : args.project ? resolveThreadDirectory(args.project) : process.cwd() - await startOfflineMode(directory, args.model) - if (offline() && ( + const args = opts as { + dir?: string + cwd?: string + directory?: string + project?: string + attach?: string + model?: string + } + const offlineTarget = (command === "run" && !args.attach ? args.dir : undefined) + ?? (command === "acp" ? args.cwd : undefined) + ?? (command === "workspace" ? args.directory : undefined) + const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) + await Offline.start(directory, args.model) + if (Offline.enabled() && ( ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web"].includes(command) || (command === "run" && args.attach) || (command === "mcp" && opts._[1] === "serve") || diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index 502523f98f..d4c75d86ed 100644 --- a/packages/opencode/src/installation/index.ts +++ b/packages/opencode/src/installation/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +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" @@ -844,7 +844,7 @@ export const layer: Layer.Layer undefined) if (snapshot) return snapshot // altimate_change start — use only the local model catalog in offline mode - if (offline() || Flag.OPENCODE_DISABLE_MODELS_FETCH) return {} + 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(() => {}) @@ -170,7 +170,7 @@ export namespace ModelsDev { export async function refresh(force = false) { // altimate_change start — skip explicit model catalog refresh in offline mode - if (offline()) return + if (Offline.enabled()) return // altimate_change end if (skip(force)) return ModelsDev.Data.reset() await Flock.withLock(`models-dev:${filepath}`, async () => { diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index e876522d5e..51992688de 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline, offlineModelFetch, offlineProvider } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import z from "zod" import { Schema } from "effect" @@ -1400,11 +1400,11 @@ export namespace Provider { const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null // altimate_change start — offline provider selection is independent of online fallback rules - const offlineProviderID = offline() ? offlineProvider(config) : undefined + const offlineProviderID = Offline.enabled() ? Offline.provider(config) : undefined // altimate_change end function isProviderAllowed(providerID: ProviderID): boolean { // altimate_change start — require a locally configured model endpoint in offline mode - if (offline()) { + if (Offline.enabled()) { const options = config.provider?.[providerID]?.options if ( providerID !== offlineProviderID || @@ -2026,7 +2026,7 @@ export namespace Provider { // altimate_change end const data = database[providerID] // altimate_change start — skip provider discovery and OAuth-backed loaders in offline mode - if (offline()) continue + if (Offline.enabled()) continue // altimate_change end if (!data) { log.error("Provider does not exist in model list " + providerID) @@ -2171,10 +2171,10 @@ export namespace Provider { // altimate_change end // altimate_change start — constrain offline model transport to its configured origin - const offlineMode = offline() + const offlineMode = Offline.enabled() if (offlineMode) { const config = await Config.get() - if (offlineProvider(config) !== model.providerID || typeof config.provider?.[model.providerID]?.options?.baseURL !== "string") + if (Offline.provider(config) !== model.providerID || typeof config.provider?.[model.providerID]?.options?.baseURL !== "string") throw new Error("Offline mode requires a locally configured model endpoint.") if (!OFFLINE_SDKS.has(model.api.npm)) throw new Error("Offline mode requires a bundled HTTP model provider such as @ai-sdk/openai-compatible.") @@ -2185,7 +2185,7 @@ export namespace Provider { if (existing) return existing // altimate_change start — constrain offline model transport to its configured origin - const customFetch = offlineMode ? offlineModelFetch(baseURL) : options["fetch"] + 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. diff --git a/packages/opencode/src/pty/index.ts b/packages/opencode/src/pty/index.ts index a3a8c3941a..3c4946fef1 100644 --- a/packages/opencode/src/pty/index.ts +++ b/packages/opencode/src/pty/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode skips terminal subprocesses -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" @@ -127,7 +127,7 @@ export namespace Pty { export async function create(input: CreateInput) { // altimate_change start — offline mode skips terminal subprocesses - if (offline()) throw new Error("Terminal sessions are disabled in offline mode.") + if (Offline.enabled()) throw new Error("Terminal sessions are disabled in offline mode.") // altimate_change end const id = PtyID.ascending() const command = input.command || Shell.preferred() diff --git a/packages/opencode/src/session/instruction.ts b/packages/opencode/src/session/instruction.ts index 24789f651a..66958fdbe0 100644 --- a/packages/opencode/src/session/instruction.ts +++ b/packages/opencode/src/session/instruction.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +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" @@ -102,7 +102,7 @@ export const layer: Layer.Layer< const fetch = Effect.fnUntraced(function* (url: string) { // altimate_change start — skip network work in offline mode - if (offline()) return "" + if (Offline.enabled()) return "" // altimate_change end const res = yield* http.execute(HttpClientRequest.get(url)).pipe( Effect.timeout(5000), diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index f859e5dca4..09afd072e1 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline, warnOffline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import path from "path" import { Token } from "@/util/token" @@ -478,11 +478,11 @@ 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. - if (offline()) { + if (Offline.enabled()) { const dir = Instance.directory const { snapshotRoot, ownManifest } = await import("../altimate/workspace/skill-sync") const snapshot = await ownManifest(dir) - await warnOffline(snapshot !== null) + await Offline.announce(snapshot !== null) if (existsSync(snapshotRoot(dir))) await refreshSkillRegistry(dir) } else if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { const dir = Instance.directory @@ -4332,7 +4332,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the export type ShellInput = z.infer export async function shell(input: ShellInput) { // altimate_change start — prevent direct shell execution in offline sessions - if (offline()) throw new Error("Shell commands are disabled in offline mode.") + if (Offline.enabled()) throw new Error("Shell commands are disabled in offline mode.") // altimate_change end const abort = start(input.sessionID) if (!abort) { @@ -4842,7 +4842,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the const shell = ConfigMarkdown.shell(template) if (shell.length > 0) { // altimate_change start — template expansion can invoke an arbitrary program - if (offline()) throw new Error("Shell commands are disabled in offline mode.") + if (Offline.enabled()) throw new Error("Shell commands are disabled in offline mode.") // altimate_change end // altimate_change start — upstream_fix: command template shell // expansion must honor configured shell instead of Bun's default parser. diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 7528194018..2144d31d27 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { Bus } from "@/bus" import { Account } from "@/account" @@ -79,7 +79,7 @@ export namespace ShareNext { export async function init() { // altimate_change start — skip session sharing in offline mode - if (offline() || disabled) return + if (Offline.enabled() || disabled) return // altimate_change end Bus.subscribe(Session.Event.Updated, async (evt) => { await sync(evt.properties.info.id, [ @@ -129,7 +129,7 @@ export namespace ShareNext { export async function create(sessionID: SessionID) { // altimate_change start — skip session sharing in offline mode - if (offline() || disabled) return { id: "", url: "", secret: "" } + if (Offline.enabled() || disabled) return { id: "", url: "", secret: "" } // altimate_change end log.info("creating share", { sessionID }) const req = await request() @@ -212,7 +212,7 @@ export namespace ShareNext { const queue = new Map }>() async function sync(sessionID: SessionID, data: Data[]) { // altimate_change start — skip session sharing in offline mode - if (offline() || disabled) return + if (Offline.enabled() || disabled) return // altimate_change end const existing = queue.get(sessionID) if (existing) { @@ -259,7 +259,7 @@ export namespace ShareNext { export async function remove(sessionID: SessionID) { // altimate_change start — skip session sharing in offline mode - if (offline() || disabled) return + if (Offline.enabled() || disabled) return // altimate_change end log.info("removing share", { sessionID }) const share = get(sessionID) diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index 9c6a2abbc4..40274286d4 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { NodePath } from "@effect/platform-node" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -59,7 +59,7 @@ export namespace Discovery { const pull = Effect.fn("Discovery.pull")(function* (url: string) { // altimate_change start — skip network work in offline mode - if (offline()) return [] + if (Offline.enabled()) return [] // altimate_change end const base = url.endsWith("/") ? url : `${url}/` const index = new URL("index.json", base).href diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 536cac7ef2..e03200c259 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { PlanExitTool } from "./plan" import { QuestionTool } from "./question" @@ -420,9 +420,10 @@ export namespace ToolRegistry { configInput?: RegistryConfigInput, ): Promise { // altimate_change start — offer only local tools in offline mode - if (offline()) { + const question = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL + if (Offline.enabled()) { return AppRuntime.runPromise(Effect.scoped(Effect.all([ - InvalidTool, QuestionTool, ReadTool, GlobTool, GrepTool, EditTool, WriteTool, + InvalidTool, ...(question ? [QuestionTool] : []), ReadTool, GlobTool, GrepTool, EditTool, WriteTool, TaskTool, TodoWriteTool, SkillTool, ApplyPatchTool, WarehouseInstallDriverTool, ]))) } @@ -435,7 +436,6 @@ export namespace ToolRegistry { // altimate_change end const config = configInput?.config ?? (await Config.get()) // altimate_change end - const question = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL // 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. diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 6a7546d329..adc29287bf 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode does not run project startup scripts -import { offline } from "@/config/offline" +import { Offline } from "@/config/offline" // altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { path } from "@opencode-ai/core/effect/layer-node-platform" @@ -495,7 +495,7 @@ export const layer: Layer.Layer< const runStartScript = Effect.fnUntraced(function* (directory: string, cmd: string, kind: string) { // altimate_change start — keep worktree startup commands offline - if (offline()) return true + if (Offline.enabled()) return true // altimate_change end const text = cmd.trim() if (!text) return true diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 05fffe0dab..e9370d2b67 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -11,13 +11,14 @@ const TENANT = "offline-fixture" const KEY = "fixture-key" const SKILL = "This unique statement came from the cached offline skill." -async function fixture(snapshot: boolean, configMode: boolean) { +async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: boolean) { 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 calls = path.join(root, "calls.jsonl") const preload = path.join(root, "preload.ts") + const blocked = path.join(root, "blocked.jsonl") 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"), @@ -101,19 +102,28 @@ async function fixture(snapshot: boolean, configMode: boolean) { ALTIMATE_OFFLINE: configMode ? "" : "1", // The environment switch must preserve the snapshot even when a deployment // still has the old workspace opt-out set. - ALTIMATE_DISABLE_WORKSPACE: configMode ? "" : "1", + 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, manifest, skill } + return { root, project, preload, env, calls, blocked, manifest, skill } } -for (const configMode of [false, true]) { - test(`offline ${configMode ? "config" : "environment"} keeps network traffic on the model endpoint`, async () => { - const f = await fixture(!configMode, configMode) +for (const { scenario, snapshot, configMode, disableWorkspace } of [ + { + scenario: "environment switch with the workspace opt-out", + snapshot: true, + configMode: false, + disableWorkspace: true, + }, + { scenario: "config switch with a cached snapshot", snapshot: true, configMode: true, disableWorkspace: false }, + { scenario: "config switch without a snapshot", snapshot: false, configMode: true, disableWorkspace: false }, +]) { + test(`offline ${scenario} keeps network traffic on the model endpoint`, async () => { + const f = await fixture(snapshot, configMode, disableWorkspace) try { - const before = configMode ? undefined : await fs.readFile(f.manifest, "utf8") + 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, env: f.env, @@ -134,12 +144,13 @@ for (const configMode of [false, true]) { .filter(Boolean) .map((line) => JSON.parse(line)) expect(calls.filter((call) => call.url !== MODEL_ENDPOINT + "/chat/completions")).toEqual([]) + 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(!configMode) + expect(calls.some((call) => call.hasSkill)).toBe(snapshot) expect(stderr.match(/Offline mode:/g)).toHaveLength(1) expect(stderr).not.toContain("Workspace skills not synced") - if (configMode) expect(stderr).toContain("No usable workspace skill snapshot") + if (!snapshot) expect(stderr).toContain("No usable workspace skill snapshot") else { expect(await fs.readFile(f.manifest, "utf8")).toBe(before!) expect(await fs.readFile(f.skill, "utf8")).toContain(SKILL) @@ -175,10 +186,17 @@ test("offline model transport bypasses proxy settings and refuses redirects", as process.execPath, "-e", ` - import { startOfflineMode, offlineModelFetch } from ${JSON.stringify(source)} - await startOfflineMode(process.cwd()) - const request = offlineModelFetch(process.env.OFFLINE_TEST_MODEL) + import { Offline } from ${JSON.stringify(source)} + await Offline.start(process.cwd()) + const request = Offline.modelFetch(process.env.OFFLINE_TEST_MODEL) console.log(await (await request(process.env.OFFLINE_TEST_MODEL)).text()) + try { + await request(process.env.HTTP_PROXY) + throw new Error("cross-origin request was accepted") + } catch (error) { + if (!error.message.includes("outside the configured model endpoint")) throw error + console.log("cross-origin request refused") + } try { await request(new URL("/redirect", process.env.OFFLINE_TEST_MODEL)) throw new Error("redirect was accepted") @@ -211,7 +229,7 @@ test("offline model transport bypasses proxy settings and refuses redirects", as ]) expect({ code, stdout, stderr }).toEqual({ code: 0, - stdout: "direct model response\nredirect refused\n", + stdout: "direct model response\ncross-origin request refused\nredirect refused\n", stderr: "", }) expect(proxyCalls).toBe(0) @@ -220,3 +238,69 @@ test("offline model transport bypasses proxy settings and refuses redirects", as proxy.stop(true) } }) + +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 does not launch a configured 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 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 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(20_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(false) + expect({ code, stdout, stderr }).toMatchObject({ code: 0, stdout: expect.stringContaining("{}") }) + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 25_000) From 866ad87361214904a7d0b714d05e27adb18c9db4 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:52:39 -0800 Subject: [PATCH 06/72] fix: keep offline gating separate from account state --- packages/opencode/src/config/config.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index eb902d69a7..f181222d22 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -692,16 +692,17 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } - // altimate_change start — skip account network config in offline mode - const activeAccount = Offline.enabled() - ? undefined - : Option.getOrUndefined(yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none())))) - // altimate_change end + const activeAccount = Option.getOrUndefined( + yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none()))), + ) if (activeAccount?.active_org_id) { const accountID = activeAccount.id 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 }, From 026d63f8dc9d0d987f0de523a53ab6cda31913d9 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:58:47 -0800 Subject: [PATCH 07/72] fix: close remaining offline egress paths --- docs/mcp-workspaces.md | 2 +- .../src/altimate/workspace/api-client.ts | 2 + .../src/altimate/workspace/memory-sync.ts | 3 +- .../src/altimate/workspace/review-notices.ts | 3 +- .../opencode/src/altimate/workspace/state.ts | 7 +- packages/opencode/src/config/offline.ts | 39 +++++--- packages/opencode/src/index.ts | 3 +- packages/opencode/src/provider/provider.ts | 30 +++---- packages/opencode/src/session/prompt.ts | 4 +- packages/opencode/src/worktree/index.ts | 3 + .../opencode/test/cli/run/offline.test.ts | 88 ++++++++++++++++++- 11 files changed, 148 insertions(+), 36 deletions(-) diff --git a/docs/mcp-workspaces.md b/docs/mcp-workspaces.md index e8b3a163cf..43253b2168 100644 --- a/docs/mcp-workspaces.md +++ b/docs/mcp-workspaces.md @@ -20,7 +20,7 @@ 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. +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 diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index 4af0971b40..ee896fcfe3 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -1,3 +1,4 @@ +import { Offline } from "@/config/offline" // altimate_change - new file // // Wire client for the workspace-binding endpoints in altimate-backend @@ -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/memory-sync.ts b/packages/opencode/src/altimate/workspace/memory-sync.ts index df928a7cd3..f3f63e91e6 100644 --- a/packages/opencode/src/altimate/workspace/memory-sync.ts +++ b/packages/opencode/src/altimate/workspace/memory-sync.ts @@ -1,3 +1,4 @@ +import { Offline } from "@/config/offline" // altimate_change - new file // // Mirrors Altimate Code memory blocks to the workspace memory store, and loads @@ -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..83fb90814b 100644 --- a/packages/opencode/src/altimate/workspace/review-notices.ts +++ b/packages/opencode/src/altimate/workspace/review-notices.ts @@ -1,3 +1,4 @@ +import { Offline } from "@/config/offline" // altimate_change - new file // // Notices for the person's own workspace review requests (skills and knowledge bases): when the owner approves or @@ -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/state.ts b/packages/opencode/src/altimate/workspace/state.ts index fb501c52f9..ff683e34ee 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -1,3 +1,4 @@ +import { Offline } from "@/config/offline" // altimate_change - new file // // Local binding cache — offline fallback for the server-authoritative @@ -764,7 +765,7 @@ export async function resolvePinnedBindingForRouting( ): Promise { const pin = readPinLogged() if (pin.kind === "absent") return null - if (pin.kind === "invalid") return { status: "unknown" } + if (Offline.enabled() || pin.kind === "invalid") return { status: "unknown" } return resolvePinnedBinding(directory, pin) } @@ -861,6 +862,10 @@ export function endTurnBinding(sessionID: string): void { } export async function resolveBindingOutcome(directory: string): Promise { + if (Offline.enabled()) { + const local = readPin().kind === "absent" ? await readLocalBinding(directory).catch(() => null) : null + return local ? { status: "bound", binding: local, stale: true } : { status: "unknown" } + } // altimate_change — the IDE extension's selection outranks whatever binding this project carries. // Checked before the local cache and before any server lookup: the whole point is that the panel, // not the project's history, decides which workspace this `serve` process works against. diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index a2246f0230..f53c0da14d 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -16,8 +16,14 @@ export { enabled } async function localOptIn(directory: string) { // The switch is an opt-in from any local config source. Read just this // key so remote credentials and unrelated substitutions cannot affect it. - const enabled = (text: string | undefined) => text !== undefined && parse(text)?.offline === true - if (enabled(env("OPENCODE_CONFIG_CONTENT"))) return true + const optedIn = async (text: string | undefined, source: string | { source: string; dir: string }) => { + if (!text) return false + if (parse(text)?.offline === true) return true + if (!text.includes('"offline"')) return false + const config = await ConfigPaths.parseText(text, source, "empty", { track: false }).catch(() => undefined) + return config?.offline === true + } + if (await optedIn(env("OPENCODE_CONFIG_CONTENT"), { source: "OPENCODE_CONFIG_CONTENT", dir: directory })) return true let worktree = path.resolve(directory) while (!(await fs.stat(path.join(worktree, ".git")).catch(() => undefined))) { const parent = path.dirname(worktree) @@ -42,9 +48,10 @@ async function localOptIn(directory: string) { Flag.OPENCODE_CONFIG, ] for (const file of files) { - if (file && enabled(await fs.readFile(file, "utf8").catch(() => undefined))) return true + if (file && (await optedIn(await fs.readFile(file, "utf8").catch(() => undefined), file))) return true } - return enabled((await ConfigManaged.readManagedPreferences().catch(() => undefined))?.text) + const managed = await ConfigManaged.readManagedPreferences().catch(() => undefined) + return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false } export async function assertStartupPolicy(directory: string) { @@ -63,6 +70,7 @@ export async function start(directory: string, model?: string) { // their layers. Once enabled, keep it for the lifetime of the process. process.env.ALTIMATE_OFFLINE = "1" process.env.GIT_NO_LAZY_FETCH = "1" + process.env.GIT_ALLOW_PROTOCOL = "file" // Bun consults proxy environment variables even when fetch sets proxy: "". // Offline traffic must go directly to the one configured endpoint. process.env.NO_PROXY = "*" @@ -78,18 +86,27 @@ export async function start(directory: string, model?: string) { ) } -export function provider( - config: Pick, -) { +type ModelConfig = Pick + +function configuredBaseURL(config: ModelConfig, providerID: string) { + const url = config.provider?.[providerID]?.options?.baseURL + return typeof url === "string" && url.trim() ? url : undefined +} + +function provider(config: ModelConfig) { const model = process.env.ALTIMATE_OFFLINE_MODEL ?? config.model if (model) return model.split("/")[0] - const candidates = Object.entries(config.provider ?? {}).filter( - ([id, provider]) => - typeof provider.options?.baseURL === "string" && + const candidates = Object.keys(config.provider ?? {}).filter( + (id) => + configuredBaseURL(config, id) !== undefined && (!config.enabled_providers || config.enabled_providers.includes(id)) && !config.disabled_providers?.includes(id), ) - return candidates.length === 1 ? candidates[0][0] : undefined + return candidates.length === 1 ? candidates[0] : undefined +} + +export function endpoint(config: ModelConfig, providerID: string) { + return provider(config) === providerID ? configuredBaseURL(config, providerID) : undefined } export function modelFetch(baseURL: string | undefined): typeof fetch { diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index c4b94bae03..7228b834a9 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -184,10 +184,11 @@ let cli = yargs(args) const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) await Offline.start(directory, args.model) if (Offline.enabled() && ( - ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web"].includes(command) || + ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web", "integrations"].includes(command) || (command === "run" && args.attach) || (command === "mcp" && opts._[1] === "serve") || (command === "tool" && opts._[1] === "daemon") || + (command === "learn" && opts._[1] === "import-reviews") || (["providers", "auth", "mcp", "console"].includes(command) && opts._.some((arg) => arg === "login" || arg === "auth")) )) throw new Error("This command requires network access. Run it while online.") // altimate_change end diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index 51992688de..877e40acab 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -1399,16 +1399,11 @@ export namespace Provider { const disabled = new Set(config.disabled_providers ?? []) const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null - // altimate_change start — offline provider selection is independent of online fallback rules - const offlineProviderID = Offline.enabled() ? Offline.provider(config) : undefined - // altimate_change end function isProviderAllowed(providerID: ProviderID): boolean { // altimate_change start — require a locally configured model endpoint in offline mode if (Offline.enabled()) { - const options = config.provider?.[providerID]?.options if ( - providerID !== offlineProviderID || - typeof options?.baseURL !== "string" || + !Offline.endpoint(config, providerID) || providerID === FreeTier.PROVIDER_ID || providerID === ClaudeAgent.ID ) return false @@ -2138,9 +2133,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" @@ -2171,14 +2175,8 @@ export namespace Provider { // altimate_change end // altimate_change start — constrain offline model transport to its configured origin - const offlineMode = Offline.enabled() - if (offlineMode) { - const config = await Config.get() - if (Offline.provider(config) !== model.providerID || typeof config.provider?.[model.providerID]?.options?.baseURL !== "string") - throw new Error("Offline mode requires a locally configured model endpoint.") - if (!OFFLINE_SDKS.has(model.api.npm)) - throw new Error("Offline mode requires a bundled HTTP model provider such as @ai-sdk/openai-compatible.") - } + if (offlineMode && !OFFLINE_SDKS.has(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) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 09afd072e1..a6e4e8857b 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -2445,8 +2445,8 @@ export namespace SessionPrompt { // acts on a false positive instead of only measuring it, so it should // not ship until those heuristics are consolidated into shared, // tested primitives. - const validatorsEnabled = process.env.ALTIMATE_VALIDATORS_ENABLED === "1" - const validatorsShadow = process.env.ALTIMATE_VALIDATORS_SHADOW === "1" + const validatorsEnabled = !Offline.enabled() && process.env.ALTIMATE_VALIDATORS_ENABLED === "1" + const validatorsShadow = !Offline.enabled() && process.env.ALTIMATE_VALIDATORS_SHADOW === "1" const validatorsActive = validatorsEnabled || validatorsShadow const maxValidatorRetries = Number(process.env.ALTIMATE_VALIDATORS_MAX_RETRIES ?? "3") const validatorsDebug = process.env.ALTIMATE_VALIDATORS_DEBUG === "1" diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index adc29287bf..d1855d9fcc 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -550,6 +550,9 @@ export const layer: Layer.Layer< }) const reset = Effect.fn("Worktree.reset")(function* (input: ResetInput) { + // altimate_change start — reset fetches the base and refreshes submodules + if (Offline.enabled()) return yield* new ResetFailedError({ message: "Reset this worktree while online." }) + // altimate_change end const ctx = yield* InstanceState.context if (ctx.project.vcs !== "git") { return yield* new NotGitError({ message: "Worktrees are only supported for git projects" }) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index e9370d2b67..703c3fdde8 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -34,7 +34,10 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: mcp: { remoteFixture: { type: "remote", url: "https://mcp.test" } }, }), ) - if (configMode) await Bun.write(path.join(project, "opencode.jsonc"), '{ // local policy\n "offline": true }') + if (configMode) { + const value = snapshot ? "{env:OFFLINE_CONFIG_VALUE}" : "true" + await Bun.write(path.join(project, "opencode.jsonc"), `{ // local policy\n "offline": ${value} }`) + } await Bun.write( path.join(data, "auth.json"), JSON.stringify({ @@ -88,6 +91,18 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: 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 = { @@ -100,6 +115,7 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: XDG_CACHE_HOME: path.join(root, "cache"), XDG_STATE_HOME: path.join(root, "state"), ALTIMATE_OFFLINE: configMode ? "" : "1", + OFFLINE_CONFIG_VALUE: "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" : "", @@ -117,7 +133,12 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ configMode: false, disableWorkspace: true, }, - { scenario: "config switch with a cached snapshot", snapshot: true, configMode: true, disableWorkspace: false }, + { + 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 }, ]) { test(`offline ${scenario} keeps network traffic on the model endpoint`, async () => { @@ -304,3 +325,66 @@ test("offline mode does not launch a configured language server", async () => { await fs.rm(f.root, { recursive: true, force: true }) } }, 25_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, +) From 843dc3e67b96a4962bb4dadc76c8f5db84d4894b Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:05:17 -0800 Subject: [PATCH 08/72] fix: finish offline config, skill, and share guards --- docs/docs/configure/config.md | 2 +- packages/opencode/src/cli/cmd/skill.ts | 2 + packages/opencode/src/config/offline.ts | 1 - .../src/plugin/tui/altimate/skill-ops.tsx | 3 ++ packages/opencode/src/share/share-next.ts | 5 +- packages/opencode/src/worktree/index.ts | 3 ++ .../opencode/test/cli/run/offline.test.ts | 50 +++++++++++++++++-- .../opencode/test/share/share-next.test.ts | 19 ++++++- 8 files changed, 74 insertions(+), 11 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index a9558c5374..650b8e754e 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -170,4 +170,4 @@ Before going offline: 2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice indicating whether cached skills are available. 3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Offline mode disables all warehouse connections, including local DuckDB and SQLite, and automatic driver installs. -Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Install `ripgrep` ahead of time if you need file search on a fresh host. +Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Creating or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index 84f0043e7b..70a7fb484c 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -413,6 +413,8 @@ const SkillTestCommand = cmd({ const tools = detectToolReferences(skill.content) if (tools.length === 0) { warn(`No CLI tool references detected in skill content`) + } else if (Offline.enabled()) { + warn("Paired tool checks require online mode.") } else { process.stdout.write(EOL + ` Paired tools:` + EOL) for (const tool of tools) { diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index f53c0da14d..b49a42e0b2 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -19,7 +19,6 @@ async function localOptIn(directory: string) { const optedIn = async (text: string | undefined, source: string | { source: string; dir: string }) => { if (!text) return false if (parse(text)?.offline === true) return true - if (!text.includes('"offline"')) return false const config = await ConfigPaths.parseText(text, source, "empty", { track: false }).catch(() => undefined) return config?.offline === true } diff --git a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx index d5b52efdc9..374fde3387 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`, @@ -289,6 +291,7 @@ async function testSkillDirect( ): Promise<{ ok: boolean; message: string }> { const tools = detectToolReferences(content) if (tools.length === 0) return { ok: true, message: `${skillName}: PASS (no CLI tools)` } + if (Offline.enabled()) return { ok: false, message: "Paired tool checks require online mode." } const sep = process.platform === "win32" ? ";" : ":" const toolPath = [ diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 2144d31d27..fefb90c41c 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -258,9 +258,10 @@ export namespace ShareNext { } export async function remove(sessionID: SessionID) { - // altimate_change start — skip session sharing in offline mode - if (Offline.enabled() || disabled) return + // altimate_change start — keep the local share state until the server revokes it + if (Offline.enabled()) throw new Error("Offline mode cannot revoke a share. Run unshare while online.") // altimate_change end + if (disabled) return log.info("removing share", { sessionID }) const share = get(sessionID) if (!share) return diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index d1855d9fcc..a15ca580b2 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -234,6 +234,9 @@ export const layer: Layer.Layer< }) const setup = Effect.fnUntraced(function* (info: Info) { + // altimate_change start — checkout filters can launch programs such as Git LFS + if (Offline.enabled()) return yield* new CreateFailedError({ message: "Create this worktree while online." }) + // altimate_change end const ctx = yield* InstanceState.context const created = yield* git( info.branch diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 703c3fdde8..35ade6b6e7 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -34,10 +34,8 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: mcp: { remoteFixture: { type: "remote", url: "https://mcp.test" } }, }), ) - if (configMode) { - const value = snapshot ? "{env:OFFLINE_CONFIG_VALUE}" : "true" - await Bun.write(path.join(project, "opencode.jsonc"), `{ // local policy\n "offline": ${value} }`) - } + 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({ @@ -115,7 +113,12 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: XDG_CACHE_HOME: path.join(root, "cache"), XDG_STATE_HOME: path.join(root, "state"), ALTIMATE_OFFLINE: configMode ? "" : "1", - OFFLINE_CONFIG_VALUE: "true", + ...(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" : "", @@ -388,3 +391,40 @@ test.skipIf(process.platform === "win32")( }, 45_000, ) + +test.skipIf(process.platform === "win32")( + "offline skill validation skips running paired tools", + async () => { + const f = await fixture(true, false, false) + const bin = path.join(f.root, "bin") + const marker = path.join(f.root, "unexpected-tool") + 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(), + ]) + expect(await Bun.file(marker).exists()).toBe(false) + expect({ code, stdout, stderr }).toMatchObject({ + code: 0, + stdout: expect.stringContaining("Paired tool checks require online mode."), + }) + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } + }, + 25_000, +) diff --git a/packages/opencode/test/share/share-next.test.ts b/packages/opencode/test/share/share-next.test.ts index 86f2ddf7db..94be5b9089 100644 --- a/packages/opencode/test/share/share-next.test.ts +++ b/packages/opencode/test/share/share-next.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect } from "bun:test" +import { afterEach, beforeEach, describe, expect, test } from "bun:test" import { Effect, Exit, Layer, Option } from "effect" import { HttpClient } from "effect/unstable/http" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -10,7 +10,7 @@ import { AccessToken, AccountID, OrgID, RefreshToken } from "../../src/account/s import { AccountRepo } from "../../src/account/repo" import { EventV2Bridge } from "../../src/event-v2-bridge" import { Session } from "@/session/session" -import type { SessionID } from "../../src/session/schema" +import { SessionID } from "../../src/session/schema" import { ShareNext } from "@/share/share-next" import { SessionShareTable } from "@opencode-ai/core/share/sql" import { AccountStateTable, AccountTable } from "@opencode-ai/core/account/sql" @@ -112,6 +112,21 @@ beforeEach(async () => { }) describe("ShareNext", () => { + test("offline share revocation fails so unshare retains the local share state", async () => { + const prior = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + installFetchMock(() => new Response(null, { status: 200 })) + try { + await expect(ShareNext.remove(SessionID.make("ses_offline_share"))).rejects.toThrow( + "Offline mode cannot revoke a share. Run unshare while online.", + ) + expect(fetchRecords).toEqual([]) + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } + }) + it.live("request uses legacy share API without active org account", () => provideTmpdirInstance( () => From ef47e04ca6137d254d995bad6f4eda440a57120f Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:09:36 -0800 Subject: [PATCH 09/72] fix: block ripgrep downloads and Git snapshot filters offline --- docs/docs/configure/config.md | 2 +- packages/core/src/ripgrep/binary.ts | 7 ++++++ packages/opencode/src/file/ripgrep.ts | 6 +++++ packages/opencode/src/snapshot/index.ts | 21 ++++++++++++++++ .../opencode/test/cli/run/offline.test.ts | 3 ++- .../opencode/test/snapshot/snapshot.test.ts | 25 +++++++++++++++++++ 6 files changed, 62 insertions(+), 2 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 650b8e754e..4f552f025c 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -170,4 +170,4 @@ Before going offline: 2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice indicating whether cached skills are available. 3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Offline mode disables all warehouse connections, including local DuckDB and SQLite, and automatic driver installs. -Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Creating or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. +Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Git-backed session snapshots and revert are disabled. Creating or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. 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/opencode/src/file/ripgrep.ts b/packages/opencode/src/file/ripgrep.ts index d2356219d6..60c04a1389 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,9 @@ export namespace Ripgrep { const filepath = path.join(Global.Path.bin, "rg" + (process.platform === "win32" ? ".exe" : "")) if (!(await Filesystem.exists(filepath))) { + // altimate_change start — preserve installed ripgrep and skip downloads offline + if (offlineModeEnabled()) throw 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] if (!config) throw new UnsupportedPlatformError({ platform: platformKey }) diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index 44da196626..e0f2fa5655 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode skips Git snapshot operations +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Cause, Duration, Effect, Layer, Schedule, Schema, Semaphore, Context } from "effect" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" @@ -167,6 +170,9 @@ export const layer: Layer.Layer(fx: Effect.Effect) => lock(state.gitdir).withPermits(1)(fx) const enabled = Effect.fnUntraced(function* () { + // altimate_change start — git add can execute a configured clean filter + if (offlineModeEnabled()) return false + // altimate_change end if (state.vcs !== "git") return false return (yield* config.get()).snapshot !== false }) @@ -349,6 +355,9 @@ export const layer: Layer.Layer(config: string, self: Effect.Effect '${fwd(marker)}'; cat`]) + yield* write(path.join(directory, ".gitattributes"), "*.txt filter=offline-fixture\n") + yield* write(path.join(directory, "data.txt"), "fixture") + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const snapshot = yield* Snapshot.Service + const current = yield* withGitConfigGlobal(config, snapshot.track()) + expect(yield* exists(marker)).toBe(false) + expect(current).toBeUndefined() + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), + { git: true }, +) + it.instance( "tracks deleted files correctly", withTrackedSnapshot(({ tmp, snapshot, before }) => From ff68bbaa42fdf6493efccc0f18c3241d18fa1931 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:16:03 -0800 Subject: [PATCH 10/72] fix: skip working-tree Git filters offline --- docs/docs/configure/config.md | 2 +- packages/opencode/src/file/index.ts | 10 ++++++- packages/opencode/src/git/index.ts | 7 +++++ .../opencode/test/cli/run/offline.test.ts | 2 +- packages/opencode/test/project/vcs.test.ts | 29 +++++++++++++++++++ 5 files changed, 47 insertions(+), 3 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 4f552f025c..058194d245 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -170,4 +170,4 @@ Before going offline: 2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice indicating whether cached skills are available. 3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Offline mode disables all warehouse connections, including local DuckDB and SQLite, and automatic driver installs. -Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Git-backed session snapshots and revert are disabled. Creating or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. +Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Git-backed file diffs, session snapshots and revert are disabled. Creating or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. diff --git a/packages/opencode/src/file/index.ts b/packages/opencode/src/file/index.ts index bd1c45d042..4008a41c7b 100644 --- a/packages/opencode/src/file/index.ts +++ b/packages/opencode/src/file/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — skip Git filters when reading files offline +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end import { BusEvent } from "@/bus/bus-event" import z from "zod" import { formatPatch, structuredPatch } from "diff" @@ -440,6 +443,9 @@ export namespace File { } export async function status() { + // altimate_change start — skip Git working-tree status in offline mode + if (offlineModeEnabled()) return [] + // altimate_change end const project = Instance.project if (project.vcs !== "git") return [] @@ -567,7 +573,9 @@ export namespace File { const content = (await Filesystem.readText(full).catch(() => "")).trim() - if (project.vcs === "git") { + // altimate_change start — retain file content without the Git working-tree comparison + if (!offlineModeEnabled() && project.vcs === "git") { + // altimate_change end let diff = (await git(["-c", "core.fsmonitor=false", "diff", "--", file], { cwd: Instance.directory })).text() if (!diff.trim()) { diff = ( diff --git a/packages/opencode/src/git/index.ts b/packages/opencode/src/git/index.ts index dda3a3bec1..81d71d934f 100644 --- a/packages/opencode/src/git/index.ts +++ b/packages/opencode/src/git/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — skip working-tree Git operations that can run filters +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// 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 +112,10 @@ export const layer = Layer.effect( const run = Effect.fn("Git.run")( function* (args: string[], opts: Options) { + // altimate_change start — Git can launch filters independently of its network transport + if (offlineModeEnabled() && ["diff", "status", "apply"].includes(args[0])) + return fail(new Error("Git working-tree operations require an online run.")) + // altimate_change end const result = yield* appProcess.run( ChildProcess.make("git", [...cfg, ...args], { cwd: opts.cwd, diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index b2f742f058..2f1627a23a 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -151,7 +151,7 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ 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. - env: snapshot ? f.env : { ...f.env, PATH: path.join(f.root, "empty-path") }, + env: configMode ? { ...f.env, PATH: path.join(f.root, "empty-path") } : f.env, stdin: "ignore", stdout: "pipe", stderr: "pipe", diff --git a/packages/opencode/test/project/vcs.test.ts b/packages/opencode/test/project/vcs.test.ts index 21620adaf0..86e60f8071 100644 --- a/packages/opencode/test/project/vcs.test.ts +++ b/packages/opencode/test/project/vcs.test.ts @@ -157,6 +157,35 @@ describe("Vcs", () => { }) describe("Vcs diff", () => { + worktreeIt.instance( + "offline VCS status and diff do not execute Git working-tree filters", + Effect.gen(function* () { + const { directory } = yield* TestInstance + const marker = path.join(directory, "filter-ran") + yield* write(path.join(directory, ".gitattributes"), "*.txt filter=offline-fixture\n") + yield* write(path.join(directory, "data.txt"), "before\n") + yield* git(directory, ["add", "."]) + yield* git(directory, ["commit", "-m", "test filter fixture"]) + yield* git(directory, ["config", "filter.offline-fixture.clean", + `printf 'filter ran' > '${marker.replaceAll("\\", "/")}'; cat`]) + 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 + const state = yield* vcs.status() + const diff = yield* vcs.diff("git") + expect(yield* FSUtil.Service.use((fs) => fs.existsSafe(marker))).toBe(false) + expect(state).toEqual([]) + expect(diff).toEqual([]) + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } + }), + { git: true }, + ) + afterEach(async () => { await disposeAllInstances() }) From 890417a7d0822380ec84ebeead3f7f58cb90e5f7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:25:17 -0800 Subject: [PATCH 11/72] fix: preserve early MCP stdio startup and refuse offline browser launch --- packages/opencode/src/cli/cmd/mcp.ts | 5 ++++ packages/opencode/src/index.ts | 9 ++++--- .../opencode/test/cli/run/offline.test.ts | 27 +++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index c72bfe119a..7eede44489 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -1,3 +1,6 @@ +// altimate_change start — check offline policy before starting the standalone MCP server +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,6 +140,8 @@ 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) { + await Offline.start(process.cwd()) + if (Offline.enabled()) throw new Error("Run the standalone MCP server while online.") const { serveStdio } = await import("../../altimate/mcp-server/server") await serveStdio({ connections: args.connections, allowWrite: args.allowWrite, allTools: args.allTools, workspaceTools: args.workspaceTools }) }, diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 7228b834a9..347e98406c 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -168,6 +168,10 @@ let cli = yargs(args) if (opts.pure) { process.env.OPENCODE_PURE = "1" } + // altimate_change start — MCP stdio needs no banner, telemetry startup or agent initialization + if (opts._[0] === "mcp" && opts._[1] === "serve") return + // altimate_change end + // altimate_change start — skip network work in offline mode const command = String(opts._[0] ?? "") const args = opts as { @@ -186,15 +190,12 @@ let cli = yargs(args) if (Offline.enabled() && ( ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web", "integrations"].includes(command) || (command === "run" && args.attach) || - (command === "mcp" && opts._[1] === "serve") || (command === "tool" && opts._[1] === "daemon") || (command === "learn" && opts._[1] === "import-reviews") || + (command === "console" && opts._[1] === "open") || (["providers", "auth", "mcp", "console"].includes(command) && opts._.some((arg) => arg === "login" || arg === "auth")) )) throw new Error("This command requires network access. Run it while online.") // altimate_change end - // altimate_change start — MCP stdio needs no banner, telemetry startup or agent initialization - if (opts._[0] === "mcp" && opts._[1] === "serve") return - // altimate_change end Heap.start() diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 2f1627a23a..e1fcb8c2a6 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -429,3 +429,30 @@ test.skipIf(process.platform === "win32")( }, 25_000, ) + +test("standalone MCP rejects offline config before opening stdio", 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: "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: 1, + stdout: "", + stderr: expect.stringContaining("Run the standalone MCP server while online."), + }) + expect(await fs.readFile(f.calls, "utf8").catch(() => "")).toBe("") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 35_000) From 27c9af28c74137cd2295bdd52790b7ba4cab1ad8 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:33:30 -0800 Subject: [PATCH 12/72] fix: allow only Git metadata reads in offline mode --- docs/docs/configure/config.md | 2 +- packages/core/src/flag/flag.ts | 2 -- packages/opencode/src/altimate/debug/collect.ts | 2 -- packages/opencode/src/cli/cmd/tui.ts | 2 -- packages/opencode/src/cli/tui/worker.ts | 2 -- packages/opencode/src/file/ripgrep.ts | 2 -- packages/opencode/src/git/index.ts | 15 ++++++++++++++- packages/opencode/src/mcp/index.ts | 2 -- packages/opencode/src/tool/registry.ts | 2 -- packages/opencode/src/worktree/index.ts | 3 +++ packages/opencode/test/project/vcs.test.ts | 5 +++++ 11 files changed, 23 insertions(+), 16 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 058194d245..bca67d9a44 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -170,4 +170,4 @@ Before going offline: 2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice indicating whether cached skills are available. 3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Offline mode disables all warehouse connections, including local DuckDB and SQLite, and automatic driver installs. -Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Git-backed file diffs, session snapshots and revert are disabled. Creating or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. +Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Git-backed file diffs, session snapshots and revert are disabled. Creating, removing, or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index 26e13479c3..a9e4741573 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -20,11 +20,9 @@ export function env(key: string): string | undefined { return documented !== undefined && documented !== "" ? documented : process.env[key] } -// altimate_change start — read offline policy after the CLI startup config preflight export function offlineModeEnabled() { return process.env.ALTIMATE_OFFLINE === "1" } -// altimate_change end export function truthy(key: string) { const value = env(key)?.toLowerCase() diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 0cf1517825..157fe9a5c9 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -313,9 +313,7 @@ export async function probe( opts: { proxy?: boolean; timeoutMs?: number } = {}, deps: ProbeDeps = defaultProbeDeps, ): Promise { - // altimate_change start — skip network work in offline mode if (Offline.enabled()) return { target, host, ok: false, detail: "Skipped in offline mode", ms: 0 } - // altimate_change end const timeoutMs = opts.timeoutMs ?? NETWORK_TIMEOUT_MS const started = Date.now() const deadline = AbortSignal.timeout(timeoutMs) diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 7cb89486ac..9446ba5c2f 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -249,12 +249,10 @@ export const TuiThreadCommand = cmd({ network.port !== 0 || network.hostname !== "127.0.0.1" - // altimate_change start — keep the TUI's own requests inside its offline worker const listener = external ? await client.call("server", network) : undefined const transport = listener && !Offline.enabled() ? { url: listener.url, - // altimate_change end fetch: undefined, events: undefined, } diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 946d69ac28..6269a67454 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -44,11 +44,9 @@ import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding" // its events buffer until Telemetry.init() runs inside the Instance context in traceReady below // (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). -// altimate_change start — the parent has already selected the process-wide policy if (Offline.enabled()) await Offline.start(process.cwd()) else Telemetry.startLoopMonitor() // altimate_change end -// 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 // entry persisted without its env block (e.g. missing ELECTRON_RUN_AS_NODE for an diff --git a/packages/opencode/src/file/ripgrep.ts b/packages/opencode/src/file/ripgrep.ts index 60c04a1389..2d161b2776 100644 --- a/packages/opencode/src/file/ripgrep.ts +++ b/packages/opencode/src/file/ripgrep.ts @@ -99,9 +99,7 @@ export namespace Ripgrep { const filepath = path.join(Global.Path.bin, "rg" + (process.platform === "win32" ? ".exe" : "")) if (!(await Filesystem.exists(filepath))) { - // altimate_change start — preserve installed ripgrep and skip downloads offline if (offlineModeEnabled()) throw 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] if (!config) throw new UnsupportedPlatformError({ platform: platformKey }) diff --git a/packages/opencode/src/git/index.ts b/packages/opencode/src/git/index.ts index 81d71d934f..a5317971ef 100644 --- a/packages/opencode/src/git/index.ts +++ b/packages/opencode/src/git/index.ts @@ -20,6 +20,19 @@ const cfg = [ "core.quotepath=false", ] as const +// altimate_change start — permit only the metadata reads used by offline clients +const offlineMetadataCommands = new Set(["rev-parse", "symbolic-ref", "for-each-ref", "merge-base"]) + +function gitCommandAllowedOffline(args: string[]) { + const [command, operation] = args + if (offlineMetadataCommands.has(command)) return true + if (command === "remote") return args.length === 1 + if (command === "config") return args.length === 2 && operation === "init.defaultBranch" + if (command === "show") return args.length === 2 && !operation.startsWith("-") && operation.includes(":") + return command === "worktree" && operation === "list" +} +// altimate_change end + const out = (result: { text(): string }) => result.text().trim() const nuls = (text: string) => text.split("\0").filter(Boolean) const fail = (err: unknown) => @@ -113,7 +126,7 @@ export const layer = Layer.effect( const run = Effect.fn("Git.run")( function* (args: string[], opts: Options) { // altimate_change start — Git can launch filters independently of its network transport - if (offlineModeEnabled() && ["diff", "status", "apply"].includes(args[0])) + if (offlineModeEnabled() && !gitCommandAllowedOffline(args)) return fail(new Error("Git working-tree operations require an online run.")) // altimate_change end const result = yield* appProcess.run( diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 9745966303..d8fb83d456 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -1381,9 +1381,7 @@ export const layer = Layer.effect( }) const beginAuth = Effect.fn("MCP.beginAuth")(function* (mcpName: string, token: number) { - // altimate_change start — no external OAuth flow in offline mode if (Offline.enabled()) throw new Error("Authenticate MCP servers while online.") - // altimate_change end const lifecycle = yield* InstanceState.get(state) // altimate_change end const mcpConfig = yield* requireMcpConfig(mcpName) diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index e03200c259..0c22d47784 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -419,7 +419,6 @@ export namespace ToolRegistry { plugins?: Awaited>, configInput?: RegistryConfigInput, ): Promise { - // altimate_change start — offer only local tools in offline mode const question = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL if (Offline.enabled()) { return AppRuntime.runPromise(Effect.scoped(Effect.all([ @@ -427,7 +426,6 @@ export namespace ToolRegistry { TaskTool, TodoWriteTool, SkillTool, ApplyPatchTool, WarehouseInstallDriverTool, ]))) } - // altimate_change end const custom = configInput?.matches ? await loadCustomTools(configInput.matches).then((x) => x.custom) : await state().then((x) => x.custom) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index a15ca580b2..e41e876efb 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -413,6 +413,9 @@ export const layer: Layer.Layer< } const remove = Effect.fn("Worktree.remove")(function* (input: RemoveInput) { + // altimate_change start — reject before modifying a worktree offline + if (Offline.enabled()) return yield* new RemoveFailedError({ message: "Remove this worktree while online." }) + // altimate_change end const ctx = yield* InstanceState.context if (ctx.project.vcs !== "git") { return yield* new NotGitError({ message: "Worktrees are only supported for git projects" }) diff --git a/packages/opencode/test/project/vcs.test.ts b/packages/opencode/test/project/vcs.test.ts index 86e60f8071..c93ab97da6 100644 --- a/packages/opencode/test/project/vcs.test.ts +++ b/packages/opencode/test/project/vcs.test.ts @@ -175,6 +175,11 @@ describe("Vcs diff", () => { const vcs = yield* Vcs.Service const state = yield* vcs.status() const diff = yield* vcs.diff("git") + const prefixed = yield* Git.Service.use((git) => git.run( + ["-c", "core.quotepath=false", "diff", "--numstat", "HEAD"], + { cwd: directory }, + )) + expect(prefixed.exitCode).not.toBe(0) expect(yield* FSUtil.Service.use((fs) => fs.existsSafe(marker))).toBe(false) expect(state).toEqual([]) expect(diff).toEqual([]) From 1ed8928aed1b73076856193af63b8dbd335cf30f Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:34:25 -0800 Subject: [PATCH 13/72] fix: isolate offline gates from sibling changes --- packages/opencode/src/altimate/telemetry/index.ts | 8 +++----- packages/opencode/src/config/offline.ts | 6 ++++++ packages/opencode/src/provider/provider.ts | 6 +----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 6d789c8fbe..dd248bfe7b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end import { Config } from "@/config/config" import { Flag } from "@/flag/flag" import { InstallationVersion } from "@opencode-ai/core/installation/version" @@ -20,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" }) @@ -2519,7 +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 (Offline.enabled()) return Promise.resolve() + 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 @@ -2977,7 +2975,6 @@ export namespace Telemetry { // altimate_change end export function track(event: Event) { - if (Offline.enabled()) return // Before init completes: buffer (flushed once init enables, or cleared if disabled). // After init completed and disabled telemetry: drop silently. if (initDone && !enabled) return @@ -2985,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/config/offline.ts b/packages/opencode/src/config/offline.ts index b49a42e0b2..835280c19e 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -108,6 +108,12 @@ export function endpoint(config: ModelConfig, providerID: string) { return provider(config) === providerID ? configuredBaseURL(config, providerID) : undefined } +const httpSDKs = new Set(["@ai-sdk/openai-compatible", "@ai-sdk/openai", "@ai-sdk/anthropic"]) + +export function supportsSDK(npm: string) { + return httpSDKs.has(npm) +} + export function modelFetch(baseURL: string | undefined): typeof fetch { if (!baseURL) throw new Error("Offline mode requires a model provider with an explicit baseURL.") const endpoint = new URL(baseURL) diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index 877e40acab..e7da21d74f 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -107,10 +107,6 @@ const FREE_TIER_HEADER_TIMEOUT_DEFAULT = 300_000 const FREE_TIER_HEADER_TIMEOUT_MIN = 1_000 // altimate_change end -// altimate_change start — HTTP-only SDKs supported without network credential discovery -const OFFLINE_SDKS = new Set(["@ai-sdk/openai-compatible", "@ai-sdk/openai", "@ai-sdk/anthropic"]) -// altimate_change end - export namespace Provider { const log = Log.create({ service: "provider" }) @@ -2175,7 +2171,7 @@ export namespace Provider { // altimate_change end // altimate_change start — constrain offline model transport to its configured origin - if (offlineMode && !OFFLINE_SDKS.has(model.api.npm)) + 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 From 053c1293a8ebfe07d9766c21efd00870f2bb3e9a Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:07:08 -0800 Subject: [PATCH 14/72] Keep local analysis tools available in offline mode Restrict app-owned external traffic at the transport and install boundaries. Keep local warehouse and dbt execution, shell, LSP, MCP, and Git available, including Git project discovery during legacy storage migration. --- docs/docs/configure/config.md | 15 +- docs/mcp-workspaces.md | 2 +- packages/core/src/flag/flag.ts | 2 +- packages/core/src/npm.ts | 7 +- packages/core/test/npm.test.ts | 23 +++ packages/dbt-tools/src/adapter.ts | 9 +- .../opencode/src/altimate/debug/collect.ts | 4 +- packages/opencode/src/altimate/free/client.ts | 2 +- .../altimate/native/connections/offline.ts | 55 ++++++++ .../altimate/native/connections/register.ts | 10 +- .../altimate/native/connections/registry.ts | 12 +- .../src/altimate/native/dbt/offline.ts | 55 ++++++++ .../src/altimate/native/dbt/runner.ts | 20 ++- .../opencode/src/altimate/workspace/state.ts | 2 +- packages/opencode/src/bun/index.ts | 10 +- packages/opencode/src/cli/cmd/acp.ts | 7 +- packages/opencode/src/cli/cmd/mcp.ts | 12 +- packages/opencode/src/cli/cmd/models.ts | 1 + packages/opencode/src/cli/cmd/skill.ts | 12 +- packages/opencode/src/cli/cmd/tool.ts | 2 - packages/opencode/src/cli/cmd/tui.ts | 6 +- packages/opencode/src/cli/cmd/upgrade.ts | 6 + packages/opencode/src/cli/network.ts | 4 +- packages/opencode/src/config/config.ts | 10 +- packages/opencode/src/config/offline.ts | 37 ++++- packages/opencode/src/config/tui.ts | 4 +- packages/opencode/src/effect/runtime-flags.ts | 6 +- packages/opencode/src/file/index.ts | 8 +- packages/opencode/src/git/index.ts | 38 +++-- packages/opencode/src/index.ts | 3 +- packages/opencode/src/installation/index.ts | 6 +- packages/opencode/src/lsp/index.ts | 7 +- packages/opencode/src/mcp/index.ts | 13 +- packages/opencode/src/plugin/index.ts | 6 +- .../src/plugin/tui/altimate/skill-ops.tsx | 7 +- packages/opencode/src/plugin/tui/runtime.ts | 7 +- packages/opencode/src/pty/index.ts | 6 - packages/opencode/src/session/prompt.ts | 21 ++- packages/opencode/src/share/share-next.ts | 3 +- packages/opencode/src/skill/discovery.ts | 21 ++- packages/opencode/src/snapshot/index.ts | 25 +--- packages/opencode/src/tool/registry.ts | 21 ++- packages/opencode/src/worktree/index.ts | 35 ++--- .../native/offline-connections.test.ts | 41 ++++++ ...arehouse-install-driver-permission.test.ts | 2 +- packages/opencode/test/cli/mcp-add.test.ts | 27 +++- .../opencode/test/cli/run/offline.test.ts | 133 +++++++++++++++--- packages/opencode/test/mcp/offline.test.ts | 33 +++++ packages/opencode/test/project/vcs.test.ts | 21 +-- .../opencode/test/project/worktree.test.ts | 24 ++++ .../opencode/test/snapshot/snapshot.test.ts | 21 +-- .../opencode/test/storage/storage.test.ts | 41 +++--- 52 files changed, 661 insertions(+), 244 deletions(-) create mode 100644 packages/opencode/src/altimate/native/connections/offline.ts create mode 100644 packages/opencode/src/altimate/native/dbt/offline.ts create mode 100644 packages/opencode/test/altimate/native/offline-connections.test.ts create mode 100644 packages/opencode/test/mcp/offline.test.ts diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index bca67d9a44..53f876a8df 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -160,14 +160,15 @@ 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 -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a local config file such as `~/.config/altimate-code/altimate-code.json` or `.altimate-code/altimate-code.json` in the project. The switch is read when Altimate Code starts and applies to all projects served by that process and its workers. To use a project opt-in from an existing shared server, start a separate Altimate Code process in that project. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a local global or project configuration file. The setting applies to the process and its workers. Start a separate process in the project to opt in when using a shared server. -Before going offline: +Configure an explicit HTTP(S) provider `options.baseURL` and select its `provider/model` ID. Define the model in the provider configuration if it is absent from the bundled or cached catalog. For an OpenAI-compatible endpoint, use the bundled `@ai-sdk/openai-compatible` provider. -1. Configure the model locally, including its `provider/model` ID and the provider's explicit `options.baseURL`. For a self-hosted OpenAI-compatible server, use the bundled `@ai-sdk/openai-compatible` provider. Define the model in your provider config if it is absent from the bundled or cached model catalog. -2. From the linked project, run `altimate-code workspace refresh` while online. Keep the resulting skill snapshot and the local credentials for the same workspace account. Altimate Code uses the snapshot without refreshing or deleting it offline and prints one notice indicating whether cached skills are available. -3. Pre-install any optional warehouse drivers you'll need when you reconnect. Run `warehouse_install_driver` while online, or run the npm command the tool prints. Offline mode disables all warehouse connections, including local DuckDB and SQLite, and automatic driver installs. +- SQL tools can query local DuckDB and SQLite files or a warehouse listening on loopback. Use a local dbt profile for dbt commands. +- Bash, installed language servers, and MCP servers using stdio or a loopback HTTP(S) URL remain available. Altimate Code skips automatic language server and warehouse driver installs. Install optional drivers and ripgrep ahead of time. +- Git diffs, session snapshots and revert, and worktree creation, removal and reset operate locally. Reset uses the cached base and skips submodule downloads. Run Git remote operations online. +- Altimate Code skips telemetry, account and remote configuration requests, model catalog downloads, update checks, workspace and engine sync, session sharing, and web search and fetch. Remote warehouse and MCP connections require an online run. Refresh workspace skills before going offline to use an existing snapshot. -Offline mode sends model requests to the configured HTTP(S) endpoint. It turns off telemetry, account and remote config requests, model catalog downloads, update checks, workspace engine connections and session sharing. The offline tool catalog includes file editing, search, skills, and basic task tools. SQL and dbt tools, web tools, shell commands, external plugins, MCP servers, and language servers are unavailable. Git-backed file diffs, session snapshots and revert are disabled. Creating, removing, or resetting a Git worktree and revoking a published session share also require an online run. Install `ripgrep` ahead of time if you need file search on a fresh host. +The configured model endpoint is the only external endpoint Altimate Code contacts in offline mode. Shell commands and other programs you configure or invoke retain their own network access. diff --git a/docs/mcp-workspaces.md b/docs/mcp-workspaces.md index 43253b2168..741c4d6a54 100644 --- a/docs/mcp-workspaces.md +++ b/docs/mcp-workspaces.md @@ -20,7 +20,7 @@ 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. +In [offline mode](docs/configure/config.md#offline-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 diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index a9e4741573..06c9956ac1 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -21,7 +21,7 @@ export function env(key: string): string | undefined { } export function offlineModeEnabled() { - return process.env.ALTIMATE_OFFLINE === "1" + return killSwitchSet(process.env.ALTIMATE_OFFLINE) } export function truthy(key: string) { diff --git a/packages/core/src/npm.ts b/packages/core/src/npm.ts index b7f4159c0d..d79a6805fe 100644 --- a/packages/core/src/npm.ts +++ b/packages/core/src/npm.ts @@ -127,7 +127,12 @@ export const layer = Layer.effect( return resolveEntryPoint(name, path.join(dir, "node_modules", name)) } - if (offlineModeEnabled()) return yield* new InstallFailedError({ add: [pkg], dir }) + if (offlineModeEnabled()) + return yield* new InstallFailedError({ + add: [pkg], + dir, + cause: new Error(`Install ${pkg} while online.`), + }) const tree = yield* reify({ dir, add: [pkg] }) const first = tree.edgesOut.values().next().value?.to if (!first) { diff --git a/packages/core/test/npm.test.ts b/packages/core/test/npm.test.ts index c149116cd5..9e852f6ccb 100644 --- a/packages/core/test/npm.test.ts +++ b/packages/core/test/npm.test.ts @@ -64,6 +64,29 @@ 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 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) + 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..ce49111062 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,8 @@ function terminal(): DBTTerminal { /** What `create` needs besides the saved config. */ export type CreateOptions = { + /** Skip automatic dependency downloads and anonymous usage reporting. */ + offline?: boolean /** * 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 +98,7 @@ export type CreateOptions = { function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { const vars = { ...process.env } + if (options.offline) vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath return { pythonPath: cfg.pythonPath, @@ -113,7 +116,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/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 157fe9a5c9..5bab0b3f05 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -413,9 +413,9 @@ export function readLogTail(file: string, maxBytes = LOG_READ_BYTES): string | u export async function collect(opts: { network: boolean }): Promise { const ctx = redactContext() const mcpServers = mcpFacts() - const [account, connections, telemetry] = await Promise.all([accountFacts(), connectionFacts(), telemetryFacts(opts.network)]) + const [account, connections, telemetry] = await Promise.all([accountFacts(), connectionFacts(), telemetryFacts(opts.network && !Offline.enabled())]) const proxy = PROXY_VARS.some((k) => k.toLowerCase() !== "no_proxy" && process.env[k]) - const network = opts.network + const network = opts.network && !Offline.enabled() ? await Promise.all(networkTargets(connections, account, telemetry).map((t) => probe(t.target, t.host, { proxy }))) : [] const logPath = path.join(Global.Path.log, "opencode.log") diff --git a/packages/opencode/src/altimate/free/client.ts b/packages/opencode/src/altimate/free/client.ts index 8dda346ef6..59399e6fc1 100644 --- a/packages/opencode/src/altimate/free/client.ts +++ b/packages/opencode/src/altimate/free/client.ts @@ -404,7 +404,7 @@ async function registerOnce( export async function register( input: { origin: "picker" | "server"; signal?: AbortSignal } = { origin: "picker" }, ): Promise { - if (Offline.enabled()) throw new Error("Register Altimate Base while online.") + if (Offline.enabled()) throw new ConfigurationError("Register Altimate Base while online.") const startedAt = performance.now() let configuredGateway: string try { 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..dc5aa2e6f1 --- /dev/null +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -0,0 +1,55 @@ +// altimate_change - new file +import { isIP } from "node:net" +import { isLocalFilePath, normalizeConfig, type ConnectionConfig } from "@altimateai/drivers" + +/** 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 === "localhost." || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")) +} + +function localStore(value: unknown): boolean { + if (typeof value !== "string" || value.includes("{{")) return false + if (value === ":memory:" || value === "") return true + // UNC shares are network locations, even though they look like paths. + if (/^(?:\\\\|\/\/)/.test(value)) return false + if (/^file:/i.test(value)) { + try { + const url = new URL(value) + return !url.hostname || url.hostname === "localhost" + } catch { return false } + } + return isLocalFilePath(value) +} + +/** Guard app-owned connection setup; SQL and project macros are user-controlled code. */ +export function assertLocalConnection(raw: ConnectionConfig): void { + const config = normalizeConfig(raw) + const type = config.type.toLowerCase() + const deny = () => { throw new Error("Offline mode allows only local file databases and loopback warehouse connections.") } + if (config.ssh_host || config.replica_set || config.socketPath) deny() + if (type === "duckdb" || type === "sqlite") { + if (!localStore(config.path)) deny() + return + } + if (!["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "oracle", "redshift", "clickhouse", "trino", "mongodb", "mongo"].includes(type)) deny() + // Cloud authentication may contact an identity provider even for a loopback host. + if (config.authentication && !["default", "sql", "ntlm"].includes(String(config.authentication).toLowerCase())) deny() + if (config.host !== undefined && !isLoopbackHost(config.host)) deny() + const connectionString = type === "trino" + ? config.connection_string ?? config.server ?? config.url + : config.connection_string + if (connectionString) { + try { + const url = new URL(String(connectionString)) + if ((type === "trino" || type === "clickhouse") && !["http:", "https:"].includes(url.protocol)) deny() + if (!isLoopbackHost(url.hostname) || url.protocol === "mongodb+srv:") deny() + if (["mongodb", "mongo"].includes(type) && url.searchParams.get("directConnection") !== "true") deny() + // Drivers can override the authority via URL parameters or discover replica peers. + for (const key of url.searchParams.keys()) { + if (["host", "hostaddr", "server", "replicaset", "service"].includes(key.toLowerCase())) deny() + } + } catch { deny() } + } else if (["mongodb", "mongo"].includes(type) || !isLoopbackHost(config.host ?? "127.0.0.1")) deny() +} diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 39fcf6139f..8573ff15bb 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -1,3 +1,7 @@ +// altimate_change start — validate offline dbt profiles before starting adapters +import { Offline } from "@/config/offline" +import { assertLocalDbt } from "../dbt/offline" +// altimate_change end /** * Register native connection handlers with the Dispatcher. * @@ -66,7 +70,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 }) => 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 +128,8 @@ async function ensureDbtAdapter(): Promise { return publish(null) } + if (Offline.enabled()) await assertLocalDbt(dbtConfig.projectRoot, [], dbtConfig.dbtIntegration) + // 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,7 +138,7 @@ 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) + return publish(await create(dbtConfig, { ...options, ...(Offline.enabled() ? { offline: true } : {}) }), dbtConfig.projectRoot) } catch { // dbt-tools not available or config invalid — fall back to native return publish(null) diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 557e7242f0..57f6a54d5d 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -1,5 +1,6 @@ // altimate_change start — offline mode import { Offline } from "@/config/offline" +import { assertLocalConnection } from "./offline" // altimate_change end /** * ConnectionRegistry — manages database connections. @@ -428,9 +429,7 @@ async function createConnector( ): Promise { // altimate_change end // altimate_change start — skip network work in offline mode - if (Offline.enabled()) { - throw new Error("Offline mode disables warehouse connections.") - } + if (Offline.enabled()) assertLocalConnection(config) // altimate_change end const driverPath = DRIVER_MAP[config.type.toLowerCase()] if (!driverPath) { @@ -454,6 +453,7 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) + if (Offline.enabled()) assertLocalConnection(resolvedConfig) // altimate_change start — validate password is a string for drivers that require it // Prevents cryptic SASL/SCRAM errors from database drivers @@ -670,9 +670,6 @@ export function names(): string[] { /** Get a connector instance (creates lazily). */ export async function get(name: string): Promise { - // altimate_change start — reject warehouse execution before accessing the connector cache - if (Offline.enabled()) throw new Error("Offline mode disables warehouse connections.") - // altimate_change end // altimate_change start — captured once, so a connect that finishes later lands in the project that started it const s = ensureLoaded() const { configs, connectors, tunnels, pending } = s @@ -682,6 +679,9 @@ export async function get(name: string): Promise { return getScratch() } + const configured = configs.get(name) + if (Offline.enabled() && configured) assertLocalConnection(configured) + const cached = connectors.get(name) if (cached) { // altimate_change start — a reused connection can reconnect and ask for a browser sign-in; route it here 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..fe8da0a396 --- /dev/null +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -0,0 +1,55 @@ +// 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 } from "../connections/offline" + +function resolve(value: unknown): any { + if (typeof value === "string") return value.replace( + /\{\{\s*env_var\s*\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])(.*?)\3\s*)?\)\s*\}\}/g, + (_, _quote, name, _defaultQuote, fallback) => process.env[name] ?? fallback ?? "{{unresolved}}", + ) + if (Array.isArray(value)) return value.map(resolve) + if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolve(v)])) + return value +} + +/** Resolve exactly the selected profile/target before starting dbt-owned network work. */ +export async function assertLocalDbt(projectRoot: string, args: string[] = [], integration = "core"): Promise { + if (!["core", "corecommand", "fusion"].includes(integration)) throw new Error("Offline mode disables cloud dbt integrations.") + const option = (name: string) => { + let result: string | undefined + for (let i = 0; i < args.length; i++) { + if (args[i] === name) result = args[++i] + else if (args[i].startsWith(name + "=")) result = args[i].slice(name.length + 1) + } + return result + } + const root = option("--project-dir") ?? projectRoot + const project = resolve(parse(await fs.readFile(path.join(root, "dbt_project.yml"), "utf8"))) + const explicit = option("--profiles-dir") ?? process.env.DBT_PROFILES_DIR + const local = path.join(root, "profiles.yml") + const profilesPath = explicit ? path.join(explicit, "profiles.yml") + : await fs.stat(local).then(() => local, () => path.join(os.homedir(), ".dbt", "profiles.yml")) + const profiles = resolve(parse(await fs.readFile(profilesPath, "utf8"))) + const profileName = option("--profile") ?? process.env.DBT_PROFILE ?? project.profile + const profile = profiles?.[profileName] + const target = option("--target") ?? option("-t") ?? process.env.DBT_TARGET ?? profile?.target ?? "default" + const output = profile?.outputs?.[target] + if (!output || typeof output.type !== "string") throw new Error("Offline mode could not resolve a local dbt profile and target.") + if (!["duckdb", "sqlite"].includes(output.type)) { + if (!output.host && !output.server && !output.connection_string) + throw new Error("Offline mode requires an explicit loopback host in the dbt profile.") + 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 }) + } else { + assertLocalConnection({ ...output, path: output.path ?? (output.type === "duckdb" ? ":memory:" : undefined) }) + } + // These profile hooks cause dbt-duckdb to install extensions or open extra connections at startup. + if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length) + throw new Error("Offline mode requires a dbt profile without extension installs, attachments, plugins, or remote secrets.") +} diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index b67a16887c..2a19b972c9 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,18 @@ 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 { + if (Offline.enabled()) { + try { + if (["deps", "init"].includes(params.command || "run")) throw new Error("Offline mode disables dbt dependency installation and initialization.") + await assertLocalDbt(params.project_dir || process.cwd(), [ + ...(params.args ?? []), + ...(params.project_dir ? ["--project-dir", params.project_dir] : []), + ]) + } 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 +57,8 @@ export function runDbt(params: DbtRunParams): Promise { args.push("--project-dir", params.project_dir) } - execFile("dbt", args, { timeout: 300_000 }, (error, stdout, stderr) => { + const env = Offline.enabled() ? { ...process.env, DBT_SEND_ANONYMOUS_USAGE_STATS: "false" } : process.env + execFile("dbt", args, { timeout: 300_000, env }, (error, stdout, stderr) => { if (error) { if ((error as any).code === "ENOENT") { resolve({ diff --git a/packages/opencode/src/altimate/workspace/state.ts b/packages/opencode/src/altimate/workspace/state.ts index ff683e34ee..1e1fdffced 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -863,7 +863,7 @@ export function endTurnBinding(sessionID: string): void { export async function resolveBindingOutcome(directory: string): Promise { if (Offline.enabled()) { - const local = readPin().kind === "absent" ? await readLocalBinding(directory).catch(() => null) : null + const local = readPinLogged().kind === "absent" ? await readLocalBinding(directory).catch(() => null) : null return local ? { status: "bound", binding: local, stale: true } : { status: "unknown" } } // altimate_change — the IDE extension's selection outranks whatever binding this project carries. diff --git a/packages/opencode/src/bun/index.ts b/packages/opencode/src/bun/index.ts index b8b46ec629..dcd7efa5cf 100644 --- a/packages/opencode/src/bun/index.ts +++ b/packages/opencode/src/bun/index.ts @@ -54,9 +54,6 @@ export namespace BunProc { ) export async function install(pkg: string, version = "latest") { - // altimate_change start — prevent package installs in offline mode - if (Offline.enabled()) throw new Error("Offline mode disables package installation.") - // altimate_change end // Use lock to ensure only one install at a time using _ = await Lock.write("bun-install") @@ -72,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 this package while online.") + } + // altimate_change end + if (!modExists || !cachedVersion) { // continue to install } else if (version !== "latest" && cachedVersion === version) { diff --git a/packages/opencode/src/cli/cmd/acp.ts b/packages/opencode/src/cli/cmd/acp.ts index 1a623660b9..090f0f4566 100644 --- a/packages/opencode/src/cli/cmd/acp.ts +++ b/packages/opencode/src/cli/cmd/acp.ts @@ -36,14 +36,15 @@ export const AcpCommand = effectCmd({ yield* Effect.promise(() => FreeTierConsent.printDisclosureOnceForHeadless(autoRegisterResult.status === "registered")) // altimate_change end const opts = yield* resolveNetworkOptions(args) - // altimate_change start — upstream_fix: preserve async server listen inside ACP profiler measure - const server = yield* Effect.promise(() => + // altimate_change start — skip the HTTP listener when ACP uses in-process transport + const server = Offline.enabled() ? undefined : yield* Effect.promise(() => ACPProfile.measure("cli.acp.server.listen", async () => Server.listen(opts)), ) // altimate_change end const sdk = createOpencodeClient({ - baseUrl: `http://${server.hostname}:${server.port}`, + // altimate_change — the offline SDK dispatches against an in-process URL + baseUrl: server ? `http://${server.hostname}:${server.port}` : "http://opencode.internal", headers: ServerAuth.headers(), // altimate_change start — route the offline ACP client to the in-process API fetch: Offline.enabled() diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index 7eede44489..0588ad6d37 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -141,7 +141,6 @@ export const McpServeCommand = cmd({ .option("all-tools", { type: "boolean", default: false, describe: "Expose every tool on the allow-list, not just the default set" }), async handler(args) { await Offline.start(process.cwd()) - if (Offline.enabled()) throw new Error("Run the standalone MCP server while online.") const { serveStdio } = await import("../../altimate/mcp-server/server") await serveStdio({ connections: args.connections, allowWrite: args.allowWrite, allTools: args.allTools, workspaceTools: args.workspaceTools }) }, @@ -511,6 +510,7 @@ async function resolveConfigPath(baseDir: string, global = false) { } async function addMcpToConfig(name: string, mcpConfig: ConfigMCPV1.Info, configPath: string) { + Offline.assertLocalMcp(mcpConfig) let text = "{}" if (await Filesystem.exists(configPath)) { text = await Filesystem.readText(configPath) @@ -547,7 +547,11 @@ export const McpAddCommand = effectCmd({ .option("env", { type: "array", string: true, describe: "Environment variables as key=value (repeatable)" }) .option("header", { type: "array", string: true, describe: "HTTP headers as key=value (repeatable)" }) .option("oauth", { type: "boolean", describe: "Enable OAuth", default: true }) - .option("global", { type: "boolean", describe: "Add to global config", default: false }), + .option("global", { type: "boolean", describe: "Add to global config", default: false }) + .middleware((args) => { + // Reject before effectCmd initializes config (which can add its schema field). + if (args.url && args.type !== "local") Offline.assertLocalMcp({ type: "remote", url: args.url }) + }), // altimate_change end handler: Effect.fn("Cli.mcp.add")(function* (args) { const maybeCtx = yield* InstanceRef @@ -882,6 +886,7 @@ export const McpDebugCommand = effectCmd({ return } + Offline.assertLocalMcp(serverConfig) prompts.log.info(`Server: ${serverName}`) prompts.log.info(`URL: ${serverConfig.url}`) @@ -918,7 +923,7 @@ export const McpDebugCommand = effectCmd({ // Test basic HTTP connectivity first try { - const response = await fetch(serverConfig.url, { + const response = await (Offline.enabled() ? Offline.localFetch() : fetch)(serverConfig.url, { method: "POST", headers: { ...serverConfig.headers, @@ -972,6 +977,7 @@ export const McpDebugCommand = effectCmd({ // Try creating transport with auth provider to trigger discovery const transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), { authProvider, + fetch: Offline.enabled() ? Offline.localFetch() : undefined, requestInit: serverConfig.headers ? { headers: serverConfig.headers } : undefined, }) diff --git a/packages/opencode/src/cli/cmd/models.ts b/packages/opencode/src/cli/cmd/models.ts index bcb8c4770e..19b612d1e6 100644 --- a/packages/opencode/src/cli/cmd/models.ts +++ b/packages/opencode/src/cli/cmd/models.ts @@ -31,6 +31,7 @@ export const ModelsCommand = effectCmd({ handler: Effect.fn("Cli.models")(function* (args) { const { Provider } = yield* Effect.promise(() => import("@/provider/provider")) // 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)) diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index 70a7fb484c..fbf56135e9 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -414,7 +414,11 @@ const SkillTestCommand = cmd({ if (tools.length === 0) { warn(`No CLI tool references detected in skill content`) } else if (Offline.enabled()) { - warn("Paired tool checks require online mode.") + for (const tool of tools) { + if (await isToolOnPath(tool, projectDir)) pass(`"${tool}" found on PATH`) + else fail(`"${tool}" not found on PATH`) + } + warn("Paired tool --help checks require online mode.") } else { process.stdout.write(EOL + ` Paired tools:` + EOL) for (const tool of tools) { @@ -661,7 +665,9 @@ const SkillInstallCommand = cmd({ async handler(args) { let source = (args.source as string).trim().replace(/\.git$/, "") const githubShorthand = /^[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/ - if (Offline.enabled() && (/^https?:\/\//.test(source) || githubShorthand.test(source))) { + const offlineLocal = Offline.enabled() && githubShorthand.test(source) && + (await fs.stat(path.resolve(source)).catch(() => undefined))?.isDirectory() + if (Offline.enabled() && !offlineLocal && (/^https?:\/\//.test(source) || githubShorthand.test(source))) { throw new Error("Install remote skills while online, or install a local skill directory.") } const isGlobal = args.global as boolean @@ -700,7 +706,7 @@ const SkillInstallCommand = cmd({ process.exit(1) } skillDir = tmpDir - } else if (githubShorthand.test(source)) { + } else if (!offlineLocal && githubShorthand.test(source)) { // GitHub shorthand: owner/repo const url = `https://github.com/${source}.git` process.stdout.write(`Fetching from github.com/${source}...` + EOL) diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index 558f3fb6cc..dca5cdf61d 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -216,8 +216,6 @@ const ToolRunCommand = cmd({ try { const toolArgs = await readArgs(args) const directory = process.cwd() - if (Offline.enabled() && name !== "warehouse_install_driver") - throw new Error("This tool is disabled in offline mode.") const workspaceTools = !Offline.enabled() && (await resolveWorkspaceTools(args["workspace-tools"], directory)) const daemon = await import("../../altimate/tool-cli/daemon") const reply = !Offline.enabled() && args.daemon && !daemon.daemonDisabled() diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 9446ba5c2f..1ae9e9c17f 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -249,8 +249,10 @@ export const TuiThreadCommand = cmd({ network.port !== 0 || network.hostname !== "127.0.0.1" - const listener = external ? await client.call("server", network) : undefined - const transport = listener && !Offline.enabled() + // altimate_change start — offline requests stay in the worker + const listener = external && !Offline.enabled() ? await client.call("server", network) : undefined + // altimate_change end + const transport = listener ? { url: listener.url, fetch: undefined, diff --git a/packages/opencode/src/cli/cmd/upgrade.ts b/packages/opencode/src/cli/cmd/upgrade.ts index 1906986039..0680c1b3d3 100644 --- a/packages/opencode/src/cli/cmd/upgrade.ts +++ b/packages/opencode/src/cli/cmd/upgrade.ts @@ -1,3 +1,6 @@ +// altimate_change start — explicit upgrade requires a connection +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change end import type { Argv } from "yargs" import { UI } from "../ui" import * as prompts from "@clack/prompts" @@ -31,6 +34,9 @@ export const UpgradeCommand = { }) }, handler: async (args: { target?: string; method?: string }) => { + // altimate_change start — fail before checking installation or versions + if (offlineModeEnabled()) throw new Error("Run the upgrade while online.") + // altimate_change end UI.empty() UI.println(UI.logo(" ")) UI.empty() diff --git a/packages/opencode/src/cli/network.ts b/packages/opencode/src/cli/network.ts index 886ab195e9..3960b7116d 100644 --- a/packages/opencode/src/cli/network.ts +++ b/packages/opencode/src/cli/network.ts @@ -56,7 +56,9 @@ export function resolveNetworkOptionsNoConfig(args: NetworkOptions, config?: Con const mdnsExplicitlySet = process.argv.includes("--mdns") const mdnsDomainExplicitlySet = process.argv.includes("--mdns-domain") // altimate_change start — offline mode skips multicast discovery - const mdns = !Offline.enabled() && (mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns)) + 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) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index f181222d22..6f721315df 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -565,12 +565,12 @@ export const layer = Layer.effect( } for (const [key, value] of Object.entries(auth)) { - // altimate_change start — skip well-known network config in offline mode - if (Offline.enabled()) continue - // altimate_change end 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) @@ -851,8 +851,6 @@ export const layer = Layer.effect( if (Offline.enabled()) { result.offline = true result.share = "disabled" - result.formatter = false - result.lsp = false } // altimate_change end if (result.autoshare === true && !result.share) { @@ -871,7 +869,7 @@ export const layer = Layer.effect( // may not yet be declared in the ConfigV1 experimental schema. const autoMcpDiscovery = (result.experimental as { auto_mcp_discovery?: boolean } | undefined) ?.auto_mcp_discovery - if (!Offline.enabled() && !Flag.OPENCODE_DISABLE_PROJECT_CONFIG && autoMcpDiscovery !== false) { + if (!Flag.OPENCODE_DISABLE_PROJECT_CONFIG && autoMcpDiscovery !== false) { const { discoverExternalMcp, setDiscoveryResult, driftFields, setConfigDrift, discoveredSource } = yield* Effect.promise( () => import("../mcp/discover"), diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 835280c19e..941e1d18c8 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -68,8 +68,6 @@ export async function start(directory: string, model?: string) { // Workers and core services must see the same policy before constructing // their layers. Once enabled, keep it for the lifetime of the process. process.env.ALTIMATE_OFFLINE = "1" - process.env.GIT_NO_LAZY_FETCH = "1" - process.env.GIT_ALLOW_PROTOCOL = "file" // Bun consults proxy environment variables even when fetch sets proxy: "". // Offline traffic must go directly to the one configured endpoint. process.env.NO_PROXY = "*" @@ -78,8 +76,10 @@ export async function start(directory: string, model?: string) { if (networkFetch) return networkFetch = globalThis.fetch globalThis.fetch = Object.assign( - async () => { - throw new Error("Offline mode allows network requests only to the configured model endpoint.") + async (...args: Parameters) => { + const [input] = args + if (isLocalURL(input instanceof Request ? input.url : input.toString())) return localFetch()(...args) + throw new Error("Offline mode allows network requests only to the configured model endpoint or loopback services.") }, { preconnect: () => {} }, ) @@ -130,6 +130,35 @@ export function modelFetch(baseURL: string | undefined): typeof fetch { ) } +// Validate the URL before any offline loopback HTTP request. +export function isLocalURL(value: string | URL) { + try { + const url = new URL(value) + if (!["http:", "https:"].includes(url.protocol)) return false + const host = url.hostname.toLowerCase() + return host === "localhost" || host === "localhost." || host === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(host) + } 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 or localhost/loopback HTTP(S) MCP servers.") +} + +export function localFetch(): typeof fetch { + return Object.assign( + async (input: Parameters[0], init?: Parameters[1]) => { + const target = input instanceof Request ? input.url : input.toString() + if (!isLocalURL(target)) throw new Error("Offline mode blocked a non-local request.") + // Never follow redirects: a local endpoint must not grant access to a remote host. + return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error", proxy: undefined }) + }, + { preconnect: () => {} }, + ) +} + let warned = false export async function announce(hasSnapshot: boolean) { diff --git a/packages/opencode/src/config/tui.ts b/packages/opencode/src/config/tui.ts index a959ae6bd5..26d728e3ce 100644 --- a/packages/opencode/src/config/tui.ts +++ b/packages/opencode/src/config/tui.ts @@ -260,9 +260,7 @@ const loadState = Effect.fn("TuiConfig.loadState")(function* (ctx: { directory: return { config: result, - // altimate_change start — skip local and installed TUI plugins in offline mode - pluginOrigins: Offline.enabled() ? [] : acc.plugin_origins, - // altimate_change end + pluginOrigins: acc.plugin_origins, dirs: result.plugin?.length ? dirs : [], } }) 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/index.ts b/packages/opencode/src/file/index.ts index 4008a41c7b..9f9c563cbf 100644 --- a/packages/opencode/src/file/index.ts +++ b/packages/opencode/src/file/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — skip Git filters when reading files offline -import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" -// altimate_change end import { BusEvent } from "@/bus/bus-event" import z from "zod" import { formatPatch, structuredPatch } from "diff" @@ -443,9 +440,6 @@ export namespace File { } export async function status() { - // altimate_change start — skip Git working-tree status in offline mode - if (offlineModeEnabled()) return [] - // altimate_change end const project = Instance.project if (project.vcs !== "git") return [] @@ -574,7 +568,7 @@ export namespace File { const content = (await Filesystem.readText(full).catch(() => "")).trim() // altimate_change start — retain file content without the Git working-tree comparison - if (!offlineModeEnabled() && project.vcs === "git") { + if (project.vcs === "git") { // altimate_change end let diff = (await git(["-c", "core.fsmonitor=false", "diff", "--", file], { cwd: Instance.directory })).text() if (!diff.trim()) { diff --git a/packages/opencode/src/git/index.ts b/packages/opencode/src/git/index.ts index a5317971ef..663c0ed1c3 100644 --- a/packages/opencode/src/git/index.ts +++ b/packages/opencode/src/git/index.ts @@ -1,4 +1,4 @@ -// altimate_change start — skip working-tree Git operations that can run filters +// altimate_change start — restrict Git transport offline import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" // altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -20,16 +20,23 @@ const cfg = [ "core.quotepath=false", ] as const -// altimate_change start — permit only the metadata reads used by offline clients -const offlineMetadataCommands = new Set(["rev-parse", "symbolic-ref", "for-each-ref", "merge-base"]) +// altimate_change start — prevent Git from starting a transport offline +const remoteCommands = new Set(["clone", "fetch", "pull", "push", "ls-remote", "send-pack", "fetch-pack", "submodule--helper"]) -function gitCommandAllowedOffline(args: string[]) { - const [command, operation] = args - if (offlineMetadataCommands.has(command)) return true - if (command === "remote") return args.length === 1 - if (command === "config") return args.length === 2 && operation === "init.defaultBranch" - if (command === "show") return args.length === 2 && !operation.startsWith("-") && operation.includes(":") - return command === "worktree" && operation === "list" +export function localGitEnv(env?: Record) { + return offlineModeEnabled() + ? { ...env, GIT_ALLOW_PROTOCOL: "", GIT_NO_LAZY_FETCH: "1", GIT_LFS_SKIP_SMUDGE: "1" } + : env +} + +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, operation, ...rest] = args.slice(index) + return remoteCommands.has(command) || + (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) } // altimate_change end @@ -125,14 +132,17 @@ export const layer = Layer.effect( const run = Effect.fn("Git.run")( function* (args: string[], opts: Options) { - // altimate_change start — Git can launch filters independently of its network transport - if (offlineModeEnabled() && !gitCommandAllowedOffline(args)) - return fail(new Error("Git working-tree operations require an online run.")) + // altimate_change start — allow local Git and deny transports, including lazy object fetches + const offline = offlineModeEnabled() + if (offline && gitCommandUsesNetwork(args)) + return fail(new Error("Git remote operations require an online run.")) // altimate_change end const result = yield* appProcess.run( ChildProcess.make("git", [...cfg, ...args], { cwd: opts.cwd, - env: opts.env, + // altimate_change start — prevent Git and Git LFS network requests + env: localGitEnv(opts.env), + // altimate_change end extendEnv: true, stdin: opts.stdin ?? "ignore", stdout: "pipe", diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 347e98406c..ee996a5b13 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -193,7 +193,8 @@ let cli = yargs(args) (command === "tool" && opts._[1] === "daemon") || (command === "learn" && opts._[1] === "import-reviews") || (command === "console" && opts._[1] === "open") || - (["providers", "auth", "mcp", "console"].includes(command) && opts._.some((arg) => arg === "login" || arg === "auth")) + (["providers", "auth", "console"].includes(command) && opts._[1] === "login") || + (command === "mcp" && opts._[1] === "auth") )) throw new Error("This command requires network access. Run it while online.") // altimate_change end diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index d4c75d86ed..69337d7560 100644 --- a/packages/opencode/src/installation/index.ts +++ b/packages/opencode/src/installation/index.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { Offline } from "@/config/offline" +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" @@ -844,7 +844,7 @@ export const layer: Layer.Layer(), diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index d8fb83d456..5404d3e1eb 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -423,6 +423,13 @@ export const layer = Layer.effect( key: string, mcp: ConfigMCPV1.Info & { type: "remote" }, ) { + if (Offline.enabled() && !Offline.isLocalURL(mcp.url)) { + return { + client: undefined as MCPClient | undefined, + status: { status: "failed" as const, error: "Offline mode blocks remote MCP servers; use stdio or localhost/loopback HTTP(S)." }, + transport: undefined as TransportLabel | undefined, + } + } const url = remoteURL(mcp.url) if (!url) { return { @@ -494,6 +501,7 @@ export const layer = Layer.effect( transport: new StreamableHTTPClientTransport(url, { authProvider, requestInit, + fetch: Offline.enabled() ? Offline.localFetch() : undefined, }), }, { @@ -501,6 +509,7 @@ export const layer = Layer.effect( transport: new SSEClientTransport(url, { authProvider, requestInit, + fetch: Offline.enabled() ? Offline.localFetch() : undefined, }), }, ] @@ -673,9 +682,6 @@ export const layer = Layer.effect( const create = Effect.fn("MCP.create")( function* (key: string, mcp: ConfigMCPV1.Info) { - // altimate_change start — skip external MCP processes and servers in offline mode - if (Offline.enabled()) return DISABLED_RESULT - // altimate_change end if (mcp.enabled === false) { return DISABLED_RESULT } @@ -1070,6 +1076,7 @@ export const layer = Layer.effect( }) const add = Effect.fn("MCP.add")(function* (name: string, mcp: ConfigMCPV1.Info) { + Offline.assertLocalMcp(mcp) // altimate_change start — see claim const seq = ++lifecycleSeq // altimate_change end diff --git a/packages/opencode/src/plugin/index.ts b/packages/opencode/src/plugin/index.ts index 7e3eed56f5..2cfe1e6d53 100644 --- a/packages/opencode/src/plugin/index.ts +++ b/packages/opencode/src/plugin/index.ts @@ -114,10 +114,10 @@ export namespace Plugin { $: Bun.$, } - // altimate_change start — skip network work in offline mode - if (Offline.enabled()) return { hooks, input } + // 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_PLUGINS) { + 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 374fde3387..27d4618de0 100644 --- a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx +++ b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx @@ -291,7 +291,6 @@ async function testSkillDirect( ): Promise<{ ok: boolean; message: string }> { const tools = detectToolReferences(content) if (tools.length === 0) return { ok: true, message: `${skillName}: PASS (no CLI tools)` } - if (Offline.enabled()) return { ok: false, message: "Paired tool checks require online mode." } const sep = process.platform === "win32" ? ";" : ":" const toolPath = [ @@ -304,6 +303,10 @@ async function testSkillDirect( .join(sep) for (const tool of tools) { + if (Offline.enabled()) { + if (!Bun.which(tool, { PATH: toolPath })) return { ok: false, message: `${skillName}: FAIL — "${tool}" not found` } + continue + } try { const proc = Bun.spawn([tool, "--help"], { stdout: "pipe", @@ -320,7 +323,7 @@ async function testSkillDirect( return { ok: false, message: `${skillName}: FAIL — "${tool}" not found or failed to execute` } } } - return { ok: true, message: `${skillName}: PASS` } + return { ok: true, message: Offline.enabled() ? `${skillName}: tools found (skipped --help offline)` : `${skillName}: PASS` } } type RawSdkClient = { diff --git a/packages/opencode/src/plugin/tui/runtime.ts b/packages/opencode/src/plugin/tui/runtime.ts index 717b177a5c..1f1bc4fceb 100644 --- a/packages/opencode/src/plugin/tui/runtime.ts +++ b/packages/opencode/src/plugin/tui/runtime.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy -import { Offline } from "@/config/offline" -// altimate_change end import { runtimeModules as keymapRuntimeModules } from "@opentui/keymap/runtime-modules" import { ensureRuntimePluginSupport } from "@opentui/solid/runtime-plugin-support/configure" import { @@ -1097,9 +1094,7 @@ async function load(input: { }).pipe(Effect.provide(RuntimeFlags.defaultLayer)), ) const pluginOrigins = config.plugin_origins ?? (await TuiConfig.pluginOrigins()) - // altimate_change start — skip external TUI plugins in offline mode - const records = Offline.enabled() || Flag.OPENCODE_PURE ? [] : pluginOrigins - // altimate_change end + const records = Flag.OPENCODE_PURE ? [] : pluginOrigins if (Flag.OPENCODE_PURE && pluginOrigins.length) { } diff --git a/packages/opencode/src/pty/index.ts b/packages/opencode/src/pty/index.ts index 3c4946fef1..166d9f4213 100644 --- a/packages/opencode/src/pty/index.ts +++ b/packages/opencode/src/pty/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode skips terminal subprocesses -import { Offline } from "@/config/offline" -// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" // altimate_change start — upstream moved the pty spawn backend into @opencode-ai/core @@ -126,9 +123,6 @@ export namespace Pty { } export async function create(input: CreateInput) { - // altimate_change start — offline mode skips terminal subprocesses - if (Offline.enabled()) throw new Error("Terminal sessions are disabled in offline mode.") - // altimate_change end const id = PtyID.ascending() const command = input.command || Shell.preferred() const args = input.args || [] diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index a6e4e8857b..2efe147859 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -480,10 +480,13 @@ export namespace SessionPrompt { // does not even load the sync module. if (Offline.enabled()) { const dir = Instance.directory - const { snapshotRoot, ownManifest } = await import("../altimate/workspace/skill-sync") - const snapshot = await ownManifest(dir) - await Offline.announce(snapshot !== null) - if (existsSync(snapshotRoot(dir))) await refreshSkillRegistry(dir) + const writeOfflineNotice = async () => { + const { ownManifest } = await import("../altimate/workspace/skill-sync") + await Offline.announce((await ownManifest(dir)) !== null) + await refreshSkillRegistry(dir) + } + const notice = writeOfflineNotice().catch((error) => log.warn("offline skill snapshot setup failed", { error })) + if (existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) await notice } else if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { const dir = Instance.directory // Mirrors `MANAGED_DIR` in ./altimate/workspace/skill-sync. Inlined @@ -2445,8 +2448,8 @@ export namespace SessionPrompt { // acts on a false positive instead of only measuring it, so it should // not ship until those heuristics are consolidated into shared, // tested primitives. - const validatorsEnabled = !Offline.enabled() && process.env.ALTIMATE_VALIDATORS_ENABLED === "1" - const validatorsShadow = !Offline.enabled() && process.env.ALTIMATE_VALIDATORS_SHADOW === "1" + const validatorsEnabled = process.env.ALTIMATE_VALIDATORS_ENABLED === "1" + const validatorsShadow = process.env.ALTIMATE_VALIDATORS_SHADOW === "1" const validatorsActive = validatorsEnabled || validatorsShadow const maxValidatorRetries = Number(process.env.ALTIMATE_VALIDATORS_MAX_RETRIES ?? "3") const validatorsDebug = process.env.ALTIMATE_VALIDATORS_DEBUG === "1" @@ -4331,9 +4334,6 @@ NOTE: At any point in time through this workflow you should feel free to ask the }) export type ShellInput = z.infer export async function shell(input: ShellInput) { - // altimate_change start — prevent direct shell execution in offline sessions - if (Offline.enabled()) throw new Error("Shell commands are disabled in offline mode.") - // altimate_change end const abort = start(input.sessionID) if (!abort) { throw new Session.BusyError(input.sessionID) @@ -4841,9 +4841,6 @@ NOTE: At any point in time through this workflow you should feel free to ask the const shell = ConfigMarkdown.shell(template) if (shell.length > 0) { - // altimate_change start — template expansion can invoke an arbitrary program - if (Offline.enabled()) throw new Error("Shell commands are disabled in offline mode.") - // altimate_change end // altimate_change start — upstream_fix: command template shell // expansion must honor configured shell instead of Bun's default parser. const sh = Shell.preferred((await Config.get()).shell) diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index fefb90c41c..0a5e663edb 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -129,7 +129,8 @@ export namespace ShareNext { export async function create(sessionID: SessionID) { // altimate_change start — skip session sharing in offline mode - if (Offline.enabled() || disabled) return { id: "", url: "", secret: "" } + if (Offline.enabled()) throw new Error("Sharing sessions requires an online run.") + if (disabled) return { id: "", url: "", secret: "" } // altimate_change end log.info("creating share", { sessionID }) const req = await request() diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index 40274286d4..c7f2a69484 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -1,5 +1,6 @@ // altimate_change start — offline mode import { Offline } from "@/config/offline" +import { createHash } from "node:crypto" // altimate_change end import { NodePath } from "@effect/platform-node" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -58,11 +59,19 @@ export namespace Discovery { }) const pull = Effect.fn("Discovery.pull")(function* (url: string) { - // altimate_change start — skip network work in offline mode - if (Offline.enabled()) return [] - // altimate_change end const base = url.endsWith("/") ? url : `${url}/` const index = new URL("index.json", base).href + // altimate_change start — reuse the cached index for this source without contacting it + const indexPath = path.join(cache, ".indexes", createHash("sha256").update(index).digest("hex") + ".json") + if (Offline.enabled()) { + const cached = yield* fs.readJson(indexPath).pipe(Effect.catch(() => Effect.succeed(undefined))) + const directories = Array.isArray(cached) ? cached : [] + return yield* Effect.filter(directories.filter((dir): dir is string => + typeof dir === "string" && path.relative(cache, dir).split(path.sep).length === 1 && + path.dirname(dir) === cache, + ), (dir) => fs.exists(path.join(dir, "SKILL.md")).pipe(Effect.orElseSucceed(() => false))) + } + // altimate_change end const host = base.slice(0, -1) log.info("fetching index", { url: index }) @@ -109,7 +118,11 @@ export namespace Discovery { { concurrency: skillConcurrency }, ) - return dirs.filter((dir): dir is string => dir !== null) + const available = dirs.filter((dir): dir is string => dir !== null) + // altimate_change start — store the directory list for a later offline run + yield* fs.writeWithDirs(indexPath, JSON.stringify(available)).pipe(Effect.ignore) + // altimate_change end + return available }) return Service.of({ pull }) diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index e0f2fa5655..023ba34181 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -1,5 +1,5 @@ -// altimate_change start — offline mode skips Git snapshot operations -import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +// altimate_change start — disable Git transport when working with local snapshots +import { localGitEnv } from "@/git" // altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Cause, Duration, Effect, Layer, Schedule, Schema, Semaphore, Context } from "effect" @@ -93,7 +93,7 @@ export const layer: Layer.Layer; stdin?: string }) { const result = yield* appProcess.run( - ChildProcess.make("git", cmd, { cwd: opts?.cwd, env: opts?.env, extendEnv: true }), + ChildProcess.make("git", cmd, { cwd: opts?.cwd, env: localGitEnv(opts?.env), extendEnv: true }), { stdin: opts?.stdin }, ) return { @@ -170,9 +170,6 @@ export const layer: Layer.Layer(fx: Effect.Effect) => lock(state.gitdir).withPermits(1)(fx) const enabled = Effect.fnUntraced(function* () { - // altimate_change start — git add can execute a configured clean filter - if (offlineModeEnabled()) return false - // altimate_change end if (state.vcs !== "git") return false return (yield* config.get()).snapshot !== false }) @@ -355,9 +352,6 @@ export const layer: Layer.Layer item.ref).join("\n") + "\n" }, diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 0c22d47784..29c5e85f90 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -420,12 +420,6 @@ export namespace ToolRegistry { configInput?: RegistryConfigInput, ): Promise { const question = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL - if (Offline.enabled()) { - return AppRuntime.runPromise(Effect.scoped(Effect.all([ - InvalidTool, ...(question ? [QuestionTool] : []), ReadTool, GlobTool, GrepTool, EditTool, WriteTool, - TaskTool, TodoWriteTool, SkillTool, ApplyPatchTool, WarehouseInstallDriverTool, - ]))) - } const custom = configInput?.matches ? await loadCustomTools(configInput.matches).then((x) => x.custom) : await state().then((x) => x.custom) @@ -437,6 +431,9 @@ 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. + // altimate_change start — keep local tools available in offline sessions + const offline = Offline.enabled() + // altimate_change end const builtins = [ InvalidTool, ...(question ? [QuestionTool] : []), @@ -447,11 +444,11 @@ export namespace ToolRegistry { EditTool, WriteTool, TaskTool, - WebFetchTool, + // altimate_change start — these tools contact remote services + ...(!offline ? [WebFetchTool, WebSearchTool, CodeSearchTool] : []), + // altimate_change end TodoWriteTool, // TodoReadTool, - WebSearchTool, - CodeSearchTool, SkillTool, ApplyPatchTool, ...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [LspTool] : []), @@ -537,8 +534,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 @@ -548,7 +545,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/worktree/index.ts b/packages/opencode/src/worktree/index.ts index e41e876efb..2b68c2dfe9 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -1,4 +1,4 @@ -// altimate_change start — offline mode does not run project startup scripts +// altimate_change start — offline mode skips worktree network steps import { Offline } from "@/config/offline" // altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -15,7 +15,7 @@ import { Slug } from "@opencode-ai/core/util/slug" import { errorMessage } from "../util/error" import { EventV2 } from "@opencode-ai/core/event" import { GlobalBus } from "@/bus/global" -import { Git } from "@/git" +import { Git, localGitEnv } from "@/git" import { Effect, Layer, Path, Schema, Scope, Context } from "effect" import { ChildProcess } from "effect/unstable/process" import { NodePath } from "@effect/platform-node" @@ -176,7 +176,7 @@ 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" }), + ChildProcess.make("git", args, { cwd: opts?.cwd, env: localGitEnv(), extendEnv: true, stdin: "ignore" }), ) return { code: result.exitCode, @@ -234,9 +234,6 @@ export const layer: Layer.Layer< }) const setup = Effect.fnUntraced(function* (info: Info) { - // altimate_change start — checkout filters can launch programs such as Git LFS - if (Offline.enabled()) return yield* new CreateFailedError({ message: "Create this worktree while online." }) - // altimate_change end const ctx = yield* InstanceState.context const created = yield* git( info.branch @@ -413,9 +410,6 @@ export const layer: Layer.Layer< } const remove = Effect.fn("Worktree.remove")(function* (input: RemoveInput) { - // altimate_change start — reject before modifying a worktree offline - if (Offline.enabled()) return yield* new RemoveFailedError({ message: "Remove this worktree while online." }) - // altimate_change end const ctx = yield* InstanceState.context if (ctx.project.vcs !== "git") { return yield* new NotGitError({ message: "Worktrees are only supported for git projects" }) @@ -500,9 +494,6 @@ export const layer: Layer.Layer< ) const runStartScript = Effect.fnUntraced(function* (directory: string, cmd: string, kind: string) { - // altimate_change start — keep worktree startup commands offline - if (Offline.enabled()) return true - // altimate_change end const text = cmd.trim() if (!text) return true const result = yield* runStartCommand(directory, text) @@ -556,9 +547,6 @@ export const layer: Layer.Layer< }) const reset = Effect.fn("Worktree.reset")(function* (input: ResetInput) { - // altimate_change start — reset fetches the base and refreshes submodules - if (Offline.enabled()) return yield* new ResetFailedError({ message: "Reset this worktree while online." }) - // altimate_change end const ctx = yield* InstanceState.context if (ctx.project.vcs !== "git") { return yield* new NotGitError({ message: "Worktrees are only supported for git projects" }) @@ -588,7 +576,8 @@ export const layer: Layer.Layer< } const sep = base.ref.indexOf("/") - if (base.ref !== base.name && sep > 0) { + // altimate_change — reset to the cached ref when offline + if (!Offline.enabled() && base.ref !== base.name && sep > 0) { const remote = base.ref.slice(0, sep) const branch = base.ref.slice(sep + 1) yield* gitExpect( @@ -611,11 +600,15 @@ 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 — submodule initialization can fetch missing objects + if (!Offline.enabled()) { + yield* gitExpect( + ["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/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts new file mode 100644 index 0000000000..bf6af82a56 --- /dev/null +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -0,0 +1,41 @@ +// altimate_change - new file +import { 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" + +test("offline permits embedded databases and literal loopback", () => { + 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 host of ["localhost", "127.0.0.1", "127.0.1.2", "::1"]) + expect(() => assertLocalConnection({ type: "postgres", host })).not.toThrow() + expect(() => assertLocalConnection({ type: "postgres", connectionString: "postgres://localhost/test" })).not.toThrow() +}) +test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", () => { + for (const config of [ + { type: "duckdb", path: "md:cloud" }, + { type: "duckdb", path: "https://example.com/db" }, + { 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: "snowflake", host: "localhost" }, + { type: "sqlserver", host: "localhost", authentication: "azure-active-directory-default" }, + { type: "postgres", connection_string: "postgres://localhost/db?host=remote" }, + { type: "mongodb", connection_string: "mongodb+srv://localhost/db" }, + ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") +}) +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.toBeUndefined() + await expect(assertLocalDbt(root, [...args, "--target=remote"])).rejects.toThrow("Offline mode") + await expect(assertLocalDbt(root, args, "cloud")).rejects.toThrow("Offline mode") + } finally { await fs.rm(root, { recursive: true, force: true }) } +}) 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 183675c515..125845f7c1 100644 --- a/packages/opencode/test/altimate/warehouse-install-driver-permission.test.ts +++ b/packages/opencode/test/altimate/warehouse-install-driver-permission.test.ts @@ -105,7 +105,7 @@ describe("warehouse_install_driver permissions", () => { 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).toContain("pg") + expect(result.output).toMatch(/ pg$/) expect(ask).not.toHaveBeenCalled() expect(install).not.toHaveBeenCalled() } finally { diff --git a/packages/opencode/test/cli/mcp-add.test.ts b/packages/opencode/test/cli/mcp-add.test.ts index cf9e547f04..9a3b747bf9 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("localhost/loopback") + expect(readFileSync(configPath, "utf8")).toBe(original) + }, true) +}) + +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) +}) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index e1fcb8c2a6..37c1bd80b2 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -28,7 +28,7 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: "offline-test": { npm: "@ai-sdk/openai-compatible", options: { baseURL: MODEL_ENDPOINT, apiKey: "local-only" }, - models: { fixture: { name: "Offline fixture", limit: { context: 20000, output: 2000 } } }, + models: { fixture: { name: "Offline fixture", limit: { context: 100000, output: 2000 } } }, }, }, mcp: { remoteFixture: { type: "remote", url: "https://mcp.test" } }, @@ -76,13 +76,31 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: ` 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 chunks = [ + 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 > 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 } }, ] @@ -151,7 +169,7 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ 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. - env: configMode ? { ...f.env, PATH: path.join(f.root, "empty-path") } : f.env, + env: snapshot ? { ...f.env, PATH: path.join(f.root, "empty-path") } : f.env, stdin: "ignore", stdout: "pipe", stderr: "pipe", @@ -186,6 +204,72 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ }, 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, + env: { ...f.env, OFFLINE_TEST_BASH: "1", ALTIMATE_CLI_YOLO: "true" }, + 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" }) + 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 seed = Bun.spawn([process.execPath, "-e", ` + const duckdb = require("duckdb") + const db = new duckdb.Database(process.argv[1]) + db.run("create table fixture as select 42 as offline_answer", (err) => { + if (err) throw err + db.close() + }) + `, database], { cwd: import.meta.dir, stderr: "inherit" }) + expect(await seed.exited).toBe(0) + await Bun.write(path.join(f.project, ".altimate-code", "connections.json"), JSON.stringify({ + local: { type: "duckdb", path: database }, + })) + const proc = Bun.spawn([ + process.execPath, "--preload", f.preload, CLI, "tool", "run", "sql_execute", "--args", + JSON.stringify({ warehouse: "local", query: "select offline_answer from fixture" }), "--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(), + ]) + 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 }) + } +}, 30_000) + test("offline model transport bypasses proxy settings and refuses redirects", async () => { let proxyCalls = 0 const proxy = Bun.serve({ @@ -298,15 +382,16 @@ test("offline skill install refuses a remote repository before running git clone } }, 25_000) -test("offline mode does not launch a configured language server", async () => { +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 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"] } } }), @@ -316,19 +401,19 @@ test("offline mode does not launch a configured language server", async () => { env: f.env, stdout: "pipe", stderr: "pipe", - signal: AbortSignal.timeout(20_000), + 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(false) + 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 }) } -}, 25_000) +}, 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) @@ -421,7 +506,7 @@ test.skipIf(process.platform === "win32")( expect(await Bun.file(marker).exists()).toBe(false) expect({ code, stdout, stderr }).toMatchObject({ code: 0, - stdout: expect.stringContaining("Paired tool checks require online mode."), + stdout: expect.stringContaining("Paired tool --help checks require online mode."), }) } finally { await fs.rm(f.root, { recursive: true, force: true }) @@ -430,27 +515,33 @@ test.skipIf(process.platform === "win32")( 25_000, ) -test("standalone MCP rejects offline config before opening stdio", async () => { +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: "ignore", + stdin: "pipe", 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: 1, - stdout: "", - stderr: expect.stringContaining("Run the standalone MCP server while online."), - }) + 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 }) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts new file mode 100644 index 0000000000..7a8250d392 --- /dev/null +++ b/packages/opencode/test/mcp/offline.test.ts @@ -0,0 +1,33 @@ +// altimate_change - new file +import { expect, test } from "bun:test" +import { Offline } from "../../src/config/offline" + +test("offline MCP URL policy accepts only HTTP(S) localhost and loopback", () => { + for (const url of ["http://localhost:3000/mcp", "https://localhost./mcp", "http://127.2.3.4/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) +}) + +test("offline local MCP fetch rejects remote requests and redirects before remote egress", async () => { + let calls = 0 + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request) { + calls++ + return new URL(request.url).pathname === "/redirect" + ? Response.redirect("https://example.com/mcp") + : new Response("local MCP") + }, + }) + try { + const fetch = Offline.localFetch() + expect(await (await fetch(server.url)).text()).toBe("local MCP") + await expect(fetch(new URL("/redirect", server.url))).rejects.toThrow() + await expect(fetch("https://example.com/mcp")).rejects.toThrow("non-local request") + expect(calls).toBe(2) + } finally { + server.stop(true) + } +}) diff --git a/packages/opencode/test/project/vcs.test.ts b/packages/opencode/test/project/vcs.test.ts index c93ab97da6..3f2bd7c717 100644 --- a/packages/opencode/test/project/vcs.test.ts +++ b/packages/opencode/test/project/vcs.test.ts @@ -158,31 +158,24 @@ describe("Vcs", () => { describe("Vcs diff", () => { worktreeIt.instance( - "offline VCS status and diff do not execute Git working-tree filters", + "offline VCS shows local changes and refuses remote Git operations", Effect.gen(function* () { const { directory } = yield* TestInstance - const marker = path.join(directory, "filter-ran") - yield* write(path.join(directory, ".gitattributes"), "*.txt filter=offline-fixture\n") yield* write(path.join(directory, "data.txt"), "before\n") yield* git(directory, ["add", "."]) - yield* git(directory, ["commit", "-m", "test filter fixture"]) - yield* git(directory, ["config", "filter.offline-fixture.clean", - `printf 'filter ran' > '${marker.replaceAll("\\", "/")}'; cat`]) + 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 - const state = yield* vcs.status() - const diff = yield* vcs.diff("git") - const prefixed = yield* Git.Service.use((git) => git.run( - ["-c", "core.quotepath=false", "diff", "--numstat", "HEAD"], + 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(prefixed.exitCode).not.toBe(0) - expect(yield* FSUtil.Service.use((fs) => fs.existsSafe(marker))).toBe(false) - expect(state).toEqual([]) - expect(diff).toEqual([]) + 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 diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index bbe2af3718..db875e4c8e 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -82,6 +82,30 @@ 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* () { + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const svc = yield* Worktree.Service + const fs = yield* FSUtil.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) + }), + ) + } 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/snapshot/snapshot.test.ts b/packages/opencode/test/snapshot/snapshot.test.ts index eb99fddd50..daf82e09cb 100644 --- a/packages/opencode/test/snapshot/snapshot.test.ts +++ b/packages/opencode/test/snapshot/snapshot.test.ts @@ -101,22 +101,23 @@ const withGitConfigGlobal = (config: string, self: Effect.Effect '${fwd(marker)}'; cat`]) - yield* write(path.join(directory, ".gitattributes"), "*.txt filter=offline-fixture\n") - yield* write(path.join(directory, "data.txt"), "fixture") + const file = fwd(directory, "data.txt") + yield* write(file, "before") const previous = process.env.ALTIMATE_OFFLINE process.env.ALTIMATE_OFFLINE = "1" try { const snapshot = yield* Snapshot.Service - const current = yield* withGitConfigGlobal(config, snapshot.track()) - expect(yield* exists(marker)).toBe(false) - expect(current).toBeUndefined() + const before = yield* snapshot.track() + expect(before).toBeDefined() + yield* write(file, "after") + const patch = yield* snapshot.patch(before!) + expect(patch.files).toContain(file) + expect(yield* snapshot.diff(before!)).toContain("+after") + yield* snapshot.revert([patch]) + expect(yield* readText(file)).toBe("before") } finally { if (previous === undefined) delete process.env.ALTIMATE_OFFLINE else process.env.ALTIMATE_OFFLINE = previous diff --git a/packages/opencode/test/storage/storage.test.ts b/packages/opencode/test/storage/storage.test.ts index afb2e93755..d4a278458c 100644 --- a/packages/opencode/test/storage/storage.test.ts +++ b/packages/opencode/test/storage/storage.test.ts @@ -233,7 +233,7 @@ describe("Storage", () => { }), ) - it.live("migration 1 tolerates malformed legacy records", () => + it.live("migration 1 migrates local projects even when offline", () => Effect.gen(function* () { const fs = yield* FSUtil.Service const tmp = yield* tmpdirScoped({ git: true }) @@ -254,22 +254,29 @@ describe("Storage", () => { JSON.stringify({ role: "user", text: "hello" }), ) - yield* Effect.gen(function* () { - const svc = yield* Storage.Service - const projects = yield* svc.list(["project"]) - expect(projects).toHaveLength(1) - const project = projects[0]![1] - - expect(yield* svc.list(["session", project])).toEqual([["session", project, "ses_legacy"]]) - expect(yield* svc.read<{ id: string; title: string }>(["session", project, "ses_legacy"])).toEqual({ - id: "ses_legacy", - title: "legacy", - }) - expect(yield* svc.read<{ role: string; text: string }>(["message", "ses_legacy", "msg_legacy"])).toEqual({ - role: "user", - text: "hello", - }) - }).pipe(Effect.provide(remappedStorage(tmp))) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + yield* Effect.gen(function* () { + const svc = yield* Storage.Service + const projects = yield* svc.list(["project"]) + expect(projects).toHaveLength(1) + const project = projects[0]![1] + + expect(yield* svc.list(["session", project])).toEqual([["session", project, "ses_legacy"]]) + expect(yield* svc.read<{ id: string; title: string }>(["session", project, "ses_legacy"])).toEqual({ + id: "ses_legacy", + title: "legacy", + }) + expect(yield* svc.read<{ role: string; text: string }>(["message", "ses_legacy", "msg_legacy"])).toEqual({ + role: "user", + text: "hello", + }) + }).pipe(Effect.provide(remappedStorage(tmp))) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } expect(yield* fs.readFileString(path.join(storage, "migration"))).toBe("2") }), From 9ee08fdc2999157ed2a6b659f8bd8c42e4a03128 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:12:35 -0800 Subject: [PATCH 15/72] Tighten offline connection and startup checks Reject remote MCP connections before persisting enablement and skip workspace tools in standalone offline MCP. Validate MongoDB's effective connection options, suppress DuckDB automatic extension setup, and keep offline config discovery from expanding file references. --- packages/drivers/src/duckdb.ts | 5 +++- .../drivers/src/local-engine-child-source.ts | 2 ++ .../altimate/native/connections/offline.ts | 8 ++++-- packages/opencode/src/cli/cmd/mcp.ts | 7 ++++- packages/opencode/src/config/offline.ts | 2 +- packages/opencode/src/config/paths.ts | 12 ++++++--- packages/opencode/src/mcp/index.ts | 2 ++ packages/opencode/src/skill/discovery.ts | 16 +++++++----- .../native/offline-connections.test.ts | 3 +++ .../test/altimate/workspace/state-pin.test.ts | 26 ++++++++++++++++++- 10 files changed, 68 insertions(+), 15 deletions(-) diff --git a/packages/drivers/src/duckdb.ts b/packages/drivers/src/duckdb.ts index 19e9bb4ab4..135b999e22 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 — skip automatic extension downloads in app-owned offline helpers + const offline = process.env.ALTIMATE_OFFLINE === "1" 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..4ec174c0ec 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 — ordinary offline connections keep local file access + ...(p.offline ? { autoinstall_known_extensions: "false", autoload_known_extensions: "false" } : {}), }; let instance; await new Promise((resolve, reject) => { diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index dc5aa2e6f1..3f244edc1e 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -36,6 +36,8 @@ export function assertLocalConnection(raw: ConnectionConfig): void { if (!["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "oracle", "redshift", "clickhouse", "trino", "mongodb", "mongo"].includes(type)) deny() // Cloud authentication may contact an identity provider even for a loopback host. if (config.authentication && !["default", "sql", "ntlm"].includes(String(config.authentication).toLowerCase())) deny() + const mongo = type === "mongodb" || type === "mongo" + if (mongo && config.direct_connection !== undefined && config.direct_connection !== true) deny() if (config.host !== undefined && !isLoopbackHost(config.host)) deny() const connectionString = type === "trino" ? config.connection_string ?? config.server ?? config.url @@ -45,11 +47,13 @@ export function assertLocalConnection(raw: ConnectionConfig): void { const url = new URL(String(connectionString)) if ((type === "trino" || type === "clickhouse") && !["http:", "https:"].includes(url.protocol)) deny() if (!isLoopbackHost(url.hostname) || url.protocol === "mongodb+srv:") deny() - if (["mongodb", "mongo"].includes(type) && url.searchParams.get("directConnection") !== "true") deny() + const query = new Map([...url.searchParams].map(([key, value]) => [key.toLowerCase(), value.toLowerCase()])) + if (mongo && config.direct_connection !== true && query.get("directconnection") !== "true") deny() + if (mongo && ["mongodb-aws", "mongodb-oidc", "gssapi"].includes(query.get("authmechanism") ?? "")) deny() // Drivers can override the authority via URL parameters or discover replica peers. for (const key of url.searchParams.keys()) { if (["host", "hostaddr", "server", "replicaset", "service"].includes(key.toLowerCase())) deny() } } catch { deny() } - } else if (["mongodb", "mongo"].includes(type) || !isLoopbackHost(config.host ?? "127.0.0.1")) deny() + } else if (mongo && config.direct_connection !== true) deny() } diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index 0588ad6d37..c5f4952566 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -142,7 +142,12 @@ export const McpServeCommand = cmd({ async handler(args) { await Offline.start(process.cwd()) 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 diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 941e1d18c8..6d2dd16789 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -19,7 +19,7 @@ async function localOptIn(directory: string) { const optedIn = async (text: string | undefined, source: string | { source: string; dir: string }) => { if (!text) return false if (parse(text)?.offline === true) return true - const config = await ConfigPaths.parseText(text, source, "empty", { track: false }).catch(() => undefined) + const config = await ConfigPaths.parseText(text, source, "empty", { track: false, expandFiles: false }).catch(() => undefined) return config?.offline === true } if (await optedIn(env("OPENCODE_CONFIG_CONTENT"), { source: "OPENCODE_CONFIG_CONTENT", dir: directory })) return true diff --git a/packages/opencode/src/config/paths.ts b/packages/opencode/src/config/paths.ts index 9c979ef90c..2bb2385df9 100644 --- a/packages/opencode/src/config/paths.ts +++ b/packages/opencode/src/config/paths.ts @@ -142,7 +142,12 @@ function dir(input: ParseSource) { } /** Apply ${VAR}/${VAR:-default}/$${VAR}/{env:VAR} and {file:path} substitutions to config text. */ -async function substitute(text: string, input: ParseSource, missing: "error" | "empty" = "error", track = true) { +async function substitute( + text: string, + input: ParseSource, + missing: "error" | "empty" = "error", + opts: { track?: boolean; expandFiles?: boolean } = {}, +) { // Single-pass substitution against the ORIGINAL text prevents output of one // pattern being re-matched by another (e.g. {env:A}="${B}" expanding B). // Uses the shared ENV_VAR_PATTERN grammar, adding JSON-escaping for values @@ -205,6 +210,7 @@ async function substitute(text: string, input: ParseSource, missing: "error" | " } // altimate_change end + if (opts.expandFiles === false) return text const fileMatches = Array.from(text.matchAll(/\{file:[^}]+\}/g)) if (!fileMatches.length) return text @@ -264,10 +270,10 @@ export async function parseText( text: string, input: ParseSource, missing: "error" | "empty" = "error", - opts: { track?: boolean } = {}, + opts: { track?: boolean; expandFiles?: boolean } = {}, ): Promise { const configSource = source(input) - text = await substitute(text, input, missing, opts.track !== false) + text = await substitute(text, input, missing, opts) const errors: JsoncParseError[] = [] const data = parseJsonc(text, errors, { allowTrailingComma: true }) diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 5404d3e1eb..1090da6ded 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -1101,6 +1101,8 @@ export const layer = Layer.effect( const token = claim(s, name, seq) // altimate_change end const mcp = yield* requireMcpConfig(name) + // altimate_change — reject before persisting enabled:true for an offline remote server + Offline.assertLocalMcp(mcp) // altimate_change start — see createAndStore yield* createAndStore(name, { ...mcp, enabled: true }, token) // altimate_change end diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index c7f2a69484..27a4bdfef0 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -62,14 +62,17 @@ export namespace Discovery { const base = url.endsWith("/") ? url : `${url}/` const index = new URL("index.json", base).href // altimate_change start — reuse the cached index for this source without contacting it - const indexPath = path.join(cache, ".indexes", createHash("sha256").update(index).digest("hex") + ".json") + const sourceCache = path.join(cache, ".sources", createHash("sha256").update(index).digest("hex")) + const indexPath = path.join(sourceCache, "index.json") if (Offline.enabled()) { const cached = yield* fs.readJson(indexPath).pipe(Effect.catch(() => Effect.succeed(undefined))) const directories = Array.isArray(cached) ? cached : [] - return yield* Effect.filter(directories.filter((dir): dir is string => - typeof dir === "string" && path.relative(cache, dir).split(path.sep).length === 1 && - path.dirname(dir) === cache, - ), (dir) => fs.exists(path.join(dir, "SKILL.md")).pipe(Effect.orElseSucceed(() => false))) + const local = directories.filter((dir): dir is string => + typeof dir === "string" && path.dirname(dir) === sourceCache, + ) + return yield* Effect.filter(local, (dir) => + fs.exists(path.join(dir, "SKILL.md")).pipe(Effect.orElseSucceed(() => false)), + ) } // altimate_change end const host = base.slice(0, -1) @@ -91,6 +94,7 @@ export namespace Discovery { if (!data) return [] const list = data.skills.filter((skill) => { + if (skill.name === "." || skill.name === ".." || !skill.name || /[\\/]/.test(skill.name)) return false if (!skill.files.includes("SKILL.md")) { log.warn("skill entry missing SKILL.md", { url: index, skill: skill.name }) return false @@ -102,7 +106,7 @@ export namespace Discovery { list, (skill) => Effect.gen(function* () { - const root = path.join(cache, skill.name) + const root = path.join(sourceCache, skill.name) yield* Effect.forEach( skill.files, diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index bf6af82a56..83342b3946 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -26,6 +26,9 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "sqlserver", host: "localhost", authentication: "azure-active-directory-default" }, { type: "postgres", connection_string: "postgres://localhost/db?host=remote" }, { type: "mongodb", connection_string: "mongodb+srv://localhost/db" }, + { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true", direct_connection: false }, + { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true&authMechanism=MONGODB-AWS" }, + { type: "trino", url: "https://example.com" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) test("dbt checks selected target and CLI overrides", async () => { diff --git a/packages/opencode/test/altimate/workspace/state-pin.test.ts b/packages/opencode/test/altimate/workspace/state-pin.test.ts index 96459e2d8e..1a83fd50c4 100644 --- a/packages/opencode/test/altimate/workspace/state-pin.test.ts +++ b/packages/opencode/test/altimate/workspace/state-pin.test.ts @@ -13,7 +13,7 @@ const SANDBOX = path.join(os.tmpdir(), `altimate-state-pin-test-${process.pid}-$ mkdirSync(path.join(SANDBOX, "state"), { recursive: true }) process.env.XDG_STATE_HOME = path.join(SANDBOX, "state") -const { resolveBindingOutcome, __resetPinValidation, PIN_VALIDATION_TTL_MS, PIN_STALE_IF_ERROR_MS } = +const { recordApprovedBinding, resolveBindingOutcome, __resetPinValidation, PIN_VALIDATION_TTL_MS, PIN_STALE_IF_ERROR_MS } = await import("../../../src/altimate/workspace/state") const { AltimateApi } = await import("../../../src/altimate/api/client") const { WorkspaceApi, ForbiddenError, WorkspaceApiError } = await import( @@ -116,6 +116,30 @@ afterAll(() => { }) describe("resolveBindingOutcome — extension pin", () => { + test("offline only returns an existing unpinned local binding", async () => { + const directory = path.join(SANDBOX, "offline-project") + mkdirSync(directory, { recursive: true }) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + let requests = 0 + ;(WorkspaceApi as unknown as { listDatamates: () => Promise }).listDatamates = async () => { + requests++ + return [] + } + try { + expect(await resolveBindingOutcome(directory)).toEqual({ status: "unknown" }) + const binding = { datamateId: 17, datamateName: "local", linkedAt: Date.now(), repoRemote: null, projectPath: null } + await recordApprovedBinding(directory, binding, { seed: false, awaitBackfill: true }) + expect(await resolveBindingOutcome(directory)).toMatchObject({ status: "bound", stale: true, binding }) + setPin({ ALTIMATE_PINNED_WORKSPACE_ROOT: directory }) + expect(await resolveBindingOutcome(directory)).toEqual({ status: "unknown" }) + expect(requests).toBe(0) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) + test("a valid, account-visible pin binds, and is marked pinned", async () => { setPin() const out = await resolveBindingOutcome(ROOT) From 69e606109b4780ebec6d50bcea53daaff82e8d1c Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:14:24 -0800 Subject: [PATCH 16/72] Preserve env interpolation in offline startup detection Use the parser options for the interpolation telemetry guard. Keep the configured mode effective before startup when it comes from an env reference. --- packages/opencode/src/config/paths.ts | 2 +- packages/opencode/test/cli/run/offline.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/config/paths.ts b/packages/opencode/src/config/paths.ts index 2bb2385df9..e5bd6caab1 100644 --- a/packages/opencode/src/config/paths.ts +++ b/packages/opencode/src/config/paths.ts @@ -191,7 +191,7 @@ async function substitute( // the telemetry schema). Dynamic import avoids a circular dep with @/altimate/telemetry (which // imports @/config/config). Matches main's single emit site in substitute(). const { dollarRefs, dollarUnresolved, dollarDefaulted, dollarEscaped, legacyBraceRefs, legacyBraceUnresolved } = stats - if (track && (dollarRefs > 0 || legacyBraceRefs > 0 || dollarEscaped > 0)) { + if (opts.track !== false && (dollarRefs > 0 || legacyBraceRefs > 0 || dollarEscaped > 0)) { import("@/altimate/telemetry") .then(({ Telemetry }) => { Telemetry.track({ diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 37c1bd80b2..fac1060f3a 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -186,7 +186,7 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ .split("\n") .filter(Boolean) .map((line) => JSON.parse(line)) - expect(calls.filter((call) => call.url !== MODEL_ENDPOINT + "/chat/completions")).toEqual([]) + 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) From 251c176fbe455781eeca0e3b8e7cf441408970e7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:18:39 -0800 Subject: [PATCH 17/72] Address offline transport and local tooling review findings Validate restored warehouse targets and effective dbt CLI aliases, reject SQL Server cloud auth aliases, and update local submodules without a fetch. Let cached LSP binaries resolve without installing or mutating the npm cache. --- docs/docs/configure/config.md | 2 +- packages/core/src/npm.ts | 2 ++ packages/core/test/npm.test.ts | 7 +++++ .../altimate/native/connections/offline.ts | 2 +- .../altimate/native/connections/registry.ts | 10 +++---- .../src/altimate/native/dbt/offline.ts | 10 ++++--- packages/opencode/src/lsp/server.ts | 26 +++++++++++++------ packages/opencode/src/worktree/index.ts | 15 +++++------ .../native/offline-connections.test.ts | 3 +++ .../test/altimate/workspace/state-pin.test.ts | 2 +- 10 files changed, 50 insertions(+), 29 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 53f876a8df..7c0082e9c5 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ Configure an explicit HTTP(S) provider `options.baseURL` and select its `provide - SQL tools can query local DuckDB and SQLite files or a warehouse listening on loopback. Use a local dbt profile for dbt commands. - Bash, installed language servers, and MCP servers using stdio or a loopback HTTP(S) URL remain available. Altimate Code skips automatic language server and warehouse driver installs. Install optional drivers and ripgrep ahead of time. -- Git diffs, session snapshots and revert, and worktree creation, removal and reset operate locally. Reset uses the cached base and skips submodule downloads. Run Git remote operations online. +- Git diffs, session snapshots and revert, and worktree creation, removal and reset operate locally. Reset uses the cached base and any locally available submodule commits. Run Git remote operations online. - Altimate Code skips telemetry, account and remote configuration requests, model catalog downloads, update checks, workspace and engine sync, session sharing, and web search and fetch. Remote warehouse and MCP connections require an online run. Refresh workspace skills before going offline to use an existing snapshot. The configured model endpoint is the only external endpoint Altimate Code contacts in offline mode. Shell commands and other programs you configure or invoke retain their own network access. diff --git a/packages/core/src/npm.ts b/packages/core/src/npm.ts index d79a6805fe..6c17df2c81 100644 --- a/packages/core/src/npm.ts +++ b/packages/core/src/npm.ts @@ -233,6 +233,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/test/npm.test.ts b/packages/core/test/npm.test.ts index 9e852f6ccb..d221e61208 100644 --- a/packages/core/test/npm.test.ts +++ b/packages/core/test/npm.test.ts @@ -70,12 +70,19 @@ test("offline npm uses the cache and skips installation", async () => { 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" }] }) diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 3f244edc1e..b8a8721c51 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -35,7 +35,7 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } if (!["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "oracle", "redshift", "clickhouse", "trino", "mongodb", "mongo"].includes(type)) deny() // Cloud authentication may contact an identity provider even for a loopback host. - if (config.authentication && !["default", "sql", "ntlm"].includes(String(config.authentication).toLowerCase())) deny() + if (config.authentication && !["sql", "ntlm"].includes(String(config.authentication).toLowerCase())) deny() const mongo = type === "mongodb" || type === "mongo" if (mongo && config.direct_connection !== undefined && config.direct_connection !== true) deny() if (config.host !== undefined && !isLoopbackHost(config.host)) deny() diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 57f6a54d5d..37871ec26b 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -427,9 +427,6 @@ async function createConnector( attempt: Attempt, isCurrent: () => boolean, ): Promise { - // altimate_change end - // altimate_change start — skip network work in offline mode - if (Offline.enabled()) assertLocalConnection(config) // altimate_change end const driverPath = DRIVER_MAP[config.type.toLowerCase()] if (!driverPath) { @@ -453,6 +450,7 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) + // altimate_change — check the effective target after restoring stored credentials if (Offline.enabled()) assertLocalConnection(resolvedConfig) // altimate_change start — validate password is a string for drivers that require it @@ -679,11 +677,11 @@ export async function get(name: string): Promise { return getScratch() } - const configured = configs.get(name) - if (Offline.enabled() && configured) assertLocalConnection(configured) - const cached = connectors.get(name) if (cached) { + // altimate_change — apply the offline policy before using a cached connection + const configured = configs.get(name) + if (Offline.enabled() && configured) assertLocalConnection(await resolveConfig(name, normalizeConfig(configured))) // 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 diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index fe8da0a396..a1798ba838 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -18,11 +18,13 @@ function resolve(value: unknown): any { /** Resolve exactly the selected profile/target before starting dbt-owned network work. */ export async function assertLocalDbt(projectRoot: string, args: string[] = [], integration = "core"): Promise { if (!["core", "corecommand", "fusion"].includes(integration)) throw new Error("Offline mode disables cloud dbt integrations.") - const option = (name: string) => { + const option = (...names: string[]) => { let result: string | undefined for (let i = 0; i < args.length; i++) { - if (args[i] === name) result = args[++i] - else if (args[i].startsWith(name + "=")) result = args[i].slice(name.length + 1) + const arg = args[i] + const equals = arg.indexOf("=") + const name = equals < 0 ? arg : arg.slice(0, equals) + if (names.includes(name)) result = equals < 0 ? args[++i] : arg.slice(equals + 1) } return result } @@ -35,7 +37,7 @@ export async function assertLocalDbt(projectRoot: string, args: string[] = [], i const profiles = resolve(parse(await fs.readFile(profilesPath, "utf8"))) const profileName = option("--profile") ?? process.env.DBT_PROFILE ?? project.profile const profile = profiles?.[profileName] - const target = option("--target") ?? option("-t") ?? process.env.DBT_TARGET ?? profile?.target ?? "default" + const target = option("--target", "-t") ?? process.env.DBT_TARGET ?? profile?.target ?? "default" const output = profile?.outputs?.[target] if (!output || typeof output.type !== "string") throw new Error("Offline mode could not resolve a local dbt profile and target.") if (!["duckdb", "sqlite"].includes(output.type)) { diff --git a/packages/opencode/src/lsp/server.ts b/packages/opencode/src/lsp/server.ts index 64bcfcf486..967664c994 100644 --- a/packages/opencode/src/lsp/server.ts +++ b/packages/opencode/src/lsp/server.ts @@ -12,6 +12,8 @@ import { which } from "@opencode-ai/core/util/which" import { Module } from "@opencode-ai/core/util/module" import { spawn } from "./launch" import { Npm } from "@opencode-ai/core/npm" +// altimate_change — npm can resolve existing language servers without downloading offline +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" import type { RuntimeFlags } from "@/effect/runtime-flags" const pathExists = async (p: string) => @@ -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/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 2b68c2dfe9..9c871bda0f 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -600,14 +600,13 @@ export const layer: Layer.Layer< }) } - // altimate_change start — submodule initialization can fetch missing objects - if (!Offline.enabled()) { - yield* gitExpect( - ["submodule", "update", "--init", "--recursive", "--force"], - { cwd: worktreePath }, - (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), - ) - } + // altimate_change start — update existing submodules from objects already on disk offline + const submoduleMode = Offline.enabled() ? "--no-fetch" : "--init" + yield* gitExpect( + ["submodule", "update", submoduleMode, "--recursive", "--force"], + { cwd: worktreePath }, + (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), + ) // altimate_change end yield* gitExpect( diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 83342b3946..d628a7c362 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -24,6 +24,7 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "postgres", host: "127.0.0.1", ssh_host: "remote" }, { type: "snowflake", host: "localhost" }, { type: "sqlserver", host: "localhost", authentication: "azure-active-directory-default" }, + { type: "sqlserver", host: "localhost", authentication: "default" }, { type: "postgres", connection_string: "postgres://localhost/db?host=remote" }, { type: "mongodb", connection_string: "mongodb+srv://localhost/db" }, { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true", direct_connection: false }, @@ -39,6 +40,8 @@ test("dbt checks selected target and CLI overrides", async () => { const args = ["--profiles-dir", root] await expect(assertLocalDbt(root, args)).resolves.toBeUndefined() 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.toBeUndefined() await expect(assertLocalDbt(root, args, "cloud")).rejects.toThrow("Offline mode") } finally { await fs.rm(root, { recursive: true, force: true }) } }) diff --git a/packages/opencode/test/altimate/workspace/state-pin.test.ts b/packages/opencode/test/altimate/workspace/state-pin.test.ts index 1a83fd50c4..08ee7f1a86 100644 --- a/packages/opencode/test/altimate/workspace/state-pin.test.ts +++ b/packages/opencode/test/altimate/workspace/state-pin.test.ts @@ -128,7 +128,7 @@ describe("resolveBindingOutcome — extension pin", () => { } try { expect(await resolveBindingOutcome(directory)).toEqual({ status: "unknown" }) - const binding = { datamateId: 17, datamateName: "local", linkedAt: Date.now(), repoRemote: null, projectPath: null } + const binding = { datamateId: 17, datamateName: "local", linkedAt: Date.now(), repoRemote: null, projectPath: directory } await recordApprovedBinding(directory, binding, { seed: false, awaitBackfill: true }) expect(await resolveBindingOutcome(directory)).toMatchObject({ status: "bound", stale: true, binding }) setPin({ ALTIMATE_PINNED_WORKSPACE_ROOT: directory }) From e331f02a5eadb93b22e47a3cd56246fcc5e72cf7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:23:47 -0800 Subject: [PATCH 18/72] Address offline provider and workspace review findings Keep the local OpenAI and Anthropic SDK options, restrict model calls to the configured base path, and hide prior-workspace skills without purging their files. Retry offline notices after failed delivery. Recheck cached connectors after credential reads and recognize dbt's compact target alias. --- .../altimate/native/connections/registry.ts | 5 ++- .../src/altimate/native/dbt/offline.ts | 12 +++++-- .../src/altimate/workspace/skill-sync.ts | 8 ++++- packages/opencode/src/config/offline.ts | 33 ++++++++++++++----- packages/opencode/src/provider/provider.ts | 6 ++-- packages/opencode/src/session/prompt.ts | 8 +++-- .../native/offline-connections.test.ts | 1 + .../opencode/test/cli/run/offline.test.ts | 10 +++++- 8 files changed, 64 insertions(+), 19 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 37871ec26b..844e749233 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -681,7 +681,10 @@ export async function get(name: string): Promise { if (cached) { // altimate_change — apply the offline policy before using a cached connection const configured = configs.get(name) - if (Offline.enabled() && configured) assertLocalConnection(await resolveConfig(name, normalizeConfig(configured))) + if (Offline.enabled() && configured) { + assertLocalConnection(await resolveConfig(name, normalizeConfig(configured))) + if (connectors.get(name) !== cached || configs.get(name) !== configured) return get(name) + } // 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 diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index a1798ba838..8e6f284487 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -22,9 +22,15 @@ export async function assertLocalDbt(projectRoot: string, args: string[] = [], i let result: string | undefined for (let i = 0; i < args.length; i++) { const arg = args[i] - const equals = arg.indexOf("=") - const name = equals < 0 ? arg : arg.slice(0, equals) - if (names.includes(name)) result = equals < 0 ? args[++i] : arg.slice(equals + 1) + if (arg === "--") break + for (const name of names) { + if (arg === name) { + result = args[++i] + break + } + const prefix = name.startsWith("--") ? name + "=" : name + if (arg.startsWith(prefix)) result = arg.slice(prefix.length) + } } return result } diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index 61b7f48892..8c8ed459be 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -190,7 +190,13 @@ export async function ownManifest(directory: string): Promise { manifest.tenant === creds.altimateInstanceName && manifest.apiUrl === creds.altimateUrl && manifest.account === credentialDigest(creds.altimateUrl, creds.altimateInstanceName, creds.altimateApiKey) - return ours ? manifest : null + if (!ours) return null + // altimate_change — hide a stale workspace snapshot offline without removing it + if (Offline.enabled()) { + const local = await readLocalBinding(directory) + if (local && local.datamateId !== manifest.datamateId) return null + } + return manifest } catch { return null } diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 6d2dd16789..528e08d3a1 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -119,10 +119,14 @@ export function modelFetch(baseURL: string | undefined): typeof fetch { const endpoint = new URL(baseURL) if (!["http:", "https:"].includes(endpoint.protocol)) throw new Error("Offline mode requires an HTTP(S) model endpoint.") + const basePath = endpoint.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 !== endpoint.origin) + if ( + target.origin !== endpoint.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", proxy: undefined }) }, @@ -161,16 +165,27 @@ export function localFetch(): typeof fetch { let warned = false -export async function announce(hasSnapshot: boolean) { +export async function announce(hasSnapshot: boolean, knownEmpty = false) { if (warned) return warned = true - const message = hasSnapshot - ? "Using cached workspace skills." - : "No usable workspace skill snapshot. To use workspace skills, run altimate-code workspace refresh while online." - const { isHeadless } = await import("@/altimate/workspace/engine-seams") - const { notify, printLine } = await import("@/altimate/workspace/engine-probes") - if (isHeadless()) printLine(`Offline mode: ${message}`) - else await notify({ title: "Offline mode", message, variant: hasSnapshot ? "info" : "warning" }) + let delivered = false + try { + const message = hasSnapshot + ? "Using cached workspace skills." + : knownEmpty + ? "This workspace has no custom skills." + : "No usable workspace skill snapshot. To use workspace skills, run altimate-code workspace refresh while online." + const { isHeadless } = await import("@/altimate/workspace/engine-seams") + const { notify, printLine } = await import("@/altimate/workspace/engine-probes") + if (isHeadless()) { + printLine(`Offline mode: ${message}`) + delivered = true + } else { + delivered = await notify({ title: "Offline mode", message, variant: hasSnapshot || knownEmpty ? "info" : "warning" }) + } + } finally { + if (!delivered) warned = false + } } export * as Offline from "./offline" diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index e7da21d74f..bb022e7a47 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -2017,14 +2017,16 @@ export namespace Provider { // altimate_change end const data = database[providerID] // altimate_change start — skip provider discovery and OAuth-backed loaders in offline mode - if (Offline.enabled()) continue + 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])) { + if (result && (result.autoload || providers[providerID] || permittedOfflineLoader)) { if (result.getModel) modelLoaders[providerID] = result.getModel if (result.vars) varsLoaders[providerID] = result.vars const opts = result.options ?? {} diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 2efe147859..02aa20b5a6 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -138,6 +138,7 @@ import { ErrorDetail } from "@/altimate/telemetry/error-detail" // altimate_chan import { canonicalDirectory, endTurnBinding, + resolveBindingOutcome, turnBinding, unvalidatedTurnBinding, type AccountKey, @@ -481,8 +482,11 @@ export namespace SessionPrompt { if (Offline.enabled()) { const dir = Instance.directory const writeOfflineNotice = async () => { - const { ownManifest } = await import("../altimate/workspace/skill-sync") - await Offline.announce((await ownManifest(dir)) !== null) + const { ownManifest, snapshotKnownEmpty } = await import("../altimate/workspace/skill-sync") + const snapshot = await ownManifest(dir) + const binding = snapshot ? null : await resolveBindingOutcome(dir) + const empty = binding?.status === "bound" && await snapshotKnownEmpty(dir, binding.binding.datamateId) + await Offline.announce(snapshot !== null, empty) await refreshSkillRegistry(dir) } const notice = writeOfflineNotice().catch((error) => log.warn("offline skill snapshot setup failed", { error })) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index d628a7c362..30ca40d9e8 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -42,6 +42,7 @@ test("dbt checks selected target and CLI overrides", async () => { 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.toBeUndefined() + 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 }) } }) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index fac1060f3a..67d134e856 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -306,6 +306,14 @@ test("offline model transport bypasses proxy settings and refuses redirects", as if (!error.message.includes("outside the configured model endpoint")) throw error console.log("cross-origin request refused") } + try { + const modelScoped = Offline.modelFetch(new URL("/v1", process.env.OFFLINE_TEST_MODEL).href) + await modelScoped(new URL("/v10/admin", process.env.OFFLINE_TEST_MODEL)) + throw new Error("different endpoint path was accepted") + } catch (error) { + if (!error.message.includes("outside the configured model endpoint")) throw error + console.log("other model host path refused") + } try { await request(new URL("/redirect", process.env.OFFLINE_TEST_MODEL)) throw new Error("redirect was accepted") @@ -338,7 +346,7 @@ test("offline model transport bypasses proxy settings and refuses redirects", as ]) expect({ code, stdout, stderr }).toEqual({ code: 0, - stdout: "direct model response\ncross-origin request refused\nredirect refused\n", + stdout: "direct model response\ncross-origin request refused\nother model host path refused\nredirect refused\n", stderr: "", }) expect(proxyCalls).toBe(0) From 3d58d96bed213734d7b6fee3d1d119b9ffb6402b Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:29:28 -0800 Subject: [PATCH 19/72] Keep compatible models and workspace changes working offline Fall back to the SDK language model if an offline OpenAI provider uses the compatible SDK. Include the offline workspace binding in the skill registry identity so a rebind invalidates stale skill visibility. --- .../src/altimate/workspace/skill-sync.ts | 4 +++- packages/opencode/src/provider/provider.ts | 2 ++ .../altimate/workspace/skill-sync.test.ts | 19 +++++++++++++++++++ .../opencode/test/cli/run/offline.test.ts | 13 +++++++++---- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index 8c8ed459be..3f111d6cd2 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -515,7 +515,9 @@ async function registryIdentity(canon: string): Promise { } catch { /* no credentials resolved; the empty account is the honest answer */ } - return `${snapshotFingerprint(canon)}\u0000${account}` + // altimate_change — a changed local binding can hide a snapshot without changing its files + const binding = Offline.enabled() ? await readLocalBinding(canon) : null + return `${snapshotFingerprint(canon)}\u0000${account}\u0000${binding?.datamateId ?? ""}` } /** Does the skill registry still reflect a different snapshot, or a different diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index bb022e7a47..e4f30eaf53 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -635,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 diff --git a/packages/opencode/test/altimate/workspace/skill-sync.test.ts b/packages/opencode/test/altimate/workspace/skill-sync.test.ts index 24a56c348c..5e578a6ea6 100644 --- a/packages/opencode/test/altimate/workspace/skill-sync.test.ts +++ b/packages/opencode/test/altimate/workspace/skill-sync.test.ts @@ -1338,6 +1338,25 @@ describe("workspace skill sync", () => { } }) + test("offline registry notices a changed local binding without deleting the snapshot", async () => { + serve({ "pub-1": { "SKILL.md": "one" } }) + await syncSkills(project) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + expect(await snapshotWorkspaceId(project)).toBe(1) + await markRegistryApplied(project) + expect(await registryStale(project)).toBe(false) + bindTo(2) + expect(await registryStale(project)).toBe(true) + expect(await snapshotWorkspaceId(project)).toBeNull() + expect(existsSync(skillFile("pub-1", "SKILL.md"))).toBe(true) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) + test("registryStale reports a credential switch, with the snapshot untouched", async () => { // The disclosure this guards: the registry had already loaded the previous // account's skills, and an A-to-B switch changes nothing on disk. Keyed on diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 67d134e856..1e8e13e37a 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -11,7 +11,12 @@ const TENANT = "offline-fixture" const KEY = "fixture-key" const SKILL = "This unique statement came from the cached offline skill." -async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: boolean) { +async function fixture( + snapshot: boolean, + configMode: boolean, + 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") @@ -23,9 +28,9 @@ async function fixture(snapshot: boolean, configMode: boolean, disableWorkspace: await Bun.write( path.join(config, "altimate-code.json"), JSON.stringify({ - model: "offline-test/fixture", + model: `${provider}/fixture`, provider: { - "offline-test": { + [provider]: { npm: "@ai-sdk/openai-compatible", options: { baseURL: MODEL_ENDPOINT, apiKey: "local-only" }, models: { fixture: { name: "Offline fixture", limit: { context: 100000, output: 2000 } } }, @@ -163,7 +168,7 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ { scenario: "config switch without a snapshot", snapshot: false, configMode: true, disableWorkspace: false }, ]) { test(`offline ${scenario} keeps network traffic on the model endpoint`, async () => { - const f = await fixture(snapshot, configMode, disableWorkspace) + const f = await fixture(snapshot, configMode, disableWorkspace, snapshot ? "offline-test" : "openai") try { const before = snapshot ? await fs.readFile(f.manifest, "utf8") : undefined const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "Hello"], { From 073cf787dcbf0669f98614fd80a8e3bcfdd3fbb3 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:32:56 -0800 Subject: [PATCH 20/72] Keep offline background calls on the configured model Use the caller's model for title and helper requests unless small_model is explicitly configured. A local compatible endpoint may not serve the catalog's default model or its provider protocol. --- packages/opencode/src/provider/provider.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index e4f30eaf53..d01718f9ae 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -2436,6 +2436,9 @@ export namespace Provider { return getModel(parsed.providerID, parsed.modelID) } + // altimate_change — use the caller's configured model when no offline small model is set + if (Offline.enabled()) return undefined + const provider = await state().then((state) => state.providers[providerID]) if (provider) { let priority = [ From f6e4ca62c87cbb392d665bf289c6f6148d0c891f Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:44:16 -0800 Subject: [PATCH 21/72] Seed the offline DuckDB fixture through the SQL runner Use the production DuckDB helper to create and populate a temporary file. Assert it exists before reopening the connection read-only so Linux CI does not depend on the native driver's standalone eval timing. --- .../opencode/test/cli/run/offline.test.ts | 56 ++++++++++--------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 1e8e13e37a..229890527f 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -238,33 +238,35 @@ 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 seed = Bun.spawn([process.execPath, "-e", ` - const duckdb = require("duckdb") - const db = new duckdb.Database(process.argv[1]) - db.run("create table fixture as select 42 as offline_answer", (err) => { - if (err) throw err - db.close() + 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), }) - `, database], { cwd: import.meta.dir, stderr: "inherit" }) - expect(await seed.exited).toBe(0) - await Bun.write(path.join(f.project, ".altimate-code", "connections.json"), JSON.stringify({ - local: { type: "duckdb", path: database }, - })) - const proc = Bun.spawn([ - process.execPath, "--preload", f.preload, CLI, "tool", "run", "sql_execute", "--args", - JSON.stringify({ warehouse: "local", query: "select offline_answer from fixture" }), "--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(), - ]) + 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") @@ -273,7 +275,7 @@ test("offline SQL tool queries a local DuckDB file", async () => { } finally { await fs.rm(f.root, { recursive: true, force: true }) } -}, 30_000) +}, 55_000) test("offline model transport bypasses proxy settings and refuses redirects", async () => { let proxyCalls = 0 From 86d9c6e4e731442b9ead587f0fff0dd3608b8d24 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:55:16 -0800 Subject: [PATCH 22/72] Close offline transport gaps and cover local cache behavior Share Git transport policy across Git entry points, check remote skill paths, and bind cached connector policy to the resolved target. Preserve dbt policy errors and apply typed MCP refusals at the HTTP API. Add local coverage for installed tools, storage migration and offline client errors. --- docs/docs/configure/config.md | 4 +- packages/core/src/git.ts | 43 ++++++- packages/core/src/skill/discovery.ts | 3 +- packages/core/test/git.test.ts | 22 ++++ packages/drivers/src/duckdb.ts | 2 +- .../drivers/src/local-engine-child-source.ts | 2 + .../opencode/src/altimate/debug/collect.ts | 3 +- .../altimate/native/connections/offline.ts | 2 +- .../altimate/native/connections/register.ts | 7 +- .../altimate/native/connections/registry.ts | 23 +++- .../src/altimate/native/dbt/offline.ts | 14 ++- .../src/altimate/workspace/skill-sync.ts | 11 +- packages/opencode/src/bun/index.ts | 4 +- packages/opencode/src/cli/cmd/mcp.ts | 3 + packages/opencode/src/git/index.ts | 22 +--- packages/opencode/src/mcp/index.ts | 21 +++- .../routes/instance/httpapi/groups/mcp.ts | 4 +- packages/opencode/src/skill/discovery.ts | 6 +- packages/opencode/src/util/git.ts | 16 ++- .../test/altimate/debug/collect.test.ts | 15 ++- .../test/altimate/mcp-server/stdio.test.ts | 27 +++++ .../native/offline-connections.test.ts | 112 +++++++++++++++++- .../altimate/registry-per-project.test.ts | 19 +++ .../altimate/workspace/skill-sync.test.ts | 6 + packages/opencode/test/bun.test.ts | 42 +++++++ .../test/config/paths-parsetext.test.ts | 8 ++ packages/opencode/test/lsp/offline.test.ts | 43 +++++++ .../opencode/test/server/httpapi-mcp.test.ts | 33 ++++++ .../opencode/test/share/share-next.test.ts | 15 +++ .../opencode/test/storage/storage.test.ts | 42 +++++++ 30 files changed, 519 insertions(+), 55 deletions(-) create mode 100644 packages/opencode/test/lsp/offline.test.ts diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 7c0082e9c5..afdeb2ca92 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ Configure an explicit HTTP(S) provider `options.baseURL` and select its `provide - SQL tools can query local DuckDB and SQLite files or a warehouse listening on loopback. Use a local dbt profile for dbt commands. - Bash, installed language servers, and MCP servers using stdio or a loopback HTTP(S) URL remain available. Altimate Code skips automatic language server and warehouse driver installs. Install optional drivers and ripgrep ahead of time. -- Git diffs, session snapshots and revert, and worktree creation, removal and reset operate locally. Reset uses the cached base and any locally available submodule commits. Run Git remote operations online. -- Altimate Code skips telemetry, account and remote configuration requests, model catalog downloads, update checks, workspace and engine sync, session sharing, and web search and fetch. Remote warehouse and MCP connections require an online run. Refresh workspace skills before going offline to use an existing snapshot. +- Git diffs, session snapshots and revert, and worktree creation, removal and reset operate locally. Reset uses the cached base and any locally available submodule commits. Git LFS files may appear as pointers until hydrated online. Run Git remote operations online. +- Altimate Code skips telemetry, account and remote configuration requests, model catalog downloads, update checks, workspace and engine sync, session sharing, and web search and fetch. Remote warehouse and MCP connections require an online run. Run `altimate-code workspace refresh` before going offline to save a snapshot. Keep local credentials for the same workspace account to use that snapshot. The configured model endpoint is the only external endpoint Altimate Code contacts in offline mode. Shell commands and other programs you configure or invoke retain their own network access. diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 0041c3353f..9b18c4d8a2 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -7,6 +7,29 @@ import { AbsolutePath } from "./schema" import { FSUtil } from "./fs-util" import { AppProcess } from "./process" import { LayerNode } from "./effect/layer-node" +// altimate_change — offline transport policy +import { offlineModeEnabled } from "./flag/flag" + +// altimate_change start — prevent Git from starting a transport offline +const remoteCommands = new Set(["clone", "fetch", "pull", "push", "ls-remote", "send-pack", "fetch-pack", "submodule--helper"]) + +export function localGitEnv(env?: Record) { + return offlineModeEnabled() + ? { ...env, GIT_ALLOW_PROTOCOL: "", GIT_NO_LAZY_FETCH: "1", GIT_LFS_SKIP_SMUDGE: "1" } + : env +} + +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, operation, ...rest] = args.slice(index) + return remoteCommands.has(command) || + (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) +} +// altimate_change end + export interface Repo { /** @@ -251,6 +274,9 @@ export const layer = Layer.effect( .run( ChildProcess.make("git", ["apply", "-"], { cwd: input.directory, + // altimate_change start — apply the offline transport policy to patch application + env: localGitEnv(), + // altimate_change end extendEnv: true, stdin: Stream.make(new TextEncoder().encode(input.patch)), }), @@ -334,7 +360,9 @@ export const layer = Layer.effect( cwd = repo.directory, ) { const result = yield* proc - .run(ChildProcess.make("git", args, { cwd, extendEnv: true, stdin: "ignore" })) + // altimate_change start — apply offline transport policy to worktree commands + .run(ChildProcess.make("git", args, { cwd, env: localGitEnv(), extendEnv: true, stdin: "ignore" })) + // altimate_change end .pipe( Effect.mapError( (cause) => new WorktreeError({ operation, directory: worktreeDirectory, message: cause.message, cause }), @@ -414,13 +442,18 @@ function run(cwd: string, proc: AppProcess.Interface) { execute(cwd, proc)(args).pipe(Effect.catch(() => Effect.succeed({ exitCode: 1, text: "", stderr: "" }))) } +// altimate_change start — enforce offline Git transport policy at the spawn boundary function execute(cwd: string, proc: AppProcess.Interface) { - return (args: string[]) => - proc + return (args: string[]) => { + if (offlineModeEnabled() && gitCommandUsesNetwork(args)) { + return Effect.succeed({ exitCode: 1, text: "", stderr: "Git remote operations require an online run." }) + } + return proc .run( ChildProcess.make("git", args, { cwd, - extendEnv: true, + env: localGitEnv(), + extendEnv: true, stdin: "ignore", }), ) @@ -434,7 +467,9 @@ function execute(cwd: string, proc: AppProcess.Interface) { }) satisfies Result, ), ) + } } +// altimate_change end function resolvePath(cwd: string, value: string) { const trimmed = value.replace(/[\r\n]+$/, "") diff --git a/packages/core/src/skill/discovery.ts b/packages/core/src/skill/discovery.ts index 6402dd3b71..4c08deaa74 100644 --- a/packages/core/src/skill/discovery.ts +++ b/packages/core/src/skill/discovery.ts @@ -21,7 +21,8 @@ function isSafeSegment(value: string) { ) } -function isSafeRelativePath(value: string) { +// altimate_change — share cache path validation with the CLI skill loader +export function isSafeRelativePath(value: string) { const segments = value.split("/") return ( value.length > 0 && 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/drivers/src/duckdb.ts b/packages/drivers/src/duckdb.ts index 135b999e22..5e8f809bf6 100644 --- a/packages/drivers/src/duckdb.ts +++ b/packages/drivers/src/duckdb.ts @@ -113,7 +113,7 @@ export async function connect( const { ms: openTimeoutMs, source: openTimeoutSource } = resolveOpenTimeoutMs(config) // altimate_change end // altimate_change — skip automatic extension downloads in app-owned offline helpers - const offline = process.env.ALTIMATE_OFFLINE === "1" + const offline = !["", "0", "false"].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") diff --git a/packages/drivers/src/local-engine-child-source.ts b/packages/drivers/src/local-engine-child-source.ts index 4ec174c0ec..0177be2a5d 100644 --- a/packages/drivers/src/local-engine-child-source.ts +++ b/packages/drivers/src/local-engine-child-source.ts @@ -102,6 +102,8 @@ async function open(p) { ...(p.accessMode ? { access_mode: p.accessMode } : {}), ...(p.extensionDirectory ? { extension_directory: p.extensionDirectory } : {}), // altimate_change — ordinary offline connections keep local file access + // Network-capable extensions such as httpfs may already be installed, so + // restricting downloads alone cannot prevent automatic remote I/O. ...(p.offline ? { autoinstall_known_extensions: "false", autoload_known_extensions: "false" } : {}), }; let instance; diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 5bab0b3f05..f7047761fd 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -94,7 +94,8 @@ function envFlags(): string[] { /** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read * before it settles. Without, it is not started (it would send), so only the environment switches are checked. */ -async function telemetryFacts(network: boolean): Promise { +export async function telemetryFacts(network: boolean): Promise { + if (Offline.enabled()) return { enabled: false, checked: false, reason: "offline mode" } if (/^(1|true)$/i.test(process.env["ALTIMATE_TELEMETRY_DISABLED"] ?? "")) return { enabled: false, reason: "ALTIMATE_TELEMETRY_DISABLED is set" } if (/^(1|true)$/i.test(process.env["OPENCODE_DISABLE_TELEMETRY"] ?? "")) return { enabled: false, reason: "OPENCODE_DISABLE_TELEMETRY is set" } if (!network) return { enabled: false, checked: false, reason: "not started with --no-network" } diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index b8a8721c51..32fd9f6ff7 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -17,7 +17,7 @@ function localStore(value: unknown): boolean { if (/^file:/i.test(value)) { try { const url = new URL(value) - return !url.hostname || url.hostname === "localhost" + return (!url.hostname || url.hostname === "localhost") && !decodeURIComponent(url.pathname).startsWith("//") } catch { return false } } return isLocalFilePath(value) diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 8573ff15bb..7242091340 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -1,6 +1,6 @@ // altimate_change start — validate offline dbt profiles before starting adapters import { Offline } from "@/config/offline" -import { assertLocalDbt } from "../dbt/offline" +import { assertLocalDbt, OfflineDbtError } from "../dbt/offline" // altimate_change end /** * Register native connection handlers with the Dispatcher. @@ -139,7 +139,8 @@ async function ensureDbtAdapter(): Promise { ? { targetPath: await dbtToolTargetPath(dbtConfig.projectRoot) } : {} return publish(await create(dbtConfig, { ...options, ...(Offline.enabled() ? { offline: true } : {}) }), dbtConfig.projectRoot) - } catch { + } catch (error) { + if (error instanceof OfflineDbtError) throw error // dbt-tools not available or config invalid — fall back to native return publish(null) } finally { @@ -295,7 +296,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 (e instanceof OfflineDbtError || 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 844e749233..0d59b514ce 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -83,6 +83,10 @@ function createState(dir: string): State { /** Registry state per resolved project directory. */ const states = new Map() +// Classify the resolved target before SSH rewrites or driver construction. Keep only +// the verdict, not credentials, and never consult the keychain again on cache hits. +const offlineVerdicts = new WeakMap() + /** Invalidate the in-flight connect for `name`, closing the tunnel it opened. Synchronous. */ function dropAttempt(s: State, name: string): void { const attempt = s.pending.get(name) @@ -451,7 +455,13 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) // altimate_change — check the effective target after restoring stored credentials - if (Offline.enabled()) assertLocalConnection(resolvedConfig) + const offlineVerdict: { error?: Error } = {} + try { + assertLocalConnection(resolvedConfig) + } catch (error) { + offlineVerdict.error = error instanceof Error ? error : new Error(String(error)) + } + if (Offline.enabled() && offlineVerdict.error) throw offlineVerdict.error // altimate_change start — validate password is a string for drivers that require it // Prevents cryptic SASL/SCRAM errors from database drivers @@ -551,6 +561,7 @@ async function createConnector( throw new Error(`No static import available for driver: ${driverPath}`) } connector = await mod.connect(resolvedConfig) + offlineVerdicts.set(connector, offlineVerdict) } catch (e) { // Clean up SSH tunnel if driver creation fails // altimate_change start — this attempt's own tunnel, never another attempt's @@ -680,10 +691,12 @@ export async function get(name: string): Promise { const cached = connectors.get(name) if (cached) { // altimate_change — apply the offline policy before using a cached connection - const configured = configs.get(name) - if (Offline.enabled() && configured) { - assertLocalConnection(await resolveConfig(name, normalizeConfig(configured))) - if (connectors.get(name) !== cached || configs.get(name) !== configured) return get(name) + if (Offline.enabled()) { + const verdict = offlineVerdicts.get(cached) + if (!verdict || verdict.error) { + await detachCached(s, name)() + throw verdict?.error ?? new Error("Offline mode could not verify the cached connection target.") + } } // altimate_change start — a reused connection can reconnect and ask for a browser sign-in; route it here SignInNotice.rememberOrigin(accountOf(configs.get(name))) diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index 8e6f284487..70b0e89b43 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -15,8 +15,20 @@ function resolve(value: unknown): any { return value } +export class OfflineDbtError extends Error { + override name = "OfflineDbtError" +} + /** Resolve exactly the selected profile/target before starting dbt-owned network work. */ export async function assertLocalDbt(projectRoot: string, args: string[] = [], integration = "core"): Promise { + try { + await checkLocalDbt(projectRoot, args, integration) + } catch (error) { + throw new OfflineDbtError(error instanceof Error ? error.message : String(error), { cause: error }) + } +} + +async function checkLocalDbt(projectRoot: string, args: string[], integration: string): Promise { if (!["core", "corecommand", "fusion"].includes(integration)) throw new Error("Offline mode disables cloud dbt integrations.") const option = (...names: string[]) => { let result: string | undefined @@ -34,7 +46,7 @@ export async function assertLocalDbt(projectRoot: string, args: string[] = [], i } return result } - const root = option("--project-dir") ?? projectRoot + const root = option("--project-dir") ?? process.env.DBT_PROJECT_DIR ?? projectRoot const project = resolve(parse(await fs.readFile(path.join(root, "dbt_project.yml"), "utf8"))) const explicit = option("--profiles-dir") ?? process.env.DBT_PROFILES_DIR const local = path.join(root, "profiles.yml") diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index 3f111d6cd2..a63a43d23c 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -70,6 +70,7 @@ import { credentialDigest, currentScope, readLocalBinding, + readLocalBindingScopedStrict, resolveBindingOutcome, type AccountKey, type CachedBinding, @@ -193,7 +194,7 @@ export async function ownManifest(directory: string): Promise { if (!ours) return null // altimate_change — hide a stale workspace snapshot offline without removing it if (Offline.enabled()) { - const local = await readLocalBinding(directory) + const { binding: local } = await readLocalBindingScopedStrict(directory) if (local && local.datamateId !== manifest.datamateId) return null } return manifest @@ -516,8 +517,12 @@ async function registryIdentity(canon: string): Promise { /* no credentials resolved; the empty account is the honest answer */ } // altimate_change — a changed local binding can hide a snapshot without changing its files - const binding = Offline.enabled() ? await readLocalBinding(canon) : null - return `${snapshotFingerprint(canon)}\u0000${account}\u0000${binding?.datamateId ?? ""}` + const binding = Offline.enabled() + ? await readLocalBindingScopedStrict(canon) + .then(({ binding }) => binding?.datamateId ?? "") + .catch(() => "unreadable") + : "" + return `${snapshotFingerprint(canon)}\u0000${account}\u0000${binding}` } /** Does the skill registry still reflect a different snapshot, or a different diff --git a/packages/opencode/src/bun/index.ts b/packages/opencode/src/bun/index.ts index dcd7efa5cf..07a00333be 100644 --- a/packages/opencode/src/bun/index.ts +++ b/packages/opencode/src/bun/index.ts @@ -61,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 @@ -72,7 +72,7 @@ export namespace BunProc { // 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 this package while online.") + throw new Error(`Install ${pkg} while online.`) } // altimate_change end diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index c5f4952566..ace66beb5e 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -141,6 +141,9 @@ export const McpServeCommand = cmd({ .option("all-tools", { type: "boolean", default: false, describe: "Expose every tool on the allow-list, not just the default set" }), async handler(args) { await Offline.start(process.cwd()) + 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, diff --git a/packages/opencode/src/git/index.ts b/packages/opencode/src/git/index.ts index 663c0ed1c3..27ab4fe7db 100644 --- a/packages/opencode/src/git/index.ts +++ b/packages/opencode/src/git/index.ts @@ -1,5 +1,7 @@ // altimate_change start — restrict Git transport offline import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +import { gitCommandUsesNetwork, localGitEnv } from "@opencode-ai/core/git" +export { localGitEnv } // altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { AppProcess } from "@opencode-ai/core/process" @@ -20,26 +22,6 @@ const cfg = [ "core.quotepath=false", ] as const -// altimate_change start — prevent Git from starting a transport offline -const remoteCommands = new Set(["clone", "fetch", "pull", "push", "ls-remote", "send-pack", "fetch-pack", "submodule--helper"]) - -export function localGitEnv(env?: Record) { - return offlineModeEnabled() - ? { ...env, GIT_ALLOW_PROTOCOL: "", GIT_NO_LAZY_FETCH: "1", GIT_LFS_SKIP_SMUDGE: "1" } - : env -} - -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, operation, ...rest] = args.slice(index) - return remoteCommands.has(command) || - (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) -} -// altimate_change end - const out = (result: { text(): string }) => result.text().trim() const nuls = (text: string) => text.split("\0").filter(Boolean) const fail = (err: unknown) => diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 1090da6ded..4073cbd5e6 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -111,6 +111,12 @@ export class NotFoundError extends Schema.TaggedErrorClass()("MCP name: Schema.String, }) {} +export class OfflinePolicyError extends Schema.TaggedErrorClass()( + "MCP.OfflinePolicyError", + { message: Schema.String }, + { httpApiStatus: 400 }, +) {} + type MCPClient = Client function createClient(directory: string) { @@ -324,8 +330,8 @@ export interface Interface { readonly prompts: () => Effect.Effect> readonly resources: () => Effect.Effect> // altimate_change end - readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Record | Status }> - readonly connect: (name: string) => Effect.Effect + readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Record | Status }, OfflinePolicyError> + readonly connect: (name: string) => Effect.Effect readonly disconnect: (name: string) => Effect.Effect // altimate_change start — MCP.remove: full runtime teardown + ToolsChanged (merge dropped it) readonly remove: (name: string) => Effect.Effect @@ -1075,8 +1081,15 @@ export const layer = Layer.effect( // altimate_change end }) + // altimate_change start — report policy refusals as client errors + const enforceOfflinePolicy = (mcp: ConfigMCPV1.Info) => Effect.try({ + try: () => Offline.assertLocalMcp(mcp), + catch: (error) => new OfflinePolicyError({ message: error instanceof Error ? error.message : String(error) }), + }) + // altimate_change end + const add = Effect.fn("MCP.add")(function* (name: string, mcp: ConfigMCPV1.Info) { - Offline.assertLocalMcp(mcp) + yield* enforceOfflinePolicy(mcp) // altimate_change start — see claim const seq = ++lifecycleSeq // altimate_change end @@ -1102,7 +1115,7 @@ export const layer = Layer.effect( // altimate_change end const mcp = yield* requireMcpConfig(name) // altimate_change — reject before persisting enabled:true for an offline remote server - Offline.assertLocalMcp(mcp) + yield* enforceOfflinePolicy(mcp) // altimate_change start — see createAndStore yield* createAndStore(name, { ...mcp, enabled: true }, token) // altimate_change end diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts index 86ced98317..812a838d3d 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts @@ -64,7 +64,7 @@ export const McpApi = HttpApi.make("mcp") payload: AddPayload, success: described(StatusMap, "MCP server added successfully"), // altimate_change start — the workspace-managed refusal is a declared error - error: [HttpApiError.BadRequest, McpServerManagedError], + error: [HttpApiError.BadRequest, McpServerManagedError, MCP.OfflinePolicyError], // altimate_change end }).annotateMerge( OpenApi.annotations({ @@ -128,7 +128,7 @@ export const McpApi = HttpApi.make("mcp") query: WorkspaceRoutingQuery, success: described(Schema.Boolean, "MCP server connected successfully"), // altimate_change start — the workspace-managed key refuses connect/disconnect - error: [McpServerNotFoundError, McpServerManagedError], + error: [McpServerNotFoundError, McpServerManagedError, MCP.OfflinePolicyError], // altimate_change end }).annotateMerge( OpenApi.annotations({ diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index 27a4bdfef0..ef00c24836 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -1,6 +1,7 @@ // altimate_change start — offline mode import { Offline } from "@/config/offline" import { createHash } from "node:crypto" +import { SkillDiscovery } from "@opencode-ai/core/skill/discovery" // altimate_change end import { NodePath } from "@effect/platform-node" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -65,7 +66,7 @@ export namespace Discovery { const sourceCache = path.join(cache, ".sources", createHash("sha256").update(index).digest("hex")) const indexPath = path.join(sourceCache, "index.json") if (Offline.enabled()) { - const cached = yield* fs.readJson(indexPath).pipe(Effect.catch(() => Effect.succeed(undefined))) + const cached = yield* fs.readJson(indexPath).pipe(Effect.catch(() => Effect.void)) const directories = Array.isArray(cached) ? cached : [] const local = directories.filter((dir): dir is string => typeof dir === "string" && path.dirname(dir) === sourceCache, @@ -94,7 +95,8 @@ export namespace Discovery { if (!data) return [] const list = data.skills.filter((skill) => { - if (skill.name === "." || skill.name === ".." || !skill.name || /[\\/]/.test(skill.name)) return false + if (skill.name.includes("/") || !SkillDiscovery.isSafeRelativePath(skill.name)) return false + if (!skill.files.every(SkillDiscovery.isSafeRelativePath)) return false if (!skill.files.includes("SKILL.md")) { log.warn("skill entry missing SKILL.md", { url: index, skill: skill.name }) return false diff --git a/packages/opencode/src/util/git.ts b/packages/opencode/src/util/git.ts index 731131357f..7a17da92e8 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 — use the same transport controls as the Git services +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +import { gitCommandUsesNetwork, localGitEnv } from "@opencode-ai/core/git" +// altimate_change end export interface GitResult { exitCode: number @@ -14,9 +18,19 @@ export interface GitResult { * issues in embedded/client environments. */ export async function git(args: string[], opts: { cwd: string; env?: Record }): Promise { + // altimate_change start — reject remote commands and prevent implicit lazy fetching + if (offlineModeEnabled() && gitCommandUsesNetwork(args)) { + return { + exitCode: 1, + text: () => "", + stdout: Buffer.alloc(0), + stderr: Buffer.from("Git remote operations require an online run."), + } + } + // altimate_change end return Process.run(["git", ...args], { cwd: opts.cwd, - env: opts.env, + env: localGitEnv(opts.env), stdin: "ignore", nothrow: true, }) diff --git a/packages/opencode/test/altimate/debug/collect.test.ts b/packages/opencode/test/altimate/debug/collect.test.ts index 54d4a8c6de..1a27fd9f88 100644 --- a/packages/opencode/test/altimate/debug/collect.test.ts +++ b/packages/opencode/test/altimate/debug/collect.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from "bun:test" import fs from "fs" import os from "os" import path from "path" -import { configFiles, connectionFact, credentialFieldsFor, mcpFacts, pidAlive, probe } from "../../../src/altimate/debug/collect" +import { configFiles, connectionFact, credentialFieldsFor, mcpFacts, pidAlive, probe, telemetryFacts } from "../../../src/altimate/debug/collect" import { detectProblems } from "../../../src/altimate/debug/report" describe("connection facts", () => { @@ -191,3 +191,16 @@ describe("process liveness", () => { }) }) // altimate_change end + +test("offline telemetry reports the offline policy rather than --no-network", async () => { + const prior = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + for (const network of [true, false]) { + expect(await telemetryFacts(network)).toEqual({ enabled: false, checked: false, reason: "offline mode" }) + } + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } +}) diff --git a/packages/opencode/test/altimate/mcp-server/stdio.test.ts b/packages/opencode/test/altimate/mcp-server/stdio.test.ts index 9e1cf510b3..c1deba34b8 100644 --- a/packages/opencode/test/altimate/mcp-server/stdio.test.ts +++ b/packages/opencode/test/altimate/mcp-server/stdio.test.ts @@ -212,3 +212,30 @@ test("mcp serve skips CLI middleware before starting the agent heap service", as expect(starts).toBe(0) }) // altimate_change end + +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(Array.isArray(listed.tools)).toBe(true) + 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) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 30ca40d9e8..de9323e667 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -1,11 +1,24 @@ // altimate_change - new file -import { expect, test } from "bun:test" +import { afterEach, beforeEach, expect, mock, spyOn, 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 embedded databases and literal loopback", () => { for (const store of [":memory:", "/tmp/warehouse.db", "data.duckdb", "file:///tmp/local.db"]) for (const type of ["duckdb", "sqlite"]) @@ -19,6 +32,9 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "duckdb", path: "md:cloud" }, { type: "duckdb", path: "https://example.com/db" }, { type: "sqlite", path: "file://example.com/share/db" }, + { type: "sqlite", path: "file:////server/share/db.sqlite" }, + { type: "sqlite", path: "file://localhost//server/share/db.sqlite" }, + { type: "sqlite", path: "file:///%2Fserver/share/db.sqlite" }, { type: "sqlite", path: "\\\\example.com\\share\\db" }, { type: "postgres", host: "localhost.evil.test" }, { type: "postgres", host: "127.0.0.1", ssh_host: "remote" }, @@ -46,3 +62,97 @@ test("dbt checks selected target and CLI overrides", async () => { 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.toBeUndefined() + } finally { await fs.rm(root, { recursive: true, force: true }) } +}) + +test("dbt policy failure surfaces on repeated SQL calls without a registry fallback", async () => { + const Registry = await import("../../../src/altimate/native/connections/registry") + const adapter = await import("../../../src/altimate/native/connections/register") + const Dispatcher = await import("../../../src/altimate/native/dispatcher") + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-fallback-")) + const get = spyOn(Registry, "get") + try { + process.env.ALTIMATE_OFFLINE = "1" + 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: postgres\n host: example.com\n") + adapter.resetDbtAdapter() + adapter.dbtAdapterInternals.readConfig = async () => ({ projectRoot: root }) + adapter.registerAll() + Registry.setConfigs({ fallback: { type: "sqlite", path: ":memory:" } }) + for (let i = 0; i < 2; i++) { + const result = await Dispatcher.call("sql.execute", { sql: "SELECT 1" }) + expect((result as { error?: string }).error).toContain("Offline mode") + } + expect(get).not.toHaveBeenCalled() + } finally { + get.mockRestore() + delete adapter.dbtAdapterInternals.readConfig + adapter.resetDbtAdapter() + Registry.reset() + Dispatcher.reset() + await fs.rm(root, { recursive: true, force: true }) + } +}) + +test("cached local connections never reread credentials offline", async () => { + const Registry = await import("../../../src/altimate/native/connections/registry") + const Credentials = await import("../../../src/altimate/native/connections/credential-store") + const read = mock(async () => null) + try { + Credentials.setSecretBackendForTests({ name: "test", get: read, set: async () => {}, delete: async () => true }) + Registry.setConfigs({ local: { type: "sqlite", path: ":memory:" } }) + const connector = await Registry.get("local") + expect(read).toHaveBeenCalled() + read.mockClear() + process.env.ALTIMATE_OFFLINE = "1" + expect(await Registry.get("local")).toBe(connector) + expect(await Registry.get("local")).toBe(connector) + expect((await connector.execute("SELECT 1")).rows).toEqual([[1]]) + expect(read).not.toHaveBeenCalled() + } finally { + await Registry.closeAll() + Registry.reset() + Credentials.setSecretBackendForTests(undefined) + } +}) + +test("cached remote target survives lost keychain credentials and closes on rejection", async () => { + const Registry = await import("../../../src/altimate/native/connections/registry") + const Credentials = await import("../../../src/altimate/native/connections/credential-store") + const driver = await import("@altimateai/drivers/postgres") + const close = mock(async () => {}) + const connector = { connect: async () => {}, close } + const connect = spyOn(driver, "connect").mockResolvedValue(connector as any) + const read = mock(async (account: string) => account.endsWith("/connection_string") ? "postgres://remote.example/db" : null) + try { + Credentials.setSecretBackendForTests({ name: "test", get: read, set: async () => {}, delete: async () => true }) + Registry.setConfigs({ remote: { type: "postgres", host: "localhost" } }) + expect(await Registry.get("remote")).toBe(connector) + expect(connect.mock.calls[0][0].connection_string).toBe("postgres://remote.example/db") + read.mockClear() + read.mockImplementation(async () => { throw new Error("keychain locked") }) + process.env.ALTIMATE_OFFLINE = "1" + await expect(Registry.get("remote")).rejects.toThrow("Offline mode") + expect(read).not.toHaveBeenCalled() + expect(close).toHaveBeenCalledTimes(1) + await Registry.closeAll() + expect(close).toHaveBeenCalledTimes(1) + } finally { + connect.mockRestore() + await Registry.closeAll() + Registry.reset() + Credentials.setSecretBackendForTests(undefined) + } +}) diff --git a/packages/opencode/test/altimate/registry-per-project.test.ts b/packages/opencode/test/altimate/registry-per-project.test.ts index f192d63a71..60aa1955b9 100644 --- a/packages/opencode/test/altimate/registry-per-project.test.ts +++ b/packages/opencode/test/altimate/registry-per-project.test.ts @@ -240,6 +240,25 @@ describe("connectors are per project", () => { expect(b2).not.toBe(a) }) + test("offline rejection closes a cached connector and its SSH tunnel", async () => { + const offline = process.env.ALTIMATE_OFFLINE + delete process.env.ALTIMATE_OFFLINE + try { + writeLocal(projectA, { store: sshStore("offline-bastion") }) + const connector = await inProject(projectA, () => Registry.get("store")) + const close = spyOn(connector, "close") + process.env.ALTIMATE_OFFLINE = "1" + await expect(inProject(projectA, () => Registry.get("store"))).rejects.toThrow("Offline mode") + expect(close).toHaveBeenCalledTimes(1) + expect(ended("offline-bastion")).toEqual([true]) + expect(openTunnelCount()).toBe(0) + close.mockRestore() + } finally { + if (offline === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = offline + } + }) + test("same-named SSH tunnels are per project; removing in B leaves A's open", async () => { const tunnelled = (sshHost: string) => ({ store: { type: "sqlite", path: "store.sqlite", create: true, ssh_host: sshHost, host: "db", port: 5432 }, diff --git a/packages/opencode/test/altimate/workspace/skill-sync.test.ts b/packages/opencode/test/altimate/workspace/skill-sync.test.ts index 5e578a6ea6..2bf906a082 100644 --- a/packages/opencode/test/altimate/workspace/skill-sync.test.ts +++ b/packages/opencode/test/altimate/workspace/skill-sync.test.ts @@ -1350,6 +1350,12 @@ describe("workspace skill sync", () => { bindTo(2) expect(await registryStale(project)).toBe(true) expect(await snapshotWorkspaceId(project)).toBeNull() + bindTo(1) + await markRegistryApplied(project) + expect(await snapshotWorkspaceId(project)).toBe(1) + writeFileSync(cachePath(), "{") + expect(await registryStale(project)).toBe(true) + expect(await snapshotWorkspaceId(project)).toBeNull() expect(existsSync(skillFile("pub-1", "SKILL.md"))).toBe(true) } finally { if (previous === undefined) delete process.env.ALTIMATE_OFFLINE diff --git a/packages/opencode/test/bun.test.ts b/packages/opencode/test/bun.test.ts index d607ae4782..af34897f55 100644 --- a/packages/opencode/test/bun.test.ts +++ b/packages/opencode/test/bun.test.ts @@ -51,3 +51,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 + const cache = await fs.mkdtemp(path.join(originalCache, "offline-test-")) + 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 + await fs.rm(cache, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/opencode/test/config/paths-parsetext.test.ts b/packages/opencode/test/config/paths-parsetext.test.ts index c9e1b52ef5..5b3779e1b7 100644 --- a/packages/opencode/test/config/paths-parsetext.test.ts +++ b/packages/opencode/test/config/paths-parsetext.test.ts @@ -311,6 +311,14 @@ describe("ConfigPaths.parseText: ${VAR} substitution (shell/dotenv alias)", () = }) describe("ConfigPaths.parseText: {file:path} substitution", () => { + test("expandFiles=false preserves existing and missing file tokens", async () => { + await using tmp = await tmpdir() + await fs.writeFile(path.join(tmp.path, "secret.txt"), "do-not-expand") + const text = '{"existing":"{file:secret.txt}","missing":"{file:missing.txt}"}' + expect(await ConfigPaths.parseText(text, path.join(tmp.path, "config.json"), "error", { expandFiles: false })) + .toEqual({ existing: "{file:secret.txt}", missing: "{file:missing.txt}" }) + }) + test("substitutes {file:path} with file contents (trimmed)", async () => { await using tmp = await tmpdir() const secretPath = path.join(tmp.path, "secret.txt") 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/server/httpapi-mcp.test.ts b/packages/opencode/test/server/httpapi-mcp.test.ts index cb873fffb9..8e510c7dcb 100644 --- a/packages/opencode/test/server/httpapi-mcp.test.ts +++ b/packages/opencode/test/server/httpapi-mcp.test.ts @@ -21,6 +21,38 @@ const readResponse = Effect.fnUntraced(function* (input: { path: string; directo }) describe("mcp HttpApi", () => { + it.instance("returns a client error when adding or connecting a remote MCP server offline", () => + Effect.gen(function* () { + const tmp = yield* TestInstance + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const response = yield* request(McpPaths.status, tmp.directory, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ name: "remote", config: { type: "remote", url: "https://example.com/mcp" } }), + }) + expect(response.status).toBe(400) + expect(yield* json(response)).toMatchObject({ + _tag: "MCP.OfflinePolicyError", + message: expect.stringContaining("Offline mode"), + }) + const connect = yield* request("/mcp/configured-remote/connect", tmp.directory, { method: "POST" }) + expect(connect.status).toBe(400) + expect(yield* json(connect)).toMatchObject({ _tag: "MCP.OfflinePolicyError" }) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), + { + config: { + experimental: { auto_mcp_discovery: false }, + mcp: { "configured-remote": { type: "remote", url: "https://example.com/mcp", enabled: false } }, + }, + }, + ) + it.instance( "serves status endpoint", () => @@ -33,6 +65,7 @@ describe("mcp HttpApi", () => { }), { config: { + experimental: { auto_mcp_discovery: false }, mcp: { demo: { type: "local", diff --git a/packages/opencode/test/share/share-next.test.ts b/packages/opencode/test/share/share-next.test.ts index 94be5b9089..88f553400b 100644 --- a/packages/opencode/test/share/share-next.test.ts +++ b/packages/opencode/test/share/share-next.test.ts @@ -112,6 +112,21 @@ beforeEach(async () => { }) describe("ShareNext", () => { + test("offline share creation fails without making a fetch call", async () => { + const prior = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + installFetchMock(() => new Response(null, { status: 200 })) + try { + await expect(ShareNext.create(SessionID.make("ses_offline_share"))).rejects.toThrow( + "Sharing sessions requires an online run.", + ) + expect(fetchRecords).toEqual([]) + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior + } + }) + test("offline share revocation fails so unshare retains the local share state", async () => { const prior = process.env.ALTIMATE_OFFLINE process.env.ALTIMATE_OFFLINE = "1" diff --git a/packages/opencode/test/storage/storage.test.ts b/packages/opencode/test/storage/storage.test.ts index d4a278458c..80d0294494 100644 --- a/packages/opencode/test/storage/storage.test.ts +++ b/packages/opencode/test/storage/storage.test.ts @@ -233,6 +233,48 @@ describe("Storage", () => { }), ) + it.live("migration 1 tolerates malformed legacy records", () => + Effect.gen(function* () { + const fs = yield* FSUtil.Service + const tmp = yield* tmpdirScoped({ git: true }) + const storage = path.join(tmp, "storage") + const legacy = path.join(tmp, "project", "legacy") + + yield* fs.writeWithDirs(path.join(legacy, "storage", "session", "message", "probe", "0.json"), "[]") + yield* fs.writeWithDirs( + path.join(legacy, "storage", "session", "message", "probe", "1.json"), + JSON.stringify({ path: { root: tmp } }), + ) + yield* fs.writeWithDirs( + path.join(legacy, "storage", "session", "info", "ses_legacy.json"), + JSON.stringify({ id: "ses_legacy", title: "legacy" }), + ) + yield* fs.writeWithDirs( + path.join(legacy, "storage", "session", "message", "ses_legacy", "msg_legacy.json"), + JSON.stringify({ role: "user", text: "hello" }), + ) + + yield* Effect.gen(function* () { + const svc = yield* Storage.Service + const projects = yield* svc.list(["project"]) + expect(projects).toHaveLength(1) + const project = projects[0]![1] + + expect(yield* svc.list(["session", project])).toEqual([["session", project, "ses_legacy"]]) + expect(yield* svc.read<{ id: string; title: string }>(["session", project, "ses_legacy"])).toEqual({ + id: "ses_legacy", + title: "legacy", + }) + expect(yield* svc.read<{ role: string; text: string }>(["message", "ses_legacy", "msg_legacy"])).toEqual({ + role: "user", + text: "hello", + }) + }).pipe(Effect.provide(remappedStorage(tmp))) + + expect(yield* fs.readFileString(path.join(storage, "migration"))).toBe("2") + }), + ) + it.live("migration 1 migrates local projects even when offline", () => Effect.gen(function* () { const fs = yield* FSUtil.Service From 4e6a6c83c5cf5df3dd6568d68c1af32b2b01c798 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 02:56:08 -0800 Subject: [PATCH 23/72] fix: limit offline mode to network egress Run local tools offline: skill tool checks, loopback attach, workspace-serve, ACP and TUI listeners, dbt init. Keep cached Git LFS content, user proxy settings for shell, LSP and stdio MCP, and dbt profile resolution consistent with dbt. Close Trino and ClickHouse protocol and Oracle host gaps, honor legacy TOML and serve pins, and rewrite the offline docs. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 49 ++++++++++--- docs/mcp-workspaces.md | 2 +- packages/core/src/git.ts | 20 ++++-- packages/core/test/git.test.ts | 46 ++++++++++++- packages/dbt-tools/src/adapter.ts | 5 +- packages/dbt-tools/src/index.ts | 4 +- .../altimate/native/connections/offline.ts | 18 ++--- .../altimate/native/connections/register.ts | 3 +- .../src/altimate/native/dbt/offline.ts | 47 ++++++++++--- .../src/altimate/native/dbt/runner.ts | 16 +++-- .../src/altimate/workspace/skill-sync.ts | 3 + packages/opencode/src/cli/cmd/acp.ts | 19 +---- packages/opencode/src/cli/cmd/skill.ts | 6 -- packages/opencode/src/cli/cmd/tui.ts | 10 +-- packages/opencode/src/cli/tui/worker.ts | 4 +- packages/opencode/src/config/offline.ts | 48 +++++++++++-- packages/opencode/src/file/index.ts | 2 - packages/opencode/src/index.ts | 8 ++- packages/opencode/src/lsp/launch.ts | 6 ++ packages/opencode/src/mcp/index.ts | 8 ++- .../src/plugin/tui/altimate/skill-ops.tsx | 6 +- packages/opencode/src/provider/provider.ts | 11 ++- packages/opencode/src/session/prompt.ts | 5 ++ packages/opencode/src/skill/discovery.ts | 6 +- packages/opencode/src/tool/bash.ts | 6 ++ .../native/offline-connections.test.ts | 61 ++++++++++++++-- .../altimate/workspace/skill-sync.test.ts | 29 ++++++++ .../opencode/test/cli/run/offline.test.ts | 69 ++++++++++++++++--- .../test/config/offline-startup.test.ts | 28 ++++++++ packages/opencode/test/mcp/offline.test.ts | 34 +++++++++ .../opencode/test/provider/provider.test.ts | 43 ++++++++++++ .../opencode/test/skill/discovery.test.ts | 36 ++++++++++ 32 files changed, 551 insertions(+), 107 deletions(-) create mode 100644 packages/opencode/test/config/offline-startup.test.ts diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index afdeb2ca92..9825b1ef4f 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -160,15 +160,48 @@ 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 mode +## Offline / air-gapped mode -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a local global or project configuration file. The setting applies to the process and its workers. Start a separate process in the project to opt in when using a shared server. +Offline mode is for running Altimate Code against a local or self-hosted model with no other network access. It stops the network requests Altimate Code itself makes. It does not stop local work: tools, shell commands, local databases and local Git keep working. -Configure an explicit HTTP(S) provider `options.baseURL` and select its `provider/model` ID. Define the model in the provider configuration if it is absent from the bundled or cached catalog. For an OpenAI-compatible endpoint, use the bundled `@ai-sdk/openai-compatible` provider. +### Turn it on -- SQL tools can query local DuckDB and SQLite files or a warehouse listening on loopback. Use a local dbt profile for dbt commands. -- Bash, installed language servers, and MCP servers using stdio or a loopback HTTP(S) URL remain available. Altimate Code skips automatic language server and warehouse driver installs. Install optional drivers and ripgrep ahead of time. -- Git diffs, session snapshots and revert, and worktree creation, removal and reset operate locally. Reset uses the cached base and any locally available submodule commits. Git LFS files may appear as pointers until hydrated online. Run Git remote operations online. -- Altimate Code skips telemetry, account and remote configuration requests, model catalog downloads, update checks, workspace and engine sync, session sharing, and web search and fetch. Remote warehouse and MCP connections require an online run. Run `altimate-code workspace refresh` before going offline to save a snapshot. Keep local credentials for the same workspace account to use that snapshot. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file. The setting covers the process and its workers. A project that requests offline mode is refused by a shared server started without it; start Altimate Code from that project instead. -The configured model endpoint is the only external endpoint Altimate Code contacts in offline mode. Shell commands and other programs you configure or invoke retain their own network access. +Configure a provider with an explicit HTTP(S) `options.baseURL` and select 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. Requests to that endpoint are the only requests Altimate Code sends off the machine. A `small_model` is used only if it belongs to the same provider; otherwise the main model handles those tasks. + +### Before going offline + +While still online: + +- Run `altimate-code workspace refresh` to save the workspace skill snapshot. Offline runs use it without refreshing or deleting it, as long as your local credentials belong to the same workspace account. +- Install the warehouse drivers you need (the `warehouse_install_driver` tool), any language servers, and ripgrep. +- Run `dbt deps` for dbt projects. + +### What keeps working + +- Local warehouses: DuckDB and SQLite files, and warehouses whose host is `localhost`, `::1` or `127.x.x.x`. The SQL and schema tools run against them. +- dbt commands, when the selected profile and target point at a local database. +- The shell tool, installed language servers, and MCP servers that use stdio or a loopback HTTP(S) URL. +- Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and submodule commits. Git LFS files check out from the local LFS cache; a file whose content is not cached fails with a clear error instead of downloading. +- `attach` and `run --attach` to a server on this machine. + +### 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; +- session sharing; +- the web fetch, web search, code search, workspace manager, feedback and memory refresh tools; +- MCP servers at non-loopback URLs, and MCP sign-in; +- automatic installs of warehouse drivers, language servers, plugins and ripgrep; +- warehouse connections whose host is not loopback, SSH tunnels, and cloud sign-in methods; +- `dbt deps`, and dbt's own usage reporting and version check; +- Git fetch, pull, push, clone and other remote operations; +- commands that need a remote service, such as `github`, `pr`, `web` and `attach` to another machine. + +### What offline mode does not police + +Programs you run or configure yourself keep their own network access: shell commands, language servers, local MCP servers and their child processes. They also keep your proxy settings. Offline mode does not sandbox them. diff --git a/docs/mcp-workspaces.md b/docs/mcp-workspaces.md index 741c4d6a54..43253b2168 100644 --- a/docs/mcp-workspaces.md +++ b/docs/mcp-workspaces.md @@ -20,7 +20,7 @@ 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-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. +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 diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 9b18c4d8a2..e7e13f7156 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -13,10 +13,22 @@ import { offlineModeEnabled } from "./flag/flag" // altimate_change start — prevent Git from starting a transport offline const remoteCommands = new Set(["clone", "fetch", "pull", "push", "ls-remote", "send-pack", "fetch-pack", "submodule--helper"]) +// Git LFS reads cached objects locally and contacts its endpoint only for missing ones. +// Pointing that endpoint at a closed loopback port keeps cached content and fails on the rest. +const OFFLINE_LFS_URL = "http://127.0.0.1:9/" + export function localGitEnv(env?: Record) { - return offlineModeEnabled() - ? { ...env, GIT_ALLOW_PROTOCOL: "", GIT_NO_LAZY_FETCH: "1", GIT_LFS_SKIP_SMUDGE: "1" } - : env + if (!offlineModeEnabled()) return env + const inherited = Number(env?.GIT_CONFIG_COUNT ?? process.env.GIT_CONFIG_COUNT ?? 0) + const index = Number.isInteger(inherited) && inherited > 0 ? inherited : 0 + return { + ...env, + GIT_ALLOW_PROTOCOL: "", + GIT_NO_LAZY_FETCH: "1", + GIT_CONFIG_COUNT: String(index + 1), + [`GIT_CONFIG_KEY_${index}`]: "lfs.url", + [`GIT_CONFIG_VALUE_${index}`]: OFFLINE_LFS_URL, + } } export function gitCommandUsesNetwork(args: string[]) { @@ -453,7 +465,7 @@ function execute(cwd: string, proc: AppProcess.Interface) { ChildProcess.make("git", args, { cwd, env: localGitEnv(), - extendEnv: true, + extendEnv: true, stdin: "ignore", }), ) diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index e9498bcff6..dd6b7535a2 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -1,9 +1,10 @@ import { describe, expect } from "bun:test" import { $ } from "bun" import fs from "fs/promises" +import os from "os" import path from "path" import { Effect } from "effect" -import { Git } from "@opencode-ai/core/git" +import { Git, localGitEnv } from "@opencode-ai/core/git" import { AbsolutePath } from "@opencode-ai/core/schema" import { branch, commit, gitRemote } from "./fixture/git" import { tmpdir } from "./fixture/tmpdir" @@ -51,6 +52,49 @@ describe("Git", () => { ), ) + // Offline Git must not download LFS objects, but objects already in the local cache still check out. + const hasLfs = Bun.spawnSync(["git", "lfs", "version"], { stdout: "ignore", stderr: "ignore" }).exitCode === 0 + const liveIfLfs = hasLfs ? it.live : it.live.skip + liveIfLfs("offline checkout keeps cached LFS content and refuses uncached objects", () => + Effect.gen(function* () { + const tmp = yield* Effect.acquireRelease( + Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "offline-lfs-"))), + (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), + ) + const gitIn = (args: string[], env?: Record) => + Bun.spawnSync(["git", ...args], { cwd: tmp, env: { ...process.env, ...env }, stderr: "pipe", stdout: "pipe" }) + for (const args of [ + ["init", "-q"], + ["config", "user.email", "t@example.com"], + ["config", "user.name", "t"], + ["lfs", "install", "--local"], + ["lfs", "track", "*.bin"], + ["remote", "add", "origin", "https://example.invalid/repo.git"], + ]) expect(gitIn(args).exitCode).toBe(0) + yield* Effect.promise(() => fs.writeFile(path.join(tmp, "a.bin"), "cached-content")) + expect(gitIn(["add", ".gitattributes", "a.bin"]).exitCode).toBe(0) + expect(gitIn(["commit", "-qm", "lfs"]).exitCode).toBe(0) + + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const env = localGitEnv()! + yield* Effect.promise(() => fs.rm(path.join(tmp, "a.bin"))) + expect(gitIn(["checkout", "--", "a.bin"], env).exitCode).toBe(0) + expect(yield* Effect.promise(() => fs.readFile(path.join(tmp, "a.bin"), "utf8"))).toBe("cached-content") + + yield* Effect.promise(() => fs.rm(path.join(tmp, "a.bin"))) + yield* Effect.promise(() => fs.rm(path.join(tmp, ".git", "lfs", "objects"), { recursive: true, force: true })) + const missing = gitIn(["checkout", "--", "a.bin"], env) + expect(missing.exitCode).not.toBe(0) + expect(missing.stderr.toString()).toContain("127.0.0.1:9") + } 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/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index ce49111062..73aabf281f 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -98,7 +98,10 @@ export type CreateOptions = { function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { const vars = { ...process.env } - if (options.offline) vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" + if (options.offline) { + vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" + vars.DBT_VERSION_CHECK = "false" + } if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath return { pythonPath: cfg.pythonPath, diff --git a/packages/dbt-tools/src/index.ts b/packages/dbt-tools/src/index.ts index 93875fbab3..605d3704e8 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"].includes(process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() ?? "") + adapter = await create(cfg, { offline }) } catch (err) { return failure(err) } diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 32fd9f6ff7..04e2362d46 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -1,13 +1,6 @@ // altimate_change - new file -import { isIP } from "node:net" import { isLocalFilePath, normalizeConfig, type ConnectionConfig } from "@altimateai/drivers" - -/** 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 === "localhost." || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")) -} +import { isLoopbackHost } from "@/config/offline" function localStore(value: unknown): boolean { if (typeof value !== "string" || value.includes("{{")) return false @@ -39,10 +32,17 @@ export function assertLocalConnection(raw: ConnectionConfig): void { const mongo = type === "mongodb" || type === "mongo" if (mongo && config.direct_connection !== undefined && config.direct_connection !== true) deny() if (config.host !== undefined && !isLoopbackHost(config.host)) deny() + // Trino and ClickHouse build `${protocol}://${host}` URLs, so a protocol value can carry its own authority. + if ((type === "trino" || type === "clickhouse") && config.protocol !== undefined && + !["http", "https"].includes(String(config.protocol).trim().toLowerCase())) deny() const connectionString = type === "trino" ? config.connection_string ?? config.server ?? config.url : config.connection_string - if (connectionString) { + if (type === "oracle" && typeof connectionString === "string" && !connectionString.includes("://")) { + // Easy Connect: host[:port][/service]. Descriptors and TNS aliases name hosts this check cannot see. + const easy = /^(?:\/\/)?(\[[^\]]+\]|[^:/\s()]+)(?::\d+)?(?:\/[^\s()]*)?$/.exec(connectionString.trim()) + if (!easy || !isLoopbackHost(easy[1])) deny() + } else if (connectionString) { try { const url = new URL(String(connectionString)) if ((type === "trino" || type === "clickhouse") && !["http:", "https:"].includes(url.protocol)) deny() diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 7242091340..c6785d6c56 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -128,7 +128,8 @@ async function ensureDbtAdapter(): Promise { return publish(null) } - if (Offline.enabled()) await assertLocalDbt(dbtConfig.projectRoot, [], dbtConfig.dbtIntegration) + // The integration reads profiles.yml relative to the project, so check from there. + if (Offline.enabled()) await assertLocalDbt(dbtConfig.projectRoot, [], dbtConfig.dbtIntegration, dbtConfig.projectRoot) // 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 diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index 70b0e89b43..555948f33e 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -19,16 +19,41 @@ export class OfflineDbtError extends Error { override name = "OfflineDbtError" } -/** Resolve exactly the selected profile/target before starting dbt-owned network work. */ -export async function assertLocalDbt(projectRoot: string, args: string[] = [], integration = "core"): Promise { +/** 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 + } +} + +/** + * Resolve exactly the selected profile/target before starting dbt-owned network work. + * `cwd` is the directory dbt will run in: dbt reads `profiles.yml` from there, not from the project. + * Returns the profiles directory that was checked, so the caller can pin dbt to that same file. + */ +export async function assertLocalDbt( + projectRoot: string, + args: string[] = [], + integration = "core", + cwd = process.cwd(), +): Promise<{ profilesDir: string }> { try { - await checkLocalDbt(projectRoot, args, integration) + return await checkLocalDbt(projectRoot, args, integration, cwd) } catch (error) { throw new OfflineDbtError(error instanceof Error ? error.message : String(error), { cause: error }) } } -async function checkLocalDbt(projectRoot: string, args: string[], integration: string): Promise { +async function checkLocalDbt( + projectRoot: string, + args: string[], + integration: string, + cwd: string, +): Promise<{ profilesDir: string }> { if (!["core", "corecommand", "fusion"].includes(integration)) throw new Error("Offline mode disables cloud dbt integrations.") const option = (...names: string[]) => { let result: string | undefined @@ -46,13 +71,16 @@ async function checkLocalDbt(projectRoot: string, args: string[], integration: s } return result } - const root = option("--project-dir") ?? process.env.DBT_PROJECT_DIR ?? projectRoot + const root = option("--project-dir") ?? process.env.DBT_PROJECT_DIR ?? (await findProjectRoot(projectRoot)) const project = resolve(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("--profiles-dir") ?? process.env.DBT_PROFILES_DIR - const local = path.join(root, "profiles.yml") - const profilesPath = explicit ? path.join(explicit, "profiles.yml") - : await fs.stat(local).then(() => local, () => path.join(os.homedir(), ".dbt", "profiles.yml")) - const profiles = resolve(parse(await fs.readFile(profilesPath, "utf8"))) + const profilesDir = path.resolve( + cwd, + explicit ?? + (await fs.stat(path.join(cwd, "profiles.yml")).then(() => cwd, () => path.join(os.homedir(), ".dbt"))), + ) + const profiles = resolve(parse(await fs.readFile(path.join(profilesDir, "profiles.yml"), "utf8"))) const profileName = option("--profile") ?? process.env.DBT_PROFILE ?? project.profile const profile = profiles?.[profileName] const target = option("--target", "-t") ?? process.env.DBT_TARGET ?? profile?.target ?? "default" @@ -72,4 +100,5 @@ async function checkLocalDbt(projectRoot: string, args: string[], integration: s // These profile hooks cause dbt-duckdb to install extensions or open extra connections at startup. if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length) throw new Error("Offline mode requires a dbt profile without extension installs, attachments, plugins, or remote secrets.") + return { profilesDir } } diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index 2a19b972c9..55045ef118 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -29,13 +29,22 @@ function ensureUpstreamSelector(select: string, command: string): string { * Run a dbt CLI command via subprocess. */ 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 { - if (["deps", "init"].includes(params.command || "run")) throw new Error("Offline mode disables dbt dependency installation and initialization.") - await assertLocalDbt(params.project_dir || process.cwd(), [ + if ((params.command || "run") === "deps") throw new Error("Offline mode disables dbt dependency installation.") + const { profilesDir } = await assertLocalDbt(params.project_dir || process.cwd(), [ ...(params.args ?? []), ...(params.project_dir ? ["--project-dir", params.project_dir] : []), ]) + offlineEnv = { + ...process.env, + DBT_PROFILES_DIR: profilesDir, + DBT_SEND_ANONYMOUS_USAGE_STATS: "false", + DBT_VERSION_CHECK: "false", + } } catch (error) { return { stdout: "", stderr: String(error), exit_code: 1 } } @@ -57,8 +66,7 @@ export async function runDbt(params: DbtRunParams): Promise { args.push("--project-dir", params.project_dir) } - const env = Offline.enabled() ? { ...process.env, DBT_SEND_ANONYMOUS_USAGE_STATS: "false" } : process.env - execFile("dbt", args, { timeout: 300_000, env }, (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/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index a63a43d23c..fb899ddebd 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -194,6 +194,9 @@ export async function ownManifest(directory: string): Promise { if (!ours) return null // altimate_change — hide a stale workspace snapshot offline without removing it if (Offline.enabled()) { + // A serve pin outranks the project's link, as in resolveBindingOutcome; a broken pin fails closed. + const pin = readPin() + if (pin.kind === "invalid" || (pin.kind === "valid" && pin.datamateId !== manifest.datamateId)) return null const { binding: local } = await readLocalBindingScopedStrict(directory) if (local && local.datamateId !== manifest.datamateId) return null } diff --git a/packages/opencode/src/cli/cmd/acp.ts b/packages/opencode/src/cli/cmd/acp.ts index 090f0f4566..1a728f4483 100644 --- a/packages/opencode/src/cli/cmd/acp.ts +++ b/packages/opencode/src/cli/cmd/acp.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy -import { Offline } from "@/config/offline" -// altimate_change end import { Effect } from "effect" import { effectCmd } from "../effect-cmd" import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk" @@ -36,25 +33,15 @@ export const AcpCommand = effectCmd({ yield* Effect.promise(() => FreeTierConsent.printDisclosureOnceForHeadless(autoRegisterResult.status === "registered")) // altimate_change end const opts = yield* resolveNetworkOptions(args) - // altimate_change start — skip the HTTP listener when ACP uses in-process transport - const server = Offline.enabled() ? undefined : yield* Effect.promise(() => + // altimate_change start — upstream_fix: preserve async server listen inside ACP profiler measure + const server = yield* Effect.promise(() => ACPProfile.measure("cli.acp.server.listen", async () => Server.listen(opts)), ) // altimate_change end const sdk = createOpencodeClient({ - // altimate_change — the offline SDK dispatches against an in-process URL - baseUrl: server ? `http://${server.hostname}:${server.port}` : "http://opencode.internal", + baseUrl: `http://${server.hostname}:${server.port}`, headers: ServerAuth.headers(), - // altimate_change start — route the offline ACP client to the in-process API - fetch: Offline.enabled() - ? Object.assign( - async (input: Parameters[0], init?: Parameters[1]) => - Server.Default().fetch(new Request(input, init)), - { preconnect: () => {} }, - ) - : undefined, - // altimate_change end }) const input = new WritableStream({ diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index fbf56135e9..06c93ab071 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -413,12 +413,6 @@ const SkillTestCommand = cmd({ const tools = detectToolReferences(skill.content) if (tools.length === 0) { warn(`No CLI tool references detected in skill content`) - } else if (Offline.enabled()) { - for (const tool of tools) { - if (await isToolOnPath(tool, projectDir)) pass(`"${tool}" found on PATH`) - else fail(`"${tool}" not found on PATH`) - } - warn("Paired tool --help checks require online mode.") } else { process.stdout.write(EOL + ` Paired tools:` + EOL) for (const tool of tools) { diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 1ae9e9c17f..05cdde12ce 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy -import { Offline } from "@/config/offline" -// altimate_change end import { cmd } from "@/cli/cmd/cmd" import { Rpc } from "@/util/rpc" import { type rpc } from "../tui/worker" @@ -249,12 +246,9 @@ export const TuiThreadCommand = cmd({ network.port !== 0 || network.hostname !== "127.0.0.1" - // altimate_change start — offline requests stay in the worker - const listener = external && !Offline.enabled() ? await client.call("server", network) : undefined - // altimate_change end - const transport = listener + const transport = external ? { - url: listener.url, + url: (await client.call("server", network)).url, fetch: undefined, events: undefined, } diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 6269a67454..0115230070 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -73,9 +73,7 @@ Heap.start() // InstanceRuntime.load/Config.get() would otherwise race it (transiently truncated // read) or cache the pre-heal entry, making the first session spawn the broken // config anyway. Errors are swallowed: a failed sync must never block the TUI. -const datamateSyncReady: Promise = Offline.enabled() - ? Promise.resolve() - : syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) +const datamateSyncReady: Promise = syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) // altimate_change end const traceConsumer = new TraceConsumer() diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 528e08d3a1..237eea10f2 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -1,4 +1,5 @@ import fs from "node:fs/promises" +import { isIP } from "node:net" import path from "node:path" import { parse } from "jsonc-parser" import * as Effect from "effect/Effect" @@ -49,6 +50,13 @@ async function localOptIn(directory: string) { for (const file of files) { if (file && (await optedIn(await fs.readFile(file, "utf8").catch(() => undefined), file))) return true } + // The legacy global TOML file is converted to config.json only after startup, so read it here too. + const legacy = await fs.readFile(path.join(Global.Path.config, "config"), "utf8").catch(() => undefined) + if (legacy !== undefined) { + try { + if ((Bun.TOML.parse(legacy) as { offline?: unknown }).offline === true) return true + } catch {} + } const managed = await ConfigManaged.readManagedPreferences().catch(() => undefined) return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false } @@ -63,13 +71,40 @@ export async function assertStartupPolicy(directory: string) { let networkFetch: typeof fetch | undefined +const USER_PROXY = "ALTIMATE_OFFLINE_USER_PROXY" + +/** + * Environment for programs the user runs or configures (shell commands, language servers, + * stdio MCP servers). Offline mode does not police their network access, so they get the + * user's original proxy exclusions back instead of the process-wide bypass. + */ +export function userEnv>(env: T): T { + const saved = env[USER_PROXY] ?? process.env[USER_PROXY] + if (saved === undefined) return env + delete env[USER_PROXY] + try { + const original = JSON.parse(saved) as Record + for (const key of ["NO_PROXY", "no_proxy"] as const) { + // Only the inherited bypass is replaced; a value the program's own config set stays. + if (env[key] !== process.env[key]) continue + const value = original[key] + if (typeof value === "string") (env as Record)[key] = value + else delete env[key] + } + } catch {} + return env +} + export async function start(directory: string, model?: string) { if (!enabled() && !(await localOptIn(directory))) return // Workers and core services must see the same policy before constructing // their layers. Once enabled, keep it for the lifetime of the process. process.env.ALTIMATE_OFFLINE = "1" // Bun consults proxy environment variables even when fetch sets proxy: "". - // Offline traffic must go directly to the one configured endpoint. + // Offline traffic must go directly to the one configured endpoint. The user's own + // values are kept (and inherited by workers) so their programs get them back: see userEnv. + if (process.env[USER_PROXY] === undefined) + process.env[USER_PROXY] = JSON.stringify({ NO_PROXY: process.env.NO_PROXY, no_proxy: process.env.no_proxy }) process.env.NO_PROXY = "*" process.env.no_proxy = "*" if (model) process.env.ALTIMATE_OFFLINE_MODEL = model @@ -134,13 +169,18 @@ export function modelFetch(baseURL: string | undefined): typeof fetch { ) } +/** 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 === "localhost." || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")) +} + // Validate the URL before any offline loopback HTTP request. export function isLocalURL(value: string | URL) { try { const url = new URL(value) - if (!["http:", "https:"].includes(url.protocol)) return false - const host = url.hostname.toLowerCase() - return host === "localhost" || host === "localhost." || host === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(host) + return ["http:", "https:"].includes(url.protocol) && isLoopbackHost(url.hostname) } catch { return false } diff --git a/packages/opencode/src/file/index.ts b/packages/opencode/src/file/index.ts index 9f9c563cbf..bd1c45d042 100644 --- a/packages/opencode/src/file/index.ts +++ b/packages/opencode/src/file/index.ts @@ -567,9 +567,7 @@ export namespace File { const content = (await Filesystem.readText(full).catch(() => "")).trim() - // altimate_change start — retain file content without the Git working-tree comparison if (project.vcs === "git") { - // altimate_change end let diff = (await git(["-c", "core.fsmonitor=false", "diff", "--", file], { cwd: Instance.directory })).text() if (!diff.trim()) { diff = ( diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index ee996a5b13..d9e60367f5 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -180,6 +180,7 @@ let cli = yargs(args) directory?: string project?: string attach?: string + url?: string model?: string } const offlineTarget = (command === "run" && !args.attach ? args.dir : undefined) @@ -187,10 +188,11 @@ let cli = yargs(args) ?? (command === "workspace" ? args.directory : undefined) const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) await Offline.start(directory, args.model) + // Attaching to a server on this machine is local; any other server is a network peer. + const attachURL = command === "attach" ? args.url : command === "run" ? args.attach : undefined if (Offline.enabled() && ( - ["attach", "github", "gitlab", "pr", "review", "link", "workspace-client", "workspace-serve", "web", "integrations"].includes(command) || - (command === "run" && args.attach) || - (command === "tool" && opts._[1] === "daemon") || + ["github", "gitlab", "pr", "review", "link", "workspace-client", "web", "integrations"].includes(command) || + (attachURL !== undefined && !Offline.isLocalURL(attachURL)) || (command === "learn" && opts._[1] === "import-reviews") || (command === "console" && opts._[1] === "open") || (["providers", "auth", "console"].includes(command) && opts._[1] === "login") || diff --git a/packages/opencode/src/lsp/launch.ts b/packages/opencode/src/lsp/launch.ts index 4f687b1972..43d1a96ffd 100644 --- a/packages/opencode/src/lsp/launch.ts +++ b/packages/opencode/src/lsp/launch.ts @@ -1,5 +1,8 @@ import type { ChildProcessWithoutNullStreams } from "child_process" import { Process } from "@/util/process" +// altimate_change start — offline mode user environment +import { Offline } from "@/config/offline" +// altimate_change end type Child = Process.Child & ChildProcessWithoutNullStreams @@ -10,6 +13,9 @@ export function spawn(cmd: string, argsOrOpts?: string[] | Process.Options, opts const cfg = Array.isArray(argsOrOpts) ? opts : argsOrOpts const proc = Process.spawn([cmd, ...args], { ...cfg, + // altimate_change start — offline mode keeps the user's proxy settings for language servers + ...(Offline.enabled() && cfg?.env !== null ? { env: Offline.userEnv({ ...process.env, ...cfg?.env }) } : {}), + // altimate_change end stdin: "pipe", stdout: "pipe", stderr: "pipe", diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 4073cbd5e6..1ec772925e 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -622,7 +622,9 @@ export const layer = Layer.effect( command: cmd, args, cwd, - env: { + // altimate_change start — offline mode keeps the user's proxy settings for local servers + env: Offline.userEnv({ + // altimate_change end ...process.env, // altimate_change start — brand: BUN_BE_BUN for altimate/altimate-code self-spawn ...(cmd === "opencode" || cmd === "altimate" || cmd === "altimate-code" ? { BUN_BE_BUN: "1" } : {}), @@ -634,7 +636,9 @@ export const layer = Layer.effect( // values and break the `$${VAR}` escape convention — see PR #666 review. ...mcp.environment, // altimate_change end - }, + // altimate_change start — offline mode user environment + }), + // altimate_change end }) // altimate_change start — upstream_fix: drain the local server's stderr. With `stderr: "pipe"` // and no consumer, a chatty MCP server fills the OS pipe buffer (~64KiB) and blocks the child, diff --git a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx index 27d4618de0..b4cfe7059a 100644 --- a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx +++ b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx @@ -303,10 +303,6 @@ async function testSkillDirect( .join(sep) for (const tool of tools) { - if (Offline.enabled()) { - if (!Bun.which(tool, { PATH: toolPath })) return { ok: false, message: `${skillName}: FAIL — "${tool}" not found` } - continue - } try { const proc = Bun.spawn([tool, "--help"], { stdout: "pipe", @@ -323,7 +319,7 @@ async function testSkillDirect( return { ok: false, message: `${skillName}: FAIL — "${tool}" not found or failed to execute` } } } - return { ok: true, message: Offline.enabled() ? `${skillName}: tools found (skipped --help offline)` : `${skillName}: PASS` } + return { ok: true, message: `${skillName}: PASS` } } type RawSdkClient = { diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index d01718f9ae..809052443c 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -2431,14 +2431,19 @@ 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) } - // altimate_change — use the caller's configured model when no offline small model is set - if (Offline.enabled()) return undefined - const provider = await state().then((state) => state.providers[providerID]) if (provider) { let priority = [ diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 02aa20b5a6..1c862bbbb4 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -484,6 +484,11 @@ export namespace SessionPrompt { const writeOfflineNotice = async () => { const { ownManifest, snapshotKnownEmpty } = await import("../altimate/workspace/skill-sync") const snapshot = await ownManifest(dir) + // A withheld snapshot (rebound project, other account) must not stay visible through .claude/skills copies. + if (!snapshot) { + const { mirrorClaudeSkills } = await import("../altimate/workspace/claude-skill-mirror") + await mirrorClaudeSkills(dir, { withdraw: true }) + } const binding = snapshot ? null : await resolveBindingOutcome(dir) const empty = binding?.status === "bound" && await snapshotKnownEmpty(dir, binding.binding.datamateId) await Offline.announce(snapshot !== null, empty) diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index ef00c24836..830f66cb41 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -63,8 +63,10 @@ export namespace Discovery { const base = url.endsWith("/") ? url : `${url}/` const index = new URL("index.json", base).href // altimate_change start — reuse the cached index for this source without contacting it - const sourceCache = path.join(cache, ".sources", createHash("sha256").update(index).digest("hex")) - const indexPath = path.join(sourceCache, "index.json") + const sourceKey = createHash("sha256").update(index).digest("hex") + const sourceCache = path.join(cache, ".sources", sourceKey) + // Beside the source directory, not inside it, so no skill name can collide with it. + const indexPath = path.join(cache, ".sources", `${sourceKey}.json`) if (Offline.enabled()) { const cached = yield* fs.readJson(indexPath).pipe(Effect.catch(() => Effect.void)) const directories = Array.isArray(cached) ? cached : [] diff --git a/packages/opencode/src/tool/bash.ts b/packages/opencode/src/tool/bash.ts index 0ef418bdae..7dde160391 100644 --- a/packages/opencode/src/tool/bash.ts +++ b/packages/opencode/src/tool/bash.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode user environment +import { Offline } from "@/config/offline" +// altimate_change end import z from "zod" import { spawn } from "child_process" import { Tool } from "./tool" @@ -457,6 +460,9 @@ export const BashTool = Tool.define("bash", async () => { // Strip the markers that describe this host, not the child. See `stripHostMarkers` // for what each one is and why (PR #937 review, Issue #3, for the first of them). stripHostMarkers(mergedEnv) + // altimate_change start — offline mode leaves the user's own commands with their proxy settings + Offline.userEnv(mergedEnv) + // altimate_change end // altimate_change start — strip the run-mode markers for the same reason. stripRunModeMarkers(mergedEnv) // 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 index de9323e667..710b971b0b 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -46,18 +46,71 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true", direct_connection: false }, { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true&authMechanism=MONGODB-AWS" }, { type: "trino", url: "https://example.com" }, + { type: "trino", host: "127.0.0.1", protocol: "http://evil.example" }, + { type: "clickhouse", host: "127.0.0.1", protocol: "http://example.com:8123/" }, + { type: "oracle", connection_string: "db.example.com:1521/ORCL" }, + { type: "oracle", connection_string: "(DESCRIPTION=(ADDRESS=(HOST=db.example.com)))" }, + { type: "oracle", connection_string: "PRODTNS" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) + +test("offline accepts plain protocols and local Oracle Easy Connect strings", () => { + for (const config of [ + { type: "trino", host: "localhost", protocol: "https" }, + { type: "clickhouse", host: "127.0.0.1", protocol: "HTTP" }, + { type: "oracle", connection_string: "127.0.0.1:1521/ORCL" }, + { type: "oracle", connection_string: "//localhost/XEPDB1" }, + { type: "oracle", connection_string: "[::1]:1521/ORCL" }, + ]) expect(() => assertLocalConnection(config)).not.toThrow() +}) + +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") + } finally { await fs.rm(root, { recursive: true, force: true }) } +}) + +test.skipIf(process.platform === "win32")("offline dbt runs with the checked profiles directory and no version check", 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\"\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.exit_code).toBe(0) + expect(result.stdout.trim()).toBe(`${root}|false|false`) + expect((await runDbt({ command: "deps", project_dir: root })).stderr).toContain("Offline mode") + } finally { + process.env.PATH = previousPath + 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.toBeUndefined() + 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.toBeUndefined() + 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 }) } @@ -73,7 +126,7 @@ test("dbt project directory follows environment and CLI precedence", async () => 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.toBeUndefined() + await expect(assertLocalDbt(root, ["--profiles-dir", root, "--project-dir", root])).resolves.toEqual({ profilesDir: root }) } finally { await fs.rm(root, { recursive: true, force: true }) } }) @@ -139,7 +192,7 @@ test("cached remote target survives lost keychain credentials and closes on reje try { Credentials.setSecretBackendForTests({ name: "test", get: read, set: async () => {}, delete: async () => true }) Registry.setConfigs({ remote: { type: "postgres", host: "localhost" } }) - expect(await Registry.get("remote")).toBe(connector) + expect(await Registry.get("remote")).toBe(connector as any) expect(connect.mock.calls[0][0].connection_string).toBe("postgres://remote.example/db") read.mockClear() read.mockImplementation(async () => { throw new Error("keychain locked") }) diff --git a/packages/opencode/test/altimate/workspace/skill-sync.test.ts b/packages/opencode/test/altimate/workspace/skill-sync.test.ts index 2bf906a082..cc545c2125 100644 --- a/packages/opencode/test/altimate/workspace/skill-sync.test.ts +++ b/packages/opencode/test/altimate/workspace/skill-sync.test.ts @@ -1363,6 +1363,35 @@ describe("workspace skill sync", () => { } }) + test("offline withholds a snapshot from a different or broken serve pin without deleting it", async () => { + serve({ "pub-1": { "SKILL.md": "one" } }) + await syncSkills(project) + const keys = ["ALTIMATE_OFFLINE", "ALTIMATE_CODE_SERVE", "ALTIMATE_PINNED_WORKSPACE_ID", "ALTIMATE_PINNED_WORKSPACE_NAME", "ALTIMATE_PINNED_WORKSPACE_ROOT"] + const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) + const pin = (id: string) => + Object.assign(process.env, { + ALTIMATE_CODE_SERVE: "1", + ALTIMATE_PINNED_WORKSPACE_ID: id, + ALTIMATE_PINNED_WORKSPACE_NAME: "pinned", + ALTIMATE_PINNED_WORKSPACE_ROOT: project, + }) + try { + process.env.ALTIMATE_OFFLINE = "1" + pin("2") + expect(await snapshotWorkspaceId(project)).toBeNull() + pin("not-a-number") + expect(await snapshotWorkspaceId(project)).toBeNull() + pin("1") + expect(await snapshotWorkspaceId(project)).toBe(1) + expect(existsSync(skillFile("pub-1", "SKILL.md"))).toBe(true) + } finally { + for (const key of keys) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } + } + }) + test("registryStale reports a credential switch, with the snapshot untouched", async () => { // The disclosure this guards: the registry had already loaded the previous // account's skills, and an A-to-B switch changes nothing on disk. Keyed on diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 229890527f..bf3dfacf52 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -96,7 +96,7 @@ async function fixture( index: 0, id: "call_shell", type: "function", function: { name: "bash", arguments: JSON.stringify({ - command: "printf shell-ran > shell-marker", + command: 'printf "shell-ran:%s" "$NO_PROXY" > shell-marker', description: "Write a local marker", workdir: process.cwd(), timeout: 5000, @@ -214,7 +214,8 @@ test("offline model can execute a local bash command", async () => { try { const proc = Bun.spawn([process.execPath, "--preload", f.preload, CLI, "run", "--yolo", "Run the local shell command"], { cwd: f.project, - env: { ...f.env, OFFLINE_TEST_BASH: "1", ALTIMATE_CLI_YOLO: "true" }, + // The user's proxy exclusions reach their own commands; the offline bypass does not. + env: { ...f.env, OFFLINE_TEST_BASH: "1", ALTIMATE_CLI_YOLO: "true", NO_PROXY: "corp.example" }, stdin: "ignore", stdout: "pipe", stderr: "pipe", @@ -227,7 +228,7 @@ test("offline model can execute a local bash command", async () => { ]) 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" }) + expect({ marker, stdout, stderr }).toMatchObject({ marker: "shell-ran:corp.example" }) expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") } finally { await fs.rm(f.root, { recursive: true, force: true }) @@ -277,6 +278,55 @@ test("offline SQL tool queries a local DuckDB file", async () => { } }, 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 loopback warehouse connections.") + 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 model transport bypasses proxy settings and refuses redirects", async () => { let proxyCalls = 0 const proxy = Bun.serve({ @@ -494,11 +544,11 @@ test.skipIf(process.platform === "win32")( ) test.skipIf(process.platform === "win32")( - "offline skill validation skips running paired tools", + "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, "unexpected-tool") + 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) @@ -518,11 +568,10 @@ test.skipIf(process.platform === "win32")( new Response(proc.stdout).text(), new Response(proc.stderr).text(), ]) - expect(await Bun.file(marker).exists()).toBe(false) - expect({ code, stdout, stderr }).toMatchObject({ - code: 0, - stdout: expect.stringContaining("Paired tool --help checks require online mode."), - }) + // 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 }) } diff --git a/packages/opencode/test/config/offline-startup.test.ts b/packages/opencode/test/config/offline-startup.test.ts new file mode 100644 index 0000000000..158464e8aa --- /dev/null +++ b/packages/opencode/test/config/offline-startup.test.ts @@ -0,0 +1,28 @@ +// altimate_change - new file +import { expect, test } from "bun:test" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { Global } from "../../src/global" +import { Offline } from "../../src/config/offline" + +test("a legacy global TOML config that requests offline mode is detected at startup", async () => { + const project = await fs.mkdtemp(path.join(os.tmpdir(), "offline-legacy-")) + const legacy = path.join(Global.Path.config, "config") + const previous = process.env.ALTIMATE_OFFLINE + delete process.env.ALTIMATE_OFFLINE + try { + await fs.mkdir(Global.Path.config, { recursive: true }) + await fs.writeFile(legacy, 'model = "fixture"\noffline = true\n') + await expect(Offline.assertStartupPolicy(project)).rejects.toThrow("requests offline mode") + await fs.writeFile(legacy, "offline = false\n") + await expect(Offline.assertStartupPolicy(project)).resolves.toBeUndefined() + await fs.writeFile(legacy, "not = [valid toml") + await expect(Offline.assertStartupPolicy(project)).resolves.toBeUndefined() + } finally { + await fs.rm(legacy, { force: true }) + await fs.rm(project, { recursive: true, force: true }) + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } +}) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 7a8250d392..f3400629d7 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -10,6 +10,11 @@ test("offline MCP URL policy accepts only HTTP(S) localhost and loopback", () => }) test("offline local MCP fetch rejects remote requests and redirects before remote egress", async () => { + // Bun applies HTTP(S)_PROXY to loopback too unless NO_PROXY covers it; keep an ambient proxy out of this test. + const proxyKeys = ["HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"] + const savedProxy = Object.fromEntries(proxyKeys.map((key) => [key, process.env[key]])) + for (const key of proxyKeys) delete process.env[key] + process.env.NO_PROXY = process.env.no_proxy = "127.0.0.1,localhost" let calls = 0 const server = Bun.serve({ hostname: "127.0.0.1", @@ -29,5 +34,34 @@ test("offline local MCP fetch rejects remote requests and redirects before remot expect(calls).toBe(2) } finally { server.stop(true) + for (const key of proxyKeys) { + if (savedProxy[key] === undefined) delete process.env[key] + else process.env[key] = savedProxy[key] + } + } +}) + +test("user programs get their own proxy exclusions back, not the offline bypass", () => { + const keys = ["NO_PROXY", "no_proxy", "ALTIMATE_OFFLINE_USER_PROXY"] + const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) + try { + // What Offline.start leaves behind: the bypass, plus the user's original values. + process.env.ALTIMATE_OFFLINE_USER_PROXY = JSON.stringify({ NO_PROXY: "corp.example" }) + process.env.NO_PROXY = process.env.no_proxy = "*" + const env: Record = Offline.userEnv({ ...process.env, PATH: "/bin" }) + expect(env.NO_PROXY).toBe("corp.example") + expect(env.no_proxy).toBeUndefined() + expect(env.ALTIMATE_OFFLINE_USER_PROXY).toBeUndefined() + expect(env.PATH).toBe("/bin") + // A value the program's own configuration set is kept. + expect(Offline.userEnv({ ...process.env, NO_PROXY: "mcp.local" }).NO_PROXY).toBe("mcp.local") + // Without offline state, the environment is unchanged. + delete process.env.ALTIMATE_OFFLINE_USER_PROXY + expect(Offline.userEnv({ NO_PROXY: "*" }).NO_PROXY).toBe("*") + } finally { + for (const key of keys) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } } }) 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..a89a064e9e 100644 --- a/packages/opencode/test/skill/discovery.test.ts +++ b/packages/opencode/test/skill/discovery.test.ts @@ -137,4 +137,40 @@ describe("Discovery.pull", () => { expect(downloadCount).toBe(firstCount) }), ) + + // altimate_change start — offline reuses the cached source list, even when a skill is named like it + it.live("offline serves the cached skills of a source, including one named index.json", () => + Effect.gen(function* () { + const source = Bun.serve({ + port: 0, + fetch(req) { + const { pathname } = new URL(req.url) + if (pathname === "/s/index.json") + return Response.json({ + skills: [ + { name: "index.json", description: "odd name", files: ["SKILL.md"] }, + { name: "plain", description: "plain", files: ["SKILL.md"] }, + ], + }) + if (pathname.endsWith("/SKILL.md")) return new Response("---\nname: x\ndescription: x\n---\nbody") + return new Response("Not Found", { status: 404 }) + }, + }) + const previous = process.env.ALTIMATE_OFFLINE + try { + const discovery = yield* Discovery.Service + const url = `http://localhost:${source.port}/s/` + const online = yield* discovery.pull(url) + expect(online.map((dir) => path.basename(dir)).sort()).toEqual(["index.json", "plain"]) + process.env.ALTIMATE_OFFLINE = "1" + const offline = yield* discovery.pull(url) + expect(offline.sort()).toEqual(online.sort()) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + void source.stop(true) + } + }), + ) + // altimate_change end }) From 4db67d81bfa5cf3f8cf4fdeedd7c074f3c5769de Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:05:36 -0800 Subject: [PATCH 24/72] chore: mark offline changes in upstream-shared files Co-Authored-By: Claude Opus 5.5 --- packages/core/src/models-dev.ts | 2 ++ packages/core/src/npm.ts | 6 ++++++ packages/core/src/observability/otlp.ts | 6 ++++++ packages/opencode/src/cli/cmd/mcp.ts | 8 ++++++++ packages/opencode/src/config/paths.ts | 4 ++++ packages/opencode/src/mcp/index.ts | 8 ++++++++ packages/opencode/src/provider/provider.ts | 2 ++ packages/opencode/src/skill/discovery.ts | 6 ++++++ packages/opencode/src/snapshot/index.ts | 4 ++++ packages/opencode/src/worktree/index.ts | 4 ++++ 10 files changed, 50 insertions(+) diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 9962a469a7..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" +// 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" diff --git a/packages/core/src/npm.ts b/packages/core/src/npm.ts index 6c17df2c81..3207466e66 100644 --- a/packages/core/src/npm.ts +++ b/packages/core/src/npm.ts @@ -1,4 +1,6 @@ +// altimate_change start — offline mode import { offlineModeEnabled } from "./flag/flag" +// altimate_change end export * as Npm from "./npm" import path from "path" @@ -127,12 +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) { @@ -144,7 +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), diff --git a/packages/core/src/observability/otlp.ts b/packages/core/src/observability/otlp.ts index 38a2daf921..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" +// 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() { + // 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() { + // 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/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index ace66beb5e..1470977ae5 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -518,7 +518,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) @@ -894,7 +896,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}`) @@ -931,7 +935,9 @@ export const McpDebugCommand = effectCmd({ // Test basic HTTP connectivity first try { + // altimate_change start — offline mode keeps the probe on loopback const response = await (Offline.enabled() ? Offline.localFetch() : fetch)(serverConfig.url, { + // altimate_change end method: "POST", headers: { ...serverConfig.headers, @@ -985,7 +991,9 @@ export const McpDebugCommand = effectCmd({ // Try creating transport with auth provider to trigger discovery const transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), { authProvider, + // altimate_change start — offline mode keeps the probe on loopback fetch: Offline.enabled() ? Offline.localFetch() : undefined, + // altimate_change end requestInit: serverConfig.headers ? { headers: serverConfig.headers } : undefined, }) diff --git a/packages/opencode/src/config/paths.ts b/packages/opencode/src/config/paths.ts index e5bd6caab1..3ae50aaa21 100644 --- a/packages/opencode/src/config/paths.ts +++ b/packages/opencode/src/config/paths.ts @@ -210,7 +210,9 @@ async function substitute( } // altimate_change end + // altimate_change start — offline opt-in probe reads text without file substitution if (opts.expandFiles === false) return text + // altimate_change end const fileMatches = Array.from(text.matchAll(/\{file:[^}]+\}/g)) if (!fileMatches.length) return text @@ -270,10 +272,12 @@ export async function parseText( text: string, input: ParseSource, missing: "error" | "empty" = "error", + // altimate_change start — offline opt-in probe options opts: { track?: boolean; expandFiles?: boolean } = {}, ): Promise { const configSource = source(input) text = await substitute(text, input, missing, opts) + // altimate_change end const errors: JsoncParseError[] = [] const data = parseJsonc(text, errors, { allowTrailingComma: true }) diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 1ec772925e..222ada4d80 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -111,11 +111,13 @@ export class NotFoundError extends Schema.TaggedErrorClass()("MCP name: Schema.String, }) {} +// altimate_change start — offline policy refusals are client errors export class OfflinePolicyError extends Schema.TaggedErrorClass()( "MCP.OfflinePolicyError", { message: Schema.String }, { httpApiStatus: 400 }, ) {} +// altimate_change end type MCPClient = Client @@ -330,8 +332,10 @@ export interface Interface { readonly prompts: () => Effect.Effect> readonly resources: () => Effect.Effect> // altimate_change end + // altimate_change start — offline policy refusals readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Record | Status }, OfflinePolicyError> readonly connect: (name: string) => Effect.Effect + // altimate_change end readonly disconnect: (name: string) => Effect.Effect // altimate_change start — MCP.remove: full runtime teardown + ToolsChanged (merge dropped it) readonly remove: (name: string) => Effect.Effect @@ -429,6 +433,7 @@ 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, @@ -436,6 +441,7 @@ export const layer = Layer.effect( transport: undefined as TransportLabel | undefined, } } + // altimate_change end const url = remoteURL(mcp.url) if (!url) { return { @@ -1092,8 +1098,10 @@ export const layer = Layer.effect( }) // altimate_change end + // altimate_change start — offline policy refusal const add = Effect.fn("MCP.add")(function* (name: string, mcp: ConfigMCPV1.Info) { yield* enforceOfflinePolicy(mcp) + // altimate_change end // altimate_change start — see claim const seq = ++lifecycleSeq // altimate_change end diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index 809052443c..fa54fb0643 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -2028,7 +2028,9 @@ export namespace Provider { continue } const result = await fn(data) + // 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 ?? {} diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index 830f66cb41..03230043ef 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -97,8 +97,10 @@ export namespace Discovery { if (!data) return [] const list = data.skills.filter((skill) => { + // altimate_change start — reject unsafe skill names and file paths if (skill.name.includes("/") || !SkillDiscovery.isSafeRelativePath(skill.name)) return false if (!skill.files.every(SkillDiscovery.isSafeRelativePath)) return false + // altimate_change end if (!skill.files.includes("SKILL.md")) { log.warn("skill entry missing SKILL.md", { url: index, skill: skill.name }) return false @@ -110,7 +112,9 @@ export namespace Discovery { list, (skill) => Effect.gen(function* () { + // altimate_change start — per-source cache for offline reuse const root = path.join(sourceCache, skill.name) + // altimate_change end yield* Effect.forEach( skill.files, @@ -126,7 +130,9 @@ export namespace Discovery { { concurrency: skillConcurrency }, ) + // altimate_change start — per-source cache for offline reuse const available = dirs.filter((dir): dir is string => dir !== null) + // altimate_change end // altimate_change start — store the directory list for a later offline run yield* fs.writeWithDirs(indexPath, JSON.stringify(available)).pipe(Effect.ignore) // altimate_change end diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index 023ba34181..5e7a1c1ad9 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -93,7 +93,9 @@ export const layer: Layer.Layer; stdin?: string }) { const result = yield* appProcess.run( + // altimate_change start — offline Git transport policy ChildProcess.make("git", cmd, { cwd: opts?.cwd, env: localGitEnv(opts?.env), extendEnv: true }), + // altimate_change end { stdin: opts?.stdin }, ) return { @@ -609,7 +611,9 @@ export const layer: Layer.Layer item.ref).join("\n") + "\n" }, diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 9c871bda0f..12eb00a9b6 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -15,7 +15,9 @@ import { Slug } from "@opencode-ai/core/util/slug" import { errorMessage } from "../util/error" import { EventV2 } from "@opencode-ai/core/event" import { GlobalBus } from "@/bus/global" +// altimate_change start — offline Git transport policy import { Git, localGitEnv } from "@/git" +// altimate_change end import { Effect, Layer, Path, Schema, Scope, Context } from "effect" import { ChildProcess } from "effect/unstable/process" import { NodePath } from "@effect/platform-node" @@ -176,7 +178,9 @@ export const layer: Layer.Layer< const git = Effect.fnUntraced( function* (args: string[], opts?: { cwd?: string }) { const result = yield* appProcess.run( + // altimate_change start — offline Git transport policy ChildProcess.make("git", args, { cwd: opts?.cwd, env: localGitEnv(), extendEnv: true, stdin: "ignore" }), + // altimate_change end ) return { code: result.exitCode, From 3a79399245078f4e77c0b51b1f0d9878e9bd3cba Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:29:16 -0800 Subject: [PATCH 25/72] fix: address offline review findings Check dbt-mysql server hosts and dbt-duckdb remote storage, allow local Unix sockets, pin the adapter to the checked profiles directory, restore proxy settings for session shell commands, type offline MCP auth refusals, allow local review, and show the workspace notice only for projects that use a workspace. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 6 +++--- packages/dbt-tools/src/adapter.ts | 3 +++ .../src/altimate/native/connections/offline.ts | 10 ++++++++-- .../altimate/native/connections/register.ts | 12 +++++++++--- .../src/altimate/native/dbt/offline.ts | 6 ++++-- .../src/altimate/workspace/api-client.ts | 2 +- .../src/altimate/workspace/identity.ts | 2 +- .../src/altimate/workspace/memory-sync.ts | 2 +- .../src/altimate/workspace/review-notices.ts | 2 +- .../opencode/src/altimate/workspace/state.ts | 2 +- packages/opencode/src/cli/cmd/tool.ts | 2 +- packages/opencode/src/index.ts | 4 +++- packages/opencode/src/mcp/index.ts | 10 +++++++--- .../routes/instance/httpapi/groups/mcp.ts | 8 ++++++-- packages/opencode/src/session/prompt.ts | 16 ++++++++++++---- packages/opencode/src/tool/registry.ts | 2 +- .../native/offline-connections.test.ts | 18 ++++++++++++++++++ packages/opencode/test/cli/run/offline.test.ts | 5 +++-- 18 files changed, 83 insertions(+), 29 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 9825b1ef4f..310d237e32 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -180,7 +180,7 @@ While still online: ### What keeps working -- Local warehouses: DuckDB and SQLite files, and warehouses whose host is `localhost`, `::1` or `127.x.x.x`. The SQL and schema tools run against them. +- Local warehouses: DuckDB and SQLite files, and warehouses reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. The SQL and schema tools run against them. - dbt commands, when the selected profile and target point at a local database. - The shell tool, installed language servers, and MCP servers that use stdio or a loopback HTTP(S) URL. - Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and submodule commits. Git LFS files check out from the local LFS cache; a file whose content is not cached fails with a clear error instead of downloading. @@ -198,9 +198,9 @@ Each of these fails with a one-line message or is skipped: - MCP servers at non-loopback URLs, and MCP sign-in; - automatic installs of warehouse drivers, language servers, plugins and ripgrep; - warehouse connections whose host is not loopback, SSH tunnels, and cloud sign-in methods; -- `dbt deps`, and dbt's own usage reporting and version check; +- `dbt deps`, dbt's own usage reporting and version check, and dbt-duckdb profiles that use remote storage or a remote server; - Git fetch, pull, push, clone and other remote operations; -- commands that need a remote service, such as `github`, `pr`, `web` and `attach` to another machine. +- commands that need a remote service, such as `github`, `pr`, `web`, `review --post` and `attach` to another machine. ### What offline mode does not police diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 73aabf281f..e30d0afb43 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -85,6 +85,8 @@ function terminal(): DBTTerminal { 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 @@ -102,6 +104,7 @@ function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" 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, diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 04e2362d46..4f06c6ec27 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -21,7 +21,9 @@ export function assertLocalConnection(raw: ConnectionConfig): void { const config = normalizeConfig(raw) const type = config.type.toLowerCase() const deny = () => { throw new Error("Offline mode allows only local file databases and loopback warehouse connections.") } - if (config.ssh_host || config.replica_set || config.socketPath) deny() + if (config.ssh_host || config.replica_set) deny() + // A Unix socket is a local file; a Windows named pipe or other value is not checked here. + if (config.socketPath !== undefined && !(typeof config.socketPath === "string" && config.socketPath.startsWith("/"))) deny() if (type === "duckdb" || type === "sqlite") { if (!localStore(config.path)) deny() return @@ -31,7 +33,11 @@ export function assertLocalConnection(raw: ConnectionConfig): void { if (config.authentication && !["sql", "ntlm"].includes(String(config.authentication).toLowerCase())) deny() const mongo = type === "mongodb" || type === "mongo" if (mongo && config.direct_connection !== undefined && config.direct_connection !== true) deny() - if (config.host !== undefined && !isLoopbackHost(config.host)) deny() + // Postgres accepts a socket directory as its host. + const socketHost = typeof config.host === "string" && config.host.startsWith("/") && ["postgres", "postgresql", "redshift"].includes(type) + if (config.host !== undefined && !socketHost && !isLoopbackHost(config.host)) deny() + // dbt-mysql and others name the host `server`; Trino's `server` is a URL checked below. + if (type !== "trino" && config.server !== undefined && !isLoopbackHost(config.server)) deny() // Trino and ClickHouse build `${protocol}://${host}` URLs, so a protocol value can carry its own authority. if ((type === "trino" || type === "clickhouse") && config.protocol !== undefined && !["http", "https"].includes(String(config.protocol).trim().toLowerCase())) deny() diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index c6785d6c56..144a9d1c3e 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -70,7 +70,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; offline?: boolean }) => 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. */ @@ -129,7 +129,9 @@ async function ensureDbtAdapter(): Promise { } // The integration reads profiles.yml relative to the project, so check from there. - if (Offline.enabled()) await assertLocalDbt(dbtConfig.projectRoot, [], dbtConfig.dbtIntegration, dbtConfig.projectRoot) + const offline = Offline.enabled() + ? await assertLocalDbt(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 @@ -139,7 +141,11 @@ async function ensureDbtAdapter(): Promise { const options = SEPARATE_TARGET_MODES.has(dbtConfig.dbtIntegration || "core") ? { targetPath: await dbtToolTargetPath(dbtConfig.projectRoot) } : {} - return publish(await create(dbtConfig, { ...options, ...(Offline.enabled() ? { offline: true } : {}) }), dbtConfig.projectRoot) + // Offline, dbt reads exactly the profiles directory that was checked. + return publish( + await create(dbtConfig, { ...options, ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}) }), + dbtConfig.projectRoot, + ) } catch (error) { if (error instanceof OfflineDbtError) throw error // dbt-tools not available or config invalid — fall back to native diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index 555948f33e..ab1d9cf16c 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -98,7 +98,9 @@ async function checkLocalDbt( assertLocalConnection({ ...output, path: output.path ?? (output.type === "duckdb" ? ":memory:" : undefined) }) } // These profile hooks cause dbt-duckdb to install extensions or open extra connections at startup. - if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length) - throw new Error("Offline mode requires a dbt profile without extension installs, attachments, plugins, or remote secrets.") + const remoteRoot = typeof output.external_root === "string" && /^[a-z][a-z0-9+.-]*:\/\//i.test(output.external_root) + if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length || + output.filesystems?.length || output.remote || remoteRoot) + throw new Error("Offline mode requires a dbt profile without extension installs, attachments, plugins, remote secrets, remote storage, or a remote server.") return { profilesDir } } diff --git a/packages/opencode/src/altimate/workspace/api-client.ts b/packages/opencode/src/altimate/workspace/api-client.ts index ee896fcfe3..d247d25ca4 100644 --- a/packages/opencode/src/altimate/workspace/api-client.ts +++ b/packages/opencode/src/altimate/workspace/api-client.ts @@ -1,5 +1,5 @@ -import { Offline } from "@/config/offline" // 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 diff --git a/packages/opencode/src/altimate/workspace/identity.ts b/packages/opencode/src/altimate/workspace/identity.ts index 101fa953e0..143f8164fd 100644 --- a/packages/opencode/src/altimate/workspace/identity.ts +++ b/packages/opencode/src/altimate/workspace/identity.ts @@ -1,5 +1,5 @@ -import { Offline } from "@/config/offline" // 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 diff --git a/packages/opencode/src/altimate/workspace/memory-sync.ts b/packages/opencode/src/altimate/workspace/memory-sync.ts index f3f63e91e6..f85c79deb9 100644 --- a/packages/opencode/src/altimate/workspace/memory-sync.ts +++ b/packages/opencode/src/altimate/workspace/memory-sync.ts @@ -1,5 +1,5 @@ -import { Offline } from "@/config/offline" // 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. diff --git a/packages/opencode/src/altimate/workspace/review-notices.ts b/packages/opencode/src/altimate/workspace/review-notices.ts index 83fb90814b..5b11a77da3 100644 --- a/packages/opencode/src/altimate/workspace/review-notices.ts +++ b/packages/opencode/src/altimate/workspace/review-notices.ts @@ -1,5 +1,5 @@ -import { Offline } from "@/config/offline" // 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 diff --git a/packages/opencode/src/altimate/workspace/state.ts b/packages/opencode/src/altimate/workspace/state.ts index 1e1fdffced..34b78d5de7 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -1,5 +1,5 @@ -import { Offline } from "@/config/offline" // altimate_change - new file +import { Offline } from "@/config/offline" // // Local binding cache — offline fallback for the server-authoritative // pre-check. Scoped to (tenant, apiUrl, account) at the top level so a diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index dca5cdf61d..7e6dbab6d4 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -1,5 +1,5 @@ -import { Offline } from "@/config/offline" // altimate_change - new file +import { Offline } from "@/config/offline" // // Model-free access to the data tools: `tool list`, `tool run` and the optional `tool daemon` // that keeps warehouse connections and the schema cache warm between calls. The tool modules are diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index d9e60367f5..ee87088ac8 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -191,7 +191,9 @@ let cli = yargs(args) // Attaching to a server on this machine is local; any other server is a network peer. const attachURL = command === "attach" ? args.url : command === "run" ? args.attach : undefined if (Offline.enabled() && ( - ["github", "gitlab", "pr", "review", "link", "workspace-client", "web", "integrations"].includes(command) || + ["github", "gitlab", "pr", "link", "workspace-client", "web", "integrations"].includes(command) || + // A local review runs offline; posting it to GitHub does not. + (command === "review" && (opts as { post?: boolean }).post === true) || (attachURL !== undefined && !Offline.isLocalURL(attachURL)) || (command === "learn" && opts._[1] === "import-reviews") || (command === "console" && opts._[1] === "open") || diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 222ada4d80..72ec647fd5 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -349,10 +349,12 @@ export interface Interface { clientName: string, resourceUri: string, ) => Effect.Effect> | undefined> + // altimate_change start — offline refusal is a typed error readonly startAuth: ( mcpName: string, - ) => Effect.Effect<{ authorizationUrl: string; oauthState: string }, NotFoundError> - readonly authenticate: (mcpName: string) => Effect.Effect + ) => Effect.Effect<{ authorizationUrl: string; oauthState: string }, NotFoundError | OfflinePolicyError> + readonly authenticate: (mcpName: string) => Effect.Effect + // altimate_change end readonly finishAuth: (mcpName: string, authorizationCode: string) => Effect.Effect readonly removeAuth: (mcpName: string) => Effect.Effect readonly supportsOAuth: (mcpName: string) => Effect.Effect @@ -1415,7 +1417,9 @@ 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.") + // altimate_change start — offline refusal is a client error, not a crash + if (Offline.enabled()) return yield* new OfflinePolicyError({ message: "Authenticate MCP servers while online." }) + // altimate_change end const lifecycle = yield* InstanceState.get(state) // altimate_change end const mcpConfig = yield* requireMcpConfig(mcpName) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts index 812a838d3d..28924b24f9 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts @@ -77,7 +77,9 @@ export const McpApi = HttpApi.make("mcp") params: { name: Schema.String }, query: WorkspaceRoutingQuery, success: described(AuthStartResponse, "OAuth flow started"), - error: [UnsupportedOAuthError, McpServerNotFoundError], + // altimate_change start — offline refusal is a declared client error + error: [UnsupportedOAuthError, McpServerNotFoundError, MCP.OfflinePolicyError], + // altimate_change end }).annotateMerge( OpenApi.annotations({ identifier: "mcp.auth.start", @@ -103,7 +105,9 @@ export const McpApi = HttpApi.make("mcp") params: { name: Schema.String }, query: WorkspaceRoutingQuery, success: described(MCP.Status, "OAuth authentication completed"), - error: [UnsupportedOAuthError, McpServerNotFoundError], + // altimate_change start — offline refusal is a declared client error + error: [UnsupportedOAuthError, McpServerNotFoundError, MCP.OfflinePolicyError], + // altimate_change end }).annotateMerge( OpenApi.annotations({ identifier: "mcp.auth.authenticate", diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 1c862bbbb4..4f8ed0c63a 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -490,8 +490,11 @@ export namespace SessionPrompt { await mirrorClaudeSkills(dir, { withdraw: true }) } const binding = snapshot ? null : await resolveBindingOutcome(dir) - const empty = binding?.status === "bound" && await snapshotKnownEmpty(dir, binding.binding.datamateId) - await Offline.announce(snapshot !== null, empty) + // Only a project that uses a workspace hears about workspace skills. + if (snapshot || binding?.status === "bound") { + const empty = binding?.status === "bound" && await snapshotKnownEmpty(dir, binding.binding.datamateId) + await Offline.announce(snapshot !== null, empty) + } await refreshSkillRegistry(dir) } const notice = writeOfflineNotice().catch((error) => log.warn("offline skill snapshot setup failed", { error })) @@ -4511,11 +4514,13 @@ NOTE: At any point in time through this workflow you should feel free to ask the detached: process.platform !== "win32", windowsHide: process.platform === "win32", stdio: ["ignore", "pipe", "pipe"], - env: { + // altimate_change start — offline mode leaves the user's own commands with their proxy settings + env: Offline.userEnv({ ...process.env, ...shellEnv.env, TERM: "dumb", - }, + }), + // altimate_change end }) let output = "" @@ -4860,6 +4865,9 @@ NOTE: At any point in time through this workflow you should feel free to ask the // altimate_change start — upstream_fix: non-bash command-template shells need an explicit cwd. cwd: Instance.directory, // altimate_change end + // altimate_change start — offline mode leaves the user's own commands with their proxy settings + ...(Offline.enabled() ? { env: Offline.userEnv({ ...process.env }) } : {}), + // altimate_change end stdout: "pipe", stderr: "pipe", }) diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 29c5e85f90..7295d2de5f 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -419,7 +419,6 @@ export namespace ToolRegistry { plugins?: Awaited>, configInput?: RegistryConfigInput, ): Promise { - const question = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL const custom = configInput?.matches ? await loadCustomTools(configInput.matches).then((x) => x.custom) : await state().then((x) => x.custom) @@ -428,6 +427,7 @@ export namespace ToolRegistry { // altimate_change end const config = configInput?.config ?? (await Config.get()) // altimate_change end + const question = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL // 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. diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 710b971b0b..985edcae55 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -51,6 +51,8 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "oracle", connection_string: "db.example.com:1521/ORCL" }, { type: "oracle", connection_string: "(DESCRIPTION=(ADDRESS=(HOST=db.example.com)))" }, { type: "oracle", connection_string: "PRODTNS" }, + { type: "mysql", server: "db.example.com" }, + { type: "mysql", socketPath: "\\\\.\\pipe\\remote" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) @@ -61,6 +63,9 @@ test("offline accepts plain protocols and local Oracle Easy Connect strings", () { type: "oracle", connection_string: "127.0.0.1:1521/ORCL" }, { type: "oracle", connection_string: "//localhost/XEPDB1" }, { type: "oracle", connection_string: "[::1]:1521/ORCL" }, + { type: "mysql", server: "127.0.0.1" }, + { type: "mysql", socketPath: "/tmp/mysql.sock" }, + { type: "postgres", host: "/var/run/postgresql" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -80,6 +85,19 @@ test("dbt finds the project from a subdirectory and reads profiles from the work } finally { await fs.rm(root, { recursive: true, force: true }) } }) +test("dbt-duckdb profiles that reach remote storage or a remote server are refused", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-duckdb-")) + try { + await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: test\n") + for (const extra of ["external_root: s3://bucket/x", "remote:\n host: db.example.com", "filesystems:\n - fs: s3"]) { + await fs.writeFile(path.join(root, "profiles.yml"), `test:\n outputs:\n default:\n type: duckdb\n path: local.duckdb\n ${extra}\n`) + await expect(assertLocalDbt(root, ["--profiles-dir", root])).rejects.toThrow("Offline mode") + } + await fs.writeFile(path.join(root, "profiles.yml"), "test:\n outputs:\n default:\n type: duckdb\n path: local.duckdb\n external_root: out/parquet\n") + 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 version check", async () => { const { runDbt } = await import("../../../src/altimate/native/dbt/runner") const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-run-")) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index bf3dfacf52..b82cba5495 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -196,10 +196,11 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ 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.match(/Offline mode:/g)).toHaveLength(1) expect(stderr).not.toContain("Workspace skills not synced") - if (!snapshot) expect(stderr).toContain("No usable workspace skill snapshot") + // The fixture without a snapshot has no workspace link, so it gets no workspace notice at all. + if (!snapshot) expect(stderr).not.toContain("Offline mode:") else { + expect(stderr.match(/Offline mode:/g)).toHaveLength(1) expect(await fs.readFile(f.manifest, "utf8")).toBe(before!) expect(await fs.readFile(f.skill, "utf8")).toContain(SKILL) } From 34fd5565c59364bcb89474ac40176c14127a72ec Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:42:14 -0800 Subject: [PATCH 26/72] fix: close remaining offline review gaps Pin the dbt adapter check to the project it runs, honor a matching serve pin over the project link, restore proxy settings in the terminal, treat wildcard bind addresses as local, keep shared sessions until their share can be revoked, and skip needless offline probe work. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 2 +- .../altimate/native/connections/register.ts | 2 +- .../src/altimate/workspace/skill-sync.ts | 2 ++ packages/opencode/src/config/offline.ts | 6 +++- packages/opencode/src/pty/index.ts | 9 ++++-- packages/opencode/src/session/index.ts | 7 +++++ packages/opencode/src/session/prompt.ts | 2 +- .../native/offline-connections.test.ts | 31 +++++++++++++++++++ .../altimate/workspace/skill-sync.test.ts | 3 ++ packages/opencode/test/mcp/offline.test.ts | 2 +- 10 files changed, 59 insertions(+), 7 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 310d237e32..acb654209f 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ Offline mode is for running Altimate Code against a local or self-hosted model w Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file. The setting covers the process and its workers. A project that requests offline mode is refused by a shared server started without it; start Altimate Code from that project instead. -Configure a provider with an explicit HTTP(S) `options.baseURL` and select 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. Requests to that endpoint are the only requests Altimate Code sends off the machine. A `small_model` is used only if it belongs to the same provider; otherwise the main model handles those tasks. +Configure a provider with an explicit HTTP(S) `options.baseURL` and select 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. Requests to that endpoint are the only requests Altimate Code sends off the machine. They go directly to the endpoint, not through `HTTP_PROXY` or `HTTPS_PROXY`, so the endpoint must be reachable without a proxy. A `small_model` is used only if it belongs to the same provider; otherwise the main model handles those tasks. ### Before going offline diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 144a9d1c3e..25278a9c35 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -130,7 +130,7 @@ async function ensureDbtAdapter(): Promise { // The integration reads profiles.yml relative to the project, so check from there. const offline = Offline.enabled() - ? await assertLocalDbt(dbtConfig.projectRoot, [], dbtConfig.dbtIntegration, dbtConfig.projectRoot) + ? 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 diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index fb899ddebd..ad0128a245 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -197,6 +197,8 @@ export async function ownManifest(directory: string): Promise { // A serve pin outranks the project's link, as in resolveBindingOutcome; a broken pin fails closed. const pin = readPin() if (pin.kind === "invalid" || (pin.kind === "valid" && pin.datamateId !== manifest.datamateId)) return null + // A matching pin decides on its own; the project's link is consulted only without one. + if (pin.kind === "valid") return manifest const { binding: local } = await readLocalBindingScopedStrict(directory) if (local && local.datamateId !== manifest.datamateId) return null } diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 237eea10f2..9c993921d8 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -19,6 +19,8 @@ async function localOptIn(directory: string) { // key so remote credentials and unrelated substitutions cannot affect it. const optedIn = async (text: string | undefined, source: string | { source: string; dir: string }) => { if (!text) return false + // Skip the substitution pass for text that can neither name nor produce the key. + if (!text.includes("offline") && !/\{env:|\$\{|\{file:/.test(text)) return false if (parse(text)?.offline === true) return true const config = await ConfigPaths.parseText(text, source, "empty", { track: false, expandFiles: false }).catch(() => undefined) return config?.offline === true @@ -173,7 +175,9 @@ export function modelFetch(baseURL: string | undefined): typeof fetch { export function isLoopbackHost(value: unknown): boolean { if (typeof value !== "string") return false const host = value.toLowerCase().replace(/^\[|\]$/g, "") - return host === "localhost" || host === "localhost." || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")) + // Wildcard bind addresses (0.0.0.0, ::) are reached on this machine when used as a destination. + return host === "localhost" || host === "localhost." || host === "::1" || host === "::" || host === "0.0.0.0" || + (isIP(host) === 4 && host.startsWith("127.")) } // Validate the URL before any offline loopback HTTP request. diff --git a/packages/opencode/src/pty/index.ts b/packages/opencode/src/pty/index.ts index 166d9f4213..470024a1a0 100644 --- a/packages/opencode/src/pty/index.ts +++ b/packages/opencode/src/pty/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode user environment +import { Offline } from "@/config/offline" +// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" // altimate_change start — upstream moved the pty spawn backend into @opencode-ai/core @@ -132,13 +135,15 @@ export namespace Pty { const cwd = input.cwd || Instance.directory const shellEnv = await Plugin.trigger("shell.env", { cwd }, { env: {} }) - const env = { + // altimate_change start — offline mode leaves the user's terminal with their proxy settings + const env = Offline.userEnv({ ...process.env, ...input.env, ...shellEnv.env, TERM: "xterm-256color", OPENCODE_TERMINAL: "1", - } as Record + }) as Record + // altimate_change end // altimate_change start — prepend user tools dirs to PATH in terminal sessions const sep = process.platform === "win32" ? ";" : ":" diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index aee9ca8898..4cac7eaba0 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end // altimate_change start — release session-owned scratch stores on deletion import { closeScratch } from "@/altimate/native/connections/scratch" // altimate_change end @@ -749,6 +752,10 @@ export namespace Session { const project = Instance.project try { const session = await get(sessionID) + // altimate_change start — offline mode cannot revoke a public share, so it keeps the session that holds it + if (Offline.enabled() && session.share?.url) + throw new Error("This session is shared. Delete it while online so its share can be revoked.") + // altimate_change end for (const child of await children(sessionID)) { await remove(child.id) } diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 4f8ed0c63a..66ec7d2f49 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -485,7 +485,7 @@ export namespace SessionPrompt { const { ownManifest, snapshotKnownEmpty } = await import("../altimate/workspace/skill-sync") const snapshot = await ownManifest(dir) // A withheld snapshot (rebound project, other account) must not stay visible through .claude/skills copies. - if (!snapshot) { + if (!snapshot && existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) { const { mirrorClaudeSkills } = await import("../altimate/workspace/claude-skill-mirror") await mirrorClaudeSkills(dir, { withdraw: true }) } diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 985edcae55..3bdcae06ba 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -177,6 +177,37 @@ test("dbt policy failure surfaces on repeated SQL calls without a registry fallb } }) +test("the dbt adapter is checked against the project it will run, not DBT_PROJECT_DIR", async () => { + const adapter = await import("../../../src/altimate/native/connections/register") + const Dispatcher = await import("../../../src/altimate/native/dispatcher") + const Registry = await import("../../../src/altimate/native/connections/registry") + const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-projectdir-")) + const create = mock(async () => ({})) + try { + const other = path.join(root, "other") + await fs.mkdir(other) + await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: remote\n") + await fs.writeFile(path.join(other, "dbt_project.yml"), "profile: local\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: db.example.com\n") + process.env.ALTIMATE_OFFLINE = "1" + process.env.DBT_PROJECT_DIR = other + adapter.resetDbtAdapter() + adapter.dbtAdapterInternals.readConfig = async () => ({ projectRoot: root }) + adapter.dbtAdapterInternals.create = create + adapter.registerAll() + const result = await Dispatcher.call("sql.execute", { sql: "SELECT 1" }) + expect((result as { error?: string }).error).toContain("Offline mode") + expect(create).not.toHaveBeenCalled() + } finally { + delete adapter.dbtAdapterInternals.readConfig + delete adapter.dbtAdapterInternals.create + adapter.resetDbtAdapter() + Registry.reset() + Dispatcher.reset() + await fs.rm(root, { recursive: true, force: true }) + } +}) + test("cached local connections never reread credentials offline", async () => { const Registry = await import("../../../src/altimate/native/connections/registry") const Credentials = await import("../../../src/altimate/native/connections/credential-store") diff --git a/packages/opencode/test/altimate/workspace/skill-sync.test.ts b/packages/opencode/test/altimate/workspace/skill-sync.test.ts index cc545c2125..dc111b907d 100644 --- a/packages/opencode/test/altimate/workspace/skill-sync.test.ts +++ b/packages/opencode/test/altimate/workspace/skill-sync.test.ts @@ -1383,6 +1383,9 @@ describe("workspace skill sync", () => { expect(await snapshotWorkspaceId(project)).toBeNull() pin("1") expect(await snapshotWorkspaceId(project)).toBe(1) + // A matching pin outranks a project link that names another workspace. + bindTo(2) + expect(await snapshotWorkspaceId(project)).toBe(1) expect(existsSync(skillFile("pub-1", "SKILL.md"))).toBe(true) } finally { for (const key of keys) { diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index f3400629d7..234f7cc074 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -3,7 +3,7 @@ import { expect, test } from "bun:test" import { Offline } from "../../src/config/offline" test("offline MCP URL policy accepts only HTTP(S) localhost and loopback", () => { - for (const url of ["http://localhost:3000/mcp", "https://localhost./mcp", "http://127.2.3.4/mcp", "http://[::1]:3000/mcp"]) + for (const url of ["http://localhost:3000/mcp", "https://localhost./mcp", "http://127.2.3.4/mcp", "http://[::1]:3000/mcp", "http://0.0.0.0:4096", "http://[::]:4096"]) 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) From 5f09cb92e195e79b2d5c0f02c619a80186886155 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:59:00 -0800 Subject: [PATCH 27/72] fix: refuse offline deletion of shared sessions visibly Check the whole session tree before deleting so the refusal reaches the caller, expand ~ in the dbt profiles directory, and accept local SQL Server instances and Postgres socket URLs. Co-Authored-By: Claude Opus 5.5 --- .../altimate/native/connections/offline.ts | 12 ++++-- .../src/altimate/native/dbt/offline.ts | 3 +- packages/opencode/src/session/index.ts | 16 ++++++-- .../native/offline-connections.test.ts | 7 ++++ .../test/session/offline-delete.test.ts | 39 +++++++++++++++++++ .../opencode/test/skill/discovery.test.ts | 2 + 6 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 packages/opencode/test/session/offline-delete.test.ts diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 4f06c6ec27..2a477ce88b 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -34,8 +34,11 @@ export function assertLocalConnection(raw: ConnectionConfig): void { const mongo = type === "mongodb" || type === "mongo" if (mongo && config.direct_connection !== undefined && config.direct_connection !== true) deny() // Postgres accepts a socket directory as its host. - const socketHost = typeof config.host === "string" && config.host.startsWith("/") && ["postgres", "postgresql", "redshift"].includes(type) - if (config.host !== undefined && !socketHost && !isLoopbackHost(config.host)) deny() + const postgres = ["postgres", "postgresql", "redshift"].includes(type) + const socketHost = typeof config.host === "string" && config.host.startsWith("/") && postgres + // SQL Server names an instance as host\instance. + const host = typeof config.host === "string" && ["sqlserver", "mssql"].includes(type) ? config.host.split("\\")[0] : config.host + if (host !== undefined && !socketHost && !isLoopbackHost(host)) deny() // dbt-mysql and others name the host `server`; Trino's `server` is a URL checked below. if (type !== "trino" && config.server !== undefined && !isLoopbackHost(config.server)) deny() // Trino and ClickHouse build `${protocol}://${host}` URLs, so a protocol value can carry its own authority. @@ -52,12 +55,15 @@ export function assertLocalConnection(raw: ConnectionConfig): void { try { const url = new URL(String(connectionString)) if ((type === "trino" || type === "clickhouse") && !["http:", "https:"].includes(url.protocol)) deny() - if (!isLoopbackHost(url.hostname) || url.protocol === "mongodb+srv:") deny() const query = new Map([...url.searchParams].map(([key, value]) => [key.toLowerCase(), value.toLowerCase()])) + // postgresql:///db?host=/run/postgresql connects through a local Unix socket. + const socketURL = postgres && !url.hostname && (query.get("host") ?? "").startsWith("/") && !query.has("hostaddr") + if ((!socketURL && !isLoopbackHost(url.hostname)) || url.protocol === "mongodb+srv:") deny() if (mongo && config.direct_connection !== true && query.get("directconnection") !== "true") deny() if (mongo && ["mongodb-aws", "mongodb-oidc", "gssapi"].includes(query.get("authmechanism") ?? "")) deny() // Drivers can override the authority via URL parameters or discover replica peers. for (const key of url.searchParams.keys()) { + if (socketURL && key.toLowerCase() === "host") continue if (["host", "hostaddr", "server", "replicaset", "service"].includes(key.toLowerCase())) deny() } } catch { deny() } diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index ab1d9cf16c..d5d6559bb0 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -74,7 +74,8 @@ async function checkLocalDbt( const root = option("--project-dir") ?? process.env.DBT_PROJECT_DIR ?? (await findProjectRoot(projectRoot)) const project = resolve(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("--profiles-dir") ?? process.env.DBT_PROFILES_DIR + // dbt expands ~ in the profiles directory. + const explicit = (option("--profiles-dir") ?? process.env.DBT_PROFILES_DIR)?.replace(/^~(?=$|[\\/])/, os.homedir()) const profilesDir = path.resolve( cwd, explicit ?? diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index 4cac7eaba0..c12189b904 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -750,12 +750,20 @@ export namespace Session { export const remove = fn(SessionID.zod, async (sessionID) => { const project = Instance.project + // altimate_change start — offline mode cannot revoke a public share, so it refuses to delete a shared + // session (or one with a shared descendant) before anything is removed + if (Offline.enabled()) { + const pending = [sessionID] + while (pending.length) { + const id = pending.pop()! + if ((await get(id).catch(() => undefined))?.share?.url) + throw new Error("This session is shared. Delete it while online so its share can be revoked.") + pending.push(...(await children(id)).map((child) => child.id)) + } + } + // altimate_change end try { const session = await get(sessionID) - // altimate_change start — offline mode cannot revoke a public share, so it keeps the session that holds it - if (Offline.enabled() && session.share?.url) - throw new Error("This session is shared. Delete it while online so its share can be revoked.") - // altimate_change end for (const child of await children(sessionID)) { await remove(child.id) } diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 3bdcae06ba..14fc812046 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -52,6 +52,8 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "oracle", connection_string: "(DESCRIPTION=(ADDRESS=(HOST=db.example.com)))" }, { type: "oracle", connection_string: "PRODTNS" }, { type: "mysql", server: "db.example.com" }, + { type: "postgres", connection_string: "postgresql:///analytics?host=/var/run/postgresql&hostaddr=10.0.0.5" }, + { type: "sqlserver", host: "db.example.com\\SQLEXPRESS" }, { type: "mysql", socketPath: "\\\\.\\pipe\\remote" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) @@ -66,6 +68,8 @@ test("offline accepts plain protocols and local Oracle Easy Connect strings", () { type: "mysql", server: "127.0.0.1" }, { type: "mysql", socketPath: "/tmp/mysql.sock" }, { type: "postgres", host: "/var/run/postgresql" }, + { type: "postgres", connection_string: "postgresql:///analytics?host=/var/run/postgresql" }, + { type: "sqlserver", host: "localhost\\SQLEXPRESS" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -82,6 +86,9 @@ test("dbt finds the project from a subdirectory and reads profiles from the work 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 }) } }) diff --git a/packages/opencode/test/session/offline-delete.test.ts b/packages/opencode/test/session/offline-delete.test.ts new file mode 100644 index 0000000000..668f1b8069 --- /dev/null +++ b/packages/opencode/test/session/offline-delete.test.ts @@ -0,0 +1,39 @@ +// altimate_change - new file +import { afterEach, expect, test } from "bun:test" +import { SessionTable } from "@opencode-ai/core/session/sql" +import { Instance } from "../../src/project/instance" +import { Session } from "../../src/session" +import { Database, eq } from "../../src/storage/db" +import { Log } from "../../src/util/log" +import { tmpdir } from "../fixture/fixture" + +Log.init({ print: false }) +afterEach(async () => { + await Instance.disposeAll() +}) + +test("offline mode refuses to delete a shared session, or its parent, and keeps both", async () => { + await using tmp = await tmpdir({ git: true }) + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const parent = await Session.create({ title: "parent" }) + const child = await Session.create({ title: "child", parentID: parent.id }) + Database.use((db) => + db.update(SessionTable).set({ share_url: "https://share.example/s/1" }).where(eq(SessionTable.id, child.id)).run(), + ) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + await expect(Session.remove(child.id)).rejects.toThrow("This session is shared") + await expect(Session.remove(parent.id)).rejects.toThrow("This session is shared") + expect((await Session.get(child.id)).share?.url).toBe("https://share.example/s/1") + expect((await Session.get(parent.id)).id).toBe(parent.id) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + await Session.remove(parent.id).catch(() => {}) + }, + }) +}) diff --git a/packages/opencode/test/skill/discovery.test.ts b/packages/opencode/test/skill/discovery.test.ts index a89a064e9e..d53c93d98f 100644 --- a/packages/opencode/test/skill/discovery.test.ts +++ b/packages/opencode/test/skill/discovery.test.ts @@ -163,6 +163,8 @@ describe("Discovery.pull", () => { const online = yield* discovery.pull(url) expect(online.map((dir) => path.basename(dir)).sort()).toEqual(["index.json", "plain"]) process.env.ALTIMATE_OFFLINE = "1" + // The source is gone: offline results can only come from the cache. + void source.stop(true) const offline = yield* discovery.pull(url) expect(offline.sort()).toEqual(online.sort()) } finally { From 676180830ae0ed76e60914ddc8a328fd23ab7fa5 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:28:04 -0800 Subject: [PATCH 28/72] fix: address offline bot review round Apply explicit env after proxy restoration, keep LFS override last, block dbt usage reporting flags, scope serve pins to their root, refuse offline deletion of shared sessions from the CLI, tighten Postgres socket and UNC checks, gate workspace tools in every tool command, and harden tests. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 4 ++- packages/core/src/git.ts | 3 +++ packages/core/test/git.test.ts | 9 ++++++- packages/dbt-tools/src/adapter.ts | 1 + .../altimate/native/connections/offline.ts | 9 ++++--- .../src/altimate/native/dbt/offline.ts | 10 +++++--- .../src/altimate/native/dbt/runner.ts | 19 +++++++++----- .../src/altimate/tool-cli/workspace-tools.ts | 3 +++ .../src/altimate/workspace/skill-sync.ts | 4 ++- packages/opencode/src/cli/cmd/session.ts | 15 +++++++++++ packages/opencode/src/cli/cmd/skill.ts | 2 +- packages/opencode/src/cli/tui/worker.ts | 6 ++++- packages/opencode/src/config/offline.ts | 7 ++++-- packages/opencode/src/config/paths.ts | 2 +- packages/opencode/src/index.ts | 2 +- packages/opencode/src/lsp/launch.ts | 5 +++- packages/opencode/src/mcp/index.ts | 10 +++----- packages/opencode/src/pty/index.ts | 6 ++--- packages/opencode/src/session/index.ts | 11 ++++++-- packages/opencode/src/session/prompt.ts | 9 ++++--- packages/opencode/src/session/session.ts | 23 +++++++++++++++++ packages/opencode/src/skill/discovery.ts | 10 ++++++-- packages/opencode/src/tool/bash.ts | 7 +++--- packages/opencode/src/worktree/index.ts | 8 +++++- .../test/altimate/debug/collect.test.ts | 25 ++++++++++--------- .../test/altimate/mcp-server/stdio.test.ts | 4 ++- .../native/offline-connections.test.ts | 2 +- packages/opencode/test/bun.test.ts | 5 ++-- .../test/config/offline-startup.test.ts | 20 +++++++++------ packages/opencode/test/mcp/offline.test.ts | 23 +++++++++-------- packages/opencode/test/util/git.test.ts | 19 ++++++++++++++ 31 files changed, 205 insertions(+), 78 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index acb654209f..f1bceca7f5 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -194,7 +194,7 @@ Each of these fails with a one-line message or is skipped: - model catalog downloads and update checks; - workspace and workspace engine sync; - session sharing; -- the web fetch, web search, code search, workspace manager, feedback and memory refresh tools; +- the web fetch, web search, code search, `datamate_manager`, feedback and memory refresh tools; - MCP servers at non-loopback URLs, and MCP sign-in; - automatic installs of warehouse drivers, language servers, plugins and ripgrep; - warehouse connections whose host is not loopback, SSH tunnels, and cloud sign-in methods; @@ -205,3 +205,5 @@ Each of these fails with a one-line message or is skipped: ### What offline mode does not police Programs you run or configure yourself keep their own network access: shell commands, language servers, local MCP servers and their child processes. They also keep your proxy settings. Offline mode does not sandbox them. + +DuckDB connections do not install or load extensions automatically offline. SQL that explicitly runs `INSTALL` or `LOAD` (for example for `httpfs`) and then 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, usage reporting and version check. diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index e7e13f7156..df0003b737 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -21,6 +21,8 @@ export function localGitEnv(env?: Record) { if (!offlineModeEnabled()) return env const inherited = Number(env?.GIT_CONFIG_COUNT ?? process.env.GIT_CONFIG_COUNT ?? 0) const index = Number.isInteger(inherited) && inherited > 0 ? inherited : 0 + // Inherited `-c` parameters are read after GIT_CONFIG_COUNT entries, so the override is appended there as well. + const parameters = env?.GIT_CONFIG_PARAMETERS ?? process.env.GIT_CONFIG_PARAMETERS return { ...env, GIT_ALLOW_PROTOCOL: "", @@ -28,6 +30,7 @@ export function localGitEnv(env?: Record) { GIT_CONFIG_COUNT: String(index + 1), [`GIT_CONFIG_KEY_${index}`]: "lfs.url", [`GIT_CONFIG_VALUE_${index}`]: OFFLINE_LFS_URL, + ...(parameters ? { GIT_CONFIG_PARAMETERS: `${parameters} 'lfs.url'='${OFFLINE_LFS_URL}'` } : {}), } } diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index dd6b7535a2..61ddd012fb 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -61,10 +61,17 @@ describe("Git", () => { Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "offline-lfs-"))), (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), ) + // Repository-location variables inherited from a caller would redirect these commands away from tmp. + const base = Object.fromEntries( + Object.entries(process.env).filter( + ([key]) => !["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_COMMON_DIR"].includes(key), + ), + ) const gitIn = (args: string[], env?: Record) => - Bun.spawnSync(["git", ...args], { cwd: tmp, env: { ...process.env, ...env }, stderr: "pipe", stdout: "pipe" }) + Bun.spawnSync(["git", ...args], { cwd: tmp, env: { ...base, ...env }, stderr: "pipe", stdout: "pipe" }) for (const args of [ ["init", "-q"], + ["config", "commit.gpgsign", "false"], ["config", "user.email", "t@example.com"], ["config", "user.name", "t"], ["lfs", "install", "--local"], diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index e30d0afb43..42fca5af31 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -102,6 +102,7 @@ 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 diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 2a477ce88b..cc3c949485 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -23,7 +23,7 @@ export function assertLocalConnection(raw: ConnectionConfig): void { const deny = () => { throw new Error("Offline mode allows only local file databases and loopback warehouse connections.") } if (config.ssh_host || config.replica_set) deny() // A Unix socket is a local file; a Windows named pipe or other value is not checked here. - if (config.socketPath !== undefined && !(typeof config.socketPath === "string" && config.socketPath.startsWith("/"))) deny() + if (config.socketPath && !(typeof config.socketPath === "string" && config.socketPath.startsWith("/"))) deny() if (type === "duckdb" || type === "sqlite") { if (!localStore(config.path)) deny() return @@ -57,13 +57,16 @@ export function assertLocalConnection(raw: ConnectionConfig): void { if ((type === "trino" || type === "clickhouse") && !["http:", "https:"].includes(url.protocol)) deny() const query = new Map([...url.searchParams].map(([key, value]) => [key.toLowerCase(), value.toLowerCase()])) // postgresql:///db?host=/run/postgresql connects through a local Unix socket. - const socketURL = postgres && !url.hostname && (query.get("host") ?? "").startsWith("/") && !query.has("hostaddr") + // Exactly one lowercase host parameter, naming a socket directory; drivers read only that exact key. + const hostParams = [...url.searchParams.keys()].filter((key) => key.toLowerCase() === "host") + const socketURL = postgres && !url.hostname && hostParams.length === 1 && hostParams[0] === "host" && + url.searchParams.get("host")!.startsWith("/") && !query.has("hostaddr") if ((!socketURL && !isLoopbackHost(url.hostname)) || url.protocol === "mongodb+srv:") deny() if (mongo && config.direct_connection !== true && query.get("directconnection") !== "true") deny() if (mongo && ["mongodb-aws", "mongodb-oidc", "gssapi"].includes(query.get("authmechanism") ?? "")) deny() // Drivers can override the authority via URL parameters or discover replica peers. for (const key of url.searchParams.keys()) { - if (socketURL && key.toLowerCase() === "host") continue + if (socketURL && key === "host") continue if (["host", "hostaddr", "server", "replicaset", "service"].includes(key.toLowerCase())) deny() } } catch { deny() } diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index d5d6559bb0..3fcebb4c69 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -44,7 +44,10 @@ export async function assertLocalDbt( try { return await checkLocalDbt(projectRoot, args, integration, cwd) } catch (error) { - throw new OfflineDbtError(error instanceof Error ? error.message : String(error), { cause: error }) + // Policy refusals are typed; a missing or unreadable project or profile keeps its own error. + if (error instanceof Error && error.message.startsWith("Offline mode")) + throw new OfflineDbtError(error.message, { cause: error }) + throw error } } @@ -75,7 +78,7 @@ async function checkLocalDbt( const project = resolve(parse(await fs.readFile(path.join(root, "dbt_project.yml"), "utf8"))) // dbt's order: --profiles-dir, DBT_PROFILES_DIR, the working directory, then ~/.dbt. // dbt expands ~ in the profiles directory. - const explicit = (option("--profiles-dir") ?? process.env.DBT_PROFILES_DIR)?.replace(/^~(?=$|[\\/])/, os.homedir()) + const explicit = (option("--profiles-dir") ?? process.env.DBT_PROFILES_DIR)?.replace(/^~(?=$|[\\/])/, () => os.homedir()) const profilesDir = path.resolve( cwd, explicit ?? @@ -99,7 +102,8 @@ async function checkLocalDbt( assertLocalConnection({ ...output, path: output.path ?? (output.type === "duckdb" ? ":memory:" : undefined) }) } // These profile hooks cause dbt-duckdb to install extensions or open extra connections at startup. - const remoteRoot = typeof output.external_root === "string" && /^[a-z][a-z0-9+.-]*:\/\//i.test(output.external_root) + const remoteRoot = typeof output.external_root === "string" && + (/^(?:\\\\|\/\/)/.test(output.external_root) || /^[a-z][a-z0-9+.-]*:\/\//i.test(output.external_root)) if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length || output.filesystems?.length || output.remote || remoteRoot) throw new Error("Offline mode requires a dbt profile without extension installs, attachments, plugins, remote secrets, remote storage, or a remote server.") diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index 55045ef118..539397a611 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -34,15 +34,22 @@ export async function runDbt(params: DbtRunParams): Promise { let offlineEnv: NodeJS.ProcessEnv | undefined if (Offline.enabled()) { try { - if ((params.command || "run") === "deps") throw new Error("Offline mode disables dbt dependency installation.") - const { profilesDir } = await assertLocalDbt(params.project_dir || process.cwd(), [ - ...(params.args ?? []), - ...(params.project_dir ? ["--project-dir", params.project_dir] : []), - ]) + 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 init` creates a project; there is no profile to check yet. + const checked = command === "init" + ? undefined + : await assertLocalDbt(params.project_dir || process.cwd(), [ + ...(params.args ?? []), + ...(params.project_dir ? ["--project-dir", params.project_dir] : []), + ]) offlineEnv = { ...process.env, - DBT_PROFILES_DIR: profilesDir, + ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), DBT_SEND_ANONYMOUS_USAGE_STATS: "false", + DO_NOT_TRACK: "1", DBT_VERSION_CHECK: "false", } } catch (error) { diff --git a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts index 7f4d14560b..e8596b4659 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,8 @@ 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()) return false return flag ?? (await linked(directory)) } diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index ad0128a245..2ca3429ada 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -195,7 +195,9 @@ export async function ownManifest(directory: string): Promise { // altimate_change — hide a stale workspace snapshot offline without removing it if (Offline.enabled()) { // A serve pin outranks the project's link, as in resolveBindingOutcome; a broken pin fails closed. - const pin = readPin() + const raw = readPin() + // A pin covers only the tree serve was launched for. + const pin = raw.kind === "valid" && resolveWithinRoot(directory, raw.root) === null ? { kind: "absent" as const } : raw if (pin.kind === "invalid" || (pin.kind === "valid" && pin.datamateId !== manifest.datamateId)) return null // A matching pin decides on its own; the project's link is consulted only without one. if (pin.kind === "valid") return manifest diff --git a/packages/opencode/src/cli/cmd/session.ts b/packages/opencode/src/cli/cmd/session.ts index 9e6ddda9d2..a0537adec1 100644 --- a/packages/opencode/src/cli/cmd/session.ts +++ b/packages/opencode/src/cli/cmd/session.ts @@ -3,6 +3,10 @@ import { Effect } from "effect" import { cmd } from "./cmd" import { effectCmd, fail } from "../effect-cmd" import { Session } from "@/session/session" +// altimate_change start — offline shared-session refusal +import { Offline } from "@/config/offline" +import { OFFLINE_SHARED_SESSION } from "@/session/session" +// altimate_change end import { SessionID } from "../../session/schema" import { UI } from "../ui" import { Locale } from "@/util/locale" @@ -60,6 +64,17 @@ export const SessionDeleteCommand = effectCmd({ handler: Effect.fn("Cli.session.delete")(function* (args) { const svc = yield* Session.Service const sessionID = SessionID.make(args.sessionID) + // altimate_change start — offline mode keeps a shared session until its share can be revoked + if (Offline.enabled()) { + const pending = [sessionID] + while (pending.length) { + const id = pending.pop()! + const info = yield* svc.get(id).pipe(Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`))) + if (info.share?.url) return yield* fail(OFFLINE_SHARED_SESSION) + pending.push(...(yield* svc.children(id)).map((child) => child.id)) + } + } + // altimate_change end yield* svc .remove(sessionID) .pipe(Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`))) diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index 06c93ab071..3307535abe 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -424,7 +424,7 @@ const SkillTestCommand = cmd({ try { const worktreeDir = Instance.worktree !== "/" ? Instance.worktree : projectDir const toolEnv = { - ...process.env, + ...Offline.userEnv({ ...process.env }), PATH: [ process.env.ALTIMATE_BIN_DIR, path.join(worktreeDir, ".opencode", "tools"), diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 0115230070..0a8a73a07f 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -73,7 +73,11 @@ Heap.start() // InstanceRuntime.load/Config.get() would otherwise race it (transiently truncated // read) or cache the pre-heal entry, making the first session spawn the broken // config anyway. Errors are swallowed: a failed sync must never block the TUI. -const datamateSyncReady: Promise = syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) +// altimate_change start — offline mode skips the IDE workspace engine sync +const datamateSyncReady: Promise = Offline.enabled() + ? Promise.resolve() + : syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) +// altimate_change end // altimate_change end const traceConsumer = new TraceConsumer() diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 9c993921d8..f8db3ebc94 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -20,7 +20,7 @@ async function localOptIn(directory: string) { const optedIn = async (text: string | undefined, source: string | { source: string; dir: string }) => { if (!text) return false // Skip the substitution pass for text that can neither name nor produce the key. - if (!text.includes("offline") && !/\{env:|\$\{|\{file:/.test(text)) return false + if (!text.includes("offline") && !/\{env:|\$\{|\{file:|\\u/.test(text)) return false if (parse(text)?.offline === true) return true const config = await ConfigPaths.parseText(text, source, "empty", { track: false, expandFiles: false }).catch(() => undefined) return config?.offline === true @@ -57,7 +57,10 @@ async function localOptIn(directory: string) { if (legacy !== undefined) { try { if ((Bun.TOML.parse(legacy) as { offline?: unknown }).offline === true) return true - } catch {} + } catch { + // An unparseable file still counts when it plainly requests offline mode. + if (/^\s*offline\s*=\s*true\b/m.test(legacy)) return true + } } const managed = await ConfigManaged.readManagedPreferences().catch(() => undefined) return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false diff --git a/packages/opencode/src/config/paths.ts b/packages/opencode/src/config/paths.ts index 3ae50aaa21..d21d0b2464 100644 --- a/packages/opencode/src/config/paths.ts +++ b/packages/opencode/src/config/paths.ts @@ -272,7 +272,7 @@ export async function parseText( text: string, input: ParseSource, missing: "error" | "empty" = "error", - // altimate_change start — offline opt-in probe options + // altimate_change start — options gain expandFiles for the offline opt-in probe opts: { track?: boolean; expandFiles?: boolean } = {}, ): Promise { const configSource = source(input) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index ee87088ac8..f7e43e5975 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -189,7 +189,7 @@ let cli = yargs(args) const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) await Offline.start(directory, args.model) // Attaching to a server on this machine is local; any other server is a network peer. - const attachURL = command === "attach" ? args.url : command === "run" ? args.attach : undefined + const attachURL = command === "attach" ? args.url : command === "run" ? args.attach || undefined : undefined if (Offline.enabled() && ( ["github", "gitlab", "pr", "link", "workspace-client", "web", "integrations"].includes(command) || // A local review runs offline; posting it to GitHub does not. diff --git a/packages/opencode/src/lsp/launch.ts b/packages/opencode/src/lsp/launch.ts index 43d1a96ffd..bc6036a111 100644 --- a/packages/opencode/src/lsp/launch.ts +++ b/packages/opencode/src/lsp/launch.ts @@ -14,7 +14,10 @@ export function spawn(cmd: string, argsOrOpts?: string[] | Process.Options, opts const proc = Process.spawn([cmd, ...args], { ...cfg, // altimate_change start — offline mode keeps the user's proxy settings for language servers - ...(Offline.enabled() && cfg?.env !== null ? { env: Offline.userEnv({ ...process.env, ...cfg?.env }) } : {}), + // Process.spawn merges process.env underneath, so a removed key is set to undefined (unset) instead. + ...(Offline.enabled() && cfg?.env !== null + ? { env: { NO_PROXY: undefined, no_proxy: undefined, ...Offline.userEnv({ ...process.env }), ...cfg?.env } } + : {}), // altimate_change end stdin: "pipe", stdout: "pipe", diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 72ec647fd5..7067954d47 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -630,10 +630,10 @@ export const layer = Layer.effect( command: cmd, args, cwd, - // altimate_change start — offline mode keeps the user's proxy settings for local servers - env: Offline.userEnv({ + env: { + // altimate_change start — offline mode keeps the user's proxy settings; the server's own environment still wins + ...Offline.userEnv({ ...process.env }), // altimate_change end - ...process.env, // altimate_change start — brand: BUN_BE_BUN for altimate/altimate-code self-spawn ...(cmd === "opencode" || cmd === "altimate" || cmd === "altimate-code" ? { BUN_BE_BUN: "1" } : {}), // altimate_change end @@ -644,9 +644,7 @@ export const layer = Layer.effect( // values and break the `$${VAR}` escape convention — see PR #666 review. ...mcp.environment, // altimate_change end - // altimate_change start — offline mode user environment - }), - // altimate_change end + }, }) // altimate_change start — upstream_fix: drain the local server's stderr. With `stderr: "pipe"` // and no consumer, a chatty MCP server fills the OS pipe buffer (~64KiB) and blocks the child, diff --git a/packages/opencode/src/pty/index.ts b/packages/opencode/src/pty/index.ts index 470024a1a0..367de744a6 100644 --- a/packages/opencode/src/pty/index.ts +++ b/packages/opencode/src/pty/index.ts @@ -136,13 +136,13 @@ export namespace Pty { const cwd = input.cwd || Instance.directory const shellEnv = await Plugin.trigger("shell.env", { cwd }, { env: {} }) // altimate_change start — offline mode leaves the user's terminal with their proxy settings - const env = Offline.userEnv({ - ...process.env, + const env = { + ...Offline.userEnv({ ...process.env }), ...input.env, ...shellEnv.env, TERM: "xterm-256color", OPENCODE_TERMINAL: "1", - }) as Record + } as Record // altimate_change end // altimate_change start — prepend user tools dirs to PATH in terminal sessions diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index c12189b904..214ef43213 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -748,18 +748,25 @@ export namespace Session { return rows.map(fromRow) }) + // altimate_change start — descendants already checked by an offline removal of their ancestor + const offlineTreeChecked = new Set() + // altimate_change end export const remove = fn(SessionID.zod, async (sessionID) => { const project = Instance.project // altimate_change start — offline mode cannot revoke a public share, so it refuses to delete a shared // session (or one with a shared descendant) before anything is removed - if (Offline.enabled()) { + if (Offline.enabled() && !offlineTreeChecked.delete(sessionID)) { + const tree: SessionID[] = [] const pending = [sessionID] while (pending.length) { const id = pending.pop()! - if ((await get(id).catch(() => undefined))?.share?.url) + tree.push(id) + if ((await get(id)).share?.url) throw new Error("This session is shared. Delete it while online so its share can be revoked.") pending.push(...(await children(id)).map((child) => child.id)) } + // The recursive removal of each descendant skips the scan it has already passed. + for (const id of tree.slice(1)) offlineTreeChecked.add(id) } // altimate_change end try { diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 66ec7d2f49..8713b790ff 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -491,7 +491,8 @@ export namespace SessionPrompt { } const binding = snapshot ? null : await resolveBindingOutcome(dir) // Only a project that uses a workspace hears about workspace skills. - if (snapshot || binding?.status === "bound") { + const { readPin } = await import("../altimate/workspace/pin") + if (snapshot || binding?.status === "bound" || readPin().kind === "valid") { const empty = binding?.status === "bound" && await snapshotKnownEmpty(dir, binding.binding.datamateId) await Offline.announce(snapshot !== null, empty) } @@ -4515,11 +4516,11 @@ NOTE: At any point in time through this workflow you should feel free to ask the windowsHide: process.platform === "win32", stdio: ["ignore", "pipe", "pipe"], // altimate_change start — offline mode leaves the user's own commands with their proxy settings - env: Offline.userEnv({ - ...process.env, + env: { + ...Offline.userEnv({ ...process.env }), ...shellEnv.env, TERM: "dumb", - }), + }, // altimate_change end }) diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index d77b027c97..42287f056c 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode +import { Offline } from "@/config/offline" +// altimate_change end // altimate_change start — release session-owned scratch stores on deletion import { closeScratch } from "@/altimate/native/connections/scratch" // altimate_change end @@ -467,6 +470,9 @@ export class BusyError extends Schema.TaggedErrorClass()("SessionBusy }) {} export type NotFound = NotFoundError +// altimate_change start — offline shared-session refusal +export const OFFLINE_SHARED_SESSION = "This session is shared. Delete it while online so its share can be revoked." +// altimate_change end export interface Interface { readonly list: (input?: ListInput) => Effect.Effect @@ -659,8 +665,25 @@ export const layer: Layer.Layer< return rows.map(fromRow) }) + // altimate_change start — offline shared-session check + const sharedInTree = (sessionID: SessionID): Effect.Effect => + Effect.gen(function* () { + const pending = [sessionID] + while (pending.length) { + const id = pending.pop()! + if ((yield* get(id)).share?.url) return true + pending.push(...(yield* children(id)).map((child) => child.id)) + } + return false + }) + // altimate_change end + const remove: Interface["remove"] = Effect.fnUntraced(function* (sessionID: SessionID) { const session = yield* get(sessionID) + // altimate_change start — offline mode cannot revoke a public share, so a shared tree is not deleted + if (Offline.enabled() && (yield* sharedInTree(sessionID))) + return yield* Effect.die(new Error(OFFLINE_SHARED_SESSION)) + // altimate_change end try { // `remove` needs to work in all cases, such as broken sessions that // run cleanup without instance state. diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index 03230043ef..bb11f77489 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -98,8 +98,14 @@ export namespace Discovery { const list = data.skills.filter((skill) => { // altimate_change start — reject unsafe skill names and file paths - if (skill.name.includes("/") || !SkillDiscovery.isSafeRelativePath(skill.name)) return false - if (!skill.files.every(SkillDiscovery.isSafeRelativePath)) return false + if ( + skill.name.includes("/") || + !SkillDiscovery.isSafeRelativePath(skill.name) || + !skill.files.every(SkillDiscovery.isSafeRelativePath) + ) { + log.warn("skill entry has an unsafe name or file path", { url: index, skill: skill.name }) + return false + } // altimate_change end if (!skill.files.includes("SKILL.md")) { log.warn("skill entry missing SKILL.md", { url: index, skill: skill.name }) diff --git a/packages/opencode/src/tool/bash.ts b/packages/opencode/src/tool/bash.ts index 7dde160391..c0d58c973f 100644 --- a/packages/opencode/src/tool/bash.ts +++ b/packages/opencode/src/tool/bash.ts @@ -456,13 +456,12 @@ export const BashTool = Tool.define("bash", async () => { ) // altimate_change start — prepend bundled tools dir (ALTIMATE_BIN_DIR) and user tools dirs to PATH - const mergedEnv: Record = { ...process.env, ...shellEnv.env } + // altimate_change start — offline mode restores the user's proxy settings before plugin overrides + const mergedEnv: Record = { ...Offline.userEnv({ ...process.env }), ...shellEnv.env } + // altimate_change end // Strip the markers that describe this host, not the child. See `stripHostMarkers` // for what each one is and why (PR #937 review, Issue #3, for the first of them). stripHostMarkers(mergedEnv) - // altimate_change start — offline mode leaves the user's own commands with their proxy settings - Offline.userEnv(mergedEnv) - // altimate_change end // altimate_change start — strip the run-mode markers for the same reason. stripRunModeMarkers(mergedEnv) // altimate_change end diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 12eb00a9b6..06347a4649 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -490,7 +490,13 @@ export const layer: Layer.Layer< function* (directory: string, cmd: string) { const [shell, args] = process.platform === "win32" ? ["cmd", ["/c", cmd]] : ["bash", ["-lc", cmd]] const result = yield* appProcess.run( - ChildProcess.make(shell, args as string[], { cwd: directory, extendEnv: true, stdin: "ignore" }), + ChildProcess.make(shell, args as string[], { + cwd: directory, + // altimate_change start — offline mode keeps the user's proxy settings for their start commands + ...(Offline.enabled() ? { env: Offline.userEnv({ ...process.env }) as Record, extendEnv: false } : { extendEnv: true }), + // altimate_change end + stdin: "ignore", + }), ) return { code: result.exitCode, stderr: result.stderr.toString("utf8") } }, diff --git a/packages/opencode/test/altimate/debug/collect.test.ts b/packages/opencode/test/altimate/debug/collect.test.ts index 1a27fd9f88..34ff5f07f5 100644 --- a/packages/opencode/test/altimate/debug/collect.test.ts +++ b/packages/opencode/test/altimate/debug/collect.test.ts @@ -190,17 +190,18 @@ describe("process liveness", () => { expect(pidAlive(2 ** 22 + 12345)).toBe(false) }) }) -// altimate_change end - -test("offline telemetry reports the offline policy rather than --no-network", async () => { - const prior = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - for (const network of [true, false]) { - expect(await telemetryFacts(network)).toEqual({ enabled: false, checked: false, reason: "offline mode" }) +describe("offline mode", () => { + test("offline telemetry reports the offline policy rather than --no-network", async () => { + const prior = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + for (const network of [true, false]) { + expect(await telemetryFacts(network)).toEqual({ enabled: false, checked: false, reason: "offline mode" }) + } + } finally { + if (prior === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = prior } - } finally { - if (prior === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = prior - } + }) }) +// altimate_change end diff --git a/packages/opencode/test/altimate/mcp-server/stdio.test.ts b/packages/opencode/test/altimate/mcp-server/stdio.test.ts index c1deba34b8..e3b05cbf37 100644 --- a/packages/opencode/test/altimate/mcp-server/stdio.test.ts +++ b/packages/opencode/test/altimate/mcp-server/stdio.test.ts @@ -213,6 +213,7 @@ test("mcp serve skips CLI middleware before starting the agent heap service", as }) // 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") @@ -230,7 +231,7 @@ test("offline CLI announces unavailable workspace tools on stderr and preserves try { await client.connect() const listed = await client.listTools() - expect(Array.isArray(listed.tools)).toBe(true) + 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 { @@ -239,3 +240,4 @@ test("offline CLI announces unavailable workspace tools on stderr and preserves 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 index 14fc812046..127301cfee 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -237,7 +237,7 @@ test("cached local connections never reread credentials offline", async () => { } }) -test("cached remote target survives lost keychain credentials and closes on rejection", async () => { +test("cached remote target is rejected and closed offline without rereading credentials", async () => { const Registry = await import("../../../src/altimate/native/connections/registry") const Credentials = await import("../../../src/altimate/native/connections/credential-store") const driver = await import("@altimateai/drivers/postgres") diff --git a/packages/opencode/test/bun.test.ts b/packages/opencode/test/bun.test.ts index af34897f55..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 () => { @@ -59,7 +60,8 @@ describe("BunProc offline cache", () => { const { spyOn } = await import("bun:test") const prior = process.env.ALTIMATE_OFFLINE const originalCache = Global.Path.cache - const cache = await fs.mkdtemp(path.join(originalCache, "offline-test-")) + 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 () => { @@ -89,7 +91,6 @@ describe("BunProc offline cache", () => { Global.Path.cache = originalCache if (prior === undefined) delete process.env.ALTIMATE_OFFLINE else process.env.ALTIMATE_OFFLINE = prior - await fs.rm(cache, { recursive: true, force: true }) } }) }) diff --git a/packages/opencode/test/config/offline-startup.test.ts b/packages/opencode/test/config/offline-startup.test.ts index 158464e8aa..423ebf0087 100644 --- a/packages/opencode/test/config/offline-startup.test.ts +++ b/packages/opencode/test/config/offline-startup.test.ts @@ -1,16 +1,18 @@ // altimate_change - new file import { expect, test } from "bun:test" import fs from "node:fs/promises" -import os from "node:os" +import { tmpdir } from "../fixture/fixture" import path from "node:path" import { Global } from "../../src/global" import { Offline } from "../../src/config/offline" test("a legacy global TOML config that requests offline mode is detected at startup", async () => { - const project = await fs.mkdtemp(path.join(os.tmpdir(), "offline-legacy-")) + await using tmp = await tmpdir() + const project = tmp.path const legacy = path.join(Global.Path.config, "config") - const previous = process.env.ALTIMATE_OFFLINE - delete process.env.ALTIMATE_OFFLINE + const keys = ["ALTIMATE_OFFLINE", "OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT"] + const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) + for (const key of keys) delete process.env[key] try { await fs.mkdir(Global.Path.config, { recursive: true }) await fs.writeFile(legacy, 'model = "fixture"\noffline = true\n') @@ -19,10 +21,14 @@ test("a legacy global TOML config that requests offline mode is detected at star await expect(Offline.assertStartupPolicy(project)).resolves.toBeUndefined() await fs.writeFile(legacy, "not = [valid toml") await expect(Offline.assertStartupPolicy(project)).resolves.toBeUndefined() + // An unparseable file that plainly requests offline mode still counts. + await fs.writeFile(legacy, "offline = true\nbroken = [\n") + await expect(Offline.assertStartupPolicy(project)).rejects.toThrow("requests offline mode") } finally { await fs.rm(legacy, { force: true }) - await fs.rm(project, { recursive: true, force: true }) - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous + for (const key of keys) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } } }) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 234f7cc074..5f6b57a0b1 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -16,24 +16,25 @@ test("offline local MCP fetch rejects remote requests and redirects before remot for (const key of proxyKeys) delete process.env[key] process.env.NO_PROXY = process.env.no_proxy = "127.0.0.1,localhost" let calls = 0 - const server = Bun.serve({ - hostname: "127.0.0.1", - port: 0, - fetch(request) { - calls++ - return new URL(request.url).pathname === "/redirect" - ? Response.redirect("https://example.com/mcp") - : new Response("local MCP") - }, - }) + let server: ReturnType | undefined try { + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request) { + calls++ + return new URL(request.url).pathname === "/redirect" + ? Response.redirect("https://example.com/mcp") + : new Response("local MCP") + }, + }) const fetch = Offline.localFetch() expect(await (await fetch(server.url)).text()).toBe("local MCP") await expect(fetch(new URL("/redirect", server.url))).rejects.toThrow() await expect(fetch("https://example.com/mcp")).rejects.toThrow("non-local request") expect(calls).toBe(2) } finally { - server.stop(true) + server?.stop(true) for (const key of proxyKeys) { if (savedProxy[key] === undefined) delete process.env[key] else process.env[key] = savedProxy[key] diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index 02d1b7ef86..e7c4f45920 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -48,4 +48,23 @@ 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 + } + }) + // altimate_change end }) From cea796a60135e1849c1db01ba94013d38cb24b3f Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:28:40 -0800 Subject: [PATCH 29/72] chore: mark offline worktree start command change Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/worktree/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 06347a4649..b247e718a8 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -490,13 +490,13 @@ export const layer: Layer.Layer< function* (directory: string, cmd: string) { const [shell, args] = process.platform === "win32" ? ["cmd", ["/c", cmd]] : ["bash", ["-lc", cmd]] const result = yield* appProcess.run( + // altimate_change start — offline mode keeps the user's proxy settings for their start commands ChildProcess.make(shell, args as string[], { cwd: directory, - // altimate_change start — offline mode keeps the user's proxy settings for their start commands ...(Offline.enabled() ? { env: Offline.userEnv({ ...process.env }) as Record, extendEnv: false } : { extendEnv: true }), - // altimate_change end stdin: "ignore", }), + // altimate_change end ) return { code: result.exitCode, stderr: result.stderr.toString("utf8") } }, From 117b1feac7ebc0ad5b01bc9fb14c9337f2c5587a Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:48:02 -0800 Subject: [PATCH 30/72] fix: report offline refusals to API clients Servers answer offline policy refusals (shared-session deletion, a project requesting offline mode) with a 400 and the one-line message instead of a generic 500. Formatters keep the user proxy settings, and a source test follows the bash env change. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/cli/cmd/tool.ts | 2 +- packages/opencode/src/config/offline.ts | 16 ++++++- packages/opencode/src/format/index.ts | 13 +++++- packages/opencode/src/server/middleware.ts | 7 +++ .../instance/httpapi/middleware/error.ts | 11 +++++ packages/opencode/src/server/server.ts | 7 +++ packages/opencode/src/session/index.ts | 2 +- packages/opencode/src/session/session.ts | 2 +- .../question-937-codex.test.ts | 3 +- .../test/session/offline-delete.test.ts | 44 +++++++++++++++++++ 10 files changed, 100 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index 7e6dbab6d4..3bdd5837e9 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -216,7 +216,7 @@ const ToolRunCommand = cmd({ try { const toolArgs = await readArgs(args) const directory = process.cwd() - const workspaceTools = !Offline.enabled() && (await resolveWorkspaceTools(args["workspace-tools"], directory)) + const workspaceTools = await resolveWorkspaceTools(args["workspace-tools"], directory) const daemon = await import("../../altimate/tool-cli/daemon") const reply = !Offline.enabled() && args.daemon && !daemon.daemonDisabled() ? await daemon.runViaDaemon(directory, InstallationVersion, { diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index f8db3ebc94..ac6df3f997 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -66,9 +66,23 @@ async function localOptIn(directory: string) { return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false } +/** A refusal by the offline policy. Servers report it to the client as a 400 with this message. */ +export class OfflinePolicyError extends Error { + override name = "OfflinePolicyError" +} + +/** The policy refusal behind an error, following `cause` links that runtimes add when they wrap it. */ +export function policyError(error: unknown): OfflinePolicyError | undefined { + for (let current = error, depth = 0; current && depth < 8; depth++) { + if (current instanceof OfflinePolicyError) return current + current = (current as { cause?: unknown }).cause + } + return undefined +} + export async function assertStartupPolicy(directory: string) { if (!enabled() && (await localOptIn(directory))) { - throw new Error( + throw new OfflinePolicyError( "This project requests offline mode. Start Altimate Code from the project to apply its offline policy.", ) } diff --git a/packages/opencode/src/format/index.ts b/packages/opencode/src/format/index.ts index d260f3e27e..f33d1a1a78 100644 --- a/packages/opencode/src/format/index.ts +++ b/packages/opencode/src/format/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode user environment +import { Offline } from "@/config/offline" +// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" // altimate_change start — makeRuntime for the restored Promise wrapper (bottom of file) import { makeRuntime } from "@/effect/run-service" @@ -86,10 +89,16 @@ export const layer = Layer.effect( const dir = yield* InstanceState.directory const result = yield* appProcess .run( + // altimate_change start — offline mode keeps the user's proxy settings for formatters ChildProcess.make(replaced[0]!, replaced.slice(1), { cwd: dir, - env: item.environment, - extendEnv: true, + ...(Offline.enabled() + ? { + env: { ...Offline.userEnv({ ...process.env }), ...item.environment } as Record, + extendEnv: false, + } + : { env: item.environment, extendEnv: true }), + // altimate_change end stdin: "ignore", stdout: "ignore", stderr: "ignore", diff --git a/packages/opencode/src/server/middleware.ts b/packages/opencode/src/server/middleware.ts index fc0be01255..a622e5ec00 100644 --- a/packages/opencode/src/server/middleware.ts +++ b/packages/opencode/src/server/middleware.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy refusals +import { Offline } from "@/config/offline" +// altimate_change end import { Provider } from "../provider/provider" import { NamedError } from "@opencode-ai/util/error" import { NotFoundError } from "../storage/db" @@ -29,6 +32,10 @@ export function errorHandler(log: Log.Logger): ErrorHandler { else status = 500 return c.json(err.toObject(), { status }) } + // altimate_change start — offline policy refusals reach the client with their one-line message + const refusal = Offline.policyError(err) + if (refusal) return c.json({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }) + // altimate_change end if (err instanceof Session.BusyError) { return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) } diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts index 21b53aba75..c1312f8b79 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy refusals +import { Offline } from "@/config/offline" +// altimate_change end import { NamedError } from "@opencode-ai/core/util/error" import { ConfigErrorV1 } from "@opencode-ai/core/v1/config/error" import { Cause, Effect } from "effect" @@ -24,6 +27,14 @@ export const errorLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) ) { return Effect.succeed(HttpServerResponse.jsonUnsafe(error.toObject(), { status: 400 })) } + // altimate_change start — offline policy refusals reach the client with their one-line message + const refusal = Offline.policyError(error) + if (refusal) { + return Effect.succeed( + HttpServerResponse.jsonUnsafe({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }), + ) + } + // altimate_change end const ref = `err_${crypto.randomUUID().slice(0, 8)}` diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index 6cdd58c67e..c0fd8ad1da 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy refusals +import { Offline } from "@/config/offline" +// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" import { Log } from "../util/log" @@ -305,6 +308,10 @@ export namespace Server { // altimate_change start — a busy session answers 400 with its message, as the instance routes' handler does // (middleware.ts); everything else unrecognised gets a fixed message and the ref it was logged under, never // the error's text or stack. + // altimate_change start — offline policy refusals reach the client with their one-line message + const refusal = Offline.policyError(err) + if (refusal) return c.json({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }) + // altimate_change end if (err instanceof Session.BusyError) { return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) } diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index 214ef43213..3eafe135be 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -762,7 +762,7 @@ export namespace Session { const id = pending.pop()! tree.push(id) if ((await get(id)).share?.url) - throw new Error("This session is shared. Delete it while online so its share can be revoked.") + throw new Offline.OfflinePolicyError("This session is shared. Delete it while online so its share can be revoked.") pending.push(...(await children(id)).map((child) => child.id)) } // The recursive removal of each descendant skips the scan it has already passed. diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index 42287f056c..245f715a0d 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -682,7 +682,7 @@ export const layer: Layer.Layer< const session = yield* get(sessionID) // altimate_change start — offline mode cannot revoke a public share, so a shared tree is not deleted if (Offline.enabled() && (yield* sharedInTree(sessionID))) - return yield* Effect.die(new Error(OFFLINE_SHARED_SESSION)) + return yield* Effect.die(new Offline.OfflinePolicyError(OFFLINE_SHARED_SESSION)) // altimate_change end try { // `remove` needs to work in all cases, such as broken sessions that diff --git a/packages/opencode/test/release-validation/question-937-codex.test.ts b/packages/opencode/test/release-validation/question-937-codex.test.ts index 3a7deeb244..b6ff066027 100644 --- a/packages/opencode/test/release-validation/question-937-codex.test.ts +++ b/packages/opencode/test/release-validation/question-937-codex.test.ts @@ -365,7 +365,8 @@ describe("release validation PR #937 source-level env plumbing", () => { test("bash tool strips ALTIMATE_NON_INTERACTIVE from child process env but keeps auto-answer env untouched", async () => { const source = await Bun.file(new URL("../../src/tool/bash.ts", import.meta.url)).text() - expect(source).toContain('const mergedEnv: Record = { ...process.env, ...shellEnv.env }') + // Offline mode restores the user's proxy settings on the inherited environment before plugin overrides. + expect(source).toContain('const mergedEnv: Record = { ...Offline.userEnv({ ...process.env }), ...shellEnv.env }') // The stripping moved into `stripHostMarkers` (shared with the shell tool in v0.12.1); // the contract is behavioural now: the non-interactive marker goes, auto-answer stays. expect(source).toContain("stripHostMarkers(mergedEnv)") diff --git a/packages/opencode/test/session/offline-delete.test.ts b/packages/opencode/test/session/offline-delete.test.ts index 668f1b8069..5fccc42939 100644 --- a/packages/opencode/test/session/offline-delete.test.ts +++ b/packages/opencode/test/session/offline-delete.test.ts @@ -5,6 +5,8 @@ import { Instance } from "../../src/project/instance" import { Session } from "../../src/session" import { Database, eq } from "../../src/storage/db" import { Log } from "../../src/util/log" +import { Server } from "../../src/server/server" +import path from "node:path" import { tmpdir } from "../fixture/fixture" Log.init({ print: false }) @@ -37,3 +39,45 @@ test("offline mode refuses to delete a shared session, or its parent, and keeps }, }) }) + +test("the HTTP API reports the offline shared-session refusal as a 400 with its message", async () => { + await using tmp = await tmpdir({ git: true }) + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const session = await Session.create({ title: "shared" }) + Database.use((db) => + db.update(SessionTable).set({ share_url: "https://share.example/s/2" }).where(eq(SessionTable.id, session.id)).run(), + ) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const res = await Server.Default().request(`/session/${session.id}`, { method: "DELETE" }) + const body = await res.text() + expect({ status: res.status, body }).toMatchObject({ status: 400 }) + expect(body).toContain("This session is shared") + expect((await Session.get(session.id)).id).toBe(session.id) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + Database.use((db) => db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, session.id)).run()) + await Session.remove(session.id).catch(() => {}) + }, + }) +}) + +test("a server started online refuses a project that requests offline mode, with the message", async () => { + await using tmp = await tmpdir({ git: true }) + await Bun.write(path.join(tmp.path, "opencode.json"), JSON.stringify({ offline: true })) + const previous = process.env.ALTIMATE_OFFLINE + delete process.env.ALTIMATE_OFFLINE + try { + const res = await Server.Default().request(`/session?directory=${encodeURIComponent(tmp.path)}`) + const body = await res.text() + expect({ status: res.status, body }).toMatchObject({ status: 400 }) + expect(body).toContain("This project requests offline mode") + } finally { + if (previous !== undefined) process.env.ALTIMATE_OFFLINE = previous + } +}) From 17894fadd2e9f61f0e8f270ddaa0c014fe94eeb1 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:04:32 -0800 Subject: [PATCH 31/72] fix: restore proxy settings for every language server offline Restore the user proxy settings on the merged language server env, treat variables missing from a copied env as inherited, report offline share and unshare refusals as a 400, apply the user env to TUI skill checks, allow dbt clean offline, and unnest markers. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/native/dbt/runner.ts | 4 ++-- .../src/altimate/workspace/engine-offer.ts | 4 +--- .../src/altimate/workspace/engine-overlay.ts | 4 +--- .../src/altimate/workspace/skill-sync.ts | 4 +--- packages/opencode/src/config/offline.ts | 5 ++-- packages/opencode/src/lsp/launch.ts | 9 ++++++- packages/opencode/src/mcp/index.ts | 3 +-- .../src/plugin/tui/altimate/skill-ops.tsx | 2 +- packages/opencode/src/server/server.ts | 3 +-- packages/opencode/src/share/session.ts | 6 +++++ packages/opencode/src/share/share-next.ts | 4 ++-- packages/opencode/src/tool/bash.ts | 3 +-- packages/opencode/src/tool/registry.ts | 3 +-- packages/opencode/test/lsp/offline.test.ts | 23 ++++++++++++++++++ .../test/session/offline-delete.test.ts | 24 +++++++++++++++++++ 15 files changed, 76 insertions(+), 25 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index 539397a611..7b9b2d7e90 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -38,8 +38,8 @@ export async function runDbt(params: DbtRunParams): Promise { 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 init` creates a project; there is no profile to check yet. - const checked = command === "init" + // `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 ?? []), diff --git a/packages/opencode/src/altimate/workspace/engine-offer.ts b/packages/opencode/src/altimate/workspace/engine-offer.ts index 888a7c97d5..6d424199f6 100644 --- a/packages/opencode/src/altimate/workspace/engine-offer.ts +++ b/packages/opencode/src/altimate/workspace/engine-offer.ts @@ -1,7 +1,5 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end // altimate_change - new file +import { Offline } from "@/config/offline" // // The install offer for a workspace whose engine is missing or too old. // diff --git a/packages/opencode/src/altimate/workspace/engine-overlay.ts b/packages/opencode/src/altimate/workspace/engine-overlay.ts index f29c2eeb20..71bc3e473e 100644 --- a/packages/opencode/src/altimate/workspace/engine-overlay.ts +++ b/packages/opencode/src/altimate/workspace/engine-overlay.ts @@ -1,7 +1,5 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end // altimate_change - new file +import { Offline } from "@/config/offline" // // The workspace engine overlay. // diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index 2ca3429ada..b70d4e38c1 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -1,7 +1,5 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end // 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. diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index ac6df3f997..75c807cd46 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -104,8 +104,9 @@ export function userEnv>(env: T): T try { const original = JSON.parse(saved) as Record for (const key of ["NO_PROXY", "no_proxy"] as const) { - // Only the inherited bypass is replaced; a value the program's own config set stays. - if (env[key] !== process.env[key]) continue + // Only the inherited bypass is replaced; a value the program's own config set stays. An absent key is + // inherited too: Bun leaves variables assigned after startup out of a `{ ...process.env }` copy. + if (env[key] !== undefined && env[key] !== process.env[key]) continue const value = original[key] if (typeof value === "string") (env as Record)[key] = value else delete env[key] diff --git a/packages/opencode/src/lsp/launch.ts b/packages/opencode/src/lsp/launch.ts index bc6036a111..8ecf777e4f 100644 --- a/packages/opencode/src/lsp/launch.ts +++ b/packages/opencode/src/lsp/launch.ts @@ -16,7 +16,14 @@ export function spawn(cmd: string, argsOrOpts?: string[] | Process.Options, opts // altimate_change start — offline mode keeps the user's proxy settings for language servers // Process.spawn merges process.env underneath, so a removed key is set to undefined (unset) instead. ...(Offline.enabled() && cfg?.env !== null - ? { env: { NO_PROXY: undefined, no_proxy: undefined, ...Offline.userEnv({ ...process.env }), ...cfg?.env } } + ? { + env: { + NO_PROXY: undefined, + no_proxy: undefined, + ALTIMATE_OFFLINE_USER_PROXY: undefined, + ...Offline.userEnv({ ...process.env, ...cfg?.env }), + }, + } : {}), // altimate_change end stdin: "pipe", diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 7067954d47..7aaaacf121 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -1415,9 +1415,8 @@ export const layer = Layer.effect( }) const beginAuth = Effect.fn("MCP.beginAuth")(function* (mcpName: string, token: number) { - // altimate_change start — offline refusal is a client error, not a crash + // Offline refusal is a client error, not a crash. if (Offline.enabled()) return yield* new OfflinePolicyError({ message: "Authenticate MCP servers while online." }) - // altimate_change end const lifecycle = yield* InstanceState.get(state) // altimate_change end const mcpConfig = yield* requireMcpConfig(mcpName) diff --git a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx index b4cfe7059a..2a1b4fa0d6 100644 --- a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx +++ b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx @@ -307,7 +307,7 @@ async function testSkillDirect( const proc = Bun.spawn([tool, "--help"], { stdout: "pipe", stderr: "pipe", - env: { ...process.env, PATH: toolPath }, + env: { ...Offline.userEnv({ ...process.env }), PATH: toolPath }, }) const timeout = setTimeout(() => proc.kill(), 5000) const exitCode = await proc.exited diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index c0fd8ad1da..63a83f642e 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -308,10 +308,9 @@ export namespace Server { // altimate_change start — a busy session answers 400 with its message, as the instance routes' handler does // (middleware.ts); everything else unrecognised gets a fixed message and the ref it was logged under, never // the error's text or stack. - // altimate_change start — offline policy refusals reach the client with their one-line message + // Offline policy refusals reach the client with their one-line message. const refusal = Offline.policyError(err) if (refusal) return c.json({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }) - // altimate_change end if (err instanceof Session.BusyError) { return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) } diff --git a/packages/opencode/src/share/session.ts b/packages/opencode/src/share/session.ts index 3ba70bd7f9..463c435082 100644 --- a/packages/opencode/src/share/session.ts +++ b/packages/opencode/src/share/session.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 { Session } from "@/session/session" import { SessionID } from "@/session/schema" @@ -24,6 +27,9 @@ export const layer = Layer.effect( const flags = yield* RuntimeFlags.Service const share = Effect.fn("SessionShare.share")(function* (sessionID: SessionID) { + // altimate_change start — offline mode refuses sharing with its own message, before the config check + if (Offline.enabled()) return yield* Effect.die(new Offline.OfflinePolicyError("Sharing sessions requires an online run.")) + // altimate_change end const conf = yield* cfg.get() if (conf.share === "disabled") throw new Error("Sharing is disabled in configuration") const result = yield* shareNext.create(sessionID) diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 0a5e663edb..fbaf959d34 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -129,7 +129,7 @@ export namespace ShareNext { export async function create(sessionID: SessionID) { // altimate_change start — skip session sharing in offline mode - if (Offline.enabled()) throw new Error("Sharing sessions requires an online run.") + if (Offline.enabled()) throw new Offline.OfflinePolicyError("Sharing sessions requires an online run.") if (disabled) return { id: "", url: "", secret: "" } // altimate_change end log.info("creating share", { sessionID }) @@ -260,7 +260,7 @@ export namespace ShareNext { export async function remove(sessionID: SessionID) { // altimate_change start — keep the local share state until the server revokes it - if (Offline.enabled()) throw new Error("Offline mode cannot revoke a share. Run unshare while online.") + if (Offline.enabled()) throw new Offline.OfflinePolicyError("Offline mode cannot revoke a share. Run unshare while online.") // altimate_change end if (disabled) return log.info("removing share", { sessionID }) diff --git a/packages/opencode/src/tool/bash.ts b/packages/opencode/src/tool/bash.ts index c0d58c973f..a222787fe0 100644 --- a/packages/opencode/src/tool/bash.ts +++ b/packages/opencode/src/tool/bash.ts @@ -456,9 +456,8 @@ export const BashTool = Tool.define("bash", async () => { ) // altimate_change start — prepend bundled tools dir (ALTIMATE_BIN_DIR) and user tools dirs to PATH - // altimate_change start — offline mode restores the user's proxy settings before plugin overrides + // Offline mode restores the user's proxy settings before plugin overrides. const mergedEnv: Record = { ...Offline.userEnv({ ...process.env }), ...shellEnv.env } - // altimate_change end // Strip the markers that describe this host, not the child. See `stripHostMarkers` // for what each one is and why (PR #937 review, Issue #3, for the first of them). stripHostMarkers(mergedEnv) diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 7295d2de5f..af54edf7d9 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -431,9 +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. - // altimate_change start — keep local tools available in offline sessions + // Offline sessions drop only the tools that contact remote services. const offline = Offline.enabled() - // altimate_change end const builtins = [ InvalidTool, ...(question ? [QuestionTool] : []), diff --git a/packages/opencode/test/lsp/offline.test.ts b/packages/opencode/test/lsp/offline.test.ts index 613b9c9174..99f9d051ab 100644 --- a/packages/opencode/test/lsp/offline.test.ts +++ b/packages/opencode/test/lsp/offline.test.ts @@ -41,3 +41,26 @@ test.skipIf(process.platform === "win32")("offline LSP spawns an npm-cached serv await fs.rm(dir, { recursive: true, force: true }) } }) + +test.skipIf(process.platform === "win32")("offline language servers get the user's proxy exclusions back", async () => { + const { spawn } = await import("../../src/lsp/launch") + const keys = ["ALTIMATE_OFFLINE", "NO_PROXY", "no_proxy", "ALTIMATE_OFFLINE_USER_PROXY"] + const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) + try { + // The state Offline.start leaves: the bypass, plus the user's original values. + process.env.ALTIMATE_OFFLINE = "1" + process.env.ALTIMATE_OFFLINE_USER_PROXY = JSON.stringify({ NO_PROXY: "corp.example" }) + process.env.NO_PROXY = process.env.no_proxy = "*" + for (const opts of [{}, { env: { ...process.env } }]) { + const proc = spawn("sh", ["-c", 'printf "%s|%s|%s" "$NO_PROXY" "$no_proxy" "$ALTIMATE_OFFLINE_USER_PROXY"'], opts) + const out = await new Response(proc.stdout as any).text() + await new Promise((resolve) => proc.once("exit", resolve)) + expect(out).toBe("corp.example||") + } + } finally { + for (const key of keys) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } + } +}) diff --git a/packages/opencode/test/session/offline-delete.test.ts b/packages/opencode/test/session/offline-delete.test.ts index 5fccc42939..c649909a72 100644 --- a/packages/opencode/test/session/offline-delete.test.ts +++ b/packages/opencode/test/session/offline-delete.test.ts @@ -81,3 +81,27 @@ test("a server started online refuses a project that requests offline mode, with if (previous !== undefined) process.env.ALTIMATE_OFFLINE = previous } }) + +test("the HTTP API reports offline share and unshare refusals as a 400 with the message", async () => { + await using tmp = await tmpdir({ git: true }) + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const session = await Session.create({ title: "share" }) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + for (const method of ["POST", "DELETE"]) { + const res = await Server.Default().request(`/session/${session.id}/share`, { method }) + const body = await res.text() + expect({ method, status: res.status, body }).toMatchObject({ status: 400 }) + expect(body).toContain("online") + } + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + await Session.remove(session.id).catch(() => {}) + }, + }) +}) From c527bfa85caab366d7345212c4cfbaaba3905c54 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:25:23 -0800 Subject: [PATCH 32/72] fix: type offline session refusals and close dbt gaps Return typed refusals for offline session deletion and sharing, check session trees once, refuse dbt version flags, templated external roots and libpq destination overrides, scope the pin notice to its tree, honor the target project policy for tool daemon, and run the local datamate repair offline. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 2 +- packages/core/test/git.test.ts | 20 ++++++++++++ .../src/altimate/native/dbt/offline.ts | 3 ++ .../src/altimate/native/dbt/runner.ts | 7 ++++- .../src/altimate/tool-cli/workspace-tools.ts | 9 ++++-- packages/opencode/src/cli/cmd/session.ts | 22 ++++--------- packages/opencode/src/cli/tui/worker.ts | 6 +--- .../opencode/src/control-plane/workspace.ts | 9 +++++- packages/opencode/src/index.ts | 2 ++ .../instance/httpapi/handlers/session.ts | 21 +++++++++++-- packages/opencode/src/session/index.ts | 31 ++++++++++--------- packages/opencode/src/session/prompt.ts | 10 ++++-- packages/opencode/src/session/session.ts | 23 ++++++++++---- packages/opencode/src/share/session.ts | 2 +- packages/opencode/src/share/share-next.ts | 3 +- packages/opencode/src/worktree/index.ts | 4 ++- .../native/offline-connections.test.ts | 24 +++++++++++--- packages/opencode/test/lsp/offline.test.ts | 3 +- packages/opencode/test/mcp/offline.test.ts | 3 ++ 19 files changed, 145 insertions(+), 59 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index f1bceca7f5..823c3fe2a5 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -184,7 +184,7 @@ While still online: - dbt commands, when the selected profile and target point at a local database. - The shell tool, installed language servers, and MCP servers that use stdio or a loopback HTTP(S) URL. - Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and submodule commits. Git LFS files check out from the local LFS cache; a file whose content is not cached fails with a clear error instead of downloading. -- `attach` and `run --attach` to a server on this machine. +- `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 diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index 61ddd012fb..1e9997ce42 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -52,6 +52,26 @@ describe("Git", () => { ), ) + it.live("offline LFS override is read after inherited -c parameters", () => + Effect.sync(() => { + const previous = { offline: process.env.ALTIMATE_OFFLINE, parameters: process.env.GIT_CONFIG_PARAMETERS } + process.env.ALTIMATE_OFFLINE = "1" + process.env.GIT_CONFIG_PARAMETERS = "'lfs.url'='https://inherited.example/'" + try { + const env = localGitEnv()! + expect(env.GIT_CONFIG_PARAMETERS).toBe("'lfs.url'='https://inherited.example/' 'lfs.url'='http://127.0.0.1:9/'") + // Git reads the last value of a key, so the closed loopback endpoint wins. + const read = Bun.spawnSync(["git", "config", "--get", "lfs.url"], { env: { ...process.env, ...env }, stdout: "pipe" }) + expect(read.stdout.toString().trim()).toBe("http://127.0.0.1:9/") + } finally { + if (previous.offline === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous.offline + if (previous.parameters === undefined) delete process.env.GIT_CONFIG_PARAMETERS + else process.env.GIT_CONFIG_PARAMETERS = previous.parameters + } + }), + ) + // Offline Git must not download LFS objects, but objects already in the local cache still check out. const hasLfs = Bun.spawnSync(["git", "lfs", "version"], { stdout: "ignore", stderr: "ignore" }).exitCode === 0 const liveIfLfs = hasLfs ? it.live : it.live.skip diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index 3fcebb4c69..6920ebf344 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -102,6 +102,9 @@ async function checkLocalDbt( assertLocalConnection({ ...output, path: output.path ?? (output.type === "duckdb" ? ":memory:" : undefined) }) } // These profile hooks cause dbt-duckdb to install extensions or open extra connections at startup. + // dbt renders templates after this check, so only a literal path can be judged local. + if (typeof output.external_root === "string" && /\{\{|\{%/.test(output.external_root)) + throw new Error("Offline mode requires a literal local external_root in the dbt profile.") const remoteRoot = typeof output.external_root === "string" && (/^(?:\\\\|\/\/)/.test(output.external_root) || /^[a-z][a-z0-9+.-]*:\/\//i.test(output.external_root)) if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length || diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index 7b9b2d7e90..eeb9ed20e2 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -38,6 +38,9 @@ export async function runDbt(params: DbtRunParams): Promise { 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 @@ -45,8 +48,10 @@ export async function runDbt(params: DbtRunParams): Promise { ...(params.args ?? []), ...(params.project_dir ? ["--project-dir", params.project_dir] : []), ]) + // libpq reads these destinations from the environment, overriding the checked profile host. + const { PGHOSTADDR: _hostaddr, PGSERVICE: _service, PGSERVICEFILE: _serviceFile, ...inherited } = process.env offlineEnv = { - ...process.env, + ...inherited, ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), DBT_SEND_ANONYMOUS_USAGE_STATS: "false", DO_NOT_TRACK: "1", diff --git a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts index e8596b4659..7608754331 100644 --- a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts +++ b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts @@ -23,8 +23,13 @@ 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()) return false + // Workspace tools call the workspace service, which offline mode does not reach. The target project's + // own offline setting applies too (tool daemon --dir can name another project). + await Offline.start(directory) + 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/cli/cmd/session.ts b/packages/opencode/src/cli/cmd/session.ts index a0537adec1..8d1cc37e00 100644 --- a/packages/opencode/src/cli/cmd/session.ts +++ b/packages/opencode/src/cli/cmd/session.ts @@ -3,10 +3,6 @@ import { Effect } from "effect" import { cmd } from "./cmd" import { effectCmd, fail } from "../effect-cmd" import { Session } from "@/session/session" -// altimate_change start — offline shared-session refusal -import { Offline } from "@/config/offline" -import { OFFLINE_SHARED_SESSION } from "@/session/session" -// altimate_change end import { SessionID } from "../../session/schema" import { UI } from "../ui" import { Locale } from "@/util/locale" @@ -64,20 +60,14 @@ export const SessionDeleteCommand = effectCmd({ handler: Effect.fn("Cli.session.delete")(function* (args) { const svc = yield* Session.Service const sessionID = SessionID.make(args.sessionID) - // altimate_change start — offline mode keeps a shared session until its share can be revoked - if (Offline.enabled()) { - const pending = [sessionID] - while (pending.length) { - const id = pending.pop()! - const info = yield* svc.get(id).pipe(Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`))) - if (info.share?.url) return yield* fail(OFFLINE_SHARED_SESSION) - pending.push(...(yield* svc.children(id)).map((child) => child.id)) - } - } - // altimate_change end yield* svc .remove(sessionID) - .pipe(Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`))) + .pipe( + Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`)), + // altimate_change start — offline mode keeps a shared session until its share can be revoked + Effect.catchTag("Session.OfflinePolicyError", (error) => fail(error.message)), + // altimate_change end + ) UI.println(UI.Style.TEXT_SUCCESS_BOLD + `Session ${args.sessionID} deleted` + UI.Style.TEXT_NORMAL) }), }) diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 0a8a73a07f..0115230070 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -73,11 +73,7 @@ Heap.start() // InstanceRuntime.load/Config.get() would otherwise race it (transiently truncated // read) or cache the pre-heal entry, making the first session spawn the broken // config anyway. Errors are swallowed: a failed sync must never block the TUI. -// altimate_change start — offline mode skips the IDE workspace engine sync -const datamateSyncReady: Promise = Offline.enabled() - ? Promise.resolve() - : syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) -// altimate_change end +const datamateSyncReady: Promise = syncDatamateUrlFromVscodeMcp(process.cwd()).catch(() => {}) // altimate_change end const traceConsumer = new TraceConsumer() diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index ff0af53f9a..2bdd01a649 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -809,7 +809,14 @@ export const layer = Layer.effect( yield* Effect.forEach( sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)), (sessionInfo) => - session.remove(sessionInfo.id).pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.void)), + session.remove(sessionInfo.id).pipe( + Effect.catchIf(NotFoundError.isInstance, () => Effect.void), + // altimate_change start — offline mode keeps a shared session (its share cannot be revoked offline) + Effect.catchTag("Session.OfflinePolicyError", (error) => + Effect.logWarning("kept a shared session while offline", { sessionID: sessionInfo.id, error: error.message }), + ), + // altimate_change end + ), { discard: true }, ) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index f7e43e5975..22416f0ea4 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -200,6 +200,8 @@ let cli = yargs(args) (["providers", "auth", "console"].includes(command) && opts._[1] === "login") || (command === "mcp" && opts._[1] === "auth") )) throw new Error("This command requires network access. Run it while online.") + if (Offline.enabled() && attachURL) + process.stderr.write("Offline mode: the attached server applies its own network policy; start it with offline mode too.\n") // altimate_change end Heap.start() diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts index 6281b7c9d9..766433e2d6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline policy refusals +import { Offline } from "@/config/offline" +// altimate_change end import { PermissionV1 } from "@opencode-ai/core/v1/permission" import { Agent } from "@/agent/agent" import { SessionV1 } from "@opencode-ai/core/v1/session" @@ -203,7 +206,13 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", }) const remove = Effect.fn("SessionHttpApi.remove")(function* (ctx: { params: { sessionID: SessionID } }) { - yield* SessionError.mapStorageNotFound(session.remove(ctx.params.sessionID)) + yield* SessionError.mapStorageNotFound( + // altimate_change start — the offline refusal reaches the client as a 400 with its message (error middleware) + session + .remove(ctx.params.sessionID) + .pipe(Effect.catchTag("Session.OfflinePolicyError", (error) => Effect.die(new Offline.OfflinePolicyError(error.message)))), + // altimate_change end + ) return true }) @@ -285,7 +294,15 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", // every failure to a 400 BadRequest. const share = Effect.fn("SessionHttpApi.share")(function* (ctx: { params: { sessionID: SessionID } }) { yield* requireSession(ctx.params.sessionID) - yield* shareSvc.share(ctx.params.sessionID).pipe(Effect.mapError(() => new HttpApiError.InternalServerError({}))) + yield* shareSvc.share(ctx.params.sessionID).pipe( + // altimate_change start — the offline refusal reaches the client as a 400 with its message (error middleware) + Effect.catchIf( + (error): error is Session.OfflinePolicyError => error instanceof Session.OfflinePolicyError, + (error) => Effect.die(new Offline.OfflinePolicyError(error.message)), + ), + // altimate_change end + Effect.mapError(() => new HttpApiError.InternalServerError({})), + ) return yield* requireSession(ctx.params.sessionID) }) diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index 3eafe135be..33cfca276f 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -748,31 +748,34 @@ export namespace Session { return rows.map(fromRow) }) - // altimate_change start — descendants already checked by an offline removal of their ancestor - const offlineTreeChecked = new Set() - // altimate_change end + // altimate_change start — offline mode cannot revoke a public share, so it refuses to delete a shared + // session (or one with a shared descendant) before anything is removed; the tree is checked once export const remove = fn(SessionID.zod, async (sessionID) => { - const project = Instance.project - // altimate_change start — offline mode cannot revoke a public share, so it refuses to delete a shared - // session (or one with a shared descendant) before anything is removed - if (Offline.enabled() && !offlineTreeChecked.delete(sessionID)) { - const tree: SessionID[] = [] + if (Offline.enabled()) { const pending = [sessionID] while (pending.length) { const id = pending.pop()! - tree.push(id) - if ((await get(id)).share?.url) + // A missing root behaves as online (logged by removeTree); other read failures stop the removal. + const info = await get(id).catch((error) => { + if (id === sessionID && NotFoundError.isInstance(error)) return undefined + throw error + }) + if (!info) break + if (info.share?.url) throw new Offline.OfflinePolicyError("This session is shared. Delete it while online so its share can be revoked.") pending.push(...(await children(id)).map((child) => child.id)) } - // The recursive removal of each descendant skips the scan it has already passed. - for (const id of tree.slice(1)) offlineTreeChecked.add(id) } + await removeTree(sessionID) + }) + + async function removeTree(sessionID: SessionID): Promise { // altimate_change end + const project = Instance.project try { const session = await get(sessionID) for (const child of await children(sessionID)) { - await remove(child.id) + await removeTree(child.id) } await unshare(sessionID).catch(() => {}) // altimate_change start — release only the deleted session's scratch store @@ -790,7 +793,7 @@ export namespace Session { } catch (e) { log.error(e) } - }) + } export const updateMessage = fn(MessageV2.Info, async (msg) => { const time_created = msg.time.created diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 8713b790ff..d5d68aa4ea 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -491,9 +491,13 @@ export namespace SessionPrompt { } const binding = snapshot ? null : await resolveBindingOutcome(dir) // Only a project that uses a workspace hears about workspace skills. - const { readPin } = await import("../altimate/workspace/pin") - if (snapshot || binding?.status === "bound" || readPin().kind === "valid") { - const empty = binding?.status === "bound" && await snapshotKnownEmpty(dir, binding.binding.datamateId) + // A serve pin counts only for the tree it was launched for. + const { readPin, resolveWithinRoot } = await import("../altimate/workspace/pin") + const pin = readPin() + const pinned = pin.kind === "valid" && resolveWithinRoot(dir, pin.root) !== null ? pin.datamateId : undefined + const datamateId = binding?.status === "bound" ? binding.binding.datamateId : pinned + if (snapshot || datamateId !== undefined) { + const empty = datamateId !== undefined && (await snapshotKnownEmpty(dir, datamateId)) await Offline.announce(snapshot !== null, empty) } await refreshSkillRegistry(dir) diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index 245f715a0d..1a4f9431f0 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -472,6 +472,11 @@ export class BusyError extends Schema.TaggedErrorClass()("SessionBusy export type NotFound = NotFoundError // altimate_change start — offline shared-session refusal export const OFFLINE_SHARED_SESSION = "This session is shared. Delete it while online so its share can be revoked." +export class OfflinePolicyError extends Schema.TaggedErrorClass()( + "Session.OfflinePolicyError", + { message: Schema.String }, + { httpApiStatus: 400 }, +) {} // altimate_change end export interface Interface { @@ -505,7 +510,9 @@ export interface Interface { readonly diff: (sessionID: SessionID) => Effect.Effect readonly messages: (input: { sessionID: SessionID; limit?: number }) => Effect.Effect readonly children: (parentID: SessionID) => Effect.Effect - readonly remove: (sessionID: SessionID) => Effect.Effect + // altimate_change start — offline mode refuses to delete a shared session + readonly remove: (sessionID: SessionID) => Effect.Effect + // altimate_change end readonly updateMessage: (msg: T) => Effect.Effect readonly removeMessage: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect readonly removePart: (input: { sessionID: SessionID; messageID: MessageID; partID: PartID }) => Effect.Effect @@ -678,12 +685,16 @@ export const layer: Layer.Layer< }) // altimate_change end + // altimate_change start — offline mode cannot revoke a public share: check the whole tree once, then remove const remove: Interface["remove"] = Effect.fnUntraced(function* (sessionID: SessionID) { - const session = yield* get(sessionID) - // altimate_change start — offline mode cannot revoke a public share, so a shared tree is not deleted if (Offline.enabled() && (yield* sharedInTree(sessionID))) - return yield* Effect.die(new Offline.OfflinePolicyError(OFFLINE_SHARED_SESSION)) - // altimate_change end + return yield* new OfflinePolicyError({ message: OFFLINE_SHARED_SESSION }) + yield* removeTree(sessionID) + }) + // altimate_change end + + const removeTree = Effect.fnUntraced(function* (sessionID: SessionID): Effect.fn.Return { + const session = yield* get(sessionID) try { // `remove` needs to work in all cases, such as broken sessions that // run cleanup without instance state. @@ -695,7 +706,7 @@ export const layer: Layer.Layer< if (hasInstance) yield* cancelBackgroundJobs(background, sessionID) const kids = yield* children(sessionID) for (const child of kids) { - yield* remove(child.id) + yield* removeTree(child.id) } // altimate_change start — release only the deleted session's scratch store diff --git a/packages/opencode/src/share/session.ts b/packages/opencode/src/share/session.ts index 463c435082..32bb8bd40c 100644 --- a/packages/opencode/src/share/session.ts +++ b/packages/opencode/src/share/session.ts @@ -28,7 +28,7 @@ export const layer = Layer.effect( const share = Effect.fn("SessionShare.share")(function* (sessionID: SessionID) { // altimate_change start — offline mode refuses sharing with its own message, before the config check - if (Offline.enabled()) return yield* Effect.die(new Offline.OfflinePolicyError("Sharing sessions requires an online run.")) + if (Offline.enabled()) return yield* new Session.OfflinePolicyError({ message: "Sharing sessions requires an online run." }) // altimate_change end const conf = yield* cfg.get() if (conf.share === "disabled") throw new Error("Sharing is disabled in configuration") diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index fbaf959d34..142eea5aac 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -260,7 +260,8 @@ export namespace ShareNext { export async function remove(sessionID: SessionID) { // altimate_change start — keep the local share state until the server revokes it - if (Offline.enabled()) throw new Offline.OfflinePolicyError("Offline mode cannot revoke a share. Run unshare while online.") + if (Offline.enabled()) + throw new Offline.OfflinePolicyError("Offline mode cannot revoke a share. Run unshare while online.") // altimate_change end if (disabled) return log.info("removing share", { sessionID }) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index b247e718a8..2c0eafede9 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -493,7 +493,9 @@ export const layer: Layer.Layer< // altimate_change start — offline mode keeps the user's proxy settings for their start commands ChildProcess.make(shell, args as string[], { cwd: directory, - ...(Offline.enabled() ? { env: Offline.userEnv({ ...process.env }) as Record, extendEnv: false } : { extendEnv: true }), + ...(Offline.enabled() + ? { env: Offline.userEnv({ ...process.env }) as Record, extendEnv: false } + : { extendEnv: true }), stdin: "ignore", }), // 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 index 127301cfee..4bafa46f0c 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -112,15 +112,31 @@ test.skipIf(process.platform === "win32")("offline dbt runs with the checked pro 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\"\n", { mode: 0o755 }) + await fs.writeFile(path.join(bin, "dbt"), "#!/bin/sh\necho \"$DBT_PROFILES_DIR|$DBT_VERSION_CHECK|$DBT_SEND_ANONYMOUS_USAGE_STATS|$DO_NOT_TRACK|$PGHOSTADDR\"\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.exit_code).toBe(0) - expect(result.stdout.trim()).toBe(`${root}|false|false`) + const previousHostaddr = process.env.PGHOSTADDR + process.env.PGHOSTADDR = "198.51.100.20" + try { + const result = await runDbt({ command: "ls", project_dir: root, args: ["--profiles-dir", root] }) + expect(result.exit_code).toBe(0) + // libpq's destination override is dropped; usage reporting and the version check are off. + expect(result.stdout.trim()).toBe(`${root}|false|false|1|`) + } finally { + if (previousHostaddr === undefined) delete process.env.PGHOSTADDR + else process.env.PGHOSTADDR = previousHostaddr + } expect((await runDbt({ command: "deps", project_dir: root })).stderr).toContain("Offline mode") + expect((await runDbt({ command: "ls", project_dir: root, args: ["--send-anonymous-usage-stats"] })).stderr).toContain( + "Offline mode disables dbt usage reporting.", + ) + expect((await runDbt({ command: "init", args: ["--version"] })).stderr).toContain("Offline mode disables dbt version reporting.") + // `dbt init` needs no existing project or profile. + const empty = path.join(root, "new") + await fs.mkdir(empty) + expect((await runDbt({ command: "init", project_dir: empty })).exit_code).toBe(0) } finally { process.env.PATH = previousPath await fs.rm(root, { recursive: true, force: true }) diff --git a/packages/opencode/test/lsp/offline.test.ts b/packages/opencode/test/lsp/offline.test.ts index 99f9d051ab..44cbbc3115 100644 --- a/packages/opencode/test/lsp/offline.test.ts +++ b/packages/opencode/test/lsp/offline.test.ts @@ -53,8 +53,9 @@ test.skipIf(process.platform === "win32")("offline language servers get the user process.env.NO_PROXY = process.env.no_proxy = "*" for (const opts of [{}, { env: { ...process.env } }]) { const proc = spawn("sh", ["-c", 'printf "%s|%s|%s" "$NO_PROXY" "$no_proxy" "$ALTIMATE_OFFLINE_USER_PROXY"'], opts) + const exited = proc.exited const out = await new Response(proc.stdout as any).text() - await new Promise((resolve) => proc.once("exit", resolve)) + await exited expect(out).toBe("corp.example||") } } finally { diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 5f6b57a0b1..bcab6c3759 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -54,6 +54,9 @@ test("user programs get their own proxy exclusions back, not the offline bypass" expect(env.no_proxy).toBeUndefined() expect(env.ALTIMATE_OFFLINE_USER_PROXY).toBeUndefined() expect(env.PATH).toBe("/bin") + // A copied env that lacks the key (Bun omits variables assigned after startup) still gets the saved value. + const copy: Record = { PATH: "/bin" } + expect(Offline.userEnv(copy).NO_PROXY).toBe("corp.example") // A value the program's own configuration set is kept. expect(Offline.userEnv({ ...process.env, NO_PROXY: "mcp.local" }).NO_PROXY).toBe("mcp.local") // Without offline state, the environment is unchanged. From 43607e4ea7a6d8470b5d0a475e55afd9760685b6 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:28:29 -0800 Subject: [PATCH 33/72] fix: refuse offline sharing before the config check The legacy share path reports the offline refusal as a 400 even when the offline config has already disabled sharing; mark the recursive session removal. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/session/index.ts | 3 ++ packages/opencode/src/session/session.ts | 2 ++ .../test/session/offline-delete.test.ts | 29 ++++++++++--------- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index 33cfca276f..a48517ed25 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -428,6 +428,9 @@ export namespace Session { }) export const share = fn(SessionID.zod, async (id) => { + // altimate_change start — offline mode refuses sharing with its own message, before the config check + if (Offline.enabled()) throw new Offline.OfflinePolicyError("Sharing sessions requires an online run.") + // altimate_change end const cfg = await Config.get() if (cfg.share === "disabled") { throw new Error("Sharing is disabled in configuration") diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index 1a4f9431f0..8ac9d6d56d 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -706,7 +706,9 @@ export const layer: Layer.Layer< if (hasInstance) yield* cancelBackgroundJobs(background, sessionID) const kids = yield* children(sessionID) for (const child of kids) { + // altimate_change start — recurse without repeating the offline tree check yield* removeTree(child.id) + // altimate_change end } // altimate_change start — release only the deleted session's scratch store diff --git a/packages/opencode/test/session/offline-delete.test.ts b/packages/opencode/test/session/offline-delete.test.ts index c649909a72..40d85fea7e 100644 --- a/packages/opencode/test/session/offline-delete.test.ts +++ b/packages/opencode/test/session/offline-delete.test.ts @@ -84,24 +84,25 @@ test("a server started online refuses a project that requests offline mode, with test("the HTTP API reports offline share and unshare refusals as a 400 with the message", async () => { await using tmp = await tmpdir({ git: true }) - await Instance.provide({ - directory: tmp.path, - fn: async () => { - const session = await Session.create({ title: "share" }) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { + // Offline from the start, as in a real offline process: the config is loaded with sharing disabled. + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const session = await Session.create({ title: "share" }) for (const method of ["POST", "DELETE"]) { const res = await Server.Default().request(`/session/${session.id}/share`, { method }) const body = await res.text() expect({ method, status: res.status, body }).toMatchObject({ status: 400 }) expect(body).toContain("online") } - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - await Session.remove(session.id).catch(() => {}) - }, - }) + await Session.remove(session.id).catch(() => {}) + }, + }) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } }) From 4f178f4d910a15d09e72ce033b782486e7788d0a Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:43:28 -0800 Subject: [PATCH 34/72] fix: declare offline session refusals in the API contract The session delete, share and unshare endpoints declare the offline refusal as a 400 error, the dbt adapter drops libpq destination overrides offline, and the LFS override uses the parameter form older Git versions accept. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/git.ts | 2 +- packages/core/test/git.test.ts | 2 +- packages/dbt-tools/src/adapter.ts | 4 +++ packages/opencode/src/config/offline.ts | 2 +- .../routes/instance/httpapi/groups/session.ts | 12 ++++++-- .../instance/httpapi/handlers/session.ts | 29 +++++++++++-------- 6 files changed, 33 insertions(+), 18 deletions(-) diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index df0003b737..27006eee0c 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -30,7 +30,7 @@ export function localGitEnv(env?: Record) { GIT_CONFIG_COUNT: String(index + 1), [`GIT_CONFIG_KEY_${index}`]: "lfs.url", [`GIT_CONFIG_VALUE_${index}`]: OFFLINE_LFS_URL, - ...(parameters ? { GIT_CONFIG_PARAMETERS: `${parameters} 'lfs.url'='${OFFLINE_LFS_URL}'` } : {}), + ...(parameters ? { GIT_CONFIG_PARAMETERS: `${parameters} 'lfs.url=${OFFLINE_LFS_URL}'` } : {}), } } diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index 1e9997ce42..7006aa4362 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -59,7 +59,7 @@ describe("Git", () => { process.env.GIT_CONFIG_PARAMETERS = "'lfs.url'='https://inherited.example/'" try { const env = localGitEnv()! - expect(env.GIT_CONFIG_PARAMETERS).toBe("'lfs.url'='https://inherited.example/' 'lfs.url'='http://127.0.0.1:9/'") + expect(env.GIT_CONFIG_PARAMETERS).toBe("'lfs.url'='https://inherited.example/' 'lfs.url=http://127.0.0.1:9/'") // Git reads the last value of a key, so the closed loopback endpoint wins. const read = Bun.spawnSync(["git", "config", "--get", "lfs.url"], { env: { ...process.env, ...env }, stdout: "pipe" }) expect(read.stdout.toString().trim()).toBe("http://127.0.0.1:9/") diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 42fca5af31..718773944b 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -104,6 +104,10 @@ function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" vars.DO_NOT_TRACK = "1" vars.DBT_VERSION_CHECK = "false" + // libpq reads these destinations from the environment, overriding the checked profile host. + delete vars.PGHOSTADDR + delete vars.PGSERVICE + delete vars.PGSERVICEFILE } if (options.profilesDir) vars.DBT_PROFILES_DIR = options.profilesDir if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 75c807cd46..415b617fe6 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -105,7 +105,7 @@ export function userEnv>(env: T): T const original = JSON.parse(saved) as Record for (const key of ["NO_PROXY", "no_proxy"] as const) { // Only the inherited bypass is replaced; a value the program's own config set stays. An absent key is - // inherited too: Bun leaves variables assigned after startup out of a `{ ...process.env }` copy. + // treated as inherited too, since a copied environment may not carry it. if (env[key] !== undefined && env[key] !== process.env[key]) continue const value = original[key] if (typeof value === "string") (env as Record)[key] = value diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts index 7d951a62e5..00ae842ce4 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts @@ -318,7 +318,9 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, success: described(Schema.Boolean, "Successfully deleted session"), - error: [HttpApiError.BadRequest, ApiNotFoundError], + // altimate_change start — offline refusal is a declared client error + error: [HttpApiError.BadRequest, ApiNotFoundError, Session.OfflinePolicyError], + // altimate_change end }).annotateMerge( OpenApi.annotations({ identifier: "session.delete", @@ -382,7 +384,9 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, success: described(Session.Info, "Successfully shared session"), - error: [HttpApiError.InternalServerError, ApiNotFoundError], + // altimate_change start — offline refusal is a declared client error + error: [HttpApiError.InternalServerError, ApiNotFoundError, Session.OfflinePolicyError], + // altimate_change end }).annotateMerge( OpenApi.annotations({ identifier: "session.share", @@ -394,7 +398,9 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, success: described(Session.Info, "Successfully unshared session"), - error: [HttpApiError.InternalServerError, ApiNotFoundError], + // altimate_change start — offline refusal is a declared client error + error: [HttpApiError.InternalServerError, ApiNotFoundError, Session.OfflinePolicyError], + // altimate_change end }).annotateMerge( OpenApi.annotations({ identifier: "session.unshare", diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts index 766433e2d6..ff8169f07e 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts @@ -206,13 +206,16 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", }) const remove = Effect.fn("SessionHttpApi.remove")(function* (ctx: { params: { sessionID: SessionID } }) { - yield* SessionError.mapStorageNotFound( - // altimate_change start — the offline refusal reaches the client as a 400 with its message (error middleware) - session - .remove(ctx.params.sessionID) - .pipe(Effect.catchTag("Session.OfflinePolicyError", (error) => Effect.die(new Offline.OfflinePolicyError(error.message)))), - // altimate_change end - ) + // altimate_change start — the declared offline refusal passes through as a 400 with its message + yield* session + .remove(ctx.params.sessionID) + .pipe( + Effect.catchIf( + (error): error is Session.NotFound => !(error instanceof Session.OfflinePolicyError), + (error) => SessionError.mapStorageNotFound(Effect.fail(error)), + ), + ) + // altimate_change end return true }) @@ -295,19 +298,21 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", const share = Effect.fn("SessionHttpApi.share")(function* (ctx: { params: { sessionID: SessionID } }) { yield* requireSession(ctx.params.sessionID) yield* shareSvc.share(ctx.params.sessionID).pipe( - // altimate_change start — the offline refusal reaches the client as a 400 with its message (error middleware) - Effect.catchIf( - (error): error is Session.OfflinePolicyError => error instanceof Session.OfflinePolicyError, - (error) => Effect.die(new Offline.OfflinePolicyError(error.message)), + // altimate_change start — the declared offline refusal passes through as a 400 with its message + Effect.mapError((error) => + error instanceof Session.OfflinePolicyError ? error : new HttpApiError.InternalServerError({}), ), // altimate_change end - Effect.mapError(() => new HttpApiError.InternalServerError({})), ) return yield* requireSession(ctx.params.sessionID) }) const unshare = Effect.fn("SessionHttpApi.unshare")(function* (ctx: { params: { sessionID: SessionID } }) { yield* requireSession(ctx.params.sessionID) + // altimate_change start — offline mode cannot revoke a share; the declared refusal is a 400 with its message + if (Offline.enabled()) + return yield* new Session.OfflinePolicyError({ message: "Offline mode cannot revoke a share. Run unshare while online." }) + // altimate_change end yield* shareSvc .unshare(ctx.params.sessionID) .pipe(Effect.mapError(() => new HttpApiError.InternalServerError({}))) From a7b56d1a71a0cb105a26696c3193c14143942223 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:47:16 -0800 Subject: [PATCH 35/72] test: cover offline workspace tools and templated dbt roots Co-Authored-By: Claude Opus 5.5 --- .../native/offline-connections.test.ts | 8 ++++++- .../test/altimate/tool-cli/offline.test.ts | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 packages/opencode/test/altimate/tool-cli/offline.test.ts diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 4bafa46f0c..aa4c1eea99 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -96,7 +96,13 @@ test("dbt-duckdb profiles that reach remote storage or a remote server are refus const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-duckdb-")) try { await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: test\n") - for (const extra of ["external_root: s3://bucket/x", "remote:\n host: db.example.com", "filesystems:\n - fs: s3"]) { + for (const extra of [ + "external_root: s3://bucket/x", + "external_root: \"{{ var('root') }}\"", + "external_root: \"{{ env_var('OFFLINE_TEST_UNSET_ROOT') }}\"", + "remote:\n host: db.example.com", + "filesystems:\n - fs: s3", + ]) { await fs.writeFile(path.join(root, "profiles.yml"), `test:\n outputs:\n default:\n type: duckdb\n path: local.duckdb\n ${extra}\n`) await expect(assertLocalDbt(root, ["--profiles-dir", root])).rejects.toThrow("Offline mode") } 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) +}) From 65818489addcde5f0b6ee922d42deb9bf56a32aa Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:56:39 -0800 Subject: [PATCH 36/72] fix: reset offline worktrees with unpopulated submodules Offline reset updates only the submodules this worktree already checked out, so a submodule it never cloned no longer fails the reset with a transport error. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/worktree/index.ts | 22 ++++++++---- .../opencode/test/project/worktree.test.ts | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 2c0eafede9..f09eb378ce 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -613,12 +613,22 @@ export const layer: Layer.Layer< } // altimate_change start — update existing submodules from objects already on disk offline - const submoduleMode = Offline.enabled() ? "--no-fetch" : "--init" - yield* gitExpect( - ["submodule", "update", submoduleMode, "--recursive", "--force"], - { cwd: worktreePath }, - (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), - ) + // A submodule this worktree never checked out would need a clone, so offline updates only the present ones + // (`git submodule status` marks the others with a leading "-"). + const offlineSubmodules = Offline.enabled() + ? (yield* git(["submodule", "status"], { cwd: worktreePath })).text + .split("\n") + .filter((line) => line.trim() && !line.startsWith("-")) + .map((line) => line.trim().split(/\s+/)[1]!) + : undefined + if (!offlineSubmodules || offlineSubmodules.length > 0) + yield* gitExpect( + offlineSubmodules + ? ["submodule", "update", "--no-fetch", "--recursive", "--force", "--", ...offlineSubmodules] + : ["submodule", "update", "--init", "--recursive", "--force"], + { cwd: worktreePath }, + (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), + ) // altimate_change end yield* gitExpect( diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index db875e4c8e..2c788a52fa 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -106,6 +106,40 @@ describe("Worktree", () => { { git: true }, ) + // altimate_change start — offline reset with a submodule this worktree never checked out + it.instance( + "resets an offline worktree whose repository has a submodule it never checked out", + Effect.gen(function* () { + const { directory } = yield* TestInstance + const run = (cwd: string, args: string[]) => { + const result = Bun.spawnSync(["git", "-c", "protocol.file.allow=always", ...args], { cwd, stdout: "pipe", stderr: "pipe" }) + if (result.exitCode !== 0) throw new Error(result.stderr.toString()) + } + const lib = path.join(path.dirname(directory), `${path.basename(directory)}-lib`) + Bun.spawnSync(["mkdir", "-p", lib]) + for (const args of [["init", "-q"], ["config", "user.email", "t@example.com"], ["config", "user.name", "t"], ["config", "commit.gpgsign", "false"], ["commit", "-q", "--allow-empty", "-m", "lib"]]) + run(lib, args) + run(directory, ["submodule", "add", "-q", lib, "lib"]) + run(directory, ["commit", "-q", "-m", "add submodule"]) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + const svc = yield* Worktree.Service + yield* withCreatedWorktree({ name: "offline-submodule" }, ({ info }) => + Effect.gen(function* () { + expect(yield* svc.reset({ directory: info.directory })).toBe(true) + }), + ) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + Bun.spawnSync(["rm", "-rf", lib]) + } + }), + { git: true }, + ) + // altimate_change end + describe("makeWorktreeInfo", () => { it.instance( "returns info with name, branch, and directory", From c25ebbfa5374c461b175bfda6f5c34895343cfce Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:00:09 -0800 Subject: [PATCH 37/72] fix: refuse offline unshare in the service and share the libpq list SessionShare.unshare returns the typed offline refusal, the dbt runner and adapter share one list of libpq destination variables, and an HttpApi test covers the declared offline 400s. Co-Authored-By: Claude Opus 5.5 --- packages/dbt-tools/src/adapter.ts | 6 +-- packages/dbt-tools/src/offline-env.ts | 4 ++ .../src/altimate/native/dbt/runner.ts | 5 ++- .../instance/httpapi/handlers/session.ts | 17 ++++---- packages/opencode/src/share/session.ts | 4 ++ .../server/httpapi-session-offline.test.ts | 42 +++++++++++++++++++ 6 files changed, 62 insertions(+), 16 deletions(-) create mode 100644 packages/dbt-tools/src/offline-env.ts create mode 100644 packages/opencode/test/server/httpapi-session-offline.test.ts diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 718773944b..574d97a4da 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -1,4 +1,5 @@ import type { Config } from "./config" +import { LIBPQ_DESTINATION_VARS } from "./offline-env" import { bufferLog } from "./log-buffer" import { recordManifest } from "./stale-manifest" export { getRecentDbtLogs, clearDbtLogs } from "./log-buffer" @@ -104,10 +105,7 @@ function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" vars.DO_NOT_TRACK = "1" vars.DBT_VERSION_CHECK = "false" - // libpq reads these destinations from the environment, overriding the checked profile host. - delete vars.PGHOSTADDR - delete vars.PGSERVICE - delete vars.PGSERVICEFILE + for (const name of LIBPQ_DESTINATION_VARS) delete vars[name] } if (options.profilesDir) vars.DBT_PROFILES_DIR = options.profilesDir if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath diff --git a/packages/dbt-tools/src/offline-env.ts b/packages/dbt-tools/src/offline-env.ts new file mode 100644 index 0000000000..110e80de73 --- /dev/null +++ b/packages/dbt-tools/src/offline-env.ts @@ -0,0 +1,4 @@ +// altimate_change - new file +// libpq reads these connection destinations from the environment, overriding the profile host that offline +// mode checked. Offline dbt runs drop them. +export const LIBPQ_DESTINATION_VARS = ["PGHOSTADDR", "PGSERVICE", "PGSERVICEFILE"] as const diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index eeb9ed20e2..511851c615 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -1,6 +1,7 @@ // altimate_change start — validate offline dbt targets before spawning dbt import { Offline } from "@/config/offline" import { assertLocalDbt } from "./offline" +import { LIBPQ_DESTINATION_VARS } from "../../../../../dbt-tools/src/offline-env" // altimate_change end /** * dbt CLI wrapper — spawn dbt commands as subprocesses. @@ -48,8 +49,8 @@ export async function runDbt(params: DbtRunParams): Promise { ...(params.args ?? []), ...(params.project_dir ? ["--project-dir", params.project_dir] : []), ]) - // libpq reads these destinations from the environment, overriding the checked profile host. - const { PGHOSTADDR: _hostaddr, PGSERVICE: _service, PGSERVICEFILE: _serviceFile, ...inherited } = process.env + const inherited = { ...process.env } + for (const name of LIBPQ_DESTINATION_VARS) delete inherited[name] offlineEnv = { ...inherited, ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts index ff8169f07e..9bd3680dc1 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy refusals -import { Offline } from "@/config/offline" -// altimate_change end import { PermissionV1 } from "@opencode-ai/core/v1/permission" import { Agent } from "@/agent/agent" import { SessionV1 } from "@opencode-ai/core/v1/session" @@ -309,13 +306,13 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", const unshare = Effect.fn("SessionHttpApi.unshare")(function* (ctx: { params: { sessionID: SessionID } }) { yield* requireSession(ctx.params.sessionID) - // altimate_change start — offline mode cannot revoke a share; the declared refusal is a 400 with its message - if (Offline.enabled()) - return yield* new Session.OfflinePolicyError({ message: "Offline mode cannot revoke a share. Run unshare while online." }) - // altimate_change end - yield* shareSvc - .unshare(ctx.params.sessionID) - .pipe(Effect.mapError(() => new HttpApiError.InternalServerError({}))) + yield* shareSvc.unshare(ctx.params.sessionID).pipe( + // altimate_change start — the declared offline refusal passes through as a 400 with its message + Effect.mapError((error) => + error instanceof Session.OfflinePolicyError ? error : new HttpApiError.InternalServerError({}), + ), + // altimate_change end + ) return yield* requireSession(ctx.params.sessionID) }) diff --git a/packages/opencode/src/share/session.ts b/packages/opencode/src/share/session.ts index 32bb8bd40c..9f28b33328 100644 --- a/packages/opencode/src/share/session.ts +++ b/packages/opencode/src/share/session.ts @@ -38,6 +38,10 @@ export const layer = Layer.effect( }) const unshare = Effect.fn("SessionShare.unshare")(function* (sessionID: SessionID) { + // altimate_change start — offline mode cannot revoke a share; typed refusal, local state kept + if (Offline.enabled()) + return yield* new Session.OfflinePolicyError({ message: "Offline mode cannot revoke a share. Run unshare while online." }) + // altimate_change end yield* shareNext.remove(sessionID) yield* session.setShare({ sessionID, share: undefined }) }) diff --git a/packages/opencode/test/server/httpapi-session-offline.test.ts b/packages/opencode/test/server/httpapi-session-offline.test.ts new file mode 100644 index 0000000000..9b2d532971 --- /dev/null +++ b/packages/opencode/test/server/httpapi-session-offline.test.ts @@ -0,0 +1,42 @@ +// altimate_change - new file +import { describe, expect } from "bun:test" +import { Effect } from "effect" +import { SessionTable } from "@opencode-ai/core/session/sql" +import { Database, eq } from "../../src/storage/db" +import { TestInstance } from "../fixture/fixture" +import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" + +const it = testEffect(httpApiLayer) + +describe("session HttpApi offline", () => { + it.instance("declares the offline refusals for delete, share and unshare as 400s", () => + Effect.gen(function* () { + const tmp = yield* TestInstance + const created = yield* requestInDirectory("/session", tmp.directory, { + method: "POST", + headers: { "content-type": "application/json" }, + body: "{}", + }) + const session = (yield* created.json) as { id: string } + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + for (const method of ["POST", "DELETE"]) { + const response = yield* requestInDirectory(`/session/${session.id}/share`, tmp.directory, { method }) + expect({ method, status: response.status }).toEqual({ method, status: 400 }) + expect(yield* response.json).toMatchObject({ _tag: "Session.OfflinePolicyError", message: expect.stringContaining("online") }) + } + Database.use((db) => + db.update(SessionTable).set({ share_url: "https://share.example/s/3" }).where(eq(SessionTable.id, session.id as any)).run(), + ) + const removed = yield* requestInDirectory(`/session/${session.id}`, tmp.directory, { method: "DELETE" }) + expect(removed.status).toBe(400) + expect(yield* removed.json).toMatchObject({ _tag: "Session.OfflinePolicyError", message: expect.stringContaining("shared") }) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }), + ) +}) From 7ea362a47c4bbc15db67189f4c22ebcb4024c3ae Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:02:27 -0800 Subject: [PATCH 38/72] fix: keep submodule paths whole in offline worktree reset List populated submodules with submodule foreach, which prints full paths, and make the worktree submodule test portable with its setup inside the cleanup. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/worktree/index.ts | 9 ++++----- .../opencode/test/project/worktree.test.ts | 20 ++++++++++++------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index f09eb378ce..9496938ede 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -613,13 +613,12 @@ export const layer: Layer.Layer< } // altimate_change start — update existing submodules from objects already on disk offline - // A submodule this worktree never checked out would need a clone, so offline updates only the present ones - // (`git submodule status` marks the others with a leading "-"). + // A submodule this worktree never checked out would need a clone, so offline updates only the present + // ones (`submodule foreach` visits only checked-out submodules and prints full paths, spaces included). const offlineSubmodules = Offline.enabled() - ? (yield* git(["submodule", "status"], { cwd: worktreePath })).text + ? (yield* git(["submodule", "foreach", "--quiet", 'printf "%s\\n" "$sm_path"'], { cwd: worktreePath })).text .split("\n") - .filter((line) => line.trim() && !line.startsWith("-")) - .map((line) => line.trim().split(/\s+/)[1]!) + .filter((line) => line.length > 0) : undefined if (!offlineSubmodules || offlineSubmodules.length > 0) yield* gitExpect( diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 2c788a52fa..205c1d56ac 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 { mkdir, rm } 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" @@ -115,25 +116,30 @@ describe("Worktree", () => { const result = Bun.spawnSync(["git", "-c", "protocol.file.allow=always", ...args], { cwd, stdout: "pipe", stderr: "pipe" }) if (result.exitCode !== 0) throw new Error(result.stderr.toString()) } + // A path with a space checks that submodule paths are kept whole. const lib = path.join(path.dirname(directory), `${path.basename(directory)}-lib`) - Bun.spawnSync(["mkdir", "-p", lib]) - for (const args of [["init", "-q"], ["config", "user.email", "t@example.com"], ["config", "user.name", "t"], ["config", "commit.gpgsign", "false"], ["commit", "-q", "--allow-empty", "-m", "lib"]]) - run(lib, args) - run(directory, ["submodule", "add", "-q", lib, "lib"]) - run(directory, ["commit", "-q", "-m", "add submodule"]) const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" try { + yield* Effect.promise(() => mkdir(lib, { recursive: true })) + for (const args of [["init", "-q"], ["config", "user.email", "t@example.com"], ["config", "user.name", "t"], ["config", "commit.gpgsign", "false"], ["commit", "-q", "--allow-empty", "-m", "lib"]]) + run(lib, args) + run(directory, ["submodule", "add", "-q", lib, "vendor lib"]) + run(directory, ["commit", "-q", "-m", "add submodule"]) + process.env.ALTIMATE_OFFLINE = "1" const svc = yield* Worktree.Service yield* withCreatedWorktree({ name: "offline-submodule" }, ({ info }) => Effect.gen(function* () { + // Unpopulated submodule: the offline reset skips it instead of trying to clone it. + expect(yield* svc.reset({ directory: info.directory })).toBe(true) + // Populated submodule whose path has a space: the offline reset updates it from local objects. + run(info.directory, ["submodule", "update", "--init"]) expect(yield* svc.reset({ directory: info.directory })).toBe(true) }), ) } finally { if (previous === undefined) delete process.env.ALTIMATE_OFFLINE else process.env.ALTIMATE_OFFLINE = previous - Bun.spawnSync(["rm", "-rf", lib]) + yield* Effect.promise(() => rm(lib, { recursive: true, force: true })) } }), { git: true }, From 3899993a26e54f4d515e53a8677f8c64369c3e08 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:14:00 -0800 Subject: [PATCH 39/72] fix: share offline share messages and match libpq names on Windows One pair of share refusal messages is used everywhere, libpq destination variables are dropped case-insensitively, and tests prove a blocked delete keeps the session and an offline reset moves a populated submodule to the recorded commit. Co-Authored-By: Claude Opus 5.5 --- packages/dbt-tools/src/adapter.ts | 4 +++- .../opencode/src/altimate/native/dbt/runner.ts | 4 +++- packages/opencode/src/config/offline.ts | 3 +++ packages/opencode/src/session/index.ts | 2 +- packages/opencode/src/share/session.ts | 4 ++-- packages/opencode/src/share/share-next.ts | 4 ++-- packages/opencode/test/project/worktree.test.ts | 14 +++++++++++++- .../test/server/httpapi-session-offline.test.ts | 3 +++ 8 files changed, 30 insertions(+), 8 deletions(-) diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 574d97a4da..9cac5e016a 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -105,7 +105,9 @@ function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" vars.DO_NOT_TRACK = "1" vars.DBT_VERSION_CHECK = "false" - for (const name of LIBPQ_DESTINATION_VARS) delete vars[name] + // Environment names are case-insensitive on Windows. + for (const key of Object.keys(vars)) + if ((LIBPQ_DESTINATION_VARS as readonly string[]).includes(key.toUpperCase())) delete vars[key] } if (options.profilesDir) vars.DBT_PROFILES_DIR = options.profilesDir if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index 511851c615..cad5e19b7c 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -50,7 +50,9 @@ export async function runDbt(params: DbtRunParams): Promise { ...(params.project_dir ? ["--project-dir", params.project_dir] : []), ]) const inherited = { ...process.env } - for (const name of LIBPQ_DESTINATION_VARS) delete inherited[name] + // Environment names are case-insensitive on Windows. + for (const key of Object.keys(inherited)) + if ((LIBPQ_DESTINATION_VARS as readonly string[]).includes(key.toUpperCase())) delete inherited[key] offlineEnv = { ...inherited, ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 415b617fe6..b6acb9e277 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -66,6 +66,9 @@ async function localOptIn(directory: string) { return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false } +export const SHARE_REFUSAL = "Sharing sessions requires an online run." +export const UNSHARE_REFUSAL = "Offline mode cannot revoke a share. Run unshare while online." + /** A refusal by the offline policy. Servers report it to the client as a 400 with this message. */ export class OfflinePolicyError extends Error { override name = "OfflinePolicyError" diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index a48517ed25..79376026de 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -429,7 +429,7 @@ export namespace Session { export const share = fn(SessionID.zod, async (id) => { // altimate_change start — offline mode refuses sharing with its own message, before the config check - if (Offline.enabled()) throw new Offline.OfflinePolicyError("Sharing sessions requires an online run.") + if (Offline.enabled()) throw new Offline.OfflinePolicyError(Offline.SHARE_REFUSAL) // altimate_change end const cfg = await Config.get() if (cfg.share === "disabled") { diff --git a/packages/opencode/src/share/session.ts b/packages/opencode/src/share/session.ts index 9f28b33328..427d6938c6 100644 --- a/packages/opencode/src/share/session.ts +++ b/packages/opencode/src/share/session.ts @@ -28,7 +28,7 @@ export const layer = Layer.effect( const share = Effect.fn("SessionShare.share")(function* (sessionID: SessionID) { // altimate_change start — offline mode refuses sharing with its own message, before the config check - if (Offline.enabled()) return yield* new Session.OfflinePolicyError({ message: "Sharing sessions requires an online run." }) + if (Offline.enabled()) return yield* new Session.OfflinePolicyError({ message: Offline.SHARE_REFUSAL }) // altimate_change end const conf = yield* cfg.get() if (conf.share === "disabled") throw new Error("Sharing is disabled in configuration") @@ -40,7 +40,7 @@ export const layer = Layer.effect( const unshare = Effect.fn("SessionShare.unshare")(function* (sessionID: SessionID) { // altimate_change start — offline mode cannot revoke a share; typed refusal, local state kept if (Offline.enabled()) - return yield* new Session.OfflinePolicyError({ message: "Offline mode cannot revoke a share. Run unshare while online." }) + return yield* new Session.OfflinePolicyError({ message: Offline.UNSHARE_REFUSAL }) // altimate_change end yield* shareNext.remove(sessionID) yield* session.setShare({ sessionID, share: undefined }) diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 142eea5aac..004bf29ea2 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -129,7 +129,7 @@ export namespace ShareNext { export async function create(sessionID: SessionID) { // altimate_change start — skip session sharing in offline mode - if (Offline.enabled()) throw new Offline.OfflinePolicyError("Sharing sessions requires an online run.") + if (Offline.enabled()) throw new Offline.OfflinePolicyError(Offline.SHARE_REFUSAL) if (disabled) return { id: "", url: "", secret: "" } // altimate_change end log.info("creating share", { sessionID }) @@ -261,7 +261,7 @@ export namespace ShareNext { export async function remove(sessionID: SessionID) { // altimate_change start — keep the local share state until the server revokes it if (Offline.enabled()) - throw new Offline.OfflinePolicyError("Offline mode cannot revoke a share. Run unshare while online.") + throw new Offline.OfflinePolicyError(Offline.UNSHARE_REFUSAL) // altimate_change end if (disabled) return log.info("removing share", { sessionID }) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 205c1d56ac..4c884cb9ee 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -125,15 +125,27 @@ describe("Worktree", () => { run(lib, args) run(directory, ["submodule", "add", "-q", lib, "vendor lib"]) run(directory, ["commit", "-q", "-m", "add submodule"]) + // A second lib commit, recorded in the main repo: the worktree's checkout starts at the older one. + const older = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: lib, stdout: "pipe" }).stdout.toString().trim() + run(lib, ["commit", "-q", "--allow-empty", "-m", "lib 2"]) + run(path.join(directory, "vendor lib"), ["fetch", "-q", "origin"]) + run(path.join(directory, "vendor lib"), ["checkout", "-q", "origin/HEAD"]) + const newer = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: lib, stdout: "pipe" }).stdout.toString().trim() + run(directory, ["add", "vendor lib"]) + run(directory, ["commit", "-q", "-m", "bump submodule"]) process.env.ALTIMATE_OFFLINE = "1" const svc = yield* Worktree.Service yield* withCreatedWorktree({ name: "offline-submodule" }, ({ info }) => Effect.gen(function* () { // Unpopulated submodule: the offline reset skips it instead of trying to clone it. expect(yield* svc.reset({ directory: info.directory })).toBe(true) - // Populated submodule whose path has a space: the offline reset updates it from local objects. + // Populated submodule whose path has a space, checked out at the older commit: the offline reset + // moves it to the recorded commit from objects already on disk. run(info.directory, ["submodule", "update", "--init"]) + run(path.join(info.directory, "vendor lib"), ["checkout", "-q", older]) expect(yield* svc.reset({ directory: info.directory })).toBe(true) + const head = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: path.join(info.directory, "vendor lib"), stdout: "pipe" }) + expect(head.stdout.toString().trim()).toBe(newer) }), ) } finally { diff --git a/packages/opencode/test/server/httpapi-session-offline.test.ts b/packages/opencode/test/server/httpapi-session-offline.test.ts index 9b2d532971..8cab7f89f8 100644 --- a/packages/opencode/test/server/httpapi-session-offline.test.ts +++ b/packages/opencode/test/server/httpapi-session-offline.test.ts @@ -33,6 +33,9 @@ describe("session HttpApi offline", () => { const removed = yield* requestInDirectory(`/session/${session.id}`, tmp.directory, { method: "DELETE" }) expect(removed.status).toBe(400) expect(yield* removed.json).toMatchObject({ _tag: "Session.OfflinePolicyError", message: expect.stringContaining("shared") }) + // The refusal happens before anything is deleted. + const kept = yield* requestInDirectory(`/session/${session.id}`, tmp.directory) + expect(kept.status).toBe(200) } finally { if (previous === undefined) delete process.env.ALTIMATE_OFFLINE else process.env.ALTIMATE_OFFLINE = previous From 6886cd5a60cd37986fc1d47a2d171c7719faaa85 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:26:35 -0800 Subject: [PATCH 40/72] fix: skip dbt version probes offline Offline project scan only checks that dbt is installed, and onboarding reads the dbt packages from its environment on disk instead of running dbt --version, which asks PyPI for the latest release. One helper drops libpq destination variables for both dbt paths. Co-Authored-By: Claude Opus 5.5 --- packages/dbt-tools/src/adapter.ts | 6 ++--- packages/dbt-tools/src/offline-env.ts | 6 +++++ .../src/altimate/native/dbt/runner.ts | 6 ++--- .../src/altimate/onboarding/tool-detection.ts | 23 +++++++++++++++++ .../src/altimate/tools/project-scan.ts | 3 +++ .../native/offline-connections.test.ts | 7 ++++-- .../onboarding/tool-detection.test.ts | 25 +++++++++++++++++++ .../opencode/test/project/worktree.test.ts | 3 ++- .../opencode/test/tool/project-scan.test.ts | 21 ++++++++++++++++ 9 files changed, 89 insertions(+), 11 deletions(-) diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 9cac5e016a..a2916c78d6 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -1,5 +1,5 @@ import type { Config } from "./config" -import { LIBPQ_DESTINATION_VARS } from "./offline-env" +import { dropLibpqDestinationVars } from "./offline-env" import { bufferLog } from "./log-buffer" import { recordManifest } from "./stale-manifest" export { getRecentDbtLogs, clearDbtLogs } from "./log-buffer" @@ -105,9 +105,7 @@ function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" vars.DO_NOT_TRACK = "1" vars.DBT_VERSION_CHECK = "false" - // Environment names are case-insensitive on Windows. - for (const key of Object.keys(vars)) - if ((LIBPQ_DESTINATION_VARS as readonly string[]).includes(key.toUpperCase())) delete vars[key] + dropLibpqDestinationVars(vars) } if (options.profilesDir) vars.DBT_PROFILES_DIR = options.profilesDir if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath diff --git a/packages/dbt-tools/src/offline-env.ts b/packages/dbt-tools/src/offline-env.ts index 110e80de73..fbb4c2904a 100644 --- a/packages/dbt-tools/src/offline-env.ts +++ b/packages/dbt-tools/src/offline-env.ts @@ -2,3 +2,9 @@ // libpq reads these connection destinations from the environment, overriding the profile host that offline // mode checked. Offline dbt runs drop them. export const LIBPQ_DESTINATION_VARS = ["PGHOSTADDR", "PGSERVICE", "PGSERVICEFILE"] as const + +/** Remove the libpq destination variables from `env`, matching names case-insensitively as Windows does. */ +export function dropLibpqDestinationVars(env: Record): void { + for (const key of Object.keys(env)) + if (LIBPQ_DESTINATION_VARS.some((name) => name === key.toUpperCase())) delete env[key] +} diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index cad5e19b7c..4156263224 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -1,7 +1,7 @@ // altimate_change start — validate offline dbt targets before spawning dbt import { Offline } from "@/config/offline" import { assertLocalDbt } from "./offline" -import { LIBPQ_DESTINATION_VARS } from "../../../../../dbt-tools/src/offline-env" +import { dropLibpqDestinationVars } from "../../../../../dbt-tools/src/offline-env" // altimate_change end /** * dbt CLI wrapper — spawn dbt commands as subprocesses. @@ -50,9 +50,7 @@ export async function runDbt(params: DbtRunParams): Promise { ...(params.project_dir ? ["--project-dir", params.project_dir] : []), ]) const inherited = { ...process.env } - // Environment names are case-insensitive on Windows. - for (const key of Object.keys(inherited)) - if ((LIBPQ_DESTINATION_VARS as readonly string[]).includes(key.toUpperCase())) delete inherited[key] + dropLibpqDestinationVars(inherited) offlineEnv = { ...inherited, ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 3ea8059b42..45cbc731e4 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -1,4 +1,7 @@ import { execFile } from "node:child_process" +import { existsSync, realpathSync } from "node:fs" +import path from "node:path" +import { Offline } from "@/config/offline" // 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 @@ -86,6 +89,9 @@ async function probe(): Promise { // candidate that exists. const resolved = resolveDbt() const env = buildDbtEnv(resolved) + // `dbt --version` asks PyPI for the latest release whatever DBT_VERSION_CHECK says, so offline mode + // reads the installed packages from dbt's own environment on disk instead. + if (Offline.enabled()) return offlineRuntime(resolved.path) // Async --version invocation. Reads BOTH stdout AND stderr (some dbt 1.x // builds write --version output to stderr with color codes). If it fails, @@ -123,6 +129,23 @@ async function probe(): Promise { } } +/** dbt's environment is the virtualenv or prefix its executable lives in: /bin/dbt. */ +function offlineRuntime(dbtPath: string): DbtRuntime { + const executable = path.isAbsolute(dbtPath) ? dbtPath : Bun.which(dbtPath) + if (!executable || !existsSync(executable)) return { hasDbt: false, hasDbtDuckdb: false } + const prefix = path.dirname(path.dirname(realpathSync(executable))) + const sitePackages = [ + ...new Bun.Glob("lib/python*/site-packages").scanSync({ cwd: prefix, onlyFiles: false, absolute: true }), + ...new Bun.Glob("Lib/site-packages").scanSync({ cwd: prefix, onlyFiles: false, absolute: true }), + ] + const hasDbtDuckdb = sitePackages.some((dir) => existsSync(path.join(dir, "dbt", "adapters", "duckdb"))) + const core = sitePackages + .flatMap((dir) => [...new Bun.Glob("dbt_core-*.dist-info").scanSync({ cwd: dir, onlyFiles: false })]) + .map((name) => name.match(/^dbt_core-([0-9]+\.[0-9]+\.[0-9]+\S*?)\.dist-info$/)?.[1]) + .find(Boolean) + return { hasDbt: true, hasDbtDuckdb, dbtCoreVersion: core } +} + interface DbtVersionResult { ok: boolean stdout: string diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index ca0cb1551a..c58bd080cd 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -3,6 +3,7 @@ import { Tool } from "../../tool/tool" import { Dispatcher } from "../native" import { existsSync, readFileSync } from "fs" import path from "path" +import { Offline } from "@/config/offline" import { Telemetry } from "@/telemetry" // altimate_change — onboarding funnel: environment_scan_completed import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding" @@ -484,6 +485,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 => { + // `dbt --version` asks PyPI for the latest release, so offline mode only checks that dbt is installed. + if (tool === "dbt" && Offline.enabled()) return { name: tool, installed: Bun.which(tool) !== null } const result = safeSpawnSync([tool, "--version"], { timeout: 5000 }) if (result && result.exitCode === 0) { return { diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index aa4c1eea99..4b50c2f3de 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -118,19 +118,22 @@ test.skipIf(process.platform === "win32")("offline dbt runs with the checked pro 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|$PGHOSTADDR\"\n", { mode: 0o755 }) + await fs.writeFile(path.join(bin, "dbt"), "#!/bin/sh\necho \"$DBT_PROFILES_DIR|$DBT_VERSION_CHECK|$DBT_SEND_ANONYMOUS_USAGE_STATS|$DO_NOT_TRACK|$PGHOSTADDR|$pgservice\"\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 previousHostaddr = process.env.PGHOSTADDR process.env.PGHOSTADDR = "198.51.100.20" + // A differently-cased name is dropped too. + process.env.pgservice = "remote-service" try { const result = await runDbt({ command: "ls", project_dir: root, args: ["--profiles-dir", root] }) expect(result.exit_code).toBe(0) // libpq's destination override is dropped; usage reporting and the version check are off. - expect(result.stdout.trim()).toBe(`${root}|false|false|1|`) + expect(result.stdout.trim()).toBe(`${root}|false|false|1||`) } finally { + delete process.env.pgservice if (previousHostaddr === undefined) delete process.env.PGHOSTADDR else process.env.PGHOSTADDR = previousHostaddr } diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index bd20235f9f..afc408a744 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -204,3 +204,28 @@ Plugins: expect(third.hasDbtDuckdb).toBe(false) }) }) + +// altimate_change start — offline mode reads dbt's environment instead of running `dbt --version` +test.skipIf(process.platform === "win32")("offline detection reads the installed dbt packages without running dbt", async () => { + const prefix = fs.mkdtempSync(path.join(os.tmpdir(), "offline-dbt-prefix-")) + const previous = process.env.ALTIMATE_OFFLINE + try { + const marker = path.join(prefix, "dbt-ran") + const bin = path.join(prefix, "bin") + const site = path.join(prefix, "lib", "python3.11", "site-packages") + fs.mkdirSync(bin, { recursive: true }) + fs.mkdirSync(path.join(site, "dbt", "adapters", "duckdb"), { recursive: true }) + fs.mkdirSync(path.join(site, "dbt_core-1.9.3.dist-info")) + fs.writeFileSync(path.join(bin, "dbt"), `#!/bin/sh\ntouch "${marker}"\necho "Core:"\n`, { mode: 0o755 }) + process.env.ALTIMATE_DBT_PATH = path.join(bin, "dbt") + process.env.ALTIMATE_OFFLINE = "1" + _resetDbtRuntimeCacheForTests() + expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true, dbtCoreVersion: "1.9.3" }) + expect(fs.existsSync(marker)).toBe(false) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + fs.rmSync(prefix, { recursive: true, force: true }) + } +}) +// altimate_change end diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 4c884cb9ee..95b08fbb16 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -125,7 +125,8 @@ describe("Worktree", () => { run(lib, args) run(directory, ["submodule", "add", "-q", lib, "vendor lib"]) run(directory, ["commit", "-q", "-m", "add submodule"]) - // A second lib commit, recorded in the main repo: the worktree's checkout starts at the older one. + // A second lib commit, recorded in the main repo as the newer submodule commit; the test rewinds the + // worktree's submodule to the older one below. const older = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: lib, stdout: "pipe" }).stdout.toString().trim() run(lib, ["commit", "-q", "--allow-empty", "-m", "lib 2"]) run(path.join(directory, "vendor lib"), ["fetch", "-q", "origin"]) diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index fa79b98778..85622c9b6b 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1022,3 +1022,24 @@ describe("safeSpawnSync", () => { expect(result).not.toBeNull() }) }) + +// altimate_change start — offline mode does not run `dbt --version` (it asks PyPI for the latest release) +test.skipIf(process.platform === "win32")("offline data tool detection finds dbt 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 marker = path.join(dir, "dbt-ran") + await fsp.writeFile(path.join(dir, "dbt"), `#!/bin/sh\ntouch "${marker}"\necho "dbt 1.9.3"\n`, { mode: 0o755 }) + process.env.PATH = `${dir}${path.delimiter}${previous.path}` + process.env.ALTIMATE_OFFLINE = "1" + const tools = await detectDataTools(false) + expect(tools.find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true }) + expect(await fsp.access(marker).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 From 17c40b60511b3a0587ca8d614b6ae1397deab336 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:39:34 -0800 Subject: [PATCH 41/72] fix: run offline dbt version probes behind a closed loopback proxy Instead of guessing dbt install layouts, offline detection runs dbt --version with every proxy pointed at a closed loopback port, so its PyPI lookup fails locally while the installed versions still print. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/onboarding/tool-detection.ts | 26 +++---------------- .../src/altimate/tools/project-scan.ts | 10 ++++--- packages/opencode/src/config/offline.ts | 15 +++++++++++ .../native/offline-connections.test.ts | 4 ++- .../onboarding/tool-detection.test.ts | 25 +++++++++--------- .../opencode/test/tool/project-scan.test.ts | 12 ++++----- 6 files changed, 45 insertions(+), 47 deletions(-) diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 45cbc731e4..b3046da1df 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -1,6 +1,4 @@ import { execFile } from "node:child_process" -import { existsSync, realpathSync } from "node:fs" -import path from "node:path" import { Offline } from "@/config/offline" // 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 @@ -88,10 +86,9 @@ async function probe(): Promise { // + PATH + explicit override via ALTIMATE_DBT_PATH). Returns the first // candidate that exists. const resolved = resolveDbt() - const env = buildDbtEnv(resolved) - // `dbt --version` asks PyPI for the latest release whatever DBT_VERSION_CHECK says, so offline mode - // reads the installed packages from dbt's own environment on disk instead. - if (Offline.enabled()) return offlineRuntime(resolved.path) + // `dbt --version` asks PyPI for the latest release whatever DBT_VERSION_CHECK says. Offline, that + // lookup goes to a closed loopback proxy and fails locally; dbt still prints the installed versions. + const env = Offline.enabled() ? { ...buildDbtEnv(resolved), ...Offline.CLOSED_PROXY_ENV } : buildDbtEnv(resolved) // Async --version invocation. Reads BOTH stdout AND stderr (some dbt 1.x // builds write --version output to stderr with color codes). If it fails, @@ -129,23 +126,6 @@ async function probe(): Promise { } } -/** dbt's environment is the virtualenv or prefix its executable lives in: /bin/dbt. */ -function offlineRuntime(dbtPath: string): DbtRuntime { - const executable = path.isAbsolute(dbtPath) ? dbtPath : Bun.which(dbtPath) - if (!executable || !existsSync(executable)) return { hasDbt: false, hasDbtDuckdb: false } - const prefix = path.dirname(path.dirname(realpathSync(executable))) - const sitePackages = [ - ...new Bun.Glob("lib/python*/site-packages").scanSync({ cwd: prefix, onlyFiles: false, absolute: true }), - ...new Bun.Glob("Lib/site-packages").scanSync({ cwd: prefix, onlyFiles: false, absolute: true }), - ] - const hasDbtDuckdb = sitePackages.some((dir) => existsSync(path.join(dir, "dbt", "adapters", "duckdb"))) - const core = sitePackages - .flatMap((dir) => [...new Bun.Glob("dbt_core-*.dist-info").scanSync({ cwd: dir, onlyFiles: false })]) - .map((name) => name.match(/^dbt_core-([0-9]+\.[0-9]+\.[0-9]+\S*?)\.dist-info$/)?.[1]) - .find(Boolean) - return { hasDbt: true, hasDbtDuckdb, dbtCoreVersion: core } -} - interface DbtVersionResult { ok: boolean stdout: string diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index c58bd080cd..5193803272 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -95,12 +95,14 @@ export interface ConfigFileInfo { */ export function safeSpawnSync( args: string[], - opts?: { timeout?: number }, + opts?: { timeout?: number; env?: Record }, ): { exitCode: number; stdout: string; stderr: string } | null { try { const result = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe", + // altimate_change — offline dbt probe environment + ...(opts?.env && { env: opts.env }), ...(opts?.timeout !== undefined && { timeout: opts.timeout }), }) return { @@ -485,9 +487,9 @@ 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 => { - // `dbt --version` asks PyPI for the latest release, so offline mode only checks that dbt is installed. - if (tool === "dbt" && Offline.enabled()) return { name: tool, installed: Bun.which(tool) !== null } - const result = safeSpawnSync([tool, "--version"], { timeout: 5000 }) + // `dbt --version` asks PyPI for the latest release; offline, that lookup goes to a closed loopback proxy. + const env = tool === "dbt" && Offline.enabled() ? { ...process.env, ...Offline.CLOSED_PROXY_ENV } : undefined + const result = safeSpawnSync([tool, "--version"], { timeout: 5000, env }) if (result && result.exitCode === 0) { return { name: tool, diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index b6acb9e277..f30ccb6523 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -66,6 +66,21 @@ async function localOptIn(directory: string) { return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false } +/** + * Environment for an app-owned helper program whose only network use is optional (for example dbt's + * version lookup): every proxy points at a closed loopback port, so its requests fail on this machine. + */ +export const CLOSED_PROXY_ENV: Record = { + HTTP_PROXY: "http://127.0.0.1:9", + HTTPS_PROXY: "http://127.0.0.1:9", + ALL_PROXY: "http://127.0.0.1:9", + http_proxy: "http://127.0.0.1:9", + https_proxy: "http://127.0.0.1:9", + all_proxy: "http://127.0.0.1:9", + NO_PROXY: "", + no_proxy: "", +} + export const SHARE_REFUSAL = "Sharing sessions requires an online run." export const UNSHARE_REFUSAL = "Offline mode cannot revoke a share. Run unshare while online." diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 4b50c2f3de..8991d74d8b 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -124,6 +124,7 @@ test.skipIf(process.platform === "win32")("offline dbt runs with the checked pro process.env.PATH = `${bin}${path.delimiter}${previousPath}` process.env.ALTIMATE_OFFLINE = "1" const previousHostaddr = process.env.PGHOSTADDR + const previousService = process.env.pgservice process.env.PGHOSTADDR = "198.51.100.20" // A differently-cased name is dropped too. process.env.pgservice = "remote-service" @@ -133,7 +134,8 @@ test.skipIf(process.platform === "win32")("offline dbt runs with the checked pro // libpq's destination override is dropped; usage reporting and the version check are off. expect(result.stdout.trim()).toBe(`${root}|false|false|1||`) } finally { - delete process.env.pgservice + if (previousService === undefined) delete process.env.pgservice + else process.env.pgservice = previousService if (previousHostaddr === undefined) delete process.env.PGHOSTADDR else process.env.PGHOSTADDR = previousHostaddr } diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index afc408a744..3155005a18 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -205,27 +205,26 @@ Plugins: }) }) -// altimate_change start — offline mode reads dbt's environment instead of running `dbt --version` -test.skipIf(process.platform === "win32")("offline detection reads the installed dbt packages without running dbt", async () => { - const prefix = fs.mkdtempSync(path.join(os.tmpdir(), "offline-dbt-prefix-")) +// altimate_change start — offline dbt detection sends dbt's PyPI lookup to a closed loopback proxy +test.skipIf(process.platform === "win32")("offline detection runs dbt --version behind a closed loopback proxy", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "offline-dbt-detect-")) const previous = process.env.ALTIMATE_OFFLINE try { - const marker = path.join(prefix, "dbt-ran") - const bin = path.join(prefix, "bin") - const site = path.join(prefix, "lib", "python3.11", "site-packages") - fs.mkdirSync(bin, { recursive: true }) - fs.mkdirSync(path.join(site, "dbt", "adapters", "duckdb"), { recursive: true }) - fs.mkdirSync(path.join(site, "dbt_core-1.9.3.dist-info")) - fs.writeFileSync(path.join(bin, "dbt"), `#!/bin/sh\ntouch "${marker}"\necho "Core:"\n`, { mode: 0o755 }) - process.env.ALTIMATE_DBT_PATH = path.join(bin, "dbt") + const seen = path.join(dir, "proxy") + fs.writeFileSync( + path.join(dir, "dbt"), + `#!/bin/sh\nprintf "%s|%s" "$HTTPS_PROXY" "$NO_PROXY" > "${seen}"\nprintf "Core:\\n - installed: 1.9.3\\nPlugins:\\n - duckdb: 1.9.0\\n"\n`, + { mode: 0o755 }, + ) + process.env.ALTIMATE_DBT_PATH = path.join(dir, "dbt") process.env.ALTIMATE_OFFLINE = "1" _resetDbtRuntimeCacheForTests() expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true, dbtCoreVersion: "1.9.3" }) - expect(fs.existsSync(marker)).toBe(false) + expect(fs.readFileSync(seen, "utf8")).toBe("http://127.0.0.1:9|") } finally { if (previous === undefined) delete process.env.ALTIMATE_OFFLINE else process.env.ALTIMATE_OFFLINE = previous - fs.rmSync(prefix, { recursive: true, force: true }) + fs.rmSync(dir, { recursive: true, force: true }) } }) // altimate_change end diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index 85622c9b6b..65db1477f1 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1023,18 +1023,18 @@ describe("safeSpawnSync", () => { }) }) -// altimate_change start — offline mode does not run `dbt --version` (it asks PyPI for the latest release) -test.skipIf(process.platform === "win32")("offline data tool detection finds dbt without running it", async () => { +// altimate_change start — offline dbt detection sends dbt's PyPI lookup to a closed loopback proxy +test.skipIf(process.platform === "win32")("offline data tool detection runs dbt behind a closed loopback proxy", 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 marker = path.join(dir, "dbt-ran") - await fsp.writeFile(path.join(dir, "dbt"), `#!/bin/sh\ntouch "${marker}"\necho "dbt 1.9.3"\n`, { mode: 0o755 }) + const seen = path.join(dir, "proxy") + await fsp.writeFile(path.join(dir, "dbt"), `#!/bin/sh\nprintf "%s" "$HTTPS_PROXY" > "${seen}"\necho "dbt 1.9.3"\n`, { mode: 0o755 }) process.env.PATH = `${dir}${path.delimiter}${previous.path}` process.env.ALTIMATE_OFFLINE = "1" const tools = await detectDataTools(false) - expect(tools.find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true }) - expect(await fsp.access(marker).then(() => true, () => false)).toBe(false) + expect(tools.find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) + expect(await fsp.readFile(seen, "utf8")).toBe("http://127.0.0.1:9") } finally { process.env.PATH = previous.path if (previous.offline === undefined) delete process.env.ALTIMATE_OFFLINE From 93fd3f6612d8a2bb928b2c78a0f32656f2ff9e64 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:50:13 -0800 Subject: [PATCH 42/72] fix: keep offline dbt detection when the version probe fails Offline, a dbt --version probe that times out or exits non-zero still reports dbt from the versions it printed, and the project scan falls back to a PATH check. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/onboarding/tool-detection.ts | 4 +++- packages/opencode/src/altimate/tools/project-scan.ts | 6 ++++++ .../test/altimate/onboarding/tool-detection.test.ts | 4 ++++ packages/opencode/test/tool/project-scan.test.ts | 3 +++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index b3046da1df..f4ce67a7a1 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -104,7 +104,9 @@ async function probe(): Promise { if (!out.ok && process.platform === "win32") { out = await runDbtVia(env, "cmd.exe", ["/c", "dbt", "--version"]) } - if (!out.ok) return { hasDbt: false, hasDbtDuckdb: false } + // Offline, a probe that timed out or exited non-zero still counts when it printed dbt's version lines. + const printedVersion = /-\s*installed:|core=/.test(`${out.stdout}\n${out.stderr}`) + if (!out.ok && !(Offline.enabled() && printedVersion)) return { hasDbt: false, hasDbtDuckdb: false } // dbt --version on 1.x prints: // Core: diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index 5193803272..0fba6ee568 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -490,6 +490,12 @@ export async function detectDataTools(skip: boolean): Promise { // `dbt --version` asks PyPI for the latest release; offline, that lookup goes to a closed loopback proxy. const env = tool === "dbt" && Offline.enabled() ? { ...process.env, ...Offline.CLOSED_PROXY_ENV } : undefined const result = safeSpawnSync([tool, "--version"], { timeout: 5000, env }) + // Offline, a probe that did not finish still shows dbt is installed: use what it printed, else PATH. + if (env && !(result && result.exitCode === 0)) { + const version = result ? parseToolVersion(result.stdout) : undefined + const installed = version !== undefined || Bun.which(tool, { PATH: process.env.PATH ?? "" }) !== null + return installed ? { name: tool, installed, ...(version ? { version } : {}) } : { name: tool, installed: false } + } if (result && result.exitCode === 0) { return { name: tool, diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index 3155005a18..932a500d25 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -221,6 +221,10 @@ test.skipIf(process.platform === "win32")("offline detection runs dbt --version _resetDbtRuntimeCacheForTests() expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true, dbtCoreVersion: "1.9.3" }) expect(fs.readFileSync(seen, "utf8")).toBe("http://127.0.0.1:9|") + // A probe that prints the versions and then fails (or times out) still finds dbt offline. + fs.writeFileSync(path.join(dir, "dbt"), `#!/bin/sh\nprintf "Core:\\n - installed: 1.9.3\\n"\nexit 1\n`, { mode: 0o755 }) + _resetDbtRuntimeCacheForTests() + expect(await detectDbtRuntime({ force: true })).toMatchObject({ hasDbt: true, dbtCoreVersion: "1.9.3" }) } finally { if (previous === undefined) delete process.env.ALTIMATE_OFFLINE else process.env.ALTIMATE_OFFLINE = previous diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index 65db1477f1..a8a1376332 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1035,6 +1035,9 @@ test.skipIf(process.platform === "win32")("offline data tool detection runs dbt const tools = await detectDataTools(false) expect(tools.find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) expect(await fsp.readFile(seen, "utf8")).toBe("http://127.0.0.1:9") + // A probe that does not finish cleanly still reports an installed dbt offline. + await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }) + expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true }) } finally { process.env.PATH = previous.path if (previous.offline === undefined) delete process.env.ALTIMATE_OFFLINE From 7acb3ad704b6967904ba5b274fe8572bc7afb1ba Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:56:17 -0800 Subject: [PATCH 43/72] fix: refuse offline removal of a workspace with a shared session Workspace removal checks for shared sessions before deleting anything and refuses with the offline policy error instead of half-removing. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/control-plane/workspace.ts | 19 ++++++-- .../test/control-plane/workspace.test.ts | 48 +++++++++++++++++++ 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index 2bdd01a649..a96170c2b6 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.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 { Context, Effect, FiberMap, Iterable, Layer, Schema, Stream } from "effect" @@ -800,21 +803,27 @@ export const layer = Layer.effect( const remove = Effect.fn("Workspace.remove")(function* (id: WorkspaceV2.ID) { const sessions = yield* db - .select({ id: SessionTable.id, parentID: SessionTable.parent_id }) + // altimate_change start — the share URL decides whether an offline removal may proceed + .select({ id: SessionTable.id, parentID: SessionTable.parent_id, shareURL: SessionTable.share_url }) + // altimate_change end .from(SessionTable) .where(eq(SessionTable.workspace_id, id)) .all() .pipe(Effect.orDie) + // altimate_change start — offline mode cannot revoke a public share, so it refuses before removing anything + if (Offline.enabled() && sessions.some((sessionInfo) => sessionInfo.shareURL)) + return yield* Effect.die( + new Offline.OfflinePolicyError("This workspace has a shared session. Remove it while online so the share can be revoked."), + ) + // altimate_change end const sessionIDs = new Set(sessions.map((sessionInfo) => sessionInfo.id)) yield* Effect.forEach( sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)), (sessionInfo) => session.remove(sessionInfo.id).pipe( Effect.catchIf(NotFoundError.isInstance, () => Effect.void), - // altimate_change start — offline mode keeps a shared session (its share cannot be revoked offline) - Effect.catchTag("Session.OfflinePolicyError", (error) => - Effect.logWarning("kept a shared session while offline", { sessionID: sessionInfo.id, error: error.message }), - ), + // altimate_change start — a share created since the check above: refuse rather than half-remove + Effect.catchTag("Session.OfflinePolicyError", (error) => Effect.die(new Offline.OfflinePolicyError(error.message))), // altimate_change end ), { discard: true }, diff --git a/packages/opencode/test/control-plane/workspace.test.ts b/packages/opencode/test/control-plane/workspace.test.ts index a51de0fa22..1338b16d64 100644 --- a/packages/opencode/test/control-plane/workspace.test.ts +++ b/packages/opencode/test/control-plane/workspace.test.ts @@ -808,6 +808,54 @@ describe("workspace CRUD", () => { { git: true }, ) + // altimate_change start — offline removal refuses a workspace holding a shared session, removing nothing + it.instance( + "offline remove refuses a workspace with a shared session and keeps everything", + () => + Effect.gen(function* () { + const { directory: dir } = yield* TestInstance + const instance = yield* requireInstance + const workspace = yield* Workspace.Service + const sessionSvc = yield* SessionNs.Service + const type = unique("remove-offline-shared") + const recorded = localAdapter(path.join(dir, "remove-offline-shared")) + registerAdapter(ProjectV2.ID.make(instance.project.id), type, recorded.adapter) + const info = yield* workspace.create({ type, branch: null, projectID: ProjectV2.ID.make(instance.project.id), extra: null }) + const plain = yield* sessionSvc.create({}) + const shared = yield* sessionSvc.create({}) + yield* attachSessionToWorkspace(plain.id, info.id) + yield* attachSessionToWorkspace(shared.id, info.id) + const { db } = yield* Database.Service + yield* db + .update(SessionTable) + .set({ share_url: "https://share.example/s/ws" }) + .where(eq(SessionTable.id, shared.id)) + .run() + .pipe(Effect.orDie) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + expectExitContains(yield* Effect.exit(workspace.remove(info.id)), "This workspace has a shared session") + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + expect(yield* workspace.get(info.id)).toEqual(info) + expect(recorded.calls.remove).toEqual([]) + const kept = yield* db + .select({ id: SessionTable.id }) + .from(SessionTable) + .where(eq(SessionTable.workspace_id, info.id)) + .all() + .pipe(Effect.orDie) + expect(kept.map((row) => row.id).sort()).toEqual([plain.id, shared.id].sort()) + yield* db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, shared.id)).run().pipe(Effect.orDie) + yield* workspace.remove(info.id) + }), + { git: true }, + ) + // altimate_change end + it.instance( "remove still deletes the row when the adapter cannot remove resources", () => From 78875864adc29cfbd7911289cb13d8f9f95438c9 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 07:11:03 -0800 Subject: [PATCH 44/72] fix: check whole session trees before offline workspace removal Workspace removal walks subagent descendants for shares before deleting anything, attach --dir applies that project offline setting, and the offline dbt scan reads real dbt version output. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/onboarding/tool-detection.ts | 2 +- .../src/altimate/tools/project-scan.ts | 7 ++++-- .../opencode/src/control-plane/workspace.ts | 25 +++++++++++++++---- packages/opencode/src/index.ts | 1 + .../onboarding/tool-detection.test.ts | 2 +- .../opencode/test/cli/run/offline.test.ts | 16 ++++++++++++ .../test/control-plane/workspace.test.ts | 13 ++++++++++ .../opencode/test/tool/project-scan.test.ts | 5 +++- 8 files changed, 61 insertions(+), 10 deletions(-) diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index f4ce67a7a1..2747a891bb 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -105,7 +105,7 @@ async function probe(): Promise { out = await runDbtVia(env, "cmd.exe", ["/c", "dbt", "--version"]) } // Offline, a probe that timed out or exited non-zero still counts when it printed dbt's version lines. - const printedVersion = /-\s*installed:|core=/.test(`${out.stdout}\n${out.stderr}`) + const printedVersion = /-\s*installed:\s*[0-9]+\.[0-9]+\.[0-9]+|core=[0-9]+\.[0-9]+\.[0-9]+/.test(`${out.stdout}\n${out.stderr}`) if (!out.ok && !(Offline.enabled() && printedVersion)) return { hasDbt: false, hasDbtDuckdb: false } // dbt --version on 1.x prints: diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index 0fba6ee568..82c8f1fd43 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -492,9 +492,12 @@ export async function detectDataTools(skip: boolean): Promise { const result = safeSpawnSync([tool, "--version"], { timeout: 5000, env }) // Offline, a probe that did not finish still shows dbt is installed: use what it printed, else PATH. if (env && !(result && result.exitCode === 0)) { - const version = result ? parseToolVersion(result.stdout) : undefined + // dbt 1.x prints "Core:" then " - installed: "; older output leads with the version. + const version = result + ? (result.stdout.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/)?.[1] ?? parseToolVersion(result.stdout)) + : undefined const installed = version !== undefined || Bun.which(tool, { PATH: process.env.PATH ?? "" }) !== null - return installed ? { name: tool, installed, ...(version ? { version } : {}) } : { name: tool, installed: false } + return { name: tool, installed, ...(version ? { version } : {}) } } if (result && result.exitCode === 0) { return { diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index a96170c2b6..7aabc3f79a 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -810,11 +810,26 @@ export const layer = Layer.effect( .where(eq(SessionTable.workspace_id, id)) .all() .pipe(Effect.orDie) - // altimate_change start — offline mode cannot revoke a public share, so it refuses before removing anything - if (Offline.enabled() && sessions.some((sessionInfo) => sessionInfo.shareURL)) - return yield* Effect.die( - new Offline.OfflinePolicyError("This workspace has a shared session. Remove it while online so the share can be revoked."), - ) + // altimate_change start — offline mode cannot revoke a public share, so it refuses before removing anything. + // Subagent sessions carry only a parent id, so the check walks each tree, not just the workspace's rows. + if (Offline.enabled()) { + let level = sessions + const seen = new Set(sessions.map((sessionInfo) => sessionInfo.id)) + while (level.length) { + if (level.some((sessionInfo) => sessionInfo.shareURL)) + return yield* Effect.die( + new Offline.OfflinePolicyError("This workspace has a shared session. Remove it while online so the share can be revoked."), + ) + const children = yield* db + .select({ id: SessionTable.id, parentID: SessionTable.parent_id, shareURL: SessionTable.share_url }) + .from(SessionTable) + .where(inArray(SessionTable.parent_id, level.map((sessionInfo) => sessionInfo.id))) + .all() + .pipe(Effect.orDie) + level = children.filter((child) => !seen.has(child.id)) + for (const child of level) seen.add(child.id) + } + } // altimate_change end const sessionIDs = new Set(sessions.map((sessionInfo) => sessionInfo.id)) yield* Effect.forEach( diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 22416f0ea4..1f3bc9a2ff 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -186,6 +186,7 @@ let cli = yargs(args) const offlineTarget = (command === "run" && !args.attach ? args.dir : undefined) ?? (command === "acp" ? args.cwd : undefined) ?? (command === "workspace" ? args.directory : undefined) + ?? (command === "attach" ? args.dir : undefined) const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) await Offline.start(directory, args.model) // Attaching to a server on this machine is local; any other server is a network peer. diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index 932a500d25..d732249946 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -221,7 +221,7 @@ test.skipIf(process.platform === "win32")("offline detection runs dbt --version _resetDbtRuntimeCacheForTests() expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true, dbtCoreVersion: "1.9.3" }) expect(fs.readFileSync(seen, "utf8")).toBe("http://127.0.0.1:9|") - // A probe that prints the versions and then fails (or times out) still finds dbt offline. + // A probe that prints the versions and then exits non-zero still finds dbt offline. fs.writeFileSync(path.join(dir, "dbt"), `#!/bin/sh\nprintf "Core:\\n - installed: 1.9.3\\n"\nexit 1\n`, { mode: 0o755 }) _resetDbtRuntimeCacheForTests() expect(await detectDbtRuntime({ force: true })).toMatchObject({ hasDbt: true, dbtCoreVersion: "1.9.3" }) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index b82cba5495..123bfd6d63 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -328,6 +328,22 @@ test("offline attach accepts a server on this machine and refuses a remote one", } }, 45_000) +test("attach --dir applies that project's offline setting when launched elsewhere", async () => { + // configMode without a snapshot: the project's own config turns offline mode on; the env switch is off. + const f = await fixture(false, true, false) + try { + const proc = Bun.spawn( + [process.execPath, "--preload", f.preload, CLI, "attach", "https://remote-server.test", "--dir", f.project], + { cwd: f.root, 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 + expect(stdout + stderr).toContain("This command requires network access") + } finally { + await fs.rm(f.root, { recursive: true, force: true }) + } +}, 30_000) + test("offline model transport bypasses proxy settings and refuses redirects", async () => { let proxyCalls = 0 const proxy = Bun.serve({ diff --git a/packages/opencode/test/control-plane/workspace.test.ts b/packages/opencode/test/control-plane/workspace.test.ts index 1338b16d64..3c173b0330 100644 --- a/packages/opencode/test/control-plane/workspace.test.ts +++ b/packages/opencode/test/control-plane/workspace.test.ts @@ -850,6 +850,19 @@ describe("workspace CRUD", () => { .pipe(Effect.orDie) expect(kept.map((row) => row.id).sort()).toEqual([plain.id, shared.id].sort()) yield* db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, shared.id)).run().pipe(Effect.orDie) + // A shared subagent session carries only a parent id; the check still finds it before removing anything. + const sub = yield* sessionSvc.create({ parentID: plain.id }) + yield* db.update(SessionTable).set({ share_url: "https://share.example/s/sub", workspace_id: null }).where(eq(SessionTable.id, sub.id)).run().pipe(Effect.orDie) + process.env.ALTIMATE_OFFLINE = "1" + try { + expectExitContains(yield* Effect.exit(workspace.remove(info.id)), "This workspace has a shared session") + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + expect(yield* workspace.get(info.id)).toEqual(info) + expect((yield* sessionSvc.get(plain.id)).id).toBe(plain.id) + yield* db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, sub.id)).run().pipe(Effect.orDie) yield* workspace.remove(info.id) }), { git: true }, diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index a8a1376332..cf43aa4793 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1035,7 +1035,10 @@ test.skipIf(process.platform === "win32")("offline data tool detection runs dbt const tools = await detectDataTools(false) expect(tools.find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) expect(await fsp.readFile(seen, "utf8")).toBe("http://127.0.0.1:9") - // A probe that does not finish cleanly still reports an installed dbt offline. + // A probe that prints dbt's real version lines and then exits non-zero still reports the version offline. + await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nprintf 'Core:\\n - installed: 1.9.3\\n'\nexit 1\n", { mode: 0o755 }) + expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) + // A probe that prints nothing falls back to finding dbt on PATH. await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }) expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true }) } finally { From 47497897db69b7e932cc48073f6309f38c681fa7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 07:20:47 -0800 Subject: [PATCH 45/72] fix: restore proxy settings for custom language servers offline The legacy LSP spawn for config-defined servers uses the user env, and user programs no longer inherit the session offline model choice. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/config/offline.ts | 2 ++ packages/opencode/src/lsp/index.ts | 7 ++++++- packages/opencode/test/mcp/offline.test.ts | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index f30ccb6523..d1234ab923 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -119,6 +119,8 @@ export function userEnv>(env: T): T const saved = env[USER_PROXY] ?? process.env[USER_PROXY] if (saved === undefined) return env delete env[USER_PROXY] + // The session's model choice is internal; a program the user runs (even a nested altimate-code) chooses its own. + delete env.ALTIMATE_OFFLINE_MODEL try { const original = JSON.parse(saved) as Record for (const key of ["NO_PROXY", "no_proxy"] as const) { diff --git a/packages/opencode/src/lsp/index.ts b/packages/opencode/src/lsp/index.ts index a3bf956ac7..b16f1f522e 100644 --- a/packages/opencode/src/lsp/index.ts +++ b/packages/opencode/src/lsp/index.ts @@ -1,3 +1,6 @@ +// altimate_change start — offline mode user environment +import { Offline } from "@/config/offline" +// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" import { Log } from "../util/log" @@ -134,10 +137,12 @@ export namespace LSP { process: spawn(item.command[0], item.command.slice(1), { cwd: root, windowsHide: true, + // altimate_change start — offline mode keeps the user's proxy settings for custom language servers env: { - ...process.env, + ...Offline.userEnv({ ...process.env }), ...item.env, }, + // altimate_change end }), initialization: item.initialization, } diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index bcab6c3759..28db524642 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -53,6 +53,7 @@ test("user programs get their own proxy exclusions back, not the offline bypass" expect(env.NO_PROXY).toBe("corp.example") expect(env.no_proxy).toBeUndefined() expect(env.ALTIMATE_OFFLINE_USER_PROXY).toBeUndefined() + expect(Offline.userEnv({ ...process.env, ALTIMATE_OFFLINE_MODEL: "local/main" }).ALTIMATE_OFFLINE_MODEL).toBeUndefined() expect(env.PATH).toBe("/bin") // A copied env that lacks the key (Bun omits variables assigned after startup) still gets the saved value. const copy: Record = { PATH: "/bin" } From 3f6ecfdf5b7fb189a43aecf1c79c2be79add2e07 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:27:46 -0800 Subject: [PATCH 46/72] fix: keep the invoking project offline policy for remote attach attach applies the invoking project setting and a local --dir setting, workspace removal reuses the session tree check, local store paths refuse any Jinja delimiter, and dbt version probes read stderr too. Co-Authored-By: Claude Opus 5.5 --- .../altimate/native/connections/offline.ts | 3 ++- .../src/altimate/onboarding/tool-detection.ts | 14 +++++------- .../src/altimate/tools/project-scan.ts | 4 +++- .../opencode/src/control-plane/workspace.ts | 22 +++++-------------- packages/opencode/src/index.ts | 4 +++- packages/opencode/src/lsp/launch.ts | 1 + packages/opencode/src/session/session.ts | 5 +++++ .../native/offline-connections.test.ts | 2 ++ .../opencode/test/cli/run/offline.test.ts | 10 ++++++++- .../opencode/test/tool/project-scan.test.ts | 3 +++ 10 files changed, 40 insertions(+), 28 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index cc3c949485..5cfd39a694 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -3,7 +3,8 @@ import { isLocalFilePath, normalizeConfig, type ConnectionConfig } from "@altima import { isLoopbackHost } from "@/config/offline" function localStore(value: unknown): boolean { - if (typeof value !== "string" || value.includes("{{")) return false + // dbt renders Jinja (expressions, statements, comments) after this check, so only a literal path is local. + if (typeof value !== "string" || /\{[{%#]/.test(value)) return false if (value === ":memory:" || value === "") return true // UNC shares are network locations, even though they look like paths. if (/^(?:\\\\|\/\/)/.test(value)) return false diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 2747a891bb..c299354503 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -104,9 +104,12 @@ async function probe(): Promise { if (!out.ok && process.platform === "win32") { out = await runDbtVia(env, "cmd.exe", ["/c", "dbt", "--version"]) } - // Offline, a probe that timed out or exited non-zero still counts when it printed dbt's version lines. - const printedVersion = /-\s*installed:\s*[0-9]+\.[0-9]+\.[0-9]+|core=[0-9]+\.[0-9]+\.[0-9]+/.test(`${out.stdout}\n${out.stderr}`) - if (!out.ok && !(Offline.enabled() && printedVersion)) return { hasDbt: false, hasDbtDuckdb: false } + const combined = `${out.stdout}\n${out.stderr}` + const versionMatch = + combined.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/) ?? + combined.match(/core=([0-9]+\.[0-9]+\.[0-9]+\S*)/) + // Offline, a probe that timed out or exited non-zero still counts when it printed dbt's version. + if (!out.ok && !(Offline.enabled() && versionMatch)) return { hasDbt: false, hasDbtDuckdb: false } // dbt --version on 1.x prints: // Core: @@ -115,12 +118,7 @@ async function probe(): Promise { // - duckdb: 1.11.4 - Update available! // Match the plugin line specifically ("- duckdb:") — a generic "duckdb" // substring would false-positive on an "install dbt-duckdb" upgrade hint. - const combined = `${out.stdout}\n${out.stderr}` const hasDbtDuckdb = /^\s*-\s*duckdb:/m.test(combined) - - const versionMatch = - combined.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/) ?? - combined.match(/core=([0-9]+\.[0-9]+\.[0-9]+\S*)/) return { hasDbt: true, hasDbtDuckdb, diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index 82c8f1fd43..c46b8fb2f2 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -493,8 +493,10 @@ export async function detectDataTools(skip: boolean): Promise { // Offline, a probe that did not finish still shows dbt is installed: use what it printed, else PATH. if (env && !(result && result.exitCode === 0)) { // dbt 1.x prints "Core:" then " - installed: "; older output leads with the version. + // Some dbt builds print --version to stderr. + const output = result ? `${result.stdout}\n${result.stderr}` : "" const version = result - ? (result.stdout.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/)?.[1] ?? parseToolVersion(result.stdout)) + ? (output.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/)?.[1] ?? parseToolVersion(output.trim())) : undefined const installed = version !== undefined || Bun.which(tool, { PATH: process.env.PATH ?? "" }) !== null return { name: tool, installed, ...(version ? { version } : {}) } diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index 7aabc3f79a..3a340beb15 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -803,31 +803,21 @@ export const layer = Layer.effect( const remove = Effect.fn("Workspace.remove")(function* (id: WorkspaceV2.ID) { const sessions = yield* db - // altimate_change start — the share URL decides whether an offline removal may proceed - .select({ id: SessionTable.id, parentID: SessionTable.parent_id, shareURL: SessionTable.share_url }) - // altimate_change end + .select({ id: SessionTable.id, parentID: SessionTable.parent_id }) .from(SessionTable) .where(eq(SessionTable.workspace_id, id)) .all() .pipe(Effect.orDie) // altimate_change start — offline mode cannot revoke a public share, so it refuses before removing anything. - // Subagent sessions carry only a parent id, so the check walks each tree, not just the workspace's rows. + // The session service's tree check covers subagent sessions, which carry only a parent id. if (Offline.enabled()) { - let level = sessions - const seen = new Set(sessions.map((sessionInfo) => sessionInfo.id)) - while (level.length) { - if (level.some((sessionInfo) => sessionInfo.shareURL)) + const roots = sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessions.some((other) => other.id === sessionInfo.parentID)) + for (const root of roots) { + const shared = yield* session.sharedInTree(root.id).pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(false))) + if (shared) return yield* Effect.die( new Offline.OfflinePolicyError("This workspace has a shared session. Remove it while online so the share can be revoked."), ) - const children = yield* db - .select({ id: SessionTable.id, parentID: SessionTable.parent_id, shareURL: SessionTable.share_url }) - .from(SessionTable) - .where(inArray(SessionTable.parent_id, level.map((sessionInfo) => sessionInfo.id))) - .all() - .pipe(Effect.orDie) - level = children.filter((child) => !seen.has(child.id)) - for (const child of level) seen.add(child.id) } } // altimate_change end diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 1f3bc9a2ff..7a6c80d7d8 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -1,4 +1,5 @@ // altimate_change start — offline mode +import { existsSync } from "node:fs" import { Offline } from "@/config/offline" // altimate_change end import yargs from "yargs" @@ -186,9 +187,10 @@ let cli = yargs(args) const offlineTarget = (command === "run" && !args.attach ? args.dir : undefined) ?? (command === "acp" ? args.cwd : undefined) ?? (command === "workspace" ? args.directory : undefined) - ?? (command === "attach" ? args.dir : undefined) const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) await Offline.start(directory, args.model) + // attach: the invoking project's setting applies, and so does --dir's when it is a local directory. + if (command === "attach" && args.dir && existsSync(path.resolve(args.dir))) await Offline.start(path.resolve(args.dir), args.model) // Attaching to a server on this machine is local; any other server is a network peer. const attachURL = command === "attach" ? args.url : command === "run" ? args.attach || undefined : undefined if (Offline.enabled() && ( diff --git a/packages/opencode/src/lsp/launch.ts b/packages/opencode/src/lsp/launch.ts index 8ecf777e4f..f6361ad0c5 100644 --- a/packages/opencode/src/lsp/launch.ts +++ b/packages/opencode/src/lsp/launch.ts @@ -21,6 +21,7 @@ export function spawn(cmd: string, argsOrOpts?: string[] | Process.Options, opts NO_PROXY: undefined, no_proxy: undefined, ALTIMATE_OFFLINE_USER_PROXY: undefined, + ALTIMATE_OFFLINE_MODEL: undefined, ...Offline.userEnv({ ...process.env, ...cfg?.env }), }, } diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index 8ac9d6d56d..f2e296c8c0 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -512,6 +512,8 @@ export interface Interface { readonly children: (parentID: SessionID) => Effect.Effect // altimate_change start — offline mode refuses to delete a shared session readonly remove: (sessionID: SessionID) => Effect.Effect + /** Whether the session or any descendant (subagent sessions included) has a public share. */ + readonly sharedInTree: (sessionID: SessionID) => Effect.Effect // altimate_change end readonly updateMessage: (msg: T) => Effect.Effect readonly removeMessage: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect @@ -1012,6 +1014,9 @@ export const layer: Layer.Layer< messages, children, remove, + // altimate_change start — offline shared-session check + sharedInTree, + // altimate_change end updateMessage, removeMessage, removePart, diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 8991d74d8b..2c58cdb6fd 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -30,6 +30,8 @@ test("offline permits embedded databases and literal loopback", () => { test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", () => { for (const config of [ { type: "duckdb", path: "md:cloud" }, + { type: "duckdb", path: "{% if true %}md:cloud{% endif %}" }, + { type: "duckdb", path: "{# cloud #}md:cloud" }, { type: "duckdb", path: "https://example.com/db" }, { type: "sqlite", path: "file://example.com/share/db" }, { type: "sqlite", path: "file:////server/share/db.sqlite" }, diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 123bfd6d63..6dab004566 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -339,10 +339,18 @@ test("attach --dir applies that project's offline setting when launched elsewher const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]) await proc.exited expect(stdout + stderr).toContain("This command requires network access") + // From inside that project, a --dir that exists only on the remote server keeps the project's setting. + const remote = Bun.spawn( + [process.execPath, "--preload", f.preload, CLI, "attach", "https://remote-server.test", "--dir", "/srv/remote-only"], + { cwd: f.project, env: f.env, stdin: "ignore", stdout: "pipe", stderr: "pipe", signal: AbortSignal.timeout(20_000) }, + ) + const [out2, err2] = await Promise.all([new Response(remote.stdout).text(), new Response(remote.stderr).text()]) + await remote.exited + expect(out2 + err2).toContain("This command requires network access") } finally { await fs.rm(f.root, { recursive: true, force: true }) } -}, 30_000) +}, 45_000) test("offline model transport bypasses proxy settings and refuses redirects", async () => { let proxyCalls = 0 diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index cf43aa4793..2a369ef761 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1038,6 +1038,9 @@ test.skipIf(process.platform === "win32")("offline data tool detection runs dbt // A probe that prints dbt's real version lines and then exits non-zero still reports the version offline. await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nprintf 'Core:\\n - installed: 1.9.3\\n'\nexit 1\n", { mode: 0o755 }) expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) + // Some dbt builds print --version to stderr. + await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nprintf 'Core:\\n - installed: 1.9.4\\n' >&2\nexit 1\n", { mode: 0o755 }) + expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.4" }) // A probe that prints nothing falls back to finding dbt on PATH. await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }) expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true }) From f947dbfb24c39f62d5e6f6b1ac7e47081f890f69 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:38:08 -0800 Subject: [PATCH 47/72] fix: unset the offline model for every user program userEnv drops the session model choice even without saved proxy settings, the language server spawn unsets it after the env spread, and the workspace check reuses one root set. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/config/offline.ts | 4 ++-- packages/opencode/src/control-plane/workspace.ts | 4 ++-- packages/opencode/src/lsp/launch.ts | 3 ++- .../opencode/test/altimate/native/offline-connections.test.ts | 1 + 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index d1234ab923..b9582c4841 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -116,11 +116,11 @@ const USER_PROXY = "ALTIMATE_OFFLINE_USER_PROXY" * user's original proxy exclusions back instead of the process-wide bypass. */ export function userEnv>(env: T): T { + // The session's model choice is internal; a program the user runs (even a nested altimate-code) chooses its own. + delete env.ALTIMATE_OFFLINE_MODEL const saved = env[USER_PROXY] ?? process.env[USER_PROXY] if (saved === undefined) return env delete env[USER_PROXY] - // The session's model choice is internal; a program the user runs (even a nested altimate-code) chooses its own. - delete env.ALTIMATE_OFFLINE_MODEL try { const original = JSON.parse(saved) as Record for (const key of ["NO_PROXY", "no_proxy"] as const) { diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index 3a340beb15..bb46275d98 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -811,8 +811,8 @@ export const layer = Layer.effect( // altimate_change start — offline mode cannot revoke a public share, so it refuses before removing anything. // The session service's tree check covers subagent sessions, which carry only a parent id. if (Offline.enabled()) { - const roots = sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessions.some((other) => other.id === sessionInfo.parentID)) - for (const root of roots) { + const ids = new Set(sessions.map((sessionInfo) => sessionInfo.id)) + for (const root of sessions.filter((sessionInfo) => !sessionInfo.parentID || !ids.has(sessionInfo.parentID))) { const shared = yield* session.sharedInTree(root.id).pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(false))) if (shared) return yield* Effect.die( diff --git a/packages/opencode/src/lsp/launch.ts b/packages/opencode/src/lsp/launch.ts index f6361ad0c5..5555ffad4a 100644 --- a/packages/opencode/src/lsp/launch.ts +++ b/packages/opencode/src/lsp/launch.ts @@ -21,8 +21,9 @@ export function spawn(cmd: string, argsOrOpts?: string[] | Process.Options, opts NO_PROXY: undefined, no_proxy: undefined, ALTIMATE_OFFLINE_USER_PROXY: undefined, - ALTIMATE_OFFLINE_MODEL: undefined, ...Offline.userEnv({ ...process.env, ...cfg?.env }), + // After the spread: Process.spawn merges process.env underneath, so the key must be unset explicitly. + ALTIMATE_OFFLINE_MODEL: undefined, }, } : {}), diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 2c58cdb6fd..da53b2130d 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -32,6 +32,7 @@ test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", { type: "duckdb", path: "md:cloud" }, { type: "duckdb", path: "{% if true %}md:cloud{% endif %}" }, { type: "duckdb", path: "{# cloud #}md:cloud" }, + { type: "duckdb", path: "{{ 'md:cloud' }}" }, { type: "duckdb", path: "https://example.com/db" }, { type: "sqlite", path: "file://example.com/share/db" }, { type: "sqlite", path: "file:////server/share/db.sqlite" }, From 09bbe9f1319b11195ce0cef5db8902c2197a5593 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:48:59 -0800 Subject: [PATCH 48/72] refactor: share one root session list in workspace removal Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/control-plane/workspace.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index bb46275d98..ef9e43f5e4 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -808,11 +808,13 @@ export const layer = Layer.effect( .where(eq(SessionTable.workspace_id, id)) .all() .pipe(Effect.orDie) - // altimate_change start — offline mode cannot revoke a public share, so it refuses before removing anything. - // The session service's tree check covers subagent sessions, which carry only a parent id. + // altimate_change start — one root list for the offline share check and the removal below + const sessionIDs = new Set(sessions.map((sessionInfo) => sessionInfo.id)) + const roots = sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)) + // Offline mode cannot revoke a public share, so it refuses before removing anything. The session service's + // tree check covers subagent sessions, which carry only a parent id. if (Offline.enabled()) { - const ids = new Set(sessions.map((sessionInfo) => sessionInfo.id)) - for (const root of sessions.filter((sessionInfo) => !sessionInfo.parentID || !ids.has(sessionInfo.parentID))) { + for (const root of roots) { const shared = yield* session.sharedInTree(root.id).pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(false))) if (shared) return yield* Effect.die( @@ -820,10 +822,9 @@ export const layer = Layer.effect( ) } } - // altimate_change end - const sessionIDs = new Set(sessions.map((sessionInfo) => sessionInfo.id)) yield* Effect.forEach( - sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)), + roots, + // altimate_change end (sessionInfo) => session.remove(sessionInfo.id).pipe( Effect.catchIf(NotFoundError.isInstance, () => Effect.void), From 9c40275d122c5b265068b59076df120fd0d97614 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 09:52:35 -0800 Subject: [PATCH 49/72] refactor: simplify offline mode to one module and remove its cost when off - Model calls now respect `HTTPS_PROXY`; the global `NO_PROXY="*"` bypass and `userEnv` are gone. Offline mode adds only loopback hosts to `NO_PROXY`. - Startup reads the switch once with a lean config check (no plist, managed dir or TOML; parses only files that mention it). - Reverted the skill cache restructure, typed policy errors, shared-session delete changes, snapshot pin logic, LFS env injection and per-protocol host checks. - Local DuckDB extensions, local dbt-duckdb attach/plugins and `tool run --daemon` work offline. - e2e now captures proxy and spawned-program egress, covers offline-off and a model reached through `HTTPS_PROXY`. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 38 +-- packages/core/src/git.ts | 53 +--- packages/core/src/skill/discovery.ts | 3 +- packages/core/test/git.test.ts | 73 +---- packages/dbt-tools/src/adapter.ts | 2 - packages/dbt-tools/src/offline-env.ts | 10 - packages/drivers/src/duckdb.ts | 2 +- .../drivers/src/local-engine-child-source.ts | 6 +- .../opencode/src/altimate/debug/collect.ts | 12 +- .../altimate/native/connections/offline.ts | 94 ++---- .../altimate/native/connections/register.ts | 8 +- .../altimate/native/connections/registry.ts | 23 +- .../src/altimate/native/dbt/offline.ts | 128 +++----- .../src/altimate/native/dbt/runner.ts | 5 +- .../src/altimate/onboarding/tool-detection.ts | 22 +- .../src/altimate/tool-cli/workspace-tools.ts | 4 +- .../src/altimate/tools/project-scan.ts | 24 +- .../src/altimate/workspace/skill-sync.ts | 25 +- .../opencode/src/altimate/workspace/state.ts | 7 +- packages/opencode/src/cli/cmd/mcp.ts | 22 +- packages/opencode/src/cli/cmd/session.ts | 7 +- packages/opencode/src/cli/cmd/skill.ts | 11 +- packages/opencode/src/cli/cmd/tool.ts | 3 +- packages/opencode/src/cli/cmd/upgrade.ts | 6 - packages/opencode/src/cli/tui/worker.ts | 5 +- packages/opencode/src/config/config.ts | 7 +- packages/opencode/src/config/offline.ts | 238 ++++---------- packages/opencode/src/config/paths.ts | 18 +- .../opencode/src/control-plane/workspace.ts | 26 +- packages/opencode/src/format/index.ts | 13 +- packages/opencode/src/git/index.ts | 15 +- packages/opencode/src/index.ts | 49 ++- packages/opencode/src/lsp/index.ts | 7 +- packages/opencode/src/lsp/launch.ts | 18 -- packages/opencode/src/mcp/index.ts | 42 +-- .../src/plugin/tui/altimate/skill-ops.tsx | 2 +- packages/opencode/src/pty/index.ts | 7 +- packages/opencode/src/server/middleware.ts | 7 - .../routes/instance/httpapi/groups/mcp.ts | 12 +- .../routes/instance/httpapi/groups/session.ts | 12 +- .../instance/httpapi/handlers/session.ts | 29 +- .../instance/httpapi/middleware/error.ts | 11 - packages/opencode/src/server/server.ts | 6 - packages/opencode/src/session/index.ts | 32 +- packages/opencode/src/session/prompt.ts | 34 +- packages/opencode/src/session/session.ts | 45 +-- packages/opencode/src/share/session.ts | 10 - packages/opencode/src/share/share-next.ts | 13 +- packages/opencode/src/skill/discovery.ts | 43 +-- packages/opencode/src/snapshot/index.ts | 10 +- packages/opencode/src/tool/bash.ts | 6 +- packages/opencode/src/util/git.ts | 18 +- packages/opencode/src/worktree/index.ts | 49 +-- .../test/altimate/debug/collect.test.ts | 16 +- .../native/offline-connections.test.ts | 270 ++++------------ .../onboarding/tool-detection.test.ts | 29 +- .../altimate/registry-per-project.test.ts | 19 -- .../altimate/workspace/skill-sync.test.ts | 57 ---- .../test/altimate/workspace/state-pin.test.ts | 26 +- packages/opencode/test/cli/mcp-add.test.ts | 8 +- .../opencode/test/cli/run/offline.test.ts | 299 +++++++++++------- .../test/config/offline-startup.test.ts | 34 -- .../test/config/paths-parsetext.test.ts | 8 - .../test/control-plane/workspace.test.ts | 61 ---- packages/opencode/test/lsp/offline.test.ts | 24 -- packages/opencode/test/mcp/offline.test.ts | 94 ++---- .../opencode/test/project/worktree.test.ts | 53 ---- .../question-937-codex.test.ts | 3 +- .../opencode/test/server/httpapi-mcp.test.ts | 33 -- .../server/httpapi-session-offline.test.ts | 45 --- .../test/session/offline-delete.test.ts | 108 ------- .../opencode/test/share/share-next.test.ts | 34 +- .../opencode/test/skill/discovery.test.ts | 49 +-- .../opencode/test/storage/storage.test.ts | 49 --- .../opencode/test/tool/project-scan.test.ts | 20 +- 75 files changed, 633 insertions(+), 2078 deletions(-) delete mode 100644 packages/dbt-tools/src/offline-env.ts delete mode 100644 packages/opencode/test/config/offline-startup.test.ts delete mode 100644 packages/opencode/test/server/httpapi-session-offline.test.ts delete mode 100644 packages/opencode/test/session/offline-delete.test.ts diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 823c3fe2a5..dfbeef0c4d 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -162,28 +162,31 @@ Control how context is managed when conversations grow long: ## Offline / air-gapped mode -Offline mode is for running Altimate Code against a local or self-hosted model with no other network access. It stops the network requests Altimate Code itself makes. It does not stop local work: tools, shell commands, local databases and local Git keep working. +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. Local work keeps running: tools, shell commands, local databases, language servers, local MCP servers and local Git. + +With offline mode off, nothing on this page 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 or project configuration file. The setting covers the process and its workers. A project that requests offline mode is refused by a shared server started without it; start Altimate Code from that project instead. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. Organisation-managed configuration and remote (well-known) configuration apply the setting only once they load, after some startup requests; use `ALTIMATE_OFFLINE=1` there. 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 select 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. Requests to that endpoint are the only requests Altimate Code sends off the machine. They go directly to the endpoint, not through `HTTP_PROXY` or `HTTPS_PROXY`, so the endpoint must be reachable without a proxy. A `small_model` is used only if it belongs to the same provider; otherwise the main model handles those tasks. +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 without refreshing or deleting it, as long as your local credentials belong to the same workspace account. +- 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. +- Run `dbt deps` for dbt projects, and install any DuckDB extensions your profiles use. ### What keeps working -- Local warehouses: DuckDB and SQLite files, and warehouses reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. The SQL and schema tools run against them. -- dbt commands, when the selected profile and target point at a local database. -- The shell tool, installed language servers, and MCP servers that use stdio or a loopback HTTP(S) URL. -- Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and submodule commits. Git LFS files check out from the local LFS cache; a file whose content is not cached fails with a clear error instead of downloading. +- Local warehouses: DuckDB and SQLite files, and warehouses reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. A host that is not one of these, or a connection string that cannot be parsed, is refused. +- dbt commands whose selected profile and target are local. dbt-duckdb profiles can use installed extensions, local attachments and plugins; settings that point at remote storage or a remote server (`s3://`, `https://`, `gcs://`, `md:` and similar) are refused. +- DuckDB loads extensions that are already installed; it does not download new ones. +- The shell tool, installed language servers, stdio MCP servers and MCP servers at `localhost`, `127.0.0.1` or `[::1]`, including `tool run --daemon`. +- Git diffs, session snapshots and revert, and worktree create, remove and reset (reset uses the locally cached base branch). - `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 @@ -192,18 +195,17 @@ 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; -- session sharing; +- 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 non-loopback URLs, and MCP sign-in; +- MCP servers at other URLs, and MCP sign-in; - automatic installs of warehouse drivers, language servers, plugins and ripgrep; -- warehouse connections whose host is not loopback, SSH tunnels, and cloud sign-in methods; -- `dbt deps`, dbt's own usage reporting and version check, and dbt-duckdb profiles that use remote storage or a remote server; -- Git fetch, pull, push, clone and other remote operations; -- commands that need a remote service, such as `github`, `pr`, `web`, `review --post` and `attach` to another machine. +- warehouse connections to other hosts, SSH tunnels, and cloud sign-in methods for dbt; +- `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: shell commands, language servers, local MCP servers and their child processes. They also keep your proxy settings. Offline mode does not sandbox them. +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]` so that local requests do not go through a proxy. -DuckDB connections do not install or load extensions automatically offline. SQL that explicitly runs `INSTALL` or `LOAD` (for example for `httpfs`) and then 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, usage reporting and version check. +SQL that 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/packages/core/src/git.ts b/packages/core/src/git.ts index 27006eee0c..8ddee23964 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -7,44 +7,25 @@ import { AbsolutePath } from "./schema" import { FSUtil } from "./fs-util" import { AppProcess } from "./process" import { LayerNode } from "./effect/layer-node" -// altimate_change — offline transport policy +// altimate_change start — offline mode refuses Git commands that use the network import { offlineModeEnabled } from "./flag/flag" -// altimate_change start — prevent Git from starting a transport offline const remoteCommands = new Set(["clone", "fetch", "pull", "push", "ls-remote", "send-pack", "fetch-pack", "submodule--helper"]) -// Git LFS reads cached objects locally and contacts its endpoint only for missing ones. -// Pointing that endpoint at a closed loopback port keeps cached content and fails on the rest. -const OFFLINE_LFS_URL = "http://127.0.0.1:9/" - -export function localGitEnv(env?: Record) { - if (!offlineModeEnabled()) return env - const inherited = Number(env?.GIT_CONFIG_COUNT ?? process.env.GIT_CONFIG_COUNT ?? 0) - const index = Number.isInteger(inherited) && inherited > 0 ? inherited : 0 - // Inherited `-c` parameters are read after GIT_CONFIG_COUNT entries, so the override is appended there as well. - const parameters = env?.GIT_CONFIG_PARAMETERS ?? process.env.GIT_CONFIG_PARAMETERS - return { - ...env, - GIT_ALLOW_PROTOCOL: "", - GIT_NO_LAZY_FETCH: "1", - GIT_CONFIG_COUNT: String(index + 1), - [`GIT_CONFIG_KEY_${index}`]: "lfs.url", - [`GIT_CONFIG_VALUE_${index}`]: OFFLINE_LFS_URL, - ...(parameters ? { GIT_CONFIG_PARAMETERS: `${parameters} 'lfs.url=${OFFLINE_LFS_URL}'` } : {}), - } -} - 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, operation, ...rest] = args.slice(index) - return remoteCommands.has(command) || + return ( + remoteCommands.has(command) || (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) + ) } -// altimate_change end +export const GIT_OFFLINE_REFUSAL = "Git remote operations require an online run." +// altimate_change end export interface Repo { /** @@ -289,9 +270,6 @@ export const layer = Layer.effect( .run( ChildProcess.make("git", ["apply", "-"], { cwd: input.directory, - // altimate_change start — apply the offline transport policy to patch application - env: localGitEnv(), - // altimate_change end extendEnv: true, stdin: Stream.make(new TextEncoder().encode(input.patch)), }), @@ -375,9 +353,7 @@ export const layer = Layer.effect( cwd = repo.directory, ) { const result = yield* proc - // altimate_change start — apply offline transport policy to worktree commands - .run(ChildProcess.make("git", args, { cwd, env: localGitEnv(), extendEnv: true, stdin: "ignore" })) - // altimate_change end + .run(ChildProcess.make("git", args, { cwd, extendEnv: true, stdin: "ignore" })) .pipe( Effect.mapError( (cause) => new WorktreeError({ operation, directory: worktreeDirectory, message: cause.message, cause }), @@ -457,17 +433,16 @@ function run(cwd: string, proc: AppProcess.Interface) { execute(cwd, proc)(args).pipe(Effect.catch(() => Effect.succeed({ exitCode: 1, text: "", stderr: "" }))) } -// altimate_change start — enforce offline Git transport policy at the spawn boundary function execute(cwd: string, proc: AppProcess.Interface) { - return (args: string[]) => { - if (offlineModeEnabled() && gitCommandUsesNetwork(args)) { - return Effect.succeed({ exitCode: 1, text: "", stderr: "Git remote operations require an online run." }) - } - return proc + 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, { cwd, - env: localGitEnv(), extendEnv: true, stdin: "ignore", }), @@ -482,9 +457,7 @@ function execute(cwd: string, proc: AppProcess.Interface) { }) satisfies Result, ), ) - } } -// altimate_change end function resolvePath(cwd: string, value: string) { const trimmed = value.replace(/[\r\n]+$/, "") diff --git a/packages/core/src/skill/discovery.ts b/packages/core/src/skill/discovery.ts index 4c08deaa74..6402dd3b71 100644 --- a/packages/core/src/skill/discovery.ts +++ b/packages/core/src/skill/discovery.ts @@ -21,8 +21,7 @@ function isSafeSegment(value: string) { ) } -// altimate_change — share cache path validation with the CLI skill loader -export function isSafeRelativePath(value: string) { +function isSafeRelativePath(value: string) { const segments = value.split("/") return ( value.length > 0 && diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index 7006aa4362..e9498bcff6 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -1,10 +1,9 @@ import { describe, expect } from "bun:test" import { $ } from "bun" import fs from "fs/promises" -import os from "os" import path from "path" import { Effect } from "effect" -import { Git, localGitEnv } from "@opencode-ai/core/git" +import { Git } from "@opencode-ai/core/git" import { AbsolutePath } from "@opencode-ai/core/schema" import { branch, commit, gitRemote } from "./fixture/git" import { tmpdir } from "./fixture/tmpdir" @@ -52,76 +51,6 @@ describe("Git", () => { ), ) - it.live("offline LFS override is read after inherited -c parameters", () => - Effect.sync(() => { - const previous = { offline: process.env.ALTIMATE_OFFLINE, parameters: process.env.GIT_CONFIG_PARAMETERS } - process.env.ALTIMATE_OFFLINE = "1" - process.env.GIT_CONFIG_PARAMETERS = "'lfs.url'='https://inherited.example/'" - try { - const env = localGitEnv()! - expect(env.GIT_CONFIG_PARAMETERS).toBe("'lfs.url'='https://inherited.example/' 'lfs.url=http://127.0.0.1:9/'") - // Git reads the last value of a key, so the closed loopback endpoint wins. - const read = Bun.spawnSync(["git", "config", "--get", "lfs.url"], { env: { ...process.env, ...env }, stdout: "pipe" }) - expect(read.stdout.toString().trim()).toBe("http://127.0.0.1:9/") - } finally { - if (previous.offline === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous.offline - if (previous.parameters === undefined) delete process.env.GIT_CONFIG_PARAMETERS - else process.env.GIT_CONFIG_PARAMETERS = previous.parameters - } - }), - ) - - // Offline Git must not download LFS objects, but objects already in the local cache still check out. - const hasLfs = Bun.spawnSync(["git", "lfs", "version"], { stdout: "ignore", stderr: "ignore" }).exitCode === 0 - const liveIfLfs = hasLfs ? it.live : it.live.skip - liveIfLfs("offline checkout keeps cached LFS content and refuses uncached objects", () => - Effect.gen(function* () { - const tmp = yield* Effect.acquireRelease( - Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "offline-lfs-"))), - (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), - ) - // Repository-location variables inherited from a caller would redirect these commands away from tmp. - const base = Object.fromEntries( - Object.entries(process.env).filter( - ([key]) => !["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_COMMON_DIR"].includes(key), - ), - ) - const gitIn = (args: string[], env?: Record) => - Bun.spawnSync(["git", ...args], { cwd: tmp, env: { ...base, ...env }, stderr: "pipe", stdout: "pipe" }) - for (const args of [ - ["init", "-q"], - ["config", "commit.gpgsign", "false"], - ["config", "user.email", "t@example.com"], - ["config", "user.name", "t"], - ["lfs", "install", "--local"], - ["lfs", "track", "*.bin"], - ["remote", "add", "origin", "https://example.invalid/repo.git"], - ]) expect(gitIn(args).exitCode).toBe(0) - yield* Effect.promise(() => fs.writeFile(path.join(tmp, "a.bin"), "cached-content")) - expect(gitIn(["add", ".gitattributes", "a.bin"]).exitCode).toBe(0) - expect(gitIn(["commit", "-qm", "lfs"]).exitCode).toBe(0) - - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - const env = localGitEnv()! - yield* Effect.promise(() => fs.rm(path.join(tmp, "a.bin"))) - expect(gitIn(["checkout", "--", "a.bin"], env).exitCode).toBe(0) - expect(yield* Effect.promise(() => fs.readFile(path.join(tmp, "a.bin"), "utf8"))).toBe("cached-content") - - yield* Effect.promise(() => fs.rm(path.join(tmp, "a.bin"))) - yield* Effect.promise(() => fs.rm(path.join(tmp, ".git", "lfs", "objects"), { recursive: true, force: true })) - const missing = gitIn(["checkout", "--", "a.bin"], env) - expect(missing.exitCode).not.toBe(0) - expect(missing.stderr.toString()).toContain("127.0.0.1:9") - } 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/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index a2916c78d6..42fca5af31 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -1,5 +1,4 @@ import type { Config } from "./config" -import { dropLibpqDestinationVars } from "./offline-env" import { bufferLog } from "./log-buffer" import { recordManifest } from "./stale-manifest" export { getRecentDbtLogs, clearDbtLogs } from "./log-buffer" @@ -105,7 +104,6 @@ function env(cfg: Config, options: CreateOptions): RuntimePythonEnvironment { vars.DBT_SEND_ANONYMOUS_USAGE_STATS = "false" vars.DO_NOT_TRACK = "1" vars.DBT_VERSION_CHECK = "false" - dropLibpqDestinationVars(vars) } if (options.profilesDir) vars.DBT_PROFILES_DIR = options.profilesDir if (options.targetPath) vars.DBT_TARGET_PATH = options.targetPath diff --git a/packages/dbt-tools/src/offline-env.ts b/packages/dbt-tools/src/offline-env.ts deleted file mode 100644 index fbb4c2904a..0000000000 --- a/packages/dbt-tools/src/offline-env.ts +++ /dev/null @@ -1,10 +0,0 @@ -// altimate_change - new file -// libpq reads these connection destinations from the environment, overriding the profile host that offline -// mode checked. Offline dbt runs drop them. -export const LIBPQ_DESTINATION_VARS = ["PGHOSTADDR", "PGSERVICE", "PGSERVICEFILE"] as const - -/** Remove the libpq destination variables from `env`, matching names case-insensitively as Windows does. */ -export function dropLibpqDestinationVars(env: Record): void { - for (const key of Object.keys(env)) - if (LIBPQ_DESTINATION_VARS.some((name) => name === key.toUpperCase())) delete env[key] -} diff --git a/packages/drivers/src/duckdb.ts b/packages/drivers/src/duckdb.ts index 5e8f809bf6..fbf2f7a653 100644 --- a/packages/drivers/src/duckdb.ts +++ b/packages/drivers/src/duckdb.ts @@ -112,7 +112,7 @@ export async function connect( // altimate_change start — configurable open budget const { ms: openTimeoutMs, source: openTimeoutSource } = resolveOpenTimeoutMs(config) // altimate_change end - // altimate_change — skip automatic extension downloads in app-owned offline helpers + // altimate_change — offline mode never downloads DuckDB extensions const offline = !["", "0", "false"].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 diff --git a/packages/drivers/src/local-engine-child-source.ts b/packages/drivers/src/local-engine-child-source.ts index 0177be2a5d..3595e2f164 100644 --- a/packages/drivers/src/local-engine-child-source.ts +++ b/packages/drivers/src/local-engine-child-source.ts @@ -101,10 +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 — ordinary offline connections keep local file access - // Network-capable extensions such as httpfs may already be installed, so - // restricting downloads alone cannot prevent automatic remote I/O. - ...(p.offline ? { autoinstall_known_extensions: "false", autoload_known_extensions: "false" } : {}), + // 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 f7047761fd..ffcb8b1b19 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -1,5 +1,5 @@ // altimate_change start — offline mode -import { Offline } from "@/config/offline" +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" // altimate_change end // altimate_change start — debug report: gathers the facts `report.ts` analyses /** @@ -94,8 +94,7 @@ function envFlags(): string[] { /** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read * before it settles. Without, it is not started (it would send), so only the environment switches are checked. */ -export async function telemetryFacts(network: boolean): Promise { - if (Offline.enabled()) return { enabled: false, checked: false, reason: "offline mode" } +async function telemetryFacts(network: boolean): Promise { if (/^(1|true)$/i.test(process.env["ALTIMATE_TELEMETRY_DISABLED"] ?? "")) return { enabled: false, reason: "ALTIMATE_TELEMETRY_DISABLED is set" } if (/^(1|true)$/i.test(process.env["OPENCODE_DISABLE_TELEMETRY"] ?? "")) return { enabled: false, reason: "OPENCODE_DISABLE_TELEMETRY is set" } if (!network) return { enabled: false, checked: false, reason: "not started with --no-network" } @@ -314,7 +313,6 @@ export async function probe( opts: { proxy?: boolean; timeoutMs?: number } = {}, deps: ProbeDeps = defaultProbeDeps, ): Promise { - if (Offline.enabled()) return { target, host, ok: false, detail: "Skipped in offline mode", ms: 0 } const timeoutMs = opts.timeoutMs ?? NETWORK_TIMEOUT_MS const started = Date.now() const deadline = AbortSignal.timeout(timeoutMs) @@ -412,11 +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 && !Offline.enabled())]) + const [account, connections, telemetry] = await Promise.all([accountFacts(), connectionFacts(), telemetryFacts(opts.network)]) const proxy = PROXY_VARS.some((k) => k.toLowerCase() !== "no_proxy" && process.env[k]) - const network = opts.network && !Offline.enabled() + const network = opts.network ? await Promise.all(networkTargets(connections, account, telemetry).map((t) => probe(t.target, t.host, { proxy }))) : [] const logPath = path.join(Global.Path.log, "opencode.log") diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 5cfd39a694..75ad09cf90 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -2,74 +2,48 @@ import { isLocalFilePath, normalizeConfig, type ConnectionConfig } from "@altimateai/drivers" import { isLoopbackHost } from "@/config/offline" -function localStore(value: unknown): boolean { - // dbt renders Jinja (expressions, statements, comments) after this check, so only a literal path is local. - if (typeof value !== "string" || /\{[{%#]/.test(value)) return false - if (value === ":memory:" || value === "") return true - // UNC shares are network locations, even though they look like paths. - if (/^(?:\\\\|\/\/)/.test(value)) return false - if (/^file:/i.test(value)) { - try { - const url = new URL(value) - return (!url.hostname || url.hostname === "localhost") && !decodeURIComponent(url.pathname).startsWith("//") - } catch { return false } - } +const DENIED = "Offline mode allows only local file databases and warehouses at a loopback host." + +/** 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 + if (/^file:/i.test(value)) return URL.canParse(value) && ["", "localhost"].includes(new URL(value).hostname) + // Rejects scheme:// URLs (s3, gcs, http and so on) and DuckDB's non-slash remote schemes such as md:. return isLocalFilePath(value) } -/** Guard app-owned connection setup; SQL and project macros are user-controlled code. */ +/** Refuse a warehouse connection that does not stay on this machine. */ export function assertLocalConnection(raw: ConnectionConfig): void { const config = normalizeConfig(raw) - const type = config.type.toLowerCase() - const deny = () => { throw new Error("Offline mode allows only local file databases and loopback warehouse connections.") } - if (config.ssh_host || config.replica_set) deny() - // A Unix socket is a local file; a Windows named pipe or other value is not checked here. - if (config.socketPath && !(typeof config.socketPath === "string" && config.socketPath.startsWith("/"))) deny() + const type = String(config.type).toLowerCase() if (type === "duckdb" || type === "sqlite") { - if (!localStore(config.path)) deny() + if (!isLocalPath(config.path)) throw new Error(DENIED) return } - if (!["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "oracle", "redshift", "clickhouse", "trino", "mongodb", "mongo"].includes(type)) deny() - // Cloud authentication may contact an identity provider even for a loopback host. - if (config.authentication && !["sql", "ntlm"].includes(String(config.authentication).toLowerCase())) deny() - const mongo = type === "mongodb" || type === "mongo" - if (mongo && config.direct_connection !== undefined && config.direct_connection !== true) deny() + if (config.ssh_host) 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) // Postgres accepts a socket directory as its host. - const postgres = ["postgres", "postgresql", "redshift"].includes(type) - const socketHost = typeof config.host === "string" && config.host.startsWith("/") && postgres - // SQL Server names an instance as host\instance. - const host = typeof config.host === "string" && ["sqlserver", "mssql"].includes(type) ? config.host.split("\\")[0] : config.host - if (host !== undefined && !socketHost && !isLoopbackHost(host)) deny() - // dbt-mysql and others name the host `server`; Trino's `server` is a URL checked below. - if (type !== "trino" && config.server !== undefined && !isLoopbackHost(config.server)) deny() - // Trino and ClickHouse build `${protocol}://${host}` URLs, so a protocol value can carry its own authority. - if ((type === "trino" || type === "clickhouse") && config.protocol !== undefined && - !["http", "https"].includes(String(config.protocol).trim().toLowerCase())) deny() - const connectionString = type === "trino" - ? config.connection_string ?? config.server ?? config.url - : config.connection_string - if (type === "oracle" && typeof connectionString === "string" && !connectionString.includes("://")) { - // Easy Connect: host[:port][/service]. Descriptors and TNS aliases name hosts this check cannot see. - const easy = /^(?:\/\/)?(\[[^\]]+\]|[^:/\s()]+)(?::\d+)?(?:\/[^\s()]*)?$/.exec(connectionString.trim()) - if (!easy || !isLoopbackHost(easy[1])) deny() - } else if (connectionString) { + const hosts = [config.host, config.server].filter((value) => value !== undefined) + for (const host of hosts) { + if (typeof host === "string" && host.startsWith("/")) continue + if (!isLoopbackHost(host)) throw new Error(DENIED) + } + const url = config.connection_string ?? config.url + if (url !== undefined) { + let hostname: string try { - const url = new URL(String(connectionString)) - if ((type === "trino" || type === "clickhouse") && !["http:", "https:"].includes(url.protocol)) deny() - const query = new Map([...url.searchParams].map(([key, value]) => [key.toLowerCase(), value.toLowerCase()])) - // postgresql:///db?host=/run/postgresql connects through a local Unix socket. - // Exactly one lowercase host parameter, naming a socket directory; drivers read only that exact key. - const hostParams = [...url.searchParams.keys()].filter((key) => key.toLowerCase() === "host") - const socketURL = postgres && !url.hostname && hostParams.length === 1 && hostParams[0] === "host" && - url.searchParams.get("host")!.startsWith("/") && !query.has("hostaddr") - if ((!socketURL && !isLoopbackHost(url.hostname)) || url.protocol === "mongodb+srv:") deny() - if (mongo && config.direct_connection !== true && query.get("directconnection") !== "true") deny() - if (mongo && ["mongodb-aws", "mongodb-oidc", "gssapi"].includes(query.get("authmechanism") ?? "")) deny() - // Drivers can override the authority via URL parameters or discover replica peers. - for (const key of url.searchParams.keys()) { - if (socketURL && key === "host") continue - if (["host", "hostaddr", "server", "replicaset", "service"].includes(key.toLowerCase())) deny() - } - } catch { deny() } - } else if (mongo && config.direct_connection !== true) deny() + hostname = new URL(String(url)).hostname + } catch { + throw new Error(DENIED) + } + if (!isLoopbackHost(hostname)) throw new Error(DENIED) + } + // 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 LOCALHOST_BY_DEFAULT = new Set(["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "clickhouse", "mongodb", "mongo"]) diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 25278a9c35..6b917a68ad 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -1,6 +1,6 @@ // altimate_change start — validate offline dbt profiles before starting adapters import { Offline } from "@/config/offline" -import { assertLocalDbt, OfflineDbtError } from "../dbt/offline" +import { assertLocalDbt } from "../dbt/offline" // altimate_change end /** * Register native connection handlers with the Dispatcher. @@ -128,6 +128,7 @@ async function ensureDbtAdapter(): Promise { return publish(null) } + // Offline, a profile that leaves this machine falls back to the native driver, which checks its own target. // 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) @@ -146,8 +147,7 @@ async function ensureDbtAdapter(): Promise { await create(dbtConfig, { ...options, ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}) }), dbtConfig.projectRoot, ) - } catch (error) { - if (error instanceof OfflineDbtError) throw error + } catch { // dbt-tools not available or config invalid — fall back to native return publish(null) } finally { @@ -303,7 +303,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 (e instanceof OfflineDbtError || isQueryTimeoutError(e) || context?.signal?.aborted || (e instanceof Error && e.name === "AbortError")) throw e + if (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 0d59b514ce..45f2a70aaf 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -83,10 +83,6 @@ function createState(dir: string): State { /** Registry state per resolved project directory. */ const states = new Map() -// Classify the resolved target before SSH rewrites or driver construction. Keep only -// the verdict, not credentials, and never consult the keychain again on cache hits. -const offlineVerdicts = new WeakMap() - /** Invalidate the in-flight connect for `name`, closing the tunnel it opened. Synchronous. */ function dropAttempt(s: State, name: string): void { const attempt = s.pending.get(name) @@ -454,14 +450,8 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) - // altimate_change — check the effective target after restoring stored credentials - const offlineVerdict: { error?: Error } = {} - try { - assertLocalConnection(resolvedConfig) - } catch (error) { - offlineVerdict.error = error instanceof Error ? error : new Error(String(error)) - } - if (Offline.enabled() && offlineVerdict.error) throw offlineVerdict.error + // altimate_change — offline mode checks the effective target, after stored credentials are restored + if (Offline.enabled()) assertLocalConnection(resolvedConfig) // altimate_change start — validate password is a string for drivers that require it // Prevents cryptic SASL/SCRAM errors from database drivers @@ -561,7 +551,6 @@ async function createConnector( throw new Error(`No static import available for driver: ${driverPath}`) } connector = await mod.connect(resolvedConfig) - offlineVerdicts.set(connector, offlineVerdict) } catch (e) { // Clean up SSH tunnel if driver creation fails // altimate_change start — this attempt's own tunnel, never another attempt's @@ -690,14 +679,6 @@ export async function get(name: string): Promise { const cached = connectors.get(name) if (cached) { - // altimate_change — apply the offline policy before using a cached connection - if (Offline.enabled()) { - const verdict = offlineVerdicts.get(cached) - if (!verdict || verdict.error) { - await detachCached(s, name)() - throw verdict?.error ?? new Error("Offline mode could not verify the cached connection target.") - } - } // 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 diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index 6920ebf344..cd6074f2b9 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -3,21 +3,7 @@ import fs from "node:fs/promises" import path from "node:path" import os from "node:os" import { parse } from "yaml" -import { assertLocalConnection } from "../connections/offline" - -function resolve(value: unknown): any { - if (typeof value === "string") return value.replace( - /\{\{\s*env_var\s*\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])(.*?)\3\s*)?\)\s*\}\}/g, - (_, _quote, name, _defaultQuote, fallback) => process.env[name] ?? fallback ?? "{{unresolved}}", - ) - if (Array.isArray(value)) return value.map(resolve) - if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolve(v)])) - return value -} - -export class OfflineDbtError extends Error { - override name = "OfflineDbtError" -} +import { assertLocalConnection, isLocalPath } from "../connections/offline" /** dbt searches the starting directory and its parents for the project file. */ async function findProjectRoot(start: string): Promise { @@ -30,85 +16,71 @@ async function findProjectRoot(start: string): Promise { } } +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 || + (Array.isArray(output.filesystems) && output.filesystems.length > 0) || + (Array.isArray(output.secrets) && output.secrets.length > 0) + ) +} + /** - * Resolve exactly the selected profile/target before starting dbt-owned network work. - * `cwd` is the directory dbt will run in: dbt reads `profiles.yml` from there, not from the project. - * Returns the profiles directory that was checked, so the caller can pin dbt to that same file. + * 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 }> { - try { - return await checkLocalDbt(projectRoot, args, integration, cwd) - } catch (error) { - // Policy refusals are typed; a missing or unreadable project or profile keeps its own error. - if (error instanceof Error && error.message.startsWith("Offline mode")) - throw new OfflineDbtError(error.message, { cause: error }) - throw error - } -} - -async function checkLocalDbt( - projectRoot: string, - args: string[], - integration: string, - cwd: string, ): Promise<{ profilesDir: string }> { if (!["core", "corecommand", "fusion"].includes(integration)) throw new Error("Offline mode disables cloud dbt integrations.") - const option = (...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] - break - } - const prefix = name.startsWith("--") ? name + "=" : name - if (arg.startsWith(prefix)) result = arg.slice(prefix.length) - } - } - return result - } - const root = option("--project-dir") ?? process.env.DBT_PROJECT_DIR ?? (await findProjectRoot(projectRoot)) - const project = resolve(parse(await fs.readFile(path.join(root, "dbt_project.yml"), "utf8"))) + 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. - // dbt expands ~ in the profiles directory. - const explicit = (option("--profiles-dir") ?? process.env.DBT_PROFILES_DIR)?.replace(/^~(?=$|[\\/])/, () => os.homedir()) + 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"))), + explicit ?? (await fs.stat(path.join(cwd, "profiles.yml")).then(() => cwd, () => path.join(os.homedir(), ".dbt"))), ) - const profiles = resolve(parse(await fs.readFile(path.join(profilesDir, "profiles.yml"), "utf8"))) - const profileName = option("--profile") ?? process.env.DBT_PROFILE ?? project.profile - const profile = profiles?.[profileName] - const target = option("--target", "-t") ?? process.env.DBT_TARGET ?? profile?.target ?? "default" - const output = profile?.outputs?.[target] - if (!output || typeof output.type !== "string") throw new Error("Offline mode could not resolve a local dbt profile and target.") - if (!["duckdb", "sqlite"].includes(output.type)) { - if (!output.host && !output.server && !output.connection_string) - throw new Error("Offline mode requires an explicit loopback host in the dbt profile.") - if (output.method && !["database", "password", "none"].includes(output.method)) - throw new Error("Offline mode disables dbt cloud authentication.") - } + 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 }) + 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) }) } - // These profile hooks cause dbt-duckdb to install extensions or open extra connections at startup. - // dbt renders templates after this check, so only a literal path can be judged local. - if (typeof output.external_root === "string" && /\{\{|\{%/.test(output.external_root)) - throw new Error("Offline mode requires a literal local external_root in the dbt profile.") - const remoteRoot = typeof output.external_root === "string" && - (/^(?:\\\\|\/\/)/.test(output.external_root) || /^[a-z][a-z0-9+.-]*:\/\//i.test(output.external_root)) - if (output.extensions?.length || output.attach?.length || output.plugins?.length || output.secrets?.length || - output.filesystems?.length || output.remote || remoteRoot) - throw new Error("Offline mode requires a dbt profile without extension installs, attachments, plugins, remote secrets, remote storage, or a remote server.") + if (output.type === "duckdb" && remoteDuckdbSetting(output)) + throw new Error("Offline mode refuses dbt-duckdb settings that use remote storage, a remote server or remote extensions.") return { profilesDir } } diff --git a/packages/opencode/src/altimate/native/dbt/runner.ts b/packages/opencode/src/altimate/native/dbt/runner.ts index 4156263224..7686767941 100644 --- a/packages/opencode/src/altimate/native/dbt/runner.ts +++ b/packages/opencode/src/altimate/native/dbt/runner.ts @@ -1,7 +1,6 @@ // altimate_change start — validate offline dbt targets before spawning dbt import { Offline } from "@/config/offline" import { assertLocalDbt } from "./offline" -import { dropLibpqDestinationVars } from "../../../../../dbt-tools/src/offline-env" // altimate_change end /** * dbt CLI wrapper — spawn dbt commands as subprocesses. @@ -49,10 +48,8 @@ export async function runDbt(params: DbtRunParams): Promise { ...(params.args ?? []), ...(params.project_dir ? ["--project-dir", params.project_dir] : []), ]) - const inherited = { ...process.env } - dropLibpqDestinationVars(inherited) offlineEnv = { - ...inherited, + ...process.env, ...(checked ? { DBT_PROFILES_DIR: checked.profilesDir } : {}), DBT_SEND_ANONYMOUS_USAGE_STATS: "false", DO_NOT_TRACK: "1", diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index c299354503..4d80d82656 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -1,5 +1,6 @@ import { execFile } from "node:child_process" -import { Offline } from "@/config/offline" +// altimate_change — offline mode +import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" // 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 @@ -86,9 +87,10 @@ async function probe(): Promise { // + PATH + explicit override via ALTIMATE_DBT_PATH). Returns the first // candidate that exists. const resolved = resolveDbt() - // `dbt --version` asks PyPI for the latest release whatever DBT_VERSION_CHECK says. Offline, that - // lookup goes to a closed loopback proxy and fails locally; dbt still prints the installed versions. - const env = Offline.enabled() ? { ...buildDbtEnv(resolved), ...Offline.CLOSED_PROXY_ENV } : buildDbtEnv(resolved) + // altimate_change start — `dbt --version` asks PyPI for the latest release, so offline mode does not run it + if (offlineModeEnabled()) return { hasDbt: !resolved.source.startsWith("fallback"), hasDbtDuckdb: false } + // altimate_change end + const env = buildDbtEnv(resolved) // Async --version invocation. Reads BOTH stdout AND stderr (some dbt 1.x // builds write --version output to stderr with color codes). If it fails, @@ -104,12 +106,7 @@ async function probe(): Promise { if (!out.ok && process.platform === "win32") { out = await runDbtVia(env, "cmd.exe", ["/c", "dbt", "--version"]) } - const combined = `${out.stdout}\n${out.stderr}` - const versionMatch = - combined.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/) ?? - combined.match(/core=([0-9]+\.[0-9]+\.[0-9]+\S*)/) - // Offline, a probe that timed out or exited non-zero still counts when it printed dbt's version. - if (!out.ok && !(Offline.enabled() && versionMatch)) return { hasDbt: false, hasDbtDuckdb: false } + if (!out.ok) return { hasDbt: false, hasDbtDuckdb: false } // dbt --version on 1.x prints: // Core: @@ -118,7 +115,12 @@ async function probe(): Promise { // - duckdb: 1.11.4 - Update available! // Match the plugin line specifically ("- duckdb:") — a generic "duckdb" // substring would false-positive on an "install dbt-duckdb" upgrade hint. + const combined = `${out.stdout}\n${out.stderr}` const hasDbtDuckdb = /^\s*-\s*duckdb:/m.test(combined) + + const versionMatch = + combined.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/) ?? + combined.match(/core=([0-9]+\.[0-9]+\.[0-9]+\S*)/) return { hasDbt: true, hasDbtDuckdb, diff --git a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts index 7608754331..4ff375709c 100644 --- a/packages/opencode/src/altimate/tool-cli/workspace-tools.ts +++ b/packages/opencode/src/altimate/tool-cli/workspace-tools.ts @@ -23,9 +23,7 @@ export async function resolveWorkspaceTools( directory: string, linked: (directory: string) => Promise = projectIsLinked, ): Promise { - // Workspace tools call the workspace service, which offline mode does not reach. The target project's - // own offline setting applies too (tool daemon --dir can name another project). - await Offline.start(directory) + // 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 diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index c46b8fb2f2..595d3695d1 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -3,7 +3,8 @@ import { Tool } from "../../tool/tool" import { Dispatcher } from "../native" import { existsSync, readFileSync } from "fs" import path from "path" -import { Offline } from "@/config/offline" +// 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" @@ -95,14 +96,12 @@ export interface ConfigFileInfo { */ export function safeSpawnSync( args: string[], - opts?: { timeout?: number; env?: Record }, + opts?: { timeout?: number }, ): { exitCode: number; stdout: string; stderr: string } | null { try { const result = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe", - // altimate_change — offline dbt probe environment - ...(opts?.env && { env: opts.env }), ...(opts?.timeout !== undefined && { timeout: opts.timeout }), }) return { @@ -487,20 +486,9 @@ 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 => { - // `dbt --version` asks PyPI for the latest release; offline, that lookup goes to a closed loopback proxy. - const env = tool === "dbt" && Offline.enabled() ? { ...process.env, ...Offline.CLOSED_PROXY_ENV } : undefined - const result = safeSpawnSync([tool, "--version"], { timeout: 5000, env }) - // Offline, a probe that did not finish still shows dbt is installed: use what it printed, else PATH. - if (env && !(result && result.exitCode === 0)) { - // dbt 1.x prints "Core:" then " - installed: "; older output leads with the version. - // Some dbt builds print --version to stderr. - const output = result ? `${result.stdout}\n${result.stderr}` : "" - const version = result - ? (output.match(/-\s*installed:\s*([0-9]+\.[0-9]+\.[0-9]+\S*)/)?.[1] ?? parseToolVersion(output.trim())) - : undefined - const installed = version !== undefined || Bun.which(tool, { PATH: process.env.PATH ?? "" }) !== null - return { name: tool, installed, ...(version ? { version } : {}) } - } + // 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) !== null } + const result = safeSpawnSync([tool, "--version"], { timeout: 5000 }) if (result && result.exitCode === 0) { return { name: tool, diff --git a/packages/opencode/src/altimate/workspace/skill-sync.ts b/packages/opencode/src/altimate/workspace/skill-sync.ts index b70d4e38c1..1ae6738749 100644 --- a/packages/opencode/src/altimate/workspace/skill-sync.ts +++ b/packages/opencode/src/altimate/workspace/skill-sync.ts @@ -68,7 +68,6 @@ import { credentialDigest, currentScope, readLocalBinding, - readLocalBindingScopedStrict, resolveBindingOutcome, type AccountKey, type CachedBinding, @@ -189,20 +188,7 @@ export async function ownManifest(directory: string): Promise { manifest.tenant === creds.altimateInstanceName && manifest.apiUrl === creds.altimateUrl && manifest.account === credentialDigest(creds.altimateUrl, creds.altimateInstanceName, creds.altimateApiKey) - if (!ours) return null - // altimate_change — hide a stale workspace snapshot offline without removing it - if (Offline.enabled()) { - // A serve pin outranks the project's link, as in resolveBindingOutcome; a broken pin fails closed. - const raw = readPin() - // A pin covers only the tree serve was launched for. - const pin = raw.kind === "valid" && resolveWithinRoot(directory, raw.root) === null ? { kind: "absent" as const } : raw - if (pin.kind === "invalid" || (pin.kind === "valid" && pin.datamateId !== manifest.datamateId)) return null - // A matching pin decides on its own; the project's link is consulted only without one. - if (pin.kind === "valid") return manifest - const { binding: local } = await readLocalBindingScopedStrict(directory) - if (local && local.datamateId !== manifest.datamateId) return null - } - return manifest + return ours ? manifest : null } catch { return null } @@ -521,13 +507,7 @@ async function registryIdentity(canon: string): Promise { } catch { /* no credentials resolved; the empty account is the honest answer */ } - // altimate_change — a changed local binding can hide a snapshot without changing its files - const binding = Offline.enabled() - ? await readLocalBindingScopedStrict(canon) - .then(({ binding }) => binding?.datamateId ?? "") - .catch(() => "unreadable") - : "" - return `${snapshotFingerprint(canon)}\u0000${account}\u0000${binding}` + return `${snapshotFingerprint(canon)}\u0000${account}` } /** Does the skill registry still reflect a different snapshot, or a different @@ -1261,6 +1241,7 @@ 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 diff --git a/packages/opencode/src/altimate/workspace/state.ts b/packages/opencode/src/altimate/workspace/state.ts index 34b78d5de7..fb501c52f9 100644 --- a/packages/opencode/src/altimate/workspace/state.ts +++ b/packages/opencode/src/altimate/workspace/state.ts @@ -1,5 +1,4 @@ // altimate_change - new file -import { Offline } from "@/config/offline" // // Local binding cache — offline fallback for the server-authoritative // pre-check. Scoped to (tenant, apiUrl, account) at the top level so a @@ -765,7 +764,7 @@ export async function resolvePinnedBindingForRouting( ): Promise { const pin = readPinLogged() if (pin.kind === "absent") return null - if (Offline.enabled() || pin.kind === "invalid") return { status: "unknown" } + if (pin.kind === "invalid") return { status: "unknown" } return resolvePinnedBinding(directory, pin) } @@ -862,10 +861,6 @@ export function endTurnBinding(sessionID: string): void { } export async function resolveBindingOutcome(directory: string): Promise { - if (Offline.enabled()) { - const local = readPinLogged().kind === "absent" ? await readLocalBinding(directory).catch(() => null) : null - return local ? { status: "bound", binding: local, stale: true } : { status: "unknown" } - } // altimate_change — the IDE extension's selection outranks whatever binding this project carries. // Checked before the local cache and before any server lookup: the whole point is that the panel, // not the project's history, decides which workspace this `serve` process works against. diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index 1470977ae5..eb713cec02 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -1,4 +1,4 @@ -// altimate_change start — check offline policy before starting the standalone MCP server +// altimate_change start — offline mode import { Offline } from "@/config/offline" // altimate_change end import { cmd } from "./cmd" @@ -140,10 +140,9 @@ 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) { - await Offline.start(process.cwd()) - if (Offline.enabled() && args.workspaceTools) { - process.stderr.write("Workspace tools are unavailable in offline mode.\n") - } + // 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, @@ -557,11 +556,7 @@ export const McpAddCommand = effectCmd({ .option("env", { type: "array", string: true, describe: "Environment variables as key=value (repeatable)" }) .option("header", { type: "array", string: true, describe: "HTTP headers as key=value (repeatable)" }) .option("oauth", { type: "boolean", describe: "Enable OAuth", default: true }) - .option("global", { type: "boolean", describe: "Add to global config", default: false }) - .middleware((args) => { - // Reject before effectCmd initializes config (which can add its schema field). - if (args.url && args.type !== "local") Offline.assertLocalMcp({ type: "remote", url: args.url }) - }), + .option("global", { type: "boolean", describe: "Add to global config", default: false }), // altimate_change end handler: Effect.fn("Cli.mcp.add")(function* (args) { const maybeCtx = yield* InstanceRef @@ -935,9 +930,7 @@ export const McpDebugCommand = effectCmd({ // Test basic HTTP connectivity first try { - // altimate_change start — offline mode keeps the probe on loopback - const response = await (Offline.enabled() ? Offline.localFetch() : fetch)(serverConfig.url, { - // altimate_change end + const response = await fetch(serverConfig.url, { method: "POST", headers: { ...serverConfig.headers, @@ -991,9 +984,6 @@ export const McpDebugCommand = effectCmd({ // Try creating transport with auth provider to trigger discovery const transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), { authProvider, - // altimate_change start — offline mode keeps the probe on loopback - fetch: Offline.enabled() ? Offline.localFetch() : undefined, - // altimate_change end requestInit: serverConfig.headers ? { headers: serverConfig.headers } : undefined, }) diff --git a/packages/opencode/src/cli/cmd/session.ts b/packages/opencode/src/cli/cmd/session.ts index 8d1cc37e00..9e6ddda9d2 100644 --- a/packages/opencode/src/cli/cmd/session.ts +++ b/packages/opencode/src/cli/cmd/session.ts @@ -62,12 +62,7 @@ export const SessionDeleteCommand = effectCmd({ const sessionID = SessionID.make(args.sessionID) yield* svc .remove(sessionID) - .pipe( - Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`)), - // altimate_change start — offline mode keeps a shared session until its share can be revoked - Effect.catchTag("Session.OfflinePolicyError", (error) => fail(error.message)), - // altimate_change end - ) + .pipe(Effect.catchIf(NotFoundError.isInstance, () => fail(`Session not found: ${args.sessionID}`))) UI.println(UI.Style.TEXT_SUCCESS_BOLD + `Session ${args.sessionID} deleted` + UI.Style.TEXT_NORMAL) }), }) diff --git a/packages/opencode/src/cli/cmd/skill.ts b/packages/opencode/src/cli/cmd/skill.ts index 3307535abe..02999a5110 100644 --- a/packages/opencode/src/cli/cmd/skill.ts +++ b/packages/opencode/src/cli/cmd/skill.ts @@ -424,7 +424,7 @@ const SkillTestCommand = cmd({ try { const worktreeDir = Instance.worktree !== "/" ? Instance.worktree : projectDir const toolEnv = { - ...Offline.userEnv({ ...process.env }), + ...process.env, PATH: [ process.env.ALTIMATE_BIN_DIR, path.join(worktreeDir, ".opencode", "tools"), @@ -658,12 +658,9 @@ const SkillInstallCommand = cmd({ }), async handler(args) { let source = (args.source as string).trim().replace(/\.git$/, "") - const githubShorthand = /^[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/ - const offlineLocal = Offline.enabled() && githubShorthand.test(source) && - (await fs.stat(path.resolve(source)).catch(() => undefined))?.isDirectory() - if (Offline.enabled() && !offlineLocal && (/^https?:\/\//.test(source) || githubShorthand.test(source))) { + // 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) { @@ -700,7 +697,7 @@ const SkillInstallCommand = cmd({ process.exit(1) } skillDir = tmpDir - } else if (!offlineLocal && githubShorthand.test(source)) { + } else if (source.match(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/)) { // GitHub shorthand: owner/repo const url = `https://github.com/${source}.git` process.stdout.write(`Fetching from github.com/${source}...` + EOL) diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index 3bdd5837e9..43389f4e3d 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -1,5 +1,4 @@ // altimate_change - new file -import { Offline } from "@/config/offline" // // Model-free access to the data tools: `tool list`, `tool run` and the optional `tool daemon` // that keeps warehouse connections and the schema cache warm between calls. The tool modules are @@ -218,7 +217,7 @@ const ToolRunCommand = cmd({ const directory = process.cwd() const workspaceTools = await resolveWorkspaceTools(args["workspace-tools"], directory) const daemon = await import("../../altimate/tool-cli/daemon") - const reply = !Offline.enabled() && args.daemon && !daemon.daemonDisabled() + const reply = args.daemon && !daemon.daemonDisabled() ? await daemon.runViaDaemon(directory, InstallationVersion, { id: randomUUID(), name, diff --git a/packages/opencode/src/cli/cmd/upgrade.ts b/packages/opencode/src/cli/cmd/upgrade.ts index 0680c1b3d3..1906986039 100644 --- a/packages/opencode/src/cli/cmd/upgrade.ts +++ b/packages/opencode/src/cli/cmd/upgrade.ts @@ -1,6 +1,3 @@ -// altimate_change start — explicit upgrade requires a connection -import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" -// altimate_change end import type { Argv } from "yargs" import { UI } from "../ui" import * as prompts from "@clack/prompts" @@ -34,9 +31,6 @@ export const UpgradeCommand = { }) }, handler: async (args: { target?: string; method?: string }) => { - // altimate_change start — fail before checking installation or versions - if (offlineModeEnabled()) throw new Error("Run the upgrade while online.") - // altimate_change end UI.empty() UI.println(UI.logo(" ")) UI.empty() diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 0115230070..0161d4de67 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -44,8 +44,9 @@ import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding" // its events buffer until Telemetry.init() runs inside the Instance context in traceReady below // (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). -if (Offline.enabled()) await Offline.start(process.cwd()) -else Telemetry.startLoopMonitor() +Telemetry.startLoopMonitor() +// altimate_change — 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/config/config.ts b/packages/opencode/src/config/config.ts index 6f721315df..6c15dd1412 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -502,9 +502,6 @@ export const layer = Layer.effect( const loadInstanceState = Effect.fn("Config.loadInstanceState")( function* (ctx: InstanceContext) { - // altimate_change start — skip network work in offline mode - yield* Effect.promise(() => Offline.assertStartupPolicy(ctx.directory)) - // altimate_change end const auth = yield* authSvc.all().pipe(Effect.orDie) let result: Info = {} @@ -692,6 +689,8 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } + // altimate_change — `"offline": true` in a local config turns offline mode on before the account request + if (result.offline === true) Offline.start() const activeAccount = Option.getOrUndefined( yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none()))), ) @@ -783,6 +782,8 @@ 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. + // altimate_change — managed config can turn offline mode on too + if (result.offline === true) Offline.start() const deps: Fiber.Fiber[] = [] for (const dir of directories) { if (!Offline.enabled() && ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index b9582c4841..527f81fc64 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -1,31 +1,35 @@ +// 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. import fs from "node:fs/promises" import { isIP } from "node:net" import path from "node:path" -import { parse } from "jsonc-parser" -import * as Effect from "effect/Effect" +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" -const configNames = ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"] - export { enabled } -async function localOptIn(directory: string) { - // The switch is an opt-in from any local config source. Read just this - // key so remote credentials and unrelated substitutions cannot affect it. - const optedIn = async (text: string | undefined, source: string | { source: string; dir: string }) => { - if (!text) return false - // Skip the substitution pass for text that can neither name nor produce the key. - if (!text.includes("offline") && !/\{env:|\$\{|\{file:|\\u/.test(text)) return false - if (parse(text)?.offline === true) return true - const config = await ConfigPaths.parseText(text, source, "empty", { track: false, expandFiles: false }).catch(() => undefined) +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. Organisation-managed config is applied when the configuration loads. + */ +export async function optedIn(directory: string): Promise { + const sets = async (text: string | undefined, source: string | { source: string; dir: string }) => { + if (!text || (!text.includes("offline") && !/\{env:|\$\{|\{file:/.test(text))) return false + const config = await ConfigPaths.parseText(text, source, "empty", { track: false }).catch(() => undefined) return config?.offline === true } - if (await optedIn(env("OPENCODE_CONFIG_CONTENT"), { source: "OPENCODE_CONFIG_CONTENT", dir: directory })) return 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) @@ -39,171 +43,84 @@ async function localOptIn(directory: string) { : Effect.all([ ConfigPaths.files("opencode", directory, worktree), ConfigPaths.files("altimate-code", directory, worktree), - ]).pipe(Effect.map((sources) => sources.flat())), + ]).pipe(Effect.map((found) => found.flat())), ConfigPaths.directories(directory, worktree), ]).pipe(Effect.provide(FSUtil.defaultLayer)), ) const files = [ ...projectFiles, - ...[...dirs, ConfigManaged.managedConfigDir()].flatMap((dir) => configNames.map((name) => path.join(dir, name))), + ...dirs.flatMap((dir) => CONFIG_NAMES.map((name) => path.join(dir, name))), path.join(Global.Path.config, "config.json"), Flag.OPENCODE_CONFIG, ] for (const file of files) { - if (file && (await optedIn(await fs.readFile(file, "utf8").catch(() => undefined), file))) return true - } - // The legacy global TOML file is converted to config.json only after startup, so read it here too. - const legacy = await fs.readFile(path.join(Global.Path.config, "config"), "utf8").catch(() => undefined) - if (legacy !== undefined) { - try { - if ((Bun.TOML.parse(legacy) as { offline?: unknown }).offline === true) return true - } catch { - // An unparseable file still counts when it plainly requests offline mode. - if (/^\s*offline\s*=\s*true\b/m.test(legacy)) return true - } + if (file && (await sets(await fs.readFile(file, "utf8").catch(() => undefined), file))) return true } - const managed = await ConfigManaged.readManagedPreferences().catch(() => undefined) - return managed ? optedIn(managed.text, { source: managed.source, dir: path.dirname(managed.source) }) : false + return false } -/** - * Environment for an app-owned helper program whose only network use is optional (for example dbt's - * version lookup): every proxy points at a closed loopback port, so its requests fail on this machine. - */ -export const CLOSED_PROXY_ENV: Record = { - HTTP_PROXY: "http://127.0.0.1:9", - HTTPS_PROXY: "http://127.0.0.1:9", - ALL_PROXY: "http://127.0.0.1:9", - http_proxy: "http://127.0.0.1:9", - https_proxy: "http://127.0.0.1:9", - all_proxy: "http://127.0.0.1:9", - NO_PROXY: "", - no_proxy: "", -} - -export const SHARE_REFUSAL = "Sharing sessions requires an online run." -export const UNSHARE_REFUSAL = "Offline mode cannot revoke a share. Run unshare while online." - -/** A refusal by the offline policy. Servers report it to the client as a 400 with this message. */ -export class OfflinePolicyError extends Error { - override name = "OfflinePolicyError" -} - -/** The policy refusal behind an error, following `cause` links that runtimes add when they wrap it. */ -export function policyError(error: unknown): OfflinePolicyError | undefined { - for (let current = error, depth = 0; current && depth < 8; depth++) { - if (current instanceof OfflinePolicyError) return current - current = (current as { cause?: unknown }).cause - } - return undefined -} - -export async function assertStartupPolicy(directory: string) { - if (!enabled() && (await localOptIn(directory))) { - throw new OfflinePolicyError( - "This project requests offline mode. Start Altimate Code from the project to apply its offline policy.", - ) - } -} +/** 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]"] let networkFetch: typeof fetch | undefined -const USER_PROXY = "ALTIMATE_OFFLINE_USER_PROXY" - /** - * Environment for programs the user runs or configures (shell commands, language servers, - * stdio MCP servers). Offline mode does not police their network access, so they get the - * user's original proxy exclusions back instead of the process-wide bypass. + * 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 userEnv>(env: T): T { - // The session's model choice is internal; a program the user runs (even a nested altimate-code) chooses its own. - delete env.ALTIMATE_OFFLINE_MODEL - const saved = env[USER_PROXY] ?? process.env[USER_PROXY] - if (saved === undefined) return env - delete env[USER_PROXY] - try { - const original = JSON.parse(saved) as Record - for (const key of ["NO_PROXY", "no_proxy"] as const) { - // Only the inherited bypass is replaced; a value the program's own config set stays. An absent key is - // treated as inherited too, since a copied environment may not carry it. - if (env[key] !== undefined && env[key] !== process.env[key]) continue - const value = original[key] - if (typeof value === "string") (env as Record)[key] = value - else delete env[key] - } - } catch {} - return env -} - -export async function start(directory: string, model?: string) { - if (!enabled() && !(await localOptIn(directory))) return - // Workers and core services must see the same policy before constructing - // their layers. Once enabled, keep it for the lifetime of the process. +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" - // Bun consults proxy environment variables even when fetch sets proxy: "". - // Offline traffic must go directly to the one configured endpoint. The user's own - // values are kept (and inherited by workers) so their programs get them back: see userEnv. - if (process.env[USER_PROXY] === undefined) - process.env[USER_PROXY] = JSON.stringify({ NO_PROXY: process.env.NO_PROXY, no_proxy: process.env.no_proxy }) - process.env.NO_PROXY = "*" - process.env.no_proxy = "*" - if (model) process.env.ALTIMATE_OFFLINE_MODEL = model 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. + for (const key of ["NO_PROXY", "no_proxy"]) { + const current = process.env[key] + if (current === "*") continue + const entries = (current ?? "").split(",").map((entry) => entry.trim()).filter(Boolean) + process.env[key] = [...entries, ...LOCAL_FETCH_HOSTS.filter((host) => !entries.includes(host))].join(",") + } networkFetch = globalThis.fetch globalThis.fetch = Object.assign( - async (...args: Parameters) => { - const [input] = args - if (isLocalURL(input instanceof Request ? input.url : input.toString())) return localFetch()(...args) - throw new Error("Offline mode allows network requests only to the configured model endpoint or loopback services.") + async (input: Parameters[0], init?: Parameters[1]) => { + if (!isLocalURL(input instanceof Request ? input.url : input.toString())) + throw new Error("Offline mode allows network requests only to the configured model endpoint.") + // A local endpoint must not redirect to a remote host. + return networkFetch!(input, { ...init, redirect: "error" }) }, { preconnect: () => {} }, ) } -type ModelConfig = Pick +type ModelConfig = Pick -function configuredBaseURL(config: ModelConfig, providerID: string) { +/** 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 } -function provider(config: ModelConfig) { - const model = process.env.ALTIMATE_OFFLINE_MODEL ?? config.model - if (model) return model.split("/")[0] - const candidates = Object.keys(config.provider ?? {}).filter( - (id) => - configuredBaseURL(config, id) !== undefined && - (!config.enabled_providers || config.enabled_providers.includes(id)) && - !config.disabled_providers?.includes(id), - ) - return candidates.length === 1 ? candidates[0] : undefined -} - -export function endpoint(config: ModelConfig, providerID: string) { - return provider(config) === providerID ? configuredBaseURL(config, providerID) : 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 endpoint = new URL(baseURL) - if (!["http:", "https:"].includes(endpoint.protocol)) - throw new Error("Offline mode requires an HTTP(S) model endpoint.") - const basePath = endpoint.pathname.replace(/\/+$/, "") + 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 !== endpoint.origin || - (target.pathname !== basePath && !target.pathname.startsWith(basePath + "/")) - ) + 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", proxy: undefined }) + return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error" }) }, { preconnect: () => {} }, ) @@ -213,16 +130,14 @@ export function modelFetch(baseURL: string | undefined): typeof fetch { export function isLoopbackHost(value: unknown): boolean { if (typeof value !== "string") return false const host = value.toLowerCase().replace(/^\[|\]$/g, "") - // Wildcard bind addresses (0.0.0.0, ::) are reached on this machine when used as a destination. - return host === "localhost" || host === "localhost." || host === "::1" || host === "::" || host === "0.0.0.0" || - (isIP(host) === 4 && host.startsWith("127.")) + return host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127.")) } -// Validate the URL before any offline loopback HTTP request. +/** 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) && isLoopbackHost(url.hostname) + return ["http:", "https:"].includes(url.protocol) && LOCAL_FETCH_HOSTS.includes(url.hostname.toLowerCase()) } catch { return false } @@ -230,44 +145,7 @@ export function isLocalURL(value: string | URL) { export function assertLocalMcp(config: { type: string; url?: string }) { if (enabled() && config.type === "remote" && !isLocalURL(config.url ?? "")) - throw new Error("Offline mode allows only stdio or localhost/loopback HTTP(S) MCP servers.") -} - -export function localFetch(): typeof fetch { - return Object.assign( - async (input: Parameters[0], init?: Parameters[1]) => { - const target = input instanceof Request ? input.url : input.toString() - if (!isLocalURL(target)) throw new Error("Offline mode blocked a non-local request.") - // Never follow redirects: a local endpoint must not grant access to a remote host. - return (networkFetch ?? globalThis.fetch)(input, { ...init, redirect: "error", proxy: undefined }) - }, - { preconnect: () => {} }, - ) -} - -let warned = false - -export async function announce(hasSnapshot: boolean, knownEmpty = false) { - if (warned) return - warned = true - let delivered = false - try { - const message = hasSnapshot - ? "Using cached workspace skills." - : knownEmpty - ? "This workspace has no custom skills." - : "No usable workspace skill snapshot. To use workspace skills, run altimate-code workspace refresh while online." - const { isHeadless } = await import("@/altimate/workspace/engine-seams") - const { notify, printLine } = await import("@/altimate/workspace/engine-probes") - if (isHeadless()) { - printLine(`Offline mode: ${message}`) - delivered = true - } else { - delivered = await notify({ title: "Offline mode", message, variant: hasSnapshot || knownEmpty ? "info" : "warning" }) - } - } finally { - if (!delivered) warned = false - } + throw new Error("Offline mode allows only stdio MCP servers or ones at localhost, 127.0.0.1 or [::1].") } export * as Offline from "./offline" diff --git a/packages/opencode/src/config/paths.ts b/packages/opencode/src/config/paths.ts index d21d0b2464..9c979ef90c 100644 --- a/packages/opencode/src/config/paths.ts +++ b/packages/opencode/src/config/paths.ts @@ -142,12 +142,7 @@ function dir(input: ParseSource) { } /** Apply ${VAR}/${VAR:-default}/$${VAR}/{env:VAR} and {file:path} substitutions to config text. */ -async function substitute( - text: string, - input: ParseSource, - missing: "error" | "empty" = "error", - opts: { track?: boolean; expandFiles?: boolean } = {}, -) { +async function substitute(text: string, input: ParseSource, missing: "error" | "empty" = "error", track = true) { // Single-pass substitution against the ORIGINAL text prevents output of one // pattern being re-matched by another (e.g. {env:A}="${B}" expanding B). // Uses the shared ENV_VAR_PATTERN grammar, adding JSON-escaping for values @@ -191,7 +186,7 @@ async function substitute( // the telemetry schema). Dynamic import avoids a circular dep with @/altimate/telemetry (which // imports @/config/config). Matches main's single emit site in substitute(). const { dollarRefs, dollarUnresolved, dollarDefaulted, dollarEscaped, legacyBraceRefs, legacyBraceUnresolved } = stats - if (opts.track !== false && (dollarRefs > 0 || legacyBraceRefs > 0 || dollarEscaped > 0)) { + if (track && (dollarRefs > 0 || legacyBraceRefs > 0 || dollarEscaped > 0)) { import("@/altimate/telemetry") .then(({ Telemetry }) => { Telemetry.track({ @@ -210,9 +205,6 @@ async function substitute( } // altimate_change end - // altimate_change start — offline opt-in probe reads text without file substitution - if (opts.expandFiles === false) return text - // altimate_change end const fileMatches = Array.from(text.matchAll(/\{file:[^}]+\}/g)) if (!fileMatches.length) return text @@ -272,12 +264,10 @@ export async function parseText( text: string, input: ParseSource, missing: "error" | "empty" = "error", - // altimate_change start — options gain expandFiles for the offline opt-in probe - opts: { track?: boolean; expandFiles?: boolean } = {}, + opts: { track?: boolean } = {}, ): Promise { const configSource = source(input) - text = await substitute(text, input, missing, opts) - // altimate_change end + text = await substitute(text, input, missing, opts.track !== false) const errors: JsoncParseError[] = [] const data = parseJsonc(text, errors, { allowTrailingComma: true }) diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index ef9e43f5e4..ff0af53f9a 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -1,6 +1,3 @@ -// 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 { Context, Effect, FiberMap, Iterable, Layer, Schema, Stream } from "effect" @@ -808,30 +805,11 @@ export const layer = Layer.effect( .where(eq(SessionTable.workspace_id, id)) .all() .pipe(Effect.orDie) - // altimate_change start — one root list for the offline share check and the removal below const sessionIDs = new Set(sessions.map((sessionInfo) => sessionInfo.id)) - const roots = sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)) - // Offline mode cannot revoke a public share, so it refuses before removing anything. The session service's - // tree check covers subagent sessions, which carry only a parent id. - if (Offline.enabled()) { - for (const root of roots) { - const shared = yield* session.sharedInTree(root.id).pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(false))) - if (shared) - return yield* Effect.die( - new Offline.OfflinePolicyError("This workspace has a shared session. Remove it while online so the share can be revoked."), - ) - } - } yield* Effect.forEach( - roots, - // altimate_change end + sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)), (sessionInfo) => - session.remove(sessionInfo.id).pipe( - Effect.catchIf(NotFoundError.isInstance, () => Effect.void), - // altimate_change start — a share created since the check above: refuse rather than half-remove - Effect.catchTag("Session.OfflinePolicyError", (error) => Effect.die(new Offline.OfflinePolicyError(error.message))), - // altimate_change end - ), + session.remove(sessionInfo.id).pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.void)), { discard: true }, ) diff --git a/packages/opencode/src/format/index.ts b/packages/opencode/src/format/index.ts index f33d1a1a78..d260f3e27e 100644 --- a/packages/opencode/src/format/index.ts +++ b/packages/opencode/src/format/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode user environment -import { Offline } from "@/config/offline" -// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" // altimate_change start — makeRuntime for the restored Promise wrapper (bottom of file) import { makeRuntime } from "@/effect/run-service" @@ -89,16 +86,10 @@ export const layer = Layer.effect( const dir = yield* InstanceState.directory const result = yield* appProcess .run( - // altimate_change start — offline mode keeps the user's proxy settings for formatters ChildProcess.make(replaced[0]!, replaced.slice(1), { cwd: dir, - ...(Offline.enabled() - ? { - env: { ...Offline.userEnv({ ...process.env }), ...item.environment } as Record, - extendEnv: false, - } - : { env: item.environment, extendEnv: true }), - // altimate_change end + env: item.environment, + extendEnv: true, stdin: "ignore", stdout: "ignore", stderr: "ignore", diff --git a/packages/opencode/src/git/index.ts b/packages/opencode/src/git/index.ts index 27ab4fe7db..9e52cf2ade 100644 --- a/packages/opencode/src/git/index.ts +++ b/packages/opencode/src/git/index.ts @@ -1,7 +1,6 @@ -// altimate_change start — restrict Git transport offline +// altimate_change start — offline mode refuses Git commands that use the network import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" -import { gitCommandUsesNetwork, localGitEnv } from "@opencode-ai/core/git" -export { localGitEnv } +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" @@ -114,17 +113,13 @@ export const layer = Layer.effect( const run = Effect.fn("Git.run")( function* (args: string[], opts: Options) { - // altimate_change start — allow local Git and deny transports, including lazy object fetches - const offline = offlineModeEnabled() - if (offline && gitCommandUsesNetwork(args)) - return fail(new Error("Git remote operations require an online run.")) + // 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, - // altimate_change start — prevent Git and Git LFS network requests - env: localGitEnv(opts.env), - // altimate_change end + env: opts.env, extendEnv: true, stdin: opts.stdin ?? "ignore", stdout: "pipe", diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 7a6c80d7d8..d746ed9b67 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -1,5 +1,4 @@ // altimate_change start — offline mode -import { existsSync } from "node:fs" import { Offline } from "@/config/offline" // altimate_change end import yargs from "yargs" @@ -173,38 +172,26 @@ let cli = yargs(args) if (opts._[0] === "mcp" && opts._[1] === "serve") return // altimate_change end - // altimate_change start — skip network work in offline mode + // altimate_change start — offline mode: install the fetch guard and refuse commands that need a remote service const command = String(opts._[0] ?? "") - const args = opts as { - dir?: string - cwd?: string - directory?: string - project?: string - attach?: string - url?: string - model?: string + // `attach --dir` names a directory on the server, so attach reads the invoking project's setting. + const offlineTarget = command === "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.") } - const offlineTarget = (command === "run" && !args.attach ? args.dir : undefined) - ?? (command === "acp" ? args.cwd : undefined) - ?? (command === "workspace" ? args.directory : undefined) - const directory = offlineTarget ? path.resolve(offlineTarget) : resolveThreadDirectory(args.project) - await Offline.start(directory, args.model) - // attach: the invoking project's setting applies, and so does --dir's when it is a local directory. - if (command === "attach" && args.dir && existsSync(path.resolve(args.dir))) await Offline.start(path.resolve(args.dir), args.model) - // Attaching to a server on this machine is local; any other server is a network peer. - const attachURL = command === "attach" ? args.url : command === "run" ? args.attach || undefined : undefined - if (Offline.enabled() && ( - ["github", "gitlab", "pr", "link", "workspace-client", "web", "integrations"].includes(command) || - // A local review runs offline; posting it to GitHub does not. - (command === "review" && (opts as { post?: boolean }).post === true) || - (attachURL !== undefined && !Offline.isLocalURL(attachURL)) || - (command === "learn" && opts._[1] === "import-reviews") || - (command === "console" && opts._[1] === "open") || - (["providers", "auth", "console"].includes(command) && opts._[1] === "login") || - (command === "mcp" && opts._[1] === "auth") - )) throw new Error("This command requires network access. Run it while online.") - if (Offline.enabled() && attachURL) - process.stderr.write("Offline mode: the attached server applies its own network policy; start it with offline mode too.\n") // altimate_change end Heap.start() diff --git a/packages/opencode/src/lsp/index.ts b/packages/opencode/src/lsp/index.ts index b16f1f522e..a3bf956ac7 100644 --- a/packages/opencode/src/lsp/index.ts +++ b/packages/opencode/src/lsp/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode user environment -import { Offline } from "@/config/offline" -// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" import { Log } from "../util/log" @@ -137,12 +134,10 @@ export namespace LSP { process: spawn(item.command[0], item.command.slice(1), { cwd: root, windowsHide: true, - // altimate_change start — offline mode keeps the user's proxy settings for custom language servers env: { - ...Offline.userEnv({ ...process.env }), + ...process.env, ...item.env, }, - // altimate_change end }), initialization: item.initialization, } diff --git a/packages/opencode/src/lsp/launch.ts b/packages/opencode/src/lsp/launch.ts index 5555ffad4a..4f687b1972 100644 --- a/packages/opencode/src/lsp/launch.ts +++ b/packages/opencode/src/lsp/launch.ts @@ -1,8 +1,5 @@ import type { ChildProcessWithoutNullStreams } from "child_process" import { Process } from "@/util/process" -// altimate_change start — offline mode user environment -import { Offline } from "@/config/offline" -// altimate_change end type Child = Process.Child & ChildProcessWithoutNullStreams @@ -13,21 +10,6 @@ export function spawn(cmd: string, argsOrOpts?: string[] | Process.Options, opts const cfg = Array.isArray(argsOrOpts) ? opts : argsOrOpts const proc = Process.spawn([cmd, ...args], { ...cfg, - // altimate_change start — offline mode keeps the user's proxy settings for language servers - // Process.spawn merges process.env underneath, so a removed key is set to undefined (unset) instead. - ...(Offline.enabled() && cfg?.env !== null - ? { - env: { - NO_PROXY: undefined, - no_proxy: undefined, - ALTIMATE_OFFLINE_USER_PROXY: undefined, - ...Offline.userEnv({ ...process.env, ...cfg?.env }), - // After the spread: Process.spawn merges process.env underneath, so the key must be unset explicitly. - ALTIMATE_OFFLINE_MODEL: undefined, - }, - } - : {}), - // altimate_change end stdin: "pipe", stdout: "pipe", stderr: "pipe", diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 7aaaacf121..f7d82dc034 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -111,14 +111,6 @@ export class NotFoundError extends Schema.TaggedErrorClass()("MCP name: Schema.String, }) {} -// altimate_change start — offline policy refusals are client errors -export class OfflinePolicyError extends Schema.TaggedErrorClass()( - "MCP.OfflinePolicyError", - { message: Schema.String }, - { httpApiStatus: 400 }, -) {} -// altimate_change end - type MCPClient = Client function createClient(directory: string) { @@ -332,10 +324,8 @@ export interface Interface { readonly prompts: () => Effect.Effect> readonly resources: () => Effect.Effect> // altimate_change end - // altimate_change start — offline policy refusals - readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Record | Status }, OfflinePolicyError> - readonly connect: (name: string) => Effect.Effect - // altimate_change end + readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Record | Status }> + readonly connect: (name: string) => Effect.Effect readonly disconnect: (name: string) => Effect.Effect // altimate_change start — MCP.remove: full runtime teardown + ToolsChanged (merge dropped it) readonly remove: (name: string) => Effect.Effect @@ -349,12 +339,10 @@ export interface Interface { clientName: string, resourceUri: string, ) => Effect.Effect> | undefined> - // altimate_change start — offline refusal is a typed error readonly startAuth: ( mcpName: string, - ) => Effect.Effect<{ authorizationUrl: string; oauthState: string }, NotFoundError | OfflinePolicyError> - readonly authenticate: (mcpName: string) => Effect.Effect - // altimate_change end + ) => Effect.Effect<{ authorizationUrl: string; oauthState: string }, NotFoundError> + readonly authenticate: (mcpName: string) => Effect.Effect readonly finishAuth: (mcpName: string, authorizationCode: string) => Effect.Effect readonly removeAuth: (mcpName: string) => Effect.Effect readonly supportsOAuth: (mcpName: string) => Effect.Effect @@ -439,7 +427,7 @@ export const layer = Layer.effect( if (Offline.enabled() && !Offline.isLocalURL(mcp.url)) { return { client: undefined as MCPClient | undefined, - status: { status: "failed" as const, error: "Offline mode blocks remote MCP servers; use stdio or localhost/loopback HTTP(S)." }, + status: { status: "failed" as const, error: "Offline mode allows only stdio MCP servers or ones at localhost, 127.0.0.1 or [::1]." }, transport: undefined as TransportLabel | undefined, } } @@ -515,7 +503,6 @@ export const layer = Layer.effect( transport: new StreamableHTTPClientTransport(url, { authProvider, requestInit, - fetch: Offline.enabled() ? Offline.localFetch() : undefined, }), }, { @@ -523,7 +510,6 @@ export const layer = Layer.effect( transport: new SSEClientTransport(url, { authProvider, requestInit, - fetch: Offline.enabled() ? Offline.localFetch() : undefined, }), }, ] @@ -631,9 +617,7 @@ export const layer = Layer.effect( args, cwd, env: { - // altimate_change start — offline mode keeps the user's proxy settings; the server's own environment still wins - ...Offline.userEnv({ ...process.env }), - // altimate_change end + ...process.env, // altimate_change start — brand: BUN_BE_BUN for altimate/altimate-code self-spawn ...(cmd === "opencode" || cmd === "altimate" || cmd === "altimate-code" ? { BUN_BE_BUN: "1" } : {}), // altimate_change end @@ -1091,17 +1075,7 @@ export const layer = Layer.effect( // altimate_change end }) - // altimate_change start — report policy refusals as client errors - const enforceOfflinePolicy = (mcp: ConfigMCPV1.Info) => Effect.try({ - try: () => Offline.assertLocalMcp(mcp), - catch: (error) => new OfflinePolicyError({ message: error instanceof Error ? error.message : String(error) }), - }) - // altimate_change end - - // altimate_change start — offline policy refusal const add = Effect.fn("MCP.add")(function* (name: string, mcp: ConfigMCPV1.Info) { - yield* enforceOfflinePolicy(mcp) - // altimate_change end // altimate_change start — see claim const seq = ++lifecycleSeq // altimate_change end @@ -1126,8 +1100,6 @@ export const layer = Layer.effect( const token = claim(s, name, seq) // altimate_change end const mcp = yield* requireMcpConfig(name) - // altimate_change — reject before persisting enabled:true for an offline remote server - yield* enforceOfflinePolicy(mcp) // altimate_change start — see createAndStore yield* createAndStore(name, { ...mcp, enabled: true }, token) // altimate_change end @@ -1415,8 +1387,6 @@ export const layer = Layer.effect( }) const beginAuth = Effect.fn("MCP.beginAuth")(function* (mcpName: string, token: number) { - // Offline refusal is a client error, not a crash. - if (Offline.enabled()) return yield* new OfflinePolicyError({ message: "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/tui/altimate/skill-ops.tsx b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx index 2a1b4fa0d6..b4cfe7059a 100644 --- a/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx +++ b/packages/opencode/src/plugin/tui/altimate/skill-ops.tsx @@ -307,7 +307,7 @@ async function testSkillDirect( const proc = Bun.spawn([tool, "--help"], { stdout: "pipe", stderr: "pipe", - env: { ...Offline.userEnv({ ...process.env }), PATH: toolPath }, + env: { ...process.env, PATH: toolPath }, }) const timeout = setTimeout(() => proc.kill(), 5000) const exitCode = await proc.exited diff --git a/packages/opencode/src/pty/index.ts b/packages/opencode/src/pty/index.ts index 367de744a6..166d9f4213 100644 --- a/packages/opencode/src/pty/index.ts +++ b/packages/opencode/src/pty/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode user environment -import { Offline } from "@/config/offline" -// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" // altimate_change start — upstream moved the pty spawn backend into @opencode-ai/core @@ -135,15 +132,13 @@ export namespace Pty { const cwd = input.cwd || Instance.directory const shellEnv = await Plugin.trigger("shell.env", { cwd }, { env: {} }) - // altimate_change start — offline mode leaves the user's terminal with their proxy settings const env = { - ...Offline.userEnv({ ...process.env }), + ...process.env, ...input.env, ...shellEnv.env, TERM: "xterm-256color", OPENCODE_TERMINAL: "1", } as Record - // altimate_change end // altimate_change start — prepend user tools dirs to PATH in terminal sessions const sep = process.platform === "win32" ? ";" : ":" diff --git a/packages/opencode/src/server/middleware.ts b/packages/opencode/src/server/middleware.ts index a622e5ec00..fc0be01255 100644 --- a/packages/opencode/src/server/middleware.ts +++ b/packages/opencode/src/server/middleware.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy refusals -import { Offline } from "@/config/offline" -// altimate_change end import { Provider } from "../provider/provider" import { NamedError } from "@opencode-ai/util/error" import { NotFoundError } from "../storage/db" @@ -32,10 +29,6 @@ export function errorHandler(log: Log.Logger): ErrorHandler { else status = 500 return c.json(err.toObject(), { status }) } - // altimate_change start — offline policy refusals reach the client with their one-line message - const refusal = Offline.policyError(err) - if (refusal) return c.json({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }) - // altimate_change end if (err instanceof Session.BusyError) { return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) } diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts index 28924b24f9..86ced98317 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/mcp.ts @@ -64,7 +64,7 @@ export const McpApi = HttpApi.make("mcp") payload: AddPayload, success: described(StatusMap, "MCP server added successfully"), // altimate_change start — the workspace-managed refusal is a declared error - error: [HttpApiError.BadRequest, McpServerManagedError, MCP.OfflinePolicyError], + error: [HttpApiError.BadRequest, McpServerManagedError], // altimate_change end }).annotateMerge( OpenApi.annotations({ @@ -77,9 +77,7 @@ export const McpApi = HttpApi.make("mcp") params: { name: Schema.String }, query: WorkspaceRoutingQuery, success: described(AuthStartResponse, "OAuth flow started"), - // altimate_change start — offline refusal is a declared client error - error: [UnsupportedOAuthError, McpServerNotFoundError, MCP.OfflinePolicyError], - // altimate_change end + error: [UnsupportedOAuthError, McpServerNotFoundError], }).annotateMerge( OpenApi.annotations({ identifier: "mcp.auth.start", @@ -105,9 +103,7 @@ export const McpApi = HttpApi.make("mcp") params: { name: Schema.String }, query: WorkspaceRoutingQuery, success: described(MCP.Status, "OAuth authentication completed"), - // altimate_change start — offline refusal is a declared client error - error: [UnsupportedOAuthError, McpServerNotFoundError, MCP.OfflinePolicyError], - // altimate_change end + error: [UnsupportedOAuthError, McpServerNotFoundError], }).annotateMerge( OpenApi.annotations({ identifier: "mcp.auth.authenticate", @@ -132,7 +128,7 @@ export const McpApi = HttpApi.make("mcp") query: WorkspaceRoutingQuery, success: described(Schema.Boolean, "MCP server connected successfully"), // altimate_change start — the workspace-managed key refuses connect/disconnect - error: [McpServerNotFoundError, McpServerManagedError, MCP.OfflinePolicyError], + error: [McpServerNotFoundError, McpServerManagedError], // altimate_change end }).annotateMerge( OpenApi.annotations({ diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts index 00ae842ce4..7d951a62e5 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts @@ -318,9 +318,7 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, success: described(Schema.Boolean, "Successfully deleted session"), - // altimate_change start — offline refusal is a declared client error - error: [HttpApiError.BadRequest, ApiNotFoundError, Session.OfflinePolicyError], - // altimate_change end + error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ identifier: "session.delete", @@ -384,9 +382,7 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, success: described(Session.Info, "Successfully shared session"), - // altimate_change start — offline refusal is a declared client error - error: [HttpApiError.InternalServerError, ApiNotFoundError, Session.OfflinePolicyError], - // altimate_change end + error: [HttpApiError.InternalServerError, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ identifier: "session.share", @@ -398,9 +394,7 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, success: described(Session.Info, "Successfully unshared session"), - // altimate_change start — offline refusal is a declared client error - error: [HttpApiError.InternalServerError, ApiNotFoundError, Session.OfflinePolicyError], - // altimate_change end + error: [HttpApiError.InternalServerError, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ identifier: "session.unshare", diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts index 9bd3680dc1..6281b7c9d9 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts @@ -203,16 +203,7 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", }) const remove = Effect.fn("SessionHttpApi.remove")(function* (ctx: { params: { sessionID: SessionID } }) { - // altimate_change start — the declared offline refusal passes through as a 400 with its message - yield* session - .remove(ctx.params.sessionID) - .pipe( - Effect.catchIf( - (error): error is Session.NotFound => !(error instanceof Session.OfflinePolicyError), - (error) => SessionError.mapStorageNotFound(Effect.fail(error)), - ), - ) - // altimate_change end + yield* SessionError.mapStorageNotFound(session.remove(ctx.params.sessionID)) return true }) @@ -294,25 +285,15 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", // every failure to a 400 BadRequest. const share = Effect.fn("SessionHttpApi.share")(function* (ctx: { params: { sessionID: SessionID } }) { yield* requireSession(ctx.params.sessionID) - yield* shareSvc.share(ctx.params.sessionID).pipe( - // altimate_change start — the declared offline refusal passes through as a 400 with its message - Effect.mapError((error) => - error instanceof Session.OfflinePolicyError ? error : new HttpApiError.InternalServerError({}), - ), - // altimate_change end - ) + yield* shareSvc.share(ctx.params.sessionID).pipe(Effect.mapError(() => new HttpApiError.InternalServerError({}))) return yield* requireSession(ctx.params.sessionID) }) const unshare = Effect.fn("SessionHttpApi.unshare")(function* (ctx: { params: { sessionID: SessionID } }) { yield* requireSession(ctx.params.sessionID) - yield* shareSvc.unshare(ctx.params.sessionID).pipe( - // altimate_change start — the declared offline refusal passes through as a 400 with its message - Effect.mapError((error) => - error instanceof Session.OfflinePolicyError ? error : new HttpApiError.InternalServerError({}), - ), - // altimate_change end - ) + yield* shareSvc + .unshare(ctx.params.sessionID) + .pipe(Effect.mapError(() => new HttpApiError.InternalServerError({}))) return yield* requireSession(ctx.params.sessionID) }) diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts index c1312f8b79..21b53aba75 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/error.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy refusals -import { Offline } from "@/config/offline" -// altimate_change end import { NamedError } from "@opencode-ai/core/util/error" import { ConfigErrorV1 } from "@opencode-ai/core/v1/config/error" import { Cause, Effect } from "effect" @@ -27,14 +24,6 @@ export const errorLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) ) { return Effect.succeed(HttpServerResponse.jsonUnsafe(error.toObject(), { status: 400 })) } - // altimate_change start — offline policy refusals reach the client with their one-line message - const refusal = Offline.policyError(error) - if (refusal) { - return Effect.succeed( - HttpServerResponse.jsonUnsafe({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }), - ) - } - // altimate_change end const ref = `err_${crypto.randomUUID().slice(0, 8)}` diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index 63a83f642e..6cdd58c67e 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline policy refusals -import { Offline } from "@/config/offline" -// altimate_change end import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" import { Log } from "../util/log" @@ -308,9 +305,6 @@ export namespace Server { // altimate_change start — a busy session answers 400 with its message, as the instance routes' handler does // (middleware.ts); everything else unrecognised gets a fixed message and the ref it was logged under, never // the error's text or stack. - // Offline policy refusals reach the client with their one-line message. - const refusal = Offline.policyError(err) - if (refusal) return c.json({ name: refusal.name, data: { message: refusal.message } }, { status: 400 }) if (err instanceof Session.BusyError) { return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) } diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index 79376026de..aee9ca8898 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end // altimate_change start — release session-owned scratch stores on deletion import { closeScratch } from "@/altimate/native/connections/scratch" // altimate_change end @@ -428,9 +425,6 @@ export namespace Session { }) export const share = fn(SessionID.zod, async (id) => { - // altimate_change start — offline mode refuses sharing with its own message, before the config check - if (Offline.enabled()) throw new Offline.OfflinePolicyError(Offline.SHARE_REFUSAL) - // altimate_change end const cfg = await Config.get() if (cfg.share === "disabled") { throw new Error("Sharing is disabled in configuration") @@ -751,34 +745,12 @@ export namespace Session { return rows.map(fromRow) }) - // altimate_change start — offline mode cannot revoke a public share, so it refuses to delete a shared - // session (or one with a shared descendant) before anything is removed; the tree is checked once export const remove = fn(SessionID.zod, async (sessionID) => { - if (Offline.enabled()) { - const pending = [sessionID] - while (pending.length) { - const id = pending.pop()! - // A missing root behaves as online (logged by removeTree); other read failures stop the removal. - const info = await get(id).catch((error) => { - if (id === sessionID && NotFoundError.isInstance(error)) return undefined - throw error - }) - if (!info) break - if (info.share?.url) - throw new Offline.OfflinePolicyError("This session is shared. Delete it while online so its share can be revoked.") - pending.push(...(await children(id)).map((child) => child.id)) - } - } - await removeTree(sessionID) - }) - - async function removeTree(sessionID: SessionID): Promise { - // altimate_change end const project = Instance.project try { const session = await get(sessionID) for (const child of await children(sessionID)) { - await removeTree(child.id) + await remove(child.id) } await unshare(sessionID).catch(() => {}) // altimate_change start — release only the deleted session's scratch store @@ -796,7 +768,7 @@ export namespace Session { } catch (e) { log.error(e) } - } + }) export const updateMessage = fn(MessageV2.Info, async (msg) => { const time_created = msg.time.created diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index d5d68aa4ea..210ee9a87b 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -138,7 +138,6 @@ import { ErrorDetail } from "@/altimate/telemetry/error-detail" // altimate_chan import { canonicalDirectory, endTurnBinding, - resolveBindingOutcome, turnBinding, unvalidatedTurnBinding, type AccountKey, @@ -479,32 +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 - const writeOfflineNotice = async () => { - const { ownManifest, snapshotKnownEmpty } = await import("../altimate/workspace/skill-sync") - const snapshot = await ownManifest(dir) - // A withheld snapshot (rebound project, other account) must not stay visible through .claude/skills copies. - if (!snapshot && existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) { - const { mirrorClaudeSkills } = await import("../altimate/workspace/claude-skill-mirror") - await mirrorClaudeSkills(dir, { withdraw: true }) - } - const binding = snapshot ? null : await resolveBindingOutcome(dir) - // Only a project that uses a workspace hears about workspace skills. - // A serve pin counts only for the tree it was launched for. - const { readPin, resolveWithinRoot } = await import("../altimate/workspace/pin") - const pin = readPin() - const pinned = pin.kind === "valid" && resolveWithinRoot(dir, pin.root) !== null ? pin.datamateId : undefined - const datamateId = binding?.status === "bound" ? binding.binding.datamateId : pinned - if (snapshot || datamateId !== undefined) { - const empty = datamateId !== undefined && (await snapshotKnownEmpty(dir, datamateId)) - await Offline.announce(snapshot !== null, empty) - } - await refreshSkillRegistry(dir) - } - const notice = writeOfflineNotice().catch((error) => log.warn("offline skill snapshot setup failed", { error })) - if (existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) await notice + if (existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) await refreshSkillRegistry(dir) } else if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { + // altimate_change end const dir = Instance.directory // Mirrors `MANAGED_DIR` in ./altimate/workspace/skill-sync. Inlined // rather than imported so the opted-out path stays free of that module. @@ -4519,13 +4498,11 @@ NOTE: At any point in time through this workflow you should feel free to ask the detached: process.platform !== "win32", windowsHide: process.platform === "win32", stdio: ["ignore", "pipe", "pipe"], - // altimate_change start — offline mode leaves the user's own commands with their proxy settings env: { - ...Offline.userEnv({ ...process.env }), + ...process.env, ...shellEnv.env, TERM: "dumb", }, - // altimate_change end }) let output = "" @@ -4870,9 +4847,6 @@ NOTE: At any point in time through this workflow you should feel free to ask the // altimate_change start — upstream_fix: non-bash command-template shells need an explicit cwd. cwd: Instance.directory, // altimate_change end - // altimate_change start — offline mode leaves the user's own commands with their proxy settings - ...(Offline.enabled() ? { env: Offline.userEnv({ ...process.env }) } : {}), - // altimate_change end stdout: "pipe", stderr: "pipe", }) diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index f2e296c8c0..d77b027c97 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end // altimate_change start — release session-owned scratch stores on deletion import { closeScratch } from "@/altimate/native/connections/scratch" // altimate_change end @@ -470,14 +467,6 @@ export class BusyError extends Schema.TaggedErrorClass()("SessionBusy }) {} export type NotFound = NotFoundError -// altimate_change start — offline shared-session refusal -export const OFFLINE_SHARED_SESSION = "This session is shared. Delete it while online so its share can be revoked." -export class OfflinePolicyError extends Schema.TaggedErrorClass()( - "Session.OfflinePolicyError", - { message: Schema.String }, - { httpApiStatus: 400 }, -) {} -// altimate_change end export interface Interface { readonly list: (input?: ListInput) => Effect.Effect @@ -510,11 +499,7 @@ export interface Interface { readonly diff: (sessionID: SessionID) => Effect.Effect readonly messages: (input: { sessionID: SessionID; limit?: number }) => Effect.Effect readonly children: (parentID: SessionID) => Effect.Effect - // altimate_change start — offline mode refuses to delete a shared session - readonly remove: (sessionID: SessionID) => Effect.Effect - /** Whether the session or any descendant (subagent sessions included) has a public share. */ - readonly sharedInTree: (sessionID: SessionID) => Effect.Effect - // altimate_change end + readonly remove: (sessionID: SessionID) => Effect.Effect readonly updateMessage: (msg: T) => Effect.Effect readonly removeMessage: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect readonly removePart: (input: { sessionID: SessionID; messageID: MessageID; partID: PartID }) => Effect.Effect @@ -674,28 +659,7 @@ export const layer: Layer.Layer< return rows.map(fromRow) }) - // altimate_change start — offline shared-session check - const sharedInTree = (sessionID: SessionID): Effect.Effect => - Effect.gen(function* () { - const pending = [sessionID] - while (pending.length) { - const id = pending.pop()! - if ((yield* get(id)).share?.url) return true - pending.push(...(yield* children(id)).map((child) => child.id)) - } - return false - }) - // altimate_change end - - // altimate_change start — offline mode cannot revoke a public share: check the whole tree once, then remove const remove: Interface["remove"] = Effect.fnUntraced(function* (sessionID: SessionID) { - if (Offline.enabled() && (yield* sharedInTree(sessionID))) - return yield* new OfflinePolicyError({ message: OFFLINE_SHARED_SESSION }) - yield* removeTree(sessionID) - }) - // altimate_change end - - const removeTree = Effect.fnUntraced(function* (sessionID: SessionID): Effect.fn.Return { const session = yield* get(sessionID) try { // `remove` needs to work in all cases, such as broken sessions that @@ -708,9 +672,7 @@ export const layer: Layer.Layer< if (hasInstance) yield* cancelBackgroundJobs(background, sessionID) const kids = yield* children(sessionID) for (const child of kids) { - // altimate_change start — recurse without repeating the offline tree check - yield* removeTree(child.id) - // altimate_change end + yield* remove(child.id) } // altimate_change start — release only the deleted session's scratch store @@ -1014,9 +976,6 @@ export const layer: Layer.Layer< messages, children, remove, - // altimate_change start — offline shared-session check - sharedInTree, - // altimate_change end updateMessage, removeMessage, removePart, diff --git a/packages/opencode/src/share/session.ts b/packages/opencode/src/share/session.ts index 427d6938c6..3ba70bd7f9 100644 --- a/packages/opencode/src/share/session.ts +++ b/packages/opencode/src/share/session.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Session } from "@/session/session" import { SessionID } from "@/session/schema" @@ -27,9 +24,6 @@ export const layer = Layer.effect( const flags = yield* RuntimeFlags.Service const share = Effect.fn("SessionShare.share")(function* (sessionID: SessionID) { - // altimate_change start — offline mode refuses sharing with its own message, before the config check - if (Offline.enabled()) return yield* new Session.OfflinePolicyError({ message: Offline.SHARE_REFUSAL }) - // altimate_change end const conf = yield* cfg.get() if (conf.share === "disabled") throw new Error("Sharing is disabled in configuration") const result = yield* shareNext.create(sessionID) @@ -38,10 +32,6 @@ export const layer = Layer.effect( }) const unshare = Effect.fn("SessionShare.unshare")(function* (sessionID: SessionID) { - // altimate_change start — offline mode cannot revoke a share; typed refusal, local state kept - if (Offline.enabled()) - return yield* new Session.OfflinePolicyError({ message: Offline.UNSHARE_REFUSAL }) - // altimate_change end yield* shareNext.remove(sessionID) yield* session.setShare({ sessionID, share: undefined }) }) diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 004bf29ea2..366f8eb328 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -78,9 +78,8 @@ export namespace ShareNext { const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1" export async function init() { - // altimate_change start — skip session sharing in offline mode + // altimate_change — 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, [ { @@ -128,10 +127,7 @@ export namespace ShareNext { } export async function create(sessionID: SessionID) { - // altimate_change start — skip session sharing in offline mode - if (Offline.enabled()) throw new Offline.OfflinePolicyError(Offline.SHARE_REFUSAL) if (disabled) return { id: "", url: "", secret: "" } - // altimate_change end log.info("creating share", { sessionID }) const req = await request() const response = await fetch(`${req.baseUrl}${req.api.create}`, { @@ -212,9 +208,8 @@ export namespace ShareNext { const queue = new Map }>() async function sync(sessionID: SessionID, data: Data[]) { - // altimate_change start — skip session sharing in offline mode + // altimate_change — 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) { @@ -259,10 +254,6 @@ export namespace ShareNext { } export async function remove(sessionID: SessionID) { - // altimate_change start — keep the local share state until the server revokes it - if (Offline.enabled()) - throw new Offline.OfflinePolicyError(Offline.UNSHARE_REFUSAL) - // altimate_change end if (disabled) return log.info("removing share", { sessionID }) const share = get(sessionID) diff --git a/packages/opencode/src/skill/discovery.ts b/packages/opencode/src/skill/discovery.ts index bb11f77489..4699c10b51 100644 --- a/packages/opencode/src/skill/discovery.ts +++ b/packages/opencode/src/skill/discovery.ts @@ -1,8 +1,3 @@ -// altimate_change start — offline mode -import { Offline } from "@/config/offline" -import { createHash } from "node:crypto" -import { SkillDiscovery } from "@opencode-ai/core/skill/discovery" -// altimate_change end import { NodePath } from "@effect/platform-node" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Effect, Layer, Path, Schema, Context } from "effect" @@ -62,22 +57,6 @@ export namespace Discovery { const pull = Effect.fn("Discovery.pull")(function* (url: string) { const base = url.endsWith("/") ? url : `${url}/` const index = new URL("index.json", base).href - // altimate_change start — reuse the cached index for this source without contacting it - const sourceKey = createHash("sha256").update(index).digest("hex") - const sourceCache = path.join(cache, ".sources", sourceKey) - // Beside the source directory, not inside it, so no skill name can collide with it. - const indexPath = path.join(cache, ".sources", `${sourceKey}.json`) - if (Offline.enabled()) { - const cached = yield* fs.readJson(indexPath).pipe(Effect.catch(() => Effect.void)) - const directories = Array.isArray(cached) ? cached : [] - const local = directories.filter((dir): dir is string => - typeof dir === "string" && path.dirname(dir) === sourceCache, - ) - return yield* Effect.filter(local, (dir) => - fs.exists(path.join(dir, "SKILL.md")).pipe(Effect.orElseSucceed(() => false)), - ) - } - // altimate_change end const host = base.slice(0, -1) log.info("fetching index", { url: index }) @@ -97,16 +76,6 @@ export namespace Discovery { if (!data) return [] const list = data.skills.filter((skill) => { - // altimate_change start — reject unsafe skill names and file paths - if ( - skill.name.includes("/") || - !SkillDiscovery.isSafeRelativePath(skill.name) || - !skill.files.every(SkillDiscovery.isSafeRelativePath) - ) { - log.warn("skill entry has an unsafe name or file path", { url: index, skill: skill.name }) - return false - } - // altimate_change end if (!skill.files.includes("SKILL.md")) { log.warn("skill entry missing SKILL.md", { url: index, skill: skill.name }) return false @@ -118,9 +87,7 @@ export namespace Discovery { list, (skill) => Effect.gen(function* () { - // altimate_change start — per-source cache for offline reuse - const root = path.join(sourceCache, skill.name) - // altimate_change end + const root = path.join(cache, skill.name) yield* Effect.forEach( skill.files, @@ -136,13 +103,7 @@ export namespace Discovery { { concurrency: skillConcurrency }, ) - // altimate_change start — per-source cache for offline reuse - const available = dirs.filter((dir): dir is string => dir !== null) - // altimate_change end - // altimate_change start — store the directory list for a later offline run - yield* fs.writeWithDirs(indexPath, JSON.stringify(available)).pipe(Effect.ignore) - // altimate_change end - return available + return dirs.filter((dir): dir is string => dir !== null) }) return Service.of({ pull }) diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index 5e7a1c1ad9..44da196626 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -1,6 +1,3 @@ -// altimate_change start — disable Git transport when working with local snapshots -import { localGitEnv } from "@/git" -// altimate_change end import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { Cause, Duration, Effect, Layer, Schedule, Schema, Semaphore, Context } from "effect" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" @@ -93,9 +90,7 @@ export const layer: Layer.Layer; stdin?: string }) { const result = yield* appProcess.run( - // altimate_change start — offline Git transport policy - ChildProcess.make("git", cmd, { cwd: opts?.cwd, env: localGitEnv(opts?.env), extendEnv: true }), - // altimate_change end + ChildProcess.make("git", cmd, { cwd: opts?.cwd, env: opts?.env, extendEnv: true }), { stdin: opts?.stdin }, ) return { @@ -611,9 +606,6 @@ export const layer: Layer.Layer item.ref).join("\n") + "\n" }, diff --git a/packages/opencode/src/tool/bash.ts b/packages/opencode/src/tool/bash.ts index a222787fe0..0ef418bdae 100644 --- a/packages/opencode/src/tool/bash.ts +++ b/packages/opencode/src/tool/bash.ts @@ -1,6 +1,3 @@ -// altimate_change start — offline mode user environment -import { Offline } from "@/config/offline" -// altimate_change end import z from "zod" import { spawn } from "child_process" import { Tool } from "./tool" @@ -456,8 +453,7 @@ export const BashTool = Tool.define("bash", async () => { ) // altimate_change start — prepend bundled tools dir (ALTIMATE_BIN_DIR) and user tools dirs to PATH - // Offline mode restores the user's proxy settings before plugin overrides. - const mergedEnv: Record = { ...Offline.userEnv({ ...process.env }), ...shellEnv.env } + const mergedEnv: Record = { ...process.env, ...shellEnv.env } // Strip the markers that describe this host, not the child. See `stripHostMarkers` // for what each one is and why (PR #937 review, Issue #3, for the first of them). stripHostMarkers(mergedEnv) diff --git a/packages/opencode/src/util/git.ts b/packages/opencode/src/util/git.ts index 7a17da92e8..37defc18ba 100644 --- a/packages/opencode/src/util/git.ts +++ b/packages/opencode/src/util/git.ts @@ -1,7 +1,7 @@ import { Process } from "./process" -// altimate_change start — use the same transport controls as the Git services +// altimate_change start — offline mode refuses Git commands that use the network import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" -import { gitCommandUsesNetwork, localGitEnv } from "@opencode-ai/core/git" +import { GIT_OFFLINE_REFUSAL, gitCommandUsesNetwork } from "@opencode-ai/core/git" // altimate_change end export interface GitResult { @@ -18,19 +18,13 @@ export interface GitResult { * issues in embedded/client environments. */ export async function git(args: string[], opts: { cwd: string; env?: Record }): Promise { - // altimate_change start — reject remote commands and prevent implicit lazy fetching - if (offlineModeEnabled() && gitCommandUsesNetwork(args)) { - return { - exitCode: 1, - text: () => "", - stdout: Buffer.alloc(0), - stderr: Buffer.from("Git remote operations require an online run."), - } - } + // 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: localGitEnv(opts.env), + env: opts.env, stdin: "ignore", nothrow: true, }) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 9496938ede..4cfaf90b6d 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -1,5 +1,5 @@ -// altimate_change start — offline mode skips worktree network steps -import { Offline } from "@/config/offline" +// 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" @@ -15,9 +15,7 @@ import { Slug } from "@opencode-ai/core/util/slug" import { errorMessage } from "../util/error" import { EventV2 } from "@opencode-ai/core/event" import { GlobalBus } from "@/bus/global" -// altimate_change start — offline Git transport policy -import { Git, localGitEnv } from "@/git" -// altimate_change end +import { Git } from "@/git" import { Effect, Layer, Path, Schema, Scope, Context } from "effect" import { ChildProcess } from "effect/unstable/process" import { NodePath } from "@effect/platform-node" @@ -178,9 +176,7 @@ export const layer: Layer.Layer< const git = Effect.fnUntraced( function* (args: string[], opts?: { cwd?: string }) { const result = yield* appProcess.run( - // altimate_change start — offline Git transport policy - ChildProcess.make("git", args, { cwd: opts?.cwd, env: localGitEnv(), extendEnv: true, stdin: "ignore" }), - // altimate_change end + ChildProcess.make("git", args, { cwd: opts?.cwd, extendEnv: true, stdin: "ignore" }), ) return { code: result.exitCode, @@ -490,15 +486,7 @@ export const layer: Layer.Layer< function* (directory: string, cmd: string) { const [shell, args] = process.platform === "win32" ? ["cmd", ["/c", cmd]] : ["bash", ["-lc", cmd]] const result = yield* appProcess.run( - // altimate_change start — offline mode keeps the user's proxy settings for their start commands - ChildProcess.make(shell, args as string[], { - cwd: directory, - ...(Offline.enabled() - ? { env: Offline.userEnv({ ...process.env }) as Record, extendEnv: false } - : { extendEnv: true }), - stdin: "ignore", - }), - // altimate_change end + ChildProcess.make(shell, args as string[], { cwd: directory, extendEnv: true, stdin: "ignore" }), ) return { code: result.exitCode, stderr: result.stderr.toString("utf8") } }, @@ -588,8 +576,8 @@ export const layer: Layer.Layer< } const sep = base.ref.indexOf("/") - // altimate_change — reset to the cached ref when offline - if (!Offline.enabled() && 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( @@ -612,23 +600,12 @@ export const layer: Layer.Layer< }) } - // altimate_change start — update existing submodules from objects already on disk offline - // A submodule this worktree never checked out would need a clone, so offline updates only the present - // ones (`submodule foreach` visits only checked-out submodules and prints full paths, spaces included). - const offlineSubmodules = Offline.enabled() - ? (yield* git(["submodule", "foreach", "--quiet", 'printf "%s\\n" "$sm_path"'], { cwd: worktreePath })).text - .split("\n") - .filter((line) => line.length > 0) - : undefined - if (!offlineSubmodules || offlineSubmodules.length > 0) - yield* gitExpect( - offlineSubmodules - ? ["submodule", "update", "--no-fetch", "--recursive", "--force", "--", ...offlineSubmodules] - : ["submodule", "update", "--init", "--recursive", "--force"], - { cwd: worktreePath }, - (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), - ) - // altimate_change end + yield* gitExpect( + // altimate_change — offline mode updates submodules from objects already on disk + ["submodule", "update", "--init", "--recursive", "--force", ...(offlineModeEnabled() ? ["--no-fetch"] : [])], + { cwd: worktreePath }, + (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), + ) yield* gitExpect( ["submodule", "foreach", "--recursive", "git", "reset", "--hard"], diff --git a/packages/opencode/test/altimate/debug/collect.test.ts b/packages/opencode/test/altimate/debug/collect.test.ts index 34ff5f07f5..54d4a8c6de 100644 --- a/packages/opencode/test/altimate/debug/collect.test.ts +++ b/packages/opencode/test/altimate/debug/collect.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from "bun:test" import fs from "fs" import os from "os" import path from "path" -import { configFiles, connectionFact, credentialFieldsFor, mcpFacts, pidAlive, probe, telemetryFacts } from "../../../src/altimate/debug/collect" +import { configFiles, connectionFact, credentialFieldsFor, mcpFacts, pidAlive, probe } from "../../../src/altimate/debug/collect" import { detectProblems } from "../../../src/altimate/debug/report" describe("connection facts", () => { @@ -190,18 +190,4 @@ describe("process liveness", () => { expect(pidAlive(2 ** 22 + 12345)).toBe(false) }) }) -describe("offline mode", () => { - test("offline telemetry reports the offline policy rather than --no-network", async () => { - const prior = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - for (const network of [true, false]) { - expect(await telemetryFacts(network)).toEqual({ enabled: false, checked: false, reason: "offline mode" }) - } - } finally { - if (prior === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = prior - } - }) -}) // 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 index da53b2130d..0f98c3b986 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -1,5 +1,5 @@ // altimate_change - new file -import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test" +import { afterEach, beforeEach, expect, test } from "bun:test" import fs from "node:fs/promises" import os from "node:os" import path from "node:path" @@ -19,143 +19,116 @@ afterEach(() => { } }) -test("offline permits embedded databases and literal loopback", () => { +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 host of ["localhost", "127.0.0.1", "127.0.1.2", "::1"]) - expect(() => assertLocalConnection({ type: "postgres", host })).not.toThrow() - expect(() => assertLocalConnection({ type: "postgres", connectionString: "postgres://localhost/test" })).not.toThrow() + 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: "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" }, + ]) expect(() => assertLocalConnection(config)).not.toThrow() }) -test("offline rejects remote targets, SSH, cloud auth, and URI host overrides", () => { + +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: "{% if true %}md:cloud{% endif %}" }, - { type: "duckdb", path: "{# cloud #}md:cloud" }, - { 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: "file:////server/share/db.sqlite" }, - { type: "sqlite", path: "file://localhost//server/share/db.sqlite" }, - { type: "sqlite", path: "file:///%2Fserver/share/db.sqlite" }, { type: "sqlite", path: "\\\\example.com\\share\\db" }, { type: "postgres", host: "localhost.evil.test" }, { type: "postgres", host: "127.0.0.1", ssh_host: "remote" }, - { type: "snowflake", host: "localhost" }, - { type: "sqlserver", host: "localhost", authentication: "azure-active-directory-default" }, - { type: "sqlserver", host: "localhost", authentication: "default" }, - { type: "postgres", connection_string: "postgres://localhost/db?host=remote" }, - { type: "mongodb", connection_string: "mongodb+srv://localhost/db" }, - { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true", direct_connection: false }, - { type: "mongodb", connection_string: "mongodb://localhost/db?directConnection=true&authMechanism=MONGODB-AWS" }, - { type: "trino", url: "https://example.com" }, - { type: "trino", host: "127.0.0.1", protocol: "http://evil.example" }, - { type: "clickhouse", host: "127.0.0.1", protocol: "http://example.com:8123/" }, - { type: "oracle", connection_string: "db.example.com:1521/ORCL" }, - { type: "oracle", connection_string: "(DESCRIPTION=(ADDRESS=(HOST=db.example.com)))" }, - { type: "oracle", connection_string: "PRODTNS" }, { type: "mysql", server: "db.example.com" }, - { type: "postgres", connection_string: "postgresql:///analytics?host=/var/run/postgresql&hostaddr=10.0.0.5" }, - { type: "sqlserver", host: "db.example.com\\SQLEXPRESS" }, { type: "mysql", socketPath: "\\\\.\\pipe\\remote" }, + { type: "snowflake", account: "acme" }, + { type: "trino", server: "https://example.com" }, + { type: "postgres", connection_string: "not a url" }, + { type: "oracle", connection_string: "db.example.com:1521/ORCL" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) -test("offline accepts plain protocols and local Oracle Easy Connect strings", () => { - for (const config of [ - { type: "trino", host: "localhost", protocol: "https" }, - { type: "clickhouse", host: "127.0.0.1", protocol: "HTTP" }, - { type: "oracle", connection_string: "127.0.0.1:1521/ORCL" }, - { type: "oracle", connection_string: "//localhost/XEPDB1" }, - { type: "oracle", connection_string: "[::1]:1521/ORCL" }, - { type: "mysql", server: "127.0.0.1" }, - { type: "mysql", socketPath: "/tmp/mysql.sock" }, - { type: "postgres", host: "/var/run/postgresql" }, - { type: "postgres", connection_string: "postgresql:///analytics?host=/var/run/postgresql" }, - { type: "sqlserver", host: "localhost\\SQLEXPRESS" }, - ]) expect(() => assertLocalConnection(config)).not.toThrow() -}) - -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-duckdb profiles that reach remote storage or a remote server are refused", async () => { +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') }}\"", - "external_root: \"{{ env_var('OFFLINE_TEST_UNSET_ROOT') }}\"", + "attach:\n - path: md:shared", + "attach:\n - path: https://example.com/remote.duckdb", + "extensions:\n - name: custom\n repo: https://extensions.example.com", "remote:\n host: db.example.com", "filesystems:\n - fs: s3", ]) { - await fs.writeFile(path.join(root, "profiles.yml"), `test:\n outputs:\n default:\n type: duckdb\n path: local.duckdb\n ${extra}\n`) + await profile(extra) await expect(assertLocalDbt(root, ["--profiles-dir", root])).rejects.toThrow("Offline mode") } - await fs.writeFile(path.join(root, "profiles.yml"), "test:\n outputs:\n default:\n type: duckdb\n path: local.duckdb\n external_root: out/parquet\n") - await expect(assertLocalDbt(root, ["--profiles-dir", root])).resolves.toEqual({ profilesDir: root }) - } finally { await fs.rm(root, { recursive: true, force: true }) } + 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 version check", async () => { +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|$PGHOSTADDR|$pgservice\"\n", { mode: 0o755 }) + 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 previousHostaddr = process.env.PGHOSTADDR - const previousService = process.env.pgservice - process.env.PGHOSTADDR = "198.51.100.20" - // A differently-cased name is dropped too. - process.env.pgservice = "remote-service" - try { - const result = await runDbt({ command: "ls", project_dir: root, args: ["--profiles-dir", root] }) - expect(result.exit_code).toBe(0) - // libpq's destination override is dropped; usage reporting and the version check are off. - expect(result.stdout.trim()).toBe(`${root}|false|false|1||`) - } finally { - if (previousService === undefined) delete process.env.pgservice - else process.env.pgservice = previousService - if (previousHostaddr === undefined) delete process.env.PGHOSTADDR - else process.env.PGHOSTADDR = previousHostaddr - } - expect((await runDbt({ command: "deps", project_dir: root })).stderr).toContain("Offline mode") + 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.", ) - expect((await runDbt({ command: "init", args: ["--version"] })).stderr).toContain("Offline mode disables dbt version reporting.") - // `dbt init` needs no existing project or profile. - const empty = path.join(root, "new") - await fs.mkdir(empty) - expect((await runDbt({ command: "init", project_dir: empty })).exit_code).toBe(0) } 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 { @@ -184,114 +157,3 @@ test("dbt project directory follows environment and CLI precedence", async () => await expect(assertLocalDbt(root, ["--profiles-dir", root, "--project-dir", root])).resolves.toEqual({ profilesDir: root }) } finally { await fs.rm(root, { recursive: true, force: true }) } }) - -test("dbt policy failure surfaces on repeated SQL calls without a registry fallback", async () => { - const Registry = await import("../../../src/altimate/native/connections/registry") - const adapter = await import("../../../src/altimate/native/connections/register") - const Dispatcher = await import("../../../src/altimate/native/dispatcher") - const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-fallback-")) - const get = spyOn(Registry, "get") - try { - process.env.ALTIMATE_OFFLINE = "1" - 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: postgres\n host: example.com\n") - adapter.resetDbtAdapter() - adapter.dbtAdapterInternals.readConfig = async () => ({ projectRoot: root }) - adapter.registerAll() - Registry.setConfigs({ fallback: { type: "sqlite", path: ":memory:" } }) - for (let i = 0; i < 2; i++) { - const result = await Dispatcher.call("sql.execute", { sql: "SELECT 1" }) - expect((result as { error?: string }).error).toContain("Offline mode") - } - expect(get).not.toHaveBeenCalled() - } finally { - get.mockRestore() - delete adapter.dbtAdapterInternals.readConfig - adapter.resetDbtAdapter() - Registry.reset() - Dispatcher.reset() - await fs.rm(root, { recursive: true, force: true }) - } -}) - -test("the dbt adapter is checked against the project it will run, not DBT_PROJECT_DIR", async () => { - const adapter = await import("../../../src/altimate/native/connections/register") - const Dispatcher = await import("../../../src/altimate/native/dispatcher") - const Registry = await import("../../../src/altimate/native/connections/registry") - const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-projectdir-")) - const create = mock(async () => ({})) - try { - const other = path.join(root, "other") - await fs.mkdir(other) - await fs.writeFile(path.join(root, "dbt_project.yml"), "profile: remote\n") - await fs.writeFile(path.join(other, "dbt_project.yml"), "profile: local\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: db.example.com\n") - process.env.ALTIMATE_OFFLINE = "1" - process.env.DBT_PROJECT_DIR = other - adapter.resetDbtAdapter() - adapter.dbtAdapterInternals.readConfig = async () => ({ projectRoot: root }) - adapter.dbtAdapterInternals.create = create - adapter.registerAll() - const result = await Dispatcher.call("sql.execute", { sql: "SELECT 1" }) - expect((result as { error?: string }).error).toContain("Offline mode") - expect(create).not.toHaveBeenCalled() - } finally { - delete adapter.dbtAdapterInternals.readConfig - delete adapter.dbtAdapterInternals.create - adapter.resetDbtAdapter() - Registry.reset() - Dispatcher.reset() - await fs.rm(root, { recursive: true, force: true }) - } -}) - -test("cached local connections never reread credentials offline", async () => { - const Registry = await import("../../../src/altimate/native/connections/registry") - const Credentials = await import("../../../src/altimate/native/connections/credential-store") - const read = mock(async () => null) - try { - Credentials.setSecretBackendForTests({ name: "test", get: read, set: async () => {}, delete: async () => true }) - Registry.setConfigs({ local: { type: "sqlite", path: ":memory:" } }) - const connector = await Registry.get("local") - expect(read).toHaveBeenCalled() - read.mockClear() - process.env.ALTIMATE_OFFLINE = "1" - expect(await Registry.get("local")).toBe(connector) - expect(await Registry.get("local")).toBe(connector) - expect((await connector.execute("SELECT 1")).rows).toEqual([[1]]) - expect(read).not.toHaveBeenCalled() - } finally { - await Registry.closeAll() - Registry.reset() - Credentials.setSecretBackendForTests(undefined) - } -}) - -test("cached remote target is rejected and closed offline without rereading credentials", async () => { - const Registry = await import("../../../src/altimate/native/connections/registry") - const Credentials = await import("../../../src/altimate/native/connections/credential-store") - const driver = await import("@altimateai/drivers/postgres") - const close = mock(async () => {}) - const connector = { connect: async () => {}, close } - const connect = spyOn(driver, "connect").mockResolvedValue(connector as any) - const read = mock(async (account: string) => account.endsWith("/connection_string") ? "postgres://remote.example/db" : null) - try { - Credentials.setSecretBackendForTests({ name: "test", get: read, set: async () => {}, delete: async () => true }) - Registry.setConfigs({ remote: { type: "postgres", host: "localhost" } }) - expect(await Registry.get("remote")).toBe(connector as any) - expect(connect.mock.calls[0][0].connection_string).toBe("postgres://remote.example/db") - read.mockClear() - read.mockImplementation(async () => { throw new Error("keychain locked") }) - process.env.ALTIMATE_OFFLINE = "1" - await expect(Registry.get("remote")).rejects.toThrow("Offline mode") - expect(read).not.toHaveBeenCalled() - expect(close).toHaveBeenCalledTimes(1) - await Registry.closeAll() - expect(close).toHaveBeenCalledTimes(1) - } finally { - connect.mockRestore() - await Registry.closeAll() - Registry.reset() - Credentials.setSecretBackendForTests(undefined) - } -}) diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index d732249946..60546f463a 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -205,29 +205,24 @@ Plugins: }) }) -// altimate_change start — offline dbt detection sends dbt's PyPI lookup to a closed loopback proxy -test.skipIf(process.platform === "win32")("offline detection runs dbt --version behind a closed loopback proxy", async () => { +// 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 = process.env.ALTIMATE_OFFLINE + const previous = { offline: process.env.ALTIMATE_OFFLINE, dbt: process.env.ALTIMATE_DBT_PATH } try { - const seen = path.join(dir, "proxy") - fs.writeFileSync( - path.join(dir, "dbt"), - `#!/bin/sh\nprintf "%s|%s" "$HTTPS_PROXY" "$NO_PROXY" > "${seen}"\nprintf "Core:\\n - installed: 1.9.3\\nPlugins:\\n - duckdb: 1.9.0\\n"\n`, - { mode: 0o755 }, - ) + const ran = path.join(dir, "ran") + fs.writeFileSync(path.join(dir, "dbt"), `#!/bin/sh\ntouch "${ran}"\n`, { mode: 0o755 }) process.env.ALTIMATE_DBT_PATH = path.join(dir, "dbt") process.env.ALTIMATE_OFFLINE = "1" _resetDbtRuntimeCacheForTests() - expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true, dbtCoreVersion: "1.9.3" }) - expect(fs.readFileSync(seen, "utf8")).toBe("http://127.0.0.1:9|") - // A probe that prints the versions and then exits non-zero still finds dbt offline. - fs.writeFileSync(path.join(dir, "dbt"), `#!/bin/sh\nprintf "Core:\\n - installed: 1.9.3\\n"\nexit 1\n`, { mode: 0o755 }) - _resetDbtRuntimeCacheForTests() - expect(await detectDbtRuntime({ force: true })).toMatchObject({ hasDbt: true, dbtCoreVersion: "1.9.3" }) + expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: false }) + expect(fs.existsSync(ran)).toBe(false) } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous + 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 }) } }) diff --git a/packages/opencode/test/altimate/registry-per-project.test.ts b/packages/opencode/test/altimate/registry-per-project.test.ts index 60aa1955b9..f192d63a71 100644 --- a/packages/opencode/test/altimate/registry-per-project.test.ts +++ b/packages/opencode/test/altimate/registry-per-project.test.ts @@ -240,25 +240,6 @@ describe("connectors are per project", () => { expect(b2).not.toBe(a) }) - test("offline rejection closes a cached connector and its SSH tunnel", async () => { - const offline = process.env.ALTIMATE_OFFLINE - delete process.env.ALTIMATE_OFFLINE - try { - writeLocal(projectA, { store: sshStore("offline-bastion") }) - const connector = await inProject(projectA, () => Registry.get("store")) - const close = spyOn(connector, "close") - process.env.ALTIMATE_OFFLINE = "1" - await expect(inProject(projectA, () => Registry.get("store"))).rejects.toThrow("Offline mode") - expect(close).toHaveBeenCalledTimes(1) - expect(ended("offline-bastion")).toEqual([true]) - expect(openTunnelCount()).toBe(0) - close.mockRestore() - } finally { - if (offline === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = offline - } - }) - test("same-named SSH tunnels are per project; removing in B leaves A's open", async () => { const tunnelled = (sshHost: string) => ({ store: { type: "sqlite", path: "store.sqlite", create: true, ssh_host: sshHost, host: "db", port: 5432 }, diff --git a/packages/opencode/test/altimate/workspace/skill-sync.test.ts b/packages/opencode/test/altimate/workspace/skill-sync.test.ts index dc111b907d..24a56c348c 100644 --- a/packages/opencode/test/altimate/workspace/skill-sync.test.ts +++ b/packages/opencode/test/altimate/workspace/skill-sync.test.ts @@ -1338,63 +1338,6 @@ describe("workspace skill sync", () => { } }) - test("offline registry notices a changed local binding without deleting the snapshot", async () => { - serve({ "pub-1": { "SKILL.md": "one" } }) - await syncSkills(project) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - expect(await snapshotWorkspaceId(project)).toBe(1) - await markRegistryApplied(project) - expect(await registryStale(project)).toBe(false) - bindTo(2) - expect(await registryStale(project)).toBe(true) - expect(await snapshotWorkspaceId(project)).toBeNull() - bindTo(1) - await markRegistryApplied(project) - expect(await snapshotWorkspaceId(project)).toBe(1) - writeFileSync(cachePath(), "{") - expect(await registryStale(project)).toBe(true) - expect(await snapshotWorkspaceId(project)).toBeNull() - expect(existsSync(skillFile("pub-1", "SKILL.md"))).toBe(true) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }) - - test("offline withholds a snapshot from a different or broken serve pin without deleting it", async () => { - serve({ "pub-1": { "SKILL.md": "one" } }) - await syncSkills(project) - const keys = ["ALTIMATE_OFFLINE", "ALTIMATE_CODE_SERVE", "ALTIMATE_PINNED_WORKSPACE_ID", "ALTIMATE_PINNED_WORKSPACE_NAME", "ALTIMATE_PINNED_WORKSPACE_ROOT"] - const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) - const pin = (id: string) => - Object.assign(process.env, { - ALTIMATE_CODE_SERVE: "1", - ALTIMATE_PINNED_WORKSPACE_ID: id, - ALTIMATE_PINNED_WORKSPACE_NAME: "pinned", - ALTIMATE_PINNED_WORKSPACE_ROOT: project, - }) - try { - process.env.ALTIMATE_OFFLINE = "1" - pin("2") - expect(await snapshotWorkspaceId(project)).toBeNull() - pin("not-a-number") - expect(await snapshotWorkspaceId(project)).toBeNull() - pin("1") - expect(await snapshotWorkspaceId(project)).toBe(1) - // A matching pin outranks a project link that names another workspace. - bindTo(2) - expect(await snapshotWorkspaceId(project)).toBe(1) - expect(existsSync(skillFile("pub-1", "SKILL.md"))).toBe(true) - } finally { - for (const key of keys) { - if (saved[key] === undefined) delete process.env[key] - else process.env[key] = saved[key] - } - } - }) - test("registryStale reports a credential switch, with the snapshot untouched", async () => { // The disclosure this guards: the registry had already loaded the previous // account's skills, and an A-to-B switch changes nothing on disk. Keyed on diff --git a/packages/opencode/test/altimate/workspace/state-pin.test.ts b/packages/opencode/test/altimate/workspace/state-pin.test.ts index 08ee7f1a86..96459e2d8e 100644 --- a/packages/opencode/test/altimate/workspace/state-pin.test.ts +++ b/packages/opencode/test/altimate/workspace/state-pin.test.ts @@ -13,7 +13,7 @@ const SANDBOX = path.join(os.tmpdir(), `altimate-state-pin-test-${process.pid}-$ mkdirSync(path.join(SANDBOX, "state"), { recursive: true }) process.env.XDG_STATE_HOME = path.join(SANDBOX, "state") -const { recordApprovedBinding, resolveBindingOutcome, __resetPinValidation, PIN_VALIDATION_TTL_MS, PIN_STALE_IF_ERROR_MS } = +const { resolveBindingOutcome, __resetPinValidation, PIN_VALIDATION_TTL_MS, PIN_STALE_IF_ERROR_MS } = await import("../../../src/altimate/workspace/state") const { AltimateApi } = await import("../../../src/altimate/api/client") const { WorkspaceApi, ForbiddenError, WorkspaceApiError } = await import( @@ -116,30 +116,6 @@ afterAll(() => { }) describe("resolveBindingOutcome — extension pin", () => { - test("offline only returns an existing unpinned local binding", async () => { - const directory = path.join(SANDBOX, "offline-project") - mkdirSync(directory, { recursive: true }) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - let requests = 0 - ;(WorkspaceApi as unknown as { listDatamates: () => Promise }).listDatamates = async () => { - requests++ - return [] - } - try { - expect(await resolveBindingOutcome(directory)).toEqual({ status: "unknown" }) - const binding = { datamateId: 17, datamateName: "local", linkedAt: Date.now(), repoRemote: null, projectPath: directory } - await recordApprovedBinding(directory, binding, { seed: false, awaitBackfill: true }) - expect(await resolveBindingOutcome(directory)).toMatchObject({ status: "bound", stale: true, binding }) - setPin({ ALTIMATE_PINNED_WORKSPACE_ROOT: directory }) - expect(await resolveBindingOutcome(directory)).toEqual({ status: "unknown" }) - expect(requests).toBe(0) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }) - test("a valid, account-visible pin binds, and is marked pinned", async () => { setPin() const out = await resolveBindingOutcome(ROOT) diff --git a/packages/opencode/test/cli/mcp-add.test.ts b/packages/opencode/test/cli/mcp-add.test.ts index 9a3b747bf9..5aaf2aaa6e 100644 --- a/packages/opencode/test/cli/mcp-add.test.ts +++ b/packages/opencode/test/cli/mcp-add.test.ts @@ -164,10 +164,10 @@ test("offline MCP add refuses remote configuration before writing it", () => { 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("localhost/loopback") - expect(readFileSync(configPath, "utf8")).toBe(original) + expect(`${result.stdout}${result.stderr}`).toContain("localhost, 127.0.0.1 or [::1]") + expect(readJson(configPath).mcp).toEqual({}) }, true) -}) +}, 30_000) test("offline MCP add permits stdio and loopback configuration", () => { withIsolatedCli(({ configDir, run }) => { @@ -177,4 +177,4 @@ test("offline MCP add permits stdio and loopback configuration", () => { 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 index 6dab004566..5ddcd3d91c 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -1,8 +1,10 @@ -import { expect, test } from "bun:test" +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" @@ -11,6 +13,47 @@ 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.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, @@ -24,6 +67,9 @@ async function fixture( 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"), @@ -96,7 +142,7 @@ async function fixture( index: 0, id: "call_shell", type: "function", function: { name: "bash", arguments: JSON.stringify({ - command: 'printf "shell-ran:%s" "$NO_PROXY" > shell-marker', + 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, @@ -127,7 +173,10 @@ async function fixture( `, ) const env = { - PATH: process.env.PATH, + 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: path.join(root, "managed"), @@ -149,7 +198,7 @@ async function fixture( ALTIMATE_RUN_STDIN_WAIT_MS: "0", NO_COLOR: "1", } - return { root, project, preload, env, calls, blocked, manifest, skill } + return { root, project, preload, env, calls, blocked, manifest, skill, shims, spawns } } for (const { scenario, snapshot, configMode, disableWorkspace } of [ @@ -169,12 +218,13 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ ]) { 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. - env: snapshot ? { ...f.env, PATH: path.join(f.root, "empty-path") } : f.env, + // 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", @@ -197,10 +247,9 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ expect(calls.length).toBeGreaterThan(0) expect(calls.some((call) => call.hasSkill)).toBe(snapshot) expect(stderr).not.toContain("Workspace skills not synced") - // The fixture without a snapshot has no workspace link, so it gets no workspace notice at all. - if (!snapshot) expect(stderr).not.toContain("Offline mode:") - else { - expect(stderr.match(/Offline mode:/g)).toHaveLength(1) + // 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) } @@ -215,7 +264,7 @@ test("offline model can execute a local bash command", async () => { 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 exclusions reach their own commands; the offline bypass does not. + // 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", @@ -229,7 +278,7 @@ test("offline model can execute a local bash command", async () => { ]) 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" }) + expect({ marker, stdout, stderr }).toMatchObject({ marker: `shell-ran:corp.example,localhost,127.0.0.1,[::1]|${PROXY}|1` }) expect(await fs.readFile(f.blocked, "utf8").catch(() => "")).toBe("") } finally { await fs.rm(f.root, { recursive: true, force: true }) @@ -292,7 +341,7 @@ test("offline SQL tool refuses a warehouse whose host is not loopback", async () ], { 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 loopback warehouse connections.") + 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 { @@ -328,116 +377,6 @@ test("offline attach accepts a server on this machine and refuses a remote one", } }, 45_000) -test("attach --dir applies that project's offline setting when launched elsewhere", async () => { - // configMode without a snapshot: the project's own config turns offline mode on; the env switch is off. - const f = await fixture(false, true, false) - try { - const proc = Bun.spawn( - [process.execPath, "--preload", f.preload, CLI, "attach", "https://remote-server.test", "--dir", f.project], - { cwd: f.root, 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 - expect(stdout + stderr).toContain("This command requires network access") - // From inside that project, a --dir that exists only on the remote server keeps the project's setting. - const remote = Bun.spawn( - [process.execPath, "--preload", f.preload, CLI, "attach", "https://remote-server.test", "--dir", "/srv/remote-only"], - { cwd: f.project, env: f.env, stdin: "ignore", stdout: "pipe", stderr: "pipe", signal: AbortSignal.timeout(20_000) }, - ) - const [out2, err2] = await Promise.all([new Response(remote.stdout).text(), new Response(remote.stderr).text()]) - await remote.exited - expect(out2 + err2).toContain("This command requires network access") - } finally { - await fs.rm(f.root, { recursive: true, force: true }) - } -}, 45_000) - -test("offline model transport bypasses proxy settings and refuses redirects", async () => { - let proxyCalls = 0 - const proxy = Bun.serve({ - hostname: "127.0.0.1", - port: 0, - fetch() { - proxyCalls++ - return new Response("unexpected proxy") - }, - }) - const model = Bun.serve({ - hostname: "127.0.0.1", - port: 0, - fetch(request) { - if (new URL(request.url).pathname === "/redirect") return Response.redirect(proxy.url, 302) - return new Response("direct model response") - }, - }) - try { - const source = path.resolve(import.meta.dir, "../../../src/config/offline.ts") - const proc = Bun.spawn( - [ - process.execPath, - "-e", - ` - import { Offline } from ${JSON.stringify(source)} - await Offline.start(process.cwd()) - const request = Offline.modelFetch(process.env.OFFLINE_TEST_MODEL) - console.log(await (await request(process.env.OFFLINE_TEST_MODEL)).text()) - try { - await request(process.env.HTTP_PROXY) - throw new Error("cross-origin request was accepted") - } catch (error) { - if (!error.message.includes("outside the configured model endpoint")) throw error - console.log("cross-origin request refused") - } - try { - const modelScoped = Offline.modelFetch(new URL("/v1", process.env.OFFLINE_TEST_MODEL).href) - await modelScoped(new URL("/v10/admin", process.env.OFFLINE_TEST_MODEL)) - throw new Error("different endpoint path was accepted") - } catch (error) { - if (!error.message.includes("outside the configured model endpoint")) throw error - console.log("other model host path refused") - } - try { - await request(new URL("/redirect", process.env.OFFLINE_TEST_MODEL)) - throw new Error("redirect was accepted") - } catch (error) { - if (error.message === "redirect was accepted") throw error - console.log("redirect refused") - } - `, - ], - { - cwd: path.resolve(import.meta.dir, "../../.."), - env: { - ...process.env, - ALTIMATE_OFFLINE: "1", - OFFLINE_TEST_MODEL: model.url.href, - HTTP_PROXY: proxy.url.href, - http_proxy: proxy.url.href, - NO_PROXY: "", - no_proxy: "", - }, - stdout: "pipe", - stderr: "pipe", - signal: AbortSignal.timeout(15_000), - }, - ) - const [code, stdout, stderr] = await Promise.all([ - proc.exited, - new Response(proc.stdout).text(), - new Response(proc.stderr).text(), - ]) - expect({ code, stdout, stderr }).toEqual({ - code: 0, - stdout: "direct model response\ncross-origin request refused\nother model host path refused\nredirect refused\n", - stderr: "", - }) - expect(proxyCalls).toBe(0) - } finally { - model.stop(true) - proxy.stop(true) - } -}) - 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") @@ -636,3 +575,117 @@ test("standalone MCP initializes offline over stdio without network requests", a 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/offline-startup.test.ts b/packages/opencode/test/config/offline-startup.test.ts deleted file mode 100644 index 423ebf0087..0000000000 --- a/packages/opencode/test/config/offline-startup.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -// altimate_change - new file -import { expect, test } from "bun:test" -import fs from "node:fs/promises" -import { tmpdir } from "../fixture/fixture" -import path from "node:path" -import { Global } from "../../src/global" -import { Offline } from "../../src/config/offline" - -test("a legacy global TOML config that requests offline mode is detected at startup", async () => { - await using tmp = await tmpdir() - const project = tmp.path - const legacy = path.join(Global.Path.config, "config") - const keys = ["ALTIMATE_OFFLINE", "OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT"] - const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) - for (const key of keys) delete process.env[key] - try { - await fs.mkdir(Global.Path.config, { recursive: true }) - await fs.writeFile(legacy, 'model = "fixture"\noffline = true\n') - await expect(Offline.assertStartupPolicy(project)).rejects.toThrow("requests offline mode") - await fs.writeFile(legacy, "offline = false\n") - await expect(Offline.assertStartupPolicy(project)).resolves.toBeUndefined() - await fs.writeFile(legacy, "not = [valid toml") - await expect(Offline.assertStartupPolicy(project)).resolves.toBeUndefined() - // An unparseable file that plainly requests offline mode still counts. - await fs.writeFile(legacy, "offline = true\nbroken = [\n") - await expect(Offline.assertStartupPolicy(project)).rejects.toThrow("requests offline mode") - } finally { - await fs.rm(legacy, { force: true }) - for (const key of keys) { - if (saved[key] === undefined) delete process.env[key] - else process.env[key] = saved[key] - } - } -}) diff --git a/packages/opencode/test/config/paths-parsetext.test.ts b/packages/opencode/test/config/paths-parsetext.test.ts index 5b3779e1b7..c9e1b52ef5 100644 --- a/packages/opencode/test/config/paths-parsetext.test.ts +++ b/packages/opencode/test/config/paths-parsetext.test.ts @@ -311,14 +311,6 @@ describe("ConfigPaths.parseText: ${VAR} substitution (shell/dotenv alias)", () = }) describe("ConfigPaths.parseText: {file:path} substitution", () => { - test("expandFiles=false preserves existing and missing file tokens", async () => { - await using tmp = await tmpdir() - await fs.writeFile(path.join(tmp.path, "secret.txt"), "do-not-expand") - const text = '{"existing":"{file:secret.txt}","missing":"{file:missing.txt}"}' - expect(await ConfigPaths.parseText(text, path.join(tmp.path, "config.json"), "error", { expandFiles: false })) - .toEqual({ existing: "{file:secret.txt}", missing: "{file:missing.txt}" }) - }) - test("substitutes {file:path} with file contents (trimmed)", async () => { await using tmp = await tmpdir() const secretPath = path.join(tmp.path, "secret.txt") diff --git a/packages/opencode/test/control-plane/workspace.test.ts b/packages/opencode/test/control-plane/workspace.test.ts index 3c173b0330..a51de0fa22 100644 --- a/packages/opencode/test/control-plane/workspace.test.ts +++ b/packages/opencode/test/control-plane/workspace.test.ts @@ -808,67 +808,6 @@ describe("workspace CRUD", () => { { git: true }, ) - // altimate_change start — offline removal refuses a workspace holding a shared session, removing nothing - it.instance( - "offline remove refuses a workspace with a shared session and keeps everything", - () => - Effect.gen(function* () { - const { directory: dir } = yield* TestInstance - const instance = yield* requireInstance - const workspace = yield* Workspace.Service - const sessionSvc = yield* SessionNs.Service - const type = unique("remove-offline-shared") - const recorded = localAdapter(path.join(dir, "remove-offline-shared")) - registerAdapter(ProjectV2.ID.make(instance.project.id), type, recorded.adapter) - const info = yield* workspace.create({ type, branch: null, projectID: ProjectV2.ID.make(instance.project.id), extra: null }) - const plain = yield* sessionSvc.create({}) - const shared = yield* sessionSvc.create({}) - yield* attachSessionToWorkspace(plain.id, info.id) - yield* attachSessionToWorkspace(shared.id, info.id) - const { db } = yield* Database.Service - yield* db - .update(SessionTable) - .set({ share_url: "https://share.example/s/ws" }) - .where(eq(SessionTable.id, shared.id)) - .run() - .pipe(Effect.orDie) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - expectExitContains(yield* Effect.exit(workspace.remove(info.id)), "This workspace has a shared session") - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - expect(yield* workspace.get(info.id)).toEqual(info) - expect(recorded.calls.remove).toEqual([]) - const kept = yield* db - .select({ id: SessionTable.id }) - .from(SessionTable) - .where(eq(SessionTable.workspace_id, info.id)) - .all() - .pipe(Effect.orDie) - expect(kept.map((row) => row.id).sort()).toEqual([plain.id, shared.id].sort()) - yield* db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, shared.id)).run().pipe(Effect.orDie) - // A shared subagent session carries only a parent id; the check still finds it before removing anything. - const sub = yield* sessionSvc.create({ parentID: plain.id }) - yield* db.update(SessionTable).set({ share_url: "https://share.example/s/sub", workspace_id: null }).where(eq(SessionTable.id, sub.id)).run().pipe(Effect.orDie) - process.env.ALTIMATE_OFFLINE = "1" - try { - expectExitContains(yield* Effect.exit(workspace.remove(info.id)), "This workspace has a shared session") - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - expect(yield* workspace.get(info.id)).toEqual(info) - expect((yield* sessionSvc.get(plain.id)).id).toBe(plain.id) - yield* db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, sub.id)).run().pipe(Effect.orDie) - yield* workspace.remove(info.id) - }), - { git: true }, - ) - // altimate_change end - it.instance( "remove still deletes the row when the adapter cannot remove resources", () => diff --git a/packages/opencode/test/lsp/offline.test.ts b/packages/opencode/test/lsp/offline.test.ts index 44cbbc3115..613b9c9174 100644 --- a/packages/opencode/test/lsp/offline.test.ts +++ b/packages/opencode/test/lsp/offline.test.ts @@ -41,27 +41,3 @@ test.skipIf(process.platform === "win32")("offline LSP spawns an npm-cached serv await fs.rm(dir, { recursive: true, force: true }) } }) - -test.skipIf(process.platform === "win32")("offline language servers get the user's proxy exclusions back", async () => { - const { spawn } = await import("../../src/lsp/launch") - const keys = ["ALTIMATE_OFFLINE", "NO_PROXY", "no_proxy", "ALTIMATE_OFFLINE_USER_PROXY"] - const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) - try { - // The state Offline.start leaves: the bypass, plus the user's original values. - process.env.ALTIMATE_OFFLINE = "1" - process.env.ALTIMATE_OFFLINE_USER_PROXY = JSON.stringify({ NO_PROXY: "corp.example" }) - process.env.NO_PROXY = process.env.no_proxy = "*" - for (const opts of [{}, { env: { ...process.env } }]) { - const proc = spawn("sh", ["-c", 'printf "%s|%s|%s" "$NO_PROXY" "$no_proxy" "$ALTIMATE_OFFLINE_USER_PROXY"'], opts) - const exited = proc.exited - const out = await new Response(proc.stdout as any).text() - await exited - expect(out).toBe("corp.example||") - } - } finally { - for (const key of keys) { - if (saved[key] === undefined) delete process.env[key] - else process.env[key] = saved[key] - } - } -}) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 28db524642..17c2609548 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -1,72 +1,46 @@ // altimate_change - new file import { expect, test } from "bun:test" +import path from "node:path" import { Offline } from "../../src/config/offline" -test("offline MCP URL policy accepts only HTTP(S) localhost and loopback", () => { - for (const url of ["http://localhost:3000/mcp", "https://localhost./mcp", "http://127.2.3.4/mcp", "http://[::1]:3000/mcp", "http://0.0.0.0:4096", "http://[::]:4096"]) +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) }) -test("offline local MCP fetch rejects remote requests and redirects before remote egress", async () => { - // Bun applies HTTP(S)_PROXY to loopback too unless NO_PROXY covers it; keep an ambient proxy out of this test. - const proxyKeys = ["HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"] - const savedProxy = Object.fromEntries(proxyKeys.map((key) => [key, process.env[key]])) - for (const key of proxyKeys) delete process.env[key] - process.env.NO_PROXY = process.env.no_proxy = "127.0.0.1,localhost" - let calls = 0 - let server: ReturnType | undefined - try { - server = Bun.serve({ - hostname: "127.0.0.1", - port: 0, - fetch(request) { - calls++ - return new URL(request.url).pathname === "/redirect" - ? Response.redirect("https://example.com/mcp") - : new Response("local MCP") - }, - }) - const fetch = Offline.localFetch() - expect(await (await fetch(server.url)).text()).toBe("local MCP") - await expect(fetch(new URL("/redirect", server.url))).rejects.toThrow() - await expect(fetch("https://example.com/mcp")).rejects.toThrow("non-local request") - expect(calls).toBe(2) - } finally { - server?.stop(true) - for (const key of proxyKeys) { - if (savedProxy[key] === undefined) delete process.env[key] - else process.env[key] = savedProxy[key] - } - } +// 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: () => new Response("local") }) + Offline.start() + const local = await (await fetch(server.url)).text() + const remote = await fetch("https://example.com/").then(() => "sent", (error) => error.message) + server.stop(true) + console.log(JSON.stringify({ local, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_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" }, + 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", + remote: "Offline mode allows network requests only to the configured model endpoint.", + env: ["1", "http://proxy.example:3128", "corp.example,localhost,127.0.0.1,[::1]"], + }) }) -test("user programs get their own proxy exclusions back, not the offline bypass", () => { - const keys = ["NO_PROXY", "no_proxy", "ALTIMATE_OFFLINE_USER_PROXY"] - const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])) - try { - // What Offline.start leaves behind: the bypass, plus the user's original values. - process.env.ALTIMATE_OFFLINE_USER_PROXY = JSON.stringify({ NO_PROXY: "corp.example" }) - process.env.NO_PROXY = process.env.no_proxy = "*" - const env: Record = Offline.userEnv({ ...process.env, PATH: "/bin" }) - expect(env.NO_PROXY).toBe("corp.example") - expect(env.no_proxy).toBeUndefined() - expect(env.ALTIMATE_OFFLINE_USER_PROXY).toBeUndefined() - expect(Offline.userEnv({ ...process.env, ALTIMATE_OFFLINE_MODEL: "local/main" }).ALTIMATE_OFFLINE_MODEL).toBeUndefined() - expect(env.PATH).toBe("/bin") - // A copied env that lacks the key (Bun omits variables assigned after startup) still gets the saved value. - const copy: Record = { PATH: "/bin" } - expect(Offline.userEnv(copy).NO_PROXY).toBe("corp.example") - // A value the program's own configuration set is kept. - expect(Offline.userEnv({ ...process.env, NO_PROXY: "mcp.local" }).NO_PROXY).toBe("mcp.local") - // Without offline state, the environment is unchanged. - delete process.env.ALTIMATE_OFFLINE_USER_PROXY - expect(Offline.userEnv({ NO_PROXY: "*" }).NO_PROXY).toBe("*") - } finally { - for (const key of keys) { - if (saved[key] === undefined) delete process.env[key] - else process.env[key] = saved[key] - } - } +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)") }) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 95b08fbb16..db875e4c8e 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -1,6 +1,5 @@ import { afterEach, describe, expect } from "bun:test" import path from "path" -import { mkdir, rm } 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" @@ -107,58 +106,6 @@ describe("Worktree", () => { { git: true }, ) - // altimate_change start — offline reset with a submodule this worktree never checked out - it.instance( - "resets an offline worktree whose repository has a submodule it never checked out", - Effect.gen(function* () { - const { directory } = yield* TestInstance - const run = (cwd: string, args: string[]) => { - const result = Bun.spawnSync(["git", "-c", "protocol.file.allow=always", ...args], { cwd, stdout: "pipe", stderr: "pipe" }) - if (result.exitCode !== 0) throw new Error(result.stderr.toString()) - } - // A path with a space checks that submodule paths are kept whole. - const lib = path.join(path.dirname(directory), `${path.basename(directory)}-lib`) - const previous = process.env.ALTIMATE_OFFLINE - try { - yield* Effect.promise(() => mkdir(lib, { recursive: true })) - for (const args of [["init", "-q"], ["config", "user.email", "t@example.com"], ["config", "user.name", "t"], ["config", "commit.gpgsign", "false"], ["commit", "-q", "--allow-empty", "-m", "lib"]]) - run(lib, args) - run(directory, ["submodule", "add", "-q", lib, "vendor lib"]) - run(directory, ["commit", "-q", "-m", "add submodule"]) - // A second lib commit, recorded in the main repo as the newer submodule commit; the test rewinds the - // worktree's submodule to the older one below. - const older = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: lib, stdout: "pipe" }).stdout.toString().trim() - run(lib, ["commit", "-q", "--allow-empty", "-m", "lib 2"]) - run(path.join(directory, "vendor lib"), ["fetch", "-q", "origin"]) - run(path.join(directory, "vendor lib"), ["checkout", "-q", "origin/HEAD"]) - const newer = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: lib, stdout: "pipe" }).stdout.toString().trim() - run(directory, ["add", "vendor lib"]) - run(directory, ["commit", "-q", "-m", "bump submodule"]) - process.env.ALTIMATE_OFFLINE = "1" - const svc = yield* Worktree.Service - yield* withCreatedWorktree({ name: "offline-submodule" }, ({ info }) => - Effect.gen(function* () { - // Unpopulated submodule: the offline reset skips it instead of trying to clone it. - expect(yield* svc.reset({ directory: info.directory })).toBe(true) - // Populated submodule whose path has a space, checked out at the older commit: the offline reset - // moves it to the recorded commit from objects already on disk. - run(info.directory, ["submodule", "update", "--init"]) - run(path.join(info.directory, "vendor lib"), ["checkout", "-q", older]) - expect(yield* svc.reset({ directory: info.directory })).toBe(true) - const head = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: path.join(info.directory, "vendor lib"), stdout: "pipe" }) - expect(head.stdout.toString().trim()).toBe(newer) - }), - ) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - yield* Effect.promise(() => rm(lib, { recursive: true, force: true })) - } - }), - { git: true }, - ) - // altimate_change end - describe("makeWorktreeInfo", () => { it.instance( "returns info with name, branch, and directory", diff --git a/packages/opencode/test/release-validation/question-937-codex.test.ts b/packages/opencode/test/release-validation/question-937-codex.test.ts index b6ff066027..3a7deeb244 100644 --- a/packages/opencode/test/release-validation/question-937-codex.test.ts +++ b/packages/opencode/test/release-validation/question-937-codex.test.ts @@ -365,8 +365,7 @@ describe("release validation PR #937 source-level env plumbing", () => { test("bash tool strips ALTIMATE_NON_INTERACTIVE from child process env but keeps auto-answer env untouched", async () => { const source = await Bun.file(new URL("../../src/tool/bash.ts", import.meta.url)).text() - // Offline mode restores the user's proxy settings on the inherited environment before plugin overrides. - expect(source).toContain('const mergedEnv: Record = { ...Offline.userEnv({ ...process.env }), ...shellEnv.env }') + expect(source).toContain('const mergedEnv: Record = { ...process.env, ...shellEnv.env }') // The stripping moved into `stripHostMarkers` (shared with the shell tool in v0.12.1); // the contract is behavioural now: the non-interactive marker goes, auto-answer stays. expect(source).toContain("stripHostMarkers(mergedEnv)") diff --git a/packages/opencode/test/server/httpapi-mcp.test.ts b/packages/opencode/test/server/httpapi-mcp.test.ts index 8e510c7dcb..cb873fffb9 100644 --- a/packages/opencode/test/server/httpapi-mcp.test.ts +++ b/packages/opencode/test/server/httpapi-mcp.test.ts @@ -21,38 +21,6 @@ const readResponse = Effect.fnUntraced(function* (input: { path: string; directo }) describe("mcp HttpApi", () => { - it.instance("returns a client error when adding or connecting a remote MCP server offline", () => - Effect.gen(function* () { - const tmp = yield* TestInstance - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - const response = yield* request(McpPaths.status, tmp.directory, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ name: "remote", config: { type: "remote", url: "https://example.com/mcp" } }), - }) - expect(response.status).toBe(400) - expect(yield* json(response)).toMatchObject({ - _tag: "MCP.OfflinePolicyError", - message: expect.stringContaining("Offline mode"), - }) - const connect = yield* request("/mcp/configured-remote/connect", tmp.directory, { method: "POST" }) - expect(connect.status).toBe(400) - expect(yield* json(connect)).toMatchObject({ _tag: "MCP.OfflinePolicyError" }) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }), - { - config: { - experimental: { auto_mcp_discovery: false }, - mcp: { "configured-remote": { type: "remote", url: "https://example.com/mcp", enabled: false } }, - }, - }, - ) - it.instance( "serves status endpoint", () => @@ -65,7 +33,6 @@ describe("mcp HttpApi", () => { }), { config: { - experimental: { auto_mcp_discovery: false }, mcp: { demo: { type: "local", diff --git a/packages/opencode/test/server/httpapi-session-offline.test.ts b/packages/opencode/test/server/httpapi-session-offline.test.ts deleted file mode 100644 index 8cab7f89f8..0000000000 --- a/packages/opencode/test/server/httpapi-session-offline.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -// altimate_change - new file -import { describe, expect } from "bun:test" -import { Effect } from "effect" -import { SessionTable } from "@opencode-ai/core/session/sql" -import { Database, eq } from "../../src/storage/db" -import { TestInstance } from "../fixture/fixture" -import { testEffect } from "../lib/effect" -import { httpApiLayer, requestInDirectory } from "./httpapi-layer" - -const it = testEffect(httpApiLayer) - -describe("session HttpApi offline", () => { - it.instance("declares the offline refusals for delete, share and unshare as 400s", () => - Effect.gen(function* () { - const tmp = yield* TestInstance - const created = yield* requestInDirectory("/session", tmp.directory, { - method: "POST", - headers: { "content-type": "application/json" }, - body: "{}", - }) - const session = (yield* created.json) as { id: string } - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - for (const method of ["POST", "DELETE"]) { - const response = yield* requestInDirectory(`/session/${session.id}/share`, tmp.directory, { method }) - expect({ method, status: response.status }).toEqual({ method, status: 400 }) - expect(yield* response.json).toMatchObject({ _tag: "Session.OfflinePolicyError", message: expect.stringContaining("online") }) - } - Database.use((db) => - db.update(SessionTable).set({ share_url: "https://share.example/s/3" }).where(eq(SessionTable.id, session.id as any)).run(), - ) - const removed = yield* requestInDirectory(`/session/${session.id}`, tmp.directory, { method: "DELETE" }) - expect(removed.status).toBe(400) - expect(yield* removed.json).toMatchObject({ _tag: "Session.OfflinePolicyError", message: expect.stringContaining("shared") }) - // The refusal happens before anything is deleted. - const kept = yield* requestInDirectory(`/session/${session.id}`, tmp.directory) - expect(kept.status).toBe(200) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }), - ) -}) diff --git a/packages/opencode/test/session/offline-delete.test.ts b/packages/opencode/test/session/offline-delete.test.ts deleted file mode 100644 index 40d85fea7e..0000000000 --- a/packages/opencode/test/session/offline-delete.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -// altimate_change - new file -import { afterEach, expect, test } from "bun:test" -import { SessionTable } from "@opencode-ai/core/session/sql" -import { Instance } from "../../src/project/instance" -import { Session } from "../../src/session" -import { Database, eq } from "../../src/storage/db" -import { Log } from "../../src/util/log" -import { Server } from "../../src/server/server" -import path from "node:path" -import { tmpdir } from "../fixture/fixture" - -Log.init({ print: false }) -afterEach(async () => { - await Instance.disposeAll() -}) - -test("offline mode refuses to delete a shared session, or its parent, and keeps both", async () => { - await using tmp = await tmpdir({ git: true }) - await Instance.provide({ - directory: tmp.path, - fn: async () => { - const parent = await Session.create({ title: "parent" }) - const child = await Session.create({ title: "child", parentID: parent.id }) - Database.use((db) => - db.update(SessionTable).set({ share_url: "https://share.example/s/1" }).where(eq(SessionTable.id, child.id)).run(), - ) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - await expect(Session.remove(child.id)).rejects.toThrow("This session is shared") - await expect(Session.remove(parent.id)).rejects.toThrow("This session is shared") - expect((await Session.get(child.id)).share?.url).toBe("https://share.example/s/1") - expect((await Session.get(parent.id)).id).toBe(parent.id) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - await Session.remove(parent.id).catch(() => {}) - }, - }) -}) - -test("the HTTP API reports the offline shared-session refusal as a 400 with its message", async () => { - await using tmp = await tmpdir({ git: true }) - await Instance.provide({ - directory: tmp.path, - fn: async () => { - const session = await Session.create({ title: "shared" }) - Database.use((db) => - db.update(SessionTable).set({ share_url: "https://share.example/s/2" }).where(eq(SessionTable.id, session.id)).run(), - ) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - const res = await Server.Default().request(`/session/${session.id}`, { method: "DELETE" }) - const body = await res.text() - expect({ status: res.status, body }).toMatchObject({ status: 400 }) - expect(body).toContain("This session is shared") - expect((await Session.get(session.id)).id).toBe(session.id) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - Database.use((db) => db.update(SessionTable).set({ share_url: null }).where(eq(SessionTable.id, session.id)).run()) - await Session.remove(session.id).catch(() => {}) - }, - }) -}) - -test("a server started online refuses a project that requests offline mode, with the message", async () => { - await using tmp = await tmpdir({ git: true }) - await Bun.write(path.join(tmp.path, "opencode.json"), JSON.stringify({ offline: true })) - const previous = process.env.ALTIMATE_OFFLINE - delete process.env.ALTIMATE_OFFLINE - try { - const res = await Server.Default().request(`/session?directory=${encodeURIComponent(tmp.path)}`) - const body = await res.text() - expect({ status: res.status, body }).toMatchObject({ status: 400 }) - expect(body).toContain("This project requests offline mode") - } finally { - if (previous !== undefined) process.env.ALTIMATE_OFFLINE = previous - } -}) - -test("the HTTP API reports offline share and unshare refusals as a 400 with the message", async () => { - await using tmp = await tmpdir({ git: true }) - // Offline from the start, as in a real offline process: the config is loaded with sharing disabled. - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - await Instance.provide({ - directory: tmp.path, - fn: async () => { - const session = await Session.create({ title: "share" }) - for (const method of ["POST", "DELETE"]) { - const res = await Server.Default().request(`/session/${session.id}/share`, { method }) - const body = await res.text() - expect({ method, status: res.status, body }).toMatchObject({ status: 400 }) - expect(body).toContain("online") - } - await Session.remove(session.id).catch(() => {}) - }, - }) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } -}) diff --git a/packages/opencode/test/share/share-next.test.ts b/packages/opencode/test/share/share-next.test.ts index 88f553400b..86f2ddf7db 100644 --- a/packages/opencode/test/share/share-next.test.ts +++ b/packages/opencode/test/share/share-next.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import { afterEach, beforeEach, describe, expect } from "bun:test" import { Effect, Exit, Layer, Option } from "effect" import { HttpClient } from "effect/unstable/http" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -10,7 +10,7 @@ import { AccessToken, AccountID, OrgID, RefreshToken } from "../../src/account/s import { AccountRepo } from "../../src/account/repo" import { EventV2Bridge } from "../../src/event-v2-bridge" import { Session } from "@/session/session" -import { SessionID } from "../../src/session/schema" +import type { SessionID } from "../../src/session/schema" import { ShareNext } from "@/share/share-next" import { SessionShareTable } from "@opencode-ai/core/share/sql" import { AccountStateTable, AccountTable } from "@opencode-ai/core/account/sql" @@ -112,36 +112,6 @@ beforeEach(async () => { }) describe("ShareNext", () => { - test("offline share creation fails without making a fetch call", async () => { - const prior = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - installFetchMock(() => new Response(null, { status: 200 })) - try { - await expect(ShareNext.create(SessionID.make("ses_offline_share"))).rejects.toThrow( - "Sharing sessions requires an online run.", - ) - expect(fetchRecords).toEqual([]) - } finally { - if (prior === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = prior - } - }) - - test("offline share revocation fails so unshare retains the local share state", async () => { - const prior = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - installFetchMock(() => new Response(null, { status: 200 })) - try { - await expect(ShareNext.remove(SessionID.make("ses_offline_share"))).rejects.toThrow( - "Offline mode cannot revoke a share. Run unshare while online.", - ) - expect(fetchRecords).toEqual([]) - } finally { - if (prior === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = prior - } - }) - it.live("request uses legacy share API without active org account", () => provideTmpdirInstance( () => diff --git a/packages/opencode/test/skill/discovery.test.ts b/packages/opencode/test/skill/discovery.test.ts index d53c93d98f..c3ea285232 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 — offline mode leaves the skill cache layout alone + 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 @@ -137,42 +148,4 @@ describe("Discovery.pull", () => { expect(downloadCount).toBe(firstCount) }), ) - - // altimate_change start — offline reuses the cached source list, even when a skill is named like it - it.live("offline serves the cached skills of a source, including one named index.json", () => - Effect.gen(function* () { - const source = Bun.serve({ - port: 0, - fetch(req) { - const { pathname } = new URL(req.url) - if (pathname === "/s/index.json") - return Response.json({ - skills: [ - { name: "index.json", description: "odd name", files: ["SKILL.md"] }, - { name: "plain", description: "plain", files: ["SKILL.md"] }, - ], - }) - if (pathname.endsWith("/SKILL.md")) return new Response("---\nname: x\ndescription: x\n---\nbody") - return new Response("Not Found", { status: 404 }) - }, - }) - const previous = process.env.ALTIMATE_OFFLINE - try { - const discovery = yield* Discovery.Service - const url = `http://localhost:${source.port}/s/` - const online = yield* discovery.pull(url) - expect(online.map((dir) => path.basename(dir)).sort()).toEqual(["index.json", "plain"]) - process.env.ALTIMATE_OFFLINE = "1" - // The source is gone: offline results can only come from the cache. - void source.stop(true) - const offline = yield* discovery.pull(url) - expect(offline.sort()).toEqual(online.sort()) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - void source.stop(true) - } - }), - ) - // altimate_change end }) diff --git a/packages/opencode/test/storage/storage.test.ts b/packages/opencode/test/storage/storage.test.ts index 80d0294494..afb2e93755 100644 --- a/packages/opencode/test/storage/storage.test.ts +++ b/packages/opencode/test/storage/storage.test.ts @@ -275,55 +275,6 @@ describe("Storage", () => { }), ) - it.live("migration 1 migrates local projects even when offline", () => - Effect.gen(function* () { - const fs = yield* FSUtil.Service - const tmp = yield* tmpdirScoped({ git: true }) - const storage = path.join(tmp, "storage") - const legacy = path.join(tmp, "project", "legacy") - - yield* fs.writeWithDirs(path.join(legacy, "storage", "session", "message", "probe", "0.json"), "[]") - yield* fs.writeWithDirs( - path.join(legacy, "storage", "session", "message", "probe", "1.json"), - JSON.stringify({ path: { root: tmp } }), - ) - yield* fs.writeWithDirs( - path.join(legacy, "storage", "session", "info", "ses_legacy.json"), - JSON.stringify({ id: "ses_legacy", title: "legacy" }), - ) - yield* fs.writeWithDirs( - path.join(legacy, "storage", "session", "message", "ses_legacy", "msg_legacy.json"), - JSON.stringify({ role: "user", text: "hello" }), - ) - - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - yield* Effect.gen(function* () { - const svc = yield* Storage.Service - const projects = yield* svc.list(["project"]) - expect(projects).toHaveLength(1) - const project = projects[0]![1] - - expect(yield* svc.list(["session", project])).toEqual([["session", project, "ses_legacy"]]) - expect(yield* svc.read<{ id: string; title: string }>(["session", project, "ses_legacy"])).toEqual({ - id: "ses_legacy", - title: "legacy", - }) - expect(yield* svc.read<{ role: string; text: string }>(["message", "ses_legacy", "msg_legacy"])).toEqual({ - role: "user", - text: "hello", - }) - }).pipe(Effect.provide(remappedStorage(tmp))) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - - expect(yield* fs.readFileString(path.join(storage, "migration"))).toBe("2") - }), - ) - it.live("failed migrations do not advance the marker", () => Effect.gen(function* () { const fs = yield* FSUtil.Service diff --git a/packages/opencode/test/tool/project-scan.test.ts b/packages/opencode/test/tool/project-scan.test.ts index 2a369ef761..775ecd1a56 100644 --- a/packages/opencode/test/tool/project-scan.test.ts +++ b/packages/opencode/test/tool/project-scan.test.ts @@ -1023,27 +1023,17 @@ describe("safeSpawnSync", () => { }) }) -// altimate_change start — offline dbt detection sends dbt's PyPI lookup to a closed loopback proxy -test.skipIf(process.platform === "win32")("offline data tool detection runs dbt behind a closed loopback proxy", async () => { +// 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 seen = path.join(dir, "proxy") - await fsp.writeFile(path.join(dir, "dbt"), `#!/bin/sh\nprintf "%s" "$HTTPS_PROXY" > "${seen}"\necho "dbt 1.9.3"\n`, { mode: 0o755 }) + 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" - const tools = await detectDataTools(false) - expect(tools.find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) - expect(await fsp.readFile(seen, "utf8")).toBe("http://127.0.0.1:9") - // A probe that prints dbt's real version lines and then exits non-zero still reports the version offline. - await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nprintf 'Core:\\n - installed: 1.9.3\\n'\nexit 1\n", { mode: 0o755 }) - expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.3" }) - // Some dbt builds print --version to stderr. - await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nprintf 'Core:\\n - installed: 1.9.4\\n' >&2\nexit 1\n", { mode: 0o755 }) - expect((await detectDataTools(false)).find((tool) => tool.name === "dbt")).toEqual({ name: "dbt", installed: true, version: "1.9.4" }) - // A probe that prints nothing falls back to finding dbt on PATH. - await fsp.writeFile(path.join(dir, "dbt"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }) 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 From 4cff64aff4e9352ac1865fe067e50fc687e3f5b9 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:02:38 -0800 Subject: [PATCH 50/72] fix: close review gaps in offline mode checks - Refuse a connection string whose `host`/`hostaddr` query parameter points at a non-loopback host. - Treat `submodule update --init`, LFS transfers and `archive --remote` as network Git commands; offline worktree reset clones no submodule. - `ALTIMATE_OFFLINE=off`/`no` mean off; a config read failure at startup no longer aborts a command. - Detect dbt-duckdb offline; docs say named extensions and plugins are not checked. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 4 ++-- packages/core/src/flag/flag.ts | 3 ++- packages/core/src/git.ts | 5 ++++- packages/dbt-tools/src/index.ts | 2 +- packages/drivers/src/duckdb.ts | 2 +- .../altimate/native/connections/offline.ts | 10 ++++++--- .../src/altimate/native/dbt/offline.ts | 2 +- .../src/altimate/onboarding/tool-detection.ts | 21 ++++++++++++++++++- packages/opencode/src/config/offline.ts | 6 ++++++ packages/opencode/src/worktree/index.ts | 6 ++++-- .../native/offline-connections.test.ts | 4 ++++ packages/opencode/test/mcp/offline.test.ts | 17 +++++++++++++++ .../opencode/test/project/worktree.test.ts | 11 ++++++++++ .../opencode/test/skill/discovery.test.ts | 2 +- packages/opencode/test/util/git.test.ts | 8 +++++++ 15 files changed, 89 insertions(+), 14 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index dfbeef0c4d..70cdf9087e 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ With offline mode off, nothing on this page applies and Altimate Code behaves ex ### Turn it on -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. Organisation-managed configuration and remote (well-known) configuration apply the setting only once they load, after some startup requests; use `ALTIMATE_OFFLINE=1` there. Once on, offline mode lasts for the rest of the process, including any server that loaded the project. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. Organisation-managed configuration and remote (well-known) configuration apply the setting only once they load, after some startup requests; use `ALTIMATE_OFFLINE=1` there. Any one of these sources turns it on; a value of `false` elsewhere does not turn it back off. `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`. @@ -183,7 +183,7 @@ While still online: ### What keeps working - Local warehouses: DuckDB and SQLite files, and warehouses reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. A host that is not one of these, or a connection string that cannot be parsed, is refused. -- dbt commands whose selected profile and target are local. dbt-duckdb profiles can use installed extensions, local attachments and plugins; settings that point at remote storage or a remote server (`s3://`, `https://`, `gcs://`, `md:` and similar) are refused. +- dbt commands whose selected profile and target are local. 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; it does not download new ones. - The shell tool, installed language servers, stdio MCP servers and MCP servers at `localhost`, `127.0.0.1` or `[::1]`, including `tool run --daemon`. - Git diffs, session snapshots and revert, and worktree create, remove and reset (reset uses the locally cached base branch). diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index 06c9956ac1..39df4a1229 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -21,7 +21,8 @@ export function env(key: string): string | undefined { } export function offlineModeEnabled() { - return killSwitchSet(process.env.ALTIMATE_OFFLINE) + const value = process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() + return killSwitchSet(value) && value !== "off" && value !== "no" } export function truthy(key: string) { diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 8ddee23964..d07b660ec4 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -20,7 +20,10 @@ export function gitCommandUsesNetwork(args: string[]) { const [command, operation, ...rest] = args.slice(index) return ( remoteCommands.has(command) || - (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) + (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) || + (command === "submodule" && operation === "update" && (rest.includes("--init") || !rest.includes("--no-fetch"))) || + (command === "lfs" && ["fetch", "pull", "push", "clone"].includes(operation)) || + (command === "archive" && [operation, ...rest].some((arg) => arg?.startsWith("--remote"))) ) } diff --git a/packages/dbt-tools/src/index.ts b/packages/dbt-tools/src/index.ts index 605d3704e8..b993b20b87 100644 --- a/packages/dbt-tools/src/index.ts +++ b/packages/dbt-tools/src/index.ts @@ -147,7 +147,7 @@ async function main() { try { const { create } = await import("./adapter") // Inherited from an offline Altimate Code session (same parse as its kill switches). - const offline = !["", "0", "false"].includes(process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() ?? "") + 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 fbf2f7a653..96ae962e19 100644 --- a/packages/drivers/src/duckdb.ts +++ b/packages/drivers/src/duckdb.ts @@ -113,7 +113,7 @@ export async function connect( const { ms: openTimeoutMs, source: openTimeoutSource } = resolveOpenTimeoutMs(config) // altimate_change end // altimate_change — offline mode never downloads DuckDB extensions - const offline = !["", "0", "false"].includes(process.env.ALTIMATE_OFFLINE?.trim().toLowerCase() ?? "") + 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") diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 75ad09cf90..eca44df70e 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -33,13 +33,17 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } const url = config.connection_string ?? config.url if (url !== undefined) { - let hostname: string + let parsed: URL try { - hostname = new URL(String(url)).hostname + parsed = new URL(String(url)) } catch { throw new Error(DENIED) } - if (!isLoopbackHost(hostname)) 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 (!host.startsWith("/") && !isLoopbackHost(host)) throw new Error(DENIED) } // 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)) diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index cd6074f2b9..86808cf943 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -81,6 +81,6 @@ export async function assertLocalDbt( 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 remote extensions.") + 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/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 4d80d82656..1b3562da2a 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -1,6 +1,8 @@ import { execFile } from "node:child_process" // altimate_change — offline mode import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" +import { existsSync, readdirSync } 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 @@ -82,13 +84,30 @@ export function _resetDbtRuntimeCacheForTests() { cached = undefined } +// altimate_change start — offline mode finds dbt-duckdb in the environment dbt was installed into +function hasDuckdbAdapter(binDir: string | undefined): boolean { + if (!binDir) 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) => existsSync(path.join(lib, python, "site-packages", "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()) return { hasDbt: !resolved.source.startsWith("fallback"), hasDbtDuckdb: false } + if (offlineModeEnabled()) return { hasDbt: !resolved.source.startsWith("fallback"), hasDbtDuckdb: hasDuckdbAdapter(resolved.binDir) } // altimate_change end const env = buildDbtEnv(resolved) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 527f81fc64..080a55e231 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -23,6 +23,12 @@ const CONFIG_NAMES = ["altimate-code.json", "altimate-code.jsonc", "opencode.jso * produce it by substitution, is parsed. Organisation-managed config is applied when the configuration loads. */ export async function optedIn(directory: string): Promise { + if (process.argv.includes("--get-yargs-completions")) return false + // A failure to read config here must not stop a command; the instance applies the setting when it loads. + return findOptIn(directory).catch(() => false) +} + +async function findOptIn(directory: string): Promise { const sets = async (text: string | undefined, source: string | { source: string; dir: string }) => { if (!text || (!text.includes("offline") && !/\{env:|\$\{|\{file:/.test(text))) return false const config = await ConfigPaths.parseText(text, source, "empty", { track: false }).catch(() => undefined) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 4cfaf90b6d..7c7e6840cf 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -601,8 +601,10 @@ export const layer: Layer.Layer< } yield* gitExpect( - // altimate_change — offline mode updates submodules from objects already on disk - ["submodule", "update", "--init", "--recursive", "--force", ...(offlineModeEnabled() ? ["--no-fetch"] : [])], + // altimate_change — offline mode updates checked-out submodules from objects on disk and clones none + offlineModeEnabled() + ? ["submodule", "update", "--recursive", "--force", "--no-fetch"] + : ["submodule", "update", "--init", "--recursive", "--force"], { cwd: worktreePath }, (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), ) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 0f98c3b986..02c54b0d7b 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -32,6 +32,7 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { 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" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -51,6 +52,9 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 17c2609548..1d58b119a1 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -37,6 +37,23 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use }) }) +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"]) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index db875e4c8e..eadb11e5c3 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -85,6 +85,17 @@ describe("Worktree", () => { 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}`]) const previous = process.env.ALTIMATE_OFFLINE process.env.ALTIMATE_OFFLINE = "1" try { diff --git a/packages/opencode/test/skill/discovery.test.ts b/packages/opencode/test/skill/discovery.test.ts index c3ea285232..8765134cb1 100644 --- a/packages/opencode/test/skill/discovery.test.ts +++ b/packages/opencode/test/skill/discovery.test.ts @@ -65,7 +65,7 @@ describe("Discovery.pull", () => { }), ) - // altimate_change start — offline mode leaves the skill cache layout alone + // 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 diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index e7c4f45920..1d16faf1e5 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", () => { @@ -66,5 +67,12 @@ describe("git() utility", () => { 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"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) + expect(gitCommandUsesNetwork(args)).toBe(true) + for (const args of [["submodule", "update", "--recursive", "--no-fetch"], ["lfs", "ls-files"], ["archive", "HEAD"], ["status"], ["remote", "show", "-n", "origin"]]) + expect(gitCommandUsesNetwork(args)).toBe(false) + }) // altimate_change end }) From f628a31b85770b25cba15e0a0c7a4643ac047873 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:09:04 -0800 Subject: [PATCH 51/72] fix: keep offline worktree reset off the network and tool order unchanged - Offline reset skips `submodule update`, which can clone, and sets `GIT_LFS_SKIP_SMUDGE` so checkout downloads no LFS objects. - Every `submodule update`/`add` and `remote add -f` counts as a network Git command. - With offline mode off, the built-in tool order is exactly as before. - dbt-duckdb detection follows the dbt symlink; docs cover explicit `INSTALL`, Jinja profile values and reset limits. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 8 +++---- packages/core/src/git.ts | 3 ++- .../src/altimate/onboarding/tool-detection.ts | 15 ++++++++---- packages/opencode/src/tool/registry.ts | 7 +++--- packages/opencode/src/worktree/index.ts | 23 +++++++++++-------- .../onboarding/tool-detection.test.ts | 9 ++++++++ packages/opencode/test/util/git.test.ts | 4 ++-- 7 files changed, 46 insertions(+), 23 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 70cdf9087e..4a9c7a4ae4 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -183,10 +183,10 @@ While still online: ### What keeps working - Local warehouses: DuckDB and SQLite files, and warehouses reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. A host that is not one of these, or a connection string that cannot be parsed, is refused. -- dbt commands whose selected profile and target are local. 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; it does not download new ones. +- 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` or `[::1]`, including `tool run --daemon`. -- Git diffs, session snapshots and revert, and worktree create, remove and reset (reset uses the locally cached base branch). +- Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and leaves submodules at their current commits. Git LFS files that are not cached stay 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 @@ -208,4 +208,4 @@ Each of these fails with a one-line message or is skipped: 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]` so that local requests do not go through a proxy. -SQL that 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. +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/packages/core/src/git.ts b/packages/core/src/git.ts index d07b660ec4..a421f7cbba 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -21,7 +21,8 @@ export function gitCommandUsesNetwork(args: string[]) { return ( remoteCommands.has(command) || (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) || - (command === "submodule" && operation === "update" && (rest.includes("--init") || !rest.includes("--no-fetch"))) || + (command === "submodule" && ["update", "add"].includes(operation)) || + (command === "remote" && operation === "add" && rest.some((arg) => arg === "-f" || arg === "--fetch")) || (command === "lfs" && ["fetch", "pull", "push", "clone"].includes(operation)) || (command === "archive" && [operation, ...rest].some((arg) => arg?.startsWith("--remote"))) ) diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 1b3562da2a..c009a565ca 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -1,7 +1,7 @@ import { execFile } from "node:child_process" // altimate_change — offline mode import { offlineModeEnabled } from "@opencode-ai/core/flag/flag" -import { existsSync, readdirSync } from "node:fs" +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 @@ -85,8 +85,14 @@ export function _resetDbtRuntimeCacheForTests() { } // altimate_change start — offline mode finds dbt-duckdb in the environment dbt was installed into -function hasDuckdbAdapter(binDir: string | undefined): boolean { - if (!binDir) return false +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) => existsSync(path.join(lib, python, "site-packages", "dbt", "adapters", "duckdb"))) @@ -107,7 +113,8 @@ async function probe(): Promise { // 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()) return { hasDbt: !resolved.source.startsWith("fallback"), hasDbtDuckdb: hasDuckdbAdapter(resolved.binDir) } + if (offlineModeEnabled()) + return { hasDbt: !resolved.source.startsWith("fallback"), hasDbtDuckdb: hasDuckdbAdapter(resolved.path) } // altimate_change end const env = buildDbtEnv(resolved) diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index af54edf7d9..951872821d 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -443,11 +443,12 @@ export namespace ToolRegistry { EditTool, WriteTool, TaskTool, - // altimate_change start — these tools contact remote services - ...(!offline ? [WebFetchTool, WebSearchTool, CodeSearchTool] : []), - // altimate_change end + // altimate_change start — these tools contact remote services; order unchanged with offline mode off + ...(!offline ? [WebFetchTool] : []), TodoWriteTool, // TodoReadTool, + ...(!offline ? [WebSearchTool, CodeSearchTool] : []), + // altimate_change end SkillTool, ApplyPatchTool, ...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [LspTool] : []), diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 7c7e6840cf..e835974e3f 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -176,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, @@ -600,14 +606,13 @@ export const layer: Layer.Layer< }) } - yield* gitExpect( - // altimate_change — offline mode updates checked-out submodules from objects on disk and clones none - offlineModeEnabled() - ? ["submodule", "update", "--recursive", "--force", "--no-fetch"] - : ["submodule", "update", "--init", "--recursive", "--force"], - { cwd: worktreePath }, - (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), - ) + // altimate_change — `submodule update` can clone or fetch, so offline mode leaves submodules at their commits + if (!offlineModeEnabled()) + yield* gitExpect( + ["submodule", "update", "--init", "--recursive", "--force"], + { cwd: worktreePath }, + (r) => new ResetFailedError({ message: r.stderr || r.text || "Failed to update submodules" }), + ) yield* gitExpect( ["submodule", "foreach", "--recursive", "git", "reset", "--hard"], diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index 60546f463a..2c801f9221 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -217,6 +217,15 @@ test.skipIf(process.platform === "win32")("offline detection finds dbt without r _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, "dbt"), path.join(venvBin, "dbt")) + fs.symlinkSync(path.join(venvBin, "dbt"), path.join(dir, "dbt")) + _resetDbtRuntimeCacheForTests() + expect(await detectDbtRuntime({ force: true })).toEqual({ hasDbt: true, hasDbtDuckdb: true }) + expect(fs.existsSync(ran)).toBe(false) } finally { for (const [key, value] of [["ALTIMATE_OFFLINE", previous.offline], ["ALTIMATE_DBT_PATH", previous.dbt]] as const) { if (value === undefined) delete process.env[key] diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index 1d16faf1e5..9fb5d5211d 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -69,9 +69,9 @@ describe("git() utility", () => { }) test("offline treats submodule clones, LFS transfers and remote archives as network commands", () => { - for (const args of [["submodule", "update", "--init"], ["submodule", "update"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) + for (const args of [["submodule", "update", "--init"], ["submodule", "update", "--recursive", "--no-fetch"], ["submodule", "add", "url"], ["remote", "add", "-f", "o", "url"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) expect(gitCommandUsesNetwork(args)).toBe(true) - for (const args of [["submodule", "update", "--recursive", "--no-fetch"], ["lfs", "ls-files"], ["archive", "HEAD"], ["status"], ["remote", "show", "-n", "origin"]]) + 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) }) // altimate_change end From 8d460fc0988531648a324e217c635f1df0da3a05 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:17:20 -0800 Subject: [PATCH 52/72] fix: narrow offline checks to the cases they can judge - Only host-addressed warehouse types pass the loopback check; Snowflake, BigQuery, Databricks and similar are refused. - dbt-duckdb attachments other than DuckDB or SQLite files are refused. - The fetch guard follows redirects only while they stay local and accepts `0.0.0.0`, so a TUI bound there reaches its server. - `remote prune` and `remote set-head --auto` count as network Git commands; dbt-duckdb detection also checks `dist-packages`. - The worktree test now covers the skipped submodule clone. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 6 +++--- packages/core/src/git.ts | 1 + .../altimate/native/connections/offline.ts | 8 ++++++- .../src/altimate/native/dbt/offline.ts | 3 +++ .../src/altimate/onboarding/tool-detection.ts | 4 +++- packages/opencode/src/config/offline.ts | 21 +++++++++++++------ packages/opencode/src/mcp/index.ts | 2 +- .../native/offline-connections.test.ts | 4 ++++ packages/opencode/test/cli/mcp-add.test.ts | 2 +- .../opencode/test/cli/run/offline.test.ts | 2 +- packages/opencode/test/mcp/offline.test.ts | 15 ++++++++++--- .../opencode/test/project/worktree.test.ts | 8 +++++++ packages/opencode/test/util/git.test.ts | 2 +- 13 files changed, 60 insertions(+), 18 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 4a9c7a4ae4..9c00618d07 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -182,10 +182,10 @@ While still online: ### What keeps working -- Local warehouses: DuckDB and SQLite files, and warehouses reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. A host that is not one of these, or a connection string that cannot be parsed, is refused. +- Local warehouses: DuckDB and SQLite files, and Postgres, MySQL, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. Other hosts, connection strings that cannot be parsed, 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` or `[::1]`, including `tool run --daemon`. +- 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 leaves submodules at their current commits. Git LFS files that are not cached stay 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. @@ -206,6 +206,6 @@ Each of these fails with a one-line message or is skipped: ### 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]` so that local requests do not go through a proxy. +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. 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/packages/core/src/git.ts b/packages/core/src/git.ts index a421f7cbba..c1baa0138d 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -23,6 +23,7 @@ export function gitCommandUsesNetwork(args: string[]) { (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"))) ) diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index eca44df70e..c9c793d3ba 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -21,7 +21,9 @@ export function assertLocalConnection(raw: ConnectionConfig): void { if (!isLocalPath(config.path)) throw new Error(DENIED) return } - if (config.ssh_host) throw new Error(DENIED) + // 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.ssh_host) 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) @@ -50,4 +52,8 @@ export function assertLocalConnection(raw: ConnectionConfig): void { 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"]) diff --git a/packages/opencode/src/altimate/native/dbt/offline.ts b/packages/opencode/src/altimate/native/dbt/offline.ts index 86808cf943..c05d886e67 100644 --- a/packages/opencode/src/altimate/native/dbt/offline.ts +++ b/packages/opencode/src/altimate/native/dbt/offline.ts @@ -42,6 +42,9 @@ function remoteDuckdbSetting(output: Record) { 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) ) diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index c009a565ca..0c4b2c5bb2 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -95,7 +95,9 @@ function hasDuckdbAdapter(dbtPath: string): boolean { } 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) => existsSync(path.join(lib, python, "site-packages", "dbt", "adapters", "duckdb"))) + return pythons.some((python) => + ["site-packages", "dist-packages"].some((dir) => existsSync(path.join(lib, python, dir, "dbt", "adapters", "duckdb"))), + ) } function readdirSafe(dir: string): string[] { diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 080a55e231..7722ff5893 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -66,7 +66,8 @@ async function findOptIn(directory: string): Promise { } /** 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]"] +const LOCAL_FETCH_HOSTS = ["localhost", "127.0.0.1", "[::1]", "0.0.0.0"] +const MAX_LOCAL_REDIRECTS = 5 let networkFetch: typeof fetch | undefined @@ -90,10 +91,18 @@ export function start() { networkFetch = globalThis.fetch globalThis.fetch = Object.assign( async (input: Parameters[0], init?: Parameters[1]) => { - if (!isLocalURL(input instanceof Request ? input.url : input.toString())) - throw new Error("Offline mode allows network requests only to the configured model endpoint.") - // A local endpoint must not redirect to a remote host. - return networkFetch!(input, { ...init, redirect: "error" }) + 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.") + // Follow redirects only while they stay on this machine. + let response = await networkFetch!(input, { ...init, redirect: "manual" }) + for (let hop = 0; hop < MAX_LOCAL_REDIRECTS && response.status >= 300 && response.status < 400; hop++) { + const location = response.headers.get("location") + if (!location) return response + url = new URL(location, url).href + if (!isLocalURL(url)) throw new Error("Offline mode blocked a redirect away from this machine.") + response = await networkFetch!(url, { ...init, redirect: "manual" }) + } + return response }, { preconnect: () => {} }, ) @@ -151,7 +160,7 @@ export function isLocalURL(value: string | URL) { 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 at localhost, 127.0.0.1 or [::1].") + 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).") } export * as Offline from "./offline" diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index f7d82dc034..e2a1d99e1c 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -427,7 +427,7 @@ export const layer = Layer.effect( 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 at localhost, 127.0.0.1 or [::1]." }, + 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, } } diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 02c54b0d7b..b12caefa57 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -49,6 +49,9 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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" }, @@ -69,6 +72,7 @@ test("dbt-duckdb settings are refused only when they point at something remote", "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", diff --git a/packages/opencode/test/cli/mcp-add.test.ts b/packages/opencode/test/cli/mcp-add.test.ts index 5aaf2aaa6e..e4bcfa33ba 100644 --- a/packages/opencode/test/cli/mcp-add.test.ts +++ b/packages/opencode/test/cli/mcp-add.test.ts @@ -164,7 +164,7 @@ test("offline MCP add refuses remote configuration before writing it", () => { 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("localhost, 127.0.0.1 or [::1]") + expect(`${result.stdout}${result.stderr}`).toContain("ones on this machine") expect(readJson(configPath).mcp).toEqual({}) }, true) }, 30_000) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 5ddcd3d91c..320ff5a78f 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -278,7 +278,7 @@ test("offline model can execute a local bash command", async () => { ]) 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]|${PROXY}|1` }) + 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 }) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 1d58b119a1..d6058fa977 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -17,12 +17,19 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use 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: () => new Response("local") }) + 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) + 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 remote = await fetch("https://example.com/").then(() => "sent", (error) => error.message) server.stop(true) - console.log(JSON.stringify({ local, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_PROXY, process.env.NO_PROXY] }))` + console.log(JSON.stringify({ local, followed, away, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_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" }, stdout: "pipe", @@ -32,8 +39,10 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use 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.", remote: "Offline mode allows network requests only to the configured model endpoint.", - env: ["1", "http://proxy.example:3128", "corp.example,localhost,127.0.0.1,[::1]"], + env: ["1", "http://proxy.example:3128", "corp.example,localhost,127.0.0.1,[::1],0.0.0.0"], }) }) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index eadb11e5c3..10a8fb710c 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -96,6 +96,14 @@ describe("Worktree", () => { 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, "..", `${path.basename(directory)}-lib`) + Bun.spawnSync(["git", "init", "-q", lib]) + Bun.spawnSync(["git", "-C", lib, "-c", "user.email=t@example.com", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "lib"]) + run(["-c", "protocol.file.allow=always", "submodule", "add", "-q", lib, "lib"]) + run(["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false", "commit", "-q", "-m", "add submodule"]) + run(["update-ref", `refs/remotes/origin/${branch}`, "HEAD"]) + Bun.spawnSync(["rm", "-rf", lib]) const previous = process.env.ALTIMATE_OFFLINE process.env.ALTIMATE_OFFLINE = "1" try { diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index 9fb5d5211d..5487f0535b 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -69,7 +69,7 @@ describe("git() utility", () => { }) 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"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) + for (const args of [["submodule", "update", "--init"], ["submodule", "update", "--recursive", "--no-fetch"], ["submodule", "add", "url"], ["remote", "add", "-f", "o", "url"], ["remote", "prune", "origin"], ["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) From 935f5ddf125dc26cf3eb612395998e98334b22a7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:25:59 -0800 Subject: [PATCH 53/72] fix: keep caller redirect choices in the offline fetch guard - The guard follows local redirects only for plain follow requests; a `Request` or an explicit `manual`/`error` keeps its own semantics, and too many hops is an error. - Docs list the network use offline mode does not check: partial-clone object fetches, cloud sign-in on a local warehouse, and requests set up before a late opt-in. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 6 ++++++ packages/opencode/src/config/offline.ts | 8 ++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 9c00618d07..429cfd4274 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -208,4 +208,10 @@ Each of these fails with a one-line message or is skipped: 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`. +- Cloud sign-in configured on a local warehouse (for example SQL Server `authentication: azure-active-directory-*` or MongoDB `authMechanism=MONGODB-AWS`) contacts its identity provider. +- When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), requests that were already set up are not guarded. Set `ALTIMATE_OFFLINE=1` before starting a server. + 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/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 7722ff5893..6c7c73399c 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -93,11 +93,15 @@ export function start() { 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.") - // Follow redirects only while they stay on this machine. + // A Request carries its own method and body, and a caller may ask not to follow: refuse redirects then. + const follow = !(input instanceof Request) && (init?.redirect ?? "follow") === "follow" + if (!follow) return networkFetch!(input, { ...init, redirect: init?.redirect === "manual" ? "manual" : "error" }) + // Otherwise follow redirects only while they stay on this machine. let response = await networkFetch!(input, { ...init, redirect: "manual" }) - for (let hop = 0; hop < MAX_LOCAL_REDIRECTS && response.status >= 300 && response.status < 400; hop++) { + for (let hop = 0; response.status >= 300 && response.status < 400; 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.") url = new URL(location, url).href if (!isLocalURL(url)) throw new Error("Offline mode blocked a redirect away from this machine.") response = await networkFetch!(url, { ...init, redirect: "manual" }) From 5d1dda4f4519c2acf4d59715fbfe81e4e5ea2719 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:33:42 -0800 Subject: [PATCH 54/72] fix: find dbt on the current PATH in offline data tool detection Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/tools/project-scan.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/tools/project-scan.ts b/packages/opencode/src/altimate/tools/project-scan.ts index 595d3695d1..b0667c3b49 100644 --- a/packages/opencode/src/altimate/tools/project-scan.ts +++ b/packages/opencode/src/altimate/tools/project-scan.ts @@ -487,7 +487,7 @@ export async function detectDataTools(skip: boolean): Promise { 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) !== null } + 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 { From d61a6e0b1aadccc090add7e3411c16b3fd725b28 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:35:30 -0800 Subject: [PATCH 55/72] fix: match fetch redirect rules in the offline guard and refine git and host checks - The guard honours a `Request`'s own redirect setting and switches to GET on 303 (and on 301/302 after POST), as fetch does. - Git options before the operation (`submodule --quiet update`) no longer hide a network command. - Trino and Oracle without a host default to localhost and pass; docs note Oracle Easy Connect strings need `host`, and that a late opt-in leaves shared HTTP client requests unguarded. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 4 ++-- packages/core/src/git.ts | 6 +++++- .../src/altimate/native/connections/offline.ts | 2 +- packages/opencode/src/config/offline.ts | 17 +++++++++++------ packages/opencode/test/mcp/offline.test.ts | 8 +++++++- packages/opencode/test/util/git.test.ts | 2 +- 6 files changed, 27 insertions(+), 12 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 429cfd4274..5de8b60398 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -182,7 +182,7 @@ While still online: ### What keeps working -- Local warehouses: DuckDB and SQLite files, and Postgres, MySQL, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. Other hosts, connection strings that cannot be parsed, and account-addressed warehouses such as Snowflake, BigQuery and Databricks are refused. +- Local warehouses: DuckDB and SQLite files, and Postgres, MySQL, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. 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`. @@ -212,6 +212,6 @@ Some network use happens inside programs Altimate Code starts and is not checked - Git in a partial (blobless or treeless) clone fetches missing objects on demand, even for local commands such as `diff`. - Cloud sign-in configured on a local warehouse (for example SQL Server `authentication: azure-active-directory-*` or MongoDB `authMechanism=MONGODB-AWS`) contacts its identity provider. -- When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), requests that were already set up are not guarded. Set `ALTIMATE_OFFLINE=1` before starting a server. +- When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), internal HTTP requests made through the shared HTTP client stay unguarded for the rest of that process. Set `ALTIMATE_OFFLINE=1` before starting a server. 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/packages/core/src/git.ts b/packages/core/src/git.ts index c1baa0138d..d64c430da7 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -17,7 +17,11 @@ export function gitCommandUsesNetwork(args: string[]) { while (args[index]?.startsWith("-")) { index += ["-c", "-C", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(args[index]) ? 2 : 1 } - const [command, operation, ...rest] = args.slice(index) + 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)] return ( remoteCommands.has(command) || (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) || diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index c9c793d3ba..8287f70a37 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -56,4 +56,4 @@ 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"]) +const LOCALHOST_BY_DEFAULT = new Set(["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "clickhouse", "mongodb", "mongo", "trino", "oracle"]) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 6c7c73399c..da51549a31 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -93,18 +93,23 @@ export function start() { 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.") - // A Request carries its own method and body, and a caller may ask not to follow: refuse redirects then. - const follow = !(input instanceof Request) && (init?.redirect ?? "follow") === "follow" - if (!follow) return networkFetch!(input, { ...init, redirect: init?.redirect === "manual" ? "manual" : "error" }) - // Otherwise follow redirects only while they stay on this machine. - let response = await networkFetch!(input, { ...init, redirect: "manual" }) + 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; response.status >= 300 && response.status < 400; 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.") url = new URL(location, url).href if (!isLocalURL(url)) throw new Error("Offline mode blocked a redirect away from this machine.") - response = await networkFetch!(url, { ...init, redirect: "manual" }) + const method = (request.method ?? "GET").toUpperCase() + if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === "POST")) + request = { ...request, method: method === "HEAD" ? "HEAD" : "GET", body: undefined } + response = await networkFetch!(url, request) } return response }, diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index d6058fa977..363733394a 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -21,15 +21,19 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use 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) 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" })).text() + 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, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_PROXY, process.env.NO_PROXY] }))` + console.log(JSON.stringify({ local, followed, away, seeOther, manual, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_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" }, stdout: "pipe", @@ -41,6 +45,8 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use local: "local", followed: "local", away: "Offline mode blocked a redirect away from this machine.", + seeOther: "GET", + manual: 307, remote: "Offline mode allows network requests only to the configured model endpoint.", env: ["1", "http://proxy.example:3128", "corp.example,localhost,127.0.0.1,[::1],0.0.0.0"], }) diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index 5487f0535b..c146d3a87d 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -69,7 +69,7 @@ describe("git() utility", () => { }) 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"], ["remote", "set-head", "origin", "--auto"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) + 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"], ["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) From ceeada43aca6253d91959882928d60b8c1acec48 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:42:05 -0800 Subject: [PATCH 56/72] fix: follow only real redirects and drop credentials across origins in the offline guard - Only 301, 302, 303, 307 and 308 are followed; `Authorization` is not sent to a different local origin. - `NO_PROXY` and `no_proxy` get the same list, so the user's exclusions survive in either spelling. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/config/offline.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index da51549a31..9f7455fc9f 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -82,11 +82,11 @@ export function start() { 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. - for (const key of ["NO_PROXY", "no_proxy"]) { - const current = process.env[key] - if (current === "*") continue - const entries = (current ?? "").split(",").map((entry) => entry.trim()).filter(Boolean) - process.env[key] = [...entries, ...LOCAL_FETCH_HOSTS.filter((host) => !entries.includes(host))].join(",") + // Both spellings get the same list, so programs that read either one keep the user's own exclusions. + const user = process.env.NO_PROXY ?? process.env.no_proxy + if (user !== "*") { + const entries = (user ?? "").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( @@ -100,12 +100,19 @@ export function start() { // 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; response.status >= 300 && response.status < 400; hop++) { + 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.") - url = new URL(location, url).href - if (!isLocalURL(url)) throw new Error("Offline mode blocked a redirect away from this machine.") + 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) + headers.delete("authorization") + request = { ...request, headers } + } + url = next.href const method = (request.method ?? "GET").toUpperCase() if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === "POST")) request = { ...request, method: method === "HEAD" ? "HEAD" : "GET", body: undefined } From 612e151c883c38516ebd3a58f45332087d20ae4a Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:45:33 -0800 Subject: [PATCH 57/72] fix: catch an escaped offline key at startup and correct offline docs - The startup check parses config text that could spell the key with a JSON escape. - Docs: worktree LFS files stay pointers; legacy TOML applies late; libpq env vars and LFS checkouts are not checked. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 7 ++++--- packages/opencode/src/config/offline.ts | 3 ++- packages/opencode/test/mcp/offline.test.ts | 13 +++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 5de8b60398..fbe28c318a 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ With offline mode off, nothing on this page applies and Altimate Code behaves ex ### Turn it on -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. Organisation-managed configuration and remote (well-known) configuration apply the setting only once they load, after some startup requests; use `ALTIMATE_OFFLINE=1` there. Any one of these sources turns it on; a value of `false` elsewhere does not turn it back off. `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. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. Organisation-managed configuration, remote (well-known) configuration and the legacy TOML `config` file apply the setting only once they load, after some startup requests; use `ALTIMATE_OFFLINE=1` there. Any one of these sources turns it on; a value of `false` elsewhere does not turn it back off. `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`. @@ -186,7 +186,7 @@ While still online: - 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 leaves submodules at their current commits. Git LFS files that are not cached stay as pointer files. +- Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and leaves submodules at their current commits. 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 @@ -210,7 +210,8 @@ Programs you run or configure yourself keep their own network access and proxy s 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`. +- 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. - Cloud sign-in configured on a local warehouse (for example SQL Server `authentication: azure-active-directory-*` or MongoDB `authMechanism=MONGODB-AWS`) contacts its identity provider. - When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), internal HTTP requests made through the shared HTTP client stay unguarded for the rest of that process. Set `ALTIMATE_OFFLINE=1` before starting a server. diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 9f7455fc9f..a8e6eb6fe0 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -30,7 +30,8 @@ export async function optedIn(directory: string): Promise { async function findOptIn(directory: string): Promise { const sets = async (text: string | undefined, source: string | { source: string; dir: string }) => { - if (!text || (!text.includes("offline") && !/\{env:|\$\{|\{file:/.test(text))) return false + // 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 } diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 363733394a..5a19ef22e4 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -76,3 +76,16 @@ test("model fetch stays below the configured base URL", async () => { 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 }) + } +}) From c5fb862e43bfdef54745cd932e3f78a080ef9abb Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:48:12 -0800 Subject: [PATCH 58/72] fix: merge both proxy exclusion lists and strip redirect headers like fetch - `NO_PROXY` and `no_proxy` entries are merged, not one replacing the other. - Cross-origin hops drop `Cookie` and `Proxy-Authorization` too; a redirect to GET drops body headers. - Tests cover credential stripping, the hop cap and both proxy spellings; docs note the LAN `--hostname` TUI limit. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 1 + packages/opencode/src/config/offline.ts | 15 +++++++++------ packages/opencode/test/mcp/offline.test.ts | 19 +++++++++++++------ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index fbe28c318a..b415d7e3fb 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -213,6 +213,7 @@ Some network use happens inside programs Altimate Code starts and is not checked - 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. - Cloud sign-in configured on a local warehouse (for example SQL Server `authentication: azure-active-directory-*` or MongoDB `authMechanism=MONGODB-AWS`) contacts its identity provider. +- 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`. - When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), internal HTTP requests made through the shared HTTP client stay unguarded for the rest of that process. Set `ALTIMATE_OFFLINE=1` before starting a server. 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/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index a8e6eb6fe0..84b3e87c49 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -84,9 +84,9 @@ export function start() { // 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 user = process.env.NO_PROXY ?? process.env.no_proxy - if (user !== "*") { - const entries = (user ?? "").split(",").map((entry) => entry.trim()).filter(Boolean) + const lists = [process.env.NO_PROXY, process.env.no_proxy] + if (!lists.includes("*")) { + 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 @@ -110,13 +110,16 @@ export function start() { // Like fetch, do not send credentials on to a different origin. if (next.origin !== new URL(url).origin) { const headers = new Headers(request.headers) - headers.delete("authorization") + 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")) - request = { ...request, method: method === "HEAD" ? "HEAD" : "GET", body: undefined } + 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 diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 5a19ef22e4..01848bb836 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -22,20 +22,25 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use 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) + 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" })).text() + 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, remote, env: [process.env.ALTIMATE_OFFLINE, process.env.HTTPS_PROXY, process.env.NO_PROXY] }))` + 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" }, + 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", }) @@ -45,10 +50,12 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use local: "local", followed: "local", away: "Offline mode blocked a redirect away from this machine.", - seeOther: "GET", + 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,localhost,127.0.0.1,[::1],0.0.0.0"], + 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"], }) }) From cc57dd54f835921eb434480ee1b98450897a4bdf Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 10:55:14 -0800 Subject: [PATCH 59/72] docs: note remote skill URLs are unavailable offline; fold nested markers Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 1 + packages/opencode/src/cli/tui/worker.ts | 2 +- packages/opencode/src/config/config.ts | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index b415d7e3fb..737813c663 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -198,6 +198,7 @@ Each of these fails with a one-line message or is skipped: - 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, and cloud sign-in methods for dbt; - `dbt deps` and dbt's usage reporting and version check; diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 0161d4de67..99545e7c43 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -45,7 +45,7 @@ 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() -// altimate_change — the worker inherits offline mode from its parent; install the fetch guard here too +// 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 diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 6c15dd1412..82d72b6140 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -782,7 +782,7 @@ 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. - // altimate_change — managed config can turn offline mode on too + // Managed config can turn offline mode on too. if (result.offline === true) Offline.start() const deps: Fiber.Fiber[] = [] for (const dir of directories) { From f88a960a0154109b46cf3eed2756efa0d69ca944 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:02:55 -0800 Subject: [PATCH 60/72] fix: close cubic findings on offline host, git, submodule and dbt handling - Refuse UNC `file:` paths, comma host lists, non-Postgres socket hosts, Mongo SRV/replica sets and cloud sign-in; accept SQL Server named instances and hostless Redshift. - Offline reset moves checked-out submodules from local objects; `submodule foreach git fetch` counts as network. - A dbt offline refusal surfaces instead of running elsewhere; MCP OAuth refuses offline; `run --attach --dir` is remote. - Docs, markers and tests updated. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 7 ++--- packages/core/src/git.ts | 1 + packages/drivers/src/duckdb.ts | 2 +- .../opencode/src/altimate/debug/collect.ts | 4 ++- .../altimate/native/connections/offline.ts | 28 ++++++++++++++----- .../altimate/native/connections/register.ts | 9 ++++-- .../src/altimate/onboarding/tool-detection.ts | 5 +++- packages/opencode/src/index.ts | 4 +-- packages/opencode/src/mcp/index.ts | 3 ++ packages/opencode/src/session/prompt.ts | 5 ++-- packages/opencode/src/share/share-next.ts | 6 ++-- packages/opencode/src/tool/registry.ts | 3 +- packages/opencode/src/worktree/index.ts | 17 +++++++++-- .../native/offline-connections.test.ts | 10 +++++++ .../onboarding/tool-detection.test.ts | 10 ++++--- packages/opencode/test/cli/mcp-add.test.ts | 2 +- .../opencode/test/cli/run/offline.test.ts | 1 + packages/opencode/test/util/git.test.ts | 2 +- 18 files changed, 85 insertions(+), 34 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 737813c663..8df04a17b0 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -162,9 +162,9 @@ Control how context is managed when conversations grow long: ## 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. Local work keeps running: tools, shell commands, local databases, language servers, local MCP servers and local Git. +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 on this page applies and Altimate Code behaves exactly as before. +With offline mode off, nothing in this section applies and Altimate Code behaves exactly as before. ### Turn it on @@ -200,7 +200,7 @@ Each of these fails with a one-line message or is skipped: - 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, and cloud sign-in methods for dbt; +- warehouse connections to other hosts, SSH tunnels, MongoDB SRV and replica-set discovery, and cloud sign-in (SQL Server Azure AD, 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. @@ -213,7 +213,6 @@ Some network use happens inside programs Altimate Code starts and is not checked - 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. -- Cloud sign-in configured on a local warehouse (for example SQL Server `authentication: azure-active-directory-*` or MongoDB `authMechanism=MONGODB-AWS`) contacts its identity provider. - 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`. - When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), internal HTTP requests made through the shared HTTP client stay unguarded for the rest of that process. Set `ALTIMATE_OFFLINE=1` before starting a server. diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index d64c430da7..299461f5c5 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -26,6 +26,7 @@ export function gitCommandUsesNetwork(args: string[]) { remoteCommands.has(command) || (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) || (command === "submodule" && ["update", "add"].includes(operation)) || + (command === "submodule" && operation === "foreach" && rest.some((arg) => /\b(fetch|pull|push|clone|ls-remote)\b/.test(arg))) || (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)) || diff --git a/packages/drivers/src/duckdb.ts b/packages/drivers/src/duckdb.ts index 96ae962e19..4f3a0367b4 100644 --- a/packages/drivers/src/duckdb.ts +++ b/packages/drivers/src/duckdb.ts @@ -112,7 +112,7 @@ export async function connect( // altimate_change start — configurable open budget const { ms: openTimeoutMs, source: openTimeoutSource } = resolveOpenTimeoutMs(config) // altimate_change end - // altimate_change — offline mode never downloads DuckDB extensions + // 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 diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index ffcb8b1b19..611c496b94 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -414,7 +414,9 @@ export async function collect(opts: { network: boolean }): Promise { 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/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 8287f70a37..ca67ddc280 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -8,7 +8,9 @@ const DENIED = "Offline mode allows only local file databases and warehouses at export function isLocalPath(value: unknown): boolean { if (typeof value !== "string" || /\{[{%#]/.test(value) || /^(?:\\\\|\/\/)/.test(value)) return false if (value === "" || value === ":memory:") return true - if (/^file:/i.test(value)) return URL.canParse(value) && ["", "localhost"].includes(new URL(value).hostname) + // file:////server/share is a UNC path written as a URL. + if (/^file:/i.test(value)) + return URL.canParse(value) && ["", "localhost"].includes(new URL(value).hostname) && !decodeURIComponent(new URL(value).pathname).startsWith("//") // Rejects scheme:// URLs (s3, gcs, http and so on) and DuckDB's non-slash remote schemes such as md:. return isLocalFilePath(value) } @@ -23,14 +25,21 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } // 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.ssh_host) throw new Error(DENIED) + if (!HOST_ADDRESSED.has(type) || config.ssh_host || config.replica_set) throw new Error(DENIED) + // Cloud sign-in contacts an identity provider even for a loopback host. + if (typeof config.authentication === "string" && /^azure-active-directory/i.test(config.authentication)) + 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) - // Postgres accepts a socket directory as its host. + 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 host of hosts) { - if (typeof host === "string" && host.startsWith("/")) continue + 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 @@ -41,11 +50,16 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } catch { throw new Error(DENIED) } + // mongodb+srv:// and replica sets discover other hosts. + if (parsed.protocol.endsWith("+srv:") || [...parsed.searchParams.keys()].some((key) => key.toLowerCase() === "replicaset")) + throw new Error(DENIED) + 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 (!host.startsWith("/") && !isLoopbackHost(host)) throw new Error(DENIED) + if (!socketDir(host) && !isLoopbackHost(host)) throw new Error(DENIED) } // 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)) @@ -56,4 +70,4 @@ 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", "oracle"]) +const LOCALHOST_BY_DEFAULT = new Set(["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "clickhouse", "mongodb", "mongo", "trino", "oracle", "redshift"]) diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 6b917a68ad..18337dc987 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -1,6 +1,8 @@ // 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. @@ -128,7 +130,6 @@ async function ensureDbtAdapter(): Promise { return publish(null) } - // Offline, a profile that leaves this machine falls back to the native driver, which checks its own target. // 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) @@ -147,7 +148,9 @@ async function ensureDbtAdapter(): Promise { await create(dbtConfig, { ...options, ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}) }), dbtConfig.projectRoot, ) - } catch { + } 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 { @@ -303,7 +306,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/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index 0c4b2c5bb2..c7ac8bed08 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -116,7 +116,10 @@ async function probe(): Promise { const resolved = resolveDbt() // altimate_change start — `dbt --version` asks PyPI for the latest release, so offline mode does not run it if (offlineModeEnabled()) - return { hasDbt: !resolved.source.startsWith("fallback"), hasDbtDuckdb: hasDuckdbAdapter(resolved.path) } + return { + hasDbt: !resolved.source.startsWith("fallback") || Bun.which("dbt", { PATH: process.env.PATH ?? "" }) !== null, + hasDbtDuckdb: hasDuckdbAdapter(resolved.path), + } // altimate_change end const env = buildDbtEnv(resolved) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index d746ed9b67..5f7908a0da 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -174,8 +174,8 @@ let cli = yargs(args) // altimate_change start — offline mode: install the fetch guard and refuse commands that need a remote service const command = String(opts._[0] ?? "") - // `attach --dir` names a directory on the server, so attach reads the invoking project's setting. - const offlineTarget = command === "attach" ? undefined : (opts.dir ?? opts.cwd ?? opts.directory) + // `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() diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index e2a1d99e1c..8ddaf19608 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -1387,6 +1387,9 @@ export const layer = Layer.effect( }) const beginAuth = Effect.fn("MCP.beginAuth")(function* (mcpName: string, token: number) { + // altimate_change start — offline mode refuses before starting an OAuth flow + if (Offline.enabled()) throw new Error("Authenticate MCP servers while online.") + // altimate_change end const lifecycle = yield* InstanceState.get(state) // altimate_change end const mcpConfig = yield* requireMcpConfig(mcpName) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 210ee9a87b..910efb008e 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -482,8 +482,9 @@ export namespace SessionPrompt { if (Offline.enabled()) { const dir = Instance.directory if (existsSync(path.join(dir, ".altimate-code", "skill", "_workspace"))) await refreshSkillRegistry(dir) - } else if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { - // altimate_change end + } else + // altimate_change end + if (CoreFlag.ALTIMATE_DISABLE_WORKSPACE) { const dir = Instance.directory // Mirrors `MANAGED_DIR` in ./altimate/workspace/skill-sync. Inlined // rather than imported so the opted-out path stays free of that module. diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index 366f8eb328..a0793557f4 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -78,8 +78,9 @@ export namespace ShareNext { const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1" export async function init() { - // altimate_change — offline mode does not sync shared sessions + // 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, [ { @@ -208,8 +209,9 @@ export namespace ShareNext { const queue = new Map }>() async function sync(sessionID: SessionID, data: Data[]) { - // altimate_change — offline mode does not sync shared sessions + // 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 951872821d..ec0fc54f17 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -443,12 +443,11 @@ export namespace ToolRegistry { EditTool, WriteTool, TaskTool, - // altimate_change start — these tools contact remote services; order unchanged with offline mode off + // These tools contact remote services; order unchanged with offline mode off. ...(!offline ? [WebFetchTool] : []), TodoWriteTool, // TodoReadTool, ...(!offline ? [WebSearchTool, CodeSearchTool] : []), - // altimate_change end SkillTool, ApplyPatchTool, ...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [LspTool] : []), diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index e835974e3f..469906ef73 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -606,13 +606,24 @@ export const layer: Layer.Layer< }) } - // altimate_change — `submodule update` can clone or fetch, so offline mode leaves submodules at their commits - if (!offlineModeEnabled()) + // altimate_change start — offline mode moves only checked-out submodules, from objects already on disk + // (`submodule update` would clone the others). `submodule status` marks a not-checked-out one with "-". + const checkedOut = offlineModeEnabled() + ? (yield* git(["submodule", "status", "--recursive"], { cwd: worktreePath })).text + .split("\n") + .filter((line) => line.length > 1 && !line.startsWith("-")) + .map((line) => line.slice(1).split(" ")[1]) + .filter((entry): entry is string => Boolean(entry)) + : undefined + if (!checkedOut || checkedOut.length > 0) yield* gitExpect( - ["submodule", "update", "--init", "--recursive", "--force"], + 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/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index b12caefa57..afc3963ef1 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -33,6 +33,8 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { 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" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -58,6 +60,14 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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: "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: "mongodb", connection_string: "mongodb://localhost/db?authMechanism=MONGODB-AWS" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index 2c801f9221..c01c5ae337 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -211,8 +211,10 @@ test.skipIf(process.platform === "win32")("offline detection finds dbt without r const previous = { offline: process.env.ALTIMATE_OFFLINE, dbt: process.env.ALTIMATE_DBT_PATH } try { const ran = path.join(dir, "ran") - fs.writeFileSync(path.join(dir, "dbt"), `#!/bin/sh\ntouch "${ran}"\n`, { mode: 0o755 }) - process.env.ALTIMATE_DBT_PATH = path.join(dir, "dbt") + // 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 }) @@ -221,8 +223,8 @@ test.skipIf(process.platform === "win32")("offline detection finds dbt without r 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, "dbt"), path.join(venvBin, "dbt")) - fs.symlinkSync(path.join(venvBin, "dbt"), path.join(dir, "dbt")) + 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) diff --git a/packages/opencode/test/cli/mcp-add.test.ts b/packages/opencode/test/cli/mcp-add.test.ts index e4bcfa33ba..f3e8b6ef63 100644 --- a/packages/opencode/test/cli/mcp-add.test.ts +++ b/packages/opencode/test/cli/mcp-add.test.ts @@ -165,7 +165,7 @@ test("offline MCP add refuses remote configuration before writing it", () => { 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).mcp).toEqual({}) + expect(readJson(configPath)).toMatchObject({ mcp: {}, username: "unchanged" }) }, true) }, 30_000) diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 320ff5a78f..1585ddf296 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -23,6 +23,7 @@ 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") diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index c146d3a87d..14178f2295 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -69,7 +69,7 @@ describe("git() utility", () => { }) 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"], ["remote", "-v", "update"], ["remote", "set-head", "origin", "--auto"], ["lfs", "fetch"], ["lfs", "pull"], ["archive", "--remote=origin", "HEAD"], ["-C", "x", "fetch"]]) + 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) From 1b3a0bdd367a3a27bf707348890110345b7d33c7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:06:52 -0800 Subject: [PATCH 61/72] fix: refuse SSH tunnels for file databases and non-HTTP Trino/ClickHouse protocols offline - `ssh_host` is refused for every type, `protocol` must be http/https, and explicit Mongo topology discovery is refused. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/native/connections/offline.ts | 10 ++++++++-- .../test/altimate/native/offline-connections.test.ts | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index ca67ddc280..9b9bf01743 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -19,13 +19,18 @@ export function isLocalPath(value: unknown): boolean { export function assertLocalConnection(raw: ConnectionConfig): void { const config = normalizeConfig(raw) const type = String(config.type).toLowerCase() + // 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.ssh_host || config.replica_set) throw new Error(DENIED) + if (!HOST_ADDRESSED.has(type) || config.replica_set || config.direct_connection === false) throw new Error(DENIED) + // Trino and ClickHouse build `${protocol}://${host}`, so a protocol value could carry its own authority. + if (config.protocol !== undefined && !["http", "https"].includes(String(config.protocol).trim().toLowerCase())) + throw new Error(DENIED) // Cloud sign-in contacts an identity provider even for a loopback host. if (typeof config.authentication === "string" && /^azure-active-directory/i.test(config.authentication)) throw new Error(DENIED) @@ -51,7 +56,8 @@ export function assertLocalConnection(raw: ConnectionConfig): void { throw new Error(DENIED) } // mongodb+srv:// and replica sets discover other hosts. - if (parsed.protocol.endsWith("+srv:") || [...parsed.searchParams.keys()].some((key) => key.toLowerCase() === "replicaset")) + const param = (name: string) => [...parsed.searchParams].find(([key]) => key.toLowerCase() === name)?.[1] + if (parsed.protocol.endsWith("+srv:") || param("replicaset") !== undefined || param("directconnection") === "false") throw new Error(DENIED) const mechanism = [...parsed.searchParams].find(([key]) => key.toLowerCase() === "authmechanism")?.[1]?.toUpperCase() if (mechanism && ["MONGODB-AWS", "MONGODB-OIDC", "GSSAPI"].includes(mechanism)) throw new Error(DENIED) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index afc3963ef1..c7a5c24418 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -35,6 +35,7 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { 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" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -68,6 +69,10 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { type: "sqlserver", host: "db.example.com\\SQLEXPRESS" }, { type: "sqlserver", host: "localhost", authentication: "azure-active-directory-default" }, { 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 }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) From 362f7a422a076536f6ca252455b88db3845e4a52 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:09:28 -0800 Subject: [PATCH 62/72] fix: allow only local SQL Server sign-in offline and parse submodule paths safely - SQL Server `authentication` must be SQL or Windows login; short Azure AD forms (cli, default, msi) are refused. - Offline reset updates checked-out top-level submodules and keeps paths with spaces whole. Co-Authored-By: Claude Opus 5.5 --- docs/docs/configure/config.md | 4 ++-- .../opencode/src/altimate/native/connections/offline.ts | 9 +++++++-- packages/opencode/src/worktree/index.ts | 9 +++++---- .../test/altimate/native/offline-connections.test.ts | 3 +++ 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 8df04a17b0..271186a7e8 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -186,7 +186,7 @@ While still online: - 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 leaves submodules at their current commits. Worktree create and reset leave Git LFS files as pointer files. +- Git diffs, session snapshots and revert, and worktree create, remove and reset. Reset uses the locally cached base branch and updates checked-out submodules from local objects; nested and not-checked-out submodules stay as they are. 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 @@ -200,7 +200,7 @@ Each of these fails with a one-line message or is skipped: - 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 and replica-set discovery, and cloud sign-in (SQL Server Azure AD, MongoDB AWS/OIDC/Kerberos, dbt cloud methods); +- warehouse connections to other hosts, SSH tunnels, MongoDB SRV and replica-set discovery, 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. diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 9b9bf01743..299bf433c0 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -31,8 +31,13 @@ export function assertLocalConnection(raw: ConnectionConfig): void { // Trino and ClickHouse build `${protocol}://${host}`, so a protocol value could carry its own authority. if (config.protocol !== undefined && !["http", "https"].includes(String(config.protocol).trim().toLowerCase())) throw new Error(DENIED) - // Cloud sign-in contacts an identity provider even for a loopback host. - if (typeof config.authentication === "string" && /^azure-active-directory/i.test(config.authentication)) + // 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("/"))) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index 469906ef73..b7bcfb3e51 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -606,13 +606,14 @@ export const layer: Layer.Layer< }) } - // altimate_change start — offline mode moves only checked-out submodules, from objects already on disk - // (`submodule update` would clone the others). `submodule status` marks a not-checked-out one with "-". + // 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* git(["submodule", "status", "--recursive"], { cwd: worktreePath })).text + ? (yield* git(["submodule", "status"], { cwd: worktreePath })).text .split("\n") .filter((line) => line.length > 1 && !line.startsWith("-")) - .map((line) => line.slice(1).split(" ")[1]) + .map((line) => /^.[0-9a-f]+ (.+?)(?: \([^)]*\))?$/.exec(line)?.[1]) .filter((entry): entry is string => Boolean(entry)) : undefined if (!checkedOut || checkedOut.length > 0) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index c7a5c24418..9b30d22be0 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -36,6 +36,7 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { type: "sqlserver", host: "localhost\\SQLEXPRESS" }, { type: "redshift" }, { type: "clickhouse", host: "127.0.0.1", protocol: "HTTPS" }, + { type: "sqlserver", host: "localhost", authentication: "sql" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -68,6 +69,8 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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/#" }, From 55becda29c18ae8f49b6cc7b4a22430264e42472 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:16:48 -0800 Subject: [PATCH 63/72] fix: refuse Oracle TNS aliases and hostless Oracle offline; scope protocol check to Trino and ClickHouse Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/native/connections/offline.ts | 10 ++++++++-- .../test/altimate/native/offline-connections.test.ts | 3 +++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 299bf433c0..6fef155664 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -29,8 +29,14 @@ export function assertLocalConnection(raw: ConnectionConfig): void { // warehouses (Snowflake, BigQuery, Databricks and others) are refused. if (!HOST_ADDRESSED.has(type) || config.replica_set || config.direct_connection === false) throw new Error(DENIED) // Trino and ClickHouse build `${protocol}://${host}`, so a protocol value could carry its own authority. - if (config.protocol !== undefined && !["http", "https"].includes(String(config.protocol).trim().toLowerCase())) + 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 ( @@ -81,4 +87,4 @@ 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", "oracle", "redshift"]) +const LOCALHOST_BY_DEFAULT = new Set(["postgres", "postgresql", "mysql", "mariadb", "sqlserver", "mssql", "clickhouse", "mongodb", "mongo", "trino", "redshift"]) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 9b30d22be0..a5a99b9896 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -37,6 +37,7 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { type: "redshift" }, { type: "clickhouse", host: "127.0.0.1", protocol: "HTTPS" }, { type: "sqlserver", host: "localhost", authentication: "sql" }, + { type: "oracle", host: "localhost", protocol: "tcp" }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -76,6 +77,8 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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: "oracle", tns_name: "PROD_DB" }, + { type: "oracle" }, ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) From bef616042f1a1a5ba8504b6530d6390570397526 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:28:14 -0800 Subject: [PATCH 64/72] fix(offline): close review gaps in local operations Co-Authored-By: Codex --- docs/docs/configure/config.md | 6 +-- .../altimate/native/connections/offline.ts | 25 +++++++-- .../altimate/native/connections/registry.ts | 30 +++++++++-- .../src/altimate/onboarding/tool-detection.ts | 9 ++-- packages/opencode/src/mcp/index.ts | 2 - packages/opencode/src/worktree/index.ts | 6 ++- .../native/offline-connections.test.ts | 20 ++++++++ .../onboarding/tool-detection.test.ts | 9 ++++ .../altimate/registry-per-project.test.ts | 38 ++++++++++++++ packages/opencode/test/mcp/offline.test.ts | 11 ++++ .../opencode/test/project/worktree.test.ts | 51 ++++++++++++++++--- 11 files changed, 182 insertions(+), 25 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 271186a7e8..43ac81ba69 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -182,11 +182,11 @@ While still online: ### What keeps working -- Local warehouses: DuckDB and SQLite files, and Postgres, MySQL, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. 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. +- Local warehouses: DuckDB and SQLite files, and Postgres, MySQL, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. 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 submodules from local objects; nested and not-checked-out submodules stay as they are. Worktree create and reset leave Git LFS files as pointer files. +- 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 @@ -200,7 +200,7 @@ Each of these fails with a one-line message or is skipped: - 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 and replica-set discovery, and cloud sign-in (SQL Server methods other than SQL or Windows login, MongoDB AWS/OIDC/Kerberos, dbt cloud methods); +- 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. diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 6fef155664..2b4b7222fc 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -3,14 +3,21 @@ import { isLocalFilePath, normalizeConfig, type ConnectionConfig } from "@altima 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)) - return URL.canParse(value) && ["", "localhost"].includes(new URL(value).hostname) && !decodeURIComponent(new URL(value).pathname).startsWith("//") + 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) } @@ -19,6 +26,7 @@ export function isLocalPath(value: unknown): boolean { 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") { @@ -27,7 +35,8 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } // 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 || config.direct_connection === false) throw new Error(DENIED) + if (!HOST_ADDRESSED.has(type) || config.replica_set) 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) && @@ -59,6 +68,7 @@ export function assertLocalConnection(raw: ConnectionConfig): void { 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 { @@ -68,8 +78,11 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } // mongodb+srv:// and replica sets discover other hosts. const param = (name: string) => [...parsed.searchParams].find(([key]) => key.toLowerCase() === name)?.[1] - if (parsed.protocol.endsWith("+srv:") || param("replicaset") !== undefined || param("directconnection") === "false") - throw new Error(DENIED) + const directParam = param("directconnection") + 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. @@ -78,6 +91,8 @@ export function assertLocalConnection(raw: ConnectionConfig): void { 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) diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 45f2a70aaf..58d0d83bb8 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -74,6 +74,7 @@ interface State { interface Attempt { promise?: Promise tunnel?: TunnelHandle + effectiveConfig?: ConnectionConfig } function createState(dir: string): State { @@ -82,6 +83,7 @@ function createState(dir: string): State { /** Registry state per resolved project directory. */ const states = new Map() +const connectedConfigs = new WeakMap() /** Invalidate the in-flight connect for `name`, closing the tunnel it opened. Synchronous. */ function dropAttempt(s: State, name: string): void { @@ -450,8 +452,10 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) - // altimate_change — offline mode checks the effective target, after stored credentials are restored + // altimate_change start — keep the effective target before any tunnel rewrites it + attempt.effectiveConfig = resolvedConfig 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 @@ -550,6 +554,9 @@ async function createConnector( default: throw new Error(`No static import available for driver: ${driverPath}`) } + // altimate_change start — a driver import may finish after offline activation + if (Offline.enabled()) assertLocalConnection(attempt.effectiveConfig) + // altimate_change end connector = await mod.connect(resolvedConfig) } catch (e) { // Clean up SSH tunnel if driver creation fails @@ -679,6 +686,16 @@ export async function get(name: string): Promise { const cached = connectors.get(name) if (cached) { + // altimate_change start — a project loaded later can activate offline mode process-wide + if (Offline.enabled()) { + try { + assertLocalConnection(connectedConfigs.get(cached)!) + } catch (error) { + await detachCached(s, name)() + throw error + } + } + // altimate_change end // 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 @@ -687,8 +704,11 @@ export async function get(name: string): Promise { // 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) { + if (Offline.enabled() && inflight.effectiveConfig) assertLocalConnection(inflight.effectiveConfig) + return inflight.promise + } // altimate_change end const config = configs.get(name) @@ -725,8 +745,11 @@ export async function get(name: string): Promise { try { // altimate_change start — the attempt closes only the tunnel it opened const connector = await createConnector(name, config, attempt, current) + const effectiveConfig = attempt.effectiveConfig! try { + if (Offline.enabled()) assertLocalConnection(effectiveConfig) await connector.connect() + if (Offline.enabled()) assertLocalConnection(effectiveConfig) } catch (connectErr) { // If connect() fails after tunnel was started, clean up the tunnel (first, so a hanging close cannot hold it) attempt.tunnel?.close() @@ -741,6 +764,7 @@ export async function get(name: string): Promise { throw SUPERSEDED(name) } connectors.set(name, connector) + connectedConfigs.set(connector, effectiveConfig) if (attempt.tunnel) tunnels.set(name, attempt.tunnel) // altimate_change end fileLog("INFO", "warehouse-connect", "connected", { name, type: config.type, auth: authMethod, duration_ms: Date.now() - startTime }) diff --git a/packages/opencode/src/altimate/onboarding/tool-detection.ts b/packages/opencode/src/altimate/onboarding/tool-detection.ts index c7ac8bed08..9e7be68c1a 100644 --- a/packages/opencode/src/altimate/onboarding/tool-detection.ts +++ b/packages/opencode/src/altimate/onboarding/tool-detection.ts @@ -115,11 +115,10 @@ async function probe(): Promise { // 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()) - return { - hasDbt: !resolved.source.startsWith("fallback") || Bun.which("dbt", { PATH: process.env.PATH ?? "" }) !== null, - hasDbtDuckdb: hasDuckdbAdapter(resolved.path), - } + 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) diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index 8ddaf19608..e9711ac138 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -1387,9 +1387,7 @@ export const layer = Layer.effect( }) const beginAuth = Effect.fn("MCP.beginAuth")(function* (mcpName: string, token: number) { - // altimate_change start — offline mode refuses before starting an OAuth flow if (Offline.enabled()) throw new Error("Authenticate MCP servers while online.") - // altimate_change end const lifecycle = yield* InstanceState.get(state) // altimate_change end const mcpConfig = yield* requireMcpConfig(mcpName) diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index b7bcfb3e51..3f38e0c1a5 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -610,7 +610,11 @@ export const layer: Layer.Layer< // 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* git(["submodule", "status"], { cwd: worktreePath })).text + ? (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]) diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index a5a99b9896..101d2a0ecb 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -38,6 +38,9 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { 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", connection_string: "mongodb://localhost/db", direct_connection: true }, ]) expect(() => assertLocalConnection(config)).not.toThrow() }) @@ -64,6 +67,8 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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: "postgres", host: "/tmp,db.example.com" }, { type: "mysql", host: "/tmp/mysql" }, { type: "mongodb", connection_string: "mongodb+srv://localhost/db" }, @@ -77,11 +82,26 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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 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" }, + ]) + 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) => diff --git a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts index c01c5ae337..9fffe7be1b 100644 --- a/packages/opencode/test/altimate/onboarding/tool-detection.test.ts +++ b/packages/opencode/test/altimate/onboarding/tool-detection.test.ts @@ -209,6 +209,7 @@ Plugins: 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. @@ -228,7 +229,15 @@ test.skipIf(process.platform === "win32")("offline detection finds dbt without r _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 diff --git a/packages/opencode/test/altimate/registry-per-project.test.ts b/packages/opencode/test/altimate/registry-per-project.test.ts index f192d63a71..d132c6eddd 100644 --- a/packages/opencode/test/altimate/registry-per-project.test.ts +++ b/packages/opencode/test/altimate/registry-per-project.test.ts @@ -261,6 +261,44 @@ describe("connectors are per project", () => { ]) }) + test("late offline activation closes a cached tunneled connector and keeps a local connector", async () => { + writeLocal(projectA, { + tunneled: sshStore("cached-offline", { path: "tunneled.sqlite" }), + local: { type: "sqlite", path: "local.sqlite", create: true }, + }) + await inProject(projectA, () => Registry.get("tunneled")) + const local = await inProject(projectA, () => Registry.get("local")) + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + await expect(inProject(projectA, () => Registry.get("tunneled"))).rejects.toThrow("Offline mode") + expect(ended("cached-offline")).toEqual([true]) + expect(await inProject(projectA, () => Registry.get("local"))).toBe(local) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) + + test("a pending tunnel cannot publish a connector after offline activation", async () => { + writeLocal(projectA, { tunneled: sshStore("held-offline") }) + const pending = inProject(projectA, () => Registry.get("tunneled")) + await sshConnected("held-offline") + const previous = process.env.ALTIMATE_OFFLINE + process.env.ALTIMATE_OFFLINE = "1" + try { + await expect(inProject(projectA, () => Registry.get("tunneled"))).rejects.toThrow("Offline mode") + heldReady.get("held-offline")!() + await expect(pending).rejects.toThrow("Offline mode") + expect(ended("held-offline")).toEqual([true]) + } finally { + heldReady.get("held-offline")?.() + await pending.catch(() => {}) + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) + test("a connect in flight when its project reloads is not cached over the reloaded state", async () => { writeLocal(projectA, { store: { type: "sqlite", path: "store.sqlite", create: true } }) const inflight = inProject(projectA, () => Registry.get("store")) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 01848bb836..f58d0a2493 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -3,6 +3,17 @@ import { expect, test } from "bun:test" import path from "node:path" import { Offline } from "../../src/config/offline" +test("the offline OAuth guard is covered by 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('if (Offline.enabled()) throw new Error("Authenticate MCP servers while online.")') + expect(block.match(/\/\/ altimate_change start/g)).toHaveLength(1) + expect(block).toContain("const lifecycle = yield* InstanceState.get(state)") +}) + 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) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 10a8fb710c..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" @@ -97,24 +98,62 @@ describe("Worktree", () => { 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, "..", `${path.basename(directory)}-lib`) - Bun.spawnSync(["git", "init", "-q", lib]) - Bun.spawnSync(["git", "-C", lib, "-c", "user.email=t@example.com", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "lib"]) + 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(["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false", "commit", "-q", "-m", "add submodule"]) + run([...commit, "-m", "add submodule"]) run(["update-ref", `refs/remotes/origin/${branch}`, "HEAD"]) - Bun.spawnSync(["rm", "-rf", lib]) + yield* Effect.promise(() => rename(lib, `${lib}-hidden`)) const previous = process.env.ALTIMATE_OFFLINE process.env.ALTIMATE_OFFLINE = "1" try { const svc = yield* Worktree.Service - const fs = yield* FSUtil.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 { From 3a17d06d33dab80c7fca0e919ea6b548b1b91af7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:35:22 -0800 Subject: [PATCH 65/72] fix(offline): tighten local connection and Git checks Co-Authored-By: Codex --- packages/core/src/git.ts | 7 ++++++- .../src/altimate/native/connections/offline.ts | 5 ++++- packages/opencode/src/config/offline.ts | 4 ++-- .../altimate/native/offline-connections.test.ts | 17 +++++++++++++++++ packages/opencode/test/mcp/offline.test.ts | 7 +++++++ packages/opencode/test/util/git.test.ts | 13 +++++++++++++ 6 files changed, 49 insertions(+), 4 deletions(-) diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 299461f5c5..06aa0f9550 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -26,7 +26,12 @@ export function gitCommandUsesNetwork(args: string[]) { remoteCommands.has(command) || (command === "remote" && (operation === "update" || (operation === "show" && !rest.includes("-n")))) || (command === "submodule" && ["update", "add"].includes(operation)) || - (command === "submodule" && operation === "foreach" && rest.some((arg) => /\b(fetch|pull|push|clone|ls-remote)\b/.test(arg))) || + // Git runs foreach through a shell. Allow only these literal local commands. + (command === "submodule" && + operation === "foreach" && + !["git reset --hard", "git clean -fdx", "git status"].includes( + rest.slice(rest[0] === "--recursive" ? 1 : 0).join(" "), + )) || (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)) || diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 2b4b7222fc..0f5f3a7bf4 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -36,6 +36,9 @@ export function assertLocalConnection(raw: ConnectionConfig): void { // 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 && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 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 ( @@ -80,7 +83,7 @@ export function assertLocalConnection(raw: ConnectionConfig): void { const param = (name: string) => [...parsed.searchParams].find(([key]) => key.toLowerCase() === name)?.[1] const directParam = param("directconnection") if (parsed.protocol.endsWith("+srv:") || param("replicaset") !== undefined) throw new Error(DENIED) - if (directParam === "false") throw new Error(mongo ? MONGO_DIRECT : DENIED) + if (directParam?.toLowerCase() === "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() diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 84b3e87c49..7c9722b879 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -4,6 +4,8 @@ // 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" @@ -182,5 +184,3 @@ 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).") } - -export * as Offline from "./offline" diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 101d2a0ecb..5740adfcea 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -69,6 +69,8 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse { 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" }, @@ -91,11 +93,26 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) +test("offline host-addressed databases accept only integer 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]) + expect(() => assertLocalConnection({ ...config, port })).not.toThrow() + for (const port of [null, "27017", "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.", diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index f58d0a2493..284bd76438 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -3,6 +3,13 @@ import { expect, test } from "bun:test" import path from "node:path" import { Offline } from "../../src/config/offline" +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 offline OAuth guard is covered by 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") diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index 14178f2295..f2ea896b65 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -74,5 +74,18 @@ describe("git() utility", () => { 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", ...args])).toBe(true) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--recursive", "git", "reset", "--hard"])).toBe(false) + expect(gitCommandUsesNetwork(["submodule", "foreach", "--recursive", "git clean -fdx"])).toBe(false) + }) // altimate_change end }) From 6bdbc3c5e8689d6f84d9fc22384ad134fe2935b0 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:51:18 -0800 Subject: [PATCH 66/72] fix: revalidate cached dbt adapters when offline mode activates Co-Authored-By: Codex --- .../altimate/native/connections/register.ts | 31 ++++++--- .../native/offline-connections.test.ts | 69 +++++++++++++++++++ 2 files changed, 91 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 18337dc987..016f29e3bb 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -62,6 +62,7 @@ let dbtAdapter: any | null | undefined = undefined // permanent negative cache (`dbtAdapter === null`) is unchanged — a project that // becomes valid mid-session is still not retried. let dbtAdapterInflight: Promise | undefined +let dbtAdapterCreatedOffline = false /** The project root the cached attempt read from the dbt config; null when it found none. */ let dbtProjectRoot: string | null = null /** The Python the cached attempt runs dbt with; null when it found no config. */ @@ -88,6 +89,9 @@ export const dbtAdapterInternals: { * project. Idempotent, single-flight, and permanently negative once it has failed. */ async function ensureDbtAdapter(): Promise { + // An adapter created online has neither a checked profile nor offline subprocess settings. + const disposing = + dbtAdapter && Offline.enabled() && !dbtAdapterCreatedOffline ? disposeDbtAdapter() : undefined if (dbtAdapter !== undefined) return dbtAdapter if (dbtAdapterInflight) return dbtAdapterInflight @@ -98,9 +102,10 @@ async function ensureDbtAdapter(): Promise { // Likewise the cache: a superseded attempt returns its result to the callers that // awaited it but must not publish it, or it would overwrite what the newer attempt // stored. Every write goes through here. - const publish = (value: any | null, root?: string): any | null => { + const publish = (value: any | null, root?: string, offline = false): any | null => { if (dbtAdapterInflight === mine) { dbtAdapter = value + dbtAdapterCreatedOffline = offline dbtRoute.root = value ? (root ?? null) : null dbtAdapterInternals.writes += 1 } @@ -109,6 +114,7 @@ async function ensureDbtAdapter(): Promise { mine = (async () => { dbtAdapterInternals.attempts += 1 try { + if (disposing) await disposing // Check if dbt config exists const { read: readDbtConfig } = await import( "../../../../../dbt-tools/src/config" @@ -131,9 +137,9 @@ async function ensureDbtAdapter(): Promise { } // 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 + const localProfile = () => + assertLocalDbt(dbtConfig.projectRoot, ["--project-dir", dbtConfig.projectRoot], dbtConfig.dbtIntegration, dbtConfig.projectRoot) + let offline = Offline.enabled() ? await localProfile() : 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 @@ -143,11 +149,17 @@ async function ensureDbtAdapter(): Promise { const options = SEPARATE_TARGET_MODES.has(dbtConfig.dbtIntegration || "core") ? { targetPath: await dbtToolTargetPath(dbtConfig.projectRoot) } : {} - // Offline, dbt reads exactly the profiles directory that was checked. - return publish( - await create(dbtConfig, { ...options, ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}) }), - dbtConfig.projectRoot, - ) + while (true) { + if (!offline && Offline.enabled()) offline = await localProfile() + // Offline, dbt reads exactly the profiles directory that was checked. + const adapter = await create(dbtConfig, { + ...options, + ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}), + }) + if (offline || !Offline.enabled()) return publish(adapter, dbtConfig.projectRoot, offline !== undefined) + // Requests waiting on this attempt must not receive an adapter that started online. + await adapter?.dispose?.().catch(() => {}) + } } catch (error) { // An offline refusal is the answer, not "dbt unavailable": falling back would run the query elsewhere. if (isOfflineRefusal(error)) throw error @@ -369,6 +381,7 @@ export function resetDbtAdapter(): void { dbtRoute.root = undefined // altimate_change — drop any in-flight creation too, or a test that resets mid-flight // would still receive the previous adapter. + dbtAdapterCreatedOffline = false dbtAdapterInflight = undefined dbtAdapterInternals.attempts = 0 dbtAdapterInternals.writes = 0 diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index 5740adfcea..a159e55b27 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -4,7 +4,9 @@ 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 { dbtAdapterInternals, disposeDbtAdapter, getDbtAdapter } from "../../../src/altimate/native/connections/register" import { assertLocalDbt } from "../../../src/altimate/native/dbt/offline" +import { tmpdir } from "../../fixture/fixture" const envKeys = ["DBT_TARGET", "DBT_PROFILE", "DBT_PROFILES_DIR", "DBT_PROJECT_DIR", "ALTIMATE_OFFLINE"] let savedEnv: Record @@ -195,6 +197,73 @@ test("dbt finds the project from a subdirectory and reads profiles from the work } finally { await fs.rm(root, { recursive: true, force: true }) } }) +test.each([ + ["remote", "cached"], + ["local", "cached"], + ["remote", "starting"], +])("offline activation revalidates a %s dbt target while its adapter is %s", async (target, state) => { + await using project = await tmpdir() + await Bun.write(path.join(project.path, "dbt_project.yml"), "profile: test\n") + await Bun.write( + path.join(project.path, "profiles.yml"), + `test:\n target: ${target}\n outputs:\n local:\n type: duckdb\n path: ':memory:'\n remote:\n type: postgres\n host: example.com\n`, + ) + const creations: unknown[] = [] + let disposed = 0 + const online = { dispose: async () => void (disposed += 1) } + const offline = {} + const starting = Promise.withResolvers() + const finish = Promise.withResolvers() + + await disposeDbtAdapter() + dbtAdapterInternals.readConfig = async () => ({ projectRoot: project.path, dbtIntegration: "corecommand" }) + dbtAdapterInternals.create = async (_, options) => { + creations.push(options) + if (state === "starting") { + starting.resolve() + await finish.promise + } + return options?.offline ? offline : online + } + try { + if (state === "starting") { + const first = getDbtAdapter() + await starting.promise + process.env.ALTIMATE_OFFLINE = "1" + const both = Promise.allSettled([first, getDbtAdapter()]) + finish.resolve() + for (const result of await both) { + expect(result.status).toBe("rejected") + if (result.status === "rejected") expect(result.reason.message).toContain("Offline mode") + } + expect(creations).toHaveLength(1) + expect(disposed).toBe(1) + return + } + + expect(await getDbtAdapter()).toBe(online) + expect(await getDbtAdapter()).toBe(online) + expect(creations).toHaveLength(1) + process.env.ALTIMATE_OFFLINE = "1" + + if (target === "remote") { + await expect(getDbtAdapter()).rejects.toThrow("Offline mode") + expect(creations).toHaveLength(1) + } else { + expect(await Promise.all([getDbtAdapter(), getDbtAdapter()])).toEqual([offline, offline]) + expect(await getDbtAdapter()).toBe(offline) + expect(creations).toHaveLength(2) + expect(creations[1]).toMatchObject({ offline: true, profilesDir: project.path }) + } + expect(disposed).toBe(1) + } finally { + finish.resolve() + await disposeDbtAdapter() + delete dbtAdapterInternals.readConfig + delete dbtAdapterInternals.create + } +}) + test("dbt checks selected target and CLI overrides", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-")) try { From be00b9e2dded74cfa70c9fde237ca29e56a35135 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 11:59:23 -0800 Subject: [PATCH 67/72] fix(offline): handle local ports, MongoDB options and git flags Co-Authored-By: Codex --- docs/docs/configure/config.md | 2 +- packages/core/src/git.ts | 11 ++--- .../altimate/native/connections/offline.ts | 11 +++-- .../native/offline-connections.test.ts | 12 +++-- packages/opencode/test/mcp/offline.test.ts | 47 +++++++++++++++++-- packages/opencode/test/util/git.test.ts | 4 +- 6 files changed, 69 insertions(+), 18 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 43ac81ba69..de76d954f8 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -182,7 +182,7 @@ While still online: ### What keeps working -- Local warehouses: DuckDB and SQLite files, and Postgres, MySQL, SQL Server, ClickHouse, Trino, Oracle and MongoDB servers reached through a Unix socket or a host of `localhost`, `::1` or `127.x.x.x`. 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. +- 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`. diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts index 06aa0f9550..aa12a99a51 100644 --- a/packages/core/src/git.ts +++ b/packages/core/src/git.ts @@ -22,16 +22,15 @@ export function gitCommandUsesNetwork(args: string[]) { 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)) || - // Git runs foreach through a shell. Allow only these literal local commands. - (command === "submodule" && - operation === "foreach" && - !["git reset --hard", "git clean -fdx", "git status"].includes( - rest.slice(rest[0] === "--recursive" ? 1 : 0).join(" "), - )) || (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)) || diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index 0f5f3a7bf4..cbe00b0cbf 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -37,8 +37,11 @@ export function assertLocalConnection(raw: ConnectionConfig): void { // 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 && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)) - throw new Error(DENIED) + if (port !== undefined) { + const numeric = typeof port === "string" && port.length > 0 && !/\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 ( @@ -81,9 +84,9 @@ export function assertLocalConnection(raw: ConnectionConfig): void { } // mongodb+srv:// and replica sets discover other hosts. const param = (name: string) => [...parsed.searchParams].find(([key]) => key.toLowerCase() === name)?.[1] - const directParam = param("directconnection") + const directParam = param("directconnection")?.toLowerCase() if (parsed.protocol.endsWith("+srv:") || param("replicaset") !== undefined) throw new Error(DENIED) - if (directParam?.toLowerCase() === "false") throw new Error(mongo ? MONGO_DIRECT : 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() diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index a159e55b27..c859f1b505 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -29,6 +29,7 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { 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" }, @@ -42,6 +43,8 @@ test("offline permits local files, loopback hosts and Unix sockets", () => { { 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() }) @@ -95,15 +98,18 @@ test("offline refuses remote hosts, remote storage, SSH and what it cannot parse ]) expect(() => assertLocalConnection(config)).toThrow("Offline mode") }) -test("offline host-addressed databases accept only integer ports in range", () => { +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]) + for (const port of [undefined, 1, 65535, "1", "5432", "65535"]) expect(() => assertLocalConnection({ ...config, port })).not.toThrow() - for (const port of [null, "27017", "27017,db.example.com:27017", 0, -1, 1.5, 65536, NaN, Infinity]) + 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") } }) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 284bd76438..d0b2a37aca 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -1,7 +1,14 @@ // 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() @@ -10,17 +17,51 @@ test("the offline config module self-exports before its imports", async () => { ) }) -test("the offline OAuth guard is covered by the existing lifecycle marker", async () => { +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('if (Offline.enabled()) throw new Error("Authenticate MCP servers while online.")') + expect(block).toContain('const beginAuth = Effect.fn("MCP.beginAuth")') expect(block.match(/\/\/ altimate_change start/g)).toHaveLength(1) - expect(block).toContain("const lifecycle = yield* InstanceState.get(state)") }) +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 + } + }), +) + 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) diff --git a/packages/opencode/test/util/git.test.ts b/packages/opencode/test/util/git.test.ts index f2ea896b65..dff4bc494b 100644 --- a/packages/opencode/test/util/git.test.ts +++ b/packages/opencode/test/util/git.test.ts @@ -83,9 +83,11 @@ describe("git() utility", () => { ["git lfs fetch"], ["git reset --hard && git fetch"], ]) - expect(gitCommandUsesNetwork(["submodule", "foreach", "--recursive", ...args])).toBe(true) + 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 }) From 68cfd9fb97d7759e3ceabfb2d413e4d1322bc64e Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 12:22:00 -0800 Subject: [PATCH 68/72] fix: reopen cached DuckDB when offline mode activates Co-Authored-By: Codex --- .../altimate/native/connections/registry.ts | 23 ++++++++++++++----- .../altimate/registry-per-project.test.ts | 21 +++++++++++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index 58d0d83bb8..a28c7176ee 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -75,6 +75,7 @@ interface Attempt { promise?: Promise tunnel?: TunnelHandle effectiveConfig?: ConnectionConfig + offline?: boolean } function createState(dir: string): State { @@ -83,7 +84,7 @@ function createState(dir: string): State { /** Registry state per resolved project directory. */ const states = new Map() -const connectedConfigs = new WeakMap() +const connectedConfigs = new WeakMap() /** Invalidate the in-flight connect for `name`, closing the tunnel it opened. Synchronous. */ function dropAttempt(s: State, name: string): void { @@ -555,7 +556,8 @@ async function createConnector( throw new Error(`No static import available for driver: ${driverPath}`) } // altimate_change start — a driver import may finish after offline activation - if (Offline.enabled()) assertLocalConnection(attempt.effectiveConfig) + attempt.offline = Offline.enabled() + if (attempt.offline) assertLocalConnection(attempt.effectiveConfig) // altimate_change end connector = await mod.connect(resolvedConfig) } catch (e) { @@ -685,11 +687,14 @@ export async function get(name: string): Promise { } const cached = connectors.get(name) + let reopenCached = false if (cached) { // altimate_change start — a project loaded later can activate offline mode process-wide if (Offline.enabled()) { try { - assertLocalConnection(connectedConfigs.get(cached)!) + const { config, offline } = connectedConfigs.get(cached)! + assertLocalConnection(config) + reopenCached = config.type.toLowerCase() === "duckdb" && !offline } catch (error) { await detachCached(s, name)() throw error @@ -697,9 +702,11 @@ export async function get(name: string): Promise { } // altimate_change end // altimate_change start — a reused connection can reconnect and ask for a browser sign-in; route it here - SignInNotice.rememberOrigin(accountOf(configs.get(name))) + if (!reopenCached) { + SignInNotice.rememberOrigin(accountOf(configs.get(name))) + return cached + } // altimate_change end - return cached } // If a connector is already being created, await the same Promise @@ -743,6 +750,10 @@ export async function get(name: string): Promise { // altimate_change end const promise = (async () => { try { + if (reopenCached) { + await detachCached(s, name)() + if (!current()) throw SUPERSEDED(name) + } // altimate_change start — the attempt closes only the tunnel it opened const connector = await createConnector(name, config, attempt, current) const effectiveConfig = attempt.effectiveConfig! @@ -764,7 +775,7 @@ export async function get(name: string): Promise { throw SUPERSEDED(name) } connectors.set(name, connector) - connectedConfigs.set(connector, effectiveConfig) + connectedConfigs.set(connector, { config: effectiveConfig, offline: attempt.offline! }) if (attempt.tunnel) tunnels.set(name, attempt.tunnel) // altimate_change end fileLog("INFO", "warehouse-connect", "connected", { name, type: config.type, auth: authMethod, duration_ms: Date.now() - startTime }) diff --git a/packages/opencode/test/altimate/registry-per-project.test.ts b/packages/opencode/test/altimate/registry-per-project.test.ts index d132c6eddd..f9c6144174 100644 --- a/packages/opencode/test/altimate/registry-per-project.test.ts +++ b/packages/opencode/test/altimate/registry-per-project.test.ts @@ -280,6 +280,27 @@ describe("connectors are per project", () => { } }) + test("late offline activation reopens cached DuckDB with extension autoinstall disabled", async () => { + writeLocal(projectA, { store: { type: "duckdb", path: "store.duckdb", create: true } }) + const previous = process.env.ALTIMATE_OFFLINE + const setting = "SELECT current_setting('autoinstall_known_extensions')" + delete process.env.ALTIMATE_OFFLINE + try { + const online = await inProject(projectA, () => Registry.get("store")) + expect((await online.execute(setting)).rows).toEqual([[true]]) + + process.env.ALTIMATE_OFFLINE = "1" + const [offline, concurrent] = await inProject(projectA, () => Promise.all([Registry.get("store"), Registry.get("store")])) + expect(offline).not.toBe(online) + expect(concurrent).toBe(offline) + expect((await offline.execute(setting)).rows).toEqual([[false]]) + expect(await inProject(projectA, () => Registry.get("store"))).toBe(offline) + } finally { + if (previous === undefined) delete process.env.ALTIMATE_OFFLINE + else process.env.ALTIMATE_OFFLINE = previous + } + }) + test("a pending tunnel cannot publish a connector after offline activation", async () => { writeLocal(projectA, { tunneled: sshStore("held-offline") }) const pending = inProject(projectA, () => Registry.get("tunneled")) From db57f087b0ecee66058f3a85c28f10d5c79a3739 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 12:27:14 -0800 Subject: [PATCH 69/72] refactor(offline): simplify local port validation Co-Authored-By: Codex --- packages/opencode/src/altimate/native/connections/offline.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/native/connections/offline.ts b/packages/opencode/src/altimate/native/connections/offline.ts index cbe00b0cbf..af0272e3d3 100644 --- a/packages/opencode/src/altimate/native/connections/offline.ts +++ b/packages/opencode/src/altimate/native/connections/offline.ts @@ -38,7 +38,7 @@ export function assertLocalConnection(raw: ConnectionConfig): void { if (!HOST_ADDRESSED.has(type) || config.replica_set) throw new Error(DENIED) const { port } = config if (port !== undefined) { - const numeric = typeof port === "string" && port.length > 0 && !/\D/.test(port) ? Number(port) : port + 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) } From 0d2646e73ecee4fdaa78d419f733de50463222e2 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 12:41:17 -0800 Subject: [PATCH 70/72] test: give the offline MCP auth test a CI-safe timeout Co-Authored-By: Claude Opus 5.5 --- packages/opencode/test/mcp/offline.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/opencode/test/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index d0b2a37aca..9b25a3287d 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -60,6 +60,7 @@ mcpTest.live("offline MCP auth refuses both entry points without contacting the else process.env.ALTIMATE_OFFLINE = previous } }), + 30_000, ) test("loopback checks accept only literal local addresses", () => { From 6e992bcd422847f9cf178071f645f355790cb567 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 12:50:49 -0800 Subject: [PATCH 71/72] fix(offline): require startup opt-in Refuse offline settings discovered after startup and remove late connector and dbt adapter replacement. Keep both proxy exclusions consistent when either specifies a wildcard. Co-Authored-By: Codex --- docs/docs/configure/config.md | 3 +- .../altimate/native/connections/register.ts | 32 +++------ .../altimate/native/connections/registry.ts | 42 ++--------- packages/opencode/src/config/config.ts | 15 ++-- packages/opencode/src/config/offline.ts | 8 ++- .../native/offline-connections.test.ts | 69 ------------------- .../altimate/registry-per-project.test.ts | 59 ---------------- packages/opencode/test/config/config.test.ts | 21 ++++++ packages/opencode/test/mcp/offline.test.ts | 19 +++++ 9 files changed, 71 insertions(+), 197 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index de76d954f8..777af1f7d3 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ With offline mode off, nothing in this section applies and Altimate Code behaves ### Turn it on -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. Organisation-managed configuration, remote (well-known) configuration and the legacy TOML `config` file apply the setting only once they load, after some startup requests; use `ALTIMATE_OFFLINE=1` there. Any one of these sources turns it on; a value of `false` elsewhere does not turn it back off. `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. +Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. If Altimate Code first sees `"offline": true` while loading organisation-managed configuration, remote (well-known) configuration, or the legacy TOML `config` file, it refuses to start and asks you to set `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`. @@ -214,6 +214,5 @@ Some network use happens inside programs Altimate Code starts and is not checked - 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`. -- When offline mode turns on after startup (organisation-managed or remote configuration, or a server started without it that then loads an offline project), internal HTTP requests made through the shared HTTP client stay unguarded for the rest of that process. Set `ALTIMATE_OFFLINE=1` before starting a server. 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/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 016f29e3bb..1b521d83ab 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -62,7 +62,6 @@ let dbtAdapter: any | null | undefined = undefined // permanent negative cache (`dbtAdapter === null`) is unchanged — a project that // becomes valid mid-session is still not retried. let dbtAdapterInflight: Promise | undefined -let dbtAdapterCreatedOffline = false /** The project root the cached attempt read from the dbt config; null when it found none. */ let dbtProjectRoot: string | null = null /** The Python the cached attempt runs dbt with; null when it found no config. */ @@ -89,9 +88,6 @@ export const dbtAdapterInternals: { * project. Idempotent, single-flight, and permanently negative once it has failed. */ async function ensureDbtAdapter(): Promise { - // An adapter created online has neither a checked profile nor offline subprocess settings. - const disposing = - dbtAdapter && Offline.enabled() && !dbtAdapterCreatedOffline ? disposeDbtAdapter() : undefined if (dbtAdapter !== undefined) return dbtAdapter if (dbtAdapterInflight) return dbtAdapterInflight @@ -102,10 +98,9 @@ async function ensureDbtAdapter(): Promise { // Likewise the cache: a superseded attempt returns its result to the callers that // awaited it but must not publish it, or it would overwrite what the newer attempt // stored. Every write goes through here. - const publish = (value: any | null, root?: string, offline = false): any | null => { + const publish = (value: any | null, root?: string): any | null => { if (dbtAdapterInflight === mine) { dbtAdapter = value - dbtAdapterCreatedOffline = offline dbtRoute.root = value ? (root ?? null) : null dbtAdapterInternals.writes += 1 } @@ -114,7 +109,6 @@ async function ensureDbtAdapter(): Promise { mine = (async () => { dbtAdapterInternals.attempts += 1 try { - if (disposing) await disposing // Check if dbt config exists const { read: readDbtConfig } = await import( "../../../../../dbt-tools/src/config" @@ -137,9 +131,9 @@ async function ensureDbtAdapter(): Promise { } // The integration reads profiles.yml relative to the project, so check from there. - const localProfile = () => - assertLocalDbt(dbtConfig.projectRoot, ["--project-dir", dbtConfig.projectRoot], dbtConfig.dbtIntegration, dbtConfig.projectRoot) - let offline = Offline.enabled() ? await localProfile() : undefined + 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 @@ -149,17 +143,12 @@ async function ensureDbtAdapter(): Promise { const options = SEPARATE_TARGET_MODES.has(dbtConfig.dbtIntegration || "core") ? { targetPath: await dbtToolTargetPath(dbtConfig.projectRoot) } : {} - while (true) { - if (!offline && Offline.enabled()) offline = await localProfile() - // Offline, dbt reads exactly the profiles directory that was checked. - const adapter = await create(dbtConfig, { - ...options, - ...(offline ? { offline: true, profilesDir: offline.profilesDir } : {}), - }) - if (offline || !Offline.enabled()) return publish(adapter, dbtConfig.projectRoot, offline !== undefined) - // Requests waiting on this attempt must not receive an adapter that started online. - await adapter?.dispose?.().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 @@ -381,7 +370,6 @@ export function resetDbtAdapter(): void { dbtRoute.root = undefined // altimate_change — drop any in-flight creation too, or a test that resets mid-flight // would still receive the previous adapter. - dbtAdapterCreatedOffline = false dbtAdapterInflight = undefined dbtAdapterInternals.attempts = 0 dbtAdapterInternals.writes = 0 diff --git a/packages/opencode/src/altimate/native/connections/registry.ts b/packages/opencode/src/altimate/native/connections/registry.ts index a28c7176ee..99f3a7ca8d 100644 --- a/packages/opencode/src/altimate/native/connections/registry.ts +++ b/packages/opencode/src/altimate/native/connections/registry.ts @@ -74,8 +74,6 @@ interface State { interface Attempt { promise?: Promise tunnel?: TunnelHandle - effectiveConfig?: ConnectionConfig - offline?: boolean } function createState(dir: string): State { @@ -84,7 +82,6 @@ function createState(dir: string): State { /** Registry state per resolved project directory. */ const states = new Map() -const connectedConfigs = new WeakMap() /** Invalidate the in-flight connect for `name`, closing the tunnel it opened. Synchronous. */ function dropAttempt(s: State, name: string): void { @@ -453,8 +450,7 @@ async function createConnector( // Resolve credentials from keychain resolvedConfig = await resolveConfig(name, resolvedConfig) - // altimate_change start — keep the effective target before any tunnel rewrites it - attempt.effectiveConfig = resolvedConfig + // altimate_change start — validate the resolved target before any tunnel rewrites it if (Offline.enabled()) assertLocalConnection(resolvedConfig) // altimate_change end @@ -555,10 +551,6 @@ async function createConnector( default: throw new Error(`No static import available for driver: ${driverPath}`) } - // altimate_change start — a driver import may finish after offline activation - attempt.offline = Offline.enabled() - if (attempt.offline) assertLocalConnection(attempt.effectiveConfig) - // altimate_change end connector = await mod.connect(resolvedConfig) } catch (e) { // Clean up SSH tunnel if driver creation fails @@ -687,35 +679,17 @@ export async function get(name: string): Promise { } const cached = connectors.get(name) - let reopenCached = false if (cached) { - // altimate_change start — a project loaded later can activate offline mode process-wide - if (Offline.enabled()) { - try { - const { config, offline } = connectedConfigs.get(cached)! - assertLocalConnection(config) - reopenCached = config.type.toLowerCase() === "duckdb" && !offline - } catch (error) { - await detachCached(s, name)() - throw error - } - } - // altimate_change end // altimate_change start — a reused connection can reconnect and ask for a browser sign-in; route it here - if (!reopenCached) { - SignInNotice.rememberOrigin(accountOf(configs.get(name))) - return cached - } + SignInNotice.rememberOrigin(accountOf(configs.get(name))) + 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) - if (inflight?.promise) { - if (Offline.enabled() && inflight.effectiveConfig) assertLocalConnection(inflight.effectiveConfig) - return inflight.promise - } + if (inflight?.promise) return inflight.promise // altimate_change end const config = configs.get(name) @@ -750,17 +724,10 @@ export async function get(name: string): Promise { // altimate_change end const promise = (async () => { try { - if (reopenCached) { - await detachCached(s, name)() - if (!current()) throw SUPERSEDED(name) - } // altimate_change start — the attempt closes only the tunnel it opened const connector = await createConnector(name, config, attempt, current) - const effectiveConfig = attempt.effectiveConfig! try { - if (Offline.enabled()) assertLocalConnection(effectiveConfig) await connector.connect() - if (Offline.enabled()) assertLocalConnection(effectiveConfig) } catch (connectErr) { // If connect() fails after tunnel was started, clean up the tunnel (first, so a hanging close cannot hold it) attempt.tunnel?.close() @@ -775,7 +742,6 @@ export async function get(name: string): Promise { throw SUPERSEDED(name) } connectors.set(name, connector) - connectedConfigs.set(connector, { config: effectiveConfig, offline: attempt.offline! }) if (attempt.tunnel) tunnels.set(name, attempt.tunnel) // altimate_change end fileLog("INFO", "warehouse-connect", "connected", { name, type: config.type, auth: authMethod, duration_ms: Date.now() - startTime }) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 82d72b6140..2adcc52ad4 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -54,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("This project requests offline mode. Start Altimate Code with ALTIMATE_OFFLINE=1 or from the project directory.") + } +} +// 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() @@ -689,8 +697,8 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } - // altimate_change — `"offline": true` in a local config turns offline mode on before the account request - if (result.offline === true) Offline.start() + // 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()))), ) @@ -782,8 +790,7 @@ 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. - // Managed config can turn offline mode on too. - if (result.offline === true) Offline.start() + requireOfflineStartup(result.offline) const deps: Fiber.Fiber[] = [] for (const dir of directories) { if (!Offline.enabled() && ConfigPlugin.shouldInstallDependencies(dir, result.plugin)) { diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index 7c9722b879..b5da09654c 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -22,11 +22,11 @@ const CONFIG_NAMES = ["altimate-code.json", "altimate-code.jsonc", "opencode.jso /** * 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. Organisation-managed config is applied when the configuration loads. + * 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 - // A failure to read config here must not stop a command; the instance applies the setting when it loads. + // Let the instance report config errors and reject any offline opt-in missed here. return findOptIn(directory).catch(() => false) } @@ -87,7 +87,9 @@ export function start() { // 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("*")) { + 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(",") } diff --git a/packages/opencode/test/altimate/native/offline-connections.test.ts b/packages/opencode/test/altimate/native/offline-connections.test.ts index c859f1b505..3a83c0c5f0 100644 --- a/packages/opencode/test/altimate/native/offline-connections.test.ts +++ b/packages/opencode/test/altimate/native/offline-connections.test.ts @@ -4,9 +4,7 @@ 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 { dbtAdapterInternals, disposeDbtAdapter, getDbtAdapter } from "../../../src/altimate/native/connections/register" import { assertLocalDbt } from "../../../src/altimate/native/dbt/offline" -import { tmpdir } from "../../fixture/fixture" const envKeys = ["DBT_TARGET", "DBT_PROFILE", "DBT_PROFILES_DIR", "DBT_PROJECT_DIR", "ALTIMATE_OFFLINE"] let savedEnv: Record @@ -203,73 +201,6 @@ test("dbt finds the project from a subdirectory and reads profiles from the work } finally { await fs.rm(root, { recursive: true, force: true }) } }) -test.each([ - ["remote", "cached"], - ["local", "cached"], - ["remote", "starting"], -])("offline activation revalidates a %s dbt target while its adapter is %s", async (target, state) => { - await using project = await tmpdir() - await Bun.write(path.join(project.path, "dbt_project.yml"), "profile: test\n") - await Bun.write( - path.join(project.path, "profiles.yml"), - `test:\n target: ${target}\n outputs:\n local:\n type: duckdb\n path: ':memory:'\n remote:\n type: postgres\n host: example.com\n`, - ) - const creations: unknown[] = [] - let disposed = 0 - const online = { dispose: async () => void (disposed += 1) } - const offline = {} - const starting = Promise.withResolvers() - const finish = Promise.withResolvers() - - await disposeDbtAdapter() - dbtAdapterInternals.readConfig = async () => ({ projectRoot: project.path, dbtIntegration: "corecommand" }) - dbtAdapterInternals.create = async (_, options) => { - creations.push(options) - if (state === "starting") { - starting.resolve() - await finish.promise - } - return options?.offline ? offline : online - } - try { - if (state === "starting") { - const first = getDbtAdapter() - await starting.promise - process.env.ALTIMATE_OFFLINE = "1" - const both = Promise.allSettled([first, getDbtAdapter()]) - finish.resolve() - for (const result of await both) { - expect(result.status).toBe("rejected") - if (result.status === "rejected") expect(result.reason.message).toContain("Offline mode") - } - expect(creations).toHaveLength(1) - expect(disposed).toBe(1) - return - } - - expect(await getDbtAdapter()).toBe(online) - expect(await getDbtAdapter()).toBe(online) - expect(creations).toHaveLength(1) - process.env.ALTIMATE_OFFLINE = "1" - - if (target === "remote") { - await expect(getDbtAdapter()).rejects.toThrow("Offline mode") - expect(creations).toHaveLength(1) - } else { - expect(await Promise.all([getDbtAdapter(), getDbtAdapter()])).toEqual([offline, offline]) - expect(await getDbtAdapter()).toBe(offline) - expect(creations).toHaveLength(2) - expect(creations[1]).toMatchObject({ offline: true, profilesDir: project.path }) - } - expect(disposed).toBe(1) - } finally { - finish.resolve() - await disposeDbtAdapter() - delete dbtAdapterInternals.readConfig - delete dbtAdapterInternals.create - } -}) - test("dbt checks selected target and CLI overrides", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "offline-dbt-")) try { diff --git a/packages/opencode/test/altimate/registry-per-project.test.ts b/packages/opencode/test/altimate/registry-per-project.test.ts index f9c6144174..f192d63a71 100644 --- a/packages/opencode/test/altimate/registry-per-project.test.ts +++ b/packages/opencode/test/altimate/registry-per-project.test.ts @@ -261,65 +261,6 @@ describe("connectors are per project", () => { ]) }) - test("late offline activation closes a cached tunneled connector and keeps a local connector", async () => { - writeLocal(projectA, { - tunneled: sshStore("cached-offline", { path: "tunneled.sqlite" }), - local: { type: "sqlite", path: "local.sqlite", create: true }, - }) - await inProject(projectA, () => Registry.get("tunneled")) - const local = await inProject(projectA, () => Registry.get("local")) - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - await expect(inProject(projectA, () => Registry.get("tunneled"))).rejects.toThrow("Offline mode") - expect(ended("cached-offline")).toEqual([true]) - expect(await inProject(projectA, () => Registry.get("local"))).toBe(local) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }) - - test("late offline activation reopens cached DuckDB with extension autoinstall disabled", async () => { - writeLocal(projectA, { store: { type: "duckdb", path: "store.duckdb", create: true } }) - const previous = process.env.ALTIMATE_OFFLINE - const setting = "SELECT current_setting('autoinstall_known_extensions')" - delete process.env.ALTIMATE_OFFLINE - try { - const online = await inProject(projectA, () => Registry.get("store")) - expect((await online.execute(setting)).rows).toEqual([[true]]) - - process.env.ALTIMATE_OFFLINE = "1" - const [offline, concurrent] = await inProject(projectA, () => Promise.all([Registry.get("store"), Registry.get("store")])) - expect(offline).not.toBe(online) - expect(concurrent).toBe(offline) - expect((await offline.execute(setting)).rows).toEqual([[false]]) - expect(await inProject(projectA, () => Registry.get("store"))).toBe(offline) - } finally { - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }) - - test("a pending tunnel cannot publish a connector after offline activation", async () => { - writeLocal(projectA, { tunneled: sshStore("held-offline") }) - const pending = inProject(projectA, () => Registry.get("tunneled")) - await sshConnected("held-offline") - const previous = process.env.ALTIMATE_OFFLINE - process.env.ALTIMATE_OFFLINE = "1" - try { - await expect(inProject(projectA, () => Registry.get("tunneled"))).rejects.toThrow("Offline mode") - heldReady.get("held-offline")!() - await expect(pending).rejects.toThrow("Offline mode") - expect(ended("held-offline")).toEqual([true]) - } finally { - heldReady.get("held-offline")?.() - await pending.catch(() => {}) - if (previous === undefined) delete process.env.ALTIMATE_OFFLINE - else process.env.ALTIMATE_OFFLINE = previous - } - }) - test("a connect in flight when its project reloads is not cached over the reloaded state", async () => { writeLocal(projectA, { store: { type: "sqlite", path: "store.sqlite", create: true } }) const inflight = inProject(projectA, () => Registry.get("store")) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index f32e56f635..3d9036b613 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 first discovered in managed config", () => + 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( + "This project requests offline mode. Start Altimate Code with ALTIMATE_OFFLINE=1 or from the project directory.", + ) + 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/mcp/offline.test.ts b/packages/opencode/test/mcp/offline.test.ts index 9b25a3287d..dea7a1a2fa 100644 --- a/packages/opencode/test/mcp/offline.test.ts +++ b/packages/opencode/test/mcp/offline.test.ts @@ -119,6 +119,25 @@ test("the fetch guard allows loopback, refuses everything else and keeps the use }) }) +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 { From d0b20db254ac8550547a0506a918da9fa817cefe Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 13:06:11 -0800 Subject: [PATCH 72/72] fix(offline): honor managed config at startup Co-Authored-By: Codex --- docs/docs/configure/config.md | 2 +- packages/opencode/src/config/config.ts | 2 +- packages/opencode/src/config/offline.ts | 2 ++ packages/opencode/test/cli/run/offline.test.ts | 12 ++++++++---- packages/opencode/test/config/config.test.ts | 4 ++-- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 777af1f7d3..97e1fb3ceb 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -168,7 +168,7 @@ With offline mode off, nothing in this section applies and Altimate Code behaves ### Turn it on -Set `ALTIMATE_OFFLINE=1` before starting Altimate Code, or add `"offline": true` to a global or project configuration file (or `OPENCODE_CONFIG_CONTENT`). Altimate Code checks those files for the setting when it starts, so startup requests are covered too. If Altimate Code first sees `"offline": true` while loading organisation-managed configuration, remote (well-known) configuration, or the legacy TOML `config` file, it refuses to start and asks you to set `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. +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`. diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 2adcc52ad4..6494016e3b 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -57,7 +57,7 @@ import { makeRuntime } from "@/effect/run-service" // altimate_change start — offline mode must be active before config loading function requireOfflineStartup(offline: boolean | undefined) { if (offline === true && !Offline.enabled()) { - throw new Error("This project requests offline mode. Start Altimate Code with ALTIMATE_OFFLINE=1 or from the project directory.") + throw new Error("Configuration requests offline mode. Restart Altimate Code with ALTIMATE_OFFLINE=1.") } } // altimate_change end diff --git a/packages/opencode/src/config/offline.ts b/packages/opencode/src/config/offline.ts index b5da09654c..18efecd4f0 100644 --- a/packages/opencode/src/config/offline.ts +++ b/packages/opencode/src/config/offline.ts @@ -14,6 +14,7 @@ import { Flag, env, offlineModeEnabled as enabled } from "@opencode-ai/core/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 } @@ -61,6 +62,7 @@ async function findOptIn(directory: string): Promise { ...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 diff --git a/packages/opencode/test/cli/run/offline.test.ts b/packages/opencode/test/cli/run/offline.test.ts index 1585ddf296..5deaf146f6 100644 --- a/packages/opencode/test/cli/run/offline.test.ts +++ b/packages/opencode/test/cli/run/offline.test.ts @@ -57,7 +57,7 @@ async function networkSpawns(log: string) { async function fixture( snapshot: boolean, - configMode: boolean, + configMode: boolean | "managed", disableWorkspace: boolean, provider = "offline-test", ) { @@ -65,6 +65,7 @@ async function fixture( 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") @@ -86,7 +87,9 @@ async function fixture( mcp: { remoteFixture: { type: "remote", url: "https://mcp.test" } }, }), ) - if (configMode && !snapshot) + 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"), @@ -180,7 +183,7 @@ async function fixture( ), HOME: root, OPENCODE_TEST_HOME: root, - OPENCODE_TEST_MANAGED_CONFIG_DIR: path.join(root, "managed"), + 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"), @@ -216,7 +219,8 @@ for (const { scenario, snapshot, configMode, disableWorkspace } of [ 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 diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 3d9036b613..b9f5f0d184 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -1505,7 +1505,7 @@ it.instance("migrates legacy write tool to edit permission", () => // 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 first discovered in managed config", () => +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 @@ -1514,7 +1514,7 @@ it.instance("refuses offline mode first discovered in managed config", () => const error = yield* Config.use.get().pipe(Effect.catchDefect(Effect.succeed)) expect(error).toBeInstanceOf(Error) expect((error as Error).message).toBe( - "This project requests offline mode. Start Altimate Code with ALTIMATE_OFFLINE=1 or from the project directory.", + "Configuration requests offline mode. Restart Altimate Code with ALTIMATE_OFFLINE=1.", ) expect(process.env.ALTIMATE_OFFLINE).toBeUndefined() } finally {