sync
This commit is contained in:
parent
9a26b3058f
commit
f3da73553c
47 changed files with 765 additions and 3382 deletions
3
packages/opencode/.gitignore
vendored
Normal file
3
packages/opencode/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
node_modules
|
||||
dist
|
||||
gen
|
||||
15
packages/opencode/README.md
Normal file
15
packages/opencode/README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# js
|
||||
|
||||
To install dependencies:
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
To run:
|
||||
|
||||
```bash
|
||||
bun run index.ts
|
||||
```
|
||||
|
||||
This project was created using `bun init` in bun v1.2.12. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
||||
29
packages/opencode/bin/opencode.mjs
Normal file
29
packages/opencode/bin/opencode.mjs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env node
|
||||
import { createRequire } from "node:module"
|
||||
const require = createRequire(import.meta.url)
|
||||
import path from "path"
|
||||
import { execFileSync } from "child_process"
|
||||
let resolved = process.env.SST_BIN_PATH
|
||||
if (!resolved) {
|
||||
const name = `opencode-${process.platform}-${process.arch}`
|
||||
const binary = process.platform === "win32" ? "opencode.exe" : "opencode"
|
||||
try {
|
||||
resolved = require.resolve(path.join(name, "bin", binary))
|
||||
} catch (ex) {
|
||||
console.error(
|
||||
`It seems that your package manager failed to install the right version of the SST CLI for your platform. You can try manually installing the "${name}" package`,
|
||||
)
|
||||
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
process.on("SIGINT", () => {})
|
||||
|
||||
try {
|
||||
execFileSync(resolved, process.argv.slice(2), {
|
||||
stdio: "inherit",
|
||||
})
|
||||
} catch (ex) {
|
||||
process.exit(1)
|
||||
}
|
||||
39
packages/opencode/package.json
Normal file
39
packages/opencode/package.json
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"version": "0.0.0",
|
||||
"name": "opencode",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {},
|
||||
"exports": {
|
||||
"./*": [
|
||||
"./src/*.ts",
|
||||
"./src/*/index.ts"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/bun": "^1.0.7",
|
||||
"@types/bun": "latest",
|
||||
"@types/jsdom": "^21.1.7",
|
||||
"@types/turndown": "^5.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@flystorage/file-storage": "^1.1.0",
|
||||
"@flystorage/local-fs": "^1.1.0",
|
||||
"@hono/zod-validator": "^0.5.0",
|
||||
"ai": "5.0.0-alpha.7",
|
||||
"cac": "^6.7.14",
|
||||
"decimal.js": "^10.5.0",
|
||||
"env-paths": "^3.0.0",
|
||||
"hono": "^4.7.10",
|
||||
"hono-openapi": "^0.4.8",
|
||||
"jsdom": "^26.1.0",
|
||||
"remeda": "^2.22.3",
|
||||
"ts-lsp-client": "^1.0.3",
|
||||
"turndown": "^7.2.0",
|
||||
"vscode-jsonrpc": "^8.2.1",
|
||||
"vscode-languageclient": "8",
|
||||
"zod": "^3.25.3",
|
||||
"zod-openapi": "^4.2.4"
|
||||
}
|
||||
}
|
||||
30
packages/opencode/scrap.ts
Normal file
30
packages/opencode/scrap.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// This is a dummy file for testing purposes
|
||||
console.log('Hello, world!');
|
||||
|
||||
export function dummyFunction(): void {
|
||||
console.log('This is a dummy function');
|
||||
}
|
||||
|
||||
export function anotherDummyFunction(): string {
|
||||
return 'This is another dummy function';
|
||||
}
|
||||
|
||||
export function newDummyFunction(): number {
|
||||
return 42;
|
||||
}
|
||||
|
||||
export function extraDummyFunction(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function superDummyFunction(): void {
|
||||
console.log('This is a super dummy function');
|
||||
}
|
||||
|
||||
export function ultraDummyFunction(): object {
|
||||
return { dummy: true };
|
||||
}
|
||||
|
||||
export function megaDummyFunction(): Array<string> {
|
||||
return ['dummy', 'mega', 'function'];
|
||||
}
|
||||
68
packages/opencode/script/release.ts
Executable file
68
packages/opencode/script/release.ts
Executable file
|
|
@ -0,0 +1,68 @@
|
|||
#!/usr/bin/env bun
|
||||
|
||||
import { $ } from "bun"
|
||||
|
||||
import pkg from "../package.json"
|
||||
|
||||
const version = `0.0.0-${Date.now()}`
|
||||
|
||||
const ARCH = {
|
||||
arm64: "arm64",
|
||||
x64: "amd64",
|
||||
}
|
||||
|
||||
const OS = {
|
||||
linux: "linux",
|
||||
darwin: "mac",
|
||||
win32: "windows",
|
||||
}
|
||||
|
||||
const targets = [
|
||||
["linux", "arm64"],
|
||||
["linux", "x64"],
|
||||
["darwin", "x64"],
|
||||
["darwin", "arm64"],
|
||||
["windows", "x64"],
|
||||
]
|
||||
|
||||
await $`rm -rf dist`
|
||||
|
||||
const optionalDependencies: Record<string, string> = {}
|
||||
for (const [os, arch] of targets) {
|
||||
console.log(`building ${os}-${arch}`)
|
||||
const name = `${pkg.name}-${os}-${arch}`
|
||||
await $`mkdir -p dist/${name}/bin`
|
||||
await $`bun build --compile --minify --target=bun-${os}-${arch} --outfile=dist/${name}/bin/${pkg.name} ./src/index.ts`
|
||||
await Bun.file(`dist/${name}/package.json`).write(
|
||||
JSON.stringify(
|
||||
{
|
||||
name,
|
||||
version,
|
||||
os: [os],
|
||||
cpu: [arch],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
await $`cd dist/${name} && npm publish --access public --tag latest`
|
||||
optionalDependencies[name] = version
|
||||
}
|
||||
|
||||
await $`mkdir -p ./dist/${pkg.name}`
|
||||
await $`cp -r ./bin ./dist/${pkg.name}/bin`
|
||||
await Bun.file(`./dist/${pkg.name}/package.json`).write(
|
||||
JSON.stringify(
|
||||
{
|
||||
name: pkg.name + "-ai",
|
||||
bin: {
|
||||
[pkg.name]: `./bin/${pkg.name}.mjs`,
|
||||
},
|
||||
version,
|
||||
optionalDependencies,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
await $`cd ./dist/${pkg.name} && npm publish --access public --tag latest`
|
||||
78
packages/opencode/src/app/app.ts
Normal file
78
packages/opencode/src/app/app.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import fs from "fs/promises";
|
||||
import { AppPath } from "./path";
|
||||
import { Log } from "../util/log";
|
||||
import { Context } from "../util/context";
|
||||
|
||||
export namespace App {
|
||||
const log = Log.create({ service: "app" });
|
||||
|
||||
export type Info = Awaited<ReturnType<typeof create>>;
|
||||
|
||||
const ctx = Context.create<Info>("app");
|
||||
|
||||
async function create(input: { directory: string }) {
|
||||
const dataDir = AppPath.data(input.directory);
|
||||
await fs.mkdir(dataDir, { recursive: true });
|
||||
await Log.file(input.directory);
|
||||
|
||||
log.info("created", { path: dataDir });
|
||||
|
||||
const services = new Map<
|
||||
any,
|
||||
{
|
||||
state: any;
|
||||
shutdown?: (input: any) => Promise<void>;
|
||||
}
|
||||
>();
|
||||
|
||||
const result = {
|
||||
get services() {
|
||||
return services;
|
||||
},
|
||||
get root() {
|
||||
return input.directory;
|
||||
},
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function state<State>(
|
||||
key: any,
|
||||
init: (app: Info) => State,
|
||||
shutdown?: (state: Awaited<State>) => Promise<void>,
|
||||
) {
|
||||
return () => {
|
||||
const app = ctx.use();
|
||||
const services = app.services;
|
||||
if (!services.has(key)) {
|
||||
log.info("registering service", { name: key });
|
||||
services.set(key, {
|
||||
state: init(app),
|
||||
shutdown: shutdown,
|
||||
});
|
||||
}
|
||||
return services.get(key)?.state as State;
|
||||
};
|
||||
}
|
||||
|
||||
export async function use() {
|
||||
return ctx.use();
|
||||
}
|
||||
|
||||
export async function provide<T extends (app: Info) => any>(
|
||||
input: { directory: string },
|
||||
cb: T,
|
||||
) {
|
||||
const app = await create(input);
|
||||
|
||||
return ctx.provide(app, async () => {
|
||||
const result = await cb(app);
|
||||
for (const [key, entry] of app.services.entries()) {
|
||||
log.info("shutdown", { name: key });
|
||||
await entry.shutdown?.(await entry.state);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
}
|
||||
11
packages/opencode/src/app/path.ts
Normal file
11
packages/opencode/src/app/path.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import path from "path";
|
||||
|
||||
export namespace AppPath {
|
||||
export function data(input: string) {
|
||||
return path.join(input, ".opencode");
|
||||
}
|
||||
|
||||
export function storage(input: string) {
|
||||
return path.join(data(input), "storage");
|
||||
}
|
||||
}
|
||||
28
packages/opencode/src/bun/index.ts
Normal file
28
packages/opencode/src/bun/index.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import path from "path";
|
||||
import { Log } from "../util/log";
|
||||
export namespace BunProc {
|
||||
const log = Log.create({ service: "bun" });
|
||||
|
||||
export function run(
|
||||
cmd: string[],
|
||||
options?: Bun.SpawnOptions.OptionsObject<any, any, any>,
|
||||
) {
|
||||
const root =
|
||||
process.argv0 !== "bun"
|
||||
? path.resolve(process.cwd(), process.argv0)
|
||||
: process.argv0;
|
||||
log.info("running", {
|
||||
cmd: [root, ...cmd],
|
||||
options,
|
||||
});
|
||||
const result = Bun.spawnSync([root, ...cmd], {
|
||||
...options,
|
||||
argv0: "bun",
|
||||
env: {
|
||||
...process.env,
|
||||
...options?.env,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
101
packages/opencode/src/bus/index.ts
Normal file
101
packages/opencode/src/bus/index.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { z, type ZodType } from "zod";
|
||||
import { App } from "../app/app";
|
||||
import { Log } from "../util/log";
|
||||
|
||||
export namespace Bus {
|
||||
const log = Log.create({ service: "bus" });
|
||||
type Subscription = (event: any) => void;
|
||||
|
||||
const state = App.state("bus", () => {
|
||||
const subscriptions = new Map<any, Subscription[]>();
|
||||
|
||||
return {
|
||||
subscriptions,
|
||||
};
|
||||
});
|
||||
|
||||
export type EventDefinition = ReturnType<typeof event>;
|
||||
|
||||
const registry = new Map<string, EventDefinition>();
|
||||
|
||||
export function event<Type extends string, Properties extends ZodType>(
|
||||
type: Type,
|
||||
properties: Properties,
|
||||
) {
|
||||
const result = {
|
||||
type,
|
||||
properties,
|
||||
};
|
||||
registry.set(type, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function payloads() {
|
||||
return z.discriminatedUnion(
|
||||
"type",
|
||||
registry
|
||||
.entries()
|
||||
.map(([type, def]) =>
|
||||
z
|
||||
.object({
|
||||
type: z.literal(type),
|
||||
properties: def.properties,
|
||||
})
|
||||
.openapi({
|
||||
ref: "Event" + "." + def.type,
|
||||
}),
|
||||
)
|
||||
.toArray() as any,
|
||||
);
|
||||
}
|
||||
|
||||
export function publish<Definition extends EventDefinition>(
|
||||
def: Definition,
|
||||
properties: z.output<Definition["properties"]>,
|
||||
) {
|
||||
const payload = {
|
||||
type: def.type,
|
||||
properties,
|
||||
};
|
||||
log.info("publishing", {
|
||||
type: def.type,
|
||||
});
|
||||
for (const key of [def.type, "*"]) {
|
||||
const match = state().subscriptions.get(key);
|
||||
for (const sub of match ?? []) {
|
||||
sub(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribe<Definition extends EventDefinition>(
|
||||
def: Definition,
|
||||
callback: (event: {
|
||||
type: Definition["type"];
|
||||
properties: z.infer<Definition["properties"]>;
|
||||
}) => void,
|
||||
) {
|
||||
return raw(def.type, callback);
|
||||
}
|
||||
|
||||
export function subscribeAll(callback: (event: any) => void) {
|
||||
return raw("*", callback);
|
||||
}
|
||||
|
||||
function raw(type: string, callback: (event: any) => void) {
|
||||
log.info("subscribing", { type });
|
||||
const subscriptions = state().subscriptions;
|
||||
let match = subscriptions.get(type) ?? [];
|
||||
match.push(callback);
|
||||
subscriptions.set(type, match);
|
||||
|
||||
return () => {
|
||||
log.info("unsubscribing", { type });
|
||||
const match = subscriptions.get(type);
|
||||
if (!match) return;
|
||||
const index = match.indexOf(callback);
|
||||
if (index === -1) return;
|
||||
match.splice(index, 1);
|
||||
};
|
||||
}
|
||||
}
|
||||
51
packages/opencode/src/config/config.ts
Normal file
51
packages/opencode/src/config/config.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import path from "path";
|
||||
import { Log } from "../util/log";
|
||||
import { z } from "zod";
|
||||
import { App } from "../app/app";
|
||||
import { Provider } from "../provider/provider";
|
||||
|
||||
export namespace Config {
|
||||
const log = Log.create({ service: "config" });
|
||||
|
||||
export const state = App.state("config", async (app) => {
|
||||
const result = await load(app.root);
|
||||
return result;
|
||||
});
|
||||
|
||||
export const Info = z
|
||||
.object({
|
||||
providers: Provider.Info.array().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type Info = z.output<typeof Info>;
|
||||
|
||||
export function get() {
|
||||
return state();
|
||||
}
|
||||
|
||||
async function load(directory: string) {
|
||||
let result: Info = {};
|
||||
for (const file of ["opencode.jsonc", "opencode.json"]) {
|
||||
const resolved = path.join(directory, file);
|
||||
log.info("searching", { path: resolved });
|
||||
try {
|
||||
result = await import(path.join(directory, file)).then((mod) =>
|
||||
Info.parse(mod.default),
|
||||
);
|
||||
log.info("found", { path: resolved });
|
||||
break;
|
||||
} catch (e) {
|
||||
if (e instanceof z.ZodError) {
|
||||
for (const issue of e.issues) {
|
||||
log.info(issue.message);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
log.info("loaded", result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
20
packages/opencode/src/global/index.ts
Normal file
20
packages/opencode/src/global/index.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import envpaths from "env-paths";
|
||||
import fs from "fs/promises";
|
||||
const paths = envpaths("opencode", {
|
||||
suffix: "",
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
fs.mkdir(paths.config, { recursive: true }),
|
||||
fs.mkdir(paths.cache, { recursive: true }),
|
||||
]);
|
||||
|
||||
export namespace Global {
|
||||
export function config() {
|
||||
return paths.config;
|
||||
}
|
||||
|
||||
export function cache() {
|
||||
return paths.cache;
|
||||
}
|
||||
}
|
||||
74
packages/opencode/src/id/id.ts
Normal file
74
packages/opencode/src/id/id.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { z } from "zod";
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
export namespace Identifier {
|
||||
const prefixes = {
|
||||
session: "ses",
|
||||
message: "msg",
|
||||
} as const;
|
||||
|
||||
export function schema(prefix: keyof typeof prefixes) {
|
||||
return z.string().startsWith(prefixes[prefix]);
|
||||
}
|
||||
|
||||
const LENGTH = 26;
|
||||
|
||||
// State for monotonic ID generation
|
||||
let lastTimestamp = 0;
|
||||
let counter = 0;
|
||||
|
||||
export function ascending(prefix: keyof typeof prefixes, given?: string) {
|
||||
return generateID(prefix, false, given);
|
||||
}
|
||||
|
||||
export function descending(prefix: keyof typeof prefixes, given?: string) {
|
||||
return generateID(prefix, true, given);
|
||||
}
|
||||
|
||||
function generateID(
|
||||
prefix: keyof typeof prefixes,
|
||||
descending: boolean,
|
||||
given?: string,
|
||||
): string {
|
||||
if (!given) {
|
||||
return generateNewID(prefix, descending);
|
||||
}
|
||||
|
||||
if (!given.startsWith(prefixes[prefix])) {
|
||||
throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`);
|
||||
}
|
||||
return given;
|
||||
}
|
||||
|
||||
function generateNewID(
|
||||
prefix: keyof typeof prefixes,
|
||||
descending: boolean,
|
||||
): string {
|
||||
const currentTimestamp = Date.now();
|
||||
|
||||
if (currentTimestamp !== lastTimestamp) {
|
||||
lastTimestamp = currentTimestamp;
|
||||
counter = 0;
|
||||
}
|
||||
counter++;
|
||||
|
||||
let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter);
|
||||
|
||||
now = descending ? ~now : now;
|
||||
|
||||
const timeBytes = Buffer.alloc(6);
|
||||
for (let i = 0; i < 6; i++) {
|
||||
timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff));
|
||||
}
|
||||
|
||||
const randLength = (LENGTH - 12) / 2;
|
||||
const random = randomBytes(randLength);
|
||||
|
||||
return (
|
||||
prefixes[prefix] +
|
||||
"_" +
|
||||
timeBytes.toString("hex") +
|
||||
random.toString("hex")
|
||||
);
|
||||
}
|
||||
}
|
||||
85
packages/opencode/src/index.ts
Normal file
85
packages/opencode/src/index.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import "zod-openapi/extend"
|
||||
import { App } from "./app/app"
|
||||
import { Server } from "./server/server"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { Bus } from "./bus"
|
||||
import { Session } from "./session/session"
|
||||
import cac from "cac"
|
||||
import { Share } from "./share/share"
|
||||
import { Storage } from "./storage/storage"
|
||||
import { LLM } from "./llm/llm"
|
||||
import { Message } from "./session/message"
|
||||
|
||||
const cli = cac("opencode")
|
||||
|
||||
cli.command("", "Start the opencode in interactive mode").action(async () => {
|
||||
await App.provide({ directory: process.cwd() }, async () => {
|
||||
await Share.init()
|
||||
Server.listen()
|
||||
})
|
||||
})
|
||||
|
||||
cli.command("generate", "Generate OpenAPI and event specs").action(async () => {
|
||||
const specs = await Server.openapi()
|
||||
const dir = "gen"
|
||||
await fs.rmdir(dir, { recursive: true }).catch(() => {})
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(dir, "openapi.json"),
|
||||
JSON.stringify(specs, null, 2),
|
||||
)
|
||||
})
|
||||
|
||||
cli
|
||||
.command("run [...message]", "Run a chat message")
|
||||
.option("--session <id>", "Session ID")
|
||||
.action(async (message: string[], options) => {
|
||||
await App.provide({ directory: process.cwd() }, async () => {
|
||||
await Share.init()
|
||||
const session = options.session
|
||||
? await Session.get(options.session)
|
||||
: await Session.create()
|
||||
console.log("Session:", session.id)
|
||||
|
||||
Bus.subscribe(Message.Event.Updated, async (message) => {
|
||||
console.log("Thinking...")
|
||||
})
|
||||
|
||||
const unsub = Bus.subscribe(Session.Event.Updated, async (message) => {
|
||||
if (message.properties.info.share?.url)
|
||||
console.log("Share:", message.properties.info.share.url)
|
||||
unsub()
|
||||
})
|
||||
|
||||
const providers = await LLM.providers()
|
||||
const providerID = Object.keys(providers)[0]
|
||||
const modelID = providers[providerID].info.models[0].id
|
||||
console.log("using", providerID, modelID)
|
||||
const result = await Session.chat({
|
||||
sessionID: session.id,
|
||||
providerID,
|
||||
modelID,
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: message.join(" "),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
for (const part of result.parts) {
|
||||
if (part.type === "text") {
|
||||
console.log("opencode:", part.text)
|
||||
}
|
||||
}
|
||||
console.log({
|
||||
cost: result.metadata.assistant?.cost,
|
||||
tokens: result.metadata.assistant?.tokens,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
cli.help()
|
||||
cli.version("1.0.0")
|
||||
cli.parse()
|
||||
172
packages/opencode/src/llm/llm.ts
Normal file
172
packages/opencode/src/llm/llm.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import { App } from "../app/app"
|
||||
import { Log } from "../util/log"
|
||||
import { concat } from "remeda"
|
||||
import path from "path"
|
||||
import { Provider } from "../provider/provider"
|
||||
|
||||
import type { LanguageModel, Provider as ProviderInstance } from "ai"
|
||||
import { NoSuchModelError } from "ai"
|
||||
import { Config } from "../config/config"
|
||||
import { BunProc } from "../bun"
|
||||
import { Global } from "../global"
|
||||
|
||||
export namespace LLM {
|
||||
const log = Log.create({ service: "llm" })
|
||||
|
||||
export class ModelNotFoundError extends Error {
|
||||
constructor(public readonly model: string) {
|
||||
super()
|
||||
}
|
||||
}
|
||||
|
||||
const NATIVE_PROVIDERS: Provider.Info[] = [
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
models: [
|
||||
{
|
||||
id: "claude-sonnet-4-20250514",
|
||||
name: "Claude Sonnet 4",
|
||||
cost: {
|
||||
input: 3.0 / 1_000_000,
|
||||
output: 15.0 / 1_000_000,
|
||||
inputCached: 3.75 / 1_000_000,
|
||||
outputCached: 0.3 / 1_000_000,
|
||||
},
|
||||
contextWindow: 200_000,
|
||||
maxOutputTokens: 50_000,
|
||||
attachment: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
models: [
|
||||
{
|
||||
id: "codex-mini-latest",
|
||||
name: "Codex Mini",
|
||||
cost: {
|
||||
input: 1.5 / 1_000_000,
|
||||
inputCached: 0.375 / 1_000_000,
|
||||
output: 6.0 / 1_000_000,
|
||||
outputCached: 0.0 / 1_000_000,
|
||||
},
|
||||
contextWindow: 200_000,
|
||||
maxOutputTokens: 100_000,
|
||||
attachment: true,
|
||||
reasoning: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "google",
|
||||
name: "Google",
|
||||
models: [
|
||||
{
|
||||
id: "gemini-2.5-pro-preview-03-25",
|
||||
name: "Gemini 2.5 Pro",
|
||||
cost: {
|
||||
input: 1.25 / 1_000_000,
|
||||
inputCached: 0 / 1_000_000,
|
||||
output: 10 / 1_000_000,
|
||||
outputCached: 0 / 1_000_000,
|
||||
},
|
||||
contextWindow: 1_000_000,
|
||||
maxOutputTokens: 50_000,
|
||||
attachment: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const AUTODETECT: Record<string, string[]> = {
|
||||
anthropic: ["ANTHROPIC_API_KEY"],
|
||||
openai: ["OPENAI_API_KEY"],
|
||||
google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
|
||||
}
|
||||
|
||||
const state = App.state("llm", async () => {
|
||||
const config = await Config.get()
|
||||
const providers: Record<
|
||||
string,
|
||||
{
|
||||
info: Provider.Info
|
||||
instance: ProviderInstance
|
||||
}
|
||||
> = {}
|
||||
const models = new Map<
|
||||
string,
|
||||
{ info: Provider.Model; instance: LanguageModel }
|
||||
>()
|
||||
|
||||
const list = concat(NATIVE_PROVIDERS, config.providers ?? [])
|
||||
|
||||
for (const provider of list) {
|
||||
if (
|
||||
!config.providers?.find((p) => p.id === provider.id) &&
|
||||
!AUTODETECT[provider.id]?.some((env) => process.env[env])
|
||||
)
|
||||
continue
|
||||
const dir = path.join(
|
||||
Global.cache(),
|
||||
`node_modules`,
|
||||
`@ai-sdk`,
|
||||
provider.id,
|
||||
)
|
||||
if (!(await Bun.file(path.join(dir, "package.json")).exists())) {
|
||||
BunProc.run(["add", "--exact", `@ai-sdk/${provider.id}@alpha`], {
|
||||
cwd: Global.cache(),
|
||||
})
|
||||
}
|
||||
const mod = await import(
|
||||
path.join(Global.cache(), `node_modules`, `@ai-sdk`, provider.id)
|
||||
)
|
||||
const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
|
||||
const loaded = fn(provider.options)
|
||||
log.info("loaded", { provider: provider.id })
|
||||
providers[provider.id] = {
|
||||
info: provider,
|
||||
instance: loaded,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
models,
|
||||
providers,
|
||||
}
|
||||
})
|
||||
|
||||
export async function providers() {
|
||||
return state().then((state) => state.providers)
|
||||
}
|
||||
|
||||
export async function findModel(providerID: string, modelID: string) {
|
||||
const key = `${providerID}/${modelID}`
|
||||
const s = await state()
|
||||
if (s.models.has(key)) return s.models.get(key)!
|
||||
const provider = s.providers[providerID]
|
||||
if (!provider) throw new ModelNotFoundError(modelID)
|
||||
log.info("loading", {
|
||||
providerID,
|
||||
modelID,
|
||||
})
|
||||
const info = provider.info.models.find((m) => m.id === modelID)
|
||||
if (!info) throw new ModelNotFoundError(modelID)
|
||||
try {
|
||||
const match = provider.instance.languageModel(modelID)
|
||||
log.info("found", { providerID, modelID })
|
||||
s.models.set(key, {
|
||||
info,
|
||||
instance: match,
|
||||
})
|
||||
return {
|
||||
info,
|
||||
instance: match,
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof NoSuchModelError) throw new ModelNotFoundError(modelID)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
208
packages/opencode/src/lsp/client.ts
Normal file
208
packages/opencode/src/lsp/client.ts
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
import { spawn } from "child_process";
|
||||
import path from "path";
|
||||
import {
|
||||
createMessageConnection,
|
||||
StreamMessageReader,
|
||||
StreamMessageWriter,
|
||||
} from "vscode-jsonrpc/node";
|
||||
import type { Diagnostic as VSCodeDiagnostic } from "vscode-languageserver-types";
|
||||
import { App } from "../app/app";
|
||||
import { Log } from "../util/log";
|
||||
import { LANGUAGE_EXTENSIONS } from "./language";
|
||||
import { Bus } from "../bus";
|
||||
import z from "zod";
|
||||
|
||||
export namespace LSPClient {
|
||||
const log = Log.create({ service: "lsp.client" });
|
||||
|
||||
export type Info = Awaited<ReturnType<typeof create>>;
|
||||
|
||||
export type Diagnostic = VSCodeDiagnostic;
|
||||
|
||||
export const Event = {
|
||||
Diagnostics: Bus.event(
|
||||
"lsp.client.diagnostics",
|
||||
z.object({
|
||||
serverID: z.string(),
|
||||
path: z.string(),
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
export async function create(input: { cmd: string[]; serverID: string }) {
|
||||
log.info("starting client", input);
|
||||
|
||||
const app = await App.use();
|
||||
const [command, ...args] = input.cmd;
|
||||
const server = spawn(command, args, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
cwd: app.root,
|
||||
});
|
||||
|
||||
const connection = createMessageConnection(
|
||||
new StreamMessageReader(server.stdout),
|
||||
new StreamMessageWriter(server.stdin),
|
||||
);
|
||||
|
||||
const diagnostics = new Map<string, Diagnostic[]>();
|
||||
connection.onNotification("textDocument/publishDiagnostics", (params) => {
|
||||
const path = new URL(params.uri).pathname;
|
||||
log.info("textDocument/publishDiagnostics", {
|
||||
path,
|
||||
});
|
||||
const exists = diagnostics.has(path);
|
||||
diagnostics.set(path, params.diagnostics);
|
||||
// servers seem to send one blank publishDiagnostics event before the first real one
|
||||
if (!exists && !params.diagnostics.length) return;
|
||||
Bus.publish(Event.Diagnostics, { path, serverID: input.serverID });
|
||||
});
|
||||
connection.listen();
|
||||
|
||||
await connection.sendRequest("initialize", {
|
||||
processId: server.pid,
|
||||
initializationOptions: {
|
||||
workspaceFolders: [
|
||||
{
|
||||
name: "workspace",
|
||||
uri: "file://" + app.root,
|
||||
},
|
||||
],
|
||||
tsserver: {
|
||||
path: require.resolve("typescript/lib/tsserver.js"),
|
||||
},
|
||||
},
|
||||
capabilities: {
|
||||
workspace: {
|
||||
configuration: true,
|
||||
didChangeConfiguration: {
|
||||
dynamicRegistration: true,
|
||||
},
|
||||
didChangeWatchedFiles: {
|
||||
dynamicRegistration: true,
|
||||
relativePatternSupport: true,
|
||||
},
|
||||
},
|
||||
textDocument: {
|
||||
synchronization: {
|
||||
dynamicRegistration: true,
|
||||
didSave: true,
|
||||
},
|
||||
completion: {
|
||||
completionItem: {},
|
||||
},
|
||||
codeLens: {
|
||||
dynamicRegistration: true,
|
||||
},
|
||||
documentSymbol: {},
|
||||
codeAction: {
|
||||
codeActionLiteralSupport: {
|
||||
codeActionKind: {
|
||||
valueSet: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
publishDiagnostics: {
|
||||
versionSupport: true,
|
||||
},
|
||||
semanticTokens: {
|
||||
requests: {
|
||||
range: {},
|
||||
full: {},
|
||||
},
|
||||
tokenTypes: [],
|
||||
tokenModifiers: [],
|
||||
formats: [],
|
||||
},
|
||||
},
|
||||
window: {},
|
||||
},
|
||||
});
|
||||
await connection.sendNotification("initialized", {});
|
||||
log.info("initialized");
|
||||
|
||||
const files = new Set<string>();
|
||||
|
||||
const result = {
|
||||
get clientID() {
|
||||
return input.serverID;
|
||||
},
|
||||
get connection() {
|
||||
return connection;
|
||||
},
|
||||
notify: {
|
||||
async open(input: { path: string }) {
|
||||
const file = Bun.file(input.path);
|
||||
const text = await file.text();
|
||||
const opened = files.has(input.path);
|
||||
if (!opened) {
|
||||
log.info("textDocument/didOpen", input);
|
||||
diagnostics.delete(input.path);
|
||||
const extension = path.extname(input.path);
|
||||
const languageId = LANGUAGE_EXTENSIONS[extension] ?? "plaintext";
|
||||
await connection.sendNotification("textDocument/didOpen", {
|
||||
textDocument: {
|
||||
uri: `file://` + input.path,
|
||||
languageId,
|
||||
version: Date.now(),
|
||||
text,
|
||||
},
|
||||
});
|
||||
files.add(input.path);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("textDocument/didChange", input);
|
||||
diagnostics.delete(input.path);
|
||||
await connection.sendNotification("textDocument/didChange", {
|
||||
textDocument: {
|
||||
uri: `file://` + input.path,
|
||||
version: Date.now(),
|
||||
},
|
||||
contentChanges: [
|
||||
{
|
||||
text,
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
},
|
||||
get diagnostics() {
|
||||
return diagnostics;
|
||||
},
|
||||
async waitForDiagnostics(input: { path: string }) {
|
||||
log.info("waiting for diagnostics", input);
|
||||
let unsub: () => void;
|
||||
let timeout: NodeJS.Timeout;
|
||||
return await Promise.race([
|
||||
new Promise<void>(async (resolve) => {
|
||||
unsub = Bus.subscribe(Event.Diagnostics, (event) => {
|
||||
if (
|
||||
event.properties.path === input.path &&
|
||||
event.properties.serverID === result.clientID
|
||||
) {
|
||||
log.info("got diagnostics", input);
|
||||
clearTimeout(timeout);
|
||||
unsub?.();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}),
|
||||
new Promise<void>((resolve) => {
|
||||
timeout = setTimeout(() => {
|
||||
log.info("timed out refreshing diagnostics", input);
|
||||
unsub?.();
|
||||
resolve();
|
||||
}, 5000);
|
||||
}),
|
||||
]);
|
||||
},
|
||||
async shutdown() {
|
||||
log.info("shutting down");
|
||||
connection.end();
|
||||
connection.dispose();
|
||||
},
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
131
packages/opencode/src/lsp/index.ts
Normal file
131
packages/opencode/src/lsp/index.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import { App } from "../app/app";
|
||||
import { Log } from "../util/log";
|
||||
import { LSPClient } from "./client";
|
||||
import path from "path";
|
||||
|
||||
export namespace LSP {
|
||||
const log = Log.create({ service: "lsp" });
|
||||
|
||||
const state = App.state(
|
||||
"lsp",
|
||||
async () => {
|
||||
log.info("initializing");
|
||||
const clients = new Map<string, LSPClient.Info>();
|
||||
|
||||
return {
|
||||
clients,
|
||||
};
|
||||
},
|
||||
async (state) => {
|
||||
for (const client of state.clients.values()) {
|
||||
await client.shutdown();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export async function file(input: string) {
|
||||
const extension = path.parse(input).ext;
|
||||
const s = await state();
|
||||
const matches = AUTO.filter((x) => x.extensions.includes(extension));
|
||||
for (const match of matches) {
|
||||
const existing = s.clients.get(match.id);
|
||||
if (existing) continue;
|
||||
const client = await LSPClient.create({
|
||||
cmd: match.command,
|
||||
serverID: match.id,
|
||||
});
|
||||
s.clients.set(match.id, client);
|
||||
}
|
||||
await run(async (client) => {
|
||||
const wait = client.waitForDiagnostics({ path: input });
|
||||
await client.notify.open({ path: input });
|
||||
return wait;
|
||||
});
|
||||
}
|
||||
|
||||
export async function diagnostics() {
|
||||
const results: Record<string, LSPClient.Diagnostic[]> = {};
|
||||
for (const result of await run(async (client) => client.diagnostics)) {
|
||||
for (const [path, diagnostics] of result.entries()) {
|
||||
const arr = results[path] || [];
|
||||
arr.push(...diagnostics);
|
||||
results[path] = arr;
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function hover(input: {
|
||||
file: string;
|
||||
line: number;
|
||||
character: number;
|
||||
}) {
|
||||
return run((client) => {
|
||||
return client.connection.sendRequest("textDocument/hover", {
|
||||
textDocument: {
|
||||
uri: `file://${input.file}`,
|
||||
},
|
||||
position: {
|
||||
line: input.line,
|
||||
character: input.character,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function run<T>(
|
||||
input: (client: LSPClient.Info) => Promise<T>,
|
||||
): Promise<T[]> {
|
||||
const clients = await state().then((x) => [...x.clients.values()]);
|
||||
const tasks = clients.map((x) => input(x));
|
||||
return Promise.all(tasks);
|
||||
}
|
||||
|
||||
const AUTO: {
|
||||
id: string;
|
||||
command: string[];
|
||||
extensions: string[];
|
||||
install?: () => Promise<void>;
|
||||
}[] = [
|
||||
{
|
||||
id: "typescript",
|
||||
command: ["bun", "x", "typescript-language-server", "--stdio"],
|
||||
extensions: [
|
||||
".ts",
|
||||
".tsx",
|
||||
".js",
|
||||
".jsx",
|
||||
".mjs",
|
||||
".cjs",
|
||||
".mts",
|
||||
".cts",
|
||||
".mtsx",
|
||||
".ctsx",
|
||||
],
|
||||
},
|
||||
/*
|
||||
{
|
||||
id: "golang",
|
||||
command: ["gopls"],
|
||||
extensions: [".go"],
|
||||
},
|
||||
*/
|
||||
];
|
||||
|
||||
export namespace Diagnostic {
|
||||
export function pretty(diagnostic: LSPClient.Diagnostic) {
|
||||
const severityMap = {
|
||||
1: "ERROR",
|
||||
2: "WARN",
|
||||
3: "INFO",
|
||||
4: "HINT",
|
||||
};
|
||||
|
||||
const severity = severityMap[diagnostic.severity || 1];
|
||||
const line = diagnostic.range.start.line + 1;
|
||||
const col = diagnostic.range.start.character + 1;
|
||||
|
||||
return `${severity} [${line}:${col}] ${diagnostic.message}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
89
packages/opencode/src/lsp/language.ts
Normal file
89
packages/opencode/src/lsp/language.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
export const LANGUAGE_EXTENSIONS: Record<string, string> = {
|
||||
".abap": "abap",
|
||||
".bat": "bat",
|
||||
".bib": "bibtex",
|
||||
".bibtex": "bibtex",
|
||||
".clj": "clojure",
|
||||
".coffee": "coffeescript",
|
||||
".c": "c",
|
||||
".cpp": "cpp",
|
||||
".cxx": "cpp",
|
||||
".cc": "cpp",
|
||||
".c++": "cpp",
|
||||
".cs": "csharp",
|
||||
".css": "css",
|
||||
".d": "d",
|
||||
".pas": "pascal",
|
||||
".pascal": "pascal",
|
||||
".diff": "diff",
|
||||
".patch": "diff",
|
||||
".dart": "dart",
|
||||
".dockerfile": "dockerfile",
|
||||
".ex": "elixir",
|
||||
".exs": "elixir",
|
||||
".erl": "erlang",
|
||||
".hrl": "erlang",
|
||||
".fs": "fsharp",
|
||||
".fsi": "fsharp",
|
||||
".fsx": "fsharp",
|
||||
".fsscript": "fsharp",
|
||||
".gitcommit": "git-commit",
|
||||
".gitrebase": "git-rebase",
|
||||
".go": "go",
|
||||
".groovy": "groovy",
|
||||
".hbs": "handlebars",
|
||||
".handlebars": "handlebars",
|
||||
".hs": "haskell",
|
||||
".html": "html",
|
||||
".htm": "html",
|
||||
".ini": "ini",
|
||||
".java": "java",
|
||||
".js": "javascript",
|
||||
".jsx": "javascriptreact",
|
||||
".json": "json",
|
||||
".tex": "latex",
|
||||
".latex": "latex",
|
||||
".less": "less",
|
||||
".lua": "lua",
|
||||
".makefile": "makefile",
|
||||
makefile: "makefile",
|
||||
".md": "markdown",
|
||||
".markdown": "markdown",
|
||||
".m": "objective-c",
|
||||
".mm": "objective-cpp",
|
||||
".pl": "perl",
|
||||
".pm": "perl6",
|
||||
".php": "php",
|
||||
".ps1": "powershell",
|
||||
".psm1": "powershell",
|
||||
".pug": "jade",
|
||||
".jade": "jade",
|
||||
".py": "python",
|
||||
".r": "r",
|
||||
".cshtml": "razor",
|
||||
".razor": "razor",
|
||||
".rb": "ruby",
|
||||
".rs": "rust",
|
||||
".scss": "scss",
|
||||
".sass": "sass",
|
||||
".scala": "scala",
|
||||
".shader": "shaderlab",
|
||||
".sh": "shellscript",
|
||||
".bash": "shellscript",
|
||||
".zsh": "shellscript",
|
||||
".ksh": "shellscript",
|
||||
".sql": "sql",
|
||||
".swift": "swift",
|
||||
".ts": "typescript",
|
||||
".tsx": "typescriptreact",
|
||||
".mts": "typescript",
|
||||
".cts": "typescript",
|
||||
".mtsx": "typescriptreact",
|
||||
".ctsx": "typescriptreact",
|
||||
".xml": "xml",
|
||||
".xsl": "xsl",
|
||||
".yaml": "yaml",
|
||||
".yml": "yaml",
|
||||
".mjs": "javascript",
|
||||
".cjs": "javascript",
|
||||
} as const;
|
||||
35
packages/opencode/src/provider/provider.ts
Normal file
35
packages/opencode/src/provider/provider.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import z from "zod";
|
||||
|
||||
export namespace Provider {
|
||||
export const Model = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string().optional(),
|
||||
cost: z.object({
|
||||
input: z.number(),
|
||||
inputCached: z.number(),
|
||||
output: z.number(),
|
||||
outputCached: z.number(),
|
||||
}),
|
||||
contextWindow: z.number(),
|
||||
maxOutputTokens: z.number().optional(),
|
||||
attachment: z.boolean(),
|
||||
reasoning: z.boolean().optional(),
|
||||
})
|
||||
.openapi({
|
||||
ref: "Provider.Model",
|
||||
});
|
||||
export type Model = z.output<typeof Model>;
|
||||
|
||||
export const Info = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
options: z.record(z.string(), z.any()).optional(),
|
||||
models: Model.array(),
|
||||
})
|
||||
.openapi({
|
||||
ref: "Provider.Info",
|
||||
});
|
||||
export type Info = z.output<typeof Info>;
|
||||
}
|
||||
309
packages/opencode/src/server/server.ts
Normal file
309
packages/opencode/src/server/server.ts
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
import { Log } from "../util/log";
|
||||
import { Bus } from "../bus";
|
||||
import { describeRoute, generateSpecs, openAPISpecs } from "hono-openapi";
|
||||
import { Hono } from "hono";
|
||||
import { streamSSE } from "hono/streaming";
|
||||
import { Session } from "../session/session";
|
||||
import { resolver, validator as zValidator } from "hono-openapi/zod";
|
||||
import { z } from "zod";
|
||||
import { LLM } from "../llm/llm";
|
||||
import { Message } from "../session/message";
|
||||
import { Provider } from "../provider/provider";
|
||||
|
||||
export namespace Server {
|
||||
const log = Log.create({ service: "server" });
|
||||
const PORT = 16713;
|
||||
|
||||
export type App = ReturnType<typeof app>;
|
||||
|
||||
function app() {
|
||||
const app = new Hono();
|
||||
|
||||
const result = app
|
||||
.get(
|
||||
"/openapi",
|
||||
openAPISpecs(app, {
|
||||
documentation: {
|
||||
info: {
|
||||
title: "opencode",
|
||||
version: "1.0.0",
|
||||
description: "opencode api",
|
||||
},
|
||||
openapi: "3.0.0",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.get(
|
||||
"/event",
|
||||
describeRoute({
|
||||
description: "Get events",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Event stream",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(
|
||||
Bus.payloads().openapi({
|
||||
ref: "Event",
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
log.info("event connected");
|
||||
return streamSSE(c, async (stream) => {
|
||||
stream.writeSSE({
|
||||
data: JSON.stringify({}),
|
||||
});
|
||||
const unsub = Bus.subscribeAll(async (event) => {
|
||||
await stream.writeSSE({
|
||||
data: JSON.stringify(event),
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => {
|
||||
stream.onAbort(() => {
|
||||
unsub();
|
||||
resolve();
|
||||
log.info("event disconnected");
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_create",
|
||||
describeRoute({
|
||||
description: "Create a new session",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successfully created session",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(Session.Info),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
const session = await Session.create();
|
||||
return c.json(session);
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_share",
|
||||
describeRoute({
|
||||
description: "Share the session",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successfully shared session",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(Session.Info),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
zValidator(
|
||||
"json",
|
||||
z.object({
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const body = c.req.valid("json");
|
||||
await Session.share(body.sessionID);
|
||||
const session = await Session.get(body.sessionID);
|
||||
return c.json(session);
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_messages",
|
||||
describeRoute({
|
||||
description: "Get messages for a session",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successfully created session",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(Message.Info.array()),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
zValidator(
|
||||
"json",
|
||||
z.object({
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const messages = await Session.messages(
|
||||
c.req.valid("json").sessionID,
|
||||
);
|
||||
return c.json(messages);
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_list",
|
||||
describeRoute({
|
||||
description: "List all sessions",
|
||||
responses: {
|
||||
200: {
|
||||
description: "List of sessions",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(Session.Info.array()),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
const sessions = await Array.fromAsync(Session.list());
|
||||
return c.json(sessions);
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_abort",
|
||||
describeRoute({
|
||||
description: "Abort a session",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Aborted session",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(z.boolean()),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
zValidator(
|
||||
"json",
|
||||
z.object({
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const body = c.req.valid("json");
|
||||
return c.json(Session.abort(body.sessionID));
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_summarize",
|
||||
describeRoute({
|
||||
description: "Summarize the session",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Summarize the session",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(z.boolean()),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
zValidator(
|
||||
"json",
|
||||
z.object({
|
||||
sessionID: z.string(),
|
||||
providerID: z.string(),
|
||||
modelID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const body = c.req.valid("json");
|
||||
await Session.summarize(body);
|
||||
return c.json(true);
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session_chat",
|
||||
describeRoute({
|
||||
description: "Chat with a model",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Chat with a model",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(Message.Info),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
zValidator(
|
||||
"json",
|
||||
z.object({
|
||||
sessionID: z.string(),
|
||||
providerID: z.string(),
|
||||
modelID: z.string(),
|
||||
parts: Message.Part.array(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const body = c.req.valid("json");
|
||||
const msg = await Session.chat(body);
|
||||
return c.json(msg);
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/provider_list",
|
||||
describeRoute({
|
||||
description: "List all providers",
|
||||
responses: {
|
||||
200: {
|
||||
description: "List of providers",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(Provider.Info.array()),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
const providers = await LLM.providers();
|
||||
const result = [] as (Provider.Info & { key: string })[];
|
||||
for (const [key, provider] of Object.entries(providers)) {
|
||||
result.push({ ...provider.info, key });
|
||||
}
|
||||
return c.json(result);
|
||||
},
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function openapi() {
|
||||
const a = app();
|
||||
const result = await generateSpecs(a, {
|
||||
documentation: {
|
||||
info: {
|
||||
title: "opencode",
|
||||
version: "1.0.0",
|
||||
description: "opencode api",
|
||||
},
|
||||
openapi: "3.0.0",
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export function listen() {
|
||||
const server = Bun.serve({
|
||||
port: PORT,
|
||||
hostname: "0.0.0.0",
|
||||
idleTimeout: 0,
|
||||
fetch: app().fetch,
|
||||
});
|
||||
return server;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue