opencode-orchestra 0.0.0-stage → 1.1.0

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/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # opencode-orchestra
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Plugin OpenCode V2 (`@opencode/plugin`) yang menyediakan tiga *pipeline* orkestrasi multi-agen (`/boost`, `/teamwork`, `/swarm`) secara **model-agnostic**—mewarisi model aktif sesi OpenCode (atau *override* via `--model` / konfigurasi).
4
+
5
+ ## Perintah
6
+
7
+ | Perintah | Tool | Ringkasan Alur |
8
+ | --- | --- | --- |
9
+ | `/boost` | `boost` | `DeepCoder` / `DeepInvestigator` (Worker L0) → *Adversarial Improvement Worker* (*adaptive early-stop*) → *Orchestrator Spot-Check* (+ perbaikan jika gagal). |
10
+ | `/teamwork` | `teamwork` | Orkestrasi berbasis peran (`--swe`, `--review`, `--colosseum`, `--audit`, `--discover`) dengan *scoping interview* opsional (`--no-interview` / `[skip-interview]`), gerbang verifikasi paralel, dan persistensi milestone. |
11
+ | `/swarm` | `swarm` | Eksekusi *worker* paralel (`--fanout` / `--pipeline`) dengan *shared message board* multi-channel (`@mention` & *idle park-guard*) dan isolasi *git worktree* opsional (`--worktree`). |
12
+
13
+ ## Instalasi
14
+
15
+ ```sh
16
+ opencode plugin add opencode-orchestra@1.1.0
17
+ ```
18
+
19
+ Atau tambahkan ke `opencode.jsonc` proyek / `~/.config/opencode/opencode.jsonc`:
20
+
21
+ ```jsonc
22
+ {
23
+ "$schema": "https://opencode.ai/config.json",
24
+ "plugins": ["opencode-orchestra@1.1.0"]
25
+ }
26
+ ```
27
+
28
+ Gunakan `@latest` untuk mengikuti rilis terbaru (`opencode plugin update`). Cek status dengan `opencode plugin list` / `opencode plugin check`.
29
+
30
+ Untuk pengembangan lokal: `bun install && bun run build`, lalu tambahkan `"package": "./"` ke `plugins` pada config lokal (gunakan `"./"`, bukan `"."`).
31
+
32
+ ## Penggunaan
33
+
34
+ Perintah `/boost`, `/teamwork`, dan `/swarm` menjalankan pipeline di background tanpa menampilkan prompt internal. Setelah pemeriksaan oleh verifier independen, sesi utama menerima hasil atau informasi tentang kendala. Sidebar TUI menampilkan aktivitas Boost untuk sesi yang sedang dibuka.
35
+
36
+ ```text
37
+ /boost Perbaiki race condition di connection pool dan tambahkan stress test
38
+ /boost --investigate Telusuri kenapa request timeout melonjak di atas 2MB
39
+ /teamwork --swe --no-interview Implementasi rate limiter dengan unit test
40
+ /teamwork --colosseum --workers=3 Bandingkan Redis vs SQLite untuk session store
41
+ /swarm --fanout --workers=3 --worktree Analisis bottleneck latency di seluruh service
42
+ /swarm --pipeline --workers=3 Audit dan desain ulang alur autentikasi
43
+ ```
44
+
45
+ ## Dokumentasi
46
+
47
+ - [Daftar Isi Dokumentasi](docs/README.md)
48
+ - [Arsitektur & Cara Kerja](docs/architecture.md)
49
+ - [Konfigurasi, Opsi, Flag & Skema Tool](docs/configuration.md)
50
+ - [Catatan Reverse Engineering](docs/reverse-engineering.md)
@@ -0,0 +1,47 @@
1
+ export interface PluginStorage {
2
+ get(key: string): Promise<unknown>;
3
+ set(key: string, value: unknown): Promise<void>;
4
+ remove(key: string): Promise<void>;
5
+ }
6
+ export interface BoardPost {
7
+ seq: number;
8
+ author: string;
9
+ to?: string;
10
+ channel?: string;
11
+ mentions?: string[];
12
+ message: string;
13
+ timestamp: number;
14
+ }
15
+ export declare function parseMentions(message: string): string[];
16
+ export interface TeamworkRunState {
17
+ runId: string;
18
+ mode: string;
19
+ task: string;
20
+ status: "running" | "completed" | "failed";
21
+ milestones: Array<{
22
+ name: string;
23
+ status: "pending" | "in_progress" | "done" | "failed";
24
+ summary?: string;
25
+ }>;
26
+ updatedAt: number;
27
+ }
28
+ export declare function readBoard(storage: PluginStorage, boardId: string, afterSeq?: number, channel?: string): Promise<BoardPost[]>;
29
+ export declare function postToBoard(storage: PluginStorage, boardId: string, entry: Omit<BoardPost, "seq" | "timestamp">): Promise<BoardPost>;
30
+ export interface BoardHead {
31
+ boardId: string;
32
+ latestSeq: number;
33
+ totalPosts: number;
34
+ authors: string[];
35
+ channels: string[];
36
+ lastUpdatedAt?: number;
37
+ }
38
+ export declare function getBoardHead(storage: PluginStorage, boardId: string): Promise<BoardHead>;
39
+ export interface PeerWaitStatus {
40
+ boardId: string;
41
+ workerId: string;
42
+ latestSeq: number;
43
+ unreadForWorker: BoardPost[];
44
+ hasUnreadPeerActivity: boolean;
45
+ }
46
+ export declare function checkPeerWait(storage: PluginStorage, boardId: string, workerId: string, afterSeq?: number): Promise<PeerWaitStatus>;
47
+ export declare function saveTeamworkState(storage: PluginStorage, runId: string, state: TeamworkRunState): Promise<void>;
package/dist/board.js ADDED
@@ -0,0 +1,89 @@
1
+ export function parseMentions(message) {
2
+ const matches = message.matchAll(/(?:^|[^a-zA-Z0-9_])@([a-zA-Z0-9_-]+)/g);
3
+ const found = new Set();
4
+ for (const m of matches) {
5
+ if (m[1])
6
+ found.add(m[1]);
7
+ }
8
+ return Array.from(found);
9
+ }
10
+ function boardKey(boardId) {
11
+ return `swarm:board:${boardId}`;
12
+ }
13
+ function teamworkKey(runId) {
14
+ return `teamwork:run:${runId}`;
15
+ }
16
+ export async function readBoard(storage, boardId, afterSeq = 0, channel) {
17
+ const raw = await storage.get(boardKey(boardId));
18
+ if (!Array.isArray(raw))
19
+ return [];
20
+ return raw.filter((p) => typeof p?.seq === "number" &&
21
+ p.seq > afterSeq &&
22
+ (!channel || (p.channel ?? "general") === channel));
23
+ }
24
+ const boardWriteLocks = new Map();
25
+ export async function postToBoard(storage, boardId, entry) {
26
+ const prev = boardWriteLocks.get(boardId) ?? Promise.resolve();
27
+ const run = prev.catch(() => undefined).then(async () => {
28
+ const existing = await readBoard(storage, boardId, 0);
29
+ const nextSeq = existing.length > 0
30
+ ? Math.max(0, ...existing.map((p) => p.seq)) + 1
31
+ : 1;
32
+ const mentions = parseMentions(entry.message);
33
+ const post = {
34
+ seq: nextSeq,
35
+ author: entry.author,
36
+ ...(entry.to ? { to: entry.to } : {}),
37
+ ...(entry.channel ? { channel: entry.channel } : {}),
38
+ ...(mentions.length > 0 ? { mentions } : {}),
39
+ message: entry.message,
40
+ timestamp: Date.now(),
41
+ };
42
+ await storage.set(boardKey(boardId), [...existing, post]);
43
+ return post;
44
+ });
45
+ boardWriteLocks.set(boardId, run);
46
+ try {
47
+ return await run;
48
+ }
49
+ finally {
50
+ if (boardWriteLocks.get(boardId) === run) {
51
+ boardWriteLocks.delete(boardId);
52
+ }
53
+ }
54
+ }
55
+ export async function getBoardHead(storage, boardId) {
56
+ const posts = await readBoard(storage, boardId, 0);
57
+ const latestSeq = posts.length > 0 ? Math.max(0, ...posts.map((p) => p.seq)) : 0;
58
+ const authors = Array.from(new Set(posts.map((p) => p.author)));
59
+ const channels = Array.from(new Set(posts.map((p) => p.channel ?? "general")));
60
+ const lastUpdatedAt = posts.length > 0 ? posts[posts.length - 1]?.timestamp : undefined;
61
+ return {
62
+ boardId,
63
+ latestSeq,
64
+ totalPosts: posts.length,
65
+ authors,
66
+ channels,
67
+ ...(lastUpdatedAt !== undefined ? { lastUpdatedAt } : {}),
68
+ };
69
+ }
70
+ export async function checkPeerWait(storage, boardId, workerId, afterSeq = 0) {
71
+ const allNew = await readBoard(storage, boardId, afterSeq);
72
+ const latestSeq = allNew.length > 0 ? Math.max(afterSeq, ...allNew.map((p) => p.seq)) : afterSeq;
73
+ const unreadForWorker = allNew.filter((p) => p.author !== workerId &&
74
+ (!p.to ||
75
+ p.to === "all" ||
76
+ p.to === workerId ||
77
+ (Array.isArray(p.mentions) &&
78
+ (p.mentions.includes(workerId) || p.mentions.includes("all")))));
79
+ return {
80
+ boardId,
81
+ workerId,
82
+ latestSeq,
83
+ unreadForWorker,
84
+ hasUnreadPeerActivity: unreadForWorker.length > 0,
85
+ };
86
+ }
87
+ export async function saveTeamworkState(storage, runId, state) {
88
+ await storage.set(teamworkKey(runId), state);
89
+ }
@@ -0,0 +1,22 @@
1
+ import type { BoostSessionClient } from "./pipeline.js";
2
+ /**
3
+ * Extracts a concise summary of prior conversation turns from a parent session
4
+ * so delegated workers remain aware of earlier context when a slash command
5
+ * (e.g. /boost, /teamwork, /swarm) is invoked mid-conversation.
6
+ */
7
+ export declare function extractConversationContext(sessionClient: Pick<BoostSessionClient, "context">, sessionID: string, options?: {
8
+ maxTurns?: number;
9
+ maxChars?: number;
10
+ }): Promise<string | undefined>;
11
+ /**
12
+ * Combines explicit Orchestrator-supplied additionalContext with an optional
13
+ * parent-session fallback without duplicating content.
14
+ */
15
+ export declare function mergeAdditionalContext(explicit?: string, parentFallback?: string): string | undefined;
16
+ /**
17
+ * Heuristic check for whether a worker report still flags material unresolved
18
+ * issues (e.g. Fatal Functional Bug, Shallow Verification, Critical/Blocking
19
+ * findings, or failed verification verdicts) that warrant an extra improvement
20
+ * round when budget remains.
21
+ */
22
+ export declare function hasReportUnresolvedGaps(report: string): boolean;
@@ -0,0 +1,120 @@
1
+ const DEFAULT_MAX_TURNS = 6;
2
+ const DEFAULT_MAX_CHARS = 4000;
3
+ function extractMessageText(msg) {
4
+ return (msg.content ?? [])
5
+ .filter((p) => p.type === "text" && typeof p.text === "string")
6
+ .map((p) => p.text.trim())
7
+ .filter(Boolean)
8
+ .join("\n")
9
+ .trim();
10
+ }
11
+ /**
12
+ * Extracts a concise summary of prior conversation turns from a parent session
13
+ * so delegated workers remain aware of earlier context when a slash command
14
+ * (e.g. /boost, /teamwork, /swarm) is invoked mid-conversation.
15
+ */
16
+ export async function extractConversationContext(sessionClient, sessionID, options) {
17
+ const maxTurns = options?.maxTurns ?? DEFAULT_MAX_TURNS;
18
+ const maxChars = options?.maxChars ?? DEFAULT_MAX_CHARS;
19
+ let messages;
20
+ try {
21
+ messages = await sessionClient.context({ sessionID });
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ if (!Array.isArray(messages) || messages.length === 0) {
27
+ return undefined;
28
+ }
29
+ // Drop the active turn (the last user message — typically the slash-command /
30
+ // orchestrator prompt — plus any trailing assistant/tool-call messages) so we
31
+ // only capture *prior* conversation turns.
32
+ let endIndex = messages.length;
33
+ for (let i = messages.length - 1; i >= 0; i--) {
34
+ const msg = messages[i];
35
+ if (msg.type === "user") {
36
+ endIndex = i;
37
+ break;
38
+ }
39
+ }
40
+ const turns = [];
41
+ for (let i = Math.max(0, endIndex - maxTurns * 2); i < endIndex; i++) {
42
+ const msg = messages[i];
43
+ if (msg.type !== "user" && msg.type !== "assistant")
44
+ continue;
45
+ const text = extractMessageText(msg);
46
+ if (!text)
47
+ continue;
48
+ const role = msg.type === "user" ? "User" : "Assistant";
49
+ turns.push(`[${role}]: ${text}`);
50
+ }
51
+ if (turns.length === 0) {
52
+ return undefined;
53
+ }
54
+ const recent = turns.slice(-maxTurns);
55
+ let combined = recent.join("\n\n");
56
+ if (combined.length > maxChars) {
57
+ combined = `...(truncated)\n${combined.slice(combined.length - maxChars)}`;
58
+ }
59
+ return combined;
60
+ }
61
+ /**
62
+ * Combines explicit Orchestrator-supplied additionalContext with an optional
63
+ * parent-session fallback without duplicating content.
64
+ */
65
+ export function mergeAdditionalContext(explicit, parentFallback) {
66
+ const cleanExplicit = explicit?.trim();
67
+ const cleanFallback = parentFallback?.trim();
68
+ if (cleanExplicit && cleanFallback) {
69
+ return `${cleanExplicit}\n\n## Prior Conversation Excerpt\n${cleanFallback}`;
70
+ }
71
+ return cleanExplicit || cleanFallback || undefined;
72
+ }
73
+ /**
74
+ * Heuristic check for whether a worker report still flags material unresolved
75
+ * issues (e.g. Fatal Functional Bug, Shallow Verification, Critical/Blocking
76
+ * findings, or failed verification verdicts) that warrant an extra improvement
77
+ * round when budget remains.
78
+ */
79
+ export function hasReportUnresolvedGaps(report) {
80
+ if (!report.trim())
81
+ return true;
82
+ // Explicit failure verdicts anywhere in the report
83
+ if (/\bVERDICT\s*:\s*FAIL\b/i.test(report)) {
84
+ return true;
85
+ }
86
+ // Known Issues / Findings section
87
+ const knownIssuesMatch = report.match(/##\s*(?:\d+\.\s*)?(?:Known Issues|Remaining Issues|Findings)([\s\S]*?)(?=\n##\s|$)/i);
88
+ if (knownIssuesMatch) {
89
+ const body = (knownIssuesMatch[1] ?? "").trim();
90
+ if (body &&
91
+ !/^(?:-\s*)?(?:none|n\/a|no known issues)(?:\s*\([^)]*\))?\.?$/i.test(body)) {
92
+ if (/\bFatal Functional Bug\b/i.test(body) ||
93
+ /\bShallow Verification\b/i.test(body) ||
94
+ /\b(?:Critical|Blocking)\b/i.test(body)) {
95
+ return true;
96
+ }
97
+ }
98
+ }
99
+ // Verification Record section: flag non-empty Shallow Verification or Unverified aspects
100
+ const verificationMatch = report.match(/##\s*(?:\d+\.\s*)?Verification(?:\s+Record)?([\s\S]*?)(?=\n##\s|$)/i);
101
+ if (verificationMatch) {
102
+ const body = verificationMatch[1] ?? "";
103
+ const shallowLine = body.match(/Shallow Verification[^:\n]*:\s*(.+)/i);
104
+ if (shallowLine &&
105
+ shallowLine[1] &&
106
+ !/^(?:none|n\/a|no|nothing|-)\.?$/i.test(shallowLine[1].trim().replace(/^\*+|\*+$/g, "").trim())) {
107
+ return true;
108
+ }
109
+ }
110
+ // Remaining Questions & Gaps section (used by --investigate mode)
111
+ const remainingGapsMatch = report.match(/#{2,3}\s*(?:\*{0,2})(?:\d+\.\s*)?Remaining Questions(?:\s*(?:&|and)\s*Gaps)?(?:\*{0,2})([\s\S]*?)(?=\n#{2,3}\s|$)/i);
112
+ if (remainingGapsMatch) {
113
+ const body = (remainingGapsMatch[1] ?? "").trim();
114
+ if (body &&
115
+ !/^(?:-\s*)?(?:none|n\/a|no remaining (?:questions|gaps)(?:\s*(?:&|and)\s*gaps)?)(?:\s*\([^)]*\))?\.?$/i.test(body)) {
116
+ return true;
117
+ }
118
+ }
119
+ return false;
120
+ }
@@ -0,0 +1,24 @@
1
+ export type PipelineRole = "boost" | "teamwork" | "swarm";
2
+ export type VerificationMode = "coder" | "investigate" | "review" | "generic";
3
+ export interface VerificationOutcome {
4
+ status: "verified" | "blocked" | "inconclusive";
5
+ detail: string;
6
+ }
7
+ export interface CompletionSession {
8
+ synthetic(input: {
9
+ sessionID: string;
10
+ text: string;
11
+ resume: boolean;
12
+ }): Promise<unknown>;
13
+ }
14
+ export interface DispatchOptions {
15
+ session: CompletionSession;
16
+ sessionID: string;
17
+ role: PipelineRole;
18
+ task: string;
19
+ extra?: string[];
20
+ run: () => Promise<string>;
21
+ verify: (report: string) => Promise<VerificationOutcome>;
22
+ }
23
+ export declare function completionMessage(role: PipelineRole, runID: string, task: string, report: string, outcome: VerificationOutcome): string;
24
+ export declare function dispatchBackground(options: DispatchOptions): string;
@@ -0,0 +1,49 @@
1
+ export function completionMessage(role, runID, task, report, outcome) {
2
+ const header = outcome.status === "verified"
3
+ ? "Independent verification passed"
4
+ : outcome.status === "blocked"
5
+ ? "Bounded by a blocker"
6
+ : "Final evidence check required";
7
+ return [
8
+ `[Orchestra ${role} run ${runID} finished: ${header}]`,
9
+ `Original task: ${task}`,
10
+ ...(outcome.detail ? [`Verification: ${outcome.detail}`] : []),
11
+ "",
12
+ "FINAL EVIDENCE CHECK (required before replying): confirm the claims below that would change the answer with primary evidence from the workspace, rerunning the relevant tests for coding work.",
13
+ "Then reply ONLY with the answer to the original request, stated plainly and directly.",
14
+ "Omit any account of the process, who asserted what, mistakes, confidence language, or verification narrative. If a blocker truly prevents completion, state the specific blocker and what is needed, and nothing else.",
15
+ "",
16
+ "<untrusted_worker_report>",
17
+ report,
18
+ "</untrusted_worker_report>",
19
+ ].join("\n");
20
+ }
21
+ export function dispatchBackground(options) {
22
+ const { session, sessionID, role, task, run, verify } = options;
23
+ const runID = `${role}-${crypto.randomUUID()}`;
24
+ void Promise.resolve()
25
+ .then(run)
26
+ .then(async (report) => {
27
+ const outcome = await verify(report).catch((error) => ({
28
+ status: "inconclusive",
29
+ detail: `automatic verification error: ${error instanceof Error ? error.message : String(error)}`,
30
+ }));
31
+ return session.synthetic({
32
+ sessionID,
33
+ resume: true,
34
+ text: completionMessage(role, runID, task, report, outcome),
35
+ });
36
+ })
37
+ .catch((error) => session.synthetic({
38
+ sessionID,
39
+ resume: true,
40
+ text: [
41
+ `[Orchestra ${role} run ${runID} stopped: blocking failure]`,
42
+ `Original task: ${task}`,
43
+ `Error: ${error instanceof Error ? error.message : String(error)}`,
44
+ "Explain the specific blocker to the user. Do not present a result.",
45
+ ].join("\n"),
46
+ }))
47
+ .catch((error) => console.error(`Orchestra ${runID}: completion delivery failed`, error));
48
+ return runID;
49
+ }
@@ -0,0 +1,3 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+ declare const _default: Plugin.Plugin;
3
+ export default _default;