-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
481 lines (425 loc) · 15.6 KB
/
index.js
File metadata and controls
481 lines (425 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { createHash } from "node:crypto"
import { spawn } from "node:child_process"
import { readFile } from "node:fs/promises"
import path from "path"
import process from "node:process"
const agent = "plan"
const root = ".opencode/plans"
const defaultPlanTarget = file("<session-id>")
const editPlanCommand = {
description: "Reopen the current plan in your editor",
agent,
template:
"Reopen the current markdown plan in the configured external editor by calling the edit_plan tool. If the tool reports that the user changed the plan externally, treat those edits as review feedback, summarize what changed, and continue planning from the updated plan.",
}
const plannerConfigCommand = {
description: "Show planner configuration details",
agent,
template:
"Call the planner_config tool for the current session and return its output so the user can inspect planner tool availability, editor resolution, and relevant runtime flags.",
}
function truthy(key) {
const value = process.env[key]?.toLowerCase()
return value === "true" || value === "1"
}
function hasPlanExit() {
const experimentalPlanMode = truthy("OPENCODE_EXPERIMENTAL") || truthy("OPENCODE_EXPERIMENTAL_PLAN_MODE")
const client = process.env.OPENCODE_CLIENT ?? "cli"
return experimentalPlanMode && client === "cli"
}
function file(id) {
return path.posix.join(root, `${id}.md`)
}
function reviewInstruction(target) {
return [
`When the plan is complete, if the submit_plan tool is available, use it to submit the plan for review.`,
`Otherwise, call edit_plan to open the markdown plan in the configured external editor for review. If edit_plan fails, tell the user the plan is ready at ${target} and ask for review in chat.`,
`If edit_plan reports that the user changed the plan externally, treat that as review feedback on the plan, summarize the changes, and continue planning from the revised plan.`,
].join(" ")
}
function agentPrompt(target = defaultPlanTarget) {
const planExit = hasPlanExit()
return [
"Use this agent when the user wants a design, implementation plan, or scoped investigation before coding.",
"Stay in planning mode: inspect the codebase, ask targeted questions when needed, and write a concise execution plan before implementation.",
`Default plan path: ${target}.`,
"Prefer the task tool with the explore and general subagents for deeper research.",
reviewInstruction(target),
...(planExit
? [
"After approval, if the user or Plannotator says something like 'Proceed with implementation', call plan_exit to hand off back to implementation mode.",
"If the plan changes after submit_plan, stay in planner mode, update the plan as needed, and call submit_plan again before plan_exit.",
]
: []),
].join("\n\n")
}
function promptDisclosure(target = defaultPlanTarget) {
return [
"# opencode-planner prompt basis",
"This tool shows the prompt text and planner reminder supplied by the opencode-planner plugin itself.",
"The final runtime prompt can still differ if the user overrides `agent.plan.prompt`, another plugin edits `agent.plan`, or runtime tool availability changes.",
"## Base prompt",
agentPrompt(defaultPlanTarget),
"## Planner reminder",
"This reminder is injected by the plugin at runtime to keep the `plan` agent in planner mode and enforce the review handoff workflow. It is plugin-controlled and is not customized through `agent.plan.prompt`.",
note(target.replace(`${root}/`, "").replace(/\.md$/, "")),
"## How to customize it",
"Only the Base prompt above is replaced by `agent.plan.prompt`. Add this to `opencode.jsonc` to replace that base prompt:",
[
"```json",
"{",
' "agent": {',
' "plan": {',
' "prompt": "You are my planning agent. Focus on migration risk, rollout steps, and testing strategy."',
" }",
" }",
"}",
"```",
].join("\n"),
"Ask the `plan` agent to call `plan_prompt` when you want a fresh copy of the plugin prompt as a starting point.",
].join("\n\n")
}
function note(id) {
const out = [
"<system-reminder>",
"Planner mode is active.",
"You must not edit source files, run bash, change config, or make commits.",
"You may only use read-only tools, ask clarifying questions, delegate exploration or design with the task tool, and edit allowed markdown plan files.",
`Write the plan to ${file(id)} or another allowed *.plan.md/*.spec.md file.`,
reviewInstruction(file(id)),
"</system-reminder>",
]
if (hasPlanExit()) {
out.splice(
out.length - 1,
0,
"If the user or Plannotator then says something like 'Proceed with implementation', call the plan_exit tool to leave planner mode.",
"If the plan changed after submit_plan, do not call plan_exit yet. Revise as needed and call submit_plan again first.",
)
}
return out.join("\n")
}
function partID() {
return `prt_${crypto.randomUUID()}`
}
function rules(input) {
if (!input) return {}
if (typeof input === "string") return { "*": input }
return input
}
function merge(a, b) {
const left = rules(a)
const right = rules(b)
const out = { ...left, ...right }
for (const key of Object.keys(left)) {
const x = left[key]
const y = right[key]
if (!x || !y || typeof x !== "object" || typeof y !== "object") continue
if (Array.isArray(x) || Array.isArray(y)) continue
out[key] = { ...x, ...y }
}
return out
}
function restrictPlannerSubagent(input = {}) {
return {
...input,
permission: merge(input?.permission, {
edit_plan: "deny",
planner_config: "deny",
plan_exit: "deny",
submit_plan: "deny",
}),
}
}
function editorConfig() {
const variables = ["PLAN_VISUAL", "VISUAL", "EDITOR"].map((key) => {
const value = process.env[key]?.trim() ?? ""
return {
key,
value,
set: Boolean(value),
}
})
const selected = variables.find((entry) => entry.set) ?? null
return {
variables,
selected,
command: selected?.value ?? "",
}
}
function editorCommand() {
return editorConfig().command
}
function formatSetting(value) {
return value ? `\`${value}\`` : "<unset>"
}
function hashPlan(content) {
return createHash("sha256").update(content).digest("hex")
}
async function readIfExists(target) {
try {
return await readFile(target, "utf8")
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
return null
}
throw error
}
}
function formatPlanBlock(title, content, fallback) {
return [title, "````markdown", content && content.trim() ? content : fallback, "````"].join("\n")
}
async function snapshotSubmittedPlan(sessionID, args) {
const defaultTarget = file(sessionID)
const currentFile = await readIfExists(defaultTarget)
if (currentFile !== null) {
return {
target: defaultTarget,
hash: hashPlan(currentFile),
}
}
const submitted = typeof args?.plan === "string" ? args.plan : ""
if (!submitted.trim()) return null
if (path.isAbsolute(submitted)) {
const content = await readIfExists(submitted)
if (content !== null) {
return {
target: submitted,
hash: hashPlan(content),
}
}
}
return {
target: null,
hash: hashPlan(submitted),
}
}
async function planChangedSinceSubmit(sessionID, submitted) {
if (!submitted) return false
const target = submitted.target ?? file(sessionID)
const current = await readIfExists(target)
if (current === null) {
return submitted.target !== null
}
return hashPlan(current) !== submitted.hash
}
function runEditor(target) {
const editor = editorCommand()
if (!editor) {
throw new Error(
"None of `PLAN_VISUAL`, `VISUAL`, or `EDITOR` is set, so edit_plan cannot open the plan. Configure a blocking editor command such as `code --wait`, or a terminal launcher that opens your editor in a separate window and waits.",
)
}
const shell = process.env.SHELL ?? "sh"
return new Promise((resolve, reject) => {
const child = spawn(shell, ["-lc", `${editor} "$1"`, "opencode-editor", target], {
stdio: ["ignore", "ignore", "pipe"],
env: process.env,
})
let stderr = ""
child.stderr?.on("data", (chunk) => {
stderr += chunk.toString()
})
child.on("error", reject)
child.on("exit", (code) => {
if (code === 0) {
resolve()
return
}
const detail = stderr.trim()
const suffix = detail ? `: ${detail}` : ""
reject(
new Error(
`The external editor command exited with status ${code}${suffix}. Configure PLAN_VISUAL, VISUAL, or EDITOR to launch a separate process that waits until editing is complete.`,
),
)
})
})
}
async function editPlan(sessionID) {
const target = file(sessionID ?? "<session-id>")
const before = await readIfExists(target)
await runEditor(target)
let after = ""
try {
after = await readFile(target, "utf8")
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
throw new Error(`The plan file \`${target}\` does not exist yet. Finish writing the plan first.`)
}
throw error
}
if (before === after) {
return [
"The plan was reopened in your external editor. No changes were made.",
`File: ${target}`,
"",
formatPlanBlock("## Current plan", after, `The plan file \`${target}\` is empty.`),
].join("\n")
}
return [
"The user edited the plan externally.",
`File: ${target}`,
"",
"Treat these external edits as review feedback on the plan. Summarize what changed, continue planning from the updated plan, and if this plan was already reviewed with submit_plan, submit the revised plan again before plan_exit.",
"",
formatPlanBlock("## Previous plan", before, "_(The plan file did not exist before editing.)_"),
"",
formatPlanBlock("## Updated plan", after, `The plan file \`${target}\` is empty.`),
].join("\n")
}
function plannerConfig(sessionID) {
const target = file(sessionID ?? "<session-id>")
const permission = mode().permission
const editor = editorConfig()
const planExitEnabled = hasPlanExit()
return [
"# opencode-planner configuration",
"## Planner files",
`- Current session plan path: \`${target}\``,
`- Default plan path pattern: \`${defaultPlanTarget}\``,
"",
"## Planner tools",
`- plan_prompt: ${permission.plan_prompt === "allow" ? "allowed by the `plan` agent" : "not allowed by the `plan` agent"}`,
`- edit_plan: ${permission.edit_plan === "allow" ? "allowed by the `plan` agent as the fallback local-editor review tool" : "not allowed by the `plan` agent"}`,
`- planner_config: ${permission.planner_config === "allow" ? "allowed by the `plan` agent" : "not allowed by the `plan` agent"}`,
`- submit_plan: ${permission.submit_plan === "allow" ? "allowed by the `plan` agent and required for Plannotator review; availability still depends on the host runtime" : "not allowed by the `plan` agent"}`,
`- plan_exit: ${planExitEnabled ? "enabled by the current runtime flags when the host runtime provides it" : "not enabled by the current runtime flags"}`,
"",
"## Editor resolution",
"- Precedence: `PLAN_VISUAL` -> `VISUAL` -> `EDITOR`",
...editor.variables.map((entry) => `- ${entry.key}: ${formatSetting(entry.value)}`),
`- Selected source: ${editor.selected ? `\`${editor.selected.key}\`` : "none"}`,
`- Selected command: ${formatSetting(editor.command)}`,
"",
"## Runtime flags",
`- OPENCODE_EXPERIMENTAL: ${formatSetting(process.env.OPENCODE_EXPERIMENTAL?.trim() ?? "")}`,
`- OPENCODE_EXPERIMENTAL_PLAN_MODE: ${formatSetting(process.env.OPENCODE_EXPERIMENTAL_PLAN_MODE?.trim() ?? "")}`,
`- OPENCODE_CLIENT: ${formatSetting(process.env.OPENCODE_CLIENT?.trim() ?? "")}`,
`- plan_exit expected: ${planExitEnabled ? "yes" : "no"}`,
].join("\n")
}
function mode(input = {}) {
const base = {
mode: "primary",
color: "info",
description: "Researches the codebase and writes execution plans without editing source files.",
prompt: agentPrompt(),
permission: {
"*": "deny",
read: {
"*": "allow",
"*.env": "ask",
"*.env.*": "ask",
"*.env.example": "allow",
},
glob: "allow",
grep: "allow",
question: "allow",
task: {
"*": "deny",
explore: "allow",
general: "allow",
},
webfetch: "allow",
websearch: "allow",
codesearch: "allow",
batch: "allow",
edit_plan: "allow",
planner_config: "allow",
plan_prompt: "allow",
submit_plan: "allow",
...(hasPlanExit() ? { plan_exit: "allow" } : {}),
edit: {
"*": "deny",
[path.posix.join(root, "*.md")]: "allow",
"plans/*.md": "allow",
"specs/*.md": "allow",
"**/*.plan.md": "allow",
"**/*.spec.md": "allow",
},
bash: "deny",
skill: "deny",
todowrite: "deny",
},
}
return {
...base,
...input,
prompt: input && Object.hasOwn(input, "prompt") ? input.prompt : base.prompt,
permission: merge(base.permission, input?.permission),
}
}
export const plugin = async function plannerPlugin() {
const seen = new Set()
const submittedPlans = new Map()
return {
tool: {
plan_prompt: {
description: "Reveal the planner plugin prompt basis",
args: {},
async execute(_, context) {
return promptDisclosure(context.sessionID ? file(context.sessionID) : defaultPlanTarget)
},
},
edit_plan: {
description: "Open the current plan in the configured external editor",
args: {},
async execute(_, context) {
return editPlan(context.sessionID)
},
},
planner_config: {
description: "Show planner configuration details for the current session",
args: {},
async execute(_, context) {
return plannerConfig(context.sessionID)
},
},
},
async config(cfg) {
cfg.agent ??= {}
cfg.command = {
"planner-config": plannerConfigCommand,
"edit-plan": editPlanCommand,
...cfg.command,
}
cfg.agent[agent] = mode(cfg.agent[agent])
cfg.agent.general = restrictPlannerSubagent(cfg.agent.general)
cfg.agent.explore = restrictPlannerSubagent(cfg.agent.explore)
},
async "chat.message"(input, output) {
if (input.agent !== agent) {
seen.delete(input.sessionID)
return
}
seen.add(input.sessionID)
output.parts.push({
id: partID(),
messageID: output.message.id,
sessionID: output.message.sessionID,
type: "text",
text: note(input.sessionID),
synthetic: true,
})
},
async "tool.execute.before"(input) {
if (input.tool !== "plan_exit") return
const submitted = submittedPlans.get(input.sessionID)
if (!(await planChangedSinceSubmit(input.sessionID, submitted))) return
throw new Error(
"The plan has changed since the last submit_plan review. Stay in planner mode, update the plan as needed, and call submit_plan again before plan_exit.",
)
},
async "tool.execute.after"(input) {
if (input.tool !== "submit_plan") return
const snapshot = await snapshotSubmittedPlan(input.sessionID, input.args)
if (snapshot) submittedPlans.set(input.sessionID, snapshot)
},
async "experimental.chat.system.transform"(input, output) {
if (!input.sessionID || !seen.has(input.sessionID)) return
output.system.push(note(input.sessionID))
},
}
}
export default plugin