-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode-companion.mjs
More file actions
1326 lines (1172 loc) · 44.2 KB
/
opencode-companion.mjs
File metadata and controls
1326 lines (1172 loc) · 44.2 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// OpenCode Companion - Main entry point for the Claude Code plugin.
// Mirrors the codex-plugin-cc codex-companion.mjs architecture but uses
// OpenCode's HTTP REST API instead of JSON-RPC over stdin/stdout.
//
// Modified by JohnnyVicious (2026):
// - thread `--model` through `handleReview` and `handleAdversarialReview`
// so callers can override OpenCode's default model per review;
// - accept `--pr <N>` (with `PR #N` focus auto-detect for adversarial)
// and fetch PR diffs via `gh pr diff` so reviews can target a GitHub
// pull request without checking it out;
// - `handleSetup` reads OpenCode's auth.json directly via
// `getConfiguredProviders` instead of probing the `GET /provider` HTTP
// endpoint, which returns a TypeScript schema dump rather than the
// user's configured credentials;
// - extract the model OpenCode actually used (from `response.info.model`)
// and prepend it as a `**Model:** ...` header to every review output
// so users always see which model produced the review;
// - switch reviews from OpenCode's built-in `plan` agent to a custom
// `review` agent shipped in the plugin. OpenCode's `plan` agent
// injects a synthetic user-message directive ("Plan mode ACTIVE —
// STRICTLY FORBIDDEN... produce an implementation plan") on every
// turn, which dominates our review system prompt and makes OpenCode
// return implementation plans instead of the requested review. A
// custom agent with read-only permissions and a neutral prompt body
// sidesteps the injection entirely. When our agent isn't available
// (e.g. the user already had a server running without our config
// dir), we fall back to the `build` agent with per-call tool
// restrictions and a warning;
// - parse `--model <provider>/<model-id>` into OpenCode's required
// `{providerID, modelID}` object before sending. Passing the raw
// CLI string caused HTTP 400 ("expected object, received string")
// on every `--model` invocation — the original threading commit
// wired the argument through but never adapted the shape;
// - add a `--free` flag to review, adversarial-review, and task
// handlers that shells out to `opencode models`, filters for the
// `:free` / `-free` suffix, and picks one at random so callers
// can cheaply fire off reviews/tasks against whichever free-tier
// model is available without hand-picking. Mutually exclusive
// with `--model`. For background tasks the free model is locked
// in at dispatch so the worker can't drift;
// - fix `handleTask` silently dropping `--model`: the foreground
// path passed `{agent}` to sendPrompt with no model, and the
// background worker never parsed or forwarded one. Both paths
// now honor `--model` / `--free` end-to-end.
// (Apache License 2.0 §4(b) modification notice.)
import crypto from "node:crypto";
import os from "node:os";
import path from "node:path";
import process from "node:process";
import fs from "node:fs";
import { parseArgs, extractTaskText } from "./lib/args.mjs";
import { isOpencodeInstalled, getOpencodeVersion, spawnDetached, getConfiguredProviders } from "./lib/process.mjs";
import { isServerRunning, ensureServer, createClient, connect } from "./lib/opencode-server.mjs";
import { resolveWorkspace } from "./lib/workspace.mjs";
import { loadState, updateState, upsertJob, generateJobId, jobDataPath } from "./lib/state.mjs";
import {
buildStatusSnapshot,
resolveResultJob,
resolveCancelableJob,
enrichJob,
reconcileAllJobs,
matchJobReference,
} from "./lib/job-control.mjs";
import { createJobRecord, runTrackedJob, getClaudeSessionId } from "./lib/tracked-jobs.mjs";
import {
renderStatus,
renderResult,
renderReview,
renderSetup,
extractResponseModel,
formatModelHeader,
} from "./lib/render.mjs";
import { buildReviewPrompt, buildTaskPrompt } from "./lib/prompts.mjs";
import { getDiff, getStatus as getGitStatus, detectPrReference } from "./lib/git.mjs";
import {
createWorktreeSession,
diffWorktreeSession,
cleanupWorktreeSession,
} from "./lib/worktree.mjs";
import { readJson, readDenyRules } from "./lib/fs.mjs";
import { resolveReviewAgent } from "./lib/review-agent.mjs";
import { preparePostInstructions, formatPostTrailer } from "./lib/pr-comments.mjs";
import { tryParseReview } from "./lib/review-parser.mjs";
import { parseModelString, selectFreeModel } from "./lib/model.mjs";
import {
applyDefaultModelOptions,
hasOwnOption,
normalizeDefaults,
parseDefaultAgentSetting,
parseDefaultModelSetting,
resolveTaskAgentName,
} from "./lib/defaults.mjs";
const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || path.resolve(import.meta.dirname, "..");
// ------------------------------------------------------------------
// Subcommand dispatch
// ------------------------------------------------------------------
const [subcommand, ...argv] = process.argv.slice(2);
const handlers = {
setup: handleSetup,
review: handleReview,
"adversarial-review": handleAdversarialReview,
task: handleTask,
"task-worker": handleTaskWorker,
"task-resume-candidate": handleTaskResumeCandidate,
"last-review": handleLastReview,
"worktree-cleanup": handleWorktreeCleanup,
status: handleStatus,
result: handleResult,
cancel: handleCancel,
};
const handler = handlers[subcommand];
if (!handler) {
console.error(`Unknown subcommand: ${subcommand}`);
console.error(`Available: ${Object.keys(handlers).join(", ")}`);
process.exit(1);
}
handler(argv).catch((err) => {
console.error(`Error in ${subcommand}: ${err.message}`);
process.exit(1);
});
// ------------------------------------------------------------------
// Setup
// ------------------------------------------------------------------
async function handleSetup(argv) {
const { options } = parseArgs(argv, {
valueOptions: ["review-gate-max", "review-gate-cooldown", "default-model", "default-agent"],
booleanOptions: ["json", "enable-review-gate", "disable-review-gate"],
});
let reviewGateOverride;
if (options["enable-review-gate"]) reviewGateOverride = true;
if (options["disable-review-gate"]) reviewGateOverride = false;
let reviewGateMaxPerSessionOverride;
if (options["review-gate-max"] != null) {
const raw = options["review-gate-max"];
const max = raw === "off" ? null : Number(raw);
if (max !== null && (!Number.isInteger(max) || max < 1)) {
console.error(`--review-gate-max must be a positive integer or "off".`);
process.exit(1);
}
reviewGateMaxPerSessionOverride = max;
}
let reviewGateCooldownMinutesOverride;
if (options["review-gate-cooldown"] != null) {
const raw = options["review-gate-cooldown"];
const cooldown = raw === "off" ? null : Number(raw);
if (cooldown !== null && (!Number.isInteger(cooldown) || cooldown < 1)) {
console.error(`--review-gate-cooldown must be a positive integer (minutes) or "off".`);
process.exit(1);
}
reviewGateCooldownMinutesOverride = cooldown;
}
let defaultModelOverride;
if (hasOwnOption(options, "default-model")) {
try {
defaultModelOverride = parseDefaultModelSetting(options["default-model"]);
} catch (err) {
console.error(err.message);
process.exit(1);
}
}
let defaultAgentOverride;
if (hasOwnOption(options, "default-agent")) {
try {
defaultAgentOverride = parseDefaultAgentSetting(options["default-agent"]);
} catch (err) {
console.error(err.message);
process.exit(1);
}
}
const installed = await isOpencodeInstalled();
const version = installed ? await getOpencodeVersion() : null;
let serverRunning = false;
let providers = [];
if (installed) {
serverRunning = await isServerRunning();
// Read configured providers directly from OpenCode's auth.json. The
// HTTP `GET /provider` endpoint returns a TypeScript schema dump, not
// the user's credentials, and `GET /provider/auth` only lists which
// auth methods each provider supports. auth.json is the same source
// of truth that `opencode providers list` uses, and it works whether
// or not the OpenCode server is running.
try {
providers = getConfiguredProviders();
} catch (err) {
console.error(`Warning: could not read configured providers: ${err.message}`);
}
}
// Apply setup config changes only after all inputs have been validated.
const workspace = await resolveWorkspace();
if (
reviewGateOverride !== undefined ||
reviewGateMaxPerSessionOverride !== undefined ||
reviewGateCooldownMinutesOverride !== undefined ||
defaultModelOverride !== undefined ||
defaultAgentOverride !== undefined
) {
updateState(workspace, (state) => {
state.config = state.config || {};
if (reviewGateOverride !== undefined) {
state.config.reviewGate = reviewGateOverride;
}
if (reviewGateMaxPerSessionOverride !== undefined) {
state.config.reviewGateMaxPerSession = reviewGateMaxPerSessionOverride;
}
if (reviewGateCooldownMinutesOverride !== undefined) {
state.config.reviewGateCooldownMinutes = reviewGateCooldownMinutesOverride;
}
if (defaultModelOverride !== undefined || defaultAgentOverride !== undefined) {
state.config.defaults = state.config.defaults || {};
}
if (defaultModelOverride !== undefined) {
state.config.defaults.model = defaultModelOverride;
}
if (defaultAgentOverride !== undefined) {
state.config.defaults.agent = defaultAgentOverride;
}
});
}
const finalState = loadState(workspace);
const reviewGate = finalState.config?.reviewGate ?? false;
const reviewGateMaxPerSession = finalState.config?.reviewGateMaxPerSession ?? null;
const reviewGateCooldownMinutes = finalState.config?.reviewGateCooldownMinutes ?? null;
const defaults = normalizeDefaults(finalState.config?.defaults);
const status = {
installed,
version,
serverRunning,
providers,
defaults,
reviewGate,
reviewGateMaxPerSession,
reviewGateCooldownMinutes,
};
if (options.json) {
console.log(JSON.stringify(status, null, 2));
} else {
console.log(renderSetup(status));
}
}
// ------------------------------------------------------------------
// Review
// ------------------------------------------------------------------
/**
* Resolve the model the user requested. Handles three cases:
* - `--free` : pick a random free model via `opencode models`
* - `--model X` : parse X into {providerID, modelID}
* - neither : return null (use the user's configured default)
*
* `--free` and `--model` are mutually exclusive. Errors bubble up to the
* handler, which prints them and exits non-zero.
*
* @param {{ free?: boolean, model?: string }} options
* @returns {Promise<{providerID: string, modelID: string, raw?: string} | null>}
*/
async function resolveRequestedModel(options) {
const hasModel = hasOwnOption(options, "model");
if (options.free && hasModel) {
throw new Error("--free and --model are mutually exclusive; pick one.");
}
if (options.free) {
return selectFreeModel();
}
if (hasModel) {
const parsed = parseModelString(options.model);
if (!parsed) {
throw new Error(
`Invalid --model value: ${options.model} (expected "provider/model-id", ` +
`e.g. openrouter/anthropic/claude-haiku-4.5)`
);
}
return { ...parsed, raw: options.model.trim() };
}
return null;
}
async function handleReview(argv) {
const { options } = parseArgs(argv, {
valueOptions: ["base", "scope", "model", "pr", "path", "confidence-threshold"],
multiValueOptions: ["path"],
booleanOptions: ["wait", "background", "free", "post"],
});
const prNumber = options.pr ? Number(options.pr) : null;
if (options.pr && (!Number.isFinite(prNumber) || prNumber <= 0)) {
console.error(`Invalid --pr value: ${options.pr} (must be a positive number)`);
process.exit(1);
}
const paths = normalizePathOption(options.path);
const effectivePrNumber = paths?.length ? null : prNumber;
const postRequested = Boolean(options.post);
if (postRequested && !effectivePrNumber) {
console.error(
"--post requires --pr <number> (posting back to GitHub is PR-only; --path reviews have nowhere to post)."
);
process.exit(1);
}
let confidenceThreshold;
try {
confidenceThreshold = parseConfidenceThreshold(options["confidence-threshold"]);
} catch (err) {
console.error(err.message);
process.exit(1);
}
const workspace = await resolveWorkspace();
const state = loadState(workspace);
const defaults = normalizeDefaults(state.config?.defaults);
const modelOptions = applyDefaultModelOptions(options, defaults);
let requestedModel;
try {
requestedModel = await resolveRequestedModel(modelOptions);
} catch (err) {
console.error(err.message);
process.exit(1);
}
const job = createJobRecord(workspace, "review", {
base: options.base,
model: requestedModel?.raw ?? modelOptions.model,
pr: effectivePrNumber,
paths,
});
try {
const result = await runTrackedJob(workspace, job, async ({ report, log }) => {
report("starting", "Connecting to OpenCode server...");
const client = await connect({ cwd: workspace });
report("reviewing", "Creating review session...");
const session = await client.createSession({ title: `Code Review ${job.id}` });
upsertJob(workspace, { id: job.id, opencodeSessionId: session.id });
const prompt = await buildReviewPrompt(workspace, {
base: options.base,
pr: effectivePrNumber,
paths,
adversarial: false,
}, PLUGIN_ROOT);
const reviewAgent = await resolveReviewAgent(client, log);
const modelLabel = requestedModel?.raw ?? null;
report("reviewing", "Running review...");
log(`Prompt length: ${prompt.length} chars, agent: ${reviewAgent.agent}${modelLabel ? `, model: ${modelLabel}${options.free ? " (--free picked)" : ""}` : ""}${effectivePrNumber ? `, pr: #${effectivePrNumber}` : ""}${paths?.length ? `, paths: ${paths.join(", ")}` : ""}`);
const response = await client.sendPrompt(session.id, prompt, {
agent: reviewAgent.agent,
model: requestedModel ? { providerID: requestedModel.providerID, modelID: requestedModel.modelID } : null,
tools: reviewAgent.tools,
});
report("finalizing", "Processing review output...");
// Try to parse structured output. `tryParseReview` tolerates the
// common LLM failure mode where a string value contains an
// unescaped `"` (usually embedded code or JSON literals in the
// summary) and strict JSON.parse would otherwise give up.
const text = extractResponseText(response);
let structured = tryParseReview(text);
const usedModel = extractResponseModel(response);
return {
rendered: formatModelHeader(usedModel) + (structured ? renderReview(structured) : text),
raw: response,
structured,
model: usedModel,
};
});
saveLastReview(workspace, result.rendered);
console.log(result.rendered);
if (postRequested) {
await emitPostTrailer(workspace, {
prNumber: effectivePrNumber,
result,
adversarial: false,
confidenceThreshold,
});
}
} catch (err) {
console.error(`Review failed: ${err.message}`);
process.exit(1);
}
}
async function handleAdversarialReview(argv) {
const { options, positional } = parseArgs(argv, {
valueOptions: ["base", "scope", "model", "pr", "path", "confidence-threshold"],
multiValueOptions: ["path"],
booleanOptions: ["wait", "background", "free", "post"],
});
const workspace = await resolveWorkspace();
const state = loadState(workspace);
const defaults = normalizeDefaults(state.config?.defaults);
const modelOptions = applyDefaultModelOptions(options, defaults);
let requestedModel;
try {
requestedModel = await resolveRequestedModel(modelOptions);
} catch (err) {
console.error(err.message);
process.exit(1);
}
let focus = positional.join(" ").trim();
// --pr <N> takes precedence; otherwise look for "PR #N" / "PR N" inside the
// focus text and strip it so the matched substring doesn't pollute the
// prompt with a stale instruction.
let prNumber = null;
if (options.pr) {
prNumber = Number(options.pr);
if (!Number.isFinite(prNumber) || prNumber <= 0) {
console.error(`Invalid --pr value: ${options.pr} (must be a positive number)`);
process.exit(1);
}
} else {
const detected = detectPrReference(focus);
if (detected) {
prNumber = detected.prNumber;
focus = focus.replace(detected.matched, "").replace(/\s+/g, " ").trim();
}
}
const paths = normalizePathOption(options.path);
const effectivePrNumber = paths?.length ? null : prNumber;
const postRequested = Boolean(options.post);
if (postRequested && !effectivePrNumber) {
console.error(
"--post requires --pr <number> (posting back to GitHub is PR-only; --path reviews have nowhere to post)."
);
process.exit(1);
}
let confidenceThreshold;
try {
confidenceThreshold = parseConfidenceThreshold(options["confidence-threshold"]);
} catch (err) {
console.error(err.message);
process.exit(1);
}
const job = createJobRecord(workspace, "adversarial-review", {
base: options.base,
focus,
model: requestedModel?.raw ?? modelOptions.model,
pr: effectivePrNumber,
paths,
});
try {
const result = await runTrackedJob(workspace, job, async ({ report, log }) => {
report("starting", "Connecting to OpenCode server...");
const client = await connect({ cwd: workspace });
report("reviewing", "Creating adversarial review session...");
const session = await client.createSession({ title: `Adversarial Review ${job.id}` });
upsertJob(workspace, { id: job.id, opencodeSessionId: session.id });
const prompt = await buildReviewPrompt(workspace, {
base: options.base,
pr: effectivePrNumber,
paths,
adversarial: true,
focus,
}, PLUGIN_ROOT);
const reviewAgent = await resolveReviewAgent(client, log);
const modelLabel = requestedModel?.raw ?? null;
report("reviewing", "Running adversarial review...");
log(`Prompt length: ${prompt.length} chars, agent: ${reviewAgent.agent}, focus: ${focus || "(none)"}${modelLabel ? `, model: ${modelLabel}${options.free ? " (--free picked)" : ""}` : ""}${effectivePrNumber ? `, pr: #${effectivePrNumber}` : ""}${paths?.length ? `, paths: ${paths.join(", ")}` : ""}`);
const response = await client.sendPrompt(session.id, prompt, {
agent: reviewAgent.agent,
model: requestedModel ? { providerID: requestedModel.providerID, modelID: requestedModel.modelID } : null,
tools: reviewAgent.tools,
});
report("finalizing", "Processing review output...");
// See note on `tryParseReview` in handleReview — same reason.
const text = extractResponseText(response);
let structured = tryParseReview(text);
const usedModel = extractResponseModel(response);
return {
rendered: formatModelHeader(usedModel) + (structured ? renderReview(structured) : text),
raw: response,
structured,
model: usedModel,
};
});
saveLastReview(workspace, result.rendered);
console.log(result.rendered);
if (postRequested) {
await emitPostTrailer(workspace, {
prNumber: effectivePrNumber,
result,
adversarial: true,
confidenceThreshold,
});
}
} catch (err) {
console.error(`Adversarial review failed: ${err.message}`);
process.exit(1);
}
}
/**
* Parse `--confidence-threshold` into a 0..1 float. Accepts raw floats
* (`0.8`) or percentage strings (`80`, `80%`). Returns the default 0.8
* when the option is unset.
*/
function parseConfidenceThreshold(raw) {
if (raw == null || raw === "") return 0.8;
let text = String(raw).trim();
const isPercent = text.endsWith("%");
if (isPercent) text = text.slice(0, -1).trim();
const n = Number(text);
if (!Number.isFinite(n)) {
throw new Error(
`Invalid --confidence-threshold value: ${raw} (expected a number between 0 and 1, or a percentage like 80)`
);
}
const normalized = isPercent || n > 1 ? n / 100 : n;
if (normalized < 0 || normalized > 1) {
throw new Error(
`Invalid --confidence-threshold value: ${raw} (must be between 0 and 1, or 0 and 100 if expressed as a percentage)`
);
}
return normalized;
}
/**
* Prepare a GitHub review payload and emit a structured trailer on
* stderr describing the `gh api` POST command the slash-command runner
* (Claude Code) should execute to actually publish the review.
*
* The companion deliberately does NOT run the POST itself. Keeping the
* network call in Claude's Bash tool:
* - lets Claude show/confirm the payload before it fires,
* - avoids re-implementing gh plumbing (pagination, JSON stream
* reassembly, auth) in Node, and
* - makes failures debuggable from the chat instead of buried in a
* stderr line the user may never see.
*
* Never throws — on failure the trailer is replaced with a human-
* readable `[opencode-companion] Failed to prepare PR post: …` line so
* the review output (already on stdout) is not disrupted.
*/
async function emitPostTrailer(workspace, { prNumber, result, adversarial, confidenceThreshold }) {
const prepared = await preparePostInstructions(workspace, {
prNumber,
structured: result.structured,
rendered: result.rendered,
model: result.model,
adversarial,
confidenceThreshold,
});
if (!prepared.prepared) {
process.stderr.write(
`[opencode-companion] Failed to prepare PR post for #${prNumber}: ${prepared.error}\n`
);
return;
}
process.stderr.write(formatPostTrailer(prepared));
}
// ------------------------------------------------------------------
// Task (rescue delegation)
// ------------------------------------------------------------------
async function handleTask(argv) {
const { options, positional } = parseArgs(argv, {
valueOptions: ["model", "agent"],
booleanOptions: ["write", "background", "wait", "resume-last", "fresh", "worktree", "free"],
});
const taskText = extractTaskText(argv, ["model", "agent"], [
"write", "background", "wait", "resume-last", "fresh", "worktree", "free",
]);
if (!taskText) {
console.error("No task text provided.");
process.exit(1);
}
const workspace = await resolveWorkspace();
const state = loadState(workspace);
const defaults = normalizeDefaults(state.config?.defaults);
const modelOptions = applyDefaultModelOptions(options, defaults);
// Resolve --free / --model once here so background workers inherit a
// concrete model string and can't drift if `opencode models` changes
// between dispatch and execution.
let requestedModel;
try {
requestedModel = await resolveRequestedModel(modelOptions);
} catch (err) {
console.error(err.message);
process.exit(1);
}
const isWrite = options.write !== undefined ? options.write : true;
const agentName = resolveTaskAgentName(options, defaults, isWrite);
const useWorktree = Boolean(options.worktree);
if (useWorktree && !isWrite) {
console.error("--worktree requires --write (nothing to isolate in read-only mode).");
process.exit(1);
}
// Issue #33 — warn when deny rules exist and task is write-capable.
// OpenCode runs outside Claude Code's permission system, so it may be able
// to edit files that Claude Code itself would block. Surfacing this helps
// users make an informed choice without blocking legitimate rescue work.
if (isWrite) {
const denyRules = readDenyRules(workspace);
if (denyRules.length > 0) {
process.stderr.write(
`[opencode-companion] Warning: this workspace has Claude Code deny rules (.claude/settings.json).\n` +
` OpenCode runs with its own permission boundary and may be able to read/edit files\n` +
` that Claude Code would block. Review the deny rules before proceeding:\n` +
denyRules.map((r) => ` - path: ${r.path} ${r.read ? "[read blocked]" : ""} ${r.edit ? "[edit blocked]" : ""}`).join("\n") +
`\n`
);
}
}
// Check for resume
let resumeSessionId = null;
if (options["resume-last"]) {
const state = loadState(workspace);
const sessionId = getClaudeSessionId();
const lastTask = state.jobs
?.filter((j) => j.type === "task" && j.opencodeSessionId)
?.filter((j) => !sessionId || j.sessionId === sessionId)
?.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))?.[0];
if (lastTask?.opencodeSessionId) {
resumeSessionId = lastTask.opencodeSessionId;
}
}
const job = createJobRecord(workspace, "task", {
agent: agentName,
model: requestedModel?.raw ?? modelOptions.model,
resumeSessionId,
worktree: useWorktree,
});
// Background mode: spawn a detached worker
if (options.background) {
const workerArgs = [
path.join(PLUGIN_ROOT, "scripts", "opencode-companion.mjs"),
"task-worker",
"--job-id", job.id,
"--workspace", workspace,
"--task-text", taskText,
"--agent", agentName,
];
if (isWrite) workerArgs.push("--write");
if (useWorktree) workerArgs.push("--worktree");
if (resumeSessionId) workerArgs.push("--resume-session", resumeSessionId);
// Pass the resolved model (from --model or --free) as a concrete
// "provider/model-id" string so the worker doesn't need to re-run
// `opencode models`.
if (requestedModel?.raw) {
workerArgs.push("--model", requestedModel.raw);
} else if (requestedModel) {
workerArgs.push("--model", `${requestedModel.providerID}/${requestedModel.modelID}`);
}
spawnDetached("node", workerArgs, { cwd: workspace });
console.log(`OpenCode task started in background: ${job.id}`);
if (options.free && requestedModel) {
console.log(`--free picked: ${requestedModel.raw}`);
}
console.log("Check `/opencode:status` for progress.");
return;
}
// Set up a worktree session if requested. Foreground mode only.
let worktreeSession = null;
let effectiveCwd = workspace;
if (useWorktree) {
try {
worktreeSession = await createWorktreeSession(workspace);
effectiveCwd = worktreeSession.worktreePath;
upsertJob(workspace, {
id: job.id,
worktreeSession: {
worktreePath: worktreeSession.worktreePath,
branch: worktreeSession.branch,
repoRoot: worktreeSession.repoRoot,
baseCommit: worktreeSession.baseCommit,
timestamp: worktreeSession.timestamp,
},
});
} catch (err) {
upsertJob(workspace, {
id: job.id,
status: "failed",
phase: "failed",
completedAt: new Date().toISOString(),
errorMessage: `Failed to create worktree: ${err.message}`,
});
console.error(`Failed to create worktree: ${err.message}`);
process.exit(1);
}
}
// Foreground mode
try {
const result = await runTrackedJob(workspace, job, async ({ report, log }) => {
report("starting", "Connecting to OpenCode server...");
const client = await connect({ cwd: effectiveCwd });
let sessionId;
if (resumeSessionId) {
report("starting", `Resuming OpenCode session ${resumeSessionId}...`);
sessionId = resumeSessionId;
} else {
report("starting", "Creating new OpenCode session...");
const session = await client.createSession({ title: `Task ${job.id}` });
sessionId = session.id;
}
upsertJob(workspace, { id: job.id, opencodeSessionId: sessionId });
const prompt = buildTaskPrompt(taskText, { write: isWrite });
report("investigating", "Sending task to OpenCode...");
log(
`Agent: ${agentName}, Write: ${isWrite}, ` +
`Worktree: ${useWorktree ? worktreeSession.branch : "no"}, ` +
`Prompt: ${prompt.length} chars` +
(requestedModel?.raw
? `, model: ${requestedModel.raw}${options.free ? " (--free picked)" : ""}`
: "")
);
const response = await client.sendPrompt(sessionId, prompt, {
agent: agentName,
model: requestedModel ? { providerID: requestedModel.providerID, modelID: requestedModel.modelID } : null,
});
report("finalizing", "Processing task output...");
const text = extractResponseText(response);
// Get changed files if write mode
let changedFiles = [];
if (isWrite) {
try {
const diff = await client.getSessionDiff(sessionId);
if (diff?.files) {
changedFiles = diff.files.map((f) => f.path || f.name).filter(Boolean);
}
} catch (err) {
log(`Warning: could not retrieve diff - ${err.message}`);
}
}
// If using a worktree, compute the actual git diff stat produced on
// disk. This is what the user will have to keep or discard.
let worktreeDiff = null;
if (worktreeSession) {
try {
worktreeDiff = await diffWorktreeSession(worktreeSession);
} catch (err) {
log(`Failed to compute worktree diff: ${err.message}`);
}
}
return {
rendered: worktreeSession
? renderWorktreeTaskOutput(text, worktreeSession, worktreeDiff, job.id)
: text,
messages: response,
changedFiles,
summary: text.slice(0, 500),
worktreeSession: worktreeSession
? {
worktreePath: worktreeSession.worktreePath,
branch: worktreeSession.branch,
repoRoot: worktreeSession.repoRoot,
baseCommit: worktreeSession.baseCommit,
}
: null,
};
});
console.log(result.rendered);
} catch (err) {
// On any failure with a worktree, clean it up so we don't leak dirs.
if (worktreeSession) {
try {
await cleanupWorktreeSession(worktreeSession, { keep: false });
} catch {
// best-effort
}
}
console.error(`Task failed: ${err.message}`);
process.exit(1);
}
}
function renderWorktreeTaskOutput(text, session, diff, jobId) {
const lines = [];
if (text) {
lines.push(text.trimEnd());
lines.push("");
}
lines.push("---");
lines.push("");
lines.push("## Worktree");
lines.push("");
lines.push(`Branch: \`${session.branch}\``);
lines.push(`Path: \`${session.worktreePath}\``);
lines.push("");
if (diff?.stat) {
lines.push("### Changes");
lines.push("");
lines.push("```");
lines.push(diff.stat);
lines.push("```");
lines.push("");
} else {
lines.push("OpenCode made no file changes in the worktree.");
lines.push("");
}
lines.push("### Next steps");
lines.push("");
lines.push(`- **Keep**: \`node "\${CLAUDE_PLUGIN_ROOT}/scripts/opencode-companion.mjs" worktree-cleanup ${jobId} --action keep\``);
lines.push(`- **Discard**: \`node "\${CLAUDE_PLUGIN_ROOT}/scripts/opencode-companion.mjs" worktree-cleanup ${jobId} --action discard\``);
return lines.join("\n");
}
async function handleWorktreeCleanup(argv) {
const { options, positional } = parseArgs(argv, {
valueOptions: ["action"],
booleanOptions: ["json"],
});
const jobId = positional[0];
if (!jobId) {
console.error("Usage: worktree-cleanup <job-id> --action <keep|discard>");
process.exit(1);
}
const action = options.action;
if (action !== "keep" && action !== "discard") {
console.error("--action must be 'keep' or 'discard'.");
process.exit(1);
}
const workspace = await resolveWorkspace();
const state = loadState(workspace);
const { job, ambiguous } = matchJobReference(state.jobs ?? [], jobId);
if (ambiguous) {
console.error("Ambiguous job reference. Please provide a more specific ID prefix.");
process.exit(1);
}
if (!job) {
console.error(`No job found for ${jobId}.`);
process.exit(1);
}
const session = job.worktreeSession;
if (!session?.worktreePath || !session?.branch || !session?.repoRoot) {
console.error(`Job ${jobId} has no worktree session. Was it run with --worktree?`);
process.exit(1);
}
const result = await cleanupWorktreeSession(session, { keep: action === "keep" });
if (options.json) {
console.log(JSON.stringify({ jobId: job.id, action, result }, null, 2));
return;
}
const lines = ["# Worktree Cleanup", ""];
if (action === "keep") {
if (result.applied) {
lines.push(`Applied changes from \`${session.branch}\` and cleaned up.`);
} else if (result.detail === "No changes to apply.") {
lines.push(`No changes to apply. Worktree and branch \`${session.branch}\` cleaned up.`);
} else {
lines.push(`Failed to apply changes: ${result.detail}`);
lines.push("");
lines.push(
`The worktree and branch \`${session.branch}\` have been preserved at ` +
`\`${session.worktreePath}\` for manual recovery.`
);
}
} else {
lines.push(`Discarded worktree \`${session.worktreePath}\` and branch \`${session.branch}\`.`);
}
console.log(lines.join("\n"));
}
async function handleTaskWorker(argv) {
const { options } = parseArgs(argv, {
valueOptions: ["job-id", "workspace", "task-text", "agent", "model", "resume-session"],
booleanOptions: ["write", "worktree"],
});
const workspace = options.workspace;
const jobId = options["job-id"];
const taskText = options["task-text"];
const agentName = options.agent ?? "build";
const isWrite = !!options.write;
const useWorktree = Boolean(options.worktree);
const resumeSessionId = options["resume-session"];
// Parent `handleTask` resolves --free/--model into a concrete
// provider/model-id string before spawning us, so the worker just
// needs to parse and forward it.
const workerModel = parseModelString(options.model);
if (!workspace || !jobId || !taskText) {
process.exit(1);
}
let worktreeSession = null;
let effectiveCwd = workspace;
if (useWorktree) {
try {
worktreeSession = await createWorktreeSession(workspace);
effectiveCwd = worktreeSession.worktreePath;
upsertJob(workspace, {
id: jobId,
worktreeSession: {
worktreePath: worktreeSession.worktreePath,
branch: worktreeSession.branch,
repoRoot: worktreeSession.repoRoot,
baseCommit: worktreeSession.baseCommit,
timestamp: worktreeSession.timestamp,
},
});
} catch (err) {
upsertJob(workspace, {
id: jobId,
status: "failed",
phase: "failed",
completedAt: new Date().toISOString(),
errorMessage: `Failed to create worktree: ${err.message}`,
});
process.exit(1);
}
}
let signalsHandled = false;
const handleSignal = async (signal) => {
if (signalsHandled) return;
signalsHandled = true;
upsertJob(workspace, {
id: jobId,
status: "failed",
completedAt: new Date().toISOString(),
errorMessage: `Worker terminated by ${signal}`,
});
if (worktreeSession) {