-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathagent.ts
More file actions
483 lines (464 loc) · 18.7 KB
/
agent.ts
File metadata and controls
483 lines (464 loc) · 18.7 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
import { Config } from "../config/config"
import z from "zod"
import { Provider } from "../provider/provider"
import { generateObject, streamObject, type ModelMessage } from "ai"
import { SystemPrompt } from "../session/system"
import { Instance } from "../project/instance"
import { Truncate } from "../tool/truncation"
import { Auth } from "../auth"
import { ProviderTransform } from "../provider/transform"
import PROMPT_GENERATE from "./generate.txt"
import PROMPT_COMPACTION from "./prompt/compaction.txt"
import PROMPT_EXPLORE from "./prompt/explore.txt"
import PROMPT_SUMMARY from "./prompt/summary.txt"
import PROMPT_TITLE from "./prompt/title.txt"
// altimate_change start - import custom agent mode prompts
import PROMPT_BUILDER from "../altimate/prompts/builder.txt"
import PROMPT_ANALYST from "../altimate/prompts/analyst.txt"
import PROMPT_VALIDATOR from "../altimate/prompts/validator.txt"
import PROMPT_MIGRATOR from "../altimate/prompts/migrator.txt"
import PROMPT_EXECUTIVE from "../altimate/prompts/executive.txt"
// altimate_change end
import { PermissionNext } from "@/permission/next"
import { mergeDeep, pipe, sortBy, values } from "remeda"
import { Global } from "@/global"
import path from "path"
import { Plugin } from "@/plugin"
import { Skill } from "../skill"
export namespace Agent {
export const Info = z
.object({
name: z.string(),
description: z.string().optional(),
mode: z.enum(["subagent", "primary", "all"]),
native: z.boolean().optional(),
hidden: z.boolean().optional(),
topP: z.number().optional(),
temperature: z.number().optional(),
color: z.string().optional(),
permission: PermissionNext.Ruleset,
model: z
.object({
modelID: z.string(),
providerID: z.string(),
})
.optional(),
variant: z.string().optional(),
prompt: z.string().optional(),
options: z.record(z.string(), z.any()),
steps: z.number().int().positive().optional(),
})
.meta({
ref: "Agent",
})
export type Info = z.infer<typeof Info>
const state = Instance.state(async () => {
const cfg = await Config.get()
const skillDirs = await Skill.dirs()
const whitelistedDirs = [Truncate.GLOB, ...skillDirs.map((dir) => path.join(dir, "*"))]
const defaults = PermissionNext.fromConfig({
"*": "allow",
doom_loop: "ask",
external_directory: {
"*": "ask",
...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])),
},
question: "deny",
plan_enter: "deny",
plan_exit: "deny",
// mirrors github.com/github/gitignore Node.gitignore pattern for .env files
read: {
"*": "allow",
"*.env": "ask",
"*.env.*": "ask",
"*.env.example": "allow",
},
})
const user = PermissionNext.fromConfig(cfg.permission ?? {})
const result: Record<string, Info> = {
// altimate_change start - replace default build agent with builder and add custom modes
builder: {
name: "builder",
description: "Create and modify dbt models, SQL, and data pipelines. Full read/write access.",
prompt: PROMPT_BUILDER,
options: {},
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
question: "allow",
plan_enter: "allow",
}),
user,
),
mode: "primary",
native: true,
},
analyst: {
name: "analyst",
description: "Read-only data exploration. Cannot modify files or run destructive SQL.",
prompt: PROMPT_ANALYST,
options: {},
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
sql_execute: "allow", sql_validate: "allow", sql_analyze: "allow",
sql_translate: "allow", sql_optimize: "allow", lineage_check: "allow",
warehouse_list: "allow", warehouse_test: "allow", warehouse_discover: "allow",
schema_inspect: "allow", schema_index: "allow", schema_search: "allow",
schema_cache_status: "allow", sql_explain: "allow", sql_format: "allow",
sql_fix: "allow", sql_autocomplete: "allow", sql_diff: "allow",
finops_query_history: "allow", finops_analyze_credits: "allow",
finops_expensive_queries: "allow", finops_warehouse_advice: "allow",
finops_unused_resources: "allow", finops_role_grants: "allow",
finops_role_hierarchy: "allow", finops_user_roles: "allow",
schema_detect_pii: "allow", schema_tags: "allow", schema_tags_list: "allow",
altimate_core_validate: "allow", altimate_core_lint: "allow",
altimate_core_safety: "allow", altimate_core_transpile: "allow",
altimate_core_check: "allow",
read: "allow", grep: "allow", glob: "allow",
question: "allow", webfetch: "allow", websearch: "allow",
}),
user,
),
mode: "primary",
native: true,
},
executive: {
name: "executive",
description: "Read-only data exploration with output calibrated for non-technical executives. No SQL or jargon — findings expressed as business impact.",
prompt: PROMPT_EXECUTIVE,
options: { audience: "executive" },
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
sql_execute: "allow", sql_validate: "allow", sql_analyze: "allow",
sql_translate: "allow", sql_optimize: "allow", lineage_check: "allow",
warehouse_list: "allow", warehouse_test: "allow", warehouse_discover: "allow",
schema_inspect: "allow", schema_index: "allow", schema_search: "allow",
schema_cache_status: "allow", sql_explain: "allow", sql_format: "allow",
sql_fix: "allow", sql_autocomplete: "allow", sql_diff: "allow",
finops_query_history: "allow", finops_analyze_credits: "allow",
finops_expensive_queries: "allow", finops_warehouse_advice: "allow",
finops_unused_resources: "allow", finops_role_grants: "allow",
finops_role_hierarchy: "allow", finops_user_roles: "allow",
schema_detect_pii: "allow", schema_tags: "allow", schema_tags_list: "allow",
altimate_core_validate: "allow", altimate_core_lint: "allow",
altimate_core_safety: "allow", altimate_core_transpile: "allow",
altimate_core_check: "allow",
read: "allow", grep: "allow", glob: "allow",
question: "allow", webfetch: "allow", websearch: "allow",
}),
user,
),
mode: "primary",
native: true,
},
validator: {
name: "validator",
description: "Test, lint, and verify data integrity. Cannot modify files.",
prompt: PROMPT_VALIDATOR,
options: {},
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
sql_validate: "allow", sql_execute: "allow", sql_analyze: "allow",
sql_translate: "allow", sql_optimize: "allow", lineage_check: "allow",
warehouse_list: "allow", warehouse_test: "allow", warehouse_discover: "allow",
schema_inspect: "allow", schema_index: "allow", schema_search: "allow",
schema_cache_status: "allow", sql_explain: "allow", sql_format: "allow",
sql_fix: "allow", sql_autocomplete: "allow", sql_diff: "allow",
finops_query_history: "allow", finops_analyze_credits: "allow",
finops_expensive_queries: "allow", finops_warehouse_advice: "allow",
finops_unused_resources: "allow", finops_role_grants: "allow",
finops_role_hierarchy: "allow", finops_user_roles: "allow",
schema_detect_pii: "allow", schema_tags: "allow", schema_tags_list: "allow",
altimate_core_validate: "allow", altimate_core_lint: "allow",
altimate_core_safety: "allow", altimate_core_transpile: "allow",
altimate_core_check: "allow",
read: "allow", grep: "allow", glob: "allow", bash: "allow",
question: "allow",
}),
user,
),
mode: "primary",
native: true,
},
migrator: {
name: "migrator",
description: "Cross-warehouse SQL migration and dialect conversion. Lineage extraction, dependency-ordered migration, compile gate, data validation.",
prompt: PROMPT_MIGRATOR,
options: {},
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
sql_execute: "allow", sql_validate: "allow", sql_translate: "allow",
sql_optimize: "allow", lineage_check: "allow",
warehouse_list: "allow", warehouse_test: "allow", warehouse_discover: "allow",
schema_inspect: "allow", schema_index: "allow", schema_search: "allow",
schema_cache_status: "allow", sql_explain: "allow", sql_format: "allow",
sql_fix: "allow", sql_autocomplete: "allow", sql_diff: "allow",
sql_rewrite: "allow", schema_diff: "allow",
finops_query_history: "allow", finops_analyze_credits: "allow",
finops_expensive_queries: "allow", finops_warehouse_advice: "allow",
finops_unused_resources: "allow", finops_role_grants: "allow",
finops_role_hierarchy: "allow", finops_user_roles: "allow",
schema_detect_pii: "allow", schema_tags: "allow", schema_tags_list: "allow",
altimate_core_validate: "allow", altimate_core_lint: "allow",
altimate_core_safety: "allow", altimate_core_transpile: "allow",
altimate_core_check: "allow",
altimate_core_migration: "allow", altimate_core_equivalence: "allow",
altimate_core_schema_diff: "allow", altimate_core_column_lineage: "allow",
altimate_core_track_lineage: "allow", altimate_core_semantics: "allow",
altimate_core_grade: "allow", altimate_core_testgen: "allow",
altimate_core_rewrite: "allow", altimate_core_import_ddl: "allow",
altimate_core_export_ddl: "allow", altimate_core_fix: "allow",
dbt_run: "allow", dbt_manifest: "allow", dbt_profiles: "allow",
dbt_lineage: "allow",
read: "allow", write: "allow", edit: "allow",
grep: "allow", glob: "allow", bash: "allow", question: "allow",
}),
user,
),
mode: "primary",
native: true,
},
// altimate_change end
plan: {
name: "plan",
description: "Plan mode. Disallows all edit tools.",
options: {},
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
question: "allow",
plan_exit: "allow",
external_directory: {
[path.join(Global.Path.data, "plans", "*")]: "allow",
},
edit: {
"*": "deny",
[path.join(".opencode", "plans", "*.md")]: "allow",
[path.relative(Instance.worktree, path.join(Global.Path.data, path.join("plans", "*.md")))]: "allow",
},
}),
user,
),
mode: "primary",
native: true,
},
general: {
name: "general",
description: `General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.`,
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
todoread: "deny",
todowrite: "deny",
}),
user,
),
options: {},
mode: "subagent",
native: true,
},
explore: {
name: "explore",
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
grep: "allow",
glob: "allow",
list: "allow",
bash: "allow",
webfetch: "allow",
websearch: "allow",
codesearch: "allow",
read: "allow",
external_directory: {
"*": "ask",
...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])),
},
}),
user,
),
description: `Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.`,
prompt: PROMPT_EXPLORE,
options: {},
mode: "subagent",
native: true,
},
compaction: {
name: "compaction",
mode: "primary",
native: true,
hidden: true,
prompt: PROMPT_COMPACTION,
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
}),
user,
),
options: {},
},
title: {
name: "title",
mode: "primary",
options: {},
native: true,
hidden: true,
temperature: 0.5,
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
}),
user,
),
prompt: PROMPT_TITLE,
},
summary: {
name: "summary",
mode: "primary",
options: {},
native: true,
hidden: true,
permission: PermissionNext.merge(
defaults,
PermissionNext.fromConfig({
"*": "deny",
}),
user,
),
prompt: PROMPT_SUMMARY,
},
}
for (const [key, value] of Object.entries(cfg.agent ?? {})) {
if (value.disable) {
delete result[key]
continue
}
let item = result[key]
if (!item)
item = result[key] = {
name: key,
mode: "all",
permission: PermissionNext.merge(defaults, user),
options: {},
native: false,
}
if (value.model) item.model = Provider.parseModel(value.model)
item.variant = value.variant ?? item.variant
item.prompt = value.prompt ?? item.prompt
item.description = value.description ?? item.description
item.temperature = value.temperature ?? item.temperature
item.topP = value.top_p ?? item.topP
item.mode = value.mode ?? item.mode
item.color = value.color ?? item.color
item.hidden = value.hidden ?? item.hidden
item.name = value.name ?? item.name
item.steps = value.steps ?? item.steps
item.options = mergeDeep(item.options, value.options ?? {})
item.permission = PermissionNext.merge(item.permission, PermissionNext.fromConfig(value.permission ?? {}))
}
// Ensure Truncate.GLOB is allowed unless explicitly configured
for (const name in result) {
const agent = result[name]
const explicit = agent.permission.some((r) => {
if (r.permission !== "external_directory") return false
if (r.action !== "deny") return false
return r.pattern === Truncate.GLOB
})
if (explicit) continue
result[name].permission = PermissionNext.merge(
result[name].permission,
PermissionNext.fromConfig({ external_directory: { [Truncate.GLOB]: "allow" } }),
)
}
return result
})
export async function get(agent: string) {
return state().then((x) => x[agent])
}
export async function list() {
const cfg = await Config.get()
return pipe(
await state(),
values(),
// altimate_change start - default agent is "builder" not "build"
sortBy([(x) => (cfg.default_agent ? x.name === cfg.default_agent : x.name === "builder"), "desc"]),
// altimate_change end
)
}
export async function defaultAgent() {
const cfg = await Config.get()
const agents = await state()
if (cfg.default_agent) {
const agent = agents[cfg.default_agent]
if (!agent) throw new Error(`default agent "${cfg.default_agent}" not found`)
if (agent.mode === "subagent") throw new Error(`default agent "${cfg.default_agent}" is a subagent`)
if (agent.hidden === true) throw new Error(`default agent "${cfg.default_agent}" is hidden`)
return agent.name
}
const primaryVisible = Object.values(agents).find((a) => a.mode !== "subagent" && a.hidden !== true)
if (!primaryVisible) throw new Error("no primary visible agent found")
return primaryVisible.name
}
export async function generate(input: { description: string; model?: { providerID: string; modelID: string } }) {
const cfg = await Config.get()
const defaultModel = input.model ?? (await Provider.defaultModel())
const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID)
const language = await Provider.getLanguage(model)
const system = [PROMPT_GENERATE]
await Plugin.trigger("experimental.chat.system.transform", { model }, { system })
const existing = await list()
const params = {
experimental_telemetry: {
isEnabled: cfg.experimental?.openTelemetry,
metadata: {
userId: cfg.username ?? "unknown",
},
},
temperature: 0.3,
messages: [
...system.map(
(item): ModelMessage => ({
role: "system",
content: item,
}),
),
{
role: "user",
content: `Create an agent configuration based on this request: \"${input.description}\".\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existing.map((i) => i.name).join(", ")}\n Return ONLY the JSON object, no other text, do not wrap in backticks`,
},
],
model: language,
schema: z.object({
identifier: z.string(),
whenToUse: z.string(),
systemPrompt: z.string(),
}),
} satisfies Parameters<typeof generateObject>[0]
if (defaultModel.providerID === "openai" && (await Auth.get(defaultModel.providerID))?.type === "oauth") {
const result = streamObject({
...params,
providerOptions: ProviderTransform.providerOptions(model, {
instructions: SystemPrompt.instructions(),
store: false,
}),
onError: () => {},
})
for await (const part of result.fullStream) {
if (part.type === "error") throw part.error
}
return result.object
}
const result = await generateObject(params)
return result.object
}
}