mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat(free-tier): inject the official OpenCode system prompt
The free tier only accepts agent-shaped traffic and checks it against the official CLI's prompt. Every shaped free-model body now carries that base prompt plus the <env> block (model, working directory, platform, UTC date) and the built-in skill listing. - v1 /zen uses the 1.x tool names; /inference and /zen/go use the 2.x names. - Chat folds system and developer messages into one leading system message, Anthropic prepends to system (string or text block), and Responses prepends instructions. - A body whose system content already carries the marker is passed through, so the prompt is never duplicated. System One is untouched. - Key-tier free models receive the same shaping; paid models and Go-tier paid traffic are unchanged.
This commit is contained in:
1 parent
4438acb8e7
commit
97cdb29713
8 files changed
+453
No files matched your search
@@ -234,6 +234,12 @@ Il tunnel vive nel processo del gateway: registra un dispositivo WARP, parla Wir
|
||||
|
||||
`warp.pool_size` (1–8, predefinito `2`) mantiene attive altrettante uscite e sostituisce automaticamente un'uscita bloccata o guasta; `warp.stack` seleziona `ipv4` (predefinito), `ipv6` o `dual`. `/healthz` restituisce un blocco `warp` e risponde 503 quando WARP è attivo ma nessuna uscita è operativa; `no_healthy_proxies` blocca la readiness solo con WARP disattivato o quando servono proxy per le chiavi Go. Le richieste diagnostiche acquisiscono un'uscita ma non la ruotano né la penalizzano. Disattivando WARP, i canali gratuiti tornano a usare i proxy.
|
||||
|
||||
### System prompt ufficiale
|
||||
|
||||
Ogni richiesta di un modello gratuito già normalizzata porta il system prompt della CLI OpenCode — istruzioni di base, blocco `<env>` ed elenco delle skill integrate — perché il canale gratuito verifica che il traffico abbia forma di agent. Il canale v1 `/zen` usa i nomi degli strumenti 1.x; `/inference` e `/zen/go` usano quelli 2.x. Il blocco ambiente indica il modello richiesto, la directory di lavoro del gateway, la piattaforma e la data UTC.
|
||||
|
||||
L'iniezione dipende dal protocollo: i messaggi system e developer di Chat vengono fusi in un unico messaggio `system` iniziale; Anthropic riceve un valore `system` (stringa, oppure un blocco di testo iniziale quando il chiamante invia blocchi); Responses riceve `instructions`. Se il contenuto system contiene già il marcatore `You are opencode, an interactive CLI tool`, la richiesta passa invariata, quindi un client che invia già il prompt ufficiale non ne riceve una seconda copia. I modelli gratuiti serviti da una chiave Zen o Go ricevono la stessa normalizzazione, ma escono comunque dal proxy di quel tier.
|
||||
|
||||
### Disponibilità dei modelli gratuiti
|
||||
|
||||
Il gateway verifica con una breve richiesta e il protocollo nativo i modelli il cui ID contiene `free` (senza distinzione tra maiuscole e minuscole) oppure i cui metadati indicano un costo input/output pari a zero e che non sono deprecati. Prova prima il canale anonimo abilitato, poi una chiave Zen configurata. Con `warp.enabled`, ogni canale di probe esce tramite WARP invece che da un proxy; se non è possibile acquisire un'uscita il risultato è `warp_unavailable` e resta inconcludente. Una risposta valida e completa su uno dei canali mantiene il modello abilitato. Il modello viene disabilitato nel rilevamento e nell'instradamento solo quando tutti i canali provati indicano esplicitamente che non esiste o è stato ritirato. Errori di autenticazione, limiti di frequenza, timeout, errori di trasporto, risposte 5xx e risposte malformate non sono conclusivi: non disabilitano nuovi modelli e vengono verificati di nuovo dopo un'ora. I controlli non alterano cooldown, stato dei proxy o statistiche delle richieste di produzione, ma raggiungono comunque l'upstream e possono consumare la quota gratuita.
|
||||
|
||||
@@ -236,6 +236,12 @@ The tunnel lives inside the gateway process: it registers a WARP device, speaks
|
||||
|
||||
`warp.pool_size` (1–8, default `2`) keeps that many exits active and replaces a blocked or broken exit automatically. `warp.stack` selects `ipv4` (default), `ipv6`, or `dual`. `/healthz` reports a `warp` block and answers 503 while WARP is enabled but no exit is active; `no_healthy_proxies` only blocks readiness when WARP is off or Go keys need proxies. Diagnostics acquire an exit but never rotate or penalize it. Turning WARP off restores proxy routing for the free lanes.
|
||||
|
||||
### Official system prompt
|
||||
|
||||
Every shaped free-model request carries the OpenCode CLI's own system prompt — its base instructions, the `<env>` block, and the built-in skill listing — because the free tier validates agent-shaped traffic. The v1 `/zen` lane uses the 1.x tool names; `/inference` and `/zen/go` use the 2.x names. The environment block names the requested model, the gateway's working directory, the platform, and a UTC date.
|
||||
|
||||
Injection is protocol-aware: Chat system and developer messages are folded into one leading `system` message, Anthropic receives a `system` value (a string, or a leading text block when the caller sent blocks), and Responses receives `instructions`. A body whose system content already contains the marker `You are opencode, an interactive CLI tool` is passed through, so a client that sends the official prompt never gets a second copy. Free models served by a Zen or Go key receive the same shaping even though they still leave through that tier's proxy.
|
||||
|
||||
### Free model availability
|
||||
|
||||
The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short request using its native protocol. It tries the enabled anonymous lane first and then one configured Zen Key. With `warp.enabled`, every probe lane leaves through WARP instead of a proxy; when no exit can be acquired the probe reports `warp_unavailable` and stays inconclusive. A valid completed response on either lane keeps the model enabled; the model is disabled in discovery and routing only when every attempted lane explicitly reports that the model does not exist or has been retired. Authentication errors, rate limits, timeouts, transport errors, 5xx responses, and malformed replies are inconclusive: they do not create a new disable, and are checked again in one hour. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance.
|
||||
|
||||
@@ -240,6 +240,12 @@ Mô hình miễn phí không bao giờ cần key Zen: với `anonymous: true` ch
|
||||
|
||||
`warp.pool_size` (1–8, mặc định `2`) giữ số đầu ra đó ở trạng thái hoạt động và tự thay thế đầu ra bị chặn hoặc hỏng; `warp.stack` chọn `ipv4` (mặc định), `ipv6` hoặc `dual`. `/healthz` trả về khối `warp` và 503 khi WARP bật nhưng không có đầu ra nào hoạt động; `no_healthy_proxies` chỉ chặn readiness khi WARP tắt hoặc có key Go cần proxy. Request chẩn đoán có lấy đầu ra nhưng không bao giờ luân chuyển hay phạt nó. Tắt WARP sẽ khôi phục định tuyến qua proxy cho các làn miễn phí.
|
||||
|
||||
### System prompt chính thức
|
||||
|
||||
Mỗi request mô hình miễn phí đã được định hình đều mang system prompt của chính OpenCode CLI — hướng dẫn gốc, khối `<env>` và danh sách skill tích hợp — vì làn miễn phí kiểm tra request có dạng agent. Làn v1 `/zen` dùng tên công cụ 1.x; `/inference` và `/zen/go` dùng tên 2.x. Khối môi trường nêu mô hình được yêu cầu, thư mục làm việc của gateway, nền tảng và ngày theo UTC.
|
||||
|
||||
Việc chèn phụ thuộc giao thức: các message system và developer của Chat được gộp thành một message `system` duy nhất ở đầu; Anthropic nhận giá trị `system` (chuỗi, hoặc một text block ở đầu khi bên gọi gửi danh sách block); Responses nhận `instructions`. Nếu nội dung system đã chứa dấu hiệu `You are opencode, an interactive CLI tool`, request được giữ nguyên, nên client đã gửi prompt chính thức sẽ không bị chèn lần hai. Mô hình miễn phí phục vụ qua Zen hoặc Go Key cũng được định hình như vậy nhưng vẫn ra ngoài qua proxy của tier đó.
|
||||
|
||||
### Tính khả dụng của mô hình miễn phí
|
||||
|
||||
Gateway dò các mô hình có ID chứa `free` (không phân biệt hoa thường), hoặc có metadata báo chi phí input/output bằng 0 mà không bị ngừng cấp, bằng một request ngắn dùng giao thức gốc của mô hình. Nó thử làn ẩn danh đang bật trước, rồi tới một Zen Key đã cấu hình. Khi bật `warp.enabled`, mọi làn dò đi qua WARP thay vì proxy; nếu không lấy được đầu ra, kết quả là `warp_unavailable` và được coi là không kết luận. Một phản hồi hợp lệ và hoàn tất trên bất kỳ làn nào sẽ giữ mô hình ở trạng thái bật; mô hình chỉ bị tắt trong phát hiện và định tuyến khi mọi làn được thử đều báo rõ ràng rằng mô hình không tồn tại hoặc đã bị thu hồi. Lỗi xác thực, giới hạn tần suất, timeout, lỗi truyền tải, phản hồi 5xx và câu trả lời sai định dạng đều không kết luận: chúng không tạo ra lần tắt mới và sẽ được kiểm tra lại sau một giờ. Lưu lượng dò không làm thay đổi cooldown key/proxy sản xuất hay thống kê request. Nó vẫn đi tới upstream và có thể tiêu tốn hạn mức miễn phí của họ.
|
||||
|
||||
@@ -236,6 +236,12 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
`warp.pool_size`(1–8,默认 `2`)保持相应数量的出口可用,并在出口被封锁或损坏时自动替换;`warp.stack` 可选 `ipv4`(默认)、`ipv6` 或 `dual`。`/healthz` 会返回 `warp` 状态块;启用 WARP 但没有任何活跃出口时返回 503。只有 WARP 关闭或存在 Go Key 需要代理时,`no_healthy_proxies` 才会阻塞就绪。诊断请求会占用出口,但不会轮换或淘汰它。关闭 WARP 后,免费通道恢复使用代理。
|
||||
|
||||
### 官方系统提示词
|
||||
|
||||
每个经过整形的免费模型请求都会携带 OpenCode CLI 自身的系统提示词——基础指令、`<env>` 环境块和内置 skill 列表——因为免费层级会校验请求是否具有 agent 形态。v1 `/zen` 使用 1.x 工具名,`/inference` 与 `/zen/go` 使用 2.x 工具名。环境块包含请求的模型、网关工作目录、平台和 UTC 日期。
|
||||
|
||||
注入按协议处理:Chat 的系统与 developer 消息会合并为一条位于最前的 `system` 消息;Anthropic 写入 `system`(字符串,或调用方提供块列表时在最前插入文本块);Responses 写入 `instructions`。如果系统内容中已包含标记 `You are opencode, an interactive CLI tool`,请求会原样通过,因此已经发送官方提示词的客户端不会被重复注入。通过 Zen 或 Go Key 提供的免费模型也会接受同样的整形,只是仍然从对应 Tier 的代理出网。
|
||||
|
||||
### 免费模型可用性
|
||||
|
||||
只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;启用 `warp.enabled` 时,每条探测通道都改走 WARP 而不是代理,无法取得出口时结果为 `warp_unavailable`,视为不确定。任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
// The free tier accepts only agent-shaped requests, and its abuse checks expect
|
||||
// the system prompt the official CLI sends. These assets are the CLI's own
|
||||
// wording: the v1 text for /zen (OpenCode 1.x tool names) and the v2 text for
|
||||
// /inference and /zen/go (OpenCode 2.x tool names). The v2 file is the v1 file
|
||||
// with the tool names the 2.x CLI uses.
|
||||
//
|
||||
//go:embed opencode_prompt_v1.txt
|
||||
var opencodePromptV1 string
|
||||
|
||||
//go:embed opencode_prompt_v2.txt
|
||||
var opencodePromptV2 string
|
||||
|
||||
// opencodePromptMarker identifies a body that already carries the official CLI
|
||||
// system prompt, so a client that sends it itself is left alone.
|
||||
const opencodePromptMarker = "You are opencode, an interactive CLI tool"
|
||||
|
||||
// opencodeSkills is the built-in skill listing the CLI appends after its
|
||||
// environment block. It is static, so it is part of the injected prompt.
|
||||
const opencodeSkills = `Skills provide specialized instructions and workflows for specific tasks.
|
||||
Use the skill tool to load a skill when a task matches its description.
|
||||
<available_skills>
|
||||
<skill>
|
||||
<name>customize-opencode</name>
|
||||
<description>Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.</description>
|
||||
<location><built-in></location>
|
||||
</skill>
|
||||
</available_skills>`
|
||||
|
||||
var (
|
||||
opencodeEnvOnce sync.Once
|
||||
opencodeWorkDir string
|
||||
)
|
||||
|
||||
// opencodeEnvironment renders the <env> block the CLI puts after its base
|
||||
// prompt. The working directory is resolved once per process; a platform
|
||||
// without one falls back to the official container path.
|
||||
func opencodeEnvironment(model string) string {
|
||||
opencodeEnvOnce.Do(func() {
|
||||
directory := ""
|
||||
if current, err := os.Getwd(); err == nil {
|
||||
directory = filepath.Clean(strings.TrimSpace(current))
|
||||
}
|
||||
if directory == "" || directory == "." {
|
||||
directory = "/workspace"
|
||||
}
|
||||
opencodeWorkDir = directory
|
||||
})
|
||||
apiModel := strings.TrimSpace(strings.TrimPrefix(model, "opencode/"))
|
||||
if apiModel == "" {
|
||||
apiModel = "unknown"
|
||||
}
|
||||
platform := runtime.GOOS
|
||||
if platform == "windows" {
|
||||
platform = "win32"
|
||||
}
|
||||
return strings.Join([]string{
|
||||
"You are powered by the model named " + apiModel + ". The exact model ID is opencode/" + apiModel,
|
||||
"Here is some useful information about the environment you are running in:",
|
||||
"<env>",
|
||||
" Working directory: " + opencodeWorkDir,
|
||||
" Workspace root folder: " + opencodeWorkDir,
|
||||
" Is directory a git repo: yes",
|
||||
" Platform: " + platform,
|
||||
" Today's date: " + time.Now().UTC().Format("Mon Jan 02 2006"),
|
||||
"</env>",
|
||||
}, "\n")
|
||||
}
|
||||
|
||||
// opencodeSystemPrompt assembles the full CLI system prompt for model and the
|
||||
// upstream generation's tool naming.
|
||||
func opencodeSystemPrompt(model string, v1 bool) string {
|
||||
base := opencodePromptV2
|
||||
if v1 {
|
||||
base = opencodePromptV1
|
||||
}
|
||||
return base + opencodeEnvironment(model) + "\n" + opencodeSkills
|
||||
}
|
||||
|
||||
// injectOfficialPrompt prepends the official CLI system prompt to a shaped
|
||||
// free-tier payload. It reports whether the payload changed; a body that
|
||||
// already carries the marker is left untouched, so repeated shaping cannot
|
||||
// duplicate the prompt. System One payloads are not chat bodies and are never
|
||||
// touched.
|
||||
func injectOfficialPrompt(payload map[string]any, protocol wire.Protocol, v1 bool) bool {
|
||||
if payload == nil || protocol == wire.SystemOne {
|
||||
return false
|
||||
}
|
||||
model, _ := payload["model"].(string)
|
||||
prompt := opencodeSystemPrompt(model, v1)
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
return injectChatPrompt(payload, prompt)
|
||||
case wire.Anthropic:
|
||||
return injectAnthropicPrompt(payload, prompt)
|
||||
case wire.Responses:
|
||||
return injectResponsesPrompt(payload, prompt)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// injectChatPrompt folds every system/developer message into the single system
|
||||
// message the 1.x and 2.x CLIs send, then prepends it. Client instructions keep
|
||||
// their order and are separated from the official prompt by a blank line.
|
||||
func injectChatPrompt(payload map[string]any, prompt string) bool {
|
||||
messages, ok := payload["messages"].([]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
kept := make([]any, 0, len(messages)+1)
|
||||
var instructions []string
|
||||
for _, raw := range messages {
|
||||
message, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
kept = append(kept, raw)
|
||||
continue
|
||||
}
|
||||
role, _ := message["role"].(string)
|
||||
if role != "system" && role != "developer" {
|
||||
kept = append(kept, raw)
|
||||
continue
|
||||
}
|
||||
content := message["content"]
|
||||
if carriesOpenCodePrompt(content) {
|
||||
return false
|
||||
}
|
||||
for _, part := range textFragments(content) {
|
||||
if part = strings.TrimSpace(part); part != "" {
|
||||
instructions = append(instructions, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
system := prompt
|
||||
if joined := strings.Join(instructions, "\n"); joined != "" {
|
||||
system += "\n\n" + joined
|
||||
}
|
||||
payload["messages"] = append([]any{map[string]any{"role": "system", "content": system}}, kept...)
|
||||
return true
|
||||
}
|
||||
|
||||
// injectAnthropicPrompt prepends the prompt to the top-level system value,
|
||||
// keeping a caller's string or block list intact after it.
|
||||
func injectAnthropicPrompt(payload map[string]any, prompt string) bool {
|
||||
system, exists := payload["system"]
|
||||
if exists && carriesOpenCodePrompt(system) {
|
||||
return false
|
||||
}
|
||||
if !exists {
|
||||
payload["system"] = prompt
|
||||
return true
|
||||
}
|
||||
switch value := system.(type) {
|
||||
case string:
|
||||
if strings.TrimSpace(value) == "" {
|
||||
payload["system"] = prompt
|
||||
} else {
|
||||
payload["system"] = prompt + "\n\n" + value
|
||||
}
|
||||
case []any:
|
||||
payload["system"] = append([]any{map[string]any{"type": "text", "text": prompt}}, value...)
|
||||
default:
|
||||
payload["system"] = prompt
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// injectResponsesPrompt prepends the prompt to the Responses instructions.
|
||||
func injectResponsesPrompt(payload map[string]any, prompt string) bool {
|
||||
instructions, exists := payload["instructions"]
|
||||
if exists && carriesOpenCodePrompt(instructions) {
|
||||
return false
|
||||
}
|
||||
if text, ok := instructions.(string); exists && ok {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
payload["instructions"] = prompt
|
||||
} else {
|
||||
payload["instructions"] = prompt + "\n\n" + text
|
||||
}
|
||||
return true
|
||||
}
|
||||
payload["instructions"] = prompt
|
||||
return true
|
||||
}
|
||||
|
||||
// textFragments flattens a system or instruction value into its text: a plain
|
||||
// string, a list of content blocks, or a block object carrying text or content.
|
||||
func textFragments(value any) []string {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
if strings.TrimSpace(typed) == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{typed}
|
||||
case []any:
|
||||
var parts []string
|
||||
for _, item := range typed {
|
||||
parts = append(parts, textFragments(item)...)
|
||||
}
|
||||
return parts
|
||||
case map[string]any:
|
||||
if text, ok := typed["text"].(string); ok {
|
||||
return textFragments(text)
|
||||
}
|
||||
if content, ok := typed["content"]; ok {
|
||||
return textFragments(content)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// carriesOpenCodePrompt reports whether any text inside value already contains
|
||||
// the marker.
|
||||
func carriesOpenCodePrompt(value any) bool {
|
||||
for _, part := range textFragments(value) {
|
||||
if strings.Contains(part, opencodePromptMarker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
||||
|
||||
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
||||
|
||||
If the user asks for help or wants to give feedback inform them of the following:
|
||||
- /help: Get help with using opencode
|
||||
- To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues
|
||||
|
||||
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
|
||||
|
||||
# Tone and style
|
||||
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
||||
Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
||||
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
||||
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
||||
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
||||
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
||||
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
||||
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
||||
<example>
|
||||
user: what is 2+2?
|
||||
assistant: 4
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: is 11 a prime number?
|
||||
assistant: Yes
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what command should I run to list files in the current directory?
|
||||
assistant: ls
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what command should I run to watch files in the current directory?
|
||||
assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
||||
npm run dev
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what files are in the directory src/?
|
||||
assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
||||
user: which file contains the implementation of foo?
|
||||
assistant: src/foo.c
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: write tests for new feature
|
||||
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
|
||||
</example>
|
||||
|
||||
# Proactiveness
|
||||
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
||||
1. Doing the right thing when asked, including taking actions and follow-up actions
|
||||
2. Not surprising the user with actions you take without asking
|
||||
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
||||
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
||||
|
||||
# Following conventions
|
||||
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
||||
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
||||
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
||||
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
||||
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
||||
|
||||
# Code style
|
||||
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
||||
|
||||
# Doing tasks
|
||||
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
||||
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
||||
- Implement the solution using all tools available to you
|
||||
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
||||
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
||||
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
||||
|
||||
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
||||
|
||||
# Tool usage policy
|
||||
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
||||
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
||||
|
||||
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
||||
|
||||
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
|
||||
|
||||
# Code References
|
||||
|
||||
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
|
||||
|
||||
<example>
|
||||
user: Where are errors from the client handled?
|
||||
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
|
||||
</example>
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
||||
|
||||
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
||||
|
||||
If the user asks for help or wants to give feedback inform them of the following:
|
||||
- /help: Get help with using opencode
|
||||
- To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues
|
||||
|
||||
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the webfetch tool to gather information to answer the question from opencode docs at https://opencode.ai
|
||||
|
||||
# Tone and style
|
||||
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
||||
Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
||||
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like shell or code comments as means to communicate with the user during the session.
|
||||
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
||||
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
||||
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
||||
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
||||
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
||||
<example>
|
||||
user: what is 2+2?
|
||||
assistant: 4
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: is 11 a prime number?
|
||||
assistant: Yes
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what command should I run to list files in the current directory?
|
||||
assistant: ls
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what command should I run to watch files in the current directory?
|
||||
assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
||||
npm run dev
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what files are in the directory src/?
|
||||
assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
||||
user: which file contains the implementation of foo?
|
||||
assistant: src/foo.c
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: write tests for new feature
|
||||
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
|
||||
</example>
|
||||
|
||||
# Proactiveness
|
||||
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
||||
1. Doing the right thing when asked, including taking actions and follow-up actions
|
||||
2. Not surprising the user with actions you take without asking
|
||||
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
||||
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
||||
|
||||
# Following conventions
|
||||
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
||||
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
|
||||
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
|
||||
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
|
||||
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
|
||||
|
||||
# Code style
|
||||
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
|
||||
|
||||
# Doing tasks
|
||||
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
||||
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
||||
- Implement the solution using all tools available to you
|
||||
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
||||
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with shell if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
||||
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
||||
|
||||
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
||||
|
||||
# Tool usage policy
|
||||
- When doing file search, prefer to use the subagent tool in order to reduce context usage.
|
||||
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
||||
|
||||
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
||||
|
||||
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
|
||||
|
||||
# Code References
|
||||
|
||||
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
|
||||
|
||||
<example>
|
||||
user: Where are errors from the client handled?
|
||||
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
|
||||
</example>
|
||||
|
||||
@@ -673,6 +673,9 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
|
||||
if ensureAnonymousChatUsage(payload, protocol) {
|
||||
changed = true
|
||||
}
|
||||
if injectOfficialPrompt(payload, protocol, v1) {
|
||||
changed = true
|
||||
}
|
||||
var alias string
|
||||
if v1 {
|
||||
var toolChanged bool
|
||||
|
||||
Reference in new issue
Block a user