From 04629f11f095567138343bbfacc3afe81db7e715 Mon Sep 17 00:00:00 2001 From: Lex Date: Thu, 13 Aug 2026 20:22:58 +0800 Subject: [PATCH 1/3] feat(core): add verified runtime assets --- CORRESPONDING_SOURCE.md | 21 + LICENSE-SCOPE.json | 44 ++ LICENSE-SCOPE.schema.json | 54 +++ NOTICE | 29 +- bun.lock | 1 + packages/core/package.json | 2 + packages/core/src/dag/core/graph.ts | 3 + packages/core/src/dag/core/replan.ts | 3 + .../core/src/dag/core/required-validator.ts | 3 + packages/core/src/dag/core/scheduling.ts | 3 + packages/core/src/dag/core/transitions.ts | 3 + packages/core/src/dag/core/types.ts | 3 + packages/core/src/dag/projector.ts | 3 + packages/core/src/dag/sql.ts | 3 + packages/core/src/dag/store.ts | 3 + packages/core/src/ripgrep/binary.ts | 133 +---- packages/core/src/runtime-asset/LICENSE | 235 +++++++++ .../core/src/runtime-asset/MODIFICATIONS.md | 32 ++ .../core/src/runtime-asset/SPDX-HEADER.txt | 2 + .../core/src/runtime-asset/catalog/ripgrep.ts | 89 ++++ packages/core/src/runtime-asset/index.ts | 456 ++++++++++++++++++ .../core/test/corresponding-source.test.ts | 77 +++ packages/core/test/license-scope.test.ts | 114 +++++ packages/core/test/ripgrep-binary.test.ts | 57 +++ .../core/test/runtime-asset-cache.test.ts | 168 +++++++ packages/core/test/runtime-asset.test.ts | 159 ++++++ packages/desktop/electron-builder.config.ts | 5 + packages/desktop/package.json | 11 +- packages/desktop/scripts/prebuild.ts | 9 + packages/desktop/scripts/runtime-assets.ts | 92 ++++ .../desktop/scripts/verify-runtime-assets.ts | 10 + packages/desktop/src/main/server.ts | 1 + packages/desktop/test/runtime-assets.test.ts | 25 + packages/opencode/script/prefetch-ripgrep.ts | 223 +++------ packages/opencode/src/dag/admission.ts | 3 + packages/opencode/src/dag/config.ts | 3 + packages/opencode/src/dag/dag.ts | 3 + packages/opencode/src/dag/model.ts | 3 + packages/opencode/src/dag/review-lifecycle.ts | 3 + packages/opencode/src/dag/runtime/capture.ts | 3 + packages/opencode/src/dag/runtime/eval.ts | 3 + packages/opencode/src/dag/runtime/loop.ts | 3 + packages/opencode/src/dag/runtime/recovery.ts | 3 + packages/opencode/src/dag/runtime/spawn.ts | 3 + .../src/dag/runtime/summary-publisher.ts | 3 + .../opencode/src/dag/templates/resolve.ts | 3 + .../opencode/src/dag/templates/sanitize.ts | 3 + packages/opencode/src/dag/workflows.ts | 3 + .../routes/instance/httpapi/groups/dag.ts | 3 + .../routes/instance/httpapi/handlers/dag.ts | 3 + packages/opencode/src/tool/workflow.ts | 3 + packages/schema/src/dag-event.ts | 3 + .../src/feature-plugins/sidebar/dag-panel.tsx | 3 + .../system/dag-inspector-utils.ts | 3 + .../feature-plugins/system/dag-inspector.tsx | 3 + script/check-license-scope.ts | 198 ++++++++ script/corresponding-source.ts | 168 +++++++ 57 files changed, 2220 insertions(+), 285 deletions(-) create mode 100644 CORRESPONDING_SOURCE.md create mode 100644 LICENSE-SCOPE.json create mode 100644 LICENSE-SCOPE.schema.json create mode 100644 packages/core/src/runtime-asset/LICENSE create mode 100644 packages/core/src/runtime-asset/MODIFICATIONS.md create mode 100644 packages/core/src/runtime-asset/SPDX-HEADER.txt create mode 100644 packages/core/src/runtime-asset/catalog/ripgrep.ts create mode 100644 packages/core/src/runtime-asset/index.ts create mode 100644 packages/core/test/corresponding-source.test.ts create mode 100644 packages/core/test/license-scope.test.ts create mode 100644 packages/core/test/ripgrep-binary.test.ts create mode 100644 packages/core/test/runtime-asset-cache.test.ts create mode 100644 packages/core/test/runtime-asset.test.ts create mode 100644 packages/desktop/scripts/runtime-assets.ts create mode 100644 packages/desktop/scripts/verify-runtime-assets.ts create mode 100644 packages/desktop/test/runtime-assets.test.ts create mode 100644 script/check-license-scope.ts create mode 100644 script/corresponding-source.ts diff --git a/CORRESPONDING_SOURCE.md b/CORRESPONDING_SOURCE.md new file mode 100644 index 0000000000..5fa8a1f644 --- /dev/null +++ b/CORRESPONDING_SOURCE.md @@ -0,0 +1,21 @@ +# Corresponding source + +Every OpenCode-GraphAgent binary release that contains AGPL-covered code is +paired with a source archive generated from the same Git commit by: + +```sh +bun run ./script/corresponding-source.ts --version --output +``` + +The archive contains all tracked source and build inputs, including +`package.json`, `bun.lock`, build scripts, `LICENSE`, `NOTICE`, and +`LICENSE-SCOPE.json`. The adjacent JSON manifest records the exact commit, +commit timestamp, required build inputs, archive filename, and SHA-256 digest. + +Install the Bun version declared by the root `packageManager` field, restore +dependencies from `bun.lock`, and run the package-specific build documented in +the repository. External signing keys, certificates, credentials, and ordinary +system tools are not part of the source archive. + +For an internal deployment, publish the archive, JSON manifest, and checksum +next to the binaries or at the source URL configured for that deployment. diff --git a/LICENSE-SCOPE.json b/LICENSE-SCOPE.json new file mode 100644 index 0000000000..dbda7c0f9a --- /dev/null +++ b/LICENSE-SCOPE.json @@ -0,0 +1,44 @@ +{ + "$schema": "./LICENSE-SCOPE.schema.json", + "schemaVersion": 1, + "defaultLicense": { + "spdx": "MIT", + "licenseFile": "LICENSE", + "copyright": "Copyright (c) 2025 opencode" + }, + "scopes": [ + { + "id": "dag-workflow-engine", + "name": "DAG workflow engine", + "status": "active", + "spdx": "AGPL-3.0-or-later", + "copyright": "Copyright (c) 2026 LeXwDeX", + "licenseFiles": ["packages/core/src/dag/LICENSE", "packages/opencode/src/dag/LICENSE"], + "paths": [ + "packages/core/src/dag/", + "packages/opencode/src/dag/", + "packages/opencode/src/tool/workflow.ts", + "packages/schema/src/dag-event.ts", + "packages/tui/src/feature-plugins/system/dag-inspector.tsx", + "packages/tui/src/feature-plugins/system/dag-inspector-utils.ts", + "packages/tui/src/feature-plugins/sidebar/dag-panel.tsx", + "packages/opencode/src/server/routes/instance/httpapi/groups/dag.ts", + "packages/opencode/src/server/routes/instance/httpapi/handlers/dag.ts" + ] + }, + { + "id": "portable-runtime", + "name": "Portable desktop runtime", + "status": "active", + "spdx": "AGPL-3.0-or-later", + "copyright": "Copyright (c) 2026 LeXwDeX", + "licenseFiles": ["packages/core/src/runtime-asset/LICENSE"], + "paths": [ + "packages/core/src/runtime-asset/", + "packages/opencode/script/prefetch-ripgrep.ts", + "packages/desktop/scripts/runtime-assets.ts", + "packages/desktop/scripts/verify-runtime-assets.ts" + ] + } + ] +} diff --git a/LICENSE-SCOPE.schema.json b/LICENSE-SCOPE.schema.json new file mode 100644 index 0000000000..6460640daf --- /dev/null +++ b/LICENSE-SCOPE.schema.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/LeXwDeX/opencode-graph-agent/blob/main/LICENSE-SCOPE.schema.json", + "title": "OpenCode-GraphAgent license scope manifest", + "type": "object", + "additionalProperties": false, + "required": ["schemaVersion", "defaultLicense", "scopes"], + "properties": { + "$schema": { "type": "string" }, + "schemaVersion": { "const": 1 }, + "defaultLicense": { "$ref": "#/$defs/license" }, + "scopes": { + "type": "array", + "items": { "$ref": "#/$defs/scope" }, + "minItems": 1 + } + }, + "$defs": { + "license": { + "type": "object", + "additionalProperties": false, + "required": ["spdx", "licenseFile", "copyright"], + "properties": { + "spdx": { "type": "string", "minLength": 1 }, + "licenseFile": { "type": "string", "minLength": 1 }, + "copyright": { "type": "string", "minLength": 1 } + } + }, + "scope": { + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "status", "spdx", "copyright", "licenseFiles", "paths"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }, + "name": { "type": "string", "minLength": 1 }, + "status": { "enum": ["active", "planned"] }, + "spdx": { "const": "AGPL-3.0-or-later" }, + "copyright": { "type": "string", "minLength": 1 }, + "licenseFiles": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "minItems": 1, + "uniqueItems": true + }, + "paths": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "minItems": 1, + "uniqueItems": true + } + } + } + } +} diff --git a/NOTICE b/NOTICE index 1d067dbb89..a0d1755d9f 100644 --- a/NOTICE +++ b/NOTICE @@ -7,6 +7,10 @@ an AI coding agent. It is not affiliated with or endorsed by the OpenCode team. License boundaries ------------------ +The machine-readable source of truth for these boundaries is +`./LICENSE-SCOPE.json`. The human-readable paths below use the same values and +are checked for consistency in CI. + 1. Upstream opencode code (the vast majority of this repository) License: MIT @@ -17,14 +21,15 @@ License boundaries are minor patches to upstream files (bug fixes, localization fixes, hook system, tool improvements), remains under the upstream MIT license. -2. DAG workflow engine (self-developed by the fork author) +2. Self-developed AGPL modules License: GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later) Text: ./packages/core/src/dag/LICENSE ./packages/opencode/src/dag/LICENSE + ./packages/core/src/runtime-asset/LICENSE Copyright (c) 2026 LeXwDeX - Covered directories and files: + 2.1 DAG workflow engine (active) - packages/core/src/dag/ DAG core: state machine, dependency graph, scheduling, event projection, @@ -42,11 +47,23 @@ License boundaries - packages/opencode/src/server/routes/instance/httpapi/groups/dag.ts - packages/opencode/src/server/routes/instance/httpapi/handlers/dag.ts DAG HTTP API routes - - .opencode/dag-prompts/ DAG node prompt templates + 2.2 Portable desktop runtime (active) + + - packages/core/src/runtime-asset/ Runtime asset discovery, bundled + assets, verified cache, internal + mirrors, and public fallback + - packages/opencode/script/prefetch-ripgrep.ts + Verified ripgrep release prefetch + for distributable artifacts + - packages/desktop/scripts/runtime-assets.ts + - packages/desktop/scripts/verify-runtime-assets.ts + Required desktop runtime asset + preparation and package gate - The AGPL applies to these files and to derivative works of them, including - network-server deployments. Using the rest of the repository without the - DAG engine is governed by the MIT license alone. + The AGPL applies to these paths and to derivative works of them, including + network-server deployments. Files outside the scopes recorded in + `LICENSE-SCOPE.json` remain under their existing licenses unless they carry + an explicit license notice that says otherwise. When a file under an AGPL-covered directory imports MIT-licensed upstream modules, the upstream modules remain MIT; only the AGPL-covered files and diff --git a/bun.lock b/bun.lock index 2c045542f4..a86571ba07 100644 --- a/bun.lock +++ b/bun.lock @@ -372,6 +372,7 @@ "@actions/artifact": "4.0.0", "@lydell/node-pty": "catalog:", "@opencode-ai/app": "workspace:*", + "@opencode-ai/core": "workspace:*", "@opencode-ai/ui": "workspace:*", "@sentry/solid": "catalog:", "@sentry/vite-plugin": "catalog:", diff --git a/packages/core/package.json b/packages/core/package.json index ad78990294..d30579d4c8 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -18,6 +18,8 @@ "exports": { "./session/runner": "./src/session/runner/index.ts", "./system-context": "./src/system-context/index.ts", + "./runtime-asset": "./src/runtime-asset/index.ts", + "./runtime-asset/catalog/*": "./src/runtime-asset/catalog/*.ts", "./dag/core/*": "./src/dag/core/*.ts", "./dag/*": "./src/dag/*.ts", "./*": "./src/*.ts" diff --git a/packages/core/src/dag/core/graph.ts b/packages/core/src/dag/core/graph.ts index 31cb026d56..baa6368d30 100644 --- a/packages/core/src/dag/core/graph.ts +++ b/packages/core/src/dag/core/graph.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG scheduling core — dependency graph. * diff --git a/packages/core/src/dag/core/replan.ts b/packages/core/src/dag/core/replan.ts index 08d839d83f..caca0e24b2 100644 --- a/packages/core/src/dag/core/replan.ts +++ b/packages/core/src/dag/core/replan.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG scheduling core — replan merge planning (D11, simplified model). * diff --git a/packages/core/src/dag/core/required-validator.ts b/packages/core/src/dag/core/required-validator.ts index c6f67ccf2d..551ed8b839 100644 --- a/packages/core/src/dag/core/required-validator.ts +++ b/packages/core/src/dag/core/required-validator.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG scheduling core — required-node validation. * diff --git a/packages/core/src/dag/core/scheduling.ts b/packages/core/src/dag/core/scheduling.ts index 7a988a8b34..9e17755ef2 100644 --- a/packages/core/src/dag/core/scheduling.ts +++ b/packages/core/src/dag/core/scheduling.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + import { DependencyGraph } from "./graph" export type SchedulingNodeStatus = "pending" | "running" | "satisfied" | "unsatisfied" | "skipped" diff --git a/packages/core/src/dag/core/transitions.ts b/packages/core/src/dag/core/transitions.ts index 6051098dfe..62137fa8da 100644 --- a/packages/core/src/dag/core/transitions.ts +++ b/packages/core/src/dag/core/transitions.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG scheduling core — transition-to-event mappings + status aggregation. * diff --git a/packages/core/src/dag/core/types.ts b/packages/core/src/dag/core/types.ts index f391dd6555..e74655d6c8 100644 --- a/packages/core/src/dag/core/types.ts +++ b/packages/core/src/dag/core/types.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG scheduling core — status enums, transition tables, and error types. * diff --git a/packages/core/src/dag/projector.ts b/packages/core/src/dag/projector.ts index 49b901b58d..ba9d76097a 100644 --- a/packages/core/src/dag/projector.ts +++ b/packages/core/src/dag/projector.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagProjector from "./projector" import { and, eq, inArray, sql } from "drizzle-orm" diff --git a/packages/core/src/dag/sql.ts b/packages/core/src/dag/sql.ts index eb70ca4008..9e6b9d80d0 100644 --- a/packages/core/src/dag/sql.ts +++ b/packages/core/src/dag/sql.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + import { sqliteTable, text, integer, index, primaryKey, uniqueIndex } from "drizzle-orm/sqlite-core" import { ProjectTable } from "../project/sql" import { SessionTable } from "../session/sql" diff --git a/packages/core/src/dag/store.ts b/packages/core/src/dag/store.ts index 711e3a3f19..52cb17e338 100644 --- a/packages/core/src/dag/store.ts +++ b/packages/core/src/dag/store.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagStore from "./store" import { and, asc, count, desc, eq, gt, inArray, or } from "drizzle-orm" diff --git a/packages/core/src/ripgrep/binary.ts b/packages/core/src/ripgrep/binary.ts index 9ac5d42e87..8e5b94f889 100644 --- a/packages/core/src/ripgrep/binary.ts +++ b/packages/core/src/ripgrep/binary.ts @@ -1,27 +1,9 @@ -import path from "path" -import { Context, Effect, Layer, Stream } from "effect" -import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" -import { ChildProcess } from "effect/unstable/process" -import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner" -import { CrossSpawnSpawner } from "../cross-spawn-spawner" +import { Context, Effect, Layer } from "effect" import { LayerNode } from "../effect/layer-node" -import { httpClient } from "../effect/layer-node-platform" -import { FSUtil } from "../fs-util" -import { Global } from "../global" -import { which } from "../util/which" +import { RuntimeAsset } from "../runtime-asset" +import { RipgrepAsset } from "../runtime-asset/catalog/ripgrep" export namespace RipgrepBinary { - const VERSION = "15.1.0" - const PLATFORM = { - "arm64-darwin": { platform: "aarch64-apple-darwin", extension: "tar.gz" }, - "arm64-linux": { platform: "aarch64-unknown-linux-gnu", extension: "tar.gz" }, - "x64-darwin": { platform: "x86_64-apple-darwin", extension: "tar.gz" }, - "x64-linux": { platform: "x86_64-unknown-linux-musl", extension: "tar.gz" }, - "arm64-win32": { platform: "aarch64-pc-windows-msvc", extension: "zip" }, - "ia32-win32": { platform: "i686-pc-windows-msvc", extension: "zip" }, - "x64-win32": { platform: "x86_64-pc-windows-msvc", extension: "zip" }, - } as const - interface Interface { readonly filepath: Effect.Effect } @@ -31,110 +13,25 @@ export namespace RipgrepBinary { export const layer = Layer.effect( Service, Effect.gen(function* () { - const fs = yield* FSUtil.Service - const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient) - const spawner = yield* ChildProcessSpawner - - const run = Effect.fnUntraced(function* (command: string, args: string[]) { - const handle = yield* spawner.spawn(ChildProcess.make(command, args, { extendEnv: true, stdin: "ignore" })) - const [stdout, stderr, code] = yield* Effect.all( - [ - Stream.mkString(Stream.decodeText(handle.stdout)), - Stream.mkString(Stream.decodeText(handle.stderr)), - handle.exitCode, - ], - { concurrency: "unbounded" }, - ) - return { stdout, stderr, code } - }, Effect.scoped) - - const extract = Effect.fnUntraced(function* ( - archive: string, - config: (typeof PLATFORM)[keyof typeof PLATFORM], - target: string, - ) { - const dir = yield* fs.makeTempDirectoryScoped({ directory: Global.Path.bin, prefix: "ripgrep-" }) - - if (config.extension === "zip") { - // Windows only (all win32 platforms in the PLATFORM table use zip). - // Resolve bsdtar by absolute path instead of relying on PATH: on - // GitHub Windows runners, Git for Windows' GNU tar - // (C:\Program Files\Git\usr\bin\tar.exe) shadows System32\tar.exe - // (bsdtar) in PATH, and GNU tar treats `C:\Users\...` as an SSH-style - // `host:path`, producing "Cannot connect to C: resolve failed". - // System32 bsdtar natively understands Windows drive paths. - // SystemRoot is virtually always set on Windows; fall back to the - // literal name only if it is somehow absent (cross-spawn will then - // do PATH lookup, which still works on stock Windows without Git). - const systemRoot = process.env.SystemRoot - const tarExe = systemRoot ? path.join(systemRoot, "System32", "tar.exe") : "tar" - const result = yield* run(tarExe, ["-xf", archive, "-C", dir]) - if (result.code !== 0) - throw new Error( - result.stderr.trim() || result.stdout.trim() || `ripgrep extraction failed with code ${result.code}`, - ) - } - - if (config.extension === "tar.gz") { - const result = yield* run("tar", ["-xzf", archive, "-C", dir]) - if (result.code !== 0) - throw new Error( - result.stderr.trim() || result.stdout.trim() || `ripgrep extraction failed with code ${result.code}`, - ) - } - - const extracted = path.join( - dir, - `ripgrep-${VERSION}-${config.platform}`, - process.platform === "win32" ? "rg.exe" : "rg", - ) - if (!(yield* fs.isFile(extracted))) throw new Error(`ripgrep archive did not contain executable: ${extracted}`) - - yield* fs.copyFile(extracted, target) - if (process.platform !== "win32") yield* fs.chmod(target, 0o755) - }, Effect.scoped) + const runtime = yield* RuntimeAsset.Service return Service.of({ filepath: yield* Effect.cached( - Effect.gen(function* () { - const system = yield* Effect.sync(() => which(process.platform === "win32" ? "rg.exe" : "rg")) - if (system && (yield* fs.isFile(system).pipe(Effect.orDie))) return system - - const target = path.join(Global.Path.bin, `rg${process.platform === "win32" ? ".exe" : ""}`) - if (yield* fs.isFile(target).pipe(Effect.orDie)) return target - - const platformKey = `${process.arch}-${process.platform}` as keyof typeof PLATFORM - const config = PLATFORM[platformKey] - if (!config) throw new Error(`unsupported platform for ripgrep: ${platformKey}`) - - const filename = `ripgrep-${VERSION}-${config.platform}.${config.extension}` - const url = `https://github.com/BurntSushi/ripgrep/releases/download/${VERSION}/${filename}` - const archive = path.join(Global.Path.bin, filename) - - yield* Effect.logInfo("downloading ripgrep", { url }) - yield* fs.ensureDir(Global.Path.bin).pipe(Effect.orDie) - const bytes = yield* HttpClientRequest.get(url).pipe( - http.execute, - Effect.flatMap((response) => response.arrayBuffer), - Effect.mapError((cause) => (cause instanceof Error ? cause : new Error(String(cause)))), - ) - if (bytes.byteLength === 0) throw new Error(`failed to download ripgrep from ${url}`) - - yield* fs.writeWithDirs(archive, new Uint8Array(bytes)) - yield* extract(archive, config, target) - yield* fs.remove(archive, { force: true }).pipe(Effect.ignore) - return target - }), + runtime + .resolve(RipgrepAsset.descriptor) + .pipe( + Effect.flatMap((result) => + result._tag === "Available" + ? Effect.succeed(result.path) + : Effect.fail(new Error(`ripgrep is unavailable: ${result.reason}`)), + ), + ), ), }) }), ) - export const defaultLayer = layer.pipe( - Layer.provide(FetchHttpClient.layer), - Layer.provide(FSUtil.defaultLayer), - Layer.provide(CrossSpawnSpawner.defaultLayer), - ) + export const defaultLayer = layer.pipe(Layer.provide(RuntimeAsset.defaultLayer)) - export const node = LayerNode.make(layer, [FSUtil.node, httpClient, CrossSpawnSpawner.node]) + export const node = LayerNode.make(layer, [RuntimeAsset.node]) } diff --git a/packages/core/src/runtime-asset/LICENSE b/packages/core/src/runtime-asset/LICENSE new file mode 100644 index 0000000000..0c97efd25b --- /dev/null +++ b/packages/core/src/runtime-asset/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/packages/core/src/runtime-asset/MODIFICATIONS.md b/packages/core/src/runtime-asset/MODIFICATIONS.md new file mode 100644 index 0000000000..a208447dbc --- /dev/null +++ b/packages/core/src/runtime-asset/MODIFICATIONS.md @@ -0,0 +1,32 @@ + + + +# RuntimeAsset modifications + +This module is self-developed for the OpenCode-GraphAgent fork and is licensed +under AGPL-3.0-or-later. Its full license text is in `LICENSE`. + +Every TypeScript source file in this directory starts with the two lines from +`SPDX-HEADER.txt`. Code copied or adapted from an upstream MIT file must retain +the upstream copyright and MIT permission notice; it must not be relabeled as +solely AGPL without a provenance review. + +Substantial changes are traceable through Git history and release metadata. +Each release source archive records the exact commit and build inputs. When a +change cannot be understood from its commit and path history, add a dated entry +below with the affected paths and a factual summary. + +## Entries + +- 2026-08-09: Reserved the module boundary for portable runtime asset + resolution, integrity verification, caching, and source selection. +- 2026-08-09: Added the public descriptor, policy, provenance, typed failure, + candidate resolution, Effect service, self-contained default layer, and + LayerNode interfaces. +- 2026-08-09: Added managed system/package/cache/mirror/public candidates, + pinned download verification, archive extraction, immutable cache metadata, + atomic publication, and process-local concurrent download deduplication. +- 2026-08-09: Added the pinned ripgrep 15.1.0 seven-platform catalog and + migrated the legacy binary service to the RuntimeAsset interface. +- 2026-08-09: Added desktop prebuild preparation, package verification, + electron-builder resource embedding, and packaged sidecar asset discovery. diff --git a/packages/core/src/runtime-asset/SPDX-HEADER.txt b/packages/core/src/runtime-asset/SPDX-HEADER.txt new file mode 100644 index 0000000000..a9cef60e15 --- /dev/null +++ b/packages/core/src/runtime-asset/SPDX-HEADER.txt @@ -0,0 +1,2 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/packages/core/src/runtime-asset/catalog/ripgrep.ts b/packages/core/src/runtime-asset/catalog/ripgrep.ts new file mode 100644 index 0000000000..a1f563759d --- /dev/null +++ b/packages/core/src/runtime-asset/catalog/ripgrep.ts @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { RuntimeAsset } from "../index" + +export namespace RipgrepAsset { + export const version = "15.1.0" + const release = `https://github.com/BurntSushi/ripgrep/releases/download/${version}` + + const target = (input: { + os: NodeJS.Platform + arch: string + platform: string + archive: "tar.gz" | "zip" + sha256: string + }): RuntimeAsset.Target => { + const executable = input.os === "win32" ? "rg.exe" : "rg" + const artifact = `ripgrep-${version}-${input.platform}.${input.archive}` + return { + os: input.os, + arch: input.arch, + executable, + artifact, + archive: input.archive, + entry: `ripgrep-${version}-${input.platform}/${executable}`, + sha256: input.sha256, + public: `${release}/${artifact}`, + } + } + + // Digests are the SHA-256 values published on the official GitHub 15.1.0 + // release assets. Keep the version, filename, entry, and digest together. + export const descriptor: RuntimeAsset.Descriptor = { + id: "ripgrep", + version, + required: true, + targets: [ + target({ + os: "darwin", + arch: "arm64", + platform: "aarch64-apple-darwin", + archive: "tar.gz", + sha256: "378e973289176ca0c6054054ee7f631a065874a352bf43f0fa60ef079b6ba715", + }), + target({ + os: "darwin", + arch: "x64", + platform: "x86_64-apple-darwin", + archive: "tar.gz", + sha256: "64811cb24e77cac3057d6c40b63ac9becf9082eedd54ca411b475b755d334882", + }), + target({ + os: "linux", + arch: "arm64", + platform: "aarch64-unknown-linux-gnu", + archive: "tar.gz", + sha256: "2b661c6ef508e902f388e9098d9c4c5aca72c87b55922d94abdba830b4dc885e", + }), + target({ + os: "linux", + arch: "x64", + platform: "x86_64-unknown-linux-musl", + archive: "tar.gz", + sha256: "1c9297be4a084eea7ecaedf93eb03d058d6faae29bbc57ecdaf5063921491599", + }), + target({ + os: "win32", + arch: "arm64", + platform: "aarch64-pc-windows-msvc", + archive: "zip", + sha256: "00d931fb5237c9696ca49308818edb76d8eb6fc132761cb2a1bd616b2df02f8e", + }), + target({ + os: "win32", + arch: "ia32", + platform: "i686-pc-windows-msvc", + archive: "zip", + sha256: "725be85a1e8f92878a548f40ee4f6df64bc93b809586462b3c6d884e1de1e83a", + }), + target({ + os: "win32", + arch: "x64", + platform: "x86_64-pc-windows-msvc", + archive: "zip", + sha256: "124510b94b6baa3380d051fdf4650eaa80a302c876d611e9dba0b2e18d87493a", + }), + ], + } +} diff --git a/packages/core/src/runtime-asset/index.ts b/packages/core/src/runtime-asset/index.ts new file mode 100644 index 0000000000..0a5b330d14 --- /dev/null +++ b/packages/core/src/runtime-asset/index.ts @@ -0,0 +1,456 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { existsSync } from "fs" +import { chmod, copyFile, mkdir, mkdtemp, rename, rm } from "fs/promises" +import path from "path" +import { Context, Effect, Layer } from "effect" +import { LayerNode } from "../effect/layer-node" +import { Global } from "../global" +import { which } from "../util/which" + +export namespace RuntimeAsset { + export const sources = ["system", "packaged", "cache", "mirror", "public"] as const + + export type Source = (typeof sources)[number] + export type Platform = { + readonly os: NodeJS.Platform + readonly arch: string + } + export type Target = Platform & { + readonly executable: string + readonly artifact?: string + readonly entry?: string + readonly sha256?: string + readonly executableSha256?: string + readonly archive?: "raw" | "tar.gz" | "zip" + readonly mirror?: string + readonly public?: string + } + export type Descriptor = { + readonly id: string + readonly version: string + readonly required: boolean + readonly targets: readonly Target[] + } + export type Policy = { + readonly sources?: readonly Source[] + } + export type Attempt = { + readonly source: Source + readonly reason: string + } + export type Available = { + readonly _tag: "Available" + readonly id: string + readonly version: string + readonly path: string + readonly source: Source + readonly platform: Platform + readonly sha256?: string + } + export type Unavailable = { + readonly _tag: "Unavailable" + readonly id: string + readonly version: string + readonly required: false + readonly platform: Platform + readonly reason: "unsupported-platform" | "sources-exhausted" + readonly attempts: readonly Attempt[] + } + export type Resolution = Available | Unavailable + export type CandidateRequest = { + readonly descriptor: Descriptor + readonly target: Target + readonly source: Source + } + export type CandidateResult = { + readonly path: string + } + export type Candidate = (request: CandidateRequest) => Effect.Effect + export type Candidates = Record + export type Fetch = (url: string, init: RequestInit) => Promise + export type ManagedInput = { + readonly platform: Platform + readonly cacheDirectory: string + readonly packagedDirectory?: string + readonly mirrorBaseURL?: string + readonly timeoutMs?: number + readonly fetch?: Fetch + } + export type Interface = { + readonly resolve: (descriptor: Descriptor, policy?: Policy) => Effect.Effect + } + + export class CandidateUnavailable extends Error { + readonly _tag = "CandidateUnavailable" + readonly reason: string + + constructor(input: { readonly reason: string }) { + super(input.reason) + this.reason = input.reason + } + } + + export class RequiredAssetUnavailable extends Error { + readonly _tag = "RequiredAssetUnavailable" + readonly id: string + readonly version: string + readonly platform: Platform + readonly reason: "unsupported-platform" | "sources-exhausted" + readonly attempts: readonly Attempt[] + + constructor(input: { + readonly id: string + readonly version: string + readonly platform: Platform + readonly reason: "unsupported-platform" | "sources-exhausted" + readonly attempts: readonly Attempt[] + }) { + super(`Required runtime asset is unavailable: ${input.id}@${input.version} (${input.reason})`) + this.id = input.id + this.version = input.version + this.platform = input.platform + this.reason = input.reason + this.attempts = input.attempts + } + } + + export class Service extends Context.Service()("@opencode/RuntimeAsset") {} + + export function make(input: { readonly platform: Platform; readonly candidates: Candidates }): Interface { + const finish = ( + descriptor: Descriptor, + reason: "unsupported-platform" | "sources-exhausted", + attempts: readonly Attempt[], + ): Effect.Effect => { + if (descriptor.required) { + return Effect.fail( + new RequiredAssetUnavailable({ + id: descriptor.id, + version: descriptor.version, + platform: input.platform, + reason, + attempts, + }), + ) + } + return Effect.succeed({ + _tag: "Unavailable", + id: descriptor.id, + version: descriptor.version, + required: false, + platform: input.platform, + reason, + attempts, + }) + } + + const resolve = (descriptor: Descriptor, policy?: Policy) => { + const target = descriptor.targets.find( + (candidate) => candidate.os === input.platform.os && candidate.arch === input.platform.arch, + ) + if (!target) return finish(descriptor, "unsupported-platform", []) + + const attempt = ( + pending: readonly Source[], + attempts: readonly Attempt[], + ): Effect.Effect => { + const source = pending[0] + if (!source) return finish(descriptor, "sources-exhausted", attempts) + return input.candidates[source]({ descriptor, target, source }).pipe( + Effect.map( + (result): Available => ({ + _tag: "Available", + id: descriptor.id, + version: descriptor.version, + path: result.path, + source, + platform: input.platform, + ...(target.sha256 ? { sha256: target.sha256 } : {}), + }), + ), + Effect.catchTag("CandidateUnavailable", (error) => + Effect.suspend(() => attempt(pending.slice(1), [...attempts, { source, reason: redact(error.reason) }])), + ), + ) + } + + return attempt(policy?.sources ?? sources, []) + } + + return { resolve } + } + + export function managed(input: ManagedInput) { + return make({ platform: input.platform, candidates: managedCandidates(input) }) + } + + export const layer = (input: { readonly platform: Platform; readonly candidates: Candidates }) => + Layer.succeed(Service, Service.of(make(input))) + + export const defaultLayer = Layer.succeed( + Service, + Service.of( + managed({ + platform: { os: process.platform, arch: process.arch }, + cacheDirectory: process.env.OPENCODE_RUNTIME_ASSET_CACHE ?? path.join(Global.Path.bin, "runtime-assets"), + packagedDirectory: process.env.OPENCODE_RUNTIME_ASSETS_DIR, + mirrorBaseURL: process.env.OPENCODE_RUNTIME_ASSET_MIRROR, + }), + ), + ) + + export const node = LayerNode.make(defaultLayer, []) + + function redact(reason: string) { + return reason.replace(/https?:\/\/[^\s)\]}]+/g, (value) => { + if (!URL.canParse(value)) return value + const url = new URL(value) + url.username = "" + url.password = "" + Array.from(url.searchParams.keys()) + .filter((key) => + /^(?:api[_-]?key|access[_-]?token|authorization|password|secret|sig(?:nature)?|token)$/i.test(key), + ) + .forEach((key) => url.searchParams.set(key, "REDACTED")) + return url.toString() + }) + } +} + +function managedCandidates(input: RuntimeAsset.ManagedInput): RuntimeAsset.Candidates { + const inFlight = new Map>() + const local = + (root: string | undefined, source: "packaged" | "cache"): RuntimeAsset.Candidate => + (request) => + Effect.tryPromise({ + try: () => { + if (!root) throw new Error(`${source} runtime asset directory is not configured`) + return source === "cache" ? verifiedCache(root, request) : verifiedPackaged(root, request) + }, + catch: unavailable, + }) + const network = + (source: "mirror" | "public"): RuntimeAsset.Candidate => + (request) => + Effect.tryPromise({ + try: () => { + const key = assetDirectory(input.cacheDirectory, request) + const active = inFlight.get(key) + if (active) return active + const pending = download(input, request, sourceURL(input, request, source)).finally(() => + inFlight.delete(key), + ) + inFlight.set(key, pending) + return pending + }, + catch: unavailable, + }) + + return { + system: (request) => + Effect.tryPromise({ + try: async () => { + const found = which(request.target.executable) + if (!found || !(await Bun.file(found).exists())) { + throw new Error(`system executable is unavailable: ${request.target.executable}`) + } + return { path: found } + }, + catch: unavailable, + }), + packaged: local(input.packagedDirectory, "packaged"), + cache: local(input.cacheDirectory, "cache"), + mirror: network("mirror"), + public: network("public"), + } +} + +async function verifiedPackaged(root: string, request: RuntimeAsset.CandidateRequest) { + const executable = assetPath(root, request) + if (!(await Bun.file(executable).exists())) throw new Error(`packaged executable is unavailable: ${executable}`) + if (request.target.executableSha256 && (await digestFile(executable)) !== request.target.executableSha256) { + throw new Error(`packaged executable digest mismatch: ${executable}`) + } + return { path: executable } +} + +async function verifiedCache(root: string, request: RuntimeAsset.CandidateRequest) { + const executable = assetPath(root, request) + const metadataFile = path.join(path.dirname(executable), "metadata.json") + if (!(await Bun.file(executable).exists()) || !(await Bun.file(metadataFile).exists())) { + throw new Error(`verified cache entry is unavailable: ${executable}`) + } + const value: unknown = await Bun.file(metadataFile).json() + if (!isRecord(value) || value.schemaVersion !== 1) throw new Error(`cache metadata is invalid: ${metadataFile}`) + if (request.target.sha256 && value.archiveSha256 !== request.target.sha256) { + throw new Error(`cache archive digest mismatch: ${executable}`) + } + if (typeof value.executableSha256 !== "string" || (await digestFile(executable)) !== value.executableSha256) { + throw new Error(`cache executable digest mismatch: ${executable}`) + } + return { path: executable } +} + +async function download( + input: RuntimeAsset.ManagedInput, + request: RuntimeAsset.CandidateRequest, + url: string, +): Promise { + if (!request.target.sha256 || !/^[a-f0-9]{64}$/i.test(request.target.sha256)) { + throw new Error(`network runtime asset requires a SHA-256 digest: ${request.descriptor.id}`) + } + const archiveSha256 = request.target.sha256.toLowerCase() + await mkdir(input.cacheDirectory, { recursive: true }) + const response = await (input.fetch ?? globalThis.fetch)(url, { + signal: AbortSignal.timeout(input.timeoutMs ?? 30_000), + }) + if (!response.ok) throw new Error(`download failed (${response.status}): ${url}`) + const bytes = new Uint8Array(await response.arrayBuffer()) + if (!bytes.byteLength) throw new Error(`download returned an empty asset: ${url}`) + if (digestBytes(bytes) !== archiveSha256) { + throw new Error(`download digest mismatch: ${url}`) + } + + const destination = assetDirectory(input.cacheDirectory, request) + await mkdir(path.dirname(destination), { recursive: true }) + const temporary = await mkdtemp(path.join(path.dirname(destination), `.${path.basename(destination)}-`)) + return (async () => { + const executable = path.join(temporary, executableName(request.target.executable)) + await materialize(bytes, request.target, temporary, executable) + if (process.platform !== "win32") await chmod(executable, 0o755) + const executableSha256 = await digestFile(executable) + if (request.target.executableSha256 && request.target.executableSha256 !== executableSha256) { + throw new Error(`downloaded executable digest mismatch: ${url}`) + } + await Bun.write( + path.join(temporary, "metadata.json"), + JSON.stringify( + { + schemaVersion: 1, + id: request.descriptor.id, + version: request.descriptor.version, + platform: request.target.os, + arch: request.target.arch, + archiveSha256, + executableSha256, + }, + null, + 2, + ) + "\n", + ) + await rm(destination, { recursive: true, force: true }) + await rename(temporary, destination) + return { path: path.join(destination, executableName(request.target.executable)) } + })().finally(() => rm(temporary, { recursive: true, force: true })) +} + +async function materialize(bytes: Uint8Array, target: RuntimeAsset.Target, temporary: string, executable: string) { + if ((target.archive ?? "raw") === "raw") { + await Bun.write(executable, bytes) + return + } + if (!target.entry) throw new Error(`archive entry is required for ${target.artifact ?? target.executable}`) + const entry = safeRelative(target.entry, "archive entry") + const archive = path.join(temporary, artifactName(target)) + const extracted = path.join(temporary, "extracted") + await mkdir(extracted, { recursive: true }) + await Bun.write(archive, bytes) + await command( + process.platform === "win32" && process.env.SystemRoot + ? path.join(process.env.SystemRoot, "System32", "tar.exe") + : "tar", + [target.archive === "tar.gz" ? "-xzf" : "-xf", archive, "-C", extracted], + ) + const source = path.resolve(extracted, entry) + if (source !== extracted && !source.startsWith(`${extracted}${path.sep}`)) + throw new Error(`archive entry escapes root: ${entry}`) + if (!(await Bun.file(source).exists())) throw new Error(`archive entry is missing: ${entry}`) + await copyFile(source, executable) +} + +function sourceURL( + input: RuntimeAsset.ManagedInput, + request: RuntimeAsset.CandidateRequest, + source: "mirror" | "public", +) { + const direct = request.target[source] + if (direct) return direct + if (source === "public" || !input.mirrorBaseURL) throw new Error(`${source} URL is not configured`) + if (!URL.canParse(input.mirrorBaseURL)) throw new Error(`runtime asset mirror URL is invalid: ${input.mirrorBaseURL}`) + const url = new URL(input.mirrorBaseURL) + url.pathname = [ + url.pathname.replace(/\/$/, ""), + request.descriptor.id, + request.descriptor.version, + `${request.target.os}-${request.target.arch}`, + artifactName(request.target), + ] + .map((segment) => segment.split("/").map(encodeURIComponent).join("/")) + .join("/") + return url.toString() +} + +function assetPath(root: string, request: RuntimeAsset.CandidateRequest) { + return path.join(assetDirectory(root, request), executableName(request.target.executable)) +} + +function assetDirectory(root: string, request: RuntimeAsset.CandidateRequest) { + const id = safeSegment(request.descriptor.id, "asset id") + const version = safeSegment(request.descriptor.version, "asset version") + const platform = safeSegment(`${request.target.os}-${request.target.arch}`, "asset platform") + const digest = request.target.sha256?.slice(0, 16).toLowerCase() ?? "unverified" + return path.join(root, id, version, `${platform}-${digest}`) +} + +function artifactName(target: RuntimeAsset.Target) { + return safeSegment(target.artifact ?? target.executable, "artifact filename") +} + +function executableName(executable: string) { + return safeSegment(executable, "executable filename") +} + +function safeSegment(value: string, name: string) { + if (!value || value === "." || value === ".." || path.basename(value) !== value) { + throw new Error(`${name} must be one path segment: ${value}`) + } + return value +} + +function safeRelative(value: string, name: string) { + const normalized = path.normalize(value) + if (path.isAbsolute(normalized) || normalized === ".." || normalized.startsWith(`..${path.sep}`)) { + throw new Error(`${name} must stay inside the archive: ${value}`) + } + return normalized +} + +async function command(executable: string, args: string[]) { + const child = Bun.spawn([executable, ...args], { stdout: "pipe", stderr: "pipe" }) + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]) + if (exitCode !== 0) { + throw new Error(`${executable} ${args.join(" ")} failed (${exitCode}): ${stderr.trim() || stdout.trim()}`) + } +} + +function unavailable(error: unknown) { + return new RuntimeAsset.CandidateUnavailable({ reason: error instanceof Error ? error.message : String(error) }) +} + +async function digestFile(file: string) { + return digestBytes(new Uint8Array(await Bun.file(file).arrayBuffer())) +} + +function digestBytes(bytes: Uint8Array) { + return new Bun.CryptoHasher("sha256").update(bytes).digest("hex") +} + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value) +} diff --git a/packages/core/test/corresponding-source.test.ts b/packages/core/test/corresponding-source.test.ts new file mode 100644 index 0000000000..08637b208b --- /dev/null +++ b/packages/core/test/corresponding-source.test.ts @@ -0,0 +1,77 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtemp, rm, unlink } from "fs/promises" +import os from "os" +import path from "path" +import { createCorrespondingSource, verifyCorrespondingSourceArtifacts } from "../../../script/corresponding-source" + +const roots: string[] = [] + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe("corresponding source", () => { + test("archives the exact committed tree with deterministic source metadata", async () => { + const root = await repository() + const result = await createCorrespondingSource({ + root, + output: path.join(root, "artifacts"), + version: "1.2.3-dev.4", + requiredFiles: ["LICENSE", "NOTICE", "bun.lock", "package.json"], + }) + const manifest = await Bun.file(result.manifest).json() + const entries = (await command(root, ["tar", "-tzf", result.archive])).split("\n") + + expect(result.sha256).toHaveLength(64) + expect(await Bun.file(result.checksum).text()).toBe(`${result.sha256} ${path.basename(result.archive)}\n`) + expect(manifest.commit).toBe(result.commit) + expect(manifest.archive.sha256).toBe(result.sha256) + expect(manifest.dependencyLocks).toEqual(["bun.lock"]) + expect(entries).toContain(`opencode-graphagent-1.2.3-dev.4-source-${result.commit.slice(0, 12)}/LICENSE`) + expect((await verifyCorrespondingSourceArtifacts(path.dirname(result.archive))).sha256).toBe(result.sha256) + }) + + test("rejects a release set with a missing source archive", async () => { + const root = await repository() + const result = await createCorrespondingSource({ + root, + output: path.join(root, "artifacts"), + version: "1.2.3", + requiredFiles: ["LICENSE", "NOTICE", "bun.lock", "package.json"], + }) + await unlink(result.archive) + + await expect(verifyCorrespondingSourceArtifacts(path.dirname(result.archive))).rejects.toThrow( + "Corresponding source archive is missing", + ) + }) +}) + +async function repository() { + const root = await mkdtemp(path.join(os.tmpdir(), "corresponding-source-")) + roots.push(root) + await Promise.all( + ["LICENSE", "NOTICE", "bun.lock", "package.json"].map((file) => Bun.write(path.join(root, file), `${file}\n`)), + ) + await git(root, ["init"]) + await git(root, ["config", "user.email", "test@example.com"]) + await git(root, ["config", "user.name", "Test User"]) + await git(root, ["add", "."]) + await git(root, ["commit", "-m", "test: source fixture"]) + return root +} + +async function git(root: string, args: string[]) { + return command(root, ["git", ...args]) +} + +async function command(root: string, args: string[]) { + const child = Bun.spawn(args, { cwd: root, stdout: "pipe", stderr: "pipe" }) + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]) + if (exitCode !== 0) throw new Error(`${args.join(" ")} failed: ${stderr}`) + return stdout.trim() +} diff --git a/packages/core/test/license-scope.test.ts b/packages/core/test/license-scope.test.ts new file mode 100644 index 0000000000..caf08044be --- /dev/null +++ b/packages/core/test/license-scope.test.ts @@ -0,0 +1,114 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { existsSync } from "fs" +import { mkdir, mkdtemp, rm } from "fs/promises" +import os from "os" +import path from "path" +import { z } from "zod" +import { checkLicenseScope } from "../../../script/check-license-scope" + +const root = path.join(import.meta.dir, "../../..") +const tempRoots: string[] = [] +const scopeSchema = z.object({ + id: z.string().min(1), + name: z.string().min(1), + status: z.enum(["active", "planned"]), + spdx: z.literal("AGPL-3.0-or-later"), + copyright: z.string().min(1), + licenseFiles: z.array(z.string().min(1)).min(1), + paths: z.array(z.string().min(1)).min(1), +}) +const manifestSchema = z.object({ + schemaVersion: z.literal(1), + defaultLicense: z.object({ + spdx: z.literal("MIT"), + licenseFile: z.string().min(1), + copyright: z.string().min(1), + }), + scopes: z.array(scopeSchema).min(1), +}) + +afterEach(async () => { + await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe("license scope manifest", () => { + test("uses MIT by default and AGPL only for explicit scopes", async () => { + const manifest = manifestSchema.parse(await Bun.file(path.join(root, "LICENSE-SCOPE.json")).json()) + + expect(existsSync(path.join(root, manifest.defaultLicense.licenseFile))).toBe(true) + expect(new Set(manifest.scopes.map((scope) => scope.id)).size).toBe(manifest.scopes.length) + expect(new Set(manifest.scopes.flatMap((scope) => scope.paths)).size).toBe( + manifest.scopes.flatMap((scope) => scope.paths).length, + ) + }) + + test("keeps NOTICE synchronized with every AGPL scope", async () => { + const manifest = manifestSchema.parse(await Bun.file(path.join(root, "LICENSE-SCOPE.json")).json()) + const notice = await Bun.file(path.join(root, "NOTICE")).text() + + for (const scope of manifest.scopes) { + expect(notice).toContain(scope.name) + expect(notice).toContain(scope.spdx) + expect(notice).toContain(scope.copyright) + for (const file of scope.licenseFiles) expect(existsSync(path.join(root, file))).toBe(true) + for (const file of scope.paths) expect(notice).toContain(file) + } + }) + + test("accepts the repository license boundary", async () => { + expect(await checkLicenseScope(root)).toEqual([]) + }) + + test("rejects an AGPL source without SPDX headers", async () => { + const fixture = await createFixture({ header: false, noticePath: true }) + expect((await checkLicenseScope(fixture)).map((issue) => issue.code)).toEqual([ + "missing-spdx-copyright", + "missing-spdx-license", + ]) + }) + + test("rejects an AGPL path missing from NOTICE", async () => { + const fixture = await createFixture({ header: true, noticePath: false }) + expect((await checkLicenseScope(fixture)).map((issue) => issue.code)).toEqual(["notice-missing-value"]) + }) +}) + +async function createFixture(input: { header: boolean; noticePath: boolean }) { + const root = await mkdtemp(path.join(os.tmpdir(), "license-scope-")) + tempRoots.push(root) + await mkdir(path.join(root, "src", "module"), { recursive: true }) + const copyright = "Copyright (c) 2026 LeXwDeX" + await Promise.all([ + Bun.write(path.join(root, "LICENSE"), "MIT\n"), + Bun.write(path.join(root, "AGPL.txt"), "AGPL-3.0-or-later\n"), + Bun.write( + path.join(root, "NOTICE"), + ["Fixture module", "AGPL-3.0-or-later", copyright, "AGPL.txt", input.noticePath ? "src/module/" : ""].join("\n"), + ), + Bun.write( + path.join(root, "LICENSE-SCOPE.json"), + JSON.stringify({ + schemaVersion: 1, + defaultLicense: { spdx: "MIT", licenseFile: "LICENSE", copyright: "Upstream" }, + scopes: [ + { + id: "fixture-module", + name: "Fixture module", + status: "active", + spdx: "AGPL-3.0-or-later", + copyright, + licenseFiles: ["AGPL.txt"], + paths: ["src/module/"], + }, + ], + }), + ), + Bun.write( + path.join(root, "src", "module", "index.ts"), + input.header + ? `// SPDX-FileCopyrightText: 2026 LeXwDeX\n// SPDX-License-Identifier: AGPL-3.0-or-later\n` + : "export const value = true\n", + ), + ]) + return root +} diff --git a/packages/core/test/ripgrep-binary.test.ts b/packages/core/test/ripgrep-binary.test.ts new file mode 100644 index 0000000000..ca95f7d95d --- /dev/null +++ b/packages/core/test/ripgrep-binary.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Layer } from "effect" +import { RipgrepBinary } from "@opencode-ai/core/ripgrep/binary" +import { RuntimeAsset } from "@opencode-ai/core/runtime-asset" +import { RipgrepAsset } from "@opencode-ai/core/runtime-asset/catalog/ripgrep" + +describe("RipgrepBinary", () => { + RuntimeAsset.sources.forEach((selected) => { + test(`falls back through RuntimeAsset candidates to ${selected}`, async () => { + const attempts: RuntimeAsset.Source[] = [] + const candidate = + (source: RuntimeAsset.Source): RuntimeAsset.Candidate => + () => { + attempts.push(source) + return source === selected + ? Effect.succeed({ path: `/${source}/rg` }) + : Effect.fail(new RuntimeAsset.CandidateUnavailable({ reason: `${source} unavailable` })) + } + const candidates: RuntimeAsset.Candidates = { + system: candidate("system"), + packaged: candidate("packaged"), + cache: candidate("cache"), + mirror: candidate("mirror"), + public: candidate("public"), + } + const layer = RipgrepBinary.layer.pipe( + Layer.provide( + RuntimeAsset.layer({ + platform: { os: "linux", arch: "x64" }, + candidates, + }), + ), + ) + const filepath = await Effect.runPromise( + Effect.gen(function* () { + return yield* (yield* RipgrepBinary.Service).filepath + }).pipe(Effect.provide(layer)), + ) + + expect(filepath).toBe(`/${selected}/rg`) + expect(attempts).toEqual(RuntimeAsset.sources.slice(0, RuntimeAsset.sources.indexOf(selected) + 1)) + }) + }) + + test("pins official archive metadata for every supported target", () => { + expect(RipgrepAsset.descriptor).toMatchObject({ id: "ripgrep", version: "15.1.0", required: true }) + expect(RipgrepAsset.descriptor.targets).toHaveLength(7) + expect( + RipgrepAsset.descriptor.targets.every( + (target) => + target.public?.includes(`/15.1.0/${target.artifact}`) && + target.entry?.endsWith(`/${target.executable}`) && + /^[a-f0-9]{64}$/.test(target.sha256 ?? ""), + ), + ).toBe(true) + }) +}) diff --git a/packages/core/test/runtime-asset-cache.test.ts b/packages/core/test/runtime-asset-cache.test.ts new file mode 100644 index 0000000000..7c9888ecb7 --- /dev/null +++ b/packages/core/test/runtime-asset-cache.test.ts @@ -0,0 +1,168 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdir, mkdtemp, rm } from "fs/promises" +import os from "os" +import path from "path" +import { Effect } from "effect" +import { RuntimeAsset } from "@opencode-ai/core/runtime-asset" + +const cleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())) +}) + +describe("RuntimeAsset managed candidates", () => { + test("rejects a download with the wrong SHA-256 before publishing cache files", async () => { + const root = await temporaryRoot() + const cache = path.join(root, "cache") + const runtime = RuntimeAsset.managed({ + platform: currentPlatform(), + cacheDirectory: cache, + fetch: () => Promise.resolve(new Response("corrupt")), + }) + + const result = await Effect.runPromise( + runtime.resolve(rawDescriptor("https://assets.example/tool", "0".repeat(64)), { sources: ["public"] }), + ) + + expect(result._tag).toBe("Unavailable") + expect(await Array.fromAsync(new Bun.Glob("**/tool").scan({ cwd: cache, onlyFiles: true }))).toEqual([]) + }) + + test("verifies, extracts, atomically caches, and reuses a tar.gz asset", async () => { + const root = await temporaryRoot() + const archive = await tarFixture(root) + const bytes = await Bun.file(archive).bytes() + const requests = { count: 0 } + const runtime = RuntimeAsset.managed({ + platform: currentPlatform(), + cacheDirectory: path.join(root, "cache"), + fetch: () => { + requests.count++ + return Promise.resolve(new Response(bytes)) + }, + }) + const asset = archiveDescriptor("https://assets.example/fixture.tar.gz", sha256(bytes)) + + const downloaded = await Effect.runPromise(runtime.resolve(asset, { sources: ["public"] })) + const cached = await Effect.runPromise(runtime.resolve(asset, { sources: ["cache"] })) + + expect(downloaded).toMatchObject({ _tag: "Available", source: "public" }) + expect(cached).toMatchObject({ _tag: "Available", source: "cache" }) + expect(downloaded._tag === "Available" ? await Bun.file(downloaded.path).text() : "").toBe("fixture executable\n") + expect(cached._tag === "Available" ? cached.path : "").toBe(downloaded._tag === "Available" ? downloaded.path : "") + expect(requests.count).toBe(1) + }) + + test("deduplicates concurrent downloads and never exposes a partial executable", async () => { + const root = await temporaryRoot() + const cache = path.join(root, "cache") + const requested = Promise.withResolvers() + const release = Promise.withResolvers() + const requests = { count: 0 } + const bytes = new TextEncoder().encode("executable") + const runtime = RuntimeAsset.managed({ + platform: currentPlatform(), + cacheDirectory: cache, + fetch: async () => { + requests.count++ + requested.resolve() + await release.promise + return new Response(bytes) + }, + }) + const asset = rawDescriptor("https://assets.example/tool", sha256(bytes)) + + const first = Effect.runPromise(runtime.resolve(asset, { sources: ["public"] })) + const second = Effect.runPromise(runtime.resolve(asset, { sources: ["public"] })) + await requested.promise + expect(await Array.fromAsync(new Bun.Glob("**/tool").scan({ cwd: cache, onlyFiles: true }))).toEqual([]) + release.resolve() + const results = await Promise.all([first, second]) + + expect(results.every((result) => result._tag === "Available")).toBe(true) + expect(requests.count).toBe(1) + expect(results[0]).toEqual(results[1]) + }) + + test("rejects a cache entry whose executable digest no longer matches metadata", async () => { + const root = await temporaryRoot() + const bytes = new TextEncoder().encode("original") + const runtime = RuntimeAsset.managed({ + platform: currentPlatform(), + cacheDirectory: path.join(root, "cache"), + fetch: () => Promise.resolve(new Response(bytes)), + }) + const asset = rawDescriptor("https://assets.example/tool", sha256(bytes)) + const downloaded = await Effect.runPromise(runtime.resolve(asset, { sources: ["public"] })) + if (downloaded._tag !== "Available") throw new Error("fixture download failed") + await Bun.write(downloaded.path, "tampered") + + const result = await Effect.runPromise(runtime.resolve(asset, { sources: ["cache"] })) + + expect(result._tag).toBe("Unavailable") + expect(result._tag === "Unavailable" ? result.attempts[0]?.reason : "").toContain("digest") + }) +}) + +function currentPlatform(): RuntimeAsset.Platform { + return { os: process.platform, arch: process.arch } +} + +function rawDescriptor(url: string, digest: string): RuntimeAsset.Descriptor { + return { + id: "fixture-raw", + version: "1.0.0", + required: false, + targets: [ + { + ...currentPlatform(), + executable: "tool", + artifact: "tool", + archive: "raw", + public: url, + sha256: digest, + }, + ], + } +} + +function archiveDescriptor(url: string, digest: string): RuntimeAsset.Descriptor { + return { + id: "fixture-archive", + version: "1.0.0", + required: false, + targets: [ + { + ...currentPlatform(), + executable: "tool", + artifact: "fixture.tar.gz", + archive: "tar.gz", + entry: "bin/tool", + public: url, + sha256: digest, + }, + ], + } +} + +async function temporaryRoot() { + const root = await mkdtemp(path.join(os.tmpdir(), "runtime-asset-")) + cleanups.push(() => rm(root, { recursive: true, force: true })) + return root +} + +async function tarFixture(root: string) { + const source = path.join(root, "source") + const archive = path.join(root, "fixture.tar.gz") + await mkdir(path.join(source, "bin"), { recursive: true }) + await Bun.write(path.join(source, "bin", "tool"), "fixture executable\n") + const child = Bun.spawn(["tar", "-czf", archive, "-C", source, "."], { stdout: "pipe", stderr: "pipe" }) + const [stderr, exitCode] = await Promise.all([new Response(child.stderr).text(), child.exited]) + if (exitCode !== 0) throw new Error(`tar fixture failed: ${stderr}`) + return archive +} + +function sha256(bytes: Uint8Array) { + return new Bun.CryptoHasher("sha256").update(bytes).digest("hex") +} diff --git a/packages/core/test/runtime-asset.test.ts b/packages/core/test/runtime-asset.test.ts new file mode 100644 index 0000000000..4322d68389 --- /dev/null +++ b/packages/core/test/runtime-asset.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Result } from "effect" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { RuntimeAsset } from "@opencode-ai/core/runtime-asset" + +describe("RuntimeAsset", () => { + test("uses the deterministic source order and reports provenance", async () => { + const attempts: RuntimeAsset.Source[] = [] + const runtime = RuntimeAsset.make({ + platform: { os: "linux", arch: "x64" }, + candidates: candidates({ + system: () => { + attempts.push("system") + return Effect.fail(new RuntimeAsset.CandidateUnavailable({ reason: "not installed" })) + }, + packaged: () => { + attempts.push("packaged") + return Effect.succeed({ path: "/app/assets/rg" }) + }, + cache: () => { + attempts.push("cache") + return Effect.succeed({ path: "/cache/rg" }) + }, + }), + }) + + const result = await Effect.runPromise(runtime.resolve(descriptor(false))) + + expect(result).toMatchObject({ + _tag: "Available", + path: "/app/assets/rg", + source: "packaged", + id: "ripgrep", + version: "15.1.0", + platform: { os: "linux", arch: "x64" }, + }) + expect(attempts).toEqual(["system", "packaged"]) + }) + + test("selects only the target matching the current platform", async () => { + const runtime = RuntimeAsset.make({ + platform: { os: "linux", arch: "x64" }, + candidates: candidates({ + system: (request) => Effect.succeed({ path: `/system/${request.target.executable}` }), + }), + }) + + const result = await Effect.runPromise(runtime.resolve(descriptor(false))) + + expect(result).toMatchObject({ _tag: "Available", path: "/system/rg", sha256: "linux-digest" }) + }) + + test("does not call mirror or public adapters when network sources are disabled", async () => { + const attempts: RuntimeAsset.Source[] = [] + const candidate = + (source: RuntimeAsset.Source): RuntimeAsset.Candidate => + () => { + attempts.push(source) + return source === "mirror" || source === "public" + ? Effect.succeed({ path: `/network/${source}/rg` }) + : Effect.fail(new RuntimeAsset.CandidateUnavailable({ reason: `${source} unavailable` })) + } + const runtime = RuntimeAsset.make({ + platform: { os: "linux", arch: "x64" }, + candidates: candidates({ + system: candidate("system"), + packaged: candidate("packaged"), + cache: candidate("cache"), + mirror: candidate("mirror"), + public: candidate("public"), + }), + }) + + const result = await Effect.runPromise( + runtime.resolve(descriptor(false), { sources: ["system", "packaged", "cache"] }), + ) + + expect(result._tag).toBe("Unavailable") + expect(attempts).toEqual(["system", "packaged", "cache"]) + }) + + test("returns typed unavailability for optional assets and fails required assets", async () => { + const runtime = RuntimeAsset.make({ + platform: { os: "linux", arch: "x64" }, + candidates: candidates({}), + }) + + const optional = await Effect.runPromise(runtime.resolve(descriptor(false))) + const required = await Effect.runPromise(runtime.resolve(descriptor(true)).pipe(Effect.result)) + + expect(optional).toMatchObject({ _tag: "Unavailable", id: "ripgrep", required: false }) + expect(optional._tag === "Unavailable" ? optional.attempts : []).toHaveLength(RuntimeAsset.sources.length) + expect(Result.isFailure(required)).toBe(true) + if (Result.isFailure(required)) { + expect(required.failure).toMatchObject({ _tag: "RequiredAssetUnavailable", id: "ripgrep" }) + } + }) + + test("redacts credentials and sensitive query values from diagnostics", async () => { + const runtime = RuntimeAsset.make({ + platform: { os: "linux", arch: "x64" }, + candidates: candidates({ + mirror: () => + Effect.fail( + new RuntimeAsset.CandidateUnavailable({ + reason: "download failed: https://user:secret@mirror.internal/rg?token=sensitive&file=rg", + }), + ), + }), + }) + + const result = await Effect.runPromise(runtime.resolve(descriptor(false), { sources: ["mirror"] })) + const reason = result._tag === "Unavailable" ? result.attempts[0]?.reason : "" + + expect(reason).toContain("mirror.internal/rg") + expect(reason).toContain("file=rg") + expect(reason).not.toContain("user") + expect(reason).not.toContain("secret") + expect(reason).not.toContain("sensitive") + }) + + test("builds both defaultLayer and LayerNode without ambient services", async () => { + const resolve = Effect.gen(function* () { + const runtime = yield* RuntimeAsset.Service + return yield* runtime.resolve(descriptor(false)) + }) + + const direct = await Effect.runPromise(resolve.pipe(Effect.provide(RuntimeAsset.defaultLayer))) + const node = await Effect.runPromise(resolve.pipe(Effect.provide(LayerNode.buildLayer(RuntimeAsset.node)))) + + expect(node).toEqual(direct) + }) +}) + +function descriptor(required: boolean): RuntimeAsset.Descriptor { + return { + id: "ripgrep", + version: "15.1.0", + required, + targets: [ + { os: "darwin", arch: "arm64", executable: "rg", sha256: "darwin-digest" }, + { os: "linux", arch: "x64", executable: "rg", sha256: "linux-digest" }, + ], + } +} + +function candidates(overrides: Partial): RuntimeAsset.Candidates { + const unavailable = + (source: RuntimeAsset.Source): RuntimeAsset.Candidate => + () => + Effect.fail(new RuntimeAsset.CandidateUnavailable({ reason: `${source} candidate is not configured` })) + return { + system: overrides.system ?? unavailable("system"), + packaged: overrides.packaged ?? unavailable("packaged"), + cache: overrides.cache ?? unavailable("cache"), + mirror: overrides.mirror ?? unavailable("mirror"), + public: overrides.public ?? unavailable("public"), + } +} diff --git a/packages/desktop/electron-builder.config.ts b/packages/desktop/electron-builder.config.ts index 23afe811c2..16ba64a93e 100644 --- a/packages/desktop/electron-builder.config.ts +++ b/packages/desktop/electron-builder.config.ts @@ -59,6 +59,11 @@ const getBase = (appId: string): Configuration => ({ to: "native/", filter: ["index.js", "index.d.ts", "build/Release/mac_window.node", "swift-build/**"], }, + { + from: "resources/runtime-assets/", + to: "runtime-assets/", + filter: ["**/*"], + }, ], mac: { category: "public.app-category.developer-tools", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 5a239863a8..7de87be5e9 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -16,10 +16,12 @@ "prebuild": "bun ./scripts/prebuild.ts", "build": "electron-vite build", "preview": "electron-vite preview", - "package": "electron-builder --config electron-builder.config.ts", - "package:mac": "electron-builder --mac --config electron-builder.config.ts", - "package:win": "electron-builder --win --config electron-builder.config.ts", - "package:linux": "electron-builder --linux --config electron-builder.config.ts", + "verify:runtime-assets": "bun ./scripts/verify-runtime-assets.ts", + "package": "bun run verify:runtime-assets && electron-builder --config electron-builder.config.ts", + "package:mac": "bun run verify:runtime-assets && electron-builder --mac --config electron-builder.config.ts", + "package:win": "bun run verify:runtime-assets && electron-builder --win --config electron-builder.config.ts", + "package:linux": "bun run verify:runtime-assets && electron-builder --linux --config electron-builder.config.ts", + "test": "bun test --only-failures", "native:build": "bun install --cwd native" }, "main": "./out/main/index.js", @@ -36,6 +38,7 @@ "devDependencies": { "@actions/artifact": "4.0.0", "@lydell/node-pty": "catalog:", + "@opencode-ai/core": "workspace:*", "@opencode-ai/app": "workspace:*", "@opencode-ai/ui": "workspace:*", "@sentry/solid": "catalog:", diff --git a/packages/desktop/scripts/prebuild.ts b/packages/desktop/scripts/prebuild.ts index 79b0e30afc..38ec25236b 100644 --- a/packages/desktop/scripts/prebuild.ts +++ b/packages/desktop/scripts/prebuild.ts @@ -1,10 +1,19 @@ #!/usr/bin/env bun import { $ } from "bun" +import path from "path" +import { prepareDesktopRuntimeAssets } from "./runtime-assets" import { resolveChannel } from "./utils" const channel = resolveChannel() await $`bun ./scripts/copy-icons.ts ${channel}` await $`bun ./scripts/copy-metainfo.ts ${channel}` +const runtimeAsset = await prepareDesktopRuntimeAssets({ + directory: path.resolve(import.meta.dir, "..", "resources", "runtime-assets"), + mirrorBaseURL: process.env.OPENCODE_RUNTIME_ASSET_MIRROR, + publicFallback: process.env.OPENCODE_RUNTIME_ASSET_DISABLE_PUBLIC !== "true", +}) +console.log(`[runtime-assets] prepared ${runtimeAsset.id}@${runtimeAsset.version}: ${runtimeAsset.path}`) + await $`cd ../opencode && bun script/build-node.ts` diff --git a/packages/desktop/scripts/runtime-assets.ts b/packages/desktop/scripts/runtime-assets.ts new file mode 100644 index 0000000000..621b4a39b7 --- /dev/null +++ b/packages/desktop/scripts/runtime-assets.ts @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + +import path from "path" +import { Effect } from "effect" +import { RuntimeAsset } from "@opencode-ai/core/runtime-asset" +import { RipgrepAsset } from "@opencode-ai/core/runtime-asset/catalog/ripgrep" + +export type DesktopRuntimeAssetsInput = { + readonly directory: string + readonly platform?: RuntimeAsset.Platform + readonly mirrorBaseURL?: string + readonly publicFallback?: boolean + readonly fetch?: RuntimeAsset.Fetch +} + +export async function prepareDesktopRuntimeAssets(input: DesktopRuntimeAssetsInput) { + const platform = input.platform ?? { os: process.platform, arch: process.arch } + const runtime = RuntimeAsset.managed({ + platform, + cacheDirectory: input.directory, + ...(input.mirrorBaseURL ? { mirrorBaseURL: input.mirrorBaseURL } : {}), + ...(input.fetch ? { fetch: input.fetch } : {}), + }) + const sources = RuntimeAsset.sources.filter( + (source) => + source === "cache" || + (source === "mirror" && !!input.mirrorBaseURL) || + (source === "public" && input.publicFallback !== false), + ) + const result = await Effect.runPromise(runtime.resolve(RipgrepAsset.descriptor, { sources })) + if (result._tag !== "Available") throw new Error(`required desktop runtime asset is unavailable: ${result.id}`) + await Bun.write( + path.join(input.directory, "manifest.json"), + JSON.stringify( + { + schemaVersion: 1, + assets: [ + { + id: result.id, + version: result.version, + os: platform.os, + arch: platform.arch, + path: path.relative(input.directory, result.path).replaceAll("\\", "/"), + source: result.source, + sha256: result.sha256, + }, + ], + }, + null, + 2, + ) + "\n", + ) + return verifyDesktopRuntimeAssets({ directory: input.directory, platform }) +} + +export async function verifyDesktopRuntimeAssets(input: { + readonly directory: string + readonly platform?: RuntimeAsset.Platform +}) { + const platform = input.platform ?? { os: process.platform, arch: process.arch } + const runtime = RuntimeAsset.managed({ platform, cacheDirectory: input.directory }) + const result = await Effect.runPromise( + runtime.resolve(RipgrepAsset.descriptor, { + sources: ["cache"], + }), + ) + if (result._tag !== "Available") throw new Error(`required desktop runtime asset is unavailable: ${result.id}`) + const executable = Bun.file(result.path) + if (!(await executable.exists()) || executable.size === 0) { + throw new Error(`required desktop runtime asset is empty: ${result.path}`) + } + const manifestFile = path.join(input.directory, "manifest.json") + const value: unknown = await Bun.file(manifestFile).json() + if (!isRecord(value) || value.schemaVersion !== 1 || !Array.isArray(value.assets)) { + throw new Error(`desktop runtime asset manifest is invalid: ${manifestFile}`) + } + const entry = value.assets.find( + (value) => + isRecord(value) && + value.id === RipgrepAsset.descriptor.id && + value.version === RipgrepAsset.descriptor.version && + value.os === platform.os && + value.arch === platform.arch, + ) + if (!entry) throw new Error(`desktop runtime asset manifest is missing ripgrep for ${platform.os}-${platform.arch}`) + return result +} + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value) +} diff --git a/packages/desktop/scripts/verify-runtime-assets.ts b/packages/desktop/scripts/verify-runtime-assets.ts new file mode 100644 index 0000000000..a10225027a --- /dev/null +++ b/packages/desktop/scripts/verify-runtime-assets.ts @@ -0,0 +1,10 @@ +#!/usr/bin/env bun +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + +import path from "path" +import { verifyDesktopRuntimeAssets } from "./runtime-assets" + +const directory = path.resolve(import.meta.dir, "..", "resources", "runtime-assets") +const result = await verifyDesktopRuntimeAssets({ directory }) +console.log(`[runtime-assets] verified ${result.id}@${result.version}: ${result.path}`) diff --git a/packages/desktop/src/main/server.ts b/packages/desktop/src/main/server.ts index b213dbc82a..9a793ca5e9 100644 --- a/packages/desktop/src/main/server.ts +++ b/packages/desktop/src/main/server.ts @@ -213,6 +213,7 @@ function createSidecarEnv(): Record { ) delete env.DEBUG if (process.platform === "linux") delete env.LD_PRELOAD + if (app.isPackaged) env.OPENCODE_RUNTIME_ASSETS_DIR = join(process.resourcesPath, "runtime-assets") if (!app.isPackaged) env.OPENCODE_DISABLE_CHANNEL_DB = "1" return env } diff --git a/packages/desktop/test/runtime-assets.test.ts b/packages/desktop/test/runtime-assets.test.ts new file mode 100644 index 0000000000..784a2545bb --- /dev/null +++ b/packages/desktop/test/runtime-assets.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtemp, rm } from "fs/promises" +import os from "os" +import path from "path" +import { verifyDesktopRuntimeAssets } from "../scripts/runtime-assets" + +const roots: string[] = [] + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe("desktop runtime assets", () => { + test("fails packaging verification when required ripgrep is missing", async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), "desktop-runtime-assets-")) + roots.push(directory) + + await expect( + verifyDesktopRuntimeAssets({ + directory, + platform: { os: "linux", arch: "x64" }, + }), + ).rejects.toThrow("Required runtime asset is unavailable: ripgrep@15.1.0") + }) +}) diff --git a/packages/opencode/script/prefetch-ripgrep.ts b/packages/opencode/script/prefetch-ripgrep.ts index fa955be124..28925a5dbb 100644 --- a/packages/opencode/script/prefetch-ripgrep.ts +++ b/packages/opencode/script/prefetch-ripgrep.ts @@ -1,173 +1,82 @@ #!/usr/bin/env bun -// -// Prefetch the ripgrep binary into every dist/opencode-/bin output produced -// by build.ts, so air-gapped users never hit the runtime download in -// packages/opencode/src/file/ripgrep.ts. -// -// Strategy: -// 1. Scan dist/opencode-* directories (created by build.ts). -// 2. Derive the upstream ripgrep PLATFORM key from each directory name. -// Several variants (baseline / musl) share the same rg binary, so we -// cache one download per rg-key under dist/.rg-cache/. -// 3. Extract rg (or rg.exe) into each dist/opencode-/bin/, where -// opencode's which("rg") step picks it up before any network fallback. -// -// Usage: -// bun run script/prefetch-ripgrep.ts # all platforms in dist/ -// bun run script/prefetch-ripgrep.ts --only # one directory only -// bun run script/prefetch-ripgrep.ts --version 15.1.0 -// -// Exit codes: -// 0 success / 1 fatal error / 2 no matching dist directories found. +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later -import { $ } from "bun" import fs from "fs" import path from "path" -import { fileURLToPath } from "url" +import { Effect } from "effect" +import { RuntimeAsset } from "@opencode-ai/core/runtime-asset" +import { RipgrepAsset } from "@opencode-ai/core/runtime-asset/catalog/ripgrep" -const __filename = fileURLToPath(import.meta.url) -const __dirname = path.dirname(__filename) -const pkgDir = path.resolve(__dirname, "..") - -// Keep in sync with packages/opencode/src/file/ripgrep.ts -const DEFAULT_VERSION = "15.1.0" -const PLATFORM = { - "arm64-darwin": { platform: "aarch64-apple-darwin", extension: "tar.gz" }, - "arm64-linux": { platform: "aarch64-unknown-linux-gnu", extension: "tar.gz" }, - "x64-darwin": { platform: "x86_64-apple-darwin", extension: "tar.gz" }, - "x64-linux": { platform: "x86_64-unknown-linux-musl", extension: "tar.gz" }, - "arm64-win32": { platform: "aarch64-pc-windows-msvc", extension: "zip" }, - "ia32-win32": { platform: "i686-pc-windows-msvc", extension: "zip" }, - "x64-win32": { platform: "x86_64-pc-windows-msvc", extension: "zip" }, -} as const - -type RgKey = keyof typeof PLATFORM - -const args = process.argv.slice(2) -const versionFlag = args.indexOf("--version") -const version = versionFlag >= 0 ? args[versionFlag + 1] : DEFAULT_VERSION -const onlyFlag = args.indexOf("--only") -const only = onlyFlag >= 0 ? args[onlyFlag + 1] : undefined - -const distDir = path.join(pkgDir, "dist") -if (!fs.existsSync(distDir)) { - console.error(`[prefetch-ripgrep] no dist/ directory at ${distDir}; build first.`) - process.exit(2) +const packageDirectory = path.resolve(import.meta.dir, "..") +const arguments_ = process.argv.slice(2) +const versionIndex = arguments_.indexOf("--version") +const requestedVersion = versionIndex === -1 ? undefined : arguments_[versionIndex + 1] +if (requestedVersion && requestedVersion !== RipgrepAsset.version) { + throw new Error(`ripgrep version is pinned to ${RipgrepAsset.version}; requested ${requestedVersion}`) } +const onlyIndex = arguments_.indexOf("--only") +const only = onlyIndex === -1 ? undefined : arguments_[onlyIndex + 1] +if (onlyIndex !== -1 && !only) throw new Error("--only requires a dist directory name") -const dirs = fs - .readdirSync(distDir, { withFileTypes: true }) - .filter((e) => e.isDirectory() && e.name.startsWith("opencode-")) - .map((e) => e.name) - .filter((name) => (only ? name === only : true)) - -if (dirs.length === 0) { - console.error(`[prefetch-ripgrep] no opencode-* directories under ${distDir}.`) +const distDirectory = path.join(packageDirectory, "dist") +if (!fs.existsSync(distDirectory)) { + console.error(`[prefetch-ripgrep] no dist/ directory at ${distDirectory}; build first.`) process.exit(2) } -const cacheDir = path.join(distDir, ".rg-cache") -fs.mkdirSync(cacheDir, { recursive: true }) - -/** - * Map a build.ts output directory like "opencode-windows-x64-baseline" to the - * ripgrep PLATFORM key. The `baseline` / `musl` modifiers do not affect rg. - */ -function deriveRgKey(dirName: string): RgKey | undefined { - // dirName = opencode--[-modifier...] - const parts = dirName.split("-") - if (parts.length < 3) return undefined - const [, osTok, archTok] = parts - const os = osTok === "windows" ? "win32" : osTok - const arch = archTok - const key = `${arch}-${os}` as RgKey - return key in PLATFORM ? key : undefined +const directories = fs + .readdirSync(distDirectory, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && entry.name.startsWith("opencode-")) + .map((entry) => entry.name) + .filter((name) => !only || name === only) +if (!directories.length) { + console.error(`[prefetch-ripgrep] no opencode-* directories under ${distDirectory}.`) + process.exit(2) } -async function fetchArchive(rgKey: RgKey): Promise { - const cfg = PLATFORM[rgKey] - const filename = `ripgrep-${version}-${cfg.platform}.${cfg.extension}` - const cached = path.join(cacheDir, filename) - if (fs.existsSync(cached) && fs.statSync(cached).size > 0) { - console.log(`[prefetch-ripgrep] cache hit: ${filename}`) - return cached - } - const url = `https://github.com/BurntSushi/ripgrep/releases/download/${version}/${filename}` - console.log(`[prefetch-ripgrep] downloading ${url}`) - const res = await fetch(url, { redirect: "follow" }) - if (!res.ok) throw new Error(`download failed ${res.status} ${res.statusText}: ${url}`) - const buf = new Uint8Array(await res.arrayBuffer()) - if (buf.byteLength === 0) throw new Error(`empty archive: ${url}`) - fs.writeFileSync(cached, buf) - return cached -} +const cacheDirectory = path.join(distDirectory, ".rg-cache") +const runtimes = new Map() +const sources: RuntimeAsset.Source[] = process.env.OPENCODE_RUNTIME_ASSET_MIRROR + ? ["cache", "mirror", "public"] + : ["cache", "public"] +const results = await Promise.all( + directories.map(async (directory) => { + const platform = derivePlatform(directory) + if (!platform) return { directory, status: "skipped" as const } + const key = `${platform.os}-${platform.arch}` + const runtime = + runtimes.get(key) ?? + RuntimeAsset.managed({ + platform, + cacheDirectory, + mirrorBaseURL: process.env.OPENCODE_RUNTIME_ASSET_MIRROR, + }) + runtimes.set(key, runtime) + console.log(`[prefetch-ripgrep] ${directory} -> ${key}`) -async function extractRg(archive: string, rgKey: RgKey, targetBinDir: string): Promise { - const cfg = PLATFORM[rgKey] - const rgName = cfg.extension === "zip" ? "rg.exe" : "rg" - const targetPath = path.join(targetBinDir, rgName) - if (fs.existsSync(targetPath)) { - console.log(`[prefetch-ripgrep] rg already present at ${path.relative(pkgDir, targetPath)}`) - return - } - fs.mkdirSync(targetBinDir, { recursive: true }) - // Extract to a sibling temp dir, then copy. - // On Windows, Git Bash's cygwin tar treats `D:\foo` as a remote `host:path`, - // so spawn the Windows-native tar.exe (libarchive, accepts native paths and - // handles both .tar.gz and .zip) directly via Bun.spawnSync — bypassing the - // shell entirely. On POSIX, just use system tar the same way. - const tmp = path.join(cacheDir, `extract-${rgKey}`) - fs.rmSync(tmp, { recursive: true, force: true }) - fs.mkdirSync(tmp, { recursive: true }) - const tarBin = - process.platform === "win32" && fs.existsSync("C:\\Windows\\System32\\tar.exe") - ? "C:\\Windows\\System32\\tar.exe" - : "tar" - const proc = Bun.spawnSync({ - cmd: [tarBin, "-xf", archive, "-C", tmp], - stdout: "pipe", - stderr: "pipe", - }) - if (proc.exitCode !== 0) { - throw new Error( - `tar extract failed (exit ${proc.exitCode}) for ${archive}\nstderr: ${proc.stderr?.toString() ?? ""}`, - ) - } - // ripgrep archives extract to ripgrep--/rg(.exe) - const subdirs = fs.readdirSync(tmp, { withFileTypes: true }).filter((e) => e.isDirectory()) - let extractedRg: string | undefined - for (const d of subdirs) { - const candidate = path.join(tmp, d.name, rgName) - if (fs.existsSync(candidate)) { - extractedRg = candidate - break - } - } - if (!extractedRg) { - throw new Error(`rg binary not found inside archive ${archive}`) - } - fs.copyFileSync(extractedRg, targetPath) - if (cfg.extension !== "zip") fs.chmodSync(targetPath, 0o755) - fs.rmSync(tmp, { recursive: true, force: true }) - console.log(`[prefetch-ripgrep] wrote ${path.relative(pkgDir, targetPath)}`) -} + const resolved = await Effect.runPromise(runtime.resolve(RipgrepAsset.descriptor, { sources })) + if (resolved._tag !== "Available") throw new Error(`ripgrep unavailable for ${key}: ${resolved.reason}`) + const bin = path.join(distDirectory, directory, "bin") + const target = path.join(bin, path.basename(resolved.path)) + fs.mkdirSync(bin, { recursive: true }) + fs.copyFileSync(resolved.path, target) + if (platform.os !== "win32") fs.chmodSync(target, 0o755) + console.log(`[prefetch-ripgrep] wrote ${path.relative(packageDirectory, target)} from ${resolved.source}`) + return { directory, status: "injected" as const } + }), +) -let injected = 0 -const skipped: string[] = [] -for (const dirName of dirs) { - const rgKey = deriveRgKey(dirName) - if (!rgKey) { - skipped.push(`${dirName} (unsupported platform)`) - continue - } - console.log(`[prefetch-ripgrep] ${dirName} -> ${rgKey}`) - const archive = await fetchArchive(rgKey) - const binDir = path.join(distDir, dirName, "bin") - await extractRg(archive, rgKey, binDir) - injected++ -} +const injected = results.filter((result) => result.status === "injected") +const skipped = results.filter((result) => result.status === "skipped") +console.log(`[prefetch-ripgrep] done: ${injected.length} directory(ies) injected, ${skipped.length} skipped.`) +skipped.forEach((result) => console.log(` - skip ${result.directory} (unsupported platform)`)) -console.log(`[prefetch-ripgrep] done: ${injected} directory(ies) injected, ${skipped.length} skipped.`) -if (skipped.length) { - for (const s of skipped) console.log(` - skip ${s}`) +function derivePlatform(directory: string): RuntimeAsset.Platform | undefined { + const parts = directory.split("-") + const os = parts[1] === "windows" ? "win32" : parts[1] + const arch = parts[2] + if (os !== "darwin" && os !== "linux" && os !== "win32") return + if (!arch || !RipgrepAsset.descriptor.targets.some((target) => target.os === os && target.arch === arch)) return + return { os, arch } } diff --git a/packages/opencode/src/dag/admission.ts b/packages/opencode/src/dag/admission.ts index fad431b196..68736d9f3c 100644 --- a/packages/opencode/src/dag/admission.ts +++ b/packages/opencode/src/dag/admission.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagAdmission from "./admission" import { Schema } from "effect" diff --git a/packages/opencode/src/dag/config.ts b/packages/opencode/src/dag/config.ts index 7be8c88300..78d330b8b2 100644 --- a/packages/opencode/src/dag/config.ts +++ b/packages/opencode/src/dag/config.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG defaults config — `dag.jsonc` beside the opencode config. * diff --git a/packages/opencode/src/dag/dag.ts b/packages/opencode/src/dag/dag.ts index ab03a1915d..d38dced3fb 100644 --- a/packages/opencode/src/dag/dag.ts +++ b/packages/opencode/src/dag/dag.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as Dag from "./dag" import { LayerNode } from "@opencode-ai/core/effect/layer-node" diff --git a/packages/opencode/src/dag/model.ts b/packages/opencode/src/dag/model.ts index 14224d151c..4a9612ffdb 100644 --- a/packages/opencode/src/dag/model.ts +++ b/packages/opencode/src/dag/model.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagModel from "./model" export type Ref = { diff --git a/packages/opencode/src/dag/review-lifecycle.ts b/packages/opencode/src/dag/review-lifecycle.ts index 5ee59bc9c4..b33c19dece 100644 --- a/packages/opencode/src/dag/review-lifecycle.ts +++ b/packages/opencode/src/dag/review-lifecycle.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagReviewLifecycle from "./review-lifecycle" import type { NodeConfig, WorkflowConfig } from "./dag" diff --git a/packages/opencode/src/dag/runtime/capture.ts b/packages/opencode/src/dag/runtime/capture.ts index ab15b09f87..8c0ec0572c 100644 --- a/packages/opencode/src/dag/runtime/capture.ts +++ b/packages/opencode/src/dag/runtime/capture.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG structured-output schema registry + validation. * diff --git a/packages/opencode/src/dag/runtime/eval.ts b/packages/opencode/src/dag/runtime/eval.ts index 2f9298f888..be1570cb9f 100644 --- a/packages/opencode/src/dag/runtime/eval.ts +++ b/packages/opencode/src/dag/runtime/eval.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG conditional-node evaluation + input_mapping resolution (task 2.16). * diff --git a/packages/opencode/src/dag/runtime/loop.ts b/packages/opencode/src/dag/runtime/loop.ts index ba06226b9c..5da1c80553 100644 --- a/packages/opencode/src/dag/runtime/loop.ts +++ b/packages/opencode/src/dag/runtime/loop.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagLoop from "./loop" import { Cause, Effect, Layer, Context, Stream, Semaphore, Fiber, Option, DateTime, Clock } from "effect" diff --git a/packages/opencode/src/dag/runtime/recovery.ts b/packages/opencode/src/dag/runtime/recovery.ts index a9bbc0848a..ff6a135860 100644 --- a/packages/opencode/src/dag/runtime/recovery.ts +++ b/packages/opencode/src/dag/runtime/recovery.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG crash recovery — EventV2-driven, no separate recovery table/scan. * diff --git a/packages/opencode/src/dag/runtime/spawn.ts b/packages/opencode/src/dag/runtime/spawn.ts index aa66f05966..5926e6011f 100644 --- a/packages/opencode/src/dag/runtime/spawn.ts +++ b/packages/opencode/src/dag/runtime/spawn.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG node spawn — reuses the `task` tool's spawn path. * diff --git a/packages/opencode/src/dag/runtime/summary-publisher.ts b/packages/opencode/src/dag/runtime/summary-publisher.ts index 091d3d7672..618d375762 100644 --- a/packages/opencode/src/dag/runtime/summary-publisher.ts +++ b/packages/opencode/src/dag/runtime/summary-publisher.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagSummaryPublisher from "./summary-publisher" import { Cause, Effect, Exit, Layer, Scope, Context } from "effect" diff --git a/packages/opencode/src/dag/templates/resolve.ts b/packages/opencode/src/dag/templates/resolve.ts index fc0b1c3fd4..a68356f486 100644 --- a/packages/opencode/src/dag/templates/resolve.ts +++ b/packages/opencode/src/dag/templates/resolve.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * DAG prompt-template resolver. * diff --git a/packages/opencode/src/dag/templates/sanitize.ts b/packages/opencode/src/dag/templates/sanitize.ts index 39d7964b24..536349d9a8 100644 --- a/packages/opencode/src/dag/templates/sanitize.ts +++ b/packages/opencode/src/dag/templates/sanitize.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * Prompt-injection sanitizer for DAG template input. * diff --git a/packages/opencode/src/dag/workflows.ts b/packages/opencode/src/dag/workflows.ts index b8b98d2ede..27ca8bc9fd 100644 --- a/packages/opencode/src/dag/workflows.ts +++ b/packages/opencode/src/dag/workflows.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * Workflow library — reusable start specs discovered by name. * diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/dag.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/dag.ts index 0f857c2285..34a18a8785 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/dag.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/dag.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + import { Schema } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { Authorization } from "../middleware/authorization" diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/dag.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/dag.ts index f85c23fc89..2a73c1afcc 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/dag.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/dag.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + import { Effect } from "effect" import { HttpApiBuilder } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" diff --git a/packages/opencode/src/tool/workflow.ts b/packages/opencode/src/tool/workflow.ts index f1a87358b0..a4b87ac69c 100644 --- a/packages/opencode/src/tool/workflow.ts +++ b/packages/opencode/src/tool/workflow.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + import { Tool } from "./tool" import { CommandPlugin } from "@opencode-ai/core/plugin/command" import { Effect, Option, Schema } from "effect" diff --git a/packages/schema/src/dag-event.ts b/packages/schema/src/dag-event.ts index a2a93832c0..d21987c6f5 100644 --- a/packages/schema/src/dag-event.ts +++ b/packages/schema/src/dag-event.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + export * as DagEvent from "./dag-event" import { Schema } from "effect" diff --git a/packages/tui/src/feature-plugins/sidebar/dag-panel.tsx b/packages/tui/src/feature-plugins/sidebar/dag-panel.tsx index b2832241a5..52ab53156c 100644 --- a/packages/tui/src/feature-plugins/sidebar/dag-panel.tsx +++ b/packages/tui/src/feature-plugins/sidebar/dag-panel.tsx @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** @jsxImportSource @opentui/solid */ import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui" import type { DagNode, DagWorkflowSummary } from "@opencode-ai/sdk/v2" diff --git a/packages/tui/src/feature-plugins/system/dag-inspector-utils.ts b/packages/tui/src/feature-plugins/system/dag-inspector-utils.ts index 7f5b58cf34..0fc612f54d 100644 --- a/packages/tui/src/feature-plugins/system/dag-inspector-utils.ts +++ b/packages/tui/src/feature-plugins/system/dag-inspector-utils.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** Pure topology helpers for the DAG inspector. Extracted for unit testing, * mirroring the diff-viewer-file-tree-utils pattern in this directory. */ diff --git a/packages/tui/src/feature-plugins/system/dag-inspector.tsx b/packages/tui/src/feature-plugins/system/dag-inspector.tsx index 9639a9458e..6a672515ea 100644 --- a/packages/tui/src/feature-plugins/system/dag-inspector.tsx +++ b/packages/tui/src/feature-plugins/system/dag-inspector.tsx @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** @jsxImportSource @opentui/solid */ import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui" import type { BuiltinTuiPlugin } from "../builtins" diff --git a/script/check-license-scope.ts b/script/check-license-scope.ts new file mode 100644 index 0000000000..0ea390cd9d --- /dev/null +++ b/script/check-license-scope.ts @@ -0,0 +1,198 @@ +import { existsSync } from "fs" +import path from "path" + +type LicenseScope = { + id: string + name: string + status: "active" | "planned" + spdx: "AGPL-3.0-or-later" + copyright: string + licenseFiles: string[] + paths: string[] +} + +type LicenseScopeManifest = { + schemaVersion: 1 + defaultLicense: { + spdx: "MIT" + licenseFile: string + copyright: string + } + scopes: LicenseScope[] +} + +export type LicenseScopeIssue = { + code: string + path?: string + message: string +} + +export async function checkLicenseScope(root: string) { + const manifest = parseManifest(await Bun.file(path.join(root, "LICENSE-SCOPE.json")).json()) + const notice = await Bun.file(path.join(root, "NOTICE")).text() + const allPaths = manifest.scopes.flatMap((scope) => scope.paths) + const duplicateIssues: LicenseScopeIssue[] = + new Set(allPaths).size === allPaths.length + ? [] + : [{ code: "duplicate-path", message: "LICENSE-SCOPE.json contains duplicate covered paths" }] + const defaultIssues = existsSync(path.join(root, manifest.defaultLicense.licenseFile)) + ? [] + : [ + { + code: "missing-default-license", + path: manifest.defaultLicense.licenseFile, + message: `Default MIT license file is missing: ${manifest.defaultLicense.licenseFile}`, + }, + ] + const scopeIssues = manifest.scopes.flatMap((scope) => { + const unsafePaths = [...scope.licenseFiles, ...scope.paths].filter( + (file) => path.isAbsolute(file) || file.split("/").includes(".."), + ) + const noticeValues = [scope.name, scope.spdx, scope.copyright, ...scope.licenseFiles, ...scope.paths] + return [ + ...unsafePaths.map((file) => ({ + code: "unsafe-path", + path: file, + message: `License scope path must be repository-relative: ${file}`, + })), + ...scope.licenseFiles + .filter((file) => !existsSync(path.join(root, file))) + .map((file) => ({ + code: "missing-license-file", + path: file, + message: `License text is missing: ${file}`, + })), + ...noticeValues + .filter((value) => !notice.includes(value)) + .map((value) => ({ + code: "notice-missing-value", + path: value, + message: `NOTICE does not contain license scope value: ${value}`, + })), + ...(scope.status === "active" + ? scope.paths + .filter((file) => !existsSync(path.join(root, file))) + .map((file) => ({ + code: "missing-active-path", + path: file, + message: `Active AGPL path is missing: ${file}`, + })) + : []), + ] + }) + const sourceIssues = ( + await Promise.all( + manifest.scopes + .filter((scope) => scope.status === "active") + .flatMap((scope) => scope.paths.map((file) => sourceFiles(root, file))) + .map(async (files) => + Promise.all( + (await files).map(async (file) => { + const header = (await Bun.file(file).text()).split("\n").slice(0, 8).join("\n") + const display = path.relative(root, file).split(path.sep).join("/") + return [ + ...(!header.includes("SPDX-FileCopyrightText: 2026 LeXwDeX") + ? [ + { + code: "missing-spdx-copyright", + path: display, + message: `AGPL source is missing its SPDX copyright header: ${display}`, + }, + ] + : []), + ...(!header.includes("SPDX-License-Identifier: AGPL-3.0-or-later") + ? [ + { + code: "missing-spdx-license", + path: display, + message: `AGPL source is missing its SPDX license header: ${display}`, + }, + ] + : []), + ] + }), + ), + ), + ) + ).flat(2) + + return [...duplicateIssues, ...defaultIssues, ...scopeIssues, ...sourceIssues] +} + +async function sourceFiles(root: string, file: string) { + const target = path.join(root, file) + if (!file.endsWith("/")) return /\.tsx?$/.test(file) && existsSync(target) ? [target] : [] + if (!existsSync(target)) return [] + return (await Array.fromAsync(new Bun.Glob("**/*").scan({ cwd: target, absolute: true, onlyFiles: true }))).filter( + (entry) => /\.tsx?$/.test(entry), + ) +} + +function parseManifest(value: unknown): LicenseScopeManifest { + const manifest = record(value, "license scope manifest") + if (manifest.schemaVersion !== 1) throw new Error("LICENSE-SCOPE.json schemaVersion must be 1") + const defaultLicense = record(manifest.defaultLicense, "defaultLicense") + if (defaultLicense.spdx !== "MIT") throw new Error("The default repository license must remain MIT") + if (!Array.isArray(manifest.scopes)) throw new Error("LICENSE-SCOPE.json scopes must be an array") + + return { + schemaVersion: 1, + defaultLicense: { + spdx: "MIT", + licenseFile: string(defaultLicense.licenseFile, "defaultLicense.licenseFile"), + copyright: string(defaultLicense.copyright, "defaultLicense.copyright"), + }, + scopes: manifest.scopes.map((value, index) => { + const scope = record(value, `scopes[${index}]`) + if (scope.status !== "active" && scope.status !== "planned") { + throw new Error(`scopes[${index}].status must be active or planned`) + } + if (scope.spdx !== "AGPL-3.0-or-later") { + throw new Error(`scopes[${index}].spdx must be AGPL-3.0-or-later`) + } + return { + id: string(scope.id, `scopes[${index}].id`), + name: string(scope.name, `scopes[${index}].name`), + status: scope.status, + spdx: "AGPL-3.0-or-later", + copyright: string(scope.copyright, `scopes[${index}].copyright`), + licenseFiles: strings(scope.licenseFiles, `scopes[${index}].licenseFiles`), + paths: strings(scope.paths, `scopes[${index}].paths`), + } + }), + } +} + +function record(value: unknown, name: string): Record { + if (!isRecord(value)) throw new Error(`${name} must be an object`) + return value +} + +function string(value: unknown, name: string) { + if (typeof value !== "string" || !value) throw new Error(`${name} must be a non-empty string`) + return value +} + +function strings(value: unknown, name: string) { + if (!Array.isArray(value) || !value.length || !value.every(isString)) { + throw new Error(`${name} must be a non-empty string array`) + } + return value.filter(isString) +} + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value) +} + +function isString(value: unknown): value is string { + return typeof value === "string" && !!value +} + +if (import.meta.main) { + const issues = await checkLicenseScope(path.join(import.meta.dir, "..")) + if (issues.length) { + console.error(issues.map((issue) => `[${issue.code}] ${issue.message}`).join("\n")) + process.exit(1) + } + console.log("License scope check passed") +} diff --git a/script/corresponding-source.ts b/script/corresponding-source.ts new file mode 100644 index 0000000000..a179119e86 --- /dev/null +++ b/script/corresponding-source.ts @@ -0,0 +1,168 @@ +import { existsSync } from "fs" +import { mkdir } from "fs/promises" +import path from "path" + +export const requiredSourceFiles = [ + "LICENSE", + "NOTICE", + "LICENSE-SCOPE.json", + "LICENSE-SCOPE.schema.json", + "CORRESPONDING_SOURCE.md", + "package.json", + "bun.lock", + "script/corresponding-source.ts", + "packages/opencode/script/build.ts", + "packages/desktop/scripts/prebuild.ts", + "packages/desktop/electron-builder.config.ts", +] as const + +export type CorrespondingSourceInput = { + root: string + output: string + version: string + ref?: string + allowDirty?: boolean + requiredFiles?: readonly string[] +} + +export async function createCorrespondingSource(input: CorrespondingSourceInput) { + if (!input.version.trim()) throw new Error("Corresponding source version is required") + + const root = path.resolve(input.root) + const requiredFiles = input.requiredFiles ?? requiredSourceFiles + if (requiredFiles.some((file) => path.isAbsolute(file) || file.split("/").includes(".."))) { + throw new Error("Corresponding source paths must be repository-relative") + } + + const commit = await git(root, ["rev-parse", "--verify", `${input.ref ?? "HEAD"}^{commit}`]) + if (!input.allowDirty && (await git(root, ["status", "--porcelain", "--untracked-files=no"]))) { + throw new Error("Tracked working tree changes must be committed before creating corresponding source") + } + await Promise.all(requiredFiles.map((file) => git(root, ["cat-file", "-e", `${commit}:${file}`]))) + + const output = path.resolve(input.output) + const version = input.version.replace(/[^0-9A-Za-z._-]/g, "-") + const base = `opencode-graphagent-${version}-source-${commit.slice(0, 12)}` + const archive = path.join(output, `${base}.tar.gz`) + await mkdir(output, { recursive: true }) + await command(root, ["git", "archive", "--format=tar.gz", `--prefix=${base}/`, `--output=${archive}`, commit]) + + const sha256 = await digest(archive) + const sourceDateEpoch = Number(await git(root, ["show", "-s", "--format=%ct", commit])) + const manifest = path.join(output, `${base}.source.json`) + await Bun.write( + manifest, + JSON.stringify( + { + schemaVersion: 1, + artifactKind: "agpl-corresponding-source", + project: "OpenCode-GraphAgent", + version: input.version, + commit, + generatedAt: new Date(sourceDateEpoch * 1000).toISOString(), + sourceDateEpoch, + archive: { + file: path.basename(archive), + sha256, + }, + requiredFiles, + dependencyLocks: ["bun.lock"], + licenseScope: "LICENSE-SCOPE.json", + rebuildInstructions: "CORRESPONDING_SOURCE.md", + }, + null, + 2, + ) + "\n", + ) + const checksum = path.join(output, `${base}.sha256`) + await Bun.write(checksum, `${sha256} ${path.basename(archive)}\n`) + + return { archive, manifest, checksum, commit, sha256 } +} + +export async function verifyCorrespondingSourceArtifacts(directory: string) { + const root = path.resolve(directory) + const manifests = await Array.fromAsync( + new Bun.Glob("*-source-*.source.json").scan({ cwd: root, absolute: true, onlyFiles: true }), + ) + if (manifests.length !== 1) { + throw new Error(`Expected exactly one corresponding source manifest in ${root}, found ${manifests.length}`) + } + + const value: unknown = await Bun.file(manifests[0]).json() + if (!isRecord(value) || !isRecord(value.archive)) throw new Error("Corresponding source manifest is malformed") + if (typeof value.archive.file !== "string" || path.basename(value.archive.file) !== value.archive.file) { + throw new Error("Corresponding source archive filename is invalid") + } + if (typeof value.archive.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.archive.sha256)) { + throw new Error("Corresponding source SHA-256 is invalid") + } + + const archive = path.join(root, value.archive.file) + const checksum = manifests[0].replace(/\.source\.json$/, ".sha256") + if (!existsSync(archive)) throw new Error(`Corresponding source archive is missing: ${value.archive.file}`) + if (!existsSync(checksum)) throw new Error(`Corresponding source checksum is missing: ${path.basename(checksum)}`) + const actual = await digest(archive) + if (actual !== value.archive.sha256) throw new Error(`Corresponding source digest mismatch for ${value.archive.file}`) + if ((await Bun.file(checksum).text()) !== `${actual} ${value.archive.file}\n`) { + throw new Error(`Corresponding source checksum file does not match ${value.archive.file}`) + } + return { manifest: manifests[0], archive, checksum, sha256: actual } +} + +async function git(root: string, args: string[]) { + return command(root, ["git", ...args]) +} + +async function command(root: string, args: string[]) { + const child = Bun.spawn(args, { + cwd: root, + stdout: "pipe", + stderr: "pipe", + }) + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]) + if (exitCode !== 0) throw new Error(`${args.join(" ")} failed (${exitCode}): ${stderr.trim() || stdout.trim()}`) + return stdout.trim() +} + +async function digest(file: string) { + const hasher = new Bun.CryptoHasher("sha256") + for await (const chunk of Bun.file(file).stream()) hasher.update(chunk) + return hasher.digest("hex") +} + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value) +} + +async function main() { + const verifyIndex = Bun.argv.indexOf("--verify") + if (verifyIndex !== -1) { + const directory = Bun.argv[verifyIndex + 1] + if (!directory) throw new Error("Usage: corresponding-source.ts --verify ") + console.log(JSON.stringify(await verifyCorrespondingSourceArtifacts(directory), null, 2)) + return + } + + const versionIndex = Bun.argv.indexOf("--version") + const outputIndex = Bun.argv.indexOf("--output") + const version = versionIndex === -1 ? undefined : Bun.argv[versionIndex + 1] + if (!version) throw new Error("Usage: corresponding-source.ts --version [--output ]") + const output = + outputIndex === -1 ? path.join(import.meta.dir, "..", "dist", "corresponding-source") : Bun.argv[outputIndex + 1] + if (!output) throw new Error("--output requires a directory") + + const result = await createCorrespondingSource({ + root: path.join(import.meta.dir, ".."), + output, + version, + allowDirty: Bun.argv.includes("--allow-dirty"), + }) + console.log(JSON.stringify(result, null, 2)) +} + +if (import.meta.main) await main() From ae1b391f444fe9d2814a3f4330e6893b23101b44 Mon Sep 17 00:00:00 2001 From: Lex Date: Thu, 13 Aug 2026 20:27:29 +0800 Subject: [PATCH 2/3] chore(dag): cover authoring files in license gate --- packages/opencode/src/dag/authoring.ts | 3 +++ packages/opencode/src/dag/blocks.ts | 3 +++ packages/opencode/src/dag/validation.ts | 3 +++ 3 files changed, 9 insertions(+) diff --git a/packages/opencode/src/dag/authoring.ts b/packages/opencode/src/dag/authoring.ts index 18fcceee85..94667ed338 100644 --- a/packages/opencode/src/dag/authoring.ts +++ b/packages/opencode/src/dag/authoring.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * The only source-to-prepared-graph seam for workflow authoring. * diff --git a/packages/opencode/src/dag/blocks.ts b/packages/opencode/src/dag/blocks.ts index ecc66d0775..f1c7989892 100644 --- a/packages/opencode/src/dag/blocks.ts +++ b/packages/opencode/src/dag/blocks.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + import { Schema } from "effect" import type { NodeConfig } from "./dag" diff --git a/packages/opencode/src/dag/validation.ts b/packages/opencode/src/dag/validation.ts index ace5701901..c7bb864463 100644 --- a/packages/opencode/src/dag/validation.ts +++ b/packages/opencode/src/dag/validation.ts @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2026 LeXwDeX +// SPDX-License-Identifier: AGPL-3.0-or-later + /** * Workflow spec validation authority. * From 55aa8b37896cdcca5aa559facd8113c36007ac81 Mon Sep 17 00:00:00 2001 From: Lex Date: Thu, 13 Aug 2026 20:36:21 +0800 Subject: [PATCH 3/3] fix(runtime): keep lint at baseline --- packages/core/src/runtime-asset/index.ts | 1 - packages/core/test/corresponding-source.test.ts | 8 ++++++-- packages/core/test/runtime-asset-cache.test.ts | 2 +- packages/desktop/test/runtime-assets.test.ts | 16 ++++++++++------ packages/opencode/script/prefetch-ripgrep.ts | 6 ++++-- 5 files changed, 21 insertions(+), 12 deletions(-) diff --git a/packages/core/src/runtime-asset/index.ts b/packages/core/src/runtime-asset/index.ts index 0a5b330d14..84db518cd3 100644 --- a/packages/core/src/runtime-asset/index.ts +++ b/packages/core/src/runtime-asset/index.ts @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 LeXwDeX // SPDX-License-Identifier: AGPL-3.0-or-later -import { existsSync } from "fs" import { chmod, copyFile, mkdir, mkdtemp, rename, rm } from "fs/promises" import path from "path" import { Context, Effect, Layer } from "effect" diff --git a/packages/core/test/corresponding-source.test.ts b/packages/core/test/corresponding-source.test.ts index 08637b208b..9889db0376 100644 --- a/packages/core/test/corresponding-source.test.ts +++ b/packages/core/test/corresponding-source.test.ts @@ -41,9 +41,13 @@ describe("corresponding source", () => { }) await unlink(result.archive) - await expect(verifyCorrespondingSourceArtifacts(path.dirname(result.archive))).rejects.toThrow( - "Corresponding source archive is missing", + const failure = await verifyCorrespondingSourceArtifacts(path.dirname(result.archive)).then( + () => undefined, + (error: unknown) => error, ) + expect(failure).toBeInstanceOf(Error) + if (!(failure instanceof Error)) throw new Error("expected source verification to fail") + expect(failure.message).toContain("Corresponding source archive is missing") }) }) diff --git a/packages/core/test/runtime-asset-cache.test.ts b/packages/core/test/runtime-asset-cache.test.ts index 7c9888ecb7..5fdf7abd3a 100644 --- a/packages/core/test/runtime-asset-cache.test.ts +++ b/packages/core/test/runtime-asset-cache.test.ts @@ -8,7 +8,7 @@ import { RuntimeAsset } from "@opencode-ai/core/runtime-asset" const cleanups: Array<() => void | Promise> = [] afterEach(async () => { - await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())) + await Promise.all(cleanups.splice(0).map(async (cleanup) => cleanup())) }) describe("RuntimeAsset managed candidates", () => { diff --git a/packages/desktop/test/runtime-assets.test.ts b/packages/desktop/test/runtime-assets.test.ts index 784a2545bb..1c0171db7b 100644 --- a/packages/desktop/test/runtime-assets.test.ts +++ b/packages/desktop/test/runtime-assets.test.ts @@ -15,11 +15,15 @@ describe("desktop runtime assets", () => { const directory = await mkdtemp(path.join(os.tmpdir(), "desktop-runtime-assets-")) roots.push(directory) - await expect( - verifyDesktopRuntimeAssets({ - directory, - platform: { os: "linux", arch: "x64" }, - }), - ).rejects.toThrow("Required runtime asset is unavailable: ripgrep@15.1.0") + const failure = await verifyDesktopRuntimeAssets({ + directory, + platform: { os: "linux", arch: "x64" }, + }).then( + () => undefined, + (error: unknown) => error, + ) + expect(failure).toBeInstanceOf(Error) + if (!(failure instanceof Error)) throw new Error("expected runtime asset verification to fail") + expect(failure.message).toContain("Required runtime asset is unavailable: ripgrep@15.1.0") }) }) diff --git a/packages/opencode/script/prefetch-ripgrep.ts b/packages/opencode/script/prefetch-ripgrep.ts index 28925a5dbb..cda0fc89de 100644 --- a/packages/opencode/script/prefetch-ripgrep.ts +++ b/packages/opencode/script/prefetch-ripgrep.ts @@ -76,7 +76,9 @@ function derivePlatform(directory: string): RuntimeAsset.Platform | undefined { const parts = directory.split("-") const os = parts[1] === "windows" ? "win32" : parts[1] const arch = parts[2] - if (os !== "darwin" && os !== "linux" && os !== "win32") return - if (!arch || !RipgrepAsset.descriptor.targets.some((target) => target.os === os && target.arch === arch)) return + if (os !== "darwin" && os !== "linux" && os !== "win32") return undefined + if (!arch || !RipgrepAsset.descriptor.targets.some((target) => target.os === os && target.arch === arch)) { + return undefined + } return { os, arch } }