@eduardo191labs/opencode-actions 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +311 -2
- package/action.yml +251 -0
- package/dist/actions.d.ts +351 -0
- package/dist/actions.js +561 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +180 -0
- package/dist/commands.d.ts +23 -0
- package/dist/commands.js +120 -0
- package/dist/compile.d.ts +49 -0
- package/dist/compile.js +217 -0
- package/dist/config.d.ts +306 -0
- package/dist/config.js +133 -0
- package/dist/detect.d.ts +55 -0
- package/dist/detect.js +215 -0
- package/dist/format.d.ts +79 -0
- package/dist/format.js +168 -0
- package/dist/git.d.ts +38 -0
- package/dist/git.js +125 -0
- package/dist/github.d.ts +213 -0
- package/dist/github.js +227 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/install.d.ts +2 -0
- package/dist/install.js +299 -0
- package/dist/loader.d.ts +54 -0
- package/dist/loader.js +306 -0
- package/dist/mcp-server.d.ts +16 -0
- package/dist/mcp-server.js +402 -0
- package/dist/prompts.d.ts +70 -0
- package/dist/prompts.js +260 -0
- package/dist/runner.d.ts +108 -0
- package/dist/runner.js +318 -0
- package/dist/summary.d.ts +2 -0
- package/dist/summary.js +99 -0
- package/package.json +57 -4
- package/schemas/opencode-actions.schema.json +527 -0
package/dist/prompts.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { bot } from "./config.js";
|
|
2
|
+
/** Shared rules every bot prompt inherits. */
|
|
3
|
+
export function baseSystem(config) {
|
|
4
|
+
const name = bot(config).name ?? "opencode";
|
|
5
|
+
const trailer = bot(config).commit_trailer;
|
|
6
|
+
return `You are ${name}, an autonomous engineering agent running inside GitHub Actions on behalf of the repository maintainers.
|
|
7
|
+
|
|
8
|
+
Operating rules:
|
|
9
|
+
- You work inside a checked-out git repository. Read real files; never guess.
|
|
10
|
+
- Every claim about the code must come from a file you actually read in this run.
|
|
11
|
+
- Never invent paths, symbols, line numbers or test names. If something is unknown, say so.
|
|
12
|
+
- Keep commits small and focused. Conventional Commits: \`type(scope): summary\`.
|
|
13
|
+
- Do not modify files unrelated to the task.
|
|
14
|
+
- Never print secrets or the contents of token-like environment variables.
|
|
15
|
+
- State assumptions instead of asking questions.
|
|
16
|
+
- If a task is impossible with the available permissions, explain why and stop.
|
|
17
|
+
${trailer ? `- End commit messages with this trailer: ${trailer}` : ""}
|
|
18
|
+
- Write your machine-readable answer to the file named in $OPENCODE_RESULT_FILE as JSON.
|
|
19
|
+
- Your plain-text answer is shown to humans; the JSON drives what the bot actually posts.
|
|
20
|
+
`;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Review contract. Findings are structured JSON so the bot can post valid
|
|
24
|
+
* inline comments (GitHub rejects comments on lines outside the diff).
|
|
25
|
+
*/
|
|
26
|
+
export const REVIEW_SCHEMA = `{
|
|
27
|
+
"summary": "string — 2-5 sentences on what the change does and whether it is safe",
|
|
28
|
+
"verdict": "APPROVE | COMMENT | REQUEST_CHANGES",
|
|
29
|
+
"findings": [
|
|
30
|
+
{
|
|
31
|
+
"path": "string — file path exactly as in the diff",
|
|
32
|
+
"line": "number — a line that exists on the RIGHT side of the diff",
|
|
33
|
+
"severity": "critical | high | medium | low | info",
|
|
34
|
+
"title": "string — one short sentence",
|
|
35
|
+
"body": "string — the problem and why it matters",
|
|
36
|
+
"suggestion": "string | null — exact replacement for the referenced lines, or null"
|
|
37
|
+
}
|
|
38
|
+
],
|
|
39
|
+
"strengths": ["string — what the change does well"]
|
|
40
|
+
}`;
|
|
41
|
+
export function reviewPrompt(input) {
|
|
42
|
+
const review = bot(input.config).review ?? {};
|
|
43
|
+
const include = review.include?.length ? `Focus only on: ${review.include.join(", ")}.` : "Review every changed file.";
|
|
44
|
+
const exclude = review.exclude?.length ? `Skip: ${review.exclude.join(", ")}.` : "";
|
|
45
|
+
const max = review.max_comments ?? 25;
|
|
46
|
+
const suggestions = review.suggestions === false
|
|
47
|
+
? "Do not write ```suggestion blocks."
|
|
48
|
+
: "Use ```suggestion blocks only when you are certain of the exact replacement.";
|
|
49
|
+
return `${baseSystem(input.config)}
|
|
50
|
+
# Task: code review
|
|
51
|
+
|
|
52
|
+
Repository: ${input.repo}
|
|
53
|
+
Pull request: #${input.prNumber} — ${input.title}
|
|
54
|
+
Author: ${input.author}
|
|
55
|
+
Base → head: ${input.base} → ${input.head}
|
|
56
|
+
${input.facts ? `\nRepository: ${input.facts}\n` : ""}
|
|
57
|
+
${include} ${exclude}
|
|
58
|
+
|
|
59
|
+
## Method
|
|
60
|
+
|
|
61
|
+
1. Run \`gh pr diff ${input.prNumber}\` or \`git diff ${input.base}...${input.head}\` for the full change.
|
|
62
|
+
2. For each changed file that matters, open the file and read the surrounding code. A bug is only
|
|
63
|
+
a bug if the surrounding code confirms it. Never review a diff in isolation.
|
|
64
|
+
3. Check, in order: correctness, security, resource leaks, concurrency, error handling, tests,
|
|
65
|
+
and style only where the repository has an explicit convention you can point to.
|
|
66
|
+
4. Do NOT report: formatter-handled formatting, personal preference, "consider adding a comment",
|
|
67
|
+
or hypothetical problems you cannot tie to one line.
|
|
68
|
+
5. Maximum ${max} findings, ranked by severity.
|
|
69
|
+
|
|
70
|
+
${suggestions}
|
|
71
|
+
|
|
72
|
+
## Output
|
|
73
|
+
|
|
74
|
+
Write JSON to \`$OPENCODE_RESULT_FILE\`:
|
|
75
|
+
|
|
76
|
+
\`\`\`json
|
|
77
|
+
${REVIEW_SCHEMA}
|
|
78
|
+
\`\`\`
|
|
79
|
+
|
|
80
|
+
- \`line\` must exist on the RIGHT side of the diff (an added or context line).
|
|
81
|
+
- \`body\` explains the defect; \`suggestion\` carries the fix.
|
|
82
|
+
- If the change is good: \`"verdict": "APPROVE"\` with an empty findings array.
|
|
83
|
+
${input.extraInstructions ? `\n## Repository review instructions\n\n${input.extraInstructions}\n` : ""}
|
|
84
|
+
## Files in this change
|
|
85
|
+
|
|
86
|
+
${input.filesSummary}
|
|
87
|
+
|
|
88
|
+
## Diff digest
|
|
89
|
+
|
|
90
|
+
\`\`\`diff
|
|
91
|
+
${input.diffDigest}
|
|
92
|
+
\`\`\`
|
|
93
|
+
`;
|
|
94
|
+
}
|
|
95
|
+
export const ISSUE_SCHEMA = `{
|
|
96
|
+
"summary": "string — what the issue is really asking for",
|
|
97
|
+
"severity": "critical | high | medium | low",
|
|
98
|
+
"labels": ["string — existing labels that apply"],
|
|
99
|
+
"answer": "string — markdown to post on the issue; empty if this is a bug to fix",
|
|
100
|
+
"plan": ["string — ordered implementation steps"],
|
|
101
|
+
"files": ["string — files that would need to change"],
|
|
102
|
+
"reproducible": "yes | no | unknown",
|
|
103
|
+
"needs_info": "string | null — the single question for the reporter, or null"
|
|
104
|
+
}`;
|
|
105
|
+
export function issuePrompt(input) {
|
|
106
|
+
const goal = input.mode === "implement"
|
|
107
|
+
? "Implement the fix in the repository, add a test, and commit it."
|
|
108
|
+
: input.mode === "answer"
|
|
109
|
+
? "Answer the reporter using evidence from the codebase."
|
|
110
|
+
: "Triage: classify, decide whether it is reproducible, outline a plan.";
|
|
111
|
+
return `${baseSystem(input.config)}
|
|
112
|
+
# Task: ${input.mode} issue
|
|
113
|
+
|
|
114
|
+
Repository: ${input.repo}
|
|
115
|
+
Issue: #${input.number} — ${input.title}
|
|
116
|
+
Labels: ${input.labels.join(", ") || "none"}
|
|
117
|
+
${input.facts ? `Repository: ${input.facts}` : ""}
|
|
118
|
+
|
|
119
|
+
## Issue body
|
|
120
|
+
|
|
121
|
+
${input.body || "(empty)"}
|
|
122
|
+
|
|
123
|
+
## Discussion
|
|
124
|
+
|
|
125
|
+
${input.comments || "(no comments)"}
|
|
126
|
+
|
|
127
|
+
## Goal
|
|
128
|
+
|
|
129
|
+
${goal}
|
|
130
|
+
|
|
131
|
+
## Method
|
|
132
|
+
|
|
133
|
+
1. Identify the component the issue is about. Search the code; never assume.
|
|
134
|
+
2. If it reports a bug, trace the code path and say whether the reported behaviour is possible.
|
|
135
|
+
3. ${input.mode === "implement" ? "Make the smallest correct change and add a test that fails before it. Run the project's tests." : "If more information is needed, ask exactly one specific question."}
|
|
136
|
+
|
|
137
|
+
## Output
|
|
138
|
+
|
|
139
|
+
Write JSON to \`$OPENCODE_RESULT_FILE\`:
|
|
140
|
+
|
|
141
|
+
\`\`\`json
|
|
142
|
+
${ISSUE_SCHEMA}
|
|
143
|
+
\`\`\`
|
|
144
|
+
${input.mode === "implement" ? "\nYou must also make the code change and commit it with a Conventional Commit message." : ""}
|
|
145
|
+
`;
|
|
146
|
+
}
|
|
147
|
+
export const AUTOFIX_SCHEMA = `{
|
|
148
|
+
"diagnosis": "string — the root cause of the failure",
|
|
149
|
+
"fixable": "boolean",
|
|
150
|
+
"changes": ["string — files you changed"],
|
|
151
|
+
"commit_message": "string — Conventional Commit message",
|
|
152
|
+
"summary": "string — one paragraph for the PR body",
|
|
153
|
+
"explanation": "string — what you changed and why it fixes the failure"
|
|
154
|
+
}`;
|
|
155
|
+
export function autofixPrompt(input) {
|
|
156
|
+
const autofix = bot(input.config).autofix ?? {};
|
|
157
|
+
const maxFiles = autofix.max_files ?? 10;
|
|
158
|
+
const editWorkflows = bot(input.config).permissions?.edit_workflows === "allow";
|
|
159
|
+
return `${baseSystem(input.config)}
|
|
160
|
+
# Task: fix a failing GitHub Actions workflow
|
|
161
|
+
|
|
162
|
+
Repository: ${input.repo}
|
|
163
|
+
Workflow: ${input.workflow}
|
|
164
|
+
Branch: ${input.branch} @ ${input.sha}
|
|
165
|
+
Run: ${input.runUrl}
|
|
166
|
+
|
|
167
|
+
## Failed jobs
|
|
168
|
+
|
|
169
|
+
${input.failedJobs}
|
|
170
|
+
|
|
171
|
+
## Log excerpt (tail of the failing steps)
|
|
172
|
+
|
|
173
|
+
\`\`\`text
|
|
174
|
+
${input.logExcerpt}
|
|
175
|
+
\`\`\`
|
|
176
|
+
|
|
177
|
+
${input.workflowFile ? `## Workflow file\n\n\`\`\`yaml\n${input.workflowFile}\n\`\`\`` : ""}
|
|
178
|
+
|
|
179
|
+
## Rules
|
|
180
|
+
|
|
181
|
+
- Diagnose before editing. The failure may be in the workflow, the lockfile, a dependency
|
|
182
|
+
bump, or the code the workflow tests.
|
|
183
|
+
- Change at most ${maxFiles} files.
|
|
184
|
+
- ${editWorkflows ? "You may edit .github/workflows/ if the workflow itself is wrong." : "You must NOT edit .github/workflows/. If the workflow is wrong, set \"fixable\": false and explain the required change."}
|
|
185
|
+
- Never weaken a check to make it pass: no \`continue-on-error\` to hide failures, no deleted or
|
|
186
|
+
skipped tests, no loosened assertions.
|
|
187
|
+
- Prefer the smallest change that makes the failure impossible.
|
|
188
|
+
|
|
189
|
+
## Output
|
|
190
|
+
|
|
191
|
+
Write JSON to \`$OPENCODE_RESULT_FILE\`:
|
|
192
|
+
|
|
193
|
+
\`\`\`json
|
|
194
|
+
${AUTOFIX_SCHEMA}
|
|
195
|
+
\`\`\`
|
|
196
|
+
|
|
197
|
+
Then commit your changes if \`fixable\` is true.
|
|
198
|
+
`;
|
|
199
|
+
}
|
|
200
|
+
export function commandPrompt(input) {
|
|
201
|
+
return `${baseSystem(input.config)}
|
|
202
|
+
# Task: respond to a maintainer command
|
|
203
|
+
|
|
204
|
+
Repository: ${input.repo}
|
|
205
|
+
Target: ${input.target}
|
|
206
|
+
Requested by: @${input.actor}
|
|
207
|
+
Command: \`${input.command} ${input.args.join(" ")}\`
|
|
208
|
+
|
|
209
|
+
## What the maintainer wrote
|
|
210
|
+
|
|
211
|
+
${input.body}
|
|
212
|
+
|
|
213
|
+
## Repository context
|
|
214
|
+
|
|
215
|
+
${input.context}
|
|
216
|
+
|
|
217
|
+
## Goal
|
|
218
|
+
|
|
219
|
+
Carry out \`${input.command}\` precisely as asked. If it is a question, answer with evidence from
|
|
220
|
+
the code. If it is a code change, make it and commit it.
|
|
221
|
+
|
|
222
|
+
Keep the final answer short and concrete. Do not restate the request.`;
|
|
223
|
+
}
|
|
224
|
+
export function describePrompt(input) {
|
|
225
|
+
const sections = bot(input.config).describe?.sections ?? ["What changed", "Why", "How to test", "Risk"];
|
|
226
|
+
return `${baseSystem(input.config)}
|
|
227
|
+
# Task: rewrite the pull request description
|
|
228
|
+
|
|
229
|
+
Repository: ${input.repo}
|
|
230
|
+
Pull request: #${input.prNumber} — ${input.title}
|
|
231
|
+
Diff: \`git diff ${input.base}...${input.head}\`
|
|
232
|
+
|
|
233
|
+
Current description:
|
|
234
|
+
|
|
235
|
+
${input.currentBody || "(empty)"}
|
|
236
|
+
|
|
237
|
+
Write a description for a reviewer who has not seen the commit history. Use these sections,
|
|
238
|
+
omitting any that do not apply:
|
|
239
|
+
|
|
240
|
+
${sections.map((section) => `## ${section}`).join("\n")}
|
|
241
|
+
|
|
242
|
+
Be specific: name the functions, files and behaviours that changed. Do not pad.
|
|
243
|
+
Return only the markdown body.`;
|
|
244
|
+
}
|
|
245
|
+
/** A short reply when the agent was asked something conversational. */
|
|
246
|
+
export function replyPrompt(input) {
|
|
247
|
+
return `${baseSystem(input.config)}
|
|
248
|
+
# Task: answer a question
|
|
249
|
+
|
|
250
|
+
## Question
|
|
251
|
+
|
|
252
|
+
${input.question}
|
|
253
|
+
|
|
254
|
+
## Context
|
|
255
|
+
|
|
256
|
+
${input.context}
|
|
257
|
+
|
|
258
|
+
Answer directly. Cite files as \`path:line\`. If the answer requires a code change, say so
|
|
259
|
+
explicitly instead of making it.`;
|
|
260
|
+
}
|
package/dist/runner.d.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
export interface RunOptions {
|
|
2
|
+
/** Prompt sent to the agent. */
|
|
3
|
+
message: string;
|
|
4
|
+
/** Working directory. */
|
|
5
|
+
cwd: string;
|
|
6
|
+
/** OpenCode config object, serialized into OPENCODE_CONFIG_CONTENT. */
|
|
7
|
+
config?: Record<string, unknown>;
|
|
8
|
+
/** Model id, "provider/model#variant". */
|
|
9
|
+
model?: string;
|
|
10
|
+
/** Agent name (build, plan, reviewer...). */
|
|
11
|
+
agent?: string;
|
|
12
|
+
/** Approve permissions that are not explicitly denied. */
|
|
13
|
+
auto?: boolean;
|
|
14
|
+
/** Files attached to the message. */
|
|
15
|
+
files?: string[];
|
|
16
|
+
/** Environment additions (secrets expanded by the caller). */
|
|
17
|
+
env?: Record<string, string>;
|
|
18
|
+
/** Stream the transcript to the log. */
|
|
19
|
+
live?: boolean;
|
|
20
|
+
/** Session id to continue. */
|
|
21
|
+
session?: string;
|
|
22
|
+
/** Abort signal. */
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
/** Executable (defaults to `opencode`). */
|
|
25
|
+
executable?: string;
|
|
26
|
+
/** Extra CLI arguments appended after `run`. */
|
|
27
|
+
extraArgs?: string[];
|
|
28
|
+
}
|
|
29
|
+
export interface RunResult {
|
|
30
|
+
ok: boolean;
|
|
31
|
+
exitCode: number;
|
|
32
|
+
/** Final assistant text (concatenated). */
|
|
33
|
+
text: string;
|
|
34
|
+
/** Every text chunk in order. */
|
|
35
|
+
chunks: string[];
|
|
36
|
+
/** Tool calls in order. */
|
|
37
|
+
tools: {
|
|
38
|
+
name: string;
|
|
39
|
+
input: unknown;
|
|
40
|
+
status: "completed" | "error";
|
|
41
|
+
output?: string;
|
|
42
|
+
error?: string;
|
|
43
|
+
}[];
|
|
44
|
+
cost: number;
|
|
45
|
+
tokens: {
|
|
46
|
+
input?: number;
|
|
47
|
+
output?: number;
|
|
48
|
+
reasoning?: number;
|
|
49
|
+
};
|
|
50
|
+
sessionID?: string;
|
|
51
|
+
error?: string;
|
|
52
|
+
durationMs: number;
|
|
53
|
+
/** Raw NDJSON lines, kept for debugging. */
|
|
54
|
+
events: unknown[];
|
|
55
|
+
/** Parsed JSON the agent wrote to $OPENCODE_RESULT_FILE. */
|
|
56
|
+
resultJson?: unknown;
|
|
57
|
+
}
|
|
58
|
+
export declare const ANSI: {
|
|
59
|
+
reset: string;
|
|
60
|
+
dim: string;
|
|
61
|
+
bold: string;
|
|
62
|
+
cyan: string;
|
|
63
|
+
green: string;
|
|
64
|
+
yellow: string;
|
|
65
|
+
red: string;
|
|
66
|
+
magenta: string;
|
|
67
|
+
blue: string;
|
|
68
|
+
};
|
|
69
|
+
export type RenderMode = "github" | "plain" | "none";
|
|
70
|
+
export interface Renderer {
|
|
71
|
+
onEvent(event: Record<string, any>): void;
|
|
72
|
+
toolLine(icon: string, title: string, detail?: string): void;
|
|
73
|
+
note(text: string): void;
|
|
74
|
+
banner(lines: string[]): void;
|
|
75
|
+
summary(info: {
|
|
76
|
+
model?: string;
|
|
77
|
+
cost: number;
|
|
78
|
+
tokens: Record<string, number>;
|
|
79
|
+
durationMs: number;
|
|
80
|
+
tools: number;
|
|
81
|
+
}): void;
|
|
82
|
+
text?: (chunk: string) => void;
|
|
83
|
+
}
|
|
84
|
+
export declare function createRenderer(mode?: RenderMode, out?: NodeJS.WritableStream): Renderer;
|
|
85
|
+
/** Map an OpenCode tool name to a compact TUI-style line. */
|
|
86
|
+
export declare function describeTool(name: string, input: Record<string, unknown>): {
|
|
87
|
+
icon: string;
|
|
88
|
+
title: string;
|
|
89
|
+
detail?: string;
|
|
90
|
+
};
|
|
91
|
+
export declare function runOpencode(options: RunOptions): Promise<RunResult>;
|
|
92
|
+
/** Write hidden instruction files the agent should read, without polluting the diff. */
|
|
93
|
+
export declare function stageInstructions(cwd: string, files: Record<string, string>): Promise<string[]>;
|
|
94
|
+
export interface AgentArtifacts {
|
|
95
|
+
/** Machine-readable result the agent must write. */
|
|
96
|
+
resultPath: string;
|
|
97
|
+
/** Human-readable transcript for the PR comment. */
|
|
98
|
+
transcriptPath: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Give the agent a scratch directory and a strict output contract: it must
|
|
102
|
+
* write JSON to `resultPath`. This is how the bot turns free-form agent work
|
|
103
|
+
* into structured review comments, issue replies and commit messages.
|
|
104
|
+
*/
|
|
105
|
+
export declare function prepareArtifacts(): Promise<AgentArtifacts>;
|
|
106
|
+
export declare function readResult(path: string): Promise<Record<string, any> | null>;
|
|
107
|
+
export declare function writeResult(path: string, value: unknown): Promise<void>;
|
|
108
|
+
export declare function appendLog(path: string, line: string): Promise<void>;
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { mkdir, writeFile, readFile, appendFile } from "node:fs/promises";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
// ------------------------------------------------------------------ rendering
|
|
7
|
+
export const ANSI = {
|
|
8
|
+
reset: "\x1b[0m",
|
|
9
|
+
dim: "\x1b[90m",
|
|
10
|
+
bold: "\x1b[1m",
|
|
11
|
+
cyan: "\x1b[36m",
|
|
12
|
+
green: "\x1b[32m",
|
|
13
|
+
yellow: "\x1b[33m",
|
|
14
|
+
red: "\x1b[31m",
|
|
15
|
+
magenta: "\x1b[35m",
|
|
16
|
+
blue: "\x1b[34m",
|
|
17
|
+
};
|
|
18
|
+
const useColor = process.env.NO_COLOR === undefined && process.env.TERM !== "dumb";
|
|
19
|
+
const c = (code, text) => (useColor ? `${code}${text}${ANSI.reset}` : text);
|
|
20
|
+
export function createRenderer(mode = "github", out = process.stdout) {
|
|
21
|
+
const write = (line) => {
|
|
22
|
+
if (mode === "none")
|
|
23
|
+
return;
|
|
24
|
+
out.write(line + "\n");
|
|
25
|
+
};
|
|
26
|
+
if (mode === "github") {
|
|
27
|
+
// GitHub Actions folds long output; each step gets a ::group:: so the run log reads like a TUI.
|
|
28
|
+
write("::group::opencode agent");
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
onEvent() { },
|
|
32
|
+
banner(lines) {
|
|
33
|
+
for (const line of lines)
|
|
34
|
+
write(c(ANSI.cyan, line));
|
|
35
|
+
},
|
|
36
|
+
toolLine(icon, title, detail) {
|
|
37
|
+
const suffix = detail ? c(ANSI.dim, ` (${detail})`) : "";
|
|
38
|
+
write(`${c(ANSI.magenta, icon)} ${c(ANSI.bold, title)}${suffix}`);
|
|
39
|
+
},
|
|
40
|
+
note(text) {
|
|
41
|
+
write(c(ANSI.dim, text));
|
|
42
|
+
},
|
|
43
|
+
summary({ model, cost, tokens, durationMs, tools }) {
|
|
44
|
+
const parts = [
|
|
45
|
+
model ? `model ${model}` : null,
|
|
46
|
+
`$${cost.toFixed(4)}`,
|
|
47
|
+
tokens.input !== undefined ? `${fmt(tokens.input)} in / ${fmt(tokens.output ?? 0)} out` : null,
|
|
48
|
+
`${tools} tool${tools === 1 ? "" : "s"}`,
|
|
49
|
+
`${(durationMs / 1000).toFixed(1)}s`,
|
|
50
|
+
].filter(Boolean);
|
|
51
|
+
write("");
|
|
52
|
+
write(c(ANSI.green, "✓ ") + c(ANSI.dim, parts.join(" · ")));
|
|
53
|
+
if (mode === "github")
|
|
54
|
+
write("::endgroup::");
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function fmt(value) {
|
|
59
|
+
if (value >= 1_000_000)
|
|
60
|
+
return `${(value / 1_000_000).toFixed(1)}M`;
|
|
61
|
+
if (value >= 1_000)
|
|
62
|
+
return `${(value / 1_000).toFixed(1)}k`;
|
|
63
|
+
return String(value);
|
|
64
|
+
}
|
|
65
|
+
/** Map an OpenCode tool name to a compact TUI-style line. */
|
|
66
|
+
export function describeTool(name, input) {
|
|
67
|
+
const pick = (...keys) => {
|
|
68
|
+
for (const key of keys) {
|
|
69
|
+
const value = input[key];
|
|
70
|
+
if (typeof value === "string" && value.trim())
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
};
|
|
75
|
+
switch (name) {
|
|
76
|
+
case "bash":
|
|
77
|
+
case "shell":
|
|
78
|
+
return { icon: "⌘", title: "Run", detail: truncate(pick("command", "cmd") ?? "", 140) };
|
|
79
|
+
case "read":
|
|
80
|
+
case "view":
|
|
81
|
+
return { icon: "→", title: "Read", detail: truncate(pick("filePath", "path", "file") ?? "", 120) };
|
|
82
|
+
case "write":
|
|
83
|
+
return { icon: "✎", title: "Write", detail: truncate(pick("filePath", "path", "file") ?? "", 120) };
|
|
84
|
+
case "edit":
|
|
85
|
+
case "patch":
|
|
86
|
+
return { icon: "✎", title: "Edit", detail: truncate(pick("filePath", "path", "file") ?? "", 120) };
|
|
87
|
+
case "glob":
|
|
88
|
+
return { icon: "✱", title: "Glob", detail: truncate(pick("pattern") ?? "", 120) };
|
|
89
|
+
case "grep":
|
|
90
|
+
return { icon: "✱", title: "Grep", detail: truncate(pick("pattern") ?? "", 120) };
|
|
91
|
+
case "list":
|
|
92
|
+
return { icon: "≡", title: "List", detail: truncate(pick("path") ?? ".", 120) };
|
|
93
|
+
case "webfetch":
|
|
94
|
+
case "fetch":
|
|
95
|
+
return { icon: "↗", title: "Fetch", detail: truncate(pick("url") ?? "", 140) };
|
|
96
|
+
case "websearch":
|
|
97
|
+
case "search":
|
|
98
|
+
return { icon: "↗", title: "Search", detail: truncate(pick("query") ?? "", 140) };
|
|
99
|
+
case "task":
|
|
100
|
+
case "agent":
|
|
101
|
+
return { icon: "⚙", title: "Agent", detail: truncate(pick("description", "prompt") ?? "", 140) };
|
|
102
|
+
case "todowrite":
|
|
103
|
+
case "todoread":
|
|
104
|
+
return { icon: "▸", title: "Todo" };
|
|
105
|
+
default:
|
|
106
|
+
return {
|
|
107
|
+
icon: "●",
|
|
108
|
+
title: name,
|
|
109
|
+
detail: Object.keys(input).length ? truncate(JSON.stringify(input), 120) : undefined,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function truncate(text, max) {
|
|
114
|
+
const single = text.replace(/\s+/g, " ").trim();
|
|
115
|
+
return single.length > max ? single.slice(0, max - 1) + "…" : single;
|
|
116
|
+
}
|
|
117
|
+
// --------------------------------------------------------------------- runner
|
|
118
|
+
export async function runOpencode(options) {
|
|
119
|
+
const started = Date.now();
|
|
120
|
+
const env = { ...process.env, ...(options.env ?? {}) };
|
|
121
|
+
// Keep the run quiet, reproducible and offline-unfriendly paths out of the way.
|
|
122
|
+
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(options.config ?? {});
|
|
123
|
+
env.OPENCODE_CLI_SILENT = env.OPENCODE_CLI_SILENT ?? "1";
|
|
124
|
+
env.GIT_TERMINAL_PROMPT = "0";
|
|
125
|
+
env.CI = env.CI ?? "true";
|
|
126
|
+
const args = ["run", "--format", "json"];
|
|
127
|
+
if (options.model)
|
|
128
|
+
args.push("--model", options.model);
|
|
129
|
+
if (options.agent)
|
|
130
|
+
args.push("--agent", options.agent);
|
|
131
|
+
if (options.auto)
|
|
132
|
+
args.push("--auto");
|
|
133
|
+
if (options.session)
|
|
134
|
+
args.push("--session", options.session);
|
|
135
|
+
for (const file of options.files ?? [])
|
|
136
|
+
args.push("--file", file);
|
|
137
|
+
args.push("--", options.message);
|
|
138
|
+
args.push(...(options.extraArgs ?? []));
|
|
139
|
+
const executable = options.executable ?? env.OPENCODE_BIN ?? "opencode";
|
|
140
|
+
const renderer = options.live ? createRenderer(env.OPENCODE_LOG_STYLE ?? "github") : null;
|
|
141
|
+
const result = {
|
|
142
|
+
ok: false,
|
|
143
|
+
exitCode: -1,
|
|
144
|
+
text: "",
|
|
145
|
+
chunks: [],
|
|
146
|
+
tools: [],
|
|
147
|
+
cost: 0,
|
|
148
|
+
tokens: {},
|
|
149
|
+
durationMs: 0,
|
|
150
|
+
events: [],
|
|
151
|
+
};
|
|
152
|
+
return await new Promise((resolve) => {
|
|
153
|
+
const child = spawn(executable, args, {
|
|
154
|
+
cwd: options.cwd,
|
|
155
|
+
env,
|
|
156
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
157
|
+
signal: options.signal,
|
|
158
|
+
});
|
|
159
|
+
let buffer = "";
|
|
160
|
+
const handle = (event) => {
|
|
161
|
+
result.events.push(event);
|
|
162
|
+
if (event.sessionID)
|
|
163
|
+
result.sessionID = event.sessionID;
|
|
164
|
+
const part = event.part;
|
|
165
|
+
switch (event.type) {
|
|
166
|
+
case "step_start": {
|
|
167
|
+
const model = part?.model?.id ?? event.model?.id;
|
|
168
|
+
renderer?.note(`> ${part?.agent ?? options.agent ?? "build"}${model ? ` · ${model}` : ""}`);
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
case "text": {
|
|
172
|
+
const chunk = part?.text ?? "";
|
|
173
|
+
if (chunk) {
|
|
174
|
+
result.text += chunk;
|
|
175
|
+
result.chunks.push(chunk);
|
|
176
|
+
}
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
case "reasoning": {
|
|
180
|
+
// Reasoning stays out of the final answer; the live log keeps it dim.
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
case "tool_use": {
|
|
184
|
+
const name = part?.tool ?? "tool";
|
|
185
|
+
const state = part?.state ?? {};
|
|
186
|
+
const input = (state.input ?? {});
|
|
187
|
+
const entry = {
|
|
188
|
+
name,
|
|
189
|
+
input,
|
|
190
|
+
status: (state.status === "error" ? "error" : "completed"),
|
|
191
|
+
output: typeof state.output === "string" ? state.output : undefined,
|
|
192
|
+
error: typeof state.error === "string" ? state.error : undefined,
|
|
193
|
+
};
|
|
194
|
+
result.tools.push(entry);
|
|
195
|
+
if (renderer) {
|
|
196
|
+
const view = describeTool(name, input);
|
|
197
|
+
renderer.toolLine(view.icon, view.title, view.detail);
|
|
198
|
+
if (entry.status === "error" && entry.error)
|
|
199
|
+
renderer.note(` ${c(ANSI.red, entry.error.split("\n")[0])}`);
|
|
200
|
+
}
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
case "step_finish": {
|
|
204
|
+
result.cost += Number(part?.cost ?? 0);
|
|
205
|
+
const tokens = part?.tokens ?? {};
|
|
206
|
+
result.tokens.input = (result.tokens.input ?? 0) + Number(tokens.input ?? 0);
|
|
207
|
+
result.tokens.output = (result.tokens.output ?? 0) + Number(tokens.output ?? 0);
|
|
208
|
+
result.tokens.reasoning = (result.tokens.reasoning ?? 0) + Number(tokens.reasoning ?? 0);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
case "retry": {
|
|
212
|
+
renderer?.note(c(ANSI.yellow, `! retrying (attempt ${event.attempt}): ${event.error?.message ?? ""}`));
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
case "error": {
|
|
216
|
+
result.error = event.error?.message ?? "unknown error";
|
|
217
|
+
renderer?.note(c(ANSI.red, `Error: ${result.error}`));
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
default:
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
child.stdout.on("data", (data) => {
|
|
225
|
+
buffer += data.toString("utf8");
|
|
226
|
+
const lines = buffer.split("\n");
|
|
227
|
+
buffer = lines.pop() ?? "";
|
|
228
|
+
for (const line of lines) {
|
|
229
|
+
const trimmed = line.trim();
|
|
230
|
+
if (!trimmed)
|
|
231
|
+
continue;
|
|
232
|
+
try {
|
|
233
|
+
handle(JSON.parse(trimmed));
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
// Non-JSON noise on stdout (rare) goes to the renderer as a note.
|
|
237
|
+
renderer?.note(trimmed);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
let stderr = "";
|
|
242
|
+
child.stderr.on("data", (data) => {
|
|
243
|
+
stderr += data.toString("utf8");
|
|
244
|
+
if (options.live)
|
|
245
|
+
process.stderr.write(data);
|
|
246
|
+
});
|
|
247
|
+
child.on("error", (error) => {
|
|
248
|
+
result.error = error.message;
|
|
249
|
+
result.exitCode = -1;
|
|
250
|
+
result.durationMs = Date.now() - started;
|
|
251
|
+
resolve(result);
|
|
252
|
+
});
|
|
253
|
+
child.on("close", (code) => {
|
|
254
|
+
if (buffer.trim()) {
|
|
255
|
+
try {
|
|
256
|
+
handle(JSON.parse(buffer.trim()));
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
/* ignore trailing partial line */
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
result.exitCode = code ?? -1;
|
|
263
|
+
result.ok = code === 0 && !result.error;
|
|
264
|
+
if (!result.ok && !result.error)
|
|
265
|
+
result.error = stderr.trim().split("\n").slice(-5).join("\n");
|
|
266
|
+
result.durationMs = Date.now() - started;
|
|
267
|
+
renderer?.summary({
|
|
268
|
+
model: options.model,
|
|
269
|
+
cost: result.cost,
|
|
270
|
+
tokens: result.tokens,
|
|
271
|
+
durationMs: result.durationMs,
|
|
272
|
+
tools: result.tools.length,
|
|
273
|
+
});
|
|
274
|
+
resolve(result);
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
// ------------------------------------------------------------- config staging
|
|
279
|
+
/** Write hidden instruction files the agent should read, without polluting the diff. */
|
|
280
|
+
export async function stageInstructions(cwd, files) {
|
|
281
|
+
const written = [];
|
|
282
|
+
for (const [name, content] of Object.entries(files)) {
|
|
283
|
+
const target = join(cwd, name);
|
|
284
|
+
await mkdir(join(target, ".."), { recursive: true });
|
|
285
|
+
await writeFile(target, content, "utf8");
|
|
286
|
+
written.push(name);
|
|
287
|
+
}
|
|
288
|
+
return written;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Give the agent a scratch directory and a strict output contract: it must
|
|
292
|
+
* write JSON to `resultPath`. This is how the bot turns free-form agent work
|
|
293
|
+
* into structured review comments, issue replies and commit messages.
|
|
294
|
+
*/
|
|
295
|
+
export async function prepareArtifacts() {
|
|
296
|
+
const dir = join(tmpdir(), `opencode-actions-${Date.now()}`);
|
|
297
|
+
await mkdir(dir, { recursive: true });
|
|
298
|
+
return {
|
|
299
|
+
resultPath: join(dir, "result.json"),
|
|
300
|
+
transcriptPath: join(dir, "transcript.md"),
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
export async function readResult(path) {
|
|
304
|
+
if (!existsSync(path))
|
|
305
|
+
return null;
|
|
306
|
+
try {
|
|
307
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
export async function writeResult(path, value) {
|
|
314
|
+
await writeFile(path, JSON.stringify(value, null, 2), "utf8");
|
|
315
|
+
}
|
|
316
|
+
export async function appendLog(path, line) {
|
|
317
|
+
await appendFile(path, line + "\n", "utf8");
|
|
318
|
+
}
|