Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/opencode/script/aws-node-resolve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// altimate_change - new file
//
// The release build bundles with the "browser" export condition, which the Solid TUI needs. Under it, the AWS SDK's
// and Smithy's packages resolve to their browser entries, where every node-only export is a stub:
// `@smithy/core/config` exports `parseKnownFiles = Symbol.for("node-only")`. `fromNodeProviderChain` reads the AWS
// config and credentials files through it, so every Amazon Bedrock request in a compiled binary failed with
// "parseKnownFiles is not a function", while source runs, which resolve the node entries, worked.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (does not block: predates this PR, developer-only, fine as a follow-up). "Source runs, which resolve the node entries, worked" holds for bun run src/index.ts, but not for bun dev. Both package.json:9 and packages/opencode/package.json:16 run bun run --conditions=browser ./src/index.ts, and at runtime that condition picks @smithy/core's browser entries too.

Repro with this PR's own fixture and a fake profile in scratch files (AWS_CONFIG_FILE, AWS_SHARED_CREDENTIALS_FILE, AWS_PROFILE=fake, scratch HOME), run from packages/opencode:

  • bun run test/fixture/aws-credential-chain.ts prints {"accessKeyId":"fake-access-key-id"}.
  • bun run --conditions=browser test/fixture/aws-credential-chain.ts throws TypeError: config.parseKnownFiles is not a function ... 'config.parseKnownFiles' is a Symbol.

So Bedrock is still broken under bun dev at this head. Suggest rewording the comment to "plain bun run source runs". A follow-up could fix the dev path, for example by preloading a runtime plugin that does the same resolution, or by dropping --conditions=browser from the dev scripts if the TUI no longer needs it. Upstream filed the same dev-script issue as anomalyco/opencode#40408.

//
// `awsNodeResolvePlugin` resolves those packages the way Node does and leaves the browser condition in place for
// everything else. `nodeOnlyStubInputs` is the build's check that no bundled module carries such a stub.
import fs from "fs"
import path from "path"
import type { BunPlugin } from "bun"

/** Packages that ship browser entries with node-only stubs. */
export const NODE_RESOLVED_PACKAGES = /^@(aws-sdk|smithy|aws-crypto)\//

export const awsNodeResolvePlugin: BunPlugin = {
name: "aws-node-resolve",
setup(build) {
build.onResolve({ filter: NODE_RESOLVED_PACKAGES }, (args) => ({
// The build script runs under Bun's own conditions (bun, node, import, require), never "browser".
path: Bun.resolveSync(args.path, path.dirname(args.importer)),
}))
},
}

const NODE_ONLY_STUB = Buffer.from('Symbol.for("node-only")')

/** How many node-only stubs a file carries. Any is a node-only path that can't work. */
export function nodeOnlyStubCount(bytes: Uint8Array): number {
const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
let count = 0
for (let at = buf.indexOf(NODE_ONLY_STUB); at !== -1; at = buf.indexOf(NODE_ONLY_STUB, at + 1)) count++

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🟠 MEDIUM] Using at + 1 in indexOf leads to unnecessary overlapping substring checks. Since the stub string does not overlap with itself, advancing the search index by the length of NODE_ONLY_STUB is more efficient.

Suggested change:

Suggested change
for (let at = buf.indexOf(NODE_ONLY_STUB); at !== -1; at = buf.indexOf(NODE_ONLY_STUB, at + 1)) count++
for (let at = buf.indexOf(NODE_ONLY_STUB); at !== -1; at = buf.indexOf(NODE_ONLY_STUB, at + NODE_ONLY_STUB.length)) count++

return count
}

/**
* The bundled modules, from a Bun.build metafile, whose source carries a node-only stub. The check reads the
* modules rather than the compiled binary: CHANGELOG.md, builtin skills and migrations are embedded verbatim and
* may quote the marker. A module it cannot read fails the check, so it never passes without having looked.
*/
export function nodeOnlyStubInputs(metafile: { inputs: Record<string, unknown> } | undefined): string[] {
if (!metafile) throw new Error("Bun.build returned no metafile, so the node-only stub check cannot run")
const inputs = Object.keys(metafile.inputs)
Comment on lines +44 to +45

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🟠 MEDIUM] For safety, it's recommended to defensively verify that metafile.inputs exists before passing it to Object.keys. If the metafile object returned by the build API is truthy but unexpectedly lacks the inputs property (e.g., due to Bun version changes or API anomalies), it will throw a TypeError.

Suggested change:

Suggested change
if (!metafile) throw new Error("Bun.build returned no metafile, so the node-only stub check cannot run")
const inputs = Object.keys(metafile.inputs)
if (!metafile || !metafile.inputs) throw new Error("Bun.build returned no metafile, so the node-only stub check cannot run")
const inputs = Object.keys(metafile.inputs)

if (inputs.length === 0) throw new Error("Bun.build's metafile lists no inputs, so the node-only stub check cannot run")
// Metafile inputs are relative to the build's working directory.
const unreadable = inputs.filter((input) => !fs.existsSync(path.resolve(input)))
if (unreadable.length > 0) {
throw new Error(
`The node-only stub check cannot read ${unreadable.length} bundled module(s) from ${process.cwd()}:\n` +
unreadable.join("\n"),
)
}
return inputs.filter((input) => nodeOnlyStubCount(fs.readFileSync(path.resolve(input))) > 0)
}
23 changes: 21 additions & 2 deletions packages/opencode/script/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import { Script } from "@opencode-ai/script"
import pkg from "../package.json"
import { walkInputs } from "./stamp-inputs"
import { assertUsableCatalog, catalogDiagnosticOrigin, formatCatalogSummary } from "./models-catalog"
// altimate_change start — resolve the AWS SDK's node entries under the browser condition (aws-node-resolve.ts)
import { awsNodeResolvePlugin, nodeOnlyStubInputs } from "./aws-node-resolve"
// altimate_change end
import { FreeTierUrl } from "../src/altimate/free/url"

// Python engine has been eliminated — all methods run natively in TypeScript.
Expand Down Expand Up @@ -621,10 +624,14 @@ for (const item of targets) {
},
}

await Bun.build({
// altimate_change — keep the result: its metafile feeds the node-only stub check below
const bundled = await Bun.build({
conditions: ["browser"],
tsconfig: "./tsconfig.json",
plugins: [solidPlugin, altimateCoreResolverPlugin],
// altimate_change start — awsNodeResolvePlugin: the AWS SDK's node entries, not its browser stubs
plugins: [solidPlugin, altimateCoreResolverPlugin, awsNodeResolvePlugin],
metafile: true,
// altimate_change end
sourcemap: "external",
// IMPORTANT: Without code splitting, Bun inlines dynamic import() targets
// into the main chunk. Any external require() in those targets will fail
Expand Down Expand Up @@ -661,6 +668,18 @@ for (const item of targets) {
},
})

// altimate_change start — refuse a build that bundled a node-only stub (aws-node-resolve.ts)
// A browser entry's stub in place of a node export fails only at run time, on the path that calls it (the
// Bedrock credential chain did).
const stubbed = nodeOnlyStubInputs(bundled.metafile)
Comment on lines +671 to +674

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🟠 MEDIUM] Bun.build does not throw an error if the build fails. If the build fails (e.g., due to a TypeScript error), bundled.success will be false and bundled.metafile may be undefined. Passing an undefined metafile to nodeOnlyStubInputs will throw a generic "Bun.build returned no metafile..." error, which masks the actual underlying compilation error.

Consider checking bundled.success before inspecting the metafile to provide clear error messages, similar to how it is handled in your test fixtures.

Suggested change:

Suggested change
// altimate_change start — refuse a build that bundled a node-only stub (aws-node-resolve.ts)
// A browser entry's stub in place of a node export fails only at run time, on the path that calls it (the
// Bedrock credential chain did).
const stubbed = nodeOnlyStubInputs(bundled.metafile)
if (!bundled.success) {
for (const log of bundled.logs) console.error(log)
throw new Error(`Build failed for ${name}`)
}
// altimate_change start — refuse a build that bundled a node-only stub (aws-node-resolve.ts)
// A browser entry's stub in place of a node export fails only at run time, on the path that calls it (the
// Bedrock credential chain did).
const stubbed = nodeOnlyStubInputs(bundled.metafile)

if (stubbed.length > 0) {
throw new Error(
`${name}: ${stubbed.length} bundled module(s) carry a Symbol.for("node-only") stub, so a package resolved to ` +
`its browser entry. Add it to NODE_RESOLVED_PACKAGES in script/aws-node-resolve.ts:\n${stubbed.join("\n")}`,
)
}
// altimate_change end

// Staging dir is no longer needed once Bun has embedded the shim + .node.
await $`rm -rf dist/${name}/.altimate-core-staged`

Expand Down
24 changes: 24 additions & 0 deletions packages/opencode/test/fixture/aws-credential-chain-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// altimate_change - new file
//
// Bundles aws-credential-chain.ts with the release build's resolution settings (the "browser" condition, and
// awsNodeResolvePlugin unless the mode is "plain"), embedding a note that quotes the stub marker the way build.ts
// embeds CHANGELOG.md. Prints the bundle's path and the bundled modules that carry a stub. Run in its own process
// by test/provider/aws-node-resolve.test.ts: a second Bun.build inside `bun test` fails reading files.
import path from "path"
import { awsNodeResolvePlugin, nodeOnlyStubInputs } from "../../script/aws-node-resolve"

const [outdir, mode] = process.argv.slice(2)
const out = await Bun.build({
entrypoints: [path.join(import.meta.dir, "aws-credential-chain.ts")],
outdir,
target: "bun",
conditions: ["browser"],
plugins: mode === "plain" ? [] : [awsNodeResolvePlugin],
define: { EMBEDDED_NOTE: JSON.stringify('A changelog line quoting Symbol.for("node-only").') },
metafile: true,
})
if (!out.success) {
for (const log of out.logs) console.error(log)
process.exit(1)
}
console.log(JSON.stringify({ file: out.outputs[0].path, stubInputs: nodeOnlyStubInputs(out.metafile) }))
12 changes: 12 additions & 0 deletions packages/opencode/test/fixture/aws-credential-chain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// altimate_change - new file
//
// Bundled by test/provider/aws-node-resolve.test.ts with the release build's resolution settings: resolves the
// AWS credential chain for AWS_PROFILE, as the Amazon Bedrock provider does, and prints the access key id.
import { fromNodeProviderChain } from "@aws-sdk/credential-providers"

// Defined by aws-credential-chain-build.ts; referenced so the bundle embeds it.
declare const EMBEDDED_NOTE: string
if (process.env.PRINT_EMBEDDED_NOTE) console.log(EMBEDDED_NOTE)

const credentials = await fromNodeProviderChain({ profile: process.env.AWS_PROFILE })()
console.log(JSON.stringify({ accessKeyId: credentials.accessKeyId }))
85 changes: 85 additions & 0 deletions packages/opencode/test/provider/aws-node-resolve.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// altimate_change - new file
//
// The release build bundles with the "browser" export condition, where the AWS SDK's node-only exports are stubs
// (`parseKnownFiles` is `Symbol.for("node-only")`), and every Bedrock request in a compiled binary failed with
// "parseKnownFiles is not a function". These tests bundle the credential chain the way the build does and run it
// offline against a fake profile in scratch files: no network, and the real ~/.aws is never read.
import { afterAll, describe, expect, test } from "bun:test"
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"
import os from "os"
import path from "path"
import { nodeOnlyStubCount, nodeOnlyStubInputs } from "../../script/aws-node-resolve"

const dir = mkdtempSync(path.join(os.tmpdir(), "aws-node-resolve-"))
afterAll(() => rmSync(dir, { recursive: true, force: true }))

const builder = path.join(import.meta.dir, "..", "fixture", "aws-credential-chain-build.ts")

/** Bundles the fixture in its own process, with or without awsNodeResolvePlugin. */
function bundle(mode: "plugin" | "plain"): { file: string; stubInputs: string[] } {
const run = Bun.spawnSync([process.execPath, builder, path.join(dir, mode), mode])
expect(run.stderr.toString()).toBe("")
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
expect(run.exitCode).toBe(0)
return JSON.parse(run.stdout.toString().trim())
}

/** Runs a bundled credential chain with a fake profile; only the scratch AWS files are visible to it. */
function resolveFakeProfile(file: string) {
const credentials = path.join(dir, "credentials")
const config = path.join(dir, "config")
writeFileSync(credentials, "[fake]\naws_access_key_id = fake-access-key-id\naws_secret_access_key = fake-secret\n")
writeFileSync(config, "[profile fake]\nregion = us-east-1\n")
const run = Bun.spawnSync([process.execPath, file], {
env: {
PATH: process.env.PATH ?? "",
HOME: dir,
AWS_PROFILE: "fake",
AWS_CONFIG_FILE: config,
AWS_SHARED_CREDENTIALS_FILE: credentials,
AWS_EC2_METADATA_DISABLED: "true",
},
})
return { exitCode: run.exitCode, stdout: run.stdout.toString(), stderr: run.stderr.toString() }
}

describe("the AWS credential chain under the release build's browser condition", () => {
test("with awsNodeResolvePlugin, no bundled module has a node-only stub and the bundle reads the profile", () => {
const { file, stubInputs } = bundle("plugin")
expect(stubInputs).toEqual([])
// The markers left are the embedded note's, which the check does not count as stubs.
expect(nodeOnlyStubCount(readFileSync(file))).toBeGreaterThan(0)
const run = resolveFakeProfile(file)
expect(run.stderr).not.toContain("parseKnownFiles")
expect(run.exitCode).toBe(0)
expect(JSON.parse(run.stdout.trim())).toEqual({ accessKeyId: "fake-access-key-id" })
}, 60_000)

test("without it, the same bundle gets the browser stubs and the chain fails as it did in the binary", () => {
const { file, stubInputs } = bundle("plain")
expect(stubInputs.length).toBeGreaterThan(0)
for (const input of stubInputs) expect(input).toMatch(/node_modules\/@(smithy|aws-sdk)\//)
const run = resolveFakeProfile(file)
expect(run.exitCode).not.toBe(0)
expect(run.stderr).toContain("parseKnownFiles is not a function")
}, 60_000)

test("the release build registers the plugin and checks its bundled modules for node-only stubs", () => {
const build = readFileSync(path.join(import.meta.dir, "..", "..", "script", "build.ts"), "utf8")
expect(build).toMatch(/plugins: \[[^\]]*\bawsNodeResolvePlugin\b[^\]]*\]/)
expect(build).toContain("metafile: true")
expect(build).toContain("nodeOnlyStubInputs(bundled.metafile)")
})

test("nodeOnlyStubCount counts every stub", () => {
const stub = 'Symbol.for("node-only")'
expect(nodeOnlyStubCount(Buffer.from(`a ${stub} b ${stub}${stub}`))).toBe(3)
expect(nodeOnlyStubCount(Buffer.from("leader-node-only function"))).toBe(0)
})

test("the module check fails rather than pass without reading every bundled module", () => {
expect(() => nodeOnlyStubInputs(undefined)).toThrow("no metafile")
expect(() => nodeOnlyStubInputs({ inputs: {} })).toThrow("lists no inputs")
const unreadable = path.relative(process.cwd(), path.join(dir, "not-on-disk.js"))
expect(() => nodeOnlyStubInputs({ inputs: { [unreadable]: {} } })).toThrow("cannot read 1 bundled module(s)")
})
})
Loading