Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48e12ade76 | ||
|
|
6145dfcca0 | ||
|
|
4580c88c0b | ||
|
|
061ba65d20 | ||
|
|
457386ad08 | ||
|
|
fce04dc48b | ||
|
|
81534ab387 | ||
|
|
409a6f93b2 | ||
|
|
55c294c013 | ||
|
|
70db372466 | ||
|
|
8cc427daba | ||
|
|
8fde772957 | ||
|
|
d8dc23bde9 | ||
|
|
1c83ef75a2 | ||
|
|
95e410db88 | ||
|
|
13d3fba86b | ||
|
|
3ab4f42ebb | ||
|
|
b8d2aebf09 | ||
|
|
20e818ad05 | ||
|
|
542186aa49 | ||
|
|
c478d1bdbb | ||
|
|
7fd2222976 | ||
|
|
e86adb2ec8 | ||
|
|
34ac0e895d | ||
|
|
bd4319f2bc | ||
|
|
696ab1a752 | ||
|
|
d3ff66e911 | ||
|
|
1954b59167 | ||
|
|
e2fac991dc | ||
|
|
8ba35eadd4 | ||
|
|
7446f5ad7b | ||
|
|
81a3e02474 |
@@ -1,4 +1,6 @@
|
|||||||
---
|
---
|
||||||
|
model: openai/gpt-5
|
||||||
|
reasoningEffort: medium
|
||||||
description: ALWAYS use this when writing docs
|
description: ALWAYS use this when writing docs
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -42,3 +42,5 @@
|
|||||||
| 2025-08-06 | 147,067 (+5,471) | 158,309 (+2,557) | 305,376 (+8,028) |
|
| 2025-08-06 | 147,067 (+5,471) | 158,309 (+2,557) | 305,376 (+8,028) |
|
||||||
| 2025-08-07 | 152,591 (+5,524) | 160,889 (+2,580) | 313,480 (+8,104) |
|
| 2025-08-07 | 152,591 (+5,524) | 160,889 (+2,580) | 313,480 (+8,104) |
|
||||||
| 2025-08-08 | 158,187 (+5,596) | 163,448 (+2,559) | 321,635 (+8,155) |
|
| 2025-08-08 | 158,187 (+5,596) | 163,448 (+2,559) | 321,635 (+8,155) |
|
||||||
|
| 2025-08-09 | 162,770 (+4,583) | 165,721 (+2,273) | 328,491 (+6,856) |
|
||||||
|
| 2025-08-10 | 165,695 (+2,925) | 167,109 (+1,388) | 332,804 (+4,313) |
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"name": "@opencode/cloud-core",
|
"name": "@opencode/cloud-core",
|
||||||
"version": "0.0.0",
|
"version": "0.4.13",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode/cloud-function",
|
"name": "@opencode/cloud-function",
|
||||||
"version": "0.3.130",
|
"version": "0.4.13",
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ import { Resource } from "sst"
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import { issuer } from "@openauthjs/openauth"
|
import { issuer } from "@openauthjs/openauth"
|
||||||
import { createSubjects } from "@openauthjs/openauth/subject"
|
import { createSubjects } from "@openauthjs/openauth/subject"
|
||||||
|
import { CodeProvider } from "@openauthjs/openauth/provider/code"
|
||||||
import { GithubProvider } from "@openauthjs/openauth/provider/github"
|
import { GithubProvider } from "@openauthjs/openauth/provider/github"
|
||||||
|
import { GoogleOidcProvider } from "@openauthjs/openauth/provider/google"
|
||||||
import { CloudflareStorage } from "@openauthjs/openauth/storage/cloudflare"
|
import { CloudflareStorage } from "@openauthjs/openauth/storage/cloudflare"
|
||||||
import { Account } from "@opencode/cloud-core/account.js"
|
import { Account } from "@opencode/cloud-core/account.js"
|
||||||
|
|
||||||
@@ -30,6 +32,53 @@ export default {
|
|||||||
clientSecret: Resource.GITHUB_CLIENT_SECRET_CONSOLE.value,
|
clientSecret: Resource.GITHUB_CLIENT_SECRET_CONSOLE.value,
|
||||||
scopes: ["read:user", "user:email"],
|
scopes: ["read:user", "user:email"],
|
||||||
}),
|
}),
|
||||||
|
google: GoogleOidcProvider({
|
||||||
|
clientID: Resource.GOOGLE_CLIENT_ID.value,
|
||||||
|
scopes: ["openid", "email"],
|
||||||
|
}),
|
||||||
|
// email: CodeProvider({
|
||||||
|
// async request(req, state, form, error) {
|
||||||
|
// console.log(state)
|
||||||
|
// const params = new URLSearchParams()
|
||||||
|
// if (error) {
|
||||||
|
// params.set("error", error.type)
|
||||||
|
// }
|
||||||
|
// if (state.type === "start") {
|
||||||
|
// return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/email?" + params.toString(), 302)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if (state.type === "code") {
|
||||||
|
// return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/code?" + params.toString(), 302)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return new Response("ok")
|
||||||
|
// },
|
||||||
|
// async sendCode(claims, code) {
|
||||||
|
// const email = z.string().email().parse(claims.email)
|
||||||
|
// const cmd = new SendEmailCommand({
|
||||||
|
// Destination: {
|
||||||
|
// ToAddresses: [email],
|
||||||
|
// },
|
||||||
|
// FromEmailAddress: `SST <auth@${Resource.Email.sender}>`,
|
||||||
|
// Content: {
|
||||||
|
// Simple: {
|
||||||
|
// Body: {
|
||||||
|
// Html: {
|
||||||
|
// Data: `Your pin code is <strong>${code}</strong>`,
|
||||||
|
// },
|
||||||
|
// Text: {
|
||||||
|
// Data: `Your pin code is ${code}`,
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// Subject: {
|
||||||
|
// Data: "SST Console Pin Code: " + code,
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// })
|
||||||
|
// await ses.send(cmd)
|
||||||
|
// },
|
||||||
|
// }),
|
||||||
},
|
},
|
||||||
storage: CloudflareStorage({
|
storage: CloudflareStorage({
|
||||||
namespace: env.AuthStorage,
|
namespace: env.AuthStorage,
|
||||||
@@ -50,7 +99,14 @@ export default {
|
|||||||
})
|
})
|
||||||
const user = (await userResponse.json()) as { email: string }
|
const user = (await userResponse.json()) as { email: string }
|
||||||
email = user.email
|
email = user.email
|
||||||
} else throw new Error("Unsupported provider")
|
} else if (response.provider === "google") {
|
||||||
|
if (!response.id.email_verified) throw new Error("Google email not verified")
|
||||||
|
email = response.id.email as string
|
||||||
|
}
|
||||||
|
//if (response.provider === "email") {
|
||||||
|
// email = response.claims.email
|
||||||
|
//}
|
||||||
|
else throw new Error("Unsupported provider")
|
||||||
|
|
||||||
if (!email) throw new Error("No email found")
|
if (!email) throw new Error("No email found")
|
||||||
|
|
||||||
|
|||||||
+447
-425
@@ -4,11 +4,11 @@ import { cors } from "hono/cors"
|
|||||||
import { HTTPException } from "hono/http-exception"
|
import { HTTPException } from "hono/http-exception"
|
||||||
import { zValidator } from "@hono/zod-validator"
|
import { zValidator } from "@hono/zod-validator"
|
||||||
import { Resource } from "sst"
|
import { Resource } from "sst"
|
||||||
import { generateText, streamText } from "ai"
|
import { type ProviderMetadata, type LanguageModelUsage, generateText, streamText } from "ai"
|
||||||
import { createAnthropic } from "@ai-sdk/anthropic"
|
import { createAnthropic } from "@ai-sdk/anthropic"
|
||||||
import { createOpenAI } from "@ai-sdk/openai"
|
import { createOpenAI } from "@ai-sdk/openai"
|
||||||
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
|
||||||
import type { LanguageModelV2Usage, LanguageModelV2Prompt } from "@ai-sdk/provider"
|
import type { LanguageModelV2Prompt } from "@ai-sdk/provider"
|
||||||
import { type ChatCompletionCreateParamsBase } from "openai/resources/chat/completions"
|
import { type ChatCompletionCreateParamsBase } from "openai/resources/chat/completions"
|
||||||
import { Actor } from "@opencode/cloud-core/actor.js"
|
import { Actor } from "@opencode/cloud-core/actor.js"
|
||||||
import { and, Database, eq, sql } from "@opencode/cloud-core/drizzle/index.js"
|
import { and, Database, eq, sql } from "@opencode/cloud-core/drizzle/index.js"
|
||||||
@@ -178,469 +178,491 @@ const RestAuth: MiddlewareHandler = async (c, next) => {
|
|||||||
const app = new Hono<{ Bindings: Env; Variables: { keyRecord?: { id: string; workspaceID: string } } }>()
|
const app = new Hono<{ Bindings: Env; Variables: { keyRecord?: { id: string; workspaceID: string } } }>()
|
||||||
.get("/", (c) => c.text("Hello, world!"))
|
.get("/", (c) => c.text("Hello, world!"))
|
||||||
.post("/v1/chat/completions", GatewayAuth, async (c) => {
|
.post("/v1/chat/completions", GatewayAuth, async (c) => {
|
||||||
try {
|
const keyRecord = c.get("keyRecord")!
|
||||||
const body = await c.req.json<ChatCompletionCreateParamsBase>()
|
|
||||||
|
|
||||||
console.log(body)
|
return await Actor.provide("system", { workspaceID: keyRecord.workspaceID }, async () => {
|
||||||
|
try {
|
||||||
const model = SUPPORTED_MODELS[body.model as keyof typeof SUPPORTED_MODELS]?.model()
|
// Check balance
|
||||||
if (!model) throw new Error(`Unsupported model: ${body.model}`)
|
const customer = await Billing.get()
|
||||||
|
if (customer.balance <= 0) {
|
||||||
const requestBody = transformOpenAIRequestToAiSDK()
|
return c.json(
|
||||||
|
|
||||||
return body.stream ? await handleStream() : await handleGenerate()
|
|
||||||
|
|
||||||
async function handleStream() {
|
|
||||||
const result = await streamText({
|
|
||||||
model,
|
|
||||||
...requestBody,
|
|
||||||
})
|
|
||||||
|
|
||||||
const encoder = new TextEncoder()
|
|
||||||
const stream = new ReadableStream({
|
|
||||||
async start(controller) {
|
|
||||||
const id = `chatcmpl-${Date.now()}`
|
|
||||||
const created = Math.floor(Date.now() / 1000)
|
|
||||||
|
|
||||||
try {
|
|
||||||
for await (const chunk of result.fullStream) {
|
|
||||||
// TODO
|
|
||||||
//console.log("!!! CHUCK !!!", chunk);
|
|
||||||
switch (chunk.type) {
|
|
||||||
case "text-delta": {
|
|
||||||
const data = {
|
|
||||||
id,
|
|
||||||
object: "chat.completion.chunk",
|
|
||||||
created,
|
|
||||||
model: body.model,
|
|
||||||
choices: [
|
|
||||||
{
|
|
||||||
index: 0,
|
|
||||||
delta: {
|
|
||||||
content: chunk.text,
|
|
||||||
},
|
|
||||||
finish_reason: null,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case "reasoning-delta": {
|
|
||||||
const data = {
|
|
||||||
id,
|
|
||||||
object: "chat.completion.chunk",
|
|
||||||
created,
|
|
||||||
model: body.model,
|
|
||||||
choices: [
|
|
||||||
{
|
|
||||||
index: 0,
|
|
||||||
delta: {
|
|
||||||
reasoning_content: chunk.text,
|
|
||||||
},
|
|
||||||
finish_reason: null,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case "tool-call": {
|
|
||||||
const data = {
|
|
||||||
id,
|
|
||||||
object: "chat.completion.chunk",
|
|
||||||
created,
|
|
||||||
model: body.model,
|
|
||||||
choices: [
|
|
||||||
{
|
|
||||||
index: 0,
|
|
||||||
delta: {
|
|
||||||
tool_calls: [
|
|
||||||
{
|
|
||||||
id: chunk.toolCallId,
|
|
||||||
type: "function",
|
|
||||||
function: {
|
|
||||||
name: chunk.toolName,
|
|
||||||
arguments: JSON.stringify(chunk.input),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
finish_reason: null,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case "error": {
|
|
||||||
const data = {
|
|
||||||
id,
|
|
||||||
object: "chat.completion.chunk",
|
|
||||||
created,
|
|
||||||
model: body.model,
|
|
||||||
error: {
|
|
||||||
message: chunk.error,
|
|
||||||
type: "server_error",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
|
||||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
|
||||||
controller.close()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case "finish": {
|
|
||||||
const finishReason =
|
|
||||||
{
|
|
||||||
stop: "stop",
|
|
||||||
length: "length",
|
|
||||||
"content-filter": "content_filter",
|
|
||||||
"tool-calls": "tool_calls",
|
|
||||||
error: "stop",
|
|
||||||
other: "stop",
|
|
||||||
unknown: "stop",
|
|
||||||
}[chunk.finishReason] || "stop"
|
|
||||||
|
|
||||||
const data = {
|
|
||||||
id,
|
|
||||||
object: "chat.completion.chunk",
|
|
||||||
created,
|
|
||||||
model: body.model,
|
|
||||||
choices: [
|
|
||||||
{
|
|
||||||
index: 0,
|
|
||||||
delta: {},
|
|
||||||
finish_reason: finishReason,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
usage: {
|
|
||||||
prompt_tokens: chunk.totalUsage.inputTokens,
|
|
||||||
completion_tokens: chunk.totalUsage.outputTokens,
|
|
||||||
total_tokens: chunk.totalUsage.totalTokens,
|
|
||||||
completion_tokens_details: {
|
|
||||||
reasoning_tokens: chunk.totalUsage.reasoningTokens,
|
|
||||||
},
|
|
||||||
prompt_tokens_details: {
|
|
||||||
cached_tokens: chunk.totalUsage.cachedInputTokens,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
|
||||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
|
||||||
controller.close()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
//case "stream-start":
|
|
||||||
//case "response-metadata":
|
|
||||||
case "start-step":
|
|
||||||
case "finish-step":
|
|
||||||
case "text-start":
|
|
||||||
case "text-end":
|
|
||||||
case "reasoning-start":
|
|
||||||
case "reasoning-end":
|
|
||||||
case "tool-input-start":
|
|
||||||
case "tool-input-delta":
|
|
||||||
case "tool-input-end":
|
|
||||||
case "raw":
|
|
||||||
default:
|
|
||||||
// Log unknown chunk types for debugging
|
|
||||||
console.warn(`Unknown chunk type: ${(chunk as any).type}`)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
controller.error(error)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return new Response(stream, {
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "text/plain; charset=utf-8",
|
|
||||||
"Cache-Control": "no-cache",
|
|
||||||
Connection: "keep-alive",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleGenerate() {
|
|
||||||
const response = await generateText({
|
|
||||||
model,
|
|
||||||
...requestBody,
|
|
||||||
})
|
|
||||||
await trackUsage(body.model, response.usage)
|
|
||||||
return c.json({
|
|
||||||
id: `chatcmpl-${Date.now()}`,
|
|
||||||
object: "chat.completion" as const,
|
|
||||||
created: Math.floor(Date.now() / 1000),
|
|
||||||
model: body.model,
|
|
||||||
choices: [
|
|
||||||
{
|
{
|
||||||
index: 0,
|
error: {
|
||||||
message: {
|
message: "Insufficient balance",
|
||||||
role: "assistant" as const,
|
type: "insufficient_quota",
|
||||||
content: response.content?.find((c) => c.type === "text")?.text ?? "",
|
param: null,
|
||||||
reasoning_content: response.content?.find((c) => c.type === "reasoning")?.text,
|
code: "insufficient_quota",
|
||||||
tool_calls: response.content
|
|
||||||
?.filter((c) => c.type === "tool-call")
|
|
||||||
.map((toolCall) => ({
|
|
||||||
id: toolCall.toolCallId,
|
|
||||||
type: "function" as const,
|
|
||||||
function: {
|
|
||||||
name: toolCall.toolName,
|
|
||||||
arguments: toolCall.input,
|
|
||||||
},
|
|
||||||
})),
|
|
||||||
},
|
},
|
||||||
finish_reason:
|
|
||||||
(
|
|
||||||
{
|
|
||||||
stop: "stop",
|
|
||||||
length: "length",
|
|
||||||
"content-filter": "content_filter",
|
|
||||||
"tool-calls": "tool_calls",
|
|
||||||
error: "stop",
|
|
||||||
other: "stop",
|
|
||||||
unknown: "stop",
|
|
||||||
} as const
|
|
||||||
)[response.finishReason] || "stop",
|
|
||||||
},
|
},
|
||||||
],
|
401,
|
||||||
usage: {
|
)
|
||||||
prompt_tokens: response.usage?.inputTokens,
|
|
||||||
completion_tokens: response.usage?.outputTokens,
|
|
||||||
total_tokens: response.usage?.totalTokens,
|
|
||||||
completion_tokens_details: {
|
|
||||||
reasoning_tokens: response.usage?.reasoningTokens,
|
|
||||||
},
|
|
||||||
prompt_tokens_details: {
|
|
||||||
cached_tokens: response.usage?.cachedInputTokens,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function transformOpenAIRequestToAiSDK() {
|
|
||||||
const prompt = transformMessages()
|
|
||||||
|
|
||||||
return {
|
|
||||||
prompt,
|
|
||||||
maxOutputTokens: body.max_tokens ?? body.max_completion_tokens ?? undefined,
|
|
||||||
temperature: body.temperature ?? undefined,
|
|
||||||
topP: body.top_p ?? undefined,
|
|
||||||
frequencyPenalty: body.frequency_penalty ?? undefined,
|
|
||||||
presencePenalty: body.presence_penalty ?? undefined,
|
|
||||||
providerOptions: body.reasoning_effort
|
|
||||||
? {
|
|
||||||
anthropic: {
|
|
||||||
reasoningEffort: body.reasoning_effort,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
stopSequences: (typeof body.stop === "string" ? [body.stop] : body.stop) ?? undefined,
|
|
||||||
responseFormat: (() => {
|
|
||||||
if (!body.response_format) return { type: "text" }
|
|
||||||
if (body.response_format.type === "json_schema")
|
|
||||||
return {
|
|
||||||
type: "json",
|
|
||||||
schema: body.response_format.json_schema.schema,
|
|
||||||
name: body.response_format.json_schema.name,
|
|
||||||
description: body.response_format.json_schema.description,
|
|
||||||
}
|
|
||||||
if (body.response_format.type === "json_object") return { type: "json" }
|
|
||||||
throw new Error("Unsupported response format")
|
|
||||||
})(),
|
|
||||||
seed: body.seed ?? undefined,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function transformTools() {
|
const body = await c.req.json<ChatCompletionCreateParamsBase>()
|
||||||
const { tools, tool_choice } = body
|
const model = SUPPORTED_MODELS[body.model as keyof typeof SUPPORTED_MODELS]?.model()
|
||||||
|
if (!model) throw new Error(`Unsupported model: ${body.model}`)
|
||||||
|
|
||||||
if (!tools || tools.length === 0) {
|
const requestBody = transformOpenAIRequestToAiSDK()
|
||||||
return { tools: undefined, toolChoice: undefined }
|
|
||||||
|
return body.stream ? await handleStream() : await handleGenerate()
|
||||||
|
|
||||||
|
async function handleStream() {
|
||||||
|
const result = await model.doStream({
|
||||||
|
...requestBody,
|
||||||
|
})
|
||||||
|
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
const stream = new ReadableStream({
|
||||||
|
async start(controller) {
|
||||||
|
const id = `chatcmpl-${Date.now()}`
|
||||||
|
const created = Math.floor(Date.now() / 1000)
|
||||||
|
|
||||||
|
try {
|
||||||
|
for await (const chunk of result.stream) {
|
||||||
|
console.log("!!! CHUNK !!! : " + chunk.type)
|
||||||
|
switch (chunk.type) {
|
||||||
|
case "text-delta": {
|
||||||
|
const data = {
|
||||||
|
id,
|
||||||
|
object: "chat.completion.chunk",
|
||||||
|
created,
|
||||||
|
model: body.model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
delta: {
|
||||||
|
content: chunk.delta,
|
||||||
|
},
|
||||||
|
finish_reason: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case "reasoning-delta": {
|
||||||
|
const data = {
|
||||||
|
id,
|
||||||
|
object: "chat.completion.chunk",
|
||||||
|
created,
|
||||||
|
model: body.model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
delta: {
|
||||||
|
reasoning_content: chunk.delta,
|
||||||
|
},
|
||||||
|
finish_reason: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tool-call": {
|
||||||
|
const data = {
|
||||||
|
id,
|
||||||
|
object: "chat.completion.chunk",
|
||||||
|
created,
|
||||||
|
model: body.model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
delta: {
|
||||||
|
tool_calls: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
id: chunk.toolCallId,
|
||||||
|
type: "function",
|
||||||
|
function: {
|
||||||
|
name: chunk.toolName,
|
||||||
|
arguments: chunk.input,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
finish_reason: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case "error": {
|
||||||
|
const data = {
|
||||||
|
id,
|
||||||
|
object: "chat.completion.chunk",
|
||||||
|
created,
|
||||||
|
model: body.model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
delta: {},
|
||||||
|
finish_reason: "stop",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
error: {
|
||||||
|
message: typeof chunk.error === "string" ? chunk.error : chunk.error,
|
||||||
|
type: "server_error",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||||
|
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||||
|
controller.close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case "finish": {
|
||||||
|
const data = {
|
||||||
|
id,
|
||||||
|
object: "chat.completion.chunk",
|
||||||
|
created,
|
||||||
|
model: body.model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
delta: {},
|
||||||
|
finish_reason:
|
||||||
|
{
|
||||||
|
stop: "stop",
|
||||||
|
length: "length",
|
||||||
|
"content-filter": "content_filter",
|
||||||
|
"tool-calls": "tool_calls",
|
||||||
|
error: "stop",
|
||||||
|
other: "stop",
|
||||||
|
unknown: "stop",
|
||||||
|
}[chunk.finishReason] || "stop",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
usage: {
|
||||||
|
prompt_tokens: chunk.usage.inputTokens,
|
||||||
|
completion_tokens: chunk.usage.outputTokens,
|
||||||
|
total_tokens: chunk.usage.totalTokens,
|
||||||
|
completion_tokens_details: {
|
||||||
|
reasoning_tokens: chunk.usage.reasoningTokens,
|
||||||
|
},
|
||||||
|
prompt_tokens_details: {
|
||||||
|
cached_tokens: chunk.usage.cachedInputTokens,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
await trackUsage(body.model, chunk.usage, chunk.providerMetadata)
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||||
|
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||||
|
controller.close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
//case "stream-start":
|
||||||
|
//case "response-metadata":
|
||||||
|
case "text-start":
|
||||||
|
case "text-end":
|
||||||
|
case "reasoning-start":
|
||||||
|
case "reasoning-end":
|
||||||
|
case "tool-input-start":
|
||||||
|
case "tool-input-delta":
|
||||||
|
case "tool-input-end":
|
||||||
|
case "raw":
|
||||||
|
default:
|
||||||
|
// Log unknown chunk types for debugging
|
||||||
|
console.warn(`Unknown chunk type: ${(chunk as any).type}`)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return new Response(stream, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/plain; charset=utf-8",
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
Connection: "keep-alive",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGenerate() {
|
||||||
|
const response = await model.doGenerate({
|
||||||
|
...requestBody,
|
||||||
|
})
|
||||||
|
await trackUsage(body.model, response.usage, response.providerMetadata)
|
||||||
|
return c.json({
|
||||||
|
id: `chatcmpl-${Date.now()}`,
|
||||||
|
object: "chat.completion" as const,
|
||||||
|
created: Math.floor(Date.now() / 1000),
|
||||||
|
model: body.model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
message: {
|
||||||
|
role: "assistant" as const,
|
||||||
|
content: response.content?.find((c) => c.type === "text")?.text ?? "",
|
||||||
|
reasoning_content: response.content?.find((c) => c.type === "reasoning")?.text,
|
||||||
|
tool_calls: response.content
|
||||||
|
?.filter((c) => c.type === "tool-call")
|
||||||
|
.map((toolCall) => ({
|
||||||
|
id: toolCall.toolCallId,
|
||||||
|
type: "function" as const,
|
||||||
|
function: {
|
||||||
|
name: toolCall.toolName,
|
||||||
|
arguments: toolCall.input,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
finish_reason:
|
||||||
|
(
|
||||||
|
{
|
||||||
|
stop: "stop",
|
||||||
|
length: "length",
|
||||||
|
"content-filter": "content_filter",
|
||||||
|
"tool-calls": "tool_calls",
|
||||||
|
error: "stop",
|
||||||
|
other: "stop",
|
||||||
|
unknown: "stop",
|
||||||
|
} as const
|
||||||
|
)[response.finishReason] || "stop",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
usage: {
|
||||||
|
prompt_tokens: response.usage?.inputTokens,
|
||||||
|
completion_tokens: response.usage?.outputTokens,
|
||||||
|
total_tokens: response.usage?.totalTokens,
|
||||||
|
completion_tokens_details: {
|
||||||
|
reasoning_tokens: response.usage?.reasoningTokens,
|
||||||
|
},
|
||||||
|
prompt_tokens_details: {
|
||||||
|
cached_tokens: response.usage?.cachedInputTokens,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformOpenAIRequestToAiSDK() {
|
||||||
|
const prompt = transformMessages()
|
||||||
|
const tools = transformTools()
|
||||||
|
|
||||||
|
return {
|
||||||
|
prompt,
|
||||||
|
maxOutputTokens: body.max_tokens ?? body.max_completion_tokens ?? undefined,
|
||||||
|
temperature: body.temperature ?? undefined,
|
||||||
|
topP: body.top_p ?? undefined,
|
||||||
|
frequencyPenalty: body.frequency_penalty ?? undefined,
|
||||||
|
presencePenalty: body.presence_penalty ?? undefined,
|
||||||
|
providerOptions: body.reasoning_effort
|
||||||
|
? {
|
||||||
|
anthropic: {
|
||||||
|
reasoningEffort: body.reasoning_effort,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
stopSequences: (typeof body.stop === "string" ? [body.stop] : body.stop) ?? undefined,
|
||||||
|
responseFormat: (() => {
|
||||||
|
if (!body.response_format) return { type: "text" as const }
|
||||||
|
if (body.response_format.type === "json_schema")
|
||||||
|
return {
|
||||||
|
type: "json" as const,
|
||||||
|
schema: body.response_format.json_schema.schema,
|
||||||
|
name: body.response_format.json_schema.name,
|
||||||
|
description: body.response_format.json_schema.description,
|
||||||
|
}
|
||||||
|
if (body.response_format.type === "json_object") return { type: "json" as const }
|
||||||
|
throw new Error("Unsupported response format")
|
||||||
|
})(),
|
||||||
|
seed: body.seed ?? undefined,
|
||||||
|
tools: tools.tools,
|
||||||
|
toolChoice: tools.toolChoice,
|
||||||
}
|
}
|
||||||
|
|
||||||
const aiSdkTools = tools.reduce(
|
function transformTools() {
|
||||||
(acc, tool) => {
|
const { tools, tool_choice } = body
|
||||||
acc[tool.function.name] = {
|
|
||||||
type: "function" as const,
|
if (!tools || tools.length === 0) {
|
||||||
|
return { tools: undefined, toolChoice: undefined }
|
||||||
|
}
|
||||||
|
|
||||||
|
const aiSdkTools = tools.map((tool) => {
|
||||||
|
return {
|
||||||
|
type: tool.type,
|
||||||
name: tool.function.name,
|
name: tool.function.name,
|
||||||
description: tool.function.description,
|
description: tool.function.description,
|
||||||
inputSchema: tool.function.parameters,
|
inputSchema: tool.function.parameters!,
|
||||||
}
|
}
|
||||||
return acc
|
})
|
||||||
},
|
|
||||||
{} as Record<string, any>,
|
|
||||||
)
|
|
||||||
|
|
||||||
let aiSdkToolChoice
|
let aiSdkToolChoice
|
||||||
if (tool_choice == null) {
|
if (tool_choice == null) {
|
||||||
aiSdkToolChoice = undefined
|
aiSdkToolChoice = undefined
|
||||||
} else if (tool_choice === "auto") {
|
} else if (tool_choice === "auto") {
|
||||||
aiSdkToolChoice = "auto"
|
aiSdkToolChoice = { type: "auto" as const }
|
||||||
} else if (tool_choice === "none") {
|
} else if (tool_choice === "none") {
|
||||||
aiSdkToolChoice = "none"
|
aiSdkToolChoice = { type: "none" as const }
|
||||||
} else if (tool_choice === "required") {
|
} else if (tool_choice === "required") {
|
||||||
aiSdkToolChoice = "required"
|
aiSdkToolChoice = { type: "required" as const }
|
||||||
} else if (tool_choice.type === "function") {
|
} else if (tool_choice.type === "function") {
|
||||||
aiSdkToolChoice = {
|
aiSdkToolChoice = {
|
||||||
type: "tool",
|
type: "tool" as const,
|
||||||
toolName: tool_choice.function.name,
|
toolName: tool_choice.function.name,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return { tools: aiSdkTools, toolChoice: aiSdkToolChoice }
|
||||||
}
|
}
|
||||||
|
|
||||||
return { tools: aiSdkTools, toolChoice: aiSdkToolChoice }
|
function transformMessages() {
|
||||||
}
|
const { messages } = body
|
||||||
|
const prompt: LanguageModelV2Prompt = []
|
||||||
|
|
||||||
function transformMessages() {
|
for (const message of messages) {
|
||||||
const { messages } = body
|
switch (message.role) {
|
||||||
const prompt: LanguageModelV2Prompt = []
|
case "system": {
|
||||||
|
|
||||||
for (const message of messages) {
|
|
||||||
switch (message.role) {
|
|
||||||
case "system": {
|
|
||||||
prompt.push({
|
|
||||||
role: "system",
|
|
||||||
content: message.content as string,
|
|
||||||
})
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case "user": {
|
|
||||||
if (typeof message.content === "string") {
|
|
||||||
prompt.push({
|
prompt.push({
|
||||||
role: "user",
|
role: "system",
|
||||||
content: [{ type: "text", text: message.content }],
|
content: message.content as string,
|
||||||
})
|
|
||||||
} else {
|
|
||||||
const content = message.content.map((part) => {
|
|
||||||
switch (part.type) {
|
|
||||||
case "text":
|
|
||||||
return { type: "text" as const, text: part.text }
|
|
||||||
case "image_url":
|
|
||||||
return {
|
|
||||||
type: "file" as const,
|
|
||||||
mediaType: "image/jpeg" as const,
|
|
||||||
data: part.image_url.url,
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
throw new Error(`Unsupported content part type: ${(part as any).type}`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
prompt.push({
|
|
||||||
role: "user",
|
|
||||||
content,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
case "assistant": {
|
|
||||||
const content: Array<
|
|
||||||
| { type: "text"; text: string }
|
|
||||||
| {
|
|
||||||
type: "tool-call"
|
|
||||||
toolCallId: string
|
|
||||||
toolName: string
|
|
||||||
input: any
|
|
||||||
}
|
|
||||||
> = []
|
|
||||||
|
|
||||||
if (message.content) {
|
|
||||||
content.push({
|
|
||||||
type: "text",
|
|
||||||
text: message.content as string,
|
|
||||||
})
|
})
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.tool_calls) {
|
case "user": {
|
||||||
for (const toolCall of message.tool_calls) {
|
if (typeof message.content === "string") {
|
||||||
content.push({
|
prompt.push({
|
||||||
type: "tool-call",
|
role: "user",
|
||||||
toolCallId: toolCall.id,
|
content: [{ type: "text", text: message.content }],
|
||||||
toolName: toolCall.function.name,
|
})
|
||||||
input: JSON.parse(toolCall.function.arguments),
|
} else {
|
||||||
|
const content = message.content.map((part) => {
|
||||||
|
switch (part.type) {
|
||||||
|
case "text":
|
||||||
|
return { type: "text" as const, text: part.text }
|
||||||
|
case "image_url":
|
||||||
|
return {
|
||||||
|
type: "file" as const,
|
||||||
|
mediaType: "image/jpeg" as const,
|
||||||
|
data: part.image_url.url,
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error(`Unsupported content part type: ${(part as any).type}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
prompt.push({
|
||||||
|
role: "user",
|
||||||
|
content,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
prompt.push({
|
case "assistant": {
|
||||||
role: "assistant",
|
const content: Array<
|
||||||
content,
|
| { type: "text"; text: string }
|
||||||
})
|
| {
|
||||||
break
|
type: "tool-call"
|
||||||
}
|
toolCallId: string
|
||||||
|
toolName: string
|
||||||
|
input: any
|
||||||
|
}
|
||||||
|
> = []
|
||||||
|
|
||||||
case "tool": {
|
if (message.content) {
|
||||||
prompt.push({
|
content.push({
|
||||||
role: "tool",
|
type: "text",
|
||||||
content: [
|
text: message.content as string,
|
||||||
{
|
})
|
||||||
type: "tool-result",
|
}
|
||||||
toolName: "placeholder",
|
|
||||||
toolCallId: message.tool_call_id,
|
if (message.tool_calls) {
|
||||||
output: {
|
for (const toolCall of message.tool_calls) {
|
||||||
type: "text",
|
content.push({
|
||||||
value: message.content as string,
|
type: "tool-call",
|
||||||
|
toolCallId: toolCall.id,
|
||||||
|
toolName: toolCall.function.name,
|
||||||
|
input: JSON.parse(toolCall.function.arguments),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt.push({
|
||||||
|
role: "assistant",
|
||||||
|
content,
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tool": {
|
||||||
|
prompt.push({
|
||||||
|
role: "tool",
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "tool-result",
|
||||||
|
toolName: "placeholder",
|
||||||
|
toolCallId: message.tool_call_id,
|
||||||
|
output: {
|
||||||
|
type: "text",
|
||||||
|
value: message.content as string,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
],
|
||||||
],
|
})
|
||||||
})
|
break
|
||||||
break
|
}
|
||||||
}
|
|
||||||
|
|
||||||
default: {
|
default: {
|
||||||
throw new Error(`Unsupported message role: ${message.role}`)
|
throw new Error(`Unsupported message role: ${message.role}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return prompt
|
||||||
}
|
}
|
||||||
|
|
||||||
return prompt
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
async function trackUsage(model: string, usage: LanguageModelV2Usage) {
|
async function trackUsage(model: string, usage: LanguageModelUsage, providerMetadata?: ProviderMetadata) {
|
||||||
const keyRecord = c.get("keyRecord")
|
const modelData = SUPPORTED_MODELS[model as keyof typeof SUPPORTED_MODELS]
|
||||||
if (!keyRecord) return
|
if (!modelData) throw new Error(`Unsupported model: ${model}`)
|
||||||
|
|
||||||
const modelData = SUPPORTED_MODELS[model as keyof typeof SUPPORTED_MODELS]
|
const inputTokens = usage.inputTokens ?? 0
|
||||||
if (!modelData) throw new Error(`Unsupported model: ${model}`)
|
const outputTokens = usage.outputTokens ?? 0
|
||||||
|
const reasoningTokens = usage.reasoningTokens ?? 0
|
||||||
|
const cacheReadTokens = usage.cachedInputTokens ?? 0
|
||||||
|
const cacheWriteTokens =
|
||||||
|
providerMetadata?.["anthropic"]?.["cacheCreationInputTokens"] ??
|
||||||
|
// @ts-expect-error
|
||||||
|
providerMetadata?.["bedrock"]?.["usage"]?.["cacheWriteInputTokens"] ??
|
||||||
|
0
|
||||||
|
|
||||||
const inputCost = modelData.input * (usage.inputTokens ?? 0)
|
const inputCost = modelData.input * inputTokens
|
||||||
const outputCost = modelData.output * (usage.outputTokens ?? 0)
|
const outputCost = modelData.output * outputTokens
|
||||||
const reasoningCost = modelData.reasoning * (usage.reasoningTokens ?? 0)
|
const reasoningCost = modelData.reasoning * reasoningTokens
|
||||||
const cacheReadCost = modelData.cacheRead * (usage.cachedInputTokens ?? 0)
|
const cacheReadCost = modelData.cacheRead * cacheReadTokens
|
||||||
const cacheWriteCost = modelData.cacheWrite * (usage.outputTokens ?? 0)
|
const cacheWriteCost = modelData.cacheWrite * cacheWriteTokens
|
||||||
|
const costInCents = (inputCost + outputCost + reasoningCost + cacheReadCost + cacheWriteCost) * 100
|
||||||
|
|
||||||
const totalCost = inputCost + outputCost + reasoningCost + cacheReadCost + cacheWriteCost
|
|
||||||
|
|
||||||
await Actor.provide("system", { workspaceID: keyRecord.workspaceID }, async () => {
|
|
||||||
await Billing.consume({
|
await Billing.consume({
|
||||||
model,
|
model,
|
||||||
inputTokens: usage.inputTokens ?? 0,
|
inputTokens,
|
||||||
outputTokens: usage.outputTokens ?? 0,
|
outputTokens,
|
||||||
reasoningTokens: usage.reasoningTokens ?? 0,
|
reasoningTokens,
|
||||||
cacheReadTokens: usage.cachedInputTokens ?? 0,
|
cacheReadTokens,
|
||||||
cacheWriteTokens: usage.outputTokens ?? 0,
|
cacheWriteTokens,
|
||||||
costInCents: totalCost * 100,
|
costInCents,
|
||||||
})
|
})
|
||||||
})
|
|
||||||
|
|
||||||
await Database.use((tx) =>
|
await Database.use((tx) =>
|
||||||
tx
|
tx
|
||||||
.update(KeyTable)
|
.update(KeyTable)
|
||||||
.set({ timeUsed: sql`now()` })
|
.set({ timeUsed: sql`now()` })
|
||||||
.where(eq(KeyTable.id, keyRecord.id)),
|
.where(eq(KeyTable.id, keyRecord.id)),
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
return c.json({ error: { message: error.message } }, 500)
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
})
|
||||||
return c.json({ error: { message: error.message } }, 500)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.use("/*", cors())
|
.use("/*", cors())
|
||||||
.use(RestAuth)
|
.use(RestAuth)
|
||||||
@@ -699,7 +721,7 @@ const app = new Hono<{ Bindings: Env; Variables: { keyRecord?: { id: string; wor
|
|||||||
price_data: {
|
price_data: {
|
||||||
currency: "usd",
|
currency: "usd",
|
||||||
product_data: {
|
product_data: {
|
||||||
name: "OpenControl credits",
|
name: "opencode credits",
|
||||||
},
|
},
|
||||||
unit_amount: 2000, // $20 minimum
|
unit_amount: 2000, // $20 minimum
|
||||||
},
|
},
|
||||||
|
|||||||
Vendored
+4
@@ -50,6 +50,10 @@ declare module "sst" {
|
|||||||
"type": "sst.sst.Secret"
|
"type": "sst.sst.Secret"
|
||||||
"value": string
|
"value": string
|
||||||
}
|
}
|
||||||
|
"GOOGLE_CLIENT_ID": {
|
||||||
|
"type": "sst.sst.Secret"
|
||||||
|
"value": string
|
||||||
|
}
|
||||||
"OPENAI_API_KEY": {
|
"OPENAI_API_KEY": {
|
||||||
"type": "sst.sst.Secret"
|
"type": "sst.sst.Secret"
|
||||||
"value": string
|
"value": string
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode/cloud-web",
|
"name": "@opencode/cloud-web",
|
||||||
"version": "0.0.0",
|
"version": "0.4.13",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "",
|
"description": "",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -24,9 +24,12 @@ export default function Index() {
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section data-slot="cta">
|
<section data-slot="cta">
|
||||||
<div data-slot="col-2">
|
<div>
|
||||||
<span onClick={() => auth.authorize({ provider: "github" })}>Sign in with GitHub</span>
|
<span onClick={() => auth.authorize({ provider: "github" })}>Sign in with GitHub</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<span onClick={() => auth.authorize({ provider: "google" })}>Sign in with Google</span>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -80,90 +80,4 @@
|
|||||||
border-left: 2px solid var(--color-border);
|
border-left: 2px solid var(--color-border);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-slot="images"] {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
align-items: stretch;
|
|
||||||
justify-content: space-between;
|
|
||||||
border-top: 2px solid var(--color-border);
|
|
||||||
|
|
||||||
& > div {
|
|
||||||
flex: 1;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: calc(var(--padding) / 4);
|
|
||||||
padding: calc(var(--padding) / 2);
|
|
||||||
border-width: 0;
|
|
||||||
border-style: solid;
|
|
||||||
border-color: var(--color-border);
|
|
||||||
|
|
||||||
& > div, a {
|
|
||||||
flex: 1;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
letter-spacing: -0.03125rem;
|
|
||||||
text-transform: uppercase;
|
|
||||||
color: var(--color-text-dimmed);
|
|
||||||
}
|
|
||||||
|
|
||||||
& > div + div {
|
|
||||||
border-width: 0 0 0 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 30rem) {
|
|
||||||
& {
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
& > div + div {
|
|
||||||
border-width: 2px 0 0 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[data-slot="content"] {
|
|
||||||
border-top: 2px solid var(--color-border);
|
|
||||||
padding: var(--padding);
|
|
||||||
|
|
||||||
& > p {
|
|
||||||
line-height: var(--font-line-height);
|
|
||||||
}
|
|
||||||
|
|
||||||
ol {
|
|
||||||
margin-top: calc(var(--vertical-padding) / 2);
|
|
||||||
padding-left: 2.5rem;
|
|
||||||
list-style-type: decimal;
|
|
||||||
line-height: var(--font-line-height);
|
|
||||||
|
|
||||||
& > li + li {
|
|
||||||
margin-top: calc(var(--vertical-padding) / 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
& > li b {
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
[data-slot="footer"] {
|
|
||||||
border-top: 2px solid var(--color-border);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
|
|
||||||
& > div {
|
|
||||||
flex: 1;
|
|
||||||
text-align: center;
|
|
||||||
text-transform: uppercase;
|
|
||||||
padding: calc(var(--padding) / 2) 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
& > div + div {
|
|
||||||
border-left: 2px solid var(--color-border);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-32
@@ -2,6 +2,50 @@ import { WebhookEndpoint } from "pulumi-stripe"
|
|||||||
import { domain } from "./stage"
|
import { domain } from "./stage"
|
||||||
import { web } from "./app"
|
import { web } from "./app"
|
||||||
|
|
||||||
|
////////////////
|
||||||
|
// DATABASE
|
||||||
|
////////////////
|
||||||
|
|
||||||
|
const DATABASE_USERNAME = new sst.Secret("DATABASE_USERNAME")
|
||||||
|
const DATABASE_PASSWORD = new sst.Secret("DATABASE_PASSWORD")
|
||||||
|
export const database = new sst.Linkable("Database", {
|
||||||
|
properties: {
|
||||||
|
host: "aws-us-east-2-1.pg.psdb.cloud",
|
||||||
|
database: "postgres",
|
||||||
|
username: DATABASE_USERNAME.value,
|
||||||
|
password: DATABASE_PASSWORD.value,
|
||||||
|
port: 5432,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
new sst.x.DevCommand("Studio", {
|
||||||
|
link: [database],
|
||||||
|
dev: {
|
||||||
|
command: "bun db studio",
|
||||||
|
directory: "cloud/core",
|
||||||
|
autostart: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
////////////////
|
||||||
|
// AUTH
|
||||||
|
////////////////
|
||||||
|
|
||||||
|
const GITHUB_CLIENT_ID_CONSOLE = new sst.Secret("GITHUB_CLIENT_ID_CONSOLE")
|
||||||
|
const GITHUB_CLIENT_SECRET_CONSOLE = new sst.Secret("GITHUB_CLIENT_SECRET_CONSOLE")
|
||||||
|
const GOOGLE_CLIENT_ID = new sst.Secret("GOOGLE_CLIENT_ID")
|
||||||
|
const authStorage = new sst.cloudflare.Kv("AuthStorage")
|
||||||
|
export const auth = new sst.cloudflare.Worker("AuthApi", {
|
||||||
|
domain: `auth.${domain}`,
|
||||||
|
handler: "cloud/function/src/auth.ts",
|
||||||
|
url: true,
|
||||||
|
link: [database, authStorage, GITHUB_CLIENT_ID_CONSOLE, GITHUB_CLIENT_SECRET_CONSOLE, GOOGLE_CLIENT_ID],
|
||||||
|
})
|
||||||
|
|
||||||
|
////////////////
|
||||||
|
// GATEWAY
|
||||||
|
////////////////
|
||||||
|
|
||||||
export const stripeWebhook = new WebhookEndpoint("StripeWebhook", {
|
export const stripeWebhook = new WebhookEndpoint("StripeWebhook", {
|
||||||
url: $interpolate`https://api.gateway.${domain}/stripe/webhook`,
|
url: $interpolate`https://api.gateway.${domain}/stripe/webhook`,
|
||||||
enabledEvents: [
|
enabledEvents: [
|
||||||
@@ -33,41 +77,9 @@ export const stripeWebhook = new WebhookEndpoint("StripeWebhook", {
|
|||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|
||||||
const DATABASE_USERNAME = new sst.Secret("DATABASE_USERNAME")
|
|
||||||
const DATABASE_PASSWORD = new sst.Secret("DATABASE_PASSWORD")
|
|
||||||
export const database = new sst.Linkable("Database", {
|
|
||||||
properties: {
|
|
||||||
host: "aws-us-east-2-1.pg.psdb.cloud",
|
|
||||||
database: "postgres",
|
|
||||||
username: DATABASE_USERNAME.value,
|
|
||||||
password: DATABASE_PASSWORD.value,
|
|
||||||
port: 5432,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
new sst.x.DevCommand("Studio", {
|
|
||||||
link: [database],
|
|
||||||
dev: {
|
|
||||||
command: "bun db studio",
|
|
||||||
directory: "cloud/core",
|
|
||||||
autostart: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const GITHUB_CLIENT_ID_CONSOLE = new sst.Secret("GITHUB_CLIENT_ID_CONSOLE")
|
|
||||||
const GITHUB_CLIENT_SECRET_CONSOLE = new sst.Secret("GITHUB_CLIENT_SECRET_CONSOLE")
|
|
||||||
const authStorage = new sst.cloudflare.Kv("AuthStorage")
|
|
||||||
export const auth = new sst.cloudflare.Worker("AuthApi", {
|
|
||||||
domain: `auth.${domain}`,
|
|
||||||
handler: "cloud/function/src/auth.ts",
|
|
||||||
url: true,
|
|
||||||
link: [database, authStorage, GITHUB_CLIENT_ID_CONSOLE, GITHUB_CLIENT_SECRET_CONSOLE],
|
|
||||||
})
|
|
||||||
|
|
||||||
const ANTHROPIC_API_KEY = new sst.Secret("ANTHROPIC_API_KEY")
|
const ANTHROPIC_API_KEY = new sst.Secret("ANTHROPIC_API_KEY")
|
||||||
const OPENAI_API_KEY = new sst.Secret("OPENAI_API_KEY")
|
const OPENAI_API_KEY = new sst.Secret("OPENAI_API_KEY")
|
||||||
const ZHIPU_API_KEY = new sst.Secret("ZHIPU_API_KEY")
|
const ZHIPU_API_KEY = new sst.Secret("ZHIPU_API_KEY")
|
||||||
|
|
||||||
const STRIPE_SECRET_KEY = new sst.Secret("STRIPE_SECRET_KEY")
|
const STRIPE_SECRET_KEY = new sst.Secret("STRIPE_SECRET_KEY")
|
||||||
const AUTH_API_URL = new sst.Linkable("AUTH_API_URL", {
|
const AUTH_API_URL = new sst.Linkable("AUTH_API_URL", {
|
||||||
properties: { value: auth.url.apply((url) => url!) },
|
properties: { value: auth.url.apply((url) => url!) },
|
||||||
@@ -90,6 +102,10 @@ export const gateway = new sst.cloudflare.Worker("GatewayApi", {
|
|||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
////////////////
|
||||||
|
// CONSOLE
|
||||||
|
////////////////
|
||||||
|
|
||||||
export const console = new sst.cloudflare.x.StaticSite("Console", {
|
export const console = new sst.cloudflare.x.StaticSite("Console", {
|
||||||
domain: `console.${domain}`,
|
domain: `console.${domain}`,
|
||||||
path: "cloud/web",
|
path: "cloud/web",
|
||||||
|
|||||||
@@ -1,25 +1,5 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"provider": {
|
|
||||||
"oc-frank": {
|
|
||||||
"npm": "@ai-sdk/openai-compatible",
|
|
||||||
"name": "OC-Frank",
|
|
||||||
"options": {
|
|
||||||
"baseURL": "https://api.gateway.frank.dev.opencode.ai/v1"
|
|
||||||
},
|
|
||||||
"models": {
|
|
||||||
"anthropic/claude-sonnet-4": {
|
|
||||||
"name": "Claude Sonnet 4"
|
|
||||||
},
|
|
||||||
"openai/gpt-4.1": {
|
|
||||||
"name": "GPT-4.1"
|
|
||||||
},
|
|
||||||
"zhipuai/glm-4.5-flash": {
|
|
||||||
"name": "GLM-4.5 Flash"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"mcp": {
|
"mcp": {
|
||||||
"context7": {
|
"context7": {
|
||||||
"type": "remote",
|
"type": "remote",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode/function",
|
"name": "@opencode/function",
|
||||||
"version": "0.4.1",
|
"version": "0.4.13",
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
Vendored
+4
@@ -50,6 +50,10 @@ declare module "sst" {
|
|||||||
"type": "sst.sst.Secret"
|
"type": "sst.sst.Secret"
|
||||||
"value": string
|
"value": string
|
||||||
}
|
}
|
||||||
|
"GOOGLE_CLIENT_ID": {
|
||||||
|
"type": "sst.sst.Secret"
|
||||||
|
"value": string
|
||||||
|
}
|
||||||
"OPENAI_API_KEY": {
|
"OPENAI_API_KEY": {
|
||||||
"type": "sst.sst.Secret"
|
"type": "sst.sst.Secret"
|
||||||
"value": string
|
"value": string
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"version": "0.4.1",
|
"version": "0.4.13",
|
||||||
"name": "opencode",
|
"name": "opencode",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
|||||||
@@ -39,6 +39,14 @@ for (const [os, arch] of targets) {
|
|||||||
"../tui",
|
"../tui",
|
||||||
)
|
)
|
||||||
await $`bun build --define OPENCODE_TUI_PATH="'../../../dist/${name}/bin/tui'" --define OPENCODE_VERSION="'${version}'" --compile --target=bun-${os}-${arch} --outfile=dist/${name}/bin/opencode ./src/index.ts`
|
await $`bun build --define OPENCODE_TUI_PATH="'../../../dist/${name}/bin/tui'" --define OPENCODE_VERSION="'${version}'" --compile --target=bun-${os}-${arch} --outfile=dist/${name}/bin/opencode ./src/index.ts`
|
||||||
|
// Run the binary only if it matches current OS/arch
|
||||||
|
if (
|
||||||
|
process.platform === (os === "windows" ? "win32" : os) &&
|
||||||
|
(process.arch === arch || (process.arch === "x64" && arch === "x64-baseline"))
|
||||||
|
) {
|
||||||
|
console.log(`smoke test: running dist/${name}/bin/opencode --version`)
|
||||||
|
await $`./dist/${name}/bin/opencode --version`
|
||||||
|
}
|
||||||
await $`rm -rf ./dist/${name}/bin/tui`
|
await $`rm -rf ./dist/${name}/bin/tui`
|
||||||
await Bun.file(`dist/${name}/package.json`).write(
|
await Bun.file(`dist/${name}/package.json`).write(
|
||||||
JSON.stringify(
|
JSON.stringify(
|
||||||
@@ -79,44 +87,10 @@ await Bun.file(`./dist/${pkg.name}/package.json`).write(
|
|||||||
if (!dry) await $`cd ./dist/${pkg.name} && bun publish --access public --tag ${npmTag}`
|
if (!dry) await $`cd ./dist/${pkg.name} && bun publish --access public --tag ${npmTag}`
|
||||||
|
|
||||||
if (!snapshot) {
|
if (!snapshot) {
|
||||||
// Github Release
|
|
||||||
for (const key of Object.keys(optionalDependencies)) {
|
for (const key of Object.keys(optionalDependencies)) {
|
||||||
await $`cd dist/${key}/bin && zip -r ../../${key}.zip *`
|
await $`cd dist/${key}/bin && zip -r ../../${key}.zip *`
|
||||||
}
|
}
|
||||||
|
|
||||||
const previous = await fetch("https://api.github.com/repos/sst/opencode/releases/latest")
|
|
||||||
.then((res) => {
|
|
||||||
if (!res.ok) throw new Error(res.statusText)
|
|
||||||
return res.json()
|
|
||||||
})
|
|
||||||
.then((data) => data.tag_name)
|
|
||||||
|
|
||||||
console.log("finding commits between", previous, "and", "HEAD")
|
|
||||||
const commits = await fetch(`https://api.github.com/repos/sst/opencode/compare/${previous}...HEAD`)
|
|
||||||
.then((res) => res.json())
|
|
||||||
.then((data) => data.commits || [])
|
|
||||||
|
|
||||||
const raw = commits.map((commit: any) => `- ${commit.commit.message.split("\n").join(" ")}`)
|
|
||||||
console.log(raw)
|
|
||||||
|
|
||||||
const notes =
|
|
||||||
raw
|
|
||||||
.filter((x: string) => {
|
|
||||||
const lower = x.toLowerCase()
|
|
||||||
return (
|
|
||||||
!lower.includes("release:") &&
|
|
||||||
!lower.includes("ignore:") &&
|
|
||||||
!lower.includes("chore:") &&
|
|
||||||
!lower.includes("ci:") &&
|
|
||||||
!lower.includes("wip:") &&
|
|
||||||
!lower.includes("docs:") &&
|
|
||||||
!lower.includes("doc:")
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.join("\n") || "No notable changes"
|
|
||||||
|
|
||||||
if (!dry) await $`gh release create v${version} --title "v${version}" --notes ${notes} ./dist/*.zip`
|
|
||||||
|
|
||||||
// Calculate SHA values
|
// Calculate SHA values
|
||||||
const arm64Sha = await $`sha256sum ./dist/opencode-linux-arm64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
|
const arm64Sha = await $`sha256sum ./dist/opencode-linux-arm64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
|
||||||
const x64Sha = await $`sha256sum ./dist/opencode-linux-x64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
|
const x64Sha = await $`sha256sum ./dist/opencode-linux-x64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export namespace Agent {
|
|||||||
.optional(),
|
.optional(),
|
||||||
prompt: z.string().optional(),
|
prompt: z.string().optional(),
|
||||||
tools: z.record(z.boolean()),
|
tools: z.record(z.boolean()),
|
||||||
|
options: z.record(z.string(), z.any()),
|
||||||
})
|
})
|
||||||
.openapi({
|
.openapi({
|
||||||
ref: "Agent",
|
ref: "Agent",
|
||||||
@@ -39,15 +40,18 @@ export namespace Agent {
|
|||||||
todoread: false,
|
todoread: false,
|
||||||
todowrite: false,
|
todowrite: false,
|
||||||
},
|
},
|
||||||
|
options: {},
|
||||||
mode: "subagent",
|
mode: "subagent",
|
||||||
},
|
},
|
||||||
build: {
|
build: {
|
||||||
name: "build",
|
name: "build",
|
||||||
tools: {},
|
tools: {},
|
||||||
|
options: {},
|
||||||
mode: "primary",
|
mode: "primary",
|
||||||
},
|
},
|
||||||
plan: {
|
plan: {
|
||||||
name: "plan",
|
name: "plan",
|
||||||
|
options: {},
|
||||||
tools: {
|
tools: {
|
||||||
write: false,
|
write: false,
|
||||||
edit: false,
|
edit: false,
|
||||||
@@ -66,8 +70,14 @@ export namespace Agent {
|
|||||||
item = result[key] = {
|
item = result[key] = {
|
||||||
name: key,
|
name: key,
|
||||||
mode: "all",
|
mode: "all",
|
||||||
|
options: {},
|
||||||
tools: {},
|
tools: {},
|
||||||
}
|
}
|
||||||
|
const { model, prompt, tools, description, temperature, top_p, mode, ...extra } = value
|
||||||
|
item.options = {
|
||||||
|
...item.options,
|
||||||
|
...extra,
|
||||||
|
}
|
||||||
if (value.model) item.model = Provider.parseModel(value.model)
|
if (value.model) item.model = Provider.parseModel(value.model)
|
||||||
if (value.prompt) item.prompt = value.prompt
|
if (value.prompt) item.prompt = value.prompt
|
||||||
if (value.tools)
|
if (value.tools)
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ const AgentCreateCommand = cmd({
|
|||||||
const query = await prompts.text({
|
const query = await prompts.text({
|
||||||
message: "Description",
|
message: "Description",
|
||||||
placeholder: "What should this agent do?",
|
placeholder: "What should this agent do?",
|
||||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(query)) throw new UI.CancelledError()
|
if (prompts.isCancel(query)) throw new UI.CancelledError()
|
||||||
|
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ export const AuthLoginCommand = cmd({
|
|||||||
if (provider === "other") {
|
if (provider === "other") {
|
||||||
provider = await prompts.text({
|
provider = await prompts.text({
|
||||||
message: "Enter provider id",
|
message: "Enter provider id",
|
||||||
validate: (x) => x && (x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
|
validate: (x) => (x && x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(provider)) throw new UI.CancelledError()
|
if (prompts.isCancel(provider)) throw new UI.CancelledError()
|
||||||
provider = provider.replace(/^@ai-sdk\//, "")
|
provider = provider.replace(/^@ai-sdk\//, "")
|
||||||
@@ -193,7 +193,7 @@ export const AuthLoginCommand = cmd({
|
|||||||
|
|
||||||
const code = await prompts.text({
|
const code = await prompts.text({
|
||||||
message: "Paste the authorization code here: ",
|
message: "Paste the authorization code here: ",
|
||||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(code)) throw new UI.CancelledError()
|
if (prompts.isCancel(code)) throw new UI.CancelledError()
|
||||||
|
|
||||||
@@ -229,7 +229,7 @@ export const AuthLoginCommand = cmd({
|
|||||||
|
|
||||||
const code = await prompts.text({
|
const code = await prompts.text({
|
||||||
message: "Paste the authorization code here: ",
|
message: "Paste the authorization code here: ",
|
||||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(code)) throw new UI.CancelledError()
|
if (prompts.isCancel(code)) throw new UI.CancelledError()
|
||||||
|
|
||||||
@@ -302,7 +302,7 @@ export const AuthLoginCommand = cmd({
|
|||||||
|
|
||||||
const key = await prompts.password({
|
const key = await prompts.password({
|
||||||
message: "Enter your API key",
|
message: "Enter your API key",
|
||||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(key)) throw new UI.CancelledError()
|
if (prompts.isCancel(key)) throw new UI.CancelledError()
|
||||||
await Auth.set(provider, {
|
await Auth.set(provider, {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export const McpAddCommand = cmd({
|
|||||||
|
|
||||||
const name = await prompts.text({
|
const name = await prompts.text({
|
||||||
message: "Enter MCP server name",
|
message: "Enter MCP server name",
|
||||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(name)) throw new UI.CancelledError()
|
if (prompts.isCancel(name)) throw new UI.CancelledError()
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ export const McpAddCommand = cmd({
|
|||||||
const command = await prompts.text({
|
const command = await prompts.text({
|
||||||
message: "Enter command to run",
|
message: "Enter command to run",
|
||||||
placeholder: "e.g., opencode x @modelcontextprotocol/server-filesystem",
|
placeholder: "e.g., opencode x @modelcontextprotocol/server-filesystem",
|
||||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||||
})
|
})
|
||||||
if (prompts.isCancel(command)) throw new UI.CancelledError()
|
if (prompts.isCancel(command)) throw new UI.CancelledError()
|
||||||
|
|
||||||
|
|||||||
@@ -84,10 +84,6 @@ export const RunCommand = cmd({
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
UI.empty()
|
|
||||||
UI.println(UI.logo())
|
|
||||||
UI.empty()
|
|
||||||
|
|
||||||
const cfg = await Config.get()
|
const cfg = await Config.get()
|
||||||
if (cfg.share === "auto" || Flag.OPENCODE_AUTO_SHARE || args.share) {
|
if (cfg.share === "auto" || Flag.OPENCODE_AUTO_SHARE || args.share) {
|
||||||
try {
|
try {
|
||||||
@@ -101,7 +97,6 @@ export const RunCommand = cmd({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
UI.empty()
|
|
||||||
|
|
||||||
const agent = await (async () => {
|
const agent = await (async () => {
|
||||||
if (args.agent) return Agent.get(args.agent)
|
if (args.agent) return Agent.get(args.agent)
|
||||||
@@ -116,9 +111,6 @@ export const RunCommand = cmd({
|
|||||||
return Provider.defaultModel()
|
return Provider.defaultModel()
|
||||||
})()
|
})()
|
||||||
|
|
||||||
UI.println(UI.Style.TEXT_NORMAL_BOLD + "@ ", UI.Style.TEXT_NORMAL + `${providerID}/${modelID}`)
|
|
||||||
UI.empty()
|
|
||||||
|
|
||||||
function printEvent(color: string, type: string, title: string) {
|
function printEvent(color: string, type: string, title: string) {
|
||||||
UI.println(
|
UI.println(
|
||||||
color + `|`,
|
color + `|`,
|
||||||
@@ -137,7 +129,8 @@ export const RunCommand = cmd({
|
|||||||
if (part.type === "tool" && part.state.status === "completed") {
|
if (part.type === "tool" && part.state.status === "completed") {
|
||||||
const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD]
|
const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD]
|
||||||
const title =
|
const title =
|
||||||
part.state.title || Object.keys(part.state.input).length > 0 ? JSON.stringify(part.state.input) : "Unknown"
|
part.state.title ||
|
||||||
|
(Object.keys(part.state.input).length > 0 ? JSON.stringify(part.state.input) : "Unknown")
|
||||||
printEvent(color, tool, title)
|
printEvent(color, tool, title)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { Log } from "../../util/log"
|
|||||||
import { FileWatcher } from "../../file/watch"
|
import { FileWatcher } from "../../file/watch"
|
||||||
import { Ide } from "../../ide"
|
import { Ide } from "../../ide"
|
||||||
import { Agent } from "../../agent/agent"
|
import { Agent } from "../../agent/agent"
|
||||||
|
import { Flag } from "../../flag/flag"
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
const OPENCODE_TUI_PATH: string
|
const OPENCODE_TUI_PATH: string
|
||||||
@@ -126,7 +127,7 @@ export const TuiCommand = cmd({
|
|||||||
if (Installation.isDev()) return
|
if (Installation.isDev()) return
|
||||||
if (Installation.isSnapshot()) return
|
if (Installation.isSnapshot()) return
|
||||||
const config = await Config.global()
|
const config = await Config.global()
|
||||||
if (config.autoupdate === false) return
|
if (config.autoupdate === false || Flag.OPENCODE_DISABLE_AUTOUPDATE) return
|
||||||
const latest = await Installation.latest().catch(() => {})
|
const latest = await Installation.latest().catch(() => {})
|
||||||
if (!latest) return
|
if (!latest) return
|
||||||
if (Installation.VERSION === latest) return
|
if (Installation.VERSION === latest) return
|
||||||
|
|||||||
@@ -175,6 +175,7 @@ export namespace Config {
|
|||||||
description: z.string().optional().describe("Description of when to use the agent"),
|
description: z.string().optional().describe("Description of when to use the agent"),
|
||||||
mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]).optional(),
|
mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]).optional(),
|
||||||
})
|
})
|
||||||
|
.catchall(z.any())
|
||||||
.openapi({
|
.openapi({
|
||||||
ref: "AgentConfig",
|
ref: "AgentConfig",
|
||||||
})
|
})
|
||||||
@@ -341,6 +342,7 @@ export namespace Config {
|
|||||||
.object({
|
.object({
|
||||||
edit: Permission.optional(),
|
edit: Permission.optional(),
|
||||||
bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
|
bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
|
||||||
|
webfetch: Permission.optional(),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
experimental: z
|
experimental: z
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ export namespace Flag {
|
|||||||
export const OPENCODE_AUTO_SHARE = truthy("OPENCODE_AUTO_SHARE")
|
export const OPENCODE_AUTO_SHARE = truthy("OPENCODE_AUTO_SHARE")
|
||||||
export const OPENCODE_DISABLE_WATCHER = truthy("OPENCODE_DISABLE_WATCHER")
|
export const OPENCODE_DISABLE_WATCHER = truthy("OPENCODE_DISABLE_WATCHER")
|
||||||
export const OPENCODE_CONFIG = process.env["OPENCODE_CONFIG"]
|
export const OPENCODE_CONFIG = process.env["OPENCODE_CONFIG"]
|
||||||
|
export const OPENCODE_DISABLE_AUTOUPDATE = truthy("OPENCODE_DISABLE_AUTOUPDATE")
|
||||||
|
|
||||||
function truthy(key: string) {
|
function truthy(key: string) {
|
||||||
const value = process.env[key]?.toLowerCase()
|
const value = process.env[key]?.toLowerCase()
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ await Promise.all([
|
|||||||
fs.mkdir(Global.Path.log, { recursive: true }),
|
fs.mkdir(Global.Path.log, { recursive: true }),
|
||||||
])
|
])
|
||||||
|
|
||||||
const CACHE_VERSION = "5"
|
const CACHE_VERSION = "6"
|
||||||
|
|
||||||
const version = await Bun.file(path.join(Global.Path.cache, "version"))
|
const version = await Bun.file(path.join(Global.Path.cache, "version"))
|
||||||
.text()
|
.text()
|
||||||
|
|||||||
@@ -65,6 +65,66 @@ export namespace LSPServer {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const ESLint: Info = {
|
||||||
|
id: "eslint",
|
||||||
|
root: NearestRoot([
|
||||||
|
"eslint.config.js",
|
||||||
|
"eslint.config.mjs",
|
||||||
|
"eslint.config.cjs",
|
||||||
|
"eslint.config.ts",
|
||||||
|
"eslint.config.mts",
|
||||||
|
"eslint.config.cts",
|
||||||
|
".eslintrc.js",
|
||||||
|
".eslintrc.cjs",
|
||||||
|
".eslintrc.yaml",
|
||||||
|
".eslintrc.yml",
|
||||||
|
".eslintrc.json",
|
||||||
|
"package.json",
|
||||||
|
]),
|
||||||
|
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
|
||||||
|
async spawn(app, root) {
|
||||||
|
const eslint = await Bun.resolve("eslint", app.path.cwd).catch(() => {})
|
||||||
|
if (!eslint) return
|
||||||
|
const serverPath = path.join(Global.Path.bin, "vscode-eslint", "server", "out", "eslintServer.js")
|
||||||
|
if (!(await Bun.file(serverPath).exists())) {
|
||||||
|
log.info("downloading and building VS Code ESLint server")
|
||||||
|
const response = await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip")
|
||||||
|
if (!response.ok) return
|
||||||
|
|
||||||
|
const zipPath = path.join(Global.Path.bin, "vscode-eslint.zip")
|
||||||
|
await Bun.file(zipPath).write(response)
|
||||||
|
|
||||||
|
await $`unzip -o -q ${zipPath}`.cwd(Global.Path.bin).nothrow()
|
||||||
|
await fs.rm(zipPath, { force: true })
|
||||||
|
|
||||||
|
const extractedPath = path.join(Global.Path.bin, "vscode-eslint-main")
|
||||||
|
const finalPath = path.join(Global.Path.bin, "vscode-eslint")
|
||||||
|
|
||||||
|
if (await Bun.file(finalPath).exists()) {
|
||||||
|
await fs.rm(finalPath, { force: true, recursive: true })
|
||||||
|
}
|
||||||
|
await fs.rename(extractedPath, finalPath)
|
||||||
|
|
||||||
|
await $`npm install`.cwd(finalPath).quiet()
|
||||||
|
await $`npm run compile`.cwd(finalPath).quiet()
|
||||||
|
|
||||||
|
log.info("installed VS Code ESLint server", { serverPath })
|
||||||
|
}
|
||||||
|
|
||||||
|
const proc = spawn(BunProc.which(), ["--max-old-space-size=8192", serverPath, "--stdio"], {
|
||||||
|
cwd: root,
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
BUN_BE_BUN: "1",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
process: proc,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
export const Gopls: Info = {
|
export const Gopls: Info = {
|
||||||
id: "golang",
|
id: "golang",
|
||||||
root: async (file, app) => {
|
root: async (file, app) => {
|
||||||
|
|||||||
@@ -440,7 +440,7 @@ export namespace Provider {
|
|||||||
|
|
||||||
const provider = await state().then((state) => state.providers[providerID])
|
const provider = await state().then((state) => state.providers[providerID])
|
||||||
if (!provider) return
|
if (!provider) return
|
||||||
const priority = ["3-5-haiku", "3.5-haiku", "gemini-2.5-flash"]
|
const priority = ["3-5-haiku", "3.5-haiku", "gemini-2.5-flash", "gpt-5-nano"]
|
||||||
for (const item of priority) {
|
for (const item of priority) {
|
||||||
for (const model of Object.keys(provider.info.models)) {
|
for (const model of Object.keys(provider.info.models)) {
|
||||||
if (model.includes(item)) return getModel(providerID, model)
|
if (model.includes(item)) return getModel(providerID, model)
|
||||||
|
|||||||
@@ -85,9 +85,24 @@ export namespace ProviderTransform {
|
|||||||
export function options(_providerID: string, modelID: string) {
|
export function options(_providerID: string, modelID: string) {
|
||||||
if (modelID.includes("gpt-5")) {
|
if (modelID.includes("gpt-5")) {
|
||||||
return {
|
return {
|
||||||
reasoningEffort: "low",
|
reasoningEffort: "minimal",
|
||||||
textVerbosity: "low",
|
textVerbosity: "low",
|
||||||
|
// reasoningSummary: "auto",
|
||||||
|
// include: ["reasoning.encrypted_content"],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// if (modelID.includes("claude")) {
|
||||||
|
// return {
|
||||||
|
// thinking: {
|
||||||
|
// type: "enabled",
|
||||||
|
// budgetTokens: 32000,
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// if (_providerID === "bedrock") {
|
||||||
|
// return {
|
||||||
|
// reasoningConfig: { type: "enabled", budgetTokens: 32000 },
|
||||||
|
// }
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,11 +11,11 @@ import {
|
|||||||
type LanguageModelUsage,
|
type LanguageModelUsage,
|
||||||
type ProviderMetadata,
|
type ProviderMetadata,
|
||||||
type ModelMessage,
|
type ModelMessage,
|
||||||
stepCountIs,
|
|
||||||
type StreamTextResult,
|
type StreamTextResult,
|
||||||
} from "ai"
|
} from "ai"
|
||||||
|
|
||||||
import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
|
import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
|
||||||
|
import PROMPT_PLAN from "../session/prompt/plan.txt"
|
||||||
|
|
||||||
import { App } from "../app/app"
|
import { App } from "../app/app"
|
||||||
import { Bus } from "../bus"
|
import { Bus } from "../bus"
|
||||||
@@ -41,6 +41,7 @@ import { mergeDeep, pipe, splitWhen } from "remeda"
|
|||||||
import { ToolRegistry } from "../tool/registry"
|
import { ToolRegistry } from "../tool/registry"
|
||||||
import { Plugin } from "../plugin"
|
import { Plugin } from "../plugin"
|
||||||
import { Agent } from "../agent/agent"
|
import { Agent } from "../agent/agent"
|
||||||
|
import { Permission } from "../permission"
|
||||||
|
|
||||||
export namespace Session {
|
export namespace Session {
|
||||||
const log = Log.create({ service: "session" })
|
const log = Log.create({ service: "session" })
|
||||||
@@ -607,17 +608,6 @@ export namespace Session {
|
|||||||
]
|
]
|
||||||
}),
|
}),
|
||||||
).then((x) => x.flat())
|
).then((x) => x.flat())
|
||||||
/*
|
|
||||||
if (inputAgent === "plan")
|
|
||||||
userParts.push({
|
|
||||||
id: Identifier.ascending("part"),
|
|
||||||
messageID: userMsg.id,
|
|
||||||
sessionID: input.sessionID,
|
|
||||||
type: "text",
|
|
||||||
text: PROMPT_PLAN,
|
|
||||||
synthetic: true,
|
|
||||||
})
|
|
||||||
*/
|
|
||||||
await Plugin.trigger(
|
await Plugin.trigger(
|
||||||
"chat.message",
|
"chat.message",
|
||||||
{},
|
{},
|
||||||
@@ -682,6 +672,7 @@ export namespace Session {
|
|||||||
providerOptions: {
|
providerOptions: {
|
||||||
[input.providerID]: {
|
[input.providerID]: {
|
||||||
...small.info.options,
|
...small.info.options,
|
||||||
|
...ProviderTransform.options(input.providerID, small.info.id),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
messages: [
|
messages: [
|
||||||
@@ -719,6 +710,16 @@ export namespace Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const agent = await Agent.get(inputAgent)
|
const agent = await Agent.get(inputAgent)
|
||||||
|
if (agent.name === "plan") {
|
||||||
|
msgs.at(-1)?.parts.push({
|
||||||
|
id: Identifier.ascending("part"),
|
||||||
|
messageID: userMsg.id,
|
||||||
|
sessionID: input.sessionID,
|
||||||
|
type: "text",
|
||||||
|
text: PROMPT_PLAN,
|
||||||
|
synthetic: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
let system = SystemPrompt.header(input.providerID)
|
let system = SystemPrompt.header(input.providerID)
|
||||||
system.push(
|
system.push(
|
||||||
...(() => {
|
...(() => {
|
||||||
@@ -851,20 +852,24 @@ export namespace Session {
|
|||||||
tools[key] = item
|
tools[key] = item
|
||||||
}
|
}
|
||||||
|
|
||||||
const params = {
|
const params = await Plugin.trigger(
|
||||||
temperature: model.info.temperature
|
|
||||||
? (agent.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
|
|
||||||
: undefined,
|
|
||||||
topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
|
||||||
}
|
|
||||||
await Plugin.trigger(
|
|
||||||
"chat.params",
|
"chat.params",
|
||||||
{
|
{
|
||||||
model: model.info,
|
model: model.info,
|
||||||
provider: await Provider.getProvider(input.providerID),
|
provider: await Provider.getProvider(input.providerID),
|
||||||
message: userMsg,
|
message: userMsg,
|
||||||
},
|
},
|
||||||
params,
|
{
|
||||||
|
temperature: model.info.temperature
|
||||||
|
? (agent.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
|
||||||
|
: undefined,
|
||||||
|
topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
||||||
|
options: {
|
||||||
|
...ProviderTransform.options(input.providerID, input.modelID),
|
||||||
|
...model.info.options,
|
||||||
|
...agent.options,
|
||||||
|
},
|
||||||
|
},
|
||||||
)
|
)
|
||||||
const stream = streamText({
|
const stream = streamText({
|
||||||
onError(e) {
|
onError(e) {
|
||||||
@@ -932,12 +937,20 @@ export namespace Session {
|
|||||||
activeTools: Object.keys(tools).filter((x) => x !== "invalid"),
|
activeTools: Object.keys(tools).filter((x) => x !== "invalid"),
|
||||||
maxOutputTokens: outputLimit,
|
maxOutputTokens: outputLimit,
|
||||||
abortSignal: abort.signal,
|
abortSignal: abort.signal,
|
||||||
stopWhen: stepCountIs(1000),
|
stopWhen: async ({ steps }) => {
|
||||||
|
if (steps.length >= 1000) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if processor flagged that we should stop
|
||||||
|
if (processor.getShouldStop()) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
},
|
||||||
providerOptions: {
|
providerOptions: {
|
||||||
[input.providerID]: {
|
[input.providerID]: params.options,
|
||||||
...ProviderTransform.options(input.providerID, input.modelID),
|
|
||||||
...model.info.options,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
temperature: params.temperature,
|
temperature: params.temperature,
|
||||||
topP: params.topP,
|
topP: params.topP,
|
||||||
@@ -983,13 +996,18 @@ export namespace Session {
|
|||||||
function createProcessor(assistantMsg: MessageV2.Assistant, model: ModelsDev.Model) {
|
function createProcessor(assistantMsg: MessageV2.Assistant, model: ModelsDev.Model) {
|
||||||
const toolcalls: Record<string, MessageV2.ToolPart> = {}
|
const toolcalls: Record<string, MessageV2.ToolPart> = {}
|
||||||
let snapshot: string | undefined
|
let snapshot: string | undefined
|
||||||
|
let shouldStop = false
|
||||||
return {
|
return {
|
||||||
partFromToolCall(toolCallID: string) {
|
partFromToolCall(toolCallID: string) {
|
||||||
return toolcalls[toolCallID]
|
return toolcalls[toolCallID]
|
||||||
},
|
},
|
||||||
|
getShouldStop() {
|
||||||
|
return shouldStop
|
||||||
|
},
|
||||||
async process(stream: StreamTextResult<Record<string, AITool>, never>) {
|
async process(stream: StreamTextResult<Record<string, AITool>, never>) {
|
||||||
try {
|
try {
|
||||||
let currentText: MessageV2.TextPart | undefined
|
let currentText: MessageV2.TextPart | undefined
|
||||||
|
// let reasoningMap: Record<string, MessageV2.ReasoningPart> = {}
|
||||||
|
|
||||||
for await (const value of stream.fullStream) {
|
for await (const value of stream.fullStream) {
|
||||||
log.info("part", {
|
log.info("part", {
|
||||||
@@ -999,6 +1017,46 @@ export namespace Session {
|
|||||||
case "start":
|
case "start":
|
||||||
break
|
break
|
||||||
|
|
||||||
|
/*
|
||||||
|
case "reasoning-start":
|
||||||
|
if (value.id in reasoningMap) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
reasoningMap[value.id] = {
|
||||||
|
id: Identifier.ascending("part"),
|
||||||
|
messageID: assistantMsg.id,
|
||||||
|
sessionID: assistantMsg.sessionID,
|
||||||
|
type: "reasoning",
|
||||||
|
text: "",
|
||||||
|
time: {
|
||||||
|
start: Date.now(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
break
|
||||||
|
|
||||||
|
case "reasoning-delta":
|
||||||
|
if (value.id in reasoningMap) {
|
||||||
|
const part = reasoningMap[value.id]
|
||||||
|
part.text += value.text
|
||||||
|
if (part.text) await updatePart(part)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
|
||||||
|
case "reasoning-end":
|
||||||
|
if (value.id in reasoningMap) {
|
||||||
|
const part = reasoningMap[value.id]
|
||||||
|
part.text = part.text.trimEnd()
|
||||||
|
part.metadata = value.providerMetadata
|
||||||
|
part.time = {
|
||||||
|
...part.time,
|
||||||
|
end: Date.now(),
|
||||||
|
}
|
||||||
|
await updatePart(part)
|
||||||
|
delete reasoningMap[value.id]
|
||||||
|
}
|
||||||
|
break
|
||||||
|
*/
|
||||||
|
|
||||||
case "tool-input-start":
|
case "tool-input-start":
|
||||||
const part = await updatePart({
|
const part = await updatePart({
|
||||||
id: toolcalls[value.id]?.id ?? Identifier.ascending("part"),
|
id: toolcalls[value.id]?.id ?? Identifier.ascending("part"),
|
||||||
@@ -1063,6 +1121,9 @@ export namespace Session {
|
|||||||
case "tool-error": {
|
case "tool-error": {
|
||||||
const match = toolcalls[value.toolCallId]
|
const match = toolcalls[value.toolCallId]
|
||||||
if (match && match.state.status === "running") {
|
if (match && match.state.status === "running") {
|
||||||
|
if (value.error instanceof Permission.RejectedError) {
|
||||||
|
shouldStop = true
|
||||||
|
}
|
||||||
await updatePart({
|
await updatePart({
|
||||||
...match,
|
...match,
|
||||||
state: {
|
state: {
|
||||||
@@ -1079,7 +1140,6 @@ export namespace Session {
|
|||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
case "error":
|
case "error":
|
||||||
throw value.error
|
throw value.error
|
||||||
|
|
||||||
|
|||||||
@@ -118,6 +118,19 @@ export namespace MessageV2 {
|
|||||||
})
|
})
|
||||||
export type TextPart = z.infer<typeof TextPart>
|
export type TextPart = z.infer<typeof TextPart>
|
||||||
|
|
||||||
|
export const ReasoningPart = PartBase.extend({
|
||||||
|
type: z.literal("reasoning"),
|
||||||
|
text: z.string(),
|
||||||
|
metadata: z.record(z.any()).optional(),
|
||||||
|
time: z.object({
|
||||||
|
start: z.number(),
|
||||||
|
end: z.number().optional(),
|
||||||
|
}),
|
||||||
|
}).openapi({
|
||||||
|
ref: "ReasoningPart",
|
||||||
|
})
|
||||||
|
export type ReasoningPart = z.infer<typeof ReasoningPart>
|
||||||
|
|
||||||
export const ToolPart = PartBase.extend({
|
export const ToolPart = PartBase.extend({
|
||||||
type: z.literal("tool"),
|
type: z.literal("tool"),
|
||||||
callID: z.string(),
|
callID: z.string(),
|
||||||
@@ -229,6 +242,7 @@ export namespace MessageV2 {
|
|||||||
export const Part = z
|
export const Part = z
|
||||||
.discriminatedUnion("type", [
|
.discriminatedUnion("type", [
|
||||||
TextPart,
|
TextPart,
|
||||||
|
ReasoningPart,
|
||||||
FilePart,
|
FilePart,
|
||||||
ToolPart,
|
ToolPart,
|
||||||
StepStartPart,
|
StepStartPart,
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
You are a coding agent running in the opencode, a terminal-based coding assistant. opencode is an open source project. You are expected to be precise, safe, and helpful.
|
||||||
|
|
||||||
|
Your capabilities:
|
||||||
|
- Receive user prompts and other context provided by the harness, such as files in the workspace.
|
||||||
|
- Communicate with the user by streaming thinking & responses, and by making & updating plans.
|
||||||
|
- Emit function calls to run terminal commands and apply edits. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
|
||||||
|
|
||||||
|
Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
|
||||||
|
|
||||||
|
# How you work
|
||||||
|
|
||||||
|
## Personality
|
||||||
|
|
||||||
|
Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
|
||||||
|
|
||||||
|
## Responsiveness
|
||||||
|
|
||||||
|
### Preamble messages
|
||||||
|
|
||||||
|
Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
|
||||||
|
|
||||||
|
- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
|
||||||
|
- **Keep it concise**: be no more than 1-2 sentences (8–12 words for quick updates).
|
||||||
|
- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
|
||||||
|
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
- “I’ve explored the repo; now checking the API route definitions.”
|
||||||
|
- “Next, I’ll edit the config and update the related tests.”
|
||||||
|
- “I’m about to scaffold the CLI commands and helper functions.”
|
||||||
|
- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
|
||||||
|
- “Config’s looking tidy. Next up is editing helpers to keep things in sync.”
|
||||||
|
- “Finished poking at the DB gateway. I will now chase down error handling.”
|
||||||
|
- “Alright, build pipeline order is interesting. Checking how it reports failures.”
|
||||||
|
- “Spotted a clever caching util; now hunting where it gets used.”
|
||||||
|
|
||||||
|
**Avoiding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
|
||||||
|
- Jumping straight into tool calls without explaining what’s about to happen.
|
||||||
|
- Writing overly long or speculative preambles — focus on immediate, tangible next steps.
|
||||||
|
|
||||||
|
## Planning
|
||||||
|
|
||||||
|
You have access to an `todowrite` tool which tracks steps and progress and
|
||||||
|
renders them to the user. Using the tool helps demonstrate that you've
|
||||||
|
understood the task and convey how you're approaching it. Plans can help to make
|
||||||
|
complex, ambiguous, or multi-phase work clearer and more collaborative for the
|
||||||
|
user. A good plan should break the task into meaningful, logically ordered steps
|
||||||
|
that are easy to verify as you go. Note that plans are not for padding out
|
||||||
|
simple work with filler steps or stating the obvious. Do not repeat the full
|
||||||
|
contents of the plan after a `todowrite` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
|
||||||
|
|
||||||
|
Use a plan when:
|
||||||
|
- The task is non-trivial and will require multiple actions over a long time horizon.
|
||||||
|
- There are logical phases or dependencies where sequencing matters.
|
||||||
|
- The work has ambiguity that benefits from outlining high-level goals.
|
||||||
|
- You want intermediate checkpoints for feedback and validation.
|
||||||
|
- When the user asked you to do more than one thing in a single prompt
|
||||||
|
- The user has asked you to use the plan tool (aka "TODOs")
|
||||||
|
- You generate additional steps while working, and plan to do them before yielding to the user
|
||||||
|
|
||||||
|
Skip a plan when:
|
||||||
|
- The task is simple and direct.
|
||||||
|
- Breaking it down would only produce literal or trivial steps.
|
||||||
|
|
||||||
|
Planning steps are called "steps" in the tool, but really they're more like tasks or TODOs. As such they should be very concise descriptions of non-obvious work that an engineer might do like "Write the API spec", then "Update the backend", then "Implement the frontend". On the other hand, it's obvious that you'll usually have to "Explore the codebase" or "Implement the changes", so those are not worth tracking in your plan.
|
||||||
|
|
||||||
|
It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
**High-quality plans**
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
1. Add CLI entry with file args
|
||||||
|
2. Parse Markdown via CommonMark library
|
||||||
|
3. Apply semantic HTML template
|
||||||
|
4. Handle code blocks, images, links
|
||||||
|
5. Add error handling for invalid files
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
1. Define CSS variables for colors
|
||||||
|
2. Add toggle with localStorage state
|
||||||
|
3. Refactor components to use variables
|
||||||
|
4. Verify all views for readability
|
||||||
|
5. Add smooth theme-change transition
|
||||||
|
|
||||||
|
Example 3:
|
||||||
|
|
||||||
|
1. Set up Node.js + WebSocket server
|
||||||
|
2. Add join/leave broadcast events
|
||||||
|
3. Implement messaging with timestamps
|
||||||
|
4. Add usernames + mention highlighting
|
||||||
|
5. Persist messages in lightweight DB
|
||||||
|
6. Add typing indicators + unread count
|
||||||
|
|
||||||
|
**Low-quality plans**
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
1. Create CLI tool
|
||||||
|
2. Add Markdown parser
|
||||||
|
3. Convert to HTML
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
1. Add dark mode toggle
|
||||||
|
2. Save preference
|
||||||
|
3. Make styles look good
|
||||||
|
|
||||||
|
Example 3:
|
||||||
|
|
||||||
|
1. Create single-file HTML game
|
||||||
|
2. Run quick sanity check
|
||||||
|
3. Summarize usage instructions
|
||||||
|
|
||||||
|
If you need to write a plan, only write high quality plans, not low quality ones.
|
||||||
|
|
||||||
|
## Task execution
|
||||||
|
|
||||||
|
You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
|
||||||
|
|
||||||
|
You MUST adhere to the following criteria when solving queries:
|
||||||
|
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
|
||||||
|
- Analyzing code for vulnerabilities is allowed.
|
||||||
|
- Showing user code and tool call details is allowed.
|
||||||
|
- Use the `edit` tool to edit files
|
||||||
|
|
||||||
|
If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
|
||||||
|
|
||||||
|
- Fix the problem at the root cause rather than applying surface-level edits, when possible.
|
||||||
|
- Avoid unneeded complexity in your solution.
|
||||||
|
- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||||
|
- Update documentation as necessary.
|
||||||
|
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
|
||||||
|
- Use `git log` and `git blame` to search the history of the codebase if additional context is required.
|
||||||
|
- NEVER add copyright or license headers unless specifically requested.
|
||||||
|
- Do not waste tokens by re-reading files after calling `edit` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
|
||||||
|
- Do not `git commit` your changes or create new git branches unless explicitly requested.
|
||||||
|
- Do not add inline comments within code unless explicitly requested.
|
||||||
|
- Do not use one-letter variable names unless explicitly requested.
|
||||||
|
- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
|
||||||
|
|
||||||
|
## Testing your work
|
||||||
|
|
||||||
|
If the codebase has tests or the ability to build or run, you should use them to verify that your work is complete. Generally, your testing philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests, or where the patterns don't indicate so.
|
||||||
|
|
||||||
|
Once you're confident in correctness, use formatting commands to ensure that your code is well formatted. These commands can take time so you should run them on as precise a target as possible. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
|
||||||
|
|
||||||
|
For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||||
|
|
||||||
|
## Sandbox and approvals
|
||||||
|
|
||||||
|
The Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from.
|
||||||
|
|
||||||
|
Filesystem sandboxing prevents you from editing files without user approval. The options are:
|
||||||
|
- *read-only*: You can only read files.
|
||||||
|
- *workspace-write*: You can read files. You can write to files in your workspace folder, but not outside it.
|
||||||
|
- *danger-full-access*: No filesystem sandboxing.
|
||||||
|
|
||||||
|
Network sandboxing prevents you from accessing network without approval. Options are
|
||||||
|
- *ON*
|
||||||
|
- *OFF*
|
||||||
|
|
||||||
|
Approvals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user's task. Approval options are
|
||||||
|
- *untrusted*: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands.
|
||||||
|
- *on-failure*: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.
|
||||||
|
- *on-request*: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the `shell` command description.)
|
||||||
|
- *never*: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is pared with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.
|
||||||
|
|
||||||
|
When you are running with approvals `on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval:
|
||||||
|
- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp)
|
||||||
|
- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.
|
||||||
|
- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)
|
||||||
|
- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval.
|
||||||
|
- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for
|
||||||
|
- (For all of these, you should weigh alternative paths that do not require approval.)
|
||||||
|
|
||||||
|
Note that when sandboxing is set to read-only, you'll need to request approval for any command that isn't a read.
|
||||||
|
|
||||||
|
You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing ON, and approval on-failure.
|
||||||
|
|
||||||
|
## Ambition vs. precision
|
||||||
|
|
||||||
|
For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
|
||||||
|
|
||||||
|
If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
|
||||||
|
|
||||||
|
You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
|
||||||
|
|
||||||
|
## Sharing progress updates
|
||||||
|
|
||||||
|
For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
|
||||||
|
|
||||||
|
Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
|
||||||
|
|
||||||
|
The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
|
||||||
|
|
||||||
|
## Presenting your work and final message
|
||||||
|
|
||||||
|
Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
|
||||||
|
|
||||||
|
You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
|
||||||
|
|
||||||
|
The user is working on the same computer as you, and has access to your work. As
|
||||||
|
such there's no need to show the full contents of large files you have already
|
||||||
|
written unless the user explicitly asks for them. Similarly, if you've created
|
||||||
|
or modified files using `edit`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
|
||||||
|
|
||||||
|
If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
|
||||||
|
|
||||||
|
Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
|
||||||
|
|
||||||
|
### Final answer structure and style guidelines
|
||||||
|
|
||||||
|
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
||||||
|
|
||||||
|
**Section Headers**
|
||||||
|
- Use only when they improve clarity — they are not mandatory for every answer.
|
||||||
|
- Choose descriptive names that fit the content
|
||||||
|
- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`
|
||||||
|
- Leave no blank line before the first bullet under a header.
|
||||||
|
- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
|
||||||
|
|
||||||
|
**Bullets**
|
||||||
|
- Use `-` followed by a space for every bullet.
|
||||||
|
- Bold the keyword, then colon + concise description.
|
||||||
|
- Merge related points when possible; avoid a bullet for every trivial detail.
|
||||||
|
- Keep bullets to one line unless breaking for clarity is unavoidable.
|
||||||
|
- Group into short lists (4–6 bullets) ordered by importance.
|
||||||
|
- Use consistent keyword phrasing and formatting across sections.
|
||||||
|
|
||||||
|
**Monospace**
|
||||||
|
- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).
|
||||||
|
- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
|
||||||
|
- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).
|
||||||
|
|
||||||
|
**Structure**
|
||||||
|
- Place related bullets together; don’t mix unrelated concepts in the same section.
|
||||||
|
- Order sections from general → specific → supporting info.
|
||||||
|
- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
|
||||||
|
- Match structure to complexity:
|
||||||
|
- Multi-part or detailed results → use clear headers and grouped bullets.
|
||||||
|
- Simple results → minimal headers, possibly just a short list or paragraph.
|
||||||
|
|
||||||
|
**Tone**
|
||||||
|
- Keep the voice collaborative and natural, like a coding partner handing off work.
|
||||||
|
- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
|
||||||
|
- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
|
||||||
|
- Keep descriptions self-contained; don’t refer to “above” or “below”.
|
||||||
|
- Use parallel structure in lists for consistency.
|
||||||
|
|
||||||
|
**Don’t**
|
||||||
|
- Don’t use literal words “bold” or “monospace” in the content.
|
||||||
|
- Don’t nest bullets or create deep hierarchies.
|
||||||
|
- Don’t output ANSI escape codes directly — the CLI renderer applies them.
|
||||||
|
- Don’t cram unrelated keywords into a single bullet; split for clarity.
|
||||||
|
- Don’t let keyword lists run long — wrap or reformat for scanability.
|
||||||
|
|
||||||
|
Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
|
||||||
|
|
||||||
|
For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
<system-reminder>
|
<system-reminder>
|
||||||
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received (for example, to make edits).
|
Plan mode is active. The user indicated that they do not want you to execute yet
|
||||||
|
-- you MUST NOT make any edits, run any non-readonly tools (including changing
|
||||||
|
configs or making commits), or otherwise make any changes to the system. This
|
||||||
|
supersedes any other instructions you have received (for example, to make
|
||||||
|
edits). Bash tool must only run readonly commands
|
||||||
</system-reminder>
|
</system-reminder>
|
||||||
|
|
||||||
|
|||||||
@@ -13,13 +13,16 @@ import PROMPT_GEMINI from "./prompt/gemini.txt"
|
|||||||
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
|
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
|
||||||
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
|
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
|
||||||
import PROMPT_TITLE from "./prompt/title.txt"
|
import PROMPT_TITLE from "./prompt/title.txt"
|
||||||
|
import PROMPT_CODEX from "./prompt/codex.txt"
|
||||||
|
|
||||||
export namespace SystemPrompt {
|
export namespace SystemPrompt {
|
||||||
export function header(providerID: string) {
|
export function header(providerID: string) {
|
||||||
if (providerID.includes("anthropic")) return [PROMPT_ANTHROPIC_SPOOF.trim()]
|
if (providerID.includes("anthropic")) return [PROMPT_ANTHROPIC_SPOOF.trim()]
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
export function provider(modelID: string) {
|
export function provider(modelID: string) {
|
||||||
|
if (modelID.includes("gpt-5")) return [PROMPT_CODEX]
|
||||||
if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
|
if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
|
||||||
if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
|
if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
|
||||||
if (modelID.includes("claude")) return [PROMPT_ANTHROPIC]
|
if (modelID.includes("claude")) return [PROMPT_ANTHROPIC]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
import { exec } from "child_process"
|
import { exec } from "child_process"
|
||||||
import { text } from "stream/consumers"
|
|
||||||
import { Tool } from "./tool"
|
import { Tool } from "./tool"
|
||||||
import DESCRIPTION from "./bash.txt"
|
import DESCRIPTION from "./bash.txt"
|
||||||
import { App } from "../app/app"
|
import { App } from "../app/app"
|
||||||
@@ -130,8 +130,35 @@ export const BashTool = Tool.define("bash", {
|
|||||||
timeout,
|
timeout,
|
||||||
})
|
})
|
||||||
|
|
||||||
const stdoutPromise = text(process.stdout!)
|
let output = ""
|
||||||
const stderrPromise = text(process.stderr!)
|
|
||||||
|
// Initialize metadata with empty output
|
||||||
|
ctx.metadata({
|
||||||
|
metadata: {
|
||||||
|
output: "",
|
||||||
|
description: params.description,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
process.stdout?.on("data", (chunk) => {
|
||||||
|
output += chunk.toString()
|
||||||
|
ctx.metadata({
|
||||||
|
metadata: {
|
||||||
|
output: output,
|
||||||
|
description: params.description,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
process.stderr?.on("data", (chunk) => {
|
||||||
|
output += chunk.toString()
|
||||||
|
ctx.metadata({
|
||||||
|
metadata: {
|
||||||
|
output: output,
|
||||||
|
description: params.description,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
await new Promise<void>((resolve) => {
|
await new Promise<void>((resolve) => {
|
||||||
process.on("close", () => {
|
process.on("close", () => {
|
||||||
@@ -139,18 +166,22 @@ export const BashTool = Tool.define("bash", {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
const stdout = await stdoutPromise
|
ctx.metadata({
|
||||||
const stderr = await stderrPromise
|
metadata: {
|
||||||
|
output: output,
|
||||||
|
exit: process.exitCode,
|
||||||
|
description: params.description,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title: params.command,
|
title: params.command,
|
||||||
metadata: {
|
metadata: {
|
||||||
stderr,
|
output,
|
||||||
stdout,
|
|
||||||
exit: process.exitCode,
|
exit: process.exitCode,
|
||||||
description: params.description,
|
description: params.description,
|
||||||
},
|
},
|
||||||
output: [`<stdout>`, stdout ?? "", `</stdout>`, `<stderr>`, stderr ?? "", `</stderr>`].join("\n"),
|
output,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ export const EditTool = Tool.define("edit", {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
output += `\n<project_diagnostics>\n${file}\n${issues
|
output += `\n<project_diagnostics>\n${file}\n${issues
|
||||||
|
// TODO: may want to make more leniant for eslint
|
||||||
.filter((item) => item.severity === 1)
|
.filter((item) => item.severity === 1)
|
||||||
.map(LSP.Diagnostic.pretty)
|
.map(LSP.Diagnostic.pretty)
|
||||||
.join("\n")}\n</project_diagnostics>\n`
|
.join("\n")}\n</project_diagnostics>\n`
|
||||||
|
|||||||
@@ -79,6 +79,9 @@ export namespace ToolRegistry {
|
|||||||
if (cfg?.permission?.bash === "deny") {
|
if (cfg?.permission?.bash === "deny") {
|
||||||
result["bash"] = false
|
result["bash"] = false
|
||||||
}
|
}
|
||||||
|
if (cfg?.permission?.webfetch === "deny") {
|
||||||
|
result["webfetch"] = false
|
||||||
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { z } from "zod"
|
|||||||
import { Tool } from "./tool"
|
import { Tool } from "./tool"
|
||||||
import TurndownService from "turndown"
|
import TurndownService from "turndown"
|
||||||
import DESCRIPTION from "./webfetch.txt"
|
import DESCRIPTION from "./webfetch.txt"
|
||||||
|
import { Config } from "../config/config"
|
||||||
|
import { Permission } from "../permission"
|
||||||
|
|
||||||
const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 // 5MB
|
const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 // 5MB
|
||||||
const DEFAULT_TIMEOUT = 30 * 1000 // 30 seconds
|
const DEFAULT_TIMEOUT = 30 * 1000 // 30 seconds
|
||||||
@@ -22,6 +24,21 @@ export const WebFetchTool = Tool.define("webfetch", {
|
|||||||
throw new Error("URL must start with http:// or https://")
|
throw new Error("URL must start with http:// or https://")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const cfg = await Config.get()
|
||||||
|
if (cfg.permission?.webfetch === "ask")
|
||||||
|
await Permission.ask({
|
||||||
|
type: "webfetch",
|
||||||
|
sessionID: ctx.sessionID,
|
||||||
|
messageID: ctx.messageID,
|
||||||
|
callID: ctx.callID,
|
||||||
|
title: "Fetch content from: " + params.url,
|
||||||
|
metadata: {
|
||||||
|
url: params.url,
|
||||||
|
format: params.format,
|
||||||
|
timeout: params.timeout,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const timeout = Math.min((params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, MAX_TIMEOUT)
|
const timeout = Math.min((params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, MAX_TIMEOUT)
|
||||||
|
|
||||||
const controller = new AbortController()
|
const controller = new AbortController()
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ describe("tool.bash", () => {
|
|||||||
ctx,
|
ctx,
|
||||||
)
|
)
|
||||||
expect(result.metadata.exit).toBe(0)
|
expect(result.metadata.exit).toBe(0)
|
||||||
expect(result.metadata.stdout).toContain("test")
|
expect(result.metadata.output).toContain("test")
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"name": "@opencode-ai/plugin",
|
"name": "@opencode-ai/plugin",
|
||||||
"version": "0.4.1",
|
"version": "0.4.13",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export interface Hooks {
|
|||||||
*/
|
*/
|
||||||
"chat.params"?: (
|
"chat.params"?: (
|
||||||
input: { model: Model; provider: Provider; message: UserMessage },
|
input: { model: Model; provider: Provider; message: UserMessage },
|
||||||
output: { temperature: number; topP: number },
|
output: { temperature: number; topP: number; options: Record<string, any> },
|
||||||
) => Promise<void>
|
) => Promise<void>
|
||||||
"permission.ask"?: (input: Permission, output: { status: "ask" | "deny" | "allow" }) => Promise<void>
|
"permission.ask"?: (input: Permission, output: { status: "ask" | "deny" | "allow" }) => Promise<void>
|
||||||
"tool.execute.before"?: (
|
"tool.execute.before"?: (
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
configured_endpoints: 34
|
configured_endpoints: 34
|
||||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-da1c340135c3dd6b1edb4e00e7039d2ac54d59271683a8b6ed528e51137ce41a.yml
|
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-b86cf7bb8df4f60ebe8b8f51e281c8076cfdccc8554178c1b78beca4b025f0ff.yml
|
||||||
openapi_spec_hash: 0cdd9b6273d72f5a6f484a2999ff0632
|
openapi_spec_hash: 47633b7481d91708643ea7b43fffffe6
|
||||||
config_hash: 7581d5948150d4ef7dd7b13d0845dbeb
|
config_hash: bd7f6435ed0c0005f373b5526c07a055
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ Response Types:
|
|||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileSource">FileSource</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileSource">FileSource</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Message">Message</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Message">Message</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Part">Part</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Part">Part</a>
|
||||||
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ReasoningPart">ReasoningPart</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SnapshotPart">SnapshotPart</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SnapshotPart">SnapshotPart</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepFinishPart">StepFinishPart</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepFinishPart">StepFinishPart</a>
|
||||||
|
|||||||
@@ -74,9 +74,10 @@ type Config struct {
|
|||||||
// Control sharing behavior:'manual' allows manual sharing via commands, 'auto'
|
// Control sharing behavior:'manual' allows manual sharing via commands, 'auto'
|
||||||
// enables automatic sharing, 'disabled' disables all sharing
|
// enables automatic sharing, 'disabled' disables all sharing
|
||||||
Share ConfigShare `json:"share"`
|
Share ConfigShare `json:"share"`
|
||||||
// Small model to use for tasks like title generation in the
|
// Small model to use for tasks like title generation in the format of
|
||||||
// format of provider/model
|
// provider/model
|
||||||
SmallModel string `json:"small_model"`
|
SmallModel string `json:"small_model"`
|
||||||
|
Snapshot bool `json:"snapshot"`
|
||||||
// Theme name to use for the interface
|
// Theme name to use for the interface
|
||||||
Theme string `json:"theme"`
|
Theme string `json:"theme"`
|
||||||
// Custom username to display in conversations instead of system username
|
// Custom username to display in conversations instead of system username
|
||||||
@@ -105,6 +106,7 @@ type configJSON struct {
|
|||||||
Provider apijson.Field
|
Provider apijson.Field
|
||||||
Share apijson.Field
|
Share apijson.Field
|
||||||
SmallModel apijson.Field
|
SmallModel apijson.Field
|
||||||
|
Snapshot apijson.Field
|
||||||
Theme apijson.Field
|
Theme apijson.Field
|
||||||
Username apijson.Field
|
Username apijson.Field
|
||||||
raw string
|
raw string
|
||||||
@@ -780,9 +782,10 @@ func (r ConfigModePlanMode) IsKnown() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ConfigPermission struct {
|
type ConfigPermission struct {
|
||||||
Bash ConfigPermissionBashUnion `json:"bash"`
|
Bash ConfigPermissionBashUnion `json:"bash"`
|
||||||
Edit ConfigPermissionEdit `json:"edit"`
|
Edit ConfigPermissionEdit `json:"edit"`
|
||||||
JSON configPermissionJSON `json:"-"`
|
Webfetch ConfigPermissionWebfetch `json:"webfetch"`
|
||||||
|
JSON configPermissionJSON `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// configPermissionJSON contains the JSON metadata for the struct
|
// configPermissionJSON contains the JSON metadata for the struct
|
||||||
@@ -790,6 +793,7 @@ type ConfigPermission struct {
|
|||||||
type configPermissionJSON struct {
|
type configPermissionJSON struct {
|
||||||
Bash apijson.Field
|
Bash apijson.Field
|
||||||
Edit apijson.Field
|
Edit apijson.Field
|
||||||
|
Webfetch apijson.Field
|
||||||
raw string
|
raw string
|
||||||
ExtraFields map[string]apijson.Field
|
ExtraFields map[string]apijson.Field
|
||||||
}
|
}
|
||||||
@@ -876,6 +880,22 @@ func (r ConfigPermissionEdit) IsKnown() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ConfigPermissionWebfetch string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ConfigPermissionWebfetchAsk ConfigPermissionWebfetch = "ask"
|
||||||
|
ConfigPermissionWebfetchAllow ConfigPermissionWebfetch = "allow"
|
||||||
|
ConfigPermissionWebfetchDeny ConfigPermissionWebfetch = "deny"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r ConfigPermissionWebfetch) IsKnown() bool {
|
||||||
|
switch r {
|
||||||
|
case ConfigPermissionWebfetchAsk, ConfigPermissionWebfetchAllow, ConfigPermissionWebfetchDeny:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
type ConfigProvider struct {
|
type ConfigProvider struct {
|
||||||
Models map[string]ConfigProviderModel `json:"models,required"`
|
Models map[string]ConfigProviderModel `json:"models,required"`
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ echo "==> Starting mock server with URL ${URL}"
|
|||||||
|
|
||||||
# Run prism mock on the given spec
|
# Run prism mock on the given spec
|
||||||
if [ "$1" == "--daemon" ]; then
|
if [ "$1" == "--daemon" ]; then
|
||||||
npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" &> .prism.log &
|
npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log &
|
||||||
|
|
||||||
# Wait for server to come online
|
# Wait for server to come online
|
||||||
echo -n "Waiting for server"
|
echo -n "Waiting for server"
|
||||||
@@ -37,5 +37,5 @@ if [ "$1" == "--daemon" ]; then
|
|||||||
|
|
||||||
echo
|
echo
|
||||||
else
|
else
|
||||||
npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL"
|
npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL"
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ elif ! prism_is_running ; then
|
|||||||
echo -e "To run the server, pass in the path or url of your OpenAPI"
|
echo -e "To run the server, pass in the path or url of your OpenAPI"
|
||||||
echo -e "spec to the prism command:"
|
echo -e "spec to the prism command:"
|
||||||
echo
|
echo
|
||||||
echo -e " \$ ${YELLOW}npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock path/to/your.openapi.yml${NC}"
|
echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}"
|
||||||
echo
|
echo
|
||||||
|
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
+115
-33
@@ -962,18 +962,20 @@ type Part struct {
|
|||||||
Cost float64 `json:"cost"`
|
Cost float64 `json:"cost"`
|
||||||
Filename string `json:"filename"`
|
Filename string `json:"filename"`
|
||||||
// This field can have the runtime type of [[]string].
|
// This field can have the runtime type of [[]string].
|
||||||
Files interface{} `json:"files"`
|
Files interface{} `json:"files"`
|
||||||
Hash string `json:"hash"`
|
Hash string `json:"hash"`
|
||||||
Mime string `json:"mime"`
|
Mime string `json:"mime"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Snapshot string `json:"snapshot"`
|
// This field can have the runtime type of [map[string]interface{}].
|
||||||
|
ProviderMetadata interface{} `json:"providerMetadata"`
|
||||||
|
Snapshot string `json:"snapshot"`
|
||||||
// This field can have the runtime type of [FilePartSource], [AgentPartSource].
|
// This field can have the runtime type of [FilePartSource], [AgentPartSource].
|
||||||
Source interface{} `json:"source"`
|
Source interface{} `json:"source"`
|
||||||
// This field can have the runtime type of [ToolPartState].
|
// This field can have the runtime type of [ToolPartState].
|
||||||
State interface{} `json:"state"`
|
State interface{} `json:"state"`
|
||||||
Synthetic bool `json:"synthetic"`
|
Synthetic bool `json:"synthetic"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
// This field can have the runtime type of [TextPartTime].
|
// This field can have the runtime type of [TextPartTime], [ReasoningPartTime].
|
||||||
Time interface{} `json:"time"`
|
Time interface{} `json:"time"`
|
||||||
// This field can have the runtime type of [StepFinishPartTokens].
|
// This field can have the runtime type of [StepFinishPartTokens].
|
||||||
Tokens interface{} `json:"tokens"`
|
Tokens interface{} `json:"tokens"`
|
||||||
@@ -985,28 +987,29 @@ type Part struct {
|
|||||||
|
|
||||||
// partJSON contains the JSON metadata for the struct [Part]
|
// partJSON contains the JSON metadata for the struct [Part]
|
||||||
type partJSON struct {
|
type partJSON struct {
|
||||||
ID apijson.Field
|
ID apijson.Field
|
||||||
MessageID apijson.Field
|
MessageID apijson.Field
|
||||||
SessionID apijson.Field
|
SessionID apijson.Field
|
||||||
Type apijson.Field
|
Type apijson.Field
|
||||||
CallID apijson.Field
|
CallID apijson.Field
|
||||||
Cost apijson.Field
|
Cost apijson.Field
|
||||||
Filename apijson.Field
|
Filename apijson.Field
|
||||||
Files apijson.Field
|
Files apijson.Field
|
||||||
Hash apijson.Field
|
Hash apijson.Field
|
||||||
Mime apijson.Field
|
Mime apijson.Field
|
||||||
Name apijson.Field
|
Name apijson.Field
|
||||||
Snapshot apijson.Field
|
ProviderMetadata apijson.Field
|
||||||
Source apijson.Field
|
Snapshot apijson.Field
|
||||||
State apijson.Field
|
Source apijson.Field
|
||||||
Synthetic apijson.Field
|
State apijson.Field
|
||||||
Text apijson.Field
|
Synthetic apijson.Field
|
||||||
Time apijson.Field
|
Text apijson.Field
|
||||||
Tokens apijson.Field
|
Time apijson.Field
|
||||||
Tool apijson.Field
|
Tokens apijson.Field
|
||||||
URL apijson.Field
|
Tool apijson.Field
|
||||||
raw string
|
URL apijson.Field
|
||||||
ExtraFields map[string]apijson.Field
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r partJSON) RawJSON() string {
|
func (r partJSON) RawJSON() string {
|
||||||
@@ -1025,14 +1028,16 @@ func (r *Part) UnmarshalJSON(data []byte) (err error) {
|
|||||||
// AsUnion returns a [PartUnion] interface which you can cast to the specific types
|
// AsUnion returns a [PartUnion] interface which you can cast to the specific types
|
||||||
// for more type safety.
|
// for more type safety.
|
||||||
//
|
//
|
||||||
// Possible runtime types of the union are [TextPart], [FilePart], [ToolPart],
|
// Possible runtime types of the union are [TextPart], [ReasoningPart], [FilePart],
|
||||||
// [StepStartPart], [StepFinishPart], [SnapshotPart], [PartPatchPart], [AgentPart].
|
// [ToolPart], [StepStartPart], [StepFinishPart], [SnapshotPart], [PartPatchPart],
|
||||||
|
// [AgentPart].
|
||||||
func (r Part) AsUnion() PartUnion {
|
func (r Part) AsUnion() PartUnion {
|
||||||
return r.union
|
return r.union
|
||||||
}
|
}
|
||||||
|
|
||||||
// Union satisfied by [TextPart], [FilePart], [ToolPart], [StepStartPart],
|
// Union satisfied by [TextPart], [ReasoningPart], [FilePart], [ToolPart],
|
||||||
// [StepFinishPart], [SnapshotPart], [PartPatchPart] or [AgentPart].
|
// [StepStartPart], [StepFinishPart], [SnapshotPart], [PartPatchPart] or
|
||||||
|
// [AgentPart].
|
||||||
type PartUnion interface {
|
type PartUnion interface {
|
||||||
implementsPart()
|
implementsPart()
|
||||||
}
|
}
|
||||||
@@ -1046,6 +1051,11 @@ func init() {
|
|||||||
Type: reflect.TypeOf(TextPart{}),
|
Type: reflect.TypeOf(TextPart{}),
|
||||||
DiscriminatorValue: "text",
|
DiscriminatorValue: "text",
|
||||||
},
|
},
|
||||||
|
apijson.UnionVariant{
|
||||||
|
TypeFilter: gjson.JSON,
|
||||||
|
Type: reflect.TypeOf(ReasoningPart{}),
|
||||||
|
DiscriminatorValue: "reasoning",
|
||||||
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(FilePart{}),
|
Type: reflect.TypeOf(FilePart{}),
|
||||||
@@ -1134,6 +1144,7 @@ type PartType string
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
PartTypeText PartType = "text"
|
PartTypeText PartType = "text"
|
||||||
|
PartTypeReasoning PartType = "reasoning"
|
||||||
PartTypeFile PartType = "file"
|
PartTypeFile PartType = "file"
|
||||||
PartTypeTool PartType = "tool"
|
PartTypeTool PartType = "tool"
|
||||||
PartTypeStepStart PartType = "step-start"
|
PartTypeStepStart PartType = "step-start"
|
||||||
@@ -1145,12 +1156,83 @@ const (
|
|||||||
|
|
||||||
func (r PartType) IsKnown() bool {
|
func (r PartType) IsKnown() bool {
|
||||||
switch r {
|
switch r {
|
||||||
case PartTypeText, PartTypeFile, PartTypeTool, PartTypeStepStart, PartTypeStepFinish, PartTypeSnapshot, PartTypePatch, PartTypeAgent:
|
case PartTypeText, PartTypeReasoning, PartTypeFile, PartTypeTool, PartTypeStepStart, PartTypeStepFinish, PartTypeSnapshot, PartTypePatch, PartTypeAgent:
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ReasoningPart struct {
|
||||||
|
ID string `json:"id,required"`
|
||||||
|
MessageID string `json:"messageID,required"`
|
||||||
|
SessionID string `json:"sessionID,required"`
|
||||||
|
Text string `json:"text,required"`
|
||||||
|
Type ReasoningPartType `json:"type,required"`
|
||||||
|
ProviderMetadata map[string]interface{} `json:"providerMetadata"`
|
||||||
|
Time ReasoningPartTime `json:"time"`
|
||||||
|
JSON reasoningPartJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reasoningPartJSON contains the JSON metadata for the struct [ReasoningPart]
|
||||||
|
type reasoningPartJSON struct {
|
||||||
|
ID apijson.Field
|
||||||
|
MessageID apijson.Field
|
||||||
|
SessionID apijson.Field
|
||||||
|
Text apijson.Field
|
||||||
|
Type apijson.Field
|
||||||
|
ProviderMetadata apijson.Field
|
||||||
|
Time apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ReasoningPart) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r reasoningPartJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r ReasoningPart) implementsPart() {}
|
||||||
|
|
||||||
|
type ReasoningPartType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ReasoningPartTypeReasoning ReasoningPartType = "reasoning"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r ReasoningPartType) IsKnown() bool {
|
||||||
|
switch r {
|
||||||
|
case ReasoningPartTypeReasoning:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReasoningPartTime struct {
|
||||||
|
Start float64 `json:"start,required"`
|
||||||
|
End float64 `json:"end"`
|
||||||
|
JSON reasoningPartTimeJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reasoningPartTimeJSON contains the JSON metadata for the struct
|
||||||
|
// [ReasoningPartTime]
|
||||||
|
type reasoningPartTimeJSON struct {
|
||||||
|
Start apijson.Field
|
||||||
|
End apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ReasoningPartTime) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r reasoningPartTimeJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
type Session struct {
|
type Session struct {
|
||||||
ID string `json:"id,required"`
|
ID string `json:"id,required"`
|
||||||
Time SessionTime `json:"time,required"`
|
Time SessionTime `json:"time,required"`
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"name": "@opencode-ai/sdk",
|
"name": "@opencode-ai/sdk",
|
||||||
"version": "0.4.1",
|
"version": "0.4.13",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
|
|||||||
@@ -182,6 +182,9 @@ export type Part =
|
|||||||
| ({
|
| ({
|
||||||
type: "text"
|
type: "text"
|
||||||
} & TextPart)
|
} & TextPart)
|
||||||
|
| ({
|
||||||
|
type: "reasoning"
|
||||||
|
} & ReasoningPart)
|
||||||
| ({
|
| ({
|
||||||
type: "file"
|
type: "file"
|
||||||
} & FilePart)
|
} & FilePart)
|
||||||
@@ -217,6 +220,21 @@ export type TextPart = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ReasoningPart = {
|
||||||
|
id: string
|
||||||
|
sessionID: string
|
||||||
|
messageID: string
|
||||||
|
type: string
|
||||||
|
text: string
|
||||||
|
metadata?: {
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
time: {
|
||||||
|
start: number
|
||||||
|
end?: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export type FilePart = {
|
export type FilePart = {
|
||||||
id: string
|
id: string
|
||||||
sessionID: string
|
sessionID: string
|
||||||
@@ -691,6 +709,7 @@ export type Config = {
|
|||||||
| {
|
| {
|
||||||
[key: string]: string
|
[key: string]: string
|
||||||
}
|
}
|
||||||
|
webfetch?: string
|
||||||
}
|
}
|
||||||
experimental?: {
|
experimental?: {
|
||||||
hook?: {
|
hook?: {
|
||||||
@@ -889,6 +908,16 @@ export type AgentConfig = {
|
|||||||
*/
|
*/
|
||||||
description?: string
|
description?: string
|
||||||
mode?: string
|
mode?: string
|
||||||
|
[key: string]:
|
||||||
|
| unknown
|
||||||
|
| string
|
||||||
|
| number
|
||||||
|
| {
|
||||||
|
[key: string]: boolean
|
||||||
|
}
|
||||||
|
| boolean
|
||||||
|
| string
|
||||||
|
| undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Provider = {
|
export type Provider = {
|
||||||
@@ -1036,6 +1065,9 @@ export type Agent = {
|
|||||||
tools: {
|
tools: {
|
||||||
[key: string]: boolean
|
[key: string]: boolean
|
||||||
}
|
}
|
||||||
|
options: {
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type EventSubscribeData = {
|
export type EventSubscribeData = {
|
||||||
|
|||||||
@@ -101,6 +101,7 @@ resources:
|
|||||||
toolPart: ToolPart
|
toolPart: ToolPart
|
||||||
agentPart: AgentPart
|
agentPart: AgentPart
|
||||||
agentPartInput: AgentPartInput
|
agentPartInput: AgentPartInput
|
||||||
|
reasoningPart: ReasoningPart
|
||||||
stepStartPart: StepStartPart
|
stepStartPart: StepStartPart
|
||||||
stepFinishPart: StepFinishPart
|
stepFinishPart: StepFinishPart
|
||||||
snapshotPart: SnapshotPart
|
snapshotPart: SnapshotPart
|
||||||
|
|||||||
@@ -27,6 +27,50 @@ import (
|
|||||||
"github.com/sst/opencode/internal/util"
|
"github.com/sst/opencode/internal/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type AttachmentInsertedMsg struct{}
|
||||||
|
|
||||||
|
// unescapeClipboardText trims surrounding quotes from clipboard text and returns the inner content.
|
||||||
|
// It avoids interpreting backslash escape sequences unless the text is explicitly quoted.
|
||||||
|
func (m *editorComponent) unescapeClipboardText(s string) string {
|
||||||
|
t := strings.TrimSpace(s)
|
||||||
|
if len(t) >= 2 {
|
||||||
|
first := t[0]
|
||||||
|
last := t[len(t)-1]
|
||||||
|
if (first == '"' && last == '"') || (first == '\'' && last == '\'') {
|
||||||
|
if u, err := strconv.Unquote(t); err == nil {
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
return t[1 : len(t)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
// pathExists checks if the given path exists. Relative paths are resolved against the app CWD.
|
||||||
|
// Supports expanding '~' to the user's home directory.
|
||||||
|
func (m *editorComponent) pathExists(p string) bool {
|
||||||
|
if p == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(p, "~") {
|
||||||
|
if home, err := os.UserHomeDir(); err == nil {
|
||||||
|
if p == "~" {
|
||||||
|
p = home
|
||||||
|
} else if strings.HasPrefix(p, "~/") {
|
||||||
|
p = filepath.Join(home, p[2:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check := p
|
||||||
|
if !filepath.IsAbs(check) {
|
||||||
|
check = filepath.Join(m.app.Info.Path.Cwd, check)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(check); err == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
type EditorComponent interface {
|
type EditorComponent interface {
|
||||||
tea.Model
|
tea.Model
|
||||||
tea.ViewModel
|
tea.ViewModel
|
||||||
@@ -153,60 +197,123 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
case tea.PasteMsg:
|
case tea.PasteMsg:
|
||||||
text := string(msg)
|
// Normalize clipboard text first
|
||||||
|
textRaw := string(msg)
|
||||||
|
text := m.unescapeClipboardText(textRaw)
|
||||||
|
|
||||||
if filePath := strings.TrimSpace(strings.TrimPrefix(text, "@")); strings.HasPrefix(text, "@") && filePath != "" {
|
// Case 1: pasted content contains one or more inline @paths -> insert attachments inline
|
||||||
statPath := filePath
|
// We scan the raw pasted text to preserve original content around attachments.
|
||||||
if !filepath.IsAbs(filePath) {
|
if strings.Contains(textRaw, "@") {
|
||||||
statPath = filepath.Join(m.app.Info.Path.Cwd, filePath)
|
last := 0
|
||||||
|
idx := 0
|
||||||
|
inserted := 0
|
||||||
|
for idx < len(textRaw) {
|
||||||
|
r, size := utf8.DecodeRuneInString(textRaw[idx:])
|
||||||
|
if r != '@' {
|
||||||
|
idx += size
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert preceding chunk before attempting to consume a path
|
||||||
|
if idx > last {
|
||||||
|
m.textarea.InsertRunesFromUserInput([]rune(textRaw[last:idx]))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract candidate path after '@' up to whitespace
|
||||||
|
start := idx + size
|
||||||
|
end := start
|
||||||
|
for end < len(textRaw) {
|
||||||
|
nr, ns := utf8.DecodeRuneInString(textRaw[end:])
|
||||||
|
if nr == ' ' || nr == '\t' || nr == '\n' || nr == '\r' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
end += ns
|
||||||
|
}
|
||||||
|
|
||||||
|
if end > start {
|
||||||
|
raw := textRaw[start:end]
|
||||||
|
// Trim common trailing punctuation that may follow paths in prose
|
||||||
|
trimmed := strings.TrimRight(raw, ",.;:)]}\\\"'?!")
|
||||||
|
suffix := raw[len(trimmed):]
|
||||||
|
p := filepath.Clean(trimmed)
|
||||||
|
if m.pathExists(p) {
|
||||||
|
att := m.createAttachmentFromPath(p)
|
||||||
|
if att != nil {
|
||||||
|
m.textarea.InsertAttachment(att)
|
||||||
|
if suffix != "" {
|
||||||
|
m.textarea.InsertRunesFromUserInput([]rune(suffix))
|
||||||
|
}
|
||||||
|
// Insert a trailing space only if the next rune isn't already whitespace
|
||||||
|
insertSpace := true
|
||||||
|
if end < len(textRaw) {
|
||||||
|
nr, _ := utf8.DecodeRuneInString(textRaw[end:])
|
||||||
|
if nr == ' ' || nr == '\t' || nr == '\n' || nr == '\r' {
|
||||||
|
insertSpace = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if insertSpace {
|
||||||
|
m.textarea.InsertString(" ")
|
||||||
|
}
|
||||||
|
inserted++
|
||||||
|
last = end
|
||||||
|
idx = end
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No valid path -> keep the '@' literally
|
||||||
|
m.textarea.InsertRune('@')
|
||||||
|
last = start
|
||||||
|
idx = start
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(statPath); err == nil {
|
// Insert any trailing content after the last processed segment
|
||||||
attachment := m.createAttachmentFromPath(filePath)
|
if last < len(textRaw) {
|
||||||
if attachment != nil {
|
m.textarea.InsertRunesFromUserInput([]rune(textRaw[last:]))
|
||||||
m.textarea.InsertAttachment(attachment)
|
}
|
||||||
|
if inserted > 0 {
|
||||||
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 2: user typed '@' and then pasted a valid path -> replace '@' with attachment
|
||||||
|
at := m.textarea.LastRuneIndex('@')
|
||||||
|
if at != -1 && at == m.textarea.CursorColumn()-1 {
|
||||||
|
p := filepath.Clean(text)
|
||||||
|
if m.pathExists(p) {
|
||||||
|
cur := m.textarea.CursorColumn()
|
||||||
|
m.textarea.ReplaceRange(at, cur, "")
|
||||||
|
att := m.createAttachmentFromPath(p)
|
||||||
|
if att != nil {
|
||||||
|
m.textarea.InsertAttachment(att)
|
||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
text = strings.ReplaceAll(text, "\\", "")
|
// Case 3: plain path pasted (e.g., drag-and-drop) -> attach if image or PDF
|
||||||
text, err := strconv.Unquote(`"` + text + `"`)
|
{
|
||||||
if err != nil {
|
p := filepath.Clean(text)
|
||||||
slog.Error("Failed to unquote text", "error", err)
|
if m.pathExists(p) {
|
||||||
text := string(msg)
|
mime := getMediaTypeFromExtension(strings.ToLower(filepath.Ext(p)))
|
||||||
if m.shouldSummarizePastedText(text) {
|
if strings.HasPrefix(mime, "image/") || mime == "application/pdf" {
|
||||||
m.handleLongPaste(text)
|
if att := m.createAttachmentFromFile(p); att != nil {
|
||||||
} else {
|
m.textarea.InsertAttachment(att)
|
||||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
m.textarea.InsertString(" ")
|
||||||
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(text); err != nil {
|
|
||||||
slog.Error("Failed to paste file", "error", err)
|
|
||||||
text := string(msg)
|
|
||||||
if m.shouldSummarizePastedText(text) {
|
|
||||||
m.handleLongPaste(text)
|
|
||||||
} else {
|
|
||||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
|
||||||
}
|
|
||||||
return m, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
filePath := text
|
// Default: do not auto-convert. Insert raw text or summarize long pastes.
|
||||||
|
if m.shouldSummarizePastedText(textRaw) {
|
||||||
attachment := m.createAttachmentFromFile(filePath)
|
m.handleLongPaste(textRaw)
|
||||||
if attachment == nil {
|
|
||||||
if m.shouldSummarizePastedText(text) {
|
|
||||||
m.handleLongPaste(text)
|
|
||||||
} else {
|
|
||||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
|
||||||
}
|
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
m.textarea.InsertRunesFromUserInput([]rune(textRaw))
|
||||||
m.textarea.InsertAttachment(attachment)
|
return m, nil
|
||||||
m.textarea.InsertString(" ")
|
|
||||||
case tea.ClipboardMsg:
|
case tea.ClipboardMsg:
|
||||||
text := string(msg)
|
text := string(msg)
|
||||||
// Check if the pasted text is long and should be summarized
|
// Check if the pasted text is long and should be summarized
|
||||||
@@ -233,7 +340,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
if atIndex == -1 {
|
if atIndex == -1 {
|
||||||
// Should not happen, but as a fallback, just insert.
|
// Should not happen, but as a fallback, just insert.
|
||||||
m.textarea.InsertString(msg.Item.Value + " ")
|
m.textarea.InsertString(msg.Item.Value + " ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
}
|
}
|
||||||
|
|
||||||
// The range to replace is from the '@' up to the current cursor position.
|
// The range to replace is from the '@' up to the current cursor position.
|
||||||
@@ -247,13 +354,13 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
attachment := m.createAttachmentFromPath(filePath)
|
attachment := m.createAttachmentFromPath(filePath)
|
||||||
m.textarea.InsertAttachment(attachment)
|
m.textarea.InsertAttachment(attachment)
|
||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
case "symbols":
|
case "symbols":
|
||||||
atIndex := m.textarea.LastRuneIndex('@')
|
atIndex := m.textarea.LastRuneIndex('@')
|
||||||
if atIndex == -1 {
|
if atIndex == -1 {
|
||||||
// Should not happen, but as a fallback, just insert.
|
// Should not happen, but as a fallback, just insert.
|
||||||
m.textarea.InsertString(msg.Item.Value + " ")
|
m.textarea.InsertString(msg.Item.Value + " ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
}
|
}
|
||||||
|
|
||||||
cursorCol := m.textarea.CursorColumn()
|
cursorCol := m.textarea.CursorColumn()
|
||||||
@@ -287,13 +394,13 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
m.textarea.InsertAttachment(attachment)
|
m.textarea.InsertAttachment(attachment)
|
||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
case "agents":
|
case "agents":
|
||||||
atIndex := m.textarea.LastRuneIndex('@')
|
atIndex := m.textarea.LastRuneIndex('@')
|
||||||
if atIndex == -1 {
|
if atIndex == -1 {
|
||||||
// Should not happen, but as a fallback, just insert.
|
// Should not happen, but as a fallback, just insert.
|
||||||
m.textarea.InsertString(msg.Item.Value + " ")
|
m.textarea.InsertString(msg.Item.Value + " ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
}
|
}
|
||||||
|
|
||||||
cursorCol := m.textarea.CursorColumn()
|
cursorCol := m.textarea.CursorColumn()
|
||||||
@@ -311,8 +418,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
m.textarea.InsertAttachment(attachment)
|
m.textarea.InsertAttachment(attachment)
|
||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
return m, nil
|
return m, util.CmdHandler(AttachmentInsertedMsg{})
|
||||||
|
|
||||||
default:
|
default:
|
||||||
slog.Debug("Unknown provider", "provider", msg.Item.ProviderID)
|
slog.Debug("Unknown provider", "provider", msg.Item.ProviderID)
|
||||||
return m, nil
|
return m, nil
|
||||||
|
|||||||
@@ -0,0 +1,277 @@
|
|||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/v2/spinner"
|
||||||
|
tea "github.com/charmbracelet/bubbletea/v2"
|
||||||
|
"github.com/sst/opencode/internal/app"
|
||||||
|
"github.com/sst/opencode/internal/completions"
|
||||||
|
"github.com/sst/opencode/internal/components/dialog"
|
||||||
|
"github.com/sst/opencode/internal/components/textarea"
|
||||||
|
"github.com/sst/opencode/internal/styles"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTestEditor() *editorComponent {
|
||||||
|
m := &editorComponent{
|
||||||
|
app: &app.App{},
|
||||||
|
textarea: textarea.New(),
|
||||||
|
spinner: spinner.New(),
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasteAtPathWithTrailingComma_PreservesPunctuation_NoDoubleSpace(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
p := createTempTextFile(t, "", "pc.txt", "x")
|
||||||
|
|
||||||
|
paste := "See @" + p + ", next"
|
||||||
|
_, cmd := m.Update(tea.PasteMsg(paste))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned for comma punctuation paste")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg for comma punctuation paste")
|
||||||
|
}
|
||||||
|
if len(m.textarea.GetAttachments()) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment, got %d", len(m.textarea.GetAttachments()))
|
||||||
|
}
|
||||||
|
v := m.Value()
|
||||||
|
if !strings.Contains(v, ", next") {
|
||||||
|
t.Fatalf("expected comma and following text to be preserved, got: %q", v)
|
||||||
|
}
|
||||||
|
if strings.Contains(v, ", next") {
|
||||||
|
t.Fatalf("did not expect double space after comma, got: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasteAtPathWithTrailingQuestion_PreservesPunctuation_NoDoubleSpace(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
p := createTempTextFile(t, "", "pq.txt", "x")
|
||||||
|
|
||||||
|
paste := "Check @" + p + "? Done"
|
||||||
|
_, cmd := m.Update(tea.PasteMsg(paste))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned for question punctuation paste")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg for question punctuation paste")
|
||||||
|
}
|
||||||
|
if len(m.textarea.GetAttachments()) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment, got %d", len(m.textarea.GetAttachments()))
|
||||||
|
}
|
||||||
|
v := m.Value()
|
||||||
|
if !strings.Contains(v, "? Done") {
|
||||||
|
t.Fatalf("expected question mark and following text to be preserved, got: %q", v)
|
||||||
|
}
|
||||||
|
if strings.Contains(v, "? Done") {
|
||||||
|
t.Fatalf("did not expect double space after question mark, got: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasteMultipleInlineAtPaths_AttachesEach(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
dir := t.TempDir()
|
||||||
|
p1 := createTempTextFile(t, dir, "m1.txt", "one")
|
||||||
|
p2 := createTempTextFile(t, dir, "m2.txt", "two")
|
||||||
|
|
||||||
|
// Build a paste with text around, two @paths, and punctuation after the first
|
||||||
|
paste := "Please check @" + p1 + ", and also @" + p2 + " thanks"
|
||||||
|
|
||||||
|
_, cmd := m.Update(tea.PasteMsg(paste))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned for multi inline paste")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg for multi inline paste")
|
||||||
|
}
|
||||||
|
|
||||||
|
atts := m.textarea.GetAttachments()
|
||||||
|
if len(atts) != 2 {
|
||||||
|
t.Fatalf("expected 2 attachments, got %d", len(atts))
|
||||||
|
}
|
||||||
|
v := m.Value()
|
||||||
|
if !strings.Contains(v, "Please check") || !strings.Contains(v, "and also") || !strings.Contains(v, "thanks") {
|
||||||
|
t.Fatalf("expected surrounding text to be preserved, got: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTempTextFile(t *testing.T, dir, name, content string) string {
|
||||||
|
t.Helper()
|
||||||
|
if dir == "" {
|
||||||
|
td, err := os.MkdirTemp("", "editor-test-*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to make temp dir: %v", err)
|
||||||
|
}
|
||||||
|
dir = td
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, name)
|
||||||
|
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
|
||||||
|
t.Fatalf("failed to write temp file: %v", err)
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to get abs path: %v", err)
|
||||||
|
}
|
||||||
|
return abs
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTempBinFile(t *testing.T, dir, name string, data []byte) string {
|
||||||
|
t.Helper()
|
||||||
|
if dir == "" {
|
||||||
|
td, err := os.MkdirTemp("", "editor-test-*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to make temp dir: %v", err)
|
||||||
|
}
|
||||||
|
dir = td
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, name)
|
||||||
|
if err := os.WriteFile(p, data, 0o600); err != nil {
|
||||||
|
t.Fatalf("failed to write temp bin file: %v", err)
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to get abs path: %v", err)
|
||||||
|
}
|
||||||
|
return abs
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasteStartsWithAt_AttachesAndEmitsMsg(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
p := createTempTextFile(t, "", "a.txt", "hello")
|
||||||
|
|
||||||
|
_, cmd := m.Update(tea.PasteMsg("@" + p))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned")
|
||||||
|
}
|
||||||
|
msg := cmd()
|
||||||
|
if _, ok := msg.(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg, got %T", msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
atts := m.textarea.GetAttachments()
|
||||||
|
if len(atts) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment, got %d", len(atts))
|
||||||
|
}
|
||||||
|
if v := m.Value(); !strings.HasSuffix(v, " ") {
|
||||||
|
t.Fatalf("expected trailing space after attachment, got value: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasteAfterAt_ReplacesAtWithAttachment(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
p := createTempTextFile(t, "", "b.txt", "hello")
|
||||||
|
|
||||||
|
m.textarea.SetValue("@")
|
||||||
|
// Cursor should be at the end after SetValue; paste absolute path
|
||||||
|
_, cmd := m.Update(tea.PasteMsg(p))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg from paste after '@'")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure the raw '@' rune was removed (attachment inserted in its place)
|
||||||
|
if m.textarea.LastRuneIndex('@') != -1 {
|
||||||
|
t.Fatalf("'@' rune should have been removed from the text slice")
|
||||||
|
}
|
||||||
|
if len(m.textarea.GetAttachments()) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment inserted")
|
||||||
|
}
|
||||||
|
if v := m.Value(); !strings.HasSuffix(v, " ") {
|
||||||
|
t.Fatalf("expected trailing space after attachment, got value: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlainTextPaste_NoAttachment_NoMsg(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
_, cmd := m.Update(tea.PasteMsg("hello"))
|
||||||
|
if cmd != nil {
|
||||||
|
t.Fatalf("expected no command for plain text paste")
|
||||||
|
}
|
||||||
|
if got := m.Value(); got != "hello" {
|
||||||
|
t.Fatalf("expected value 'hello', got %q", got)
|
||||||
|
}
|
||||||
|
if len(m.textarea.GetAttachments()) != 0 {
|
||||||
|
t.Fatalf("expected no attachments for plain text paste")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlainPathPng_AttachesImage(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
// Minimal bytes; content isn't validated, extension determines mime
|
||||||
|
p := createTempBinFile(t, "", "img.png", []byte{0x89, 'P', 'N', 'G'})
|
||||||
|
|
||||||
|
_, cmd := m.Update(tea.PasteMsg(p))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned for image path paste")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg for image path paste")
|
||||||
|
}
|
||||||
|
atts := m.textarea.GetAttachments()
|
||||||
|
if len(atts) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment, got %d", len(atts))
|
||||||
|
}
|
||||||
|
if atts[0].MediaType != "image/png" {
|
||||||
|
t.Fatalf("expected image/png mime, got %q", atts[0].MediaType)
|
||||||
|
}
|
||||||
|
if v := m.Value(); !strings.HasSuffix(v, " ") {
|
||||||
|
t.Fatalf("expected trailing space after attachment, got value: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlainPathPdf_AttachesPDF(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
p := createTempBinFile(t, "", "doc.pdf", []byte("%PDF-1.4"))
|
||||||
|
|
||||||
|
_, cmd := m.Update(tea.PasteMsg(p))
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned for pdf path paste")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg for pdf path paste")
|
||||||
|
}
|
||||||
|
atts := m.textarea.GetAttachments()
|
||||||
|
if len(atts) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment, got %d", len(atts))
|
||||||
|
}
|
||||||
|
if atts[0].MediaType != "application/pdf" {
|
||||||
|
t.Fatalf("expected application/pdf mime, got %q", atts[0].MediaType)
|
||||||
|
}
|
||||||
|
if v := m.Value(); !strings.HasSuffix(v, " ") {
|
||||||
|
t.Fatalf("expected trailing space after attachment, got value: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompletionFiles_InsertsAttachment_EmitsMsg(t *testing.T) {
|
||||||
|
m := newTestEditor()
|
||||||
|
p := createTempTextFile(t, "", "c.txt", "hello")
|
||||||
|
m.textarea.SetValue("@")
|
||||||
|
|
||||||
|
item := completions.CompletionSuggestion{
|
||||||
|
ProviderID: "files",
|
||||||
|
Value: p,
|
||||||
|
Display: func(_ styles.Style) string { return p },
|
||||||
|
}
|
||||||
|
// Build the completion selected message as if the user selected from the dialog
|
||||||
|
msg := dialog.CompletionSelectedMsg{Item: item, SearchString: "@"}
|
||||||
|
|
||||||
|
_, cmd := m.Update(msg)
|
||||||
|
if cmd == nil {
|
||||||
|
t.Fatalf("expected command to be returned")
|
||||||
|
}
|
||||||
|
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
|
||||||
|
t.Fatalf("expected AttachmentInsertedMsg from files completion selection")
|
||||||
|
}
|
||||||
|
if len(m.textarea.GetAttachments()) != 1 {
|
||||||
|
t.Fatalf("expected 1 attachment inserted from completion selection")
|
||||||
|
}
|
||||||
|
if v := m.Value(); !strings.HasSuffix(v, " ") {
|
||||||
|
t.Fatalf("expected trailing space after attachment, got value: %q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -208,6 +208,7 @@ func renderText(
|
|||||||
showToolDetails bool,
|
showToolDetails bool,
|
||||||
width int,
|
width int,
|
||||||
extra string,
|
extra string,
|
||||||
|
isThinking bool,
|
||||||
fileParts []opencode.FilePart,
|
fileParts []opencode.FilePart,
|
||||||
agentParts []opencode.AgentPart,
|
agentParts []opencode.AgentPart,
|
||||||
toolCalls ...opencode.ToolPart,
|
toolCalls ...opencode.ToolPart,
|
||||||
@@ -219,8 +220,15 @@ func renderText(
|
|||||||
var content string
|
var content string
|
||||||
switch casted := message.(type) {
|
switch casted := message.(type) {
|
||||||
case opencode.AssistantMessage:
|
case opencode.AssistantMessage:
|
||||||
|
bg := t.Background()
|
||||||
|
if isThinking {
|
||||||
|
bg = t.BackgroundPanel()
|
||||||
|
}
|
||||||
ts = time.UnixMilli(int64(casted.Time.Created))
|
ts = time.UnixMilli(int64(casted.Time.Created))
|
||||||
content = util.ToMarkdown(text, width, t.Background())
|
content = util.ToMarkdown(text, width, bg)
|
||||||
|
if isThinking {
|
||||||
|
content = styles.NewStyle().Background(bg).Foreground(t.TextMuted()).Render("Thinking") + "\n\n" + content
|
||||||
|
}
|
||||||
case opencode.UserMessage:
|
case opencode.UserMessage:
|
||||||
ts = time.UnixMilli(int64(casted.Time.Created))
|
ts = time.UnixMilli(int64(casted.Time.Created))
|
||||||
base := styles.NewStyle().Foreground(t.Text()).Background(backgroundColor)
|
base := styles.NewStyle().Foreground(t.Text()).Background(backgroundColor)
|
||||||
@@ -324,9 +332,37 @@ func renderText(
|
|||||||
if time.Now().Format("02 Jan 2006") == timestamp[:11] {
|
if time.Now().Format("02 Jan 2006") == timestamp[:11] {
|
||||||
timestamp = timestamp[12:]
|
timestamp = timestamp[12:]
|
||||||
}
|
}
|
||||||
info := fmt.Sprintf("%s (%s)", author, timestamp)
|
|
||||||
info = styles.NewStyle().Foreground(t.TextMuted()).Render(info)
|
|
||||||
|
|
||||||
|
// Check if this is an assistant message with mode (agent) information
|
||||||
|
var modelAndAgentSuffix string
|
||||||
|
if assistantMsg, ok := message.(opencode.AssistantMessage); ok && assistantMsg.Mode != "" {
|
||||||
|
// Find the agent index by name to get the correct color
|
||||||
|
var agentIndex int
|
||||||
|
for i, agent := range app.Agents {
|
||||||
|
if agent.Name == assistantMsg.Mode {
|
||||||
|
agentIndex = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get agent color based on the original agent index (same as status bar)
|
||||||
|
agentColor := util.GetAgentColor(agentIndex)
|
||||||
|
|
||||||
|
// Style the agent name with the same color as status bar
|
||||||
|
agentName := strings.Title(assistantMsg.Mode)
|
||||||
|
styledAgentName := styles.NewStyle().Foreground(agentColor).Bold(true).Render(agentName)
|
||||||
|
modelAndAgentSuffix = fmt.Sprintf(" | %s | %s", assistantMsg.ModelID, styledAgentName)
|
||||||
|
}
|
||||||
|
|
||||||
|
var info string
|
||||||
|
if modelAndAgentSuffix != "" {
|
||||||
|
// For assistant messages: "timestamp | modelID | agentName"
|
||||||
|
info = fmt.Sprintf("%s%s", timestamp, modelAndAgentSuffix)
|
||||||
|
} else {
|
||||||
|
// For user messages: "author (timestamp)"
|
||||||
|
info = fmt.Sprintf("%s (%s)", author, timestamp)
|
||||||
|
}
|
||||||
|
info = styles.NewStyle().Foreground(t.TextMuted()).Render(info)
|
||||||
if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
|
if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
|
||||||
content = content + "\n\n"
|
content = content + "\n\n"
|
||||||
for _, toolCall := range toolCalls {
|
for _, toolCall := range toolCalls {
|
||||||
@@ -357,6 +393,16 @@ func renderText(
|
|||||||
WithBorderColor(t.Secondary()),
|
WithBorderColor(t.Secondary()),
|
||||||
)
|
)
|
||||||
case opencode.AssistantMessage:
|
case opencode.AssistantMessage:
|
||||||
|
if isThinking {
|
||||||
|
return renderContentBlock(
|
||||||
|
app,
|
||||||
|
content,
|
||||||
|
width,
|
||||||
|
WithTextColor(t.Text()),
|
||||||
|
WithBackgroundColor(t.BackgroundPanel()),
|
||||||
|
WithBorderColor(t.BackgroundPanel()),
|
||||||
|
)
|
||||||
|
}
|
||||||
return renderContentBlock(
|
return renderContentBlock(
|
||||||
app,
|
app,
|
||||||
content,
|
content,
|
||||||
@@ -523,13 +569,9 @@ func renderToolDetails(
|
|||||||
case "bash":
|
case "bash":
|
||||||
command := toolInputMap["command"].(string)
|
command := toolInputMap["command"].(string)
|
||||||
body = fmt.Sprintf("```console\n$ %s\n", command)
|
body = fmt.Sprintf("```console\n$ %s\n", command)
|
||||||
stdout := metadata["stdout"]
|
output := metadata["output"]
|
||||||
if stdout != nil {
|
if output != nil {
|
||||||
body += ansi.Strip(fmt.Sprintf("%s", stdout))
|
body += ansi.Strip(fmt.Sprintf("%s", output))
|
||||||
}
|
|
||||||
stderr := metadata["stderr"]
|
|
||||||
if stderr != nil {
|
|
||||||
body += ansi.Strip(fmt.Sprintf("%s", stderr))
|
|
||||||
}
|
}
|
||||||
body += "```"
|
body += "```"
|
||||||
body = util.ToMarkdown(body, width, backgroundColor)
|
body = util.ToMarkdown(body, width, backgroundColor)
|
||||||
|
|||||||
@@ -369,6 +369,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
|||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
width,
|
width,
|
||||||
files,
|
files,
|
||||||
|
false,
|
||||||
fileParts,
|
fileParts,
|
||||||
agentParts,
|
agentParts,
|
||||||
)
|
)
|
||||||
@@ -448,6 +449,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
|||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
width,
|
width,
|
||||||
"",
|
"",
|
||||||
|
false,
|
||||||
[]opencode.FilePart{},
|
[]opencode.FilePart{},
|
||||||
[]opencode.AgentPart{},
|
[]opencode.AgentPart{},
|
||||||
toolCallParts...,
|
toolCallParts...,
|
||||||
@@ -469,6 +471,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
|||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
width,
|
width,
|
||||||
"",
|
"",
|
||||||
|
false,
|
||||||
[]opencode.FilePart{},
|
[]opencode.FilePart{},
|
||||||
[]opencode.AgentPart{},
|
[]opencode.AgentPart{},
|
||||||
toolCallParts...,
|
toolCallParts...,
|
||||||
@@ -546,6 +549,35 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
|||||||
lineCount += lipgloss.Height(content) + 1
|
lineCount += lipgloss.Height(content) + 1
|
||||||
blocks = append(blocks, content)
|
blocks = append(blocks, content)
|
||||||
}
|
}
|
||||||
|
case opencode.ReasoningPart:
|
||||||
|
if reverted {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text := "..."
|
||||||
|
if part.Text != "" {
|
||||||
|
text = part.Text
|
||||||
|
}
|
||||||
|
content = renderText(
|
||||||
|
m.app,
|
||||||
|
message.Info,
|
||||||
|
text,
|
||||||
|
casted.ModelID,
|
||||||
|
m.showToolDetails,
|
||||||
|
width,
|
||||||
|
"",
|
||||||
|
true,
|
||||||
|
[]opencode.FilePart{},
|
||||||
|
[]opencode.AgentPart{},
|
||||||
|
)
|
||||||
|
content = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
content,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
|
partCount++
|
||||||
|
lineCount += lipgloss.Height(content) + 1
|
||||||
|
blocks = append(blocks, content)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,30 +121,14 @@ func (m *statusComponent) View() string {
|
|||||||
|
|
||||||
var modeBackground compat.AdaptiveColor
|
var modeBackground compat.AdaptiveColor
|
||||||
var modeForeground compat.AdaptiveColor
|
var modeForeground compat.AdaptiveColor
|
||||||
switch m.app.AgentIndex {
|
|
||||||
case 0:
|
agentColor := util.GetAgentColor(m.app.AgentIndex)
|
||||||
|
|
||||||
|
if m.app.AgentIndex == 0 {
|
||||||
modeBackground = t.BackgroundElement()
|
modeBackground = t.BackgroundElement()
|
||||||
modeForeground = t.TextMuted()
|
modeForeground = agentColor
|
||||||
case 1:
|
} else {
|
||||||
modeBackground = t.Secondary()
|
modeBackground = agentColor
|
||||||
modeForeground = t.BackgroundPanel()
|
|
||||||
case 2:
|
|
||||||
modeBackground = t.Accent()
|
|
||||||
modeForeground = t.BackgroundPanel()
|
|
||||||
case 3:
|
|
||||||
modeBackground = t.Success()
|
|
||||||
modeForeground = t.BackgroundPanel()
|
|
||||||
case 4:
|
|
||||||
modeBackground = t.Warning()
|
|
||||||
modeForeground = t.BackgroundPanel()
|
|
||||||
case 5:
|
|
||||||
modeBackground = t.Primary()
|
|
||||||
modeForeground = t.BackgroundPanel()
|
|
||||||
case 6:
|
|
||||||
modeBackground = t.Error()
|
|
||||||
modeForeground = t.BackgroundPanel()
|
|
||||||
default:
|
|
||||||
modeBackground = t.Secondary()
|
|
||||||
modeForeground = t.BackgroundPanel()
|
modeForeground = t.BackgroundPanel()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -382,6 +382,9 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
a.app.Messages = []app.Message{}
|
a.app.Messages = []app.Message{}
|
||||||
case dialog.CompletionDialogCloseMsg:
|
case dialog.CompletionDialogCloseMsg:
|
||||||
a.showCompletionDialog = false
|
a.showCompletionDialog = false
|
||||||
|
case chat.AttachmentInsertedMsg:
|
||||||
|
// Close completion dialog when the editor inserts an attachment
|
||||||
|
a.showCompletionDialog = false
|
||||||
case opencode.EventListResponseEventInstallationUpdated:
|
case opencode.EventListResponseEventInstallationUpdated:
|
||||||
return a, toast.NewSuccessToast(
|
return a, toast.NewSuccessToast(
|
||||||
"opencode updated to "+msg.Properties.Version+", restart to apply.",
|
"opencode updated to "+msg.Properties.Version+", restart to apply.",
|
||||||
@@ -420,6 +423,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
switch casted := p.(type) {
|
switch casted := p.(type) {
|
||||||
case opencode.TextPart:
|
case opencode.TextPart:
|
||||||
return casted.ID == msg.Properties.Part.ID
|
return casted.ID == msg.Properties.Part.ID
|
||||||
|
case opencode.ReasoningPart:
|
||||||
|
return casted.ID == msg.Properties.Part.ID
|
||||||
case opencode.FilePart:
|
case opencode.FilePart:
|
||||||
return casted.ID == msg.Properties.Part.ID
|
return casted.ID == msg.Properties.Part.ID
|
||||||
case opencode.ToolPart:
|
case opencode.ToolPart:
|
||||||
@@ -458,6 +463,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
switch casted := p.(type) {
|
switch casted := p.(type) {
|
||||||
case opencode.TextPart:
|
case opencode.TextPart:
|
||||||
return casted.ID == msg.Properties.PartID
|
return casted.ID == msg.Properties.PartID
|
||||||
|
case opencode.ReasoningPart:
|
||||||
|
return casted.ID == msg.Properties.PartID
|
||||||
case opencode.FilePart:
|
case opencode.FilePart:
|
||||||
return casted.ID == msg.Properties.PartID
|
return casted.ID == msg.Properties.PartID
|
||||||
case opencode.ToolPart:
|
case opencode.ToolPart:
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ package util
|
|||||||
import (
|
import (
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/lipgloss/v2/compat"
|
||||||
|
"github.com/sst/opencode/internal/theme"
|
||||||
)
|
)
|
||||||
|
|
||||||
var csiRE *regexp.Regexp
|
var csiRE *regexp.Regexp
|
||||||
@@ -89,5 +92,24 @@ func ConvertRGBToAnsi16Colors(s string) string {
|
|||||||
|
|
||||||
// func looksLikeByte(tok string) bool {
|
// func looksLikeByte(tok string) bool {
|
||||||
// v, err := strconv.Atoi(tok)
|
// v, err := strconv.Atoi(tok)
|
||||||
// return err == nil && v >= 0 && v <= 255
|
// return err == nil && v >= 0 && v <= 255
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// GetAgentColor returns the color for a given agent index, matching the status bar colors
|
||||||
|
func GetAgentColor(agentIndex int) compat.AdaptiveColor {
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
agentColors := []compat.AdaptiveColor{
|
||||||
|
t.TextMuted(),
|
||||||
|
t.Secondary(),
|
||||||
|
t.Accent(),
|
||||||
|
t.Success(),
|
||||||
|
t.Warning(),
|
||||||
|
t.Primary(),
|
||||||
|
t.Error(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if agentIndex >= 0 && agentIndex < len(agentColors) {
|
||||||
|
return agentColors[agentIndex]
|
||||||
|
}
|
||||||
|
return t.Secondary() // default fallback
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode/web",
|
"name": "@opencode/web",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "0.4.1",
|
"version": "0.4.13",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "astro dev",
|
"dev": "astro dev",
|
||||||
"dev:remote": "sst shell --stage=dev --target=Web astro dev",
|
"dev:remote": "sst shell --stage=dev --target=Web astro dev",
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ export default function Share(props: {
|
|||||||
const [store, setStore] = createStore<{
|
const [store, setStore] = createStore<{
|
||||||
info?: Session.Info
|
info?: Session.Info
|
||||||
messages: Record<string, MessageWithParts>
|
messages: Record<string, MessageWithParts>
|
||||||
}>({ info: props.info, messages: mapValues(props.messages, (x: any) => "metadata" in x ? fromV1(x) : x) })
|
}>({ info: props.info, messages: mapValues(props.messages, (x: any) => ("metadata" in x ? fromV1(x) : x)) })
|
||||||
const messages = createMemo(() => Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)))
|
const messages = createMemo(() => Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)))
|
||||||
const [connectionStatus, setConnectionStatus] = createSignal<[Status, string?]>(["disconnected", "Disconnected"])
|
const [connectionStatus, setConnectionStatus] = createSignal<[Status, string?]>(["disconnected", "Disconnected"])
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
@@ -128,12 +128,10 @@ export default function Share(props: {
|
|||||||
setStore("messages", messageID, reconcile(d.content))
|
setStore("messages", messageID, reconcile(d.content))
|
||||||
}
|
}
|
||||||
if (type === "part") {
|
if (type === "part") {
|
||||||
setStore("messages", d.content.messageID, "parts", arr => {
|
setStore("messages", d.content.messageID, "parts", (arr) => {
|
||||||
const index = arr.findIndex((x) => x.id === d.content.id)
|
const index = arr.findIndex((x) => x.id === d.content.id)
|
||||||
if (index === -1)
|
if (index === -1) arr.push(d.content)
|
||||||
arr.push(d.content)
|
if (index > -1) arr[index] = d.content
|
||||||
if (index > -1)
|
|
||||||
arr[index] = d.content
|
|
||||||
return [...arr]
|
return [...arr]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -350,7 +348,7 @@ export default function Share(props: {
|
|||||||
if (x.type === "tool" && (x.state.status === "pending" || x.state.status === "running"))
|
if (x.type === "tool" && (x.state.status === "pending" || x.state.status === "running"))
|
||||||
return false
|
return false
|
||||||
return true
|
return true
|
||||||
})
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -54,7 +54,10 @@ export function IconOpencode(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
|||||||
export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||||
return (
|
return (
|
||||||
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
<path fill="currentColor" d="M16.92 4.5c-1.851 0-3.298 1.394-4.608 3.165C10.512 5.373 9.007 4.5 7.206 4.5C3.534 4.5.72 9.28.72 14.338c0 3.165 1.531 5.162 4.096 5.162c1.846 0 3.174-.87 5.535-4.997c0 0 .984-1.737 1.66-2.934q.356.574.75 1.238l1.107 1.862c2.156 3.608 3.358 4.831 5.534 4.831c2.5 0 3.89-2.024 3.89-5.255c0-5.297-2.877-9.745-6.372-9.745m-8.37 8.886c-1.913 3-2.575 3.673-3.64 3.673c-1.097 0-1.749-.963-1.749-2.68c0-3.672 1.831-7.427 4.014-7.427c1.182 0 2.17.682 3.683 2.848c-1.437 2.204-2.307 3.586-2.307 3.586m7.224-.377L14.45 10.8a45 45 0 0 0-1.032-1.608c1.193-1.841 2.176-2.759 3.347-2.759c2.43 0 4.375 3.58 4.375 7.976c0 1.676-.549 2.649-1.686 2.649c-1.09 0-1.61-.72-3.68-4.05" />
|
<path
|
||||||
|
fill="currentColor"
|
||||||
|
d="M16.92 4.5c-1.851 0-3.298 1.394-4.608 3.165C10.512 5.373 9.007 4.5 7.206 4.5C3.534 4.5.72 9.28.72 14.338c0 3.165 1.531 5.162 4.096 5.162c1.846 0 3.174-.87 5.535-4.997c0 0 .984-1.737 1.66-2.934q.356.574.75 1.238l1.107 1.862c2.156 3.608 3.358 4.831 5.534 4.831c2.5 0 3.89-2.024 3.89-5.255c0-5.297-2.877-9.745-6.372-9.745m-8.37 8.886c-1.913 3-2.575 3.673-3.64 3.673c-1.097 0-1.749-.963-1.749-2.68c0-3.672 1.831-7.427 4.014-7.427c1.182 0 2.17.682 3.683 2.848c-1.437 2.204-2.307 3.586-2.307 3.586m7.224-.377L14.45 10.8a45 45 0 0 0-1.032-1.608c1.193-1.841 2.176-2.759 3.347-2.759c2.43 0 4.375 3.58 4.375 7.976c0 1.676-.549 2.649-1.686 2.649c-1.09 0-1.61-.72-3.68-4.05"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -63,6 +66,22 @@ export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
|||||||
export function IconRobot(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
export function IconRobot(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||||
return (
|
return (
|
||||||
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
<path fill="currentColor" d="M13.5 2c0 .444-.193.843-.5 1.118V5h5a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3h5V3.118A1.5 1.5 0 1 1 13.5 2M6 7a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1zm-4 3H0v6h2zm20 0h2v6h-2zM9 14.5a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3m6 0a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3" /></svg>
|
<path
|
||||||
|
fill="currentColor"
|
||||||
|
d="M13.5 2c0 .444-.193.843-.5 1.118V5h5a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3h5V3.118A1.5 1.5 0 1 1 13.5 2M6 7a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1zm-4 3H0v6h2zm20 0h2v6h-2zM9 14.5a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3m6 0a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://icones.js.org/collection/ri?s=brain&icon=ri:brain-2-line
|
||||||
|
export function IconBrain(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||||
|
return (
|
||||||
|
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path
|
||||||
|
fill="currentColor"
|
||||||
|
d="M7 6q.001.357.115.67a1 1 0 0 1-1 1.333L6 8a2 2 0 0 0-1.491 3.333a1 1 0 0 1 0 1.334a2 2 0 0 0 .864 3.233a1 1 0 0 1 .67 1.135a2.5 2.5 0 1 0 4.932.824q.009-.063.025-.123V6a2 2 0 1 0-4 0m6 11.736q.016.06.025.122a2.5 2.5 0 1 0 4.932-.823a1 1 0 0 1 .67-1.135a2 2 0 0 0 .864-3.233a1 1 0 0 1 0-1.334a2 2 0 0 0-1.607-3.33a1 1 0 0 1-.999-1.333q.113-.313.115-.67a2 2 0 1 0-4 0zM9 2a4 4 0 0 1 3 1.354a4 4 0 0 1 6.998 2.771A4.002 4.002 0 0 1 21.465 12A3.997 3.997 0 0 1 20 17.465v.035a4.5 4.5 0 0 1-8 2.828A4.5 4.5 0 0 1 4 17.5v-.035A3.997 3.997 0 0 1 2.535 12a4.002 4.002 0 0 1 2.467-5.874L5 6a4 4 0 0 1 4-4"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,6 +128,29 @@
|
|||||||
max-width: var(--md-tool-width);
|
max-width: var(--md-tool-width);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[data-component="assistant-reasoning"] {
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
flex-grow: 1;
|
||||||
|
max-width: var(--md-tool-width);
|
||||||
|
|
||||||
|
& > [data-component="assistant-reasoning-markdown"] {
|
||||||
|
align-self: flex-start;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
border: 1px solid var(--sl-color-blue-high);
|
||||||
|
padding: 0.5rem calc(0.5rem + 3px);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
position: relative;
|
||||||
|
|
||||||
|
[data-component="copy-button"] {
|
||||||
|
top: 0.5rem;
|
||||||
|
right: calc(0.5rem - 1px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[data-component="assistant-text"] {
|
[data-component="assistant-text"] {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
IconMagnifyingGlass,
|
IconMagnifyingGlass,
|
||||||
IconDocumentMagnifyingGlass,
|
IconDocumentMagnifyingGlass,
|
||||||
} from "../icons"
|
} from "../icons"
|
||||||
import { IconMeta, IconRobot, IconOpenAI, IconGemini, IconAnthropic } from "../icons/custom"
|
import { IconMeta, IconRobot, IconOpenAI, IconGemini, IconAnthropic, IconBrain } from "../icons/custom"
|
||||||
import { ContentCode } from "./content-code"
|
import { ContentCode } from "./content-code"
|
||||||
import { ContentDiff } from "./content-diff"
|
import { ContentDiff } from "./content-diff"
|
||||||
import { ContentText } from "./content-text"
|
import { ContentText } from "./content-text"
|
||||||
@@ -83,6 +83,9 @@ export function Part(props: PartProps) {
|
|||||||
>
|
>
|
||||||
{(model) => <ProviderIcon model={model()} size={18} />}
|
{(model) => <ProviderIcon model={model()} size={18} />}
|
||||||
</Match>
|
</Match>
|
||||||
|
<Match when={props.part.type === "reasoning" && props.message.role === "assistant"}>
|
||||||
|
<IconBrain width={18} height={18} />
|
||||||
|
</Match>
|
||||||
<Match when={props.part.type === "tool" && props.part.tool === "todowrite"}>
|
<Match when={props.part.type === "tool" && props.part.tool === "todowrite"}>
|
||||||
<IconQueueList width={18} height={18} />
|
<IconQueueList width={18} height={18} />
|
||||||
</Match>
|
</Match>
|
||||||
@@ -144,11 +147,26 @@ export function Part(props: PartProps) {
|
|||||||
DateTime.DATETIME_FULL_WITH_SECONDS,
|
DateTime.DATETIME_FULL_WITH_SECONDS,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{DateTime.fromMillis(props.message.time.completed).toLocaleString(DateTime.DATETIME_MED)}
|
{DateTime.fromMillis(props.message.time.completed || props.message.time.created).toLocaleString(
|
||||||
|
DateTime.DATETIME_MED,
|
||||||
|
)}
|
||||||
|
{` | ${props.message.modelID}`}
|
||||||
|
{props.message.mode && (
|
||||||
|
<span style={{ "font-weight": "bold", color: "var(--sl-color-accent)" }}>
|
||||||
|
{` | ${props.message.mode}`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</Footer>
|
</Footer>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{props.message.role === "assistant" && props.part.type === "reasoning" && (
|
||||||
|
<div data-component="assistant-reasoning">
|
||||||
|
<div data-component="assistant-reasoning-markdown">
|
||||||
|
<ContentMarkdown expand={props.last} text={props.part.text || "Thinking..."} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{props.message.role === "user" && props.part.type === "file" && (
|
{props.message.role === "user" && props.part.type === "file" && (
|
||||||
<div data-component="attachment">
|
<div data-component="attachment">
|
||||||
<div data-slot="copy">Attachment</div>
|
<div data-slot="copy">Attachment</div>
|
||||||
@@ -158,7 +176,17 @@ export function Part(props: PartProps) {
|
|||||||
{props.part.type === "step-start" && props.message.role === "assistant" && (
|
{props.part.type === "step-start" && props.message.role === "assistant" && (
|
||||||
<div data-component="step-start">
|
<div data-component="step-start">
|
||||||
<div data-slot="provider">{props.message.providerID}</div>
|
<div data-slot="provider">{props.message.providerID}</div>
|
||||||
<div data-slot="model">{props.message.modelID}</div>
|
<div data-slot="model">
|
||||||
|
{DateTime.fromMillis(props.message.time.completed || props.message.time.created).toLocaleString(
|
||||||
|
DateTime.DATETIME_MED,
|
||||||
|
)}
|
||||||
|
{` | ${props.message.modelID}`}
|
||||||
|
{props.message.mode && (
|
||||||
|
<span style={{ "font-weight": "bold", color: "var(--sl-color-accent)" }}>
|
||||||
|
{` | ${props.message.mode}`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{props.part.type === "tool" && props.part.state.status === "error" && (
|
{props.part.type === "tool" && props.part.state.status === "error" && (
|
||||||
@@ -577,7 +605,7 @@ export function BashTool(props: ToolProps) {
|
|||||||
return (
|
return (
|
||||||
<ContentBash
|
<ContentBash
|
||||||
command={props.state.input.command}
|
command={props.state.input.command}
|
||||||
output={props.state.metadata?.stdout || ""}
|
output={props.state.metadata.output ?? props.state.metadata?.stdout}
|
||||||
description={props.state.metadata.description}
|
description={props.state.metadata.description}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -653,9 +681,7 @@ function TaskTool(props: ToolProps) {
|
|||||||
<span data-slot="name">Task</span>
|
<span data-slot="name">Task</span>
|
||||||
<span data-slot="target">{props.state.input.description}</span>
|
<span data-slot="target">{props.state.input.description}</span>
|
||||||
</div>
|
</div>
|
||||||
<div data-component="tool-input">
|
<div data-component="tool-input">“{props.state.input.prompt}”</div>
|
||||||
“{props.state.input.prompt}”
|
|
||||||
</div>
|
|
||||||
<ResultsButton showCopy="Show output" hideCopy="Hide output">
|
<ResultsButton showCopy="Show output" hideCopy="Hide output">
|
||||||
<div data-component="tool-output">
|
<div data-component="tool-output">
|
||||||
<ContentMarkdown expand text={props.state.output} />
|
<ContentMarkdown expand text={props.state.output} />
|
||||||
|
|||||||
@@ -360,6 +360,41 @@ The `mode` option can be set to `primary`, `subagent`, or `all`. If no `mode` is
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Additional options
|
||||||
|
|
||||||
|
Any other options you specify in your agent configuration will be passed through directly to the provider as model options. This allows you to use provider-specific features and parameters.
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"agent": {
|
||||||
|
"reasoning": {
|
||||||
|
"model": "openai/gpt-5-turbo",
|
||||||
|
"reasoningEffort": "high",
|
||||||
|
"textVerbosity": "medium"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For example, with OpenAI's reasoning models, you can control the reasoning effort:
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"agent": {
|
||||||
|
"deep-thinker": {
|
||||||
|
"description": "Agent that uses high reasoning effort for complex problems",
|
||||||
|
"model": "openai/gpt-5-turbo",
|
||||||
|
"reasoningEffort": "high",
|
||||||
|
"textVerbosity": "low"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
These additional options are model and provider-specific. Check your provider's documentation for available parameters.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Create agents
|
## Create agents
|
||||||
|
|
||||||
You can create new agents using the following command:
|
You can create new agents using the following command:
|
||||||
|
|||||||
@@ -11,9 +11,10 @@ opencode integrates with your Language Server Protocol (LSP) to help the LLM int
|
|||||||
|
|
||||||
opencode comes with several built-in LSP servers for popular languages:
|
opencode comes with several built-in LSP servers for popular languages:
|
||||||
|
|
||||||
| LSP Server | Extensions | Requirements |
|
| LSP Server | Extensions | Requirements |
|
||||||
| ---------- | -------------------------------------------- | ----------------------------------- |
|
| ---------- | -------------------------------------------- | ----------------------------------- |
|
||||||
| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project |
|
| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project |
|
||||||
|
| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `eslint` dependency in project |
|
||||||
| gopls | .go | `go` command available |
|
| gopls | .go | `go` command available |
|
||||||
| ruby-lsp | .rb, .rake, .gemspec, .ru | `ruby` and `gem` commands available |
|
| ruby-lsp | .rb, .rake, .gemspec, .ru | `ruby` and `gem` commands available |
|
||||||
| pyright | .py, .pyi | `pyright` dependency installed |
|
| pyright | .py, .pyi | `pyright` dependency installed |
|
||||||
@@ -41,7 +42,7 @@ You can customize LSP servers through the `lsp` section in your opencode config.
|
|||||||
```json title="opencode.json"
|
```json title="opencode.json"
|
||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"lsp": { }
|
"lsp": {}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -49,7 +50,7 @@ Each LSP server supports the following:
|
|||||||
|
|
||||||
| Property | Type | Description |
|
| Property | Type | Description |
|
||||||
| ---------------- | -------- | ------------------------------------------------- |
|
| ---------------- | -------- | ------------------------------------------------- |
|
||||||
| `disabled` | boolean | Set this to `true` to disable the LSP server |
|
| `disabled` | boolean | Set this to `true` to disable the LSP server |
|
||||||
| `command` | string[] | The command to start the LSP server |
|
| `command` | string[] | The command to start the LSP server |
|
||||||
| `extensions` | string[] | File extensions this LSP server should handle |
|
| `extensions` | string[] | File extensions this LSP server should handle |
|
||||||
| `env` | object | Environment variables to set when starting server |
|
| `env` | object | Environment variables to set when starting server |
|
||||||
|
|||||||
@@ -13,6 +13,14 @@ The permissions system provides granular control to restrict what actions AI age
|
|||||||
|
|
||||||
Permissions are configured in your `opencode.json` file under the `permission` key. Here are the available options.
|
Permissions are configured in your `opencode.json` file under the `permission` key. Here are the available options.
|
||||||
|
|
||||||
|
### Tool Permission Support
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
| ---------- | ------------------------------- |
|
||||||
|
| `edit` | Control file editing operations |
|
||||||
|
| `bash` | Control bash command execution |
|
||||||
|
| `webfetch` | Control web content fetching |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### edit
|
### edit
|
||||||
|
|||||||
@@ -546,7 +546,7 @@ To use Kimi K2 from Moonshot AI:
|
|||||||
|
|
||||||
1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**.
|
1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**.
|
||||||
|
|
||||||
2. Run `opencode auth login` and select **Other**.
|
2. Run `opencode auth login` and select **Moonshot AI**.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ opencode auth login
|
$ opencode auth login
|
||||||
@@ -555,11 +555,11 @@ To use Kimi K2 from Moonshot AI:
|
|||||||
│
|
│
|
||||||
◆ Select provider
|
◆ Select provider
|
||||||
│ ...
|
│ ...
|
||||||
│ ● Other
|
│ ● Moonshot AI
|
||||||
└
|
└
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Enter `moonshot` as the provider ID.
|
3. Enter your Moonshot API key.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ opencode auth login
|
$ opencode auth login
|
||||||
@@ -567,48 +567,14 @@ To use Kimi K2 from Moonshot AI:
|
|||||||
┌ Add credential
|
┌ Add credential
|
||||||
│
|
│
|
||||||
◇ Select provider
|
◇ Select provider
|
||||||
│ Other
|
│ Moonshot AI
|
||||||
│
|
|
||||||
◇ Enter provider id
|
|
||||||
│ moonshot
|
|
||||||
└
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Enter your Moonshot API key.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ opencode auth login
|
|
||||||
|
|
||||||
┌ Add credential
|
|
||||||
│
|
│
|
||||||
◇ Enter your API key
|
◇ Enter your API key
|
||||||
│ sk-...
|
│ _
|
||||||
└
|
└
|
||||||
```
|
```
|
||||||
|
|
||||||
5. Configure Moonshot in your opencode config.
|
4. Run the `/models` command to select _Kimi K2_.
|
||||||
|
|
||||||
```json title="opencode.json" ""moonshot"" {5-15}
|
|
||||||
{
|
|
||||||
"$schema": "https://opencode.ai/config.json",
|
|
||||||
"provider": {
|
|
||||||
"moonshot": {
|
|
||||||
"npm": "@ai-sdk/openai-compatible",
|
|
||||||
"name": "Moonshot AI",
|
|
||||||
"options": {
|
|
||||||
"baseURL": "https://api.moonshot.ai/v1"
|
|
||||||
},
|
|
||||||
"models": {
|
|
||||||
"kimi-k2-0711-preview": {
|
|
||||||
"name": "Kimi K2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
6. Run the `/models` command to select _Kimi K2_.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
import { $ } from "bun"
|
import { $ } from "bun"
|
||||||
|
import path from "path"
|
||||||
|
|
||||||
console.log("=== publishing ===\n")
|
console.log("=== publishing ===\n")
|
||||||
|
|
||||||
@@ -38,10 +39,46 @@ await import(`../packages/sdk/js/script/publish.ts`)
|
|||||||
console.log("\n=== plugin ===\n")
|
console.log("\n=== plugin ===\n")
|
||||||
await import(`../packages/plugin/script/publish.ts`)
|
await import(`../packages/plugin/script/publish.ts`)
|
||||||
|
|
||||||
|
const dir = new URL("..", import.meta.url).pathname
|
||||||
|
process.chdir(dir)
|
||||||
|
|
||||||
if (!snapshot) {
|
if (!snapshot) {
|
||||||
await $`git commit -am "release: v${version}"`
|
await $`git commit -am "release: v${version}"`
|
||||||
await $`git tag v${version}`
|
await $`git tag v${version}`
|
||||||
await $`git push origin HEAD --tags --no-verify`
|
await $`git push origin HEAD --tags --no-verify`
|
||||||
|
|
||||||
|
const previous = await fetch("https://api.github.com/repos/sst/opencode/releases/latest")
|
||||||
|
.then((res) => {
|
||||||
|
if (!res.ok) throw new Error(res.statusText)
|
||||||
|
return res.json()
|
||||||
|
})
|
||||||
|
.then((data) => data.tag_name)
|
||||||
|
|
||||||
|
console.log("finding commits between", previous, "and", "HEAD")
|
||||||
|
const commits = await fetch(`https://api.github.com/repos/sst/opencode/compare/${previous}...HEAD`)
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data) => data.commits || [])
|
||||||
|
|
||||||
|
const raw = commits.map((commit: any) => `- ${commit.commit.message.split("\n").join(" ")}`)
|
||||||
|
console.log(raw)
|
||||||
|
|
||||||
|
const notes =
|
||||||
|
raw
|
||||||
|
.filter((x: string) => {
|
||||||
|
const lower = x.toLowerCase()
|
||||||
|
return (
|
||||||
|
!lower.includes("release:") &&
|
||||||
|
!lower.includes("ignore:") &&
|
||||||
|
!lower.includes("chore:") &&
|
||||||
|
!lower.includes("ci:") &&
|
||||||
|
!lower.includes("wip:") &&
|
||||||
|
!lower.includes("docs:") &&
|
||||||
|
!lower.includes("doc:")
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.join("\n") || "No notable changes"
|
||||||
|
|
||||||
|
await $`gh release create v${version} --title "v${version}" --notes ${notes} ./packages/opencode/dist/*.zip`
|
||||||
}
|
}
|
||||||
if (snapshot) {
|
if (snapshot) {
|
||||||
await $`git checkout -b snapshot-${version}`
|
await $`git checkout -b snapshot-${version}`
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "opencode",
|
"name": "opencode",
|
||||||
"displayName": "opencode",
|
"displayName": "opencode",
|
||||||
"description": "opencode for VS Code",
|
"description": "opencode for VS Code",
|
||||||
"version": "0.4.1",
|
"version": "0.4.13",
|
||||||
"publisher": "sst-dev",
|
"publisher": "sst-dev",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
Vendored
+4
@@ -63,6 +63,10 @@ declare module "sst" {
|
|||||||
"type": "sst.sst.Secret"
|
"type": "sst.sst.Secret"
|
||||||
"value": string
|
"value": string
|
||||||
}
|
}
|
||||||
|
"GOOGLE_CLIENT_ID": {
|
||||||
|
"type": "sst.sst.Secret"
|
||||||
|
"value": string
|
||||||
|
}
|
||||||
"GatewayApi": {
|
"GatewayApi": {
|
||||||
"type": "sst.cloudflare.Worker"
|
"type": "sst.cloudflare.Worker"
|
||||||
"url": string
|
"url": string
|
||||||
|
|||||||
Reference in New Issue
Block a user