Skip to content

Commit 8dcd39f

Browse files
committed
real life totally configurabl ai subasians
1 parent 88477b3 commit 8dcd39f

22 files changed

Lines changed: 729 additions & 122 deletions

File tree

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
.DS_Store
22
node_modules
3-
.opencode
43
.sst
54
.env
65
.idea
76
.vscode
87
openapi.json
8+
scratch

bun.lock

Lines changed: 17 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/opencode/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"ai": "catalog:",
3737
"decimal.js": "10.5.0",
3838
"diff": "8.0.2",
39+
"gray-matter": "4.0.3",
3940
"hono": "4.7.10",
4041
"hono-openapi": "0.4.8",
4142
"isomorphic-git": "1.32.1",
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { App } from "../app/app"
2+
import { Config } from "../config/config"
3+
import z from "zod"
4+
import { Provider } from "../provider/provider"
5+
import { generateObject, type ModelMessage } from "ai"
6+
import PROMPT_GENERATE from "./generate.txt"
7+
import { SystemPrompt } from "../session/system"
8+
9+
export namespace Agent {
10+
export const Info = z
11+
.object({
12+
name: z.string(),
13+
model: z
14+
.object({
15+
modelID: z.string(),
16+
providerID: z.string(),
17+
})
18+
.optional(),
19+
description: z.string(),
20+
prompt: z.string().optional(),
21+
tools: z.record(z.boolean()),
22+
})
23+
.openapi({
24+
ref: "Agent",
25+
})
26+
export type Info = z.infer<typeof Info>
27+
const state = App.state("agent", async () => {
28+
const cfg = await Config.get()
29+
const result: Record<string, Info> = {
30+
general: {
31+
name: "general",
32+
description:
33+
"General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
34+
tools: {
35+
todoread: false,
36+
todowrite: false,
37+
},
38+
},
39+
}
40+
for (const [key, value] of Object.entries(cfg.agent ?? {})) {
41+
if (value.disable) continue
42+
let item = result[key]
43+
if (!item)
44+
item = result[key] = {
45+
name: key,
46+
description: "",
47+
tools: {},
48+
}
49+
const model = value.model ?? cfg.model
50+
if (model) item.model = Provider.parseModel(model)
51+
if (value.prompt) item.prompt = value.prompt
52+
if (value.tools)
53+
item.tools = {
54+
...item.tools,
55+
...value.tools,
56+
}
57+
if (value.description) item.description = value.description
58+
}
59+
return result
60+
})
61+
62+
export async function get(agent: string) {
63+
return state().then((x) => x[agent])
64+
}
65+
66+
export async function list() {
67+
return state().then((x) => Object.values(x))
68+
}
69+
70+
export async function generate(input: { description: string }) {
71+
const defaultModel = await Provider.defaultModel()
72+
const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID)
73+
const system = SystemPrompt.header(defaultModel.providerID)
74+
system.push(PROMPT_GENERATE)
75+
const existing = await list()
76+
const result = await generateObject({
77+
temperature: 0.3,
78+
prompt: [
79+
...system.map(
80+
(item): ModelMessage => ({
81+
role: "system",
82+
content: item,
83+
}),
84+
),
85+
{
86+
role: "user",
87+
content: `Create an agent configuration based on this request: \"${input.description}\".\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existing.map((i) => i.name).join(", ")}\n Return ONLY the JSON object, no other text, do not wrap in backticks`,
88+
},
89+
],
90+
model: model.language,
91+
schema: z.object({
92+
identifier: z.string(),
93+
whenToUse: z.string(),
94+
systemPrompt: z.string(),
95+
}),
96+
})
97+
return result.object
98+
}
99+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.
2+
3+
**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.
4+
5+
When a user describes what they want an agent to do, you will:
6+
7+
1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.
8+
9+
2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.
10+
11+
3. **Architect Comprehensive Instructions**: Develop a system prompt that:
12+
13+
- Establishes clear behavioral boundaries and operational parameters
14+
- Provides specific methodologies and best practices for task execution
15+
- Anticipates edge cases and provides guidance for handling them
16+
- Incorporates any specific requirements or preferences mentioned by the user
17+
- Defines output format expectations when relevant
18+
- Aligns with project-specific coding standards and patterns from CLAUDE.md
19+
20+
4. **Optimize for Performance**: Include:
21+
22+
- Decision-making frameworks appropriate to the domain
23+
- Quality control mechanisms and self-verification steps
24+
- Efficient workflow patterns
25+
- Clear escalation or fallback strategies
26+
27+
5. **Create Identifier**: Design a concise, descriptive identifier that:
28+
- Uses lowercase letters, numbers, and hyphens only
29+
- Is typically 2-4 words joined by hyphens
30+
- Clearly indicates the agent's primary function
31+
- Is memorable and easy to type
32+
- Avoids generic terms like "helper" or "assistant"
33+
34+
6 **Example agent descriptions**:
35+
36+
- in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
37+
- examples should be of the form:
38+
- <example>
39+
Context: The user is creating a code-review agent that should be called after a logical chunk of code is written.
40+
user: "Please write a function that checks if a number is prime"
41+
assistant: "Here is the relevant function: "
42+
<function call omitted for brevity only for this example>
43+
<commentary>
44+
Since the user is greeting, use the Task tool to launch the greeting-responder agent to respond with a friendly joke.
45+
</commentary>
46+
assistant: "Now let me use the code-reviewer agent to review the code"
47+
</example>
48+
- <example>
49+
Context: User is creating an agent to respond to the word "hello" with a friendly jok.
50+
user: "Hello"
51+
assistant: "I'm going to use the Task tool to launch the greeting-responder agent to respond with a friendly joke"
52+
<commentary>
53+
Since the user is greeting, use the greeting-responder agent to respond with a friendly joke.
54+
</commentary>
55+
</example>
56+
- If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
57+
- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.
58+
59+
Your output must be a valid JSON object with exactly these fields:
60+
{
61+
"identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'code-reviewer', 'api-docs-writer', 'test-generator')",
62+
"whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
63+
"systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
64+
}
65+
66+
Key principles for your system prompts:
67+
68+
- Be specific rather than generic - avoid vague instructions
69+
- Include concrete examples when they would clarify behavior
70+
- Balance comprehensiveness with clarity - every instruction should add value
71+
- Ensure the agent has enough context to handle variations of the core task
72+
- Make the agent proactive in seeking clarification when needed
73+
- Build in quality assurance and self-correction mechanisms
74+
75+
Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { cmd } from "./cmd"
2+
import * as prompts from "@clack/prompts"
3+
import { UI } from "../ui"
4+
import { Global } from "../../global"
5+
import { Agent } from "../../agent/agent"
6+
import path from "path"
7+
import matter from "gray-matter"
8+
import { App } from "../../app/app"
9+
10+
const AgentCreateCommand = cmd({
11+
command: "create",
12+
describe: "create a new agent",
13+
async handler() {
14+
await App.provide({ cwd: process.cwd() }, async (app) => {
15+
UI.empty()
16+
prompts.intro("Create agent")
17+
18+
let scope: "global" | "project" = "global"
19+
if (app.git) {
20+
const scopeResult = await prompts.select({
21+
message: "Location",
22+
options: [
23+
{
24+
label: "Current project",
25+
value: "project" as const,
26+
hint: app.path.root,
27+
},
28+
{
29+
label: "Global",
30+
value: "global" as const,
31+
hint: Global.Path.config,
32+
},
33+
],
34+
})
35+
if (prompts.isCancel(scopeResult)) throw new UI.CancelledError()
36+
scope = scopeResult
37+
}
38+
39+
const query = await prompts.text({
40+
message: "Description",
41+
placeholder: "What should this agent do?",
42+
validate: (x) => (x.length > 0 ? undefined : "Required"),
43+
})
44+
if (prompts.isCancel(query)) throw new UI.CancelledError()
45+
46+
const spinner = prompts.spinner()
47+
48+
spinner.start("Generating agent configuration...")
49+
const generated = await Agent.generate({ description: query })
50+
spinner.stop(`Agent ${generated.identifier} generated`)
51+
52+
const availableTools = [
53+
"bash",
54+
"read",
55+
"write",
56+
"edit",
57+
"list",
58+
"glob",
59+
"grep",
60+
"webfetch",
61+
"task",
62+
"todowrite",
63+
"todoread",
64+
]
65+
66+
const selectedTools = await prompts.multiselect({
67+
message: "Select tools to enable",
68+
options: availableTools.map((tool) => ({
69+
label: tool,
70+
value: tool,
71+
})),
72+
initialValues: availableTools,
73+
})
74+
if (prompts.isCancel(selectedTools)) throw new UI.CancelledError()
75+
76+
const tools: Record<string, boolean> = {}
77+
for (const tool of availableTools) {
78+
if (!selectedTools.includes(tool)) {
79+
tools[tool] = false
80+
}
81+
}
82+
83+
const frontmatter: any = {
84+
description: generated.whenToUse,
85+
}
86+
if (Object.keys(tools).length > 0) {
87+
frontmatter.tools = tools
88+
}
89+
90+
const content = matter.stringify(generated.systemPrompt, frontmatter)
91+
const filePath = path.join(
92+
scope === "global" ? Global.Path.config : path.join(app.path.root, ".opencode"),
93+
`agent`,
94+
`${generated.identifier}.md`,
95+
)
96+
97+
await Bun.write(filePath, content)
98+
99+
prompts.log.success(`Agent created: ${filePath}`)
100+
prompts.outro("Done")
101+
})
102+
},
103+
})
104+
105+
export const AgentCommand = cmd({
106+
command: "agent",
107+
describe: "manage agents",
108+
builder: (yargs) => yargs.command(AgentCreateCommand).demandCommand(),
109+
async handler() {},
110+
})

0 commit comments

Comments
 (0)