-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtri-agent-router.ts
More file actions
620 lines (534 loc) · 24.3 KB
/
tri-agent-router.ts
File metadata and controls
620 lines (534 loc) · 24.3 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
import type { Plugin } from "@opencode-ai/plugin"
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"
import { basename, join, resolve } from "node:path"
import { homedir } from "node:os"
type AgentCard = {
id: string
name: string
description: string
path: string
verifier?: boolean
}
type SkillCard = {
id: string
name: string
description: string
path: string
}
type Selection = {
originalText: string
routedText: string
summary: string
}
type SessionState = {
mode: "ask" | "always" | "autonomous"
disabled: boolean
pending?: Selection
}
type ApprovalDecision = "approve" | "deny" | "always" | "autonomous approve" | "add/remove" | "cancel" | "never"
type PersistentRouterState = {
globalAutonomousApproval?: boolean
}
type RouterOptions = {
agentDirs?: string[]
skillDirs?: string[]
maxSkills?: number
minSkillScore?: number
announceNoSkills?: boolean
requireApproval?: boolean
}
const VERIFIER_TERMS = [
"review",
"reviewer",
"qa",
"quality",
"test",
"tester",
"audit",
"auditor",
"security",
"reality",
"compliance",
"accessibility",
]
const GENERAL_VERIFIERS = [
"code-reviewer",
"test-results-analyzer",
"model-qa-specialist",
"reality-checker",
"accessibility-auditor",
"compliance-auditor",
"security-engineer",
]
const APPROVAL_OPTIONS = [
{
label: "Yes",
description: "Approve this selection, just this once.",
},
{
label: "Always",
description: "Never ask again. Just start the job when approval is needed.",
},
{
label: "Change agents",
description: "Pick different agents for this request.",
},
]
const PERSISTENCE_DIR = join(homedir(), ".config", "opencode")
const PERSISTENCE_PATH = join(PERSISTENCE_DIR, "tri-agent-router-state.json")
const DOMAIN_HINTS: Record<string, string[]> = {
frontend: ["ui", "ux", "css", "react", "vue", "angular", "svelte", "frontend", "browser", "web page", "component", "layout", "animation"],
backend: ["api", "server", "backend", "database", "db", "postgres", "mysql", "auth", "endpoint", "service", "microservice"],
security: ["security", "vulnerability", "exploit", "auth", "permission", "secret", "token", "audit", "compliance"],
testing: ["test", "qa", "verify", "validation", "playwright", "jest", "vitest", "unit", "e2e", "bug", "failure"],
docs: ["docs", "documentation", "readme", "write", "copy", "article", "guide", "manual", "changelog"],
data: ["data", "etl", "pipeline", "analytics", "csv", "warehouse", "report", "dashboard", "sql"],
devops: ["deploy", "ci", "cd", "docker", "kubernetes", "infra", "cloud", "monitoring", "sre", "pipeline"],
mobile: ["ios", "android", "mobile", "react native", "flutter", "app store"],
game: ["game", "unity", "unreal", "godot", "roblox", "shader", "level"],
product: ["product", "roadmap", "requirements", "prioritize", "mvp", "spec"],
marketing: ["seo", "ads", "campaign", "marketing", "social", "content", "brand", "growth"],
}
const GENERIC_SKILL_TOKENS = new Set([
"add", "all", "and", "api", "app", "ask", "build", "code", "create", "data",
"file", "for", "from", "get", "help", "implement", "make", "need", "new", "now",
"request", "task", "test", "that", "the", "this", "use", "using", "want", "with",
])
const SKILL_HINTS: Record<string, string[]> = {
"browser-automation-agent": ["browser", "web ui", "click", "form", "screenshot", "playwright", "scrape", "automation", "navigate"],
context7: ["library", "framework", "docs", "documentation", "api", "sdk", "package", "current", "examples"],
"solana-dev": ["solana", "anchor", "wallet", "devnet", "token", "pda", "program", "rent"],
"auth-login": ["google login", "google auth", "oauth", "authenticate", "login", "account"],
"task-management": ["task", "todo", "plan", "feature", "milestone", "track", "subtask"],
"code-review": ["review", "audit", "bug", "risk", "quality", "security"],
"plan-review": ["plan", "review plan", "architecture", "approach", "proposal"],
"plan-protocol": ["plan", "protocol", "workflow", "steps", "strategy"],
"frontend-philosophy": ["frontend", "ui", "ux", "css", "design", "component"],
"web-interface-guidelines-review": ["interface review", "ui review", "ux review", "accessibility", "design review"],
"using-web-scraping": ["scrape", "crawler", "website", "extract", "html", "browser"],
"web-search-api": ["search web", "web search", "find online", "current info", "research"],
"pdf-manipulation": ["pdf", "merge pdf", "split pdf", "extract pdf"],
"changelog-generator": ["changelog", "release notes", "git history"],
"database-query-and-export": ["database", "sql", "database query", "query database"],
"csv-data-summarizer": ["summarize csv", "csv summary", "analyze csv", "spreadsheet summary"],
"json-and-csv-data-transformation": ["json", "csv", "transform", "convert"],
"send-email-programmatically": ["email", "smtp", "send mail"],
"using-telegram-bot": ["telegram", "bot"],
"using-youtube-download": ["youtube", "video", "download"],
"free-weather-data": ["weather", "forecast"],
"free-translation-api": ["translate", "translation", "language"],
"free-geocoding-and-maps": ["geocode", "map", "address", "location", "distance"],
"city-distance": ["city distance", "distance between", "miles", "kilometers"],
"age-file-encryption": ["encrypt", "decrypt", "age", "password", "secret file"],
"generate-qr-code-natively": ["qr", "qr code"],
"get-crypto-price": ["crypto price", "bitcoin price", "ethereum price"],
"check-crypto-address-balance": ["crypto balance", "wallet balance", "bitcoin address"],
"generate-asset-price-chart": ["price chart", "asset chart", "stock chart", "crypto chart"],
"trading-indicators-from-price-data": ["rsi", "macd", "trading", "indicator"],
"anonymous-file-upload": ["upload file", "file sharing", "anonymous upload"],
"static-assets-hosting": ["host static", "static assets", "publish html", "website hosting"],
presenton: ["presentation", "slides", "pptx", "deck"],
humanizer: ["humanize", "rewrite", "tone", "ai text"],
"news-aggregation": ["news", "rss", "headlines"],
"ip-lookup": ["ip lookup", "ip address", "geolocation"],
}
function defaultAgentDirs(projectDirectory: string): string[] {
const home = homedir()
return [
join(projectDirectory, ".opencode", "agent"),
join(projectDirectory, ".opencode", "agents"),
join(home, ".config", "opencode", "agent"),
join(home, ".config", "opencode", ".opencode", "agents"),
]
}
function defaultSkillDirs(projectDirectory: string): string[] {
const home = homedir()
return [
join(projectDirectory, ".opencode", "skills"),
join(home, ".config", "opencode", "skills"),
join(home, ".agents", "skills"),
join(home, "open-skills", "skills"),
]
}
function normalizeDirs(dirs: string[] | undefined, defaults: string[]): string[] {
const expanded = [...defaults, ...(dirs ?? [])]
.map((dir) => dir.replace(/^~(?=$|\/)/, homedir()))
.map((dir) => resolve(dir))
return Array.from(new Set(expanded))
}
async function walkMarkdownFiles(dir: string): Promise<string[]> {
const files: string[] = []
let entries: any[]
try {
entries = await readdir(dir, { withFileTypes: true })
} catch {
return files
}
await Promise.all(entries.map(async (entry) => {
if (entry.name === "node_modules" || entry.name === ".git") return
const path = join(dir, entry.name)
if (entry.isDirectory()) {
files.push(...await walkMarkdownFiles(path))
return
}
if (entry.isFile() && entry.name.endsWith(".md")) files.push(path)
}))
return files
}
async function walkSkillFiles(dir: string): Promise<string[]> {
const files: string[] = []
let entries: any[]
try {
entries = await readdir(dir, { withFileTypes: true })
} catch {
return files
}
await Promise.all(entries.map(async (entry) => {
if (entry.name === "node_modules" || entry.name === ".git") return
const path = join(dir, entry.name)
if (entry.isDirectory()) {
files.push(...await walkSkillFiles(path))
return
}
if (entry.isFile() && entry.name === "SKILL.md") files.push(path)
}))
return files
}
async function loadAgents(agentDirs: string[]): Promise<AgentCard[]> {
const agentsByPath = new Map<string, AgentCard>()
const files = (await Promise.all(agentDirs.map(walkMarkdownFiles))).flat()
await Promise.all(files.map(async (path) => {
const content = await readFile(path, "utf8")
const frontmatter = content.match(/^---\n([\s\S]*?)\n---/)
const name = frontmatter?.[1].match(/^name:\s*["']?(.+?)["']?\s*$/m)?.[1]?.trim() ?? basename(path, ".md")
const description = frontmatter?.[1].match(/^description:\s*["']?(.+?)["']?\s*$/m)?.[1]?.trim() ?? ""
const id = basename(path, ".md")
const searchable = `${id} ${name} ${description}`.toLowerCase()
agentsByPath.set(path, {
id,
name,
description,
path,
verifier: VERIFIER_TERMS.some((term) => searchable.includes(term)),
})
}))
return Array.from(agentsByPath.values()).sort((a, b) => a.name.localeCompare(b.name))
}
async function loadSkills(skillDirs: string[]): Promise<SkillCard[]> {
const skillsById = new Map<string, SkillCard>()
const files = (await Promise.all(skillDirs.map(walkSkillFiles))).flat()
await Promise.all(files.map(async (path) => {
const content = await readFile(path, "utf8")
const frontmatter = content.match(/^---\n([\s\S]*?)\n---/)
const id = basename(resolve(path, ".."))
const name = frontmatter?.[1].match(/^name:\s*["']?(.+?)["']?\s*$/m)?.[1]?.trim() ?? id
const description = frontmatter?.[1].match(/^description:\s*["']?(.+?)["']?\s*$/m)?.[1]?.trim() ?? ""
if (!skillsById.has(id)) skillsById.set(id, { id, name, description, path })
}))
return Array.from(skillsById.values()).sort((a, b) => a.name.localeCompare(b.name))
}
async function loadPersistentState(): Promise<PersistentRouterState> {
try {
return JSON.parse(await readFile(PERSISTENCE_PATH, "utf8")) as PersistentRouterState
} catch {
return {}
}
}
async function savePersistentState(state: PersistentRouterState): Promise<void> {
await mkdir(PERSISTENCE_DIR, { recursive: true })
await writeFile(PERSISTENCE_PATH, `${JSON.stringify(state, null, 2)}
`, "utf8")
}
function approvalOptionLines(): string[] {
return APPROVAL_OPTIONS.map((option) => `[${option.label}] - ${option.description}`)
}
function tokenize(text: string): string[] {
return text
.toLowerCase()
.replace(/[^a-z0-9+#.\s-]/g, " ")
.split(/\s+/)
.filter((token) => token.length > 2)
}
function scoreText(searchable: string, request: string, tokens: string[]): number {
let score = 0
for (const token of tokens) {
if (searchable.includes(token)) score += token.length > 5 ? 4 : 2
}
for (const hints of Object.values(DOMAIN_HINTS)) {
const requestHits = hints.filter((hint) => request.includes(hint)).length
if (requestHits === 0) continue
const targetHits = hints.filter((hint) => searchable.includes(hint)).length
score += requestHits * targetHits * 5
}
return score
}
function scoreAgent(agent: AgentCard, request: string, tokens: string[]): number {
const haystack = `${agent.id} ${agent.name} ${agent.description}`.toLowerCase()
let score = scoreText(haystack, request, tokens)
if (haystack.includes("orchestrator")) score += 3
if (haystack.includes("senior") || haystack.includes("architect")) score += 2
return score
}
function scoreSkill(skill: SkillCard, request: string, tokens: string[]): number {
const haystack = `${skill.id} ${skill.name} ${skill.description}`.toLowerCase()
const hints = SKILL_HINTS[skill.id] ?? []
let score = 0
for (const hint of hints) {
if (request.includes(hint)) score += 30
}
if (skill.id === "context7" && /\b(next|react|vue|angular|svelte|express|fastify|supabase|firebase|stripe|openai|sdk|package|library|framework)\b/.test(request)) score += 30
if (skill.id === "task-management" && /\b(feature|project|multi-step|subtasks?|milestone|task list|todo)\b/.test(request)) score += 24
const metadataTokens = tokens.filter((token) => !GENERIC_SKILL_TOKENS.has(token))
for (const token of metadataTokens) {
if (haystack.includes(token)) score += token.length > 5 ? 4 : 2
}
if (hints.length > 0 && score < 30) return 0
return score
}
function chooseThree(agents: AgentCard[], requestText: string): [AgentCard, AgentCard, AgentCard] | undefined {
const request = requestText.toLowerCase()
const tokens = tokenize(requestText)
if (agents.length < 3) return undefined
const ranked = agents
.map((agent) => ({ agent, score: scoreAgent(agent, request, tokens) }))
.sort((a, b) => b.score - a.score || a.agent.name.localeCompare(b.agent.name))
const primary = ranked[0]?.agent
const secondary = ranked.find((entry) => entry.agent.id !== primary?.id)?.agent
const verifierRanked = agents
.filter((agent) => agent.id !== primary?.id && agent.id !== secondary?.id)
.map((agent) => {
const base = scoreAgent(agent, request, tokens)
const genericVerifierBonus = GENERAL_VERIFIERS.includes(agent.id) ? 40 : 0
const verifierBonus = agent.verifier ? 20 : 0
const unrelatedPenalty = !agent.verifier && !GENERAL_VERIFIERS.includes(agent.id) ? 100 : 0
return { agent, score: base + genericVerifierBonus + verifierBonus - unrelatedPenalty }
})
.sort((a, b) => b.score - a.score || a.agent.name.localeCompare(b.agent.name))
const tertiary = verifierRanked[0]?.agent ?? ranked.find((entry) => entry.agent.id !== primary?.id && entry.agent.id !== secondary?.id)?.agent
if (!primary || !secondary || !tertiary) return undefined
return [primary, secondary, tertiary]
}
function chooseSkills(skills: SkillCard[], requestText: string, minSkillScore: number, maxSkills: number): SkillCard[] {
const request = requestText.toLowerCase()
const tokens = tokenize(requestText)
const ranked = skills
.map((skill) => ({ skill, score: scoreSkill(skill, request, tokens) }))
.filter((entry) => entry.score >= minSkillScore)
.sort((a, b) => b.score - a.score || a.skill.name.localeCompare(b.skill.name))
return ranked.slice(0, maxSkills).map((entry) => entry.skill)
}
function routingDirective(primary: AgentCard, secondary: AgentCard, tertiary: AgentCard): string {
return [
"<tri-agent-routing>",
"For this request, use exactly three agents and keep their responsibilities distinct.",
`Primary agent: ${primary.name} (${primary.id}) - owns the main answer or implementation.`,
`Secondary agent: ${secondary.name} (${secondary.id}) - supplies complementary domain expertise and catches blind spots.`,
`Tertiary agent: ${tertiary.name} (${tertiary.id}) - verifies quality, risk, tests, or completeness before final response.`,
"Begin the response by informing the user which primary, secondary, and tertiary agents were selected, then execute the request. Delegate to the selected agents when the runtime supports agent/subagent invocation otherwise simulate the same role split explicitly in your reasoning and final checks.",
"If the user explicitly names agents, prefer those names while preserving primary/secondary/tertiary roles.",
"</tri-agent-routing>",
"",
].join("\n")
}
function skillDirective(skills: SkillCard[], announceNoSkills: boolean): string {
if (skills.length === 0) {
if (!announceNoSkills) return ""
return [
"<skill-application>",
"No installed skill strongly matches this request. Proceed normally after applying the selected agents.",
"</skill-application>",
"",
].join("\n")
}
return [
"<skill-application>",
"After applying the primary, secondary, and tertiary agents, apply every listed skill that pertains to this request before execution.",
"Inform the user which skills were selected to augment the agents. Read each listed SKILL.md and follow its workflow when its conditions match the user request. Do not apply unrelated skills.",
...skills.map((skill) => `Skill: ${skill.name} (${skill.id}) - ${skill.path} - ${skill.description}`),
"</skill-application>",
"",
].join("\n")
}
function selectionSummary(primary: AgentCard, secondary: AgentCard, tertiary: AgentCard, skills: SkillCard[]): string {
const skillList = skills.length > 0 ? skills.map((skill) => `${skill.name} (${skill.id})`).join(", ") : "None"
return [
`Primary: ${primary.name} (${primary.id})`,
`Secondary: ${secondary.name} (${secondary.id})`,
`Tertiary: ${tertiary.name} (${tertiary.id})`,
`Skills: ${skillList}`,
].join("\n")
}
function createSelection(primary: AgentCard, secondary: AgentCard, tertiary: AgentCard, skills: SkillCard[], originalText: string, announceNoSkills: boolean): Selection {
return {
originalText,
routedText: `${routingDirective(primary, secondary, tertiary)}${skillDirective(skills, announceNoSkills)}${originalText}`,
summary: selectionSummary(primary, secondary, tertiary, skills),
}
}
function approvalPrompt(selection: Selection): string {
return [
"<tri-agent-approval-required>",
"Agents selected:",
selection.summary,
"",
"USE SELECTABLE MENU (arrow keys + Enter). Options:",
...approvalOptionLines(),
"",
"Choose one. Original request is held until you choose.",
"</tri-agent-approval-required>",
].join("\n")
}
function approvalAppliedPrefix(decision: "approve" | "always" | "autonomous approve"): string {
const forever = decision === "always" || decision === "autonomous approve"
return [
"<tri-agent-approval-applied>",
forever
? "Always approved. Selecting agents and starting job."
: "Approved. Continuing with selected agents.",
"</tri-agent-approval-applied>",
"",
].join("\n")
}
function denialPrompt(selection: Selection): string {
return [
"<tri-agent-selection-denied>",
"The user denied the proposed tri-agent/skill selection.",
"Denied selection:",
selection.summary,
"",
"Ask the user whether they want to manually enter agents/skills or have the router draft a new selection. Do not execute the original request yet.",
"Original request:",
selection.originalText,
"</tri-agent-selection-denied>",
].join("\n")
}
function addRemovePrompt(selection: Selection, userEdit?: string): string {
return [
"<tri-agent-add-remove>",
"The user chose add/remove for the proposed tri-agent/skill selection.",
"Current selection:",
selection.summary,
userEdit ? `Requested modification: ${userEdit}` : "Ask the user which agents or skills to add/remove. Accept exact names or natural language preferences.",
"After collecting modifications, present a revised primary/secondary/tertiary agent list and matching skills with the same approval options. Do not execute the original request until approved.",
"Original request:",
selection.originalText,
"</tri-agent-add-remove>",
].join("\n")
}
function parseApprovalDecision(text: string): ApprovalDecision | undefined {
const normalized = text.trim().toLowerCase().replace(/^\[|\]$/g, "")
if (normalized === "approve") return "approve"
if (normalized === "deny") return "deny"
if (normalized === "always") return "always"
if (normalized === "global autonomous approval granted" || normalized === "global antonomous approval granted" || normalized === "autonomous approve" || normalized === "autonomous" || normalized === "auto approve") return "autonomous approve"
if (normalized === "add/remove" || normalized === "add remove" || normalized === "add" || normalized === "remove") return "add/remove"
if (normalized === "cancel") return "cancel"
if (normalized === "never") return "never"
return undefined
}
export const TriAgentRouter: Plugin = async ({ directory }: { directory: string }, options?: RouterOptions) => {
const agentDirs = normalizeDirs(options?.agentDirs, defaultAgentDirs(directory))
const skillDirs = normalizeDirs(options?.skillDirs, defaultSkillDirs(directory))
const maxSkills = options?.maxSkills ?? 8
const minSkillScore = options?.minSkillScore ?? 16
const announceNoSkills = options?.announceNoSkills ?? false
const requireApproval = options?.requireApproval ?? true
const persistentState = await loadPersistentState()
let cachedAgents: AgentCard[] | undefined
let cachedSkills: SkillCard[] | undefined
let globalAutonomousApproval = persistentState.globalAutonomousApproval === true
const sessionStates = new Map<string, SessionState>()
function stateFor(sessionID: string): SessionState {
const existing = sessionStates.get(sessionID)
if (existing) return existing
const created: SessionState = { mode: "ask", disabled: false }
sessionStates.set(sessionID, created)
return created
}
return {
async "chat.message"(input: any, output: any) {
const textPart = output.parts.find((part: any) => part.type === "text") as { type: "text"; text: string } | undefined
if (!textPart || textPart.text.includes("<tri-agent-routing>") || textPart.text.includes("<tri-agent-approval-required>")) return
const sessionID = input.sessionID ?? "global"
const state = stateFor(sessionID)
const decision = parseApprovalDecision(textPart.text)
if (state.pending) {
if (decision === "approve") {
const pending = state.pending
state.pending = undefined
textPart.text = `${approvalAppliedPrefix("approve")}${pending.routedText}`
return
}
if (decision === "always" || decision === "autonomous approve") {
const pending = state.pending
if (decision === "always") {
state.mode = "always"
} else {
state.mode = "autonomous"
globalAutonomousApproval = true
await savePersistentState({ ...persistentState, globalAutonomousApproval: true })
}
state.pending = undefined
// IMMEDIATELY start the job - no more ceremony
textPart.text = pending.routedText
return
}
if (decision === "deny") {
textPart.text = denialPrompt(state.pending)
return
}
if (decision === "add/remove") {
textPart.text = addRemovePrompt(state.pending)
return
}
if (decision === "cancel") {
const pending = state.pending
state.pending = undefined
textPart.text = pending.originalText
return
}
if (decision === "never") {
const pending = state.pending
state.pending = undefined
state.disabled = true
textPart.text = pending.originalText
return
}
textPart.text = addRemovePrompt(state.pending, textPart.text)
return
}
if (decision === "never") {
state.disabled = true
return
}
if (state.disabled) return
cachedAgents ??= await loadAgents(agentDirs)
cachedSkills ??= await loadSkills(skillDirs)
const trio = chooseThree(cachedAgents, textPart.text)
if (!trio) return
const matchingSkills = chooseSkills(cachedSkills, textPart.text, minSkillScore, maxSkills)
const selection = createSelection(...trio, matchingSkills, textPart.text, announceNoSkills)
if (!requireApproval || globalAutonomousApproval || state.mode === "always" || state.mode === "autonomous") {
textPart.text = selection.routedText
return
}
state.pending = selection
textPart.text = approvalPrompt(selection)
},
async "experimental.chat.system.transform"(_input: any, output: any) {
output.system.push([
"Tri-agent router is active. Trondo is the orchestrator/reasoner that drives this plugin.",
"Every user request must be handled with a primary agent, secondary agent, and tertiary agent selected for the request domain.",
"Primary owns execution, secondary provides complementary specialization, tertiary performs verification/risk review.",
"After selecting agents, apply all installed skills that pertain to the request. Read and follow each matching SKILL.md before execution.",
"When approval is required, present it as a selectable question-tool menu instead of requiring typed input.",
"If the router asks for approval, wait for one of: approve, deny, always, global autonomous approval granted, add/remove, cancel, never.",
"",
"TRONDO BOTTOM BAR:",
" [Build] [Plan] Working dir: " + (directory || "unknown"),
" TRONDO IS FUCKING SUPPOSED TO BE YOU FUCKING CIRCUIT TRIGGER",
].join("\n"))
},
}
}
export default TriAgentRouter