-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.js
More file actions
2130 lines (1838 loc) · 84.2 KB
/
task.js
File metadata and controls
2130 lines (1838 loc) · 84.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
import { tool } from "@opencode-ai/plugin";
import fs from "fs/promises";
import path from "path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
// --- MOE Auto-Assessment Helpers ---
async function callModelForAssessment(model, prompt) {
const slashIdx = model.indexOf("/");
const providerID = slashIdx > -1 ? model.slice(0, slashIdx) : "openai";
const modelID = slashIdx > -1 ? model.slice(slashIdx + 1) : model;
const providerConfigs = {
openai: { url: "https://api.openai.com/v1/chat/completions", key: process.env.OPENAI_API_KEY },
openrouter: { url: "https://openrouter.ai/api/v1/chat/completions", key: process.env.OPENROUTER_API_KEY },
anthropic: { url: "https://api.anthropic.com/v1/messages", key: process.env.ANTHROPIC_API_KEY },
};
const provider = providerConfigs[providerID];
if (!provider?.key) throw new Error(`No API key found for provider: ${providerID}`);
const res = await fetch(provider.url, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${provider.key}` },
body: JSON.stringify({
model: modelID,
messages: [{ role: "user", content: prompt }],
temperature: 0,
max_tokens: 1000,
}),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`API error ${res.status}: ${text}`);
}
const data = await res.json();
return providerID === "anthropic" ? data.content[0].text : data.choices[0].message.content;
}
const assessedMessages = new Set();
const execFileAsync = promisify(execFile);
const MAX_BUFFER = 20 * 1024 * 1024;
const MAX_ASSESSED_MESSAGES = 1000;
const QUESTION_RELAY_TTL_MS = 24 * 60 * 60 * 1000;
const COMPLETION_RETRY_INTERVAL_MS = 500;
const COMPLETION_RETRY_MAX_MS = 5000;
const STATE_FILE = "bg-task-state.json";
/**
* @type {import("@opencode-ai/plugin").Plugin}
*/
export default async (ctx) => {
const { client } = ctx;
const rootDirectory = ctx.worktree || ctx.directory;
const homeDirectory = process.env.HOME || rootDirectory;
let repositoryRoot = null;
try {
const { stdout } = await execFileAsync("git", ["-C", rootDirectory, "rev-parse", "--show-toplevel"], { maxBuffer: MAX_BUFFER });
repositoryRoot = stdout.trim() || null;
} catch {}
const artifactRoot = repositoryRoot
? path.join(repositoryRoot, ".opencode")
: path.join(homeDirectory, ".local", "share", "opencode", "background-task-artifacts");
const trackedSessions = new Map();
const reconciliations = new Map();
const delegatedSessionParents = new Map();
const taskIdToSessionId = new Map();
const pendingQuestionRelays = new Map();
const pendingQuestionRelaysBySession = new Map();
const agentsDirectory = path.join(homeDirectory, ".config", "opencode", "agents");
const taskArtifactsDirectory = artifactRoot;
const worktreesDirectory = path.join(taskArtifactsDirectory, "worktrees");
const patchesDirectory = path.join(taskArtifactsDirectory, "patches");
const stateFilePath = path.join(taskArtifactsDirectory, STATE_FILE);
const RESULT_PREFIX = "__OPENCODE_BACKGROUND_TASK_META__";
await fs.mkdir(taskArtifactsDirectory, { recursive: true });
await fs.mkdir(worktreesDirectory, { recursive: true });
await fs.mkdir(patchesDirectory, { recursive: true });
function pruneAssessedMessages() {
if (assessedMessages.size <= MAX_ASSESSED_MESSAGES) return;
const overflow = assessedMessages.size - MAX_ASSESSED_MESSAGES;
let removed = 0;
for (const id of assessedMessages) {
assessedMessages.delete(id);
removed += 1;
if (removed >= overflow) break;
}
}
function purgeStaleQuestionRelays() {
const cutoff = Date.now() - QUESTION_RELAY_TTL_MS;
for (const relay of pendingQuestionRelays.values()) {
if ((relay.createdAt || 0) < cutoff) {
deletePendingQuestionRelay(relay);
}
}
}
function serializeMap(map) {
return Array.from(map.entries());
}
function deserializeMap(entries) {
return new Map(Array.isArray(entries) ? entries : []);
}
async function persistTaskState() {
const payload = {
trackedSessions: serializeMap(trackedSessions),
reconciliations: serializeMap(reconciliations),
delegatedSessionParents: serializeMap(delegatedSessionParents),
taskIdToSessionId: serializeMap(taskIdToSessionId),
pendingQuestionRelays: serializeMap(pendingQuestionRelays),
};
await fs.writeFile(stateFilePath, JSON.stringify(payload, null, 2), "utf8");
}
async function loadPersistedTaskState() {
try {
const raw = await fs.readFile(stateFilePath, "utf8");
const parsed = JSON.parse(raw);
for (const [key, value] of deserializeMap(parsed.trackedSessions)) trackedSessions.set(key, value);
for (const [key, value] of deserializeMap(parsed.reconciliations)) reconciliations.set(key, value);
for (const [key, value] of deserializeMap(parsed.delegatedSessionParents)) delegatedSessionParents.set(key, value);
for (const [key, value] of deserializeMap(parsed.taskIdToSessionId)) taskIdToSessionId.set(key, value);
for (const [key, value] of deserializeMap(parsed.pendingQuestionRelays)) {
pendingQuestionRelays.set(key, value);
if (value?.childSessionID) pendingQuestionRelaysBySession.set(value.childSessionID, value);
}
} catch (error) {
if (error.code !== "ENOENT") {
console.error("[task] Failed to load persisted task state:", error.message);
}
}
}
async function sweepStaleWorktrees() {
// Collect all session IDs currently referenced by live state
const liveSessionIds = new Set();
for (const [sessionID, tracked] of trackedSessions.entries()) {
if (tracked?.status === "active") liveSessionIds.add(sessionID);
}
for (const [sessionID, rec] of reconciliations.entries()) {
// Keep any reconciliation that is NOT already cleaned - user may still want to inspect/apply
if (rec?.reconcileStatus && rec.reconcileStatus !== "cleaned") liveSessionIds.add(sessionID);
}
// Build set of live workspacePaths from tracked + reconciliations
const liveWorkspacePaths = new Set();
for (const tracked of trackedSessions.values()) {
if (tracked?.workspacePath && liveSessionIds.has(tracked.sessionID || "")) {
liveWorkspacePaths.add(tracked.workspacePath);
}
}
for (const [sessionID, rec] of reconciliations.entries()) {
if (rec?.workspacePath && liveSessionIds.has(sessionID)) {
liveWorkspacePaths.add(rec.workspacePath);
}
}
// Read worktreesDirectory; for each task-* dir not in liveWorkspacePaths, attempt cleanup
let entries;
try {
entries = await fs.readdir(worktreesDirectory, { withFileTypes: true });
} catch (error) {
if (error.code !== "ENOENT") {
await logApp("warn", "Failed to read worktrees directory during sweep", { error: error.message, worktreesDirectory });
}
return;
}
let removed = 0;
let errors = 0;
const STALE_AGE_MS = 60 * 60 * 1000; // 1 hour grace period to avoid removing freshly-created worktrees mid-init
for (const entry of entries) {
if (!entry.isDirectory()) continue;
if (!entry.name.startsWith("task-")) continue;
const fullPath = path.join(worktreesDirectory, entry.name);
if (liveWorkspacePaths.has(fullPath)) continue;
// Grace period: skip if directory was modified within last hour (another session may own it)
try {
const stats = await fs.stat(fullPath);
if (Date.now() - stats.mtimeMs < STALE_AGE_MS) continue;
} catch {
continue; // gone already
}
// Find the parent repo from the .git pointer file inside the worktree
let parentRepo = null;
let branchName = null;
try {
const gitPointer = await fs.readFile(path.join(fullPath, ".git"), "utf8");
const match = gitPointer.match(/^gitdir:\s*(.+)$/m);
if (match) {
// gitdir path looks like: /path/to/repo/.git/worktrees/task-xxx
const gitdir = match[1].trim();
const wtName = path.basename(gitdir);
branchName = `opencode-${wtName}`;
// parent repo = dirname(dirname(dirname(gitdir))) since gitdir = <repo>/.git/worktrees/<name>
parentRepo = path.dirname(path.dirname(path.dirname(gitdir)));
}
} catch {}
// Try git worktree remove first (proper cleanup)
let removeOk = false;
if (parentRepo) {
try {
await runGit(parentRepo, ["worktree", "remove", "--force", fullPath]);
removeOk = true;
} catch (error) {
await logApp("warn", "git worktree remove failed during sweep", { error: error.message, fullPath, parentRepo });
}
// Prune stale refs in case the dir was already gone
try { await runGit(parentRepo, ["worktree", "prune"]); } catch {}
// Delete the branch if it exists
if (branchName) {
try { await runGit(parentRepo, ["branch", "-D", branchName]); } catch {}
}
}
// Fallback: if git cleanup didn't work, rm -rf the directory
if (!removeOk) {
try {
await fs.rm(fullPath, { recursive: true, force: true });
} catch (error) {
errors += 1;
await logApp("warn", "Failed to rm stale worktree directory", { error: error.message, fullPath });
continue;
}
}
removed += 1;
}
if (removed > 0 || errors > 0) {
await logApp("info", "Swept stale worktrees on startup", { removed, errors, worktreesDirectory });
}
}
async function purgeStaleReconciliations() {
const STALE_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
let purged = 0;
for (const [sessionID, rec] of reconciliations.entries()) {
const completedAt = rec.completedAt || rec.cleanedAt || rec.reconciledAt || Date.now();
if (Date.now() - completedAt > STALE_AGE_MS) {
if (["cleaned", "no-changes", "external-only", "cancelled"].includes(rec.reconcileStatus)) {
reconciliations.delete(sessionID);
removeTaskMappingsForSession(sessionID);
removeDelegationStateForSession(sessionID);
purged += 1;
}
}
}
if (purged > 0) {
await persistTaskState();
await logApp("info", "Auto-purged stale reconciliations", { purged });
}
}
async function withPersistedState(mutator) {
const result = await mutator();
await persistTaskState();
return result;
}
async function logApp(level, message, extra = {}) {
try {
await client.app.log({
body: {
service: "bg_task",
level,
message,
extra,
},
});
} catch {}
}
async function loadOpenCodePermissionConfig() {
try {
const rawConfig = await fs.readFile(path.join(homeDirectory, ".config", "opencode", "opencode.json"), "utf8");
const config = JSON.parse(rawConfig);
return config.permission;
} catch (error) {
await logApp("warn", "Failed to load OpenCode permission config for background task auto-approval", { error: error.message });
return undefined;
}
}
function permissionPatternToRegExp(pattern) {
let result = "^";
for (const char of String(pattern)) {
if (char === "*") {
result += ".*";
continue;
}
if (char === "?") {
result += ".";
continue;
}
result += escapeRegExp(char);
}
result += "$";
return new RegExp(result);
}
function permissionPatternMatches(rulePattern, requestedPattern) {
const rule = String(rulePattern || "");
const requested = String(requestedPattern || "");
return permissionPatternToRegExp(rule).test(requested) || permissionPatternToRegExp(requested).test(rule);
}
function resolvePermissionAction(permissionConfig, permissionType, requestedPatterns = []) {
if (!permissionConfig) return undefined;
if (typeof permissionConfig === "string") return permissionConfig;
if (typeof permissionConfig !== "object") return undefined;
const patterns = Array.isArray(requestedPatterns) ? requestedPatterns : [requestedPatterns];
let action = typeof permissionConfig["*"] === "string" ? permissionConfig["*"] : undefined;
const typeConfig = permissionConfig[permissionType];
if (typeof typeConfig === "string") return typeConfig;
if (!typeConfig || typeof typeConfig !== "object") return action;
for (const [rulePattern, ruleAction] of Object.entries(typeConfig)) {
if (!patterns.length || patterns.some((pattern) => permissionPatternMatches(rulePattern, pattern))) {
action = ruleAction;
}
}
return action;
}
async function maybeAutoReplyToChildPermission(event) {
const permission = event?.properties;
const childSessionID = permission?.sessionID;
if (!childSessionID || !permission?.id || !trackedSessions.has(childSessionID)) return false;
const permissionConfig = await loadOpenCodePermissionConfig();
const requestedPatterns = permission.pattern === undefined
? []
: Array.isArray(permission.pattern) ? permission.pattern : [permission.pattern];
const action = resolvePermissionAction(permissionConfig, permission.type, requestedPatterns);
if (action !== "allow" && action !== "deny") return false;
try {
await client.postSessionIdPermissionsPermissionId({
path: { id: childSessionID, permissionID: permission.id },
body: { response: action === "allow" ? "always" : "reject" },
});
await logApp("info", "Auto-replied to delegated session permission request", {
childSessionID,
permissionID: permission.id,
permissionType: permission.type,
patterns: requestedPatterns,
action,
});
return true;
} catch (error) {
await logApp("error", "Failed to auto-reply to delegated session permission request", {
childSessionID,
permissionID: permission.id,
permissionType: permission.type,
patterns: requestedPatterns,
action,
error: error.message,
});
return false;
}
}
async function reconcileStaleSessions() {
const activeTasks = Array.from(trackedSessions.entries()).filter(([, tracked]) => tracked.status === "active");
if (!activeTasks.length) return;
await logApp("info", "Checking active background tasks status on startup...", { count: activeTasks.length });
let statusMap = {};
try {
const statusResult = await client.session.status();
statusMap = unwrapSessionRecord(statusResult) || {};
} catch (error) {
await logApp("warn", "Failed to retrieve sessions status map on startup", { error: error.message });
}
for (const [sessionID, tracked] of activeTasks) {
try {
const { data: messages } = await client.session.messages({ path: { id: sessionID }, query: { limit: 100 } });
const result = extractFinalResult(messages);
if (result) {
await logApp("info", `Background task completed while offline: ${tracked.title}`, { sessionID });
await queueCompletion(tracked, sessionID);
} else {
const sessionStatus = statusMap[sessionID];
if (!sessionStatus || sessionStatus.type === "idle") {
await logApp("info", `Reconciling stale/idle background task: ${tracked.title}`, { sessionID, sessionStatus });
const artifacts = await collectCompletionArtifacts(tracked);
await markTaskNeedsAttention(tracked, sessionID, "Task session went idle or became unavailable without producing final result.", artifacts);
}
}
} catch (error) {
await logApp("warn", `Failed to retrieve session messages for task: ${tracked.title}`, { sessionID, error: error.message });
const artifacts = await collectCompletionArtifacts(tracked);
await markTaskNeedsAttention(tracked, sessionID, `Task session is unavailable: ${error.message}`, artifacts);
}
}
}
async function ensureServerReady(maxRetries = 10, delayMs = 500) {
for (let i = 0; i < maxRetries; i++) {
try {
await client.session.status();
return true;
} catch (error) {
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
return false;
}
await loadPersistedTaskState();
setTimeout(async () => {
try {
const ready = await ensureServerReady();
if (!ready) {
await logApp("warn", "OpenCode server did not become ready in time for background task reconciliation");
}
await reconcileStaleSessions();
await sweepStaleWorktrees();
await purgeStaleReconciliations();
} catch (err) {
await logApp("error", "Background task startup actions failed", { error: err.message, stack: err.stack });
}
}, 100);
function normalizeAgentKey(value = "") {
return value
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
function parseFrontmatterValue(source, key) {
const match = source.match(new RegExp(`^${key}:\\s*(.+)$`, "m"));
return match?.[1]?.trim();
}
function parseModelString(model) {
if (!model || !model.includes("/")) return undefined;
const divider = model.indexOf("/");
return {
providerID: model.slice(0, divider),
modelID: model.slice(divider + 1),
};
}
function uniq(values) {
return Array.from(new Set(values.filter(Boolean)));
}
function toPosixPath(value) {
return value.split(path.sep).join("/");
}
function hasGlobSyntax(value = "") {
return /[*?{}\[\]]/.test(value);
}
function normalizeTarget(target, root = rootDirectory) {
if (!target) return "";
const trimmed = target.trim();
if (!trimmed) return "";
const looksAbsolute = path.isAbsolute(trimmed);
const resolved = looksAbsolute ? path.normalize(trimmed) : path.normalize(path.join(root, trimmed));
const normalizedRoot = path.normalize(root);
if (resolved.startsWith(normalizedRoot + path.sep) || resolved === normalizedRoot) {
return toPosixPath(path.relative(normalizedRoot, resolved)) || ".";
}
return toPosixPath(trimmed.replace(/^\.\//, ""));
}
function escapeRegExp(value) {
return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
}
function globToRegExp(pattern) {
let result = "^";
for (let index = 0; index < pattern.length; index += 1) {
const char = pattern[index];
const next = pattern[index + 1];
if (char === "*" && next === "*") {
result += ".*";
index += 1;
continue;
}
if (char === "*") {
result += "[^/]*";
continue;
}
if (char === "?") {
result += "[^/]";
continue;
}
result += escapeRegExp(char);
}
result += "$";
return new RegExp(result);
}
function globPrefix(pattern) {
const match = pattern.match(/^[^*?{\[]+/);
return match ? match[0].replace(/\/+$/, "") : "";
}
function targetsOverlap(left, right) {
if (!left.length || !right.length) return true;
for (const first of left) {
for (const second of right) {
if (first === second) return true;
const firstGlob = hasGlobSyntax(first);
const secondGlob = hasGlobSyntax(second);
if (!firstGlob && !secondGlob) continue;
if (firstGlob && !secondGlob && globToRegExp(first).test(second)) return true;
if (!firstGlob && secondGlob && globToRegExp(second).test(first)) return true;
if (firstGlob && secondGlob) {
const firstPrefix = globPrefix(first);
const secondPrefix = globPrefix(second);
if (!firstPrefix || !secondPrefix) return true;
if (firstPrefix.startsWith(secondPrefix) || secondPrefix.startsWith(firstPrefix)) return true;
}
}
}
return false;
}
function describeTargets(targets) {
if (!targets?.length) return "(no explicit targets)";
return targets.join(", ");
}
function normalizeTargets(targets, root) {
return uniq((targets || []).map((target) => normalizeTarget(target, root)));
}
function isTargetInsideRoot(target, root) {
if (!target || !root) return false;
const resolved = path.isAbsolute(target) ? path.normalize(target) : path.normalize(path.join(root, target));
const normalizedRoot = path.normalize(root);
return resolved === normalizedRoot || resolved.startsWith(normalizedRoot + path.sep);
}
async function verifyExternalTargets(targets, root) {
const externalTargets = (targets || []).filter((target) => !hasGlobSyntax(target) && !isTargetInsideRoot(target, root));
if (!externalTargets.length) {
return { externalTargets: [], existingTargets: [] };
}
const existingTargets = [];
for (const target of externalTargets) {
const resolved = path.isAbsolute(target) ? path.normalize(target) : path.normalize(path.join(root, target));
try {
await fs.stat(resolved);
existingTargets.push(toPosixPath(resolved));
} catch {}
}
return { externalTargets, existingTargets };
}
async function verifyExternalTargetsInWorkspace(targets, workspacePath, root) {
const externalTargets = (targets || []).filter((target) => !hasGlobSyntax(target) && !isTargetInsideRoot(target, root));
if (!externalTargets.length) {
return { externalTargets: [], existingTargets: [] };
}
const existingTargets = [];
for (const target of externalTargets) {
const workspaceRelative = target.replace(/^\/+/, "");
const candidatePaths = [
path.join(workspacePath, workspaceRelative),
path.join(workspacePath, target),
];
for (const candidate of candidatePaths) {
try {
await fs.stat(candidate);
existingTargets.push(toPosixPath(candidate));
break;
} catch {}
}
}
return { externalTargets, existingTargets };
}
async function verifyExternalTargetsOnHost(targets, root) {
const externalTargets = (targets || []).filter((target) => !hasGlobSyntax(target) && !isTargetInsideRoot(target, root));
if (!externalTargets.length) {
return { externalTargets: [], existingTargets: [] };
}
const existingTargets = [];
for (const target of externalTargets) {
const resolved = path.isAbsolute(target) ? path.normalize(target) : path.normalize(path.join(root, target));
try {
await fs.stat(resolved);
existingTargets.push(toPosixPath(resolved));
} catch {}
}
return { externalTargets, existingTargets };
}
function cleanTargetToken(value = "") {
return value
.trim()
.replace(/^[`'"([{<]+/, "")
.replace(/[`'"\])}>.,;:!?]+$/, "")
.replace(/^\.\//, "");
}
function looksLikeTargetToken(value = "") {
if (!value) return false;
if (value.startsWith("--")) return false;
if (value.includes("://")) return false;
if (["HEAD", "true", "false", "null", "undefined"].includes(value)) return false;
const hasPathSeparator = value.includes("/") || value.includes("\\");
const hasExtension = /\.[a-z0-9]{1,10}$/i.test(value);
const hasGlob = hasGlobSyntax(value);
const hasKnownPrefix = /^(src|app|lib|test|tests|spec|specs|docs|scripts|packages|components|pages|routes|api|db|migrations|plugins|agents)\//.test(value);
return hasGlob || hasExtension || hasPathSeparator || hasKnownPrefix;
}
function extractTargetsFromText(text, root) {
if (!text) return [];
const collected = [];
const quotedPattern = /[`'\"]([^`'\"\n]+)[`'\"]/g;
for (const match of text.matchAll(quotedPattern)) {
collected.push(match[1]);
}
const tokenPattern = /(^|\s)([^\s]+)/g;
for (const match of text.matchAll(tokenPattern)) {
collected.push(match[2]);
}
return normalizeTargets(
collected
.map(cleanTargetToken)
.filter(looksLikeTargetToken),
root,
);
}
function inferTargets({ description, prompt, command }, root) {
return uniq([
...extractTargetsFromText(description, root),
...extractTargetsFromText(prompt, root),
...extractTargetsFromText(command, root),
]).slice(0, 25);
}
async function loadAgentCatalog() {
const entries = await fs.readdir(agentsDirectory);
const files = entries.filter((entry) => entry.endsWith(".md"));
const catalog = await Promise.all(
files.map(async (file) => {
const name = path.basename(file, ".md");
const source = await fs.readFile(path.join(agentsDirectory, file), "utf8");
const descriptionLine = parseFrontmatterValue(source, "description") || "Specialized agent";
const aliasSection = descriptionLine.match(/also known as:\s*(.+)$/i)?.[1] || "";
const description = descriptionLine.replace(/\s*also known as:.*$/i, "").trim();
const aliases = aliasSection
.split(",")
.map((item) => item.trim())
.filter(Boolean);
if (name === "build") aliases.push("code");
const mode = parseFrontmatterValue(source, "mode");
return {
name,
description,
variant: parseFrontmatterValue(source, "variant"),
model: parseModelString(parseFrontmatterValue(source, "model")),
aliases: Array.from(new Set([name, ...aliases])),
mode,
};
}),
);
return catalog
.filter((agent) => !agent.mode || agent.mode === "all" || agent.mode === "subagent")
.sort((a, b) => a.name.localeCompare(b.name));
}
const agentCatalog = await loadAgentCatalog();
let moeAssessmentModel = null;
async function getMoeAssessmentModel() {
if (moeAssessmentModel) return moeAssessmentModel;
try {
const rawConfig = await fs.readFile(path.join(homeDirectory, ".config", "opencode", "opencode.json"), "utf8");
const config = JSON.parse(rawConfig);
moeAssessmentModel = config.small_model || null;
} catch (e) {
// silently fall back to default — JSON parsing errors are not actionable for this plugin
}
return moeAssessmentModel;
}
function resolveAgent(requestedAgent) {
const normalized = normalizeAgentKey(requestedAgent);
return agentCatalog.find((agent) =>
agent.aliases.some((alias) => normalizeAgentKey(alias) === normalized),
);
}
function buildTaskDescription() {
const agentList = agentCatalog
.map((agent) => `- ${agent.name}: ${agent.description}`)
.join("\n");
return [
"Launch a new agent to handle complex, multistep tasks autonomously in the background. This allows the current conversation to continue immediately while the task runs asynchronously. Results are queued back here when complete.",
"",
"Selection policy:",
"- Choose the most specialized agent whose primary mission matches the requested deliverable.",
"- Base the choice on the main output needed (tests, docs, planning, research, exploration, implementation, frontend, infrastructure, database work, etc.), not just on whether the task broadly involves code.",
"- Prefer a specialist over a generalist when one agent is clearly a closer semantic match.",
"- Use staff-engineer as the fallback for mixed or ambiguous coding work, not as the default for every technical task.",
"",
"Concurrency & workspace policy:",
"- For editing tasks, provide targets whenever possible so the task system can detect overlapping file claims.",
"- Root sessions can fan out multiple tasks in parallel as long as their claimed targets do not overlap.",
"- Child sessions cannot delegate further; send follow-on delegation back to the root/orchestrator session.",
"- If a child session asks a question, the plugin relays it back to the parent session. Answer it with bg_task_question_reply or inspect pending items with bg_task_question_list.",
"- In non-git workspaces, parallel shared tasks without distinct explicit targets are treated as overlapping. To fan out multiple tasks there, give each task unique targets.",
"- mode=auto will use the main workspace when claims are non-overlapping, and will prefer an isolated git worktree when file claims are missing or overlapping.",
"- mode=shared keeps the task in the main workspace and should only be used when you are confident the task will not overlap active edits.",
"- mode=isolated forces the task into a dedicated git worktree when the project is a git repository.",
"",
"Available subagents:",
agentList,
].join("\n");
}
function unwrapSessionRecord(result) {
if (!result || typeof result !== "object") {
return result;
}
if ("data" in result && result.data) {
return unwrapSessionRecord(result.data);
}
if ("info" in result && result.info) {
return unwrapSessionRecord(result.info);
}
return result;
}
function requireSessionRecord(result, source) {
const session = unwrapSessionRecord(result);
if (!session || typeof session !== "object" || !session.id) {
const responseError = result && typeof result === "object" && "error" in result && result.error
? ` Response error: ${result.error.message || JSON.stringify(result.error)}.`
: "";
throw new Error(`${source} did not return a session object with an id.${responseError}`);
}
return session;
}
function extractParentContinuation(messages) {
for (const msg of [...messages].reverse()) {
if (msg.info?.role !== "user") continue;
if (msg.info?.model) {
return { agent: msg.info.agent, model: msg.info.model, variant: msg.info.variant };
}
}
for (const msg of [...messages].reverse()) {
if (msg.info?.role !== "assistant") continue;
if (msg.info?.providerID && msg.info?.modelID) {
return {
agent: msg.info.agent,
model: { providerID: msg.info.providerID, modelID: msg.info.modelID },
variant: msg.info.variant,
};
}
}
const lastUser = [...messages].reverse().find((message) => message.info?.role === "user");
if (lastUser) {
return { agent: lastUser.info.agent, model: lastUser.info.model, variant: lastUser.info.variant };
}
return {};
}
function extractFinalResult(messages) {
const finalMessage = [...messages].reverse().find((message) => {
if (message.info?.role !== "assistant") return false;
if (message.info.error) return true;
return Boolean(message.info.finish) && !["tool-calls", "unknown"].includes(message.info.finish);
});
if (!finalMessage) return null;
const text = finalMessage.parts
.filter((part) => part.type === "text" && !part.synthetic)
.map((part) => part.text.trim())
.filter(Boolean)
.join("\n\n");
const errorMessage = finalMessage.info.error?.data?.message || finalMessage.info.error?.name;
return {
errorMessage,
text: text || (errorMessage ? "" : "Task completed with no text output."),
agent: finalMessage.info.agent,
modelID: finalMessage.info.modelID,
};
}
function encodeToolResult({ title, metadata = {}, output }) {
const payload = Buffer.from(JSON.stringify({ title, metadata }), "utf8").toString("base64");
return `${RESULT_PREFIX}${payload}\n${output}`;
}
function decodeToolResult(output = "") {
if (!output.startsWith(RESULT_PREFIX)) return null;
const newline = output.indexOf("\n");
const encoded = newline === -1 ? output.slice(RESULT_PREFIX.length) : output.slice(RESULT_PREFIX.length, newline);
const visibleOutput = newline === -1 ? "" : output.slice(newline + 1);
try {
const parsed = JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
return {
title: parsed?.title,
metadata: parsed?.metadata || {},
output: visibleOutput,
};
} catch {
return null;
}
}
async function waitForSessionBootstrap(sessionID, timeoutMs = 1500) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const { data: messages } = await client.session.messages({
path: { id: sessionID },
query: { limit: 5 },
});
if (messages?.length) return true;
} catch {}
await new Promise((resolve) => setTimeout(resolve, 100));
}
return false;
}
async function runGit(cwd, args) {
return execFileAsync("git", ["-C", cwd, ...args], { maxBuffer: MAX_BUFFER });
}
async function getRepositoryRoot() {
try {
const { stdout } = await runGit(rootDirectory, ["rev-parse", "--show-toplevel"]);
return stdout.trim();
} catch {
return null;
}
}
function buildWorktreeToken() {
return `task-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
async function createIsolatedWorkspace(repositoryRoot) {
const token = buildWorktreeToken();
const branchName = `opencode-${token}`;
const workspacePath = path.join(worktreesDirectory, token);
await runGit(repositoryRoot, ["worktree", "add", "-b", branchName, workspacePath, "HEAD"]);
return {
workspacePath,
branchName,
baseRef: "HEAD",
};
}
async function safeRemoveWorktree(repositoryRoot, workspacePath) {
if (!repositoryRoot || !workspacePath) return;
await runGit(repositoryRoot, ["worktree", "remove", "--force", workspacePath]);
}
async function safeDeleteBranch(repositoryRoot, branchName) {
if (!repositoryRoot || !branchName) return;
await runGit(repositoryRoot, ["branch", "-D", branchName]);
}
function findConflicts(targets, sessionToIgnore) {
const conflicts = [];
for (const [sessionID, tracked] of trackedSessions.entries()) {
if (sessionID === sessionToIgnore) continue;
if (tracked.status !== "active") continue;
if (targetsOverlap(targets, tracked.claimedTargets)) {
conflicts.push({
sessionID,
title: tracked.title,
mode: tracked.effectiveMode,
targets: tracked.claimedTargets,
});
}
}
return conflicts;
}
async function listTrackedFiles(cwd) {
const [diffResult, untrackedResult] = await Promise.allSettled([
runGit(cwd, ["diff", "--name-only", "HEAD"]),
runGit(cwd, ["ls-files", "--others", "--exclude-standard"]),
]);
const changed = [];
if (diffResult.status === "fulfilled") {
changed.push(...diffResult.value.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
}
if (untrackedResult.status === "fulfilled") {
changed.push(...untrackedResult.value.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
}
return uniq(changed.map((file) => toPosixPath(file)));
}
async function collectCompletionArtifacts(tracked) {
const artifact = {
changedFiles: [],
patchPath: undefined,
reconcileStatus: undefined,
verificationStatus: "summary-only",
externalTargets: [],
};
const externalCheckRoot = tracked.repositoryRoot || rootDirectory;
const claimedTargets = tracked.claimedTargets || [];
const [workspaceExternalVerification, hostExternalVerification] = await Promise.all([
tracked.workspacePath
? verifyExternalTargetsInWorkspace(claimedTargets, tracked.workspacePath, externalCheckRoot)
: Promise.resolve({ externalTargets: [], existingTargets: [] }),
verifyExternalTargetsOnHost(claimedTargets, externalCheckRoot),
]);
const externalTargets = uniq([
...workspaceExternalVerification.existingTargets,
...hostExternalVerification.existingTargets,
]);
artifact.externalTargets = externalTargets;