-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathagent.ts
More file actions
851 lines (817 loc) · 34.7 KB
/
Copy pathagent.ts
File metadata and controls
851 lines (817 loc) · 34.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
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
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
// altimate_change start — makeRuntime for the restored Promise wrapper (bottom of file)
import { makeRuntime } from "@/effect/run-service"
// altimate_change end
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
import { Config } from "@/config/config"
import { serviceUse } from "@opencode-ai/core/effect/service-use"
import { Provider } from "@/provider/provider"
import { generateObject, streamObject, type ModelMessage } from "ai"
import { Truncate } from "@/tool/truncate"
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_REVIEWER from "../altimate/prompts/reviewer.txt"
import PROMPT_OPTIMIZER from "../altimate/prompts/dbt-optimizer.txt"
// altimate_change end
import { Permission } from "@/permission"
import { mergeDeep, pipe, sortBy, values } from "remeda"
import { Global } from "@opencode-ai/core/global"
import path from "path"
import { Plugin } from "@/plugin"
import { Skill } from "../skill"
import { Effect, Context, Layer, Schema } from "effect"
import { InstanceState } from "@/effect/instance-state"
import * as Option from "effect/Option"
import * as OtelTracer from "@effect/opentelemetry/Tracer"
import { AbsolutePath, type DeepMutable } from "@opencode-ai/core/schema"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { ModelV2 } from "@opencode-ai/core/model"
// altimate_change start — fork ID brands for re-branding at the namespace/core boundary
import { ProviderID, ModelID } from "@/provider/schema"
// altimate_change end
import { LocationServiceMap } from "@opencode-ai/core/location-layer"
import { PluginBoot } from "@opencode-ai/core/plugin/boot"
import { Reference } from "@opencode-ai/core/reference"
import { Location } from "@opencode-ai/core/location"
export const Info = Schema.Struct({
name: Schema.String,
description: Schema.optional(Schema.String),
mode: Schema.Literals(["subagent", "primary", "all"]),
native: Schema.optional(Schema.Boolean),
hidden: Schema.optional(Schema.Boolean),
topP: Schema.optional(Schema.Finite),
temperature: Schema.optional(Schema.Finite),
color: Schema.optional(Schema.String),
permission: PermissionV1.Ruleset,
model: Schema.optional(
Schema.Struct({
modelID: ModelV2.ID,
providerID: ProviderV2.ID,
}),
),
variant: Schema.optional(Schema.String),
prompt: Schema.optional(Schema.String),
options: Schema.Record(Schema.String, Schema.Unknown),
steps: Schema.optional(Schema.Finite),
}).annotate({ identifier: "Agent" })
export type Info = DeepMutable<Schema.Schema.Type<typeof Info>>
const GeneratedAgent = Schema.Struct({
identifier: Schema.String,
whenToUse: Schema.String,
systemPrompt: Schema.String,
})
export interface Interface {
readonly get: (agent: string) => Effect.Effect<Info>
readonly list: () => Effect.Effect<Info[]>
readonly defaultInfo: () => Effect.Effect<Info>
readonly defaultAgent: () => Effect.Effect<string>
readonly generate: (input: {
description: string
model?: { providerID: ProviderV2.ID; modelID: ModelV2.ID }
}) => Effect.Effect<
{
identifier: string
whenToUse: string
systemPrompt: string
},
Provider.DefaultModelError
>
}
type State = Omit<Interface, "generate">
export class Service extends Context.Service<Service, Interface>()("@opencode/Agent") {}
export const use = serviceUse(Service)
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service
const auth = yield* Auth.Service
const plugin = yield* Plugin.Service
const skill = yield* Skill.Service
const provider = yield* Provider.Service
const locations = yield* LocationServiceMap
const state = yield* InstanceState.make<State>(
Effect.fn("Agent.state")(function* (ctx) {
const cfg = yield* config.get()
const skillDirs = yield* skill.dirs()
const referenceDirs = yield* Effect.gen(function* () {
yield* (yield* PluginBoot.Service).wait()
return (yield* (yield* Reference.Service).list()).map((reference) => reference.path)
}).pipe(Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(ctx.directory) }))))
const whitelistedDirs = [
Truncate.GLOB,
path.join(Global.Path.tmp, "*"),
...skillDirs.map((dir) => path.join(dir, "*")),
...referenceDirs.map((dir) => path.join(dir, "*")),
]
const readonlyExternalDirectory = {
"*": "ask",
...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])),
} satisfies Record<string, "allow" | "ask" | "deny">
const defaults = Permission.fromConfig({
"*": "allow",
doom_loop: "ask",
external_directory: {
"*": "ask",
...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])),
},
question: "deny",
plan_enter: "deny",
plan_exit: "deny",
// altimate_change start — make the #209 sensitive-write guard actually fire.
// The guard calls ctx.ask({ permission: "sensitive_write" }) before writing a
// sensitive target (.env/.ssh/.git/...), but with no explicit rule it fell through
// to the "*": "allow" catch-all above and auto-approved — silently neutralizing the
// guard. Default it to "ask" so sensitive writes prompt (users can still override to
// "allow" in config). Restrictive agents (analyst/reviewer/plan) keep their later
// "*": "deny", so this only affects write-capable agents.
sensitive_write: "ask",
// altimate_change end
// mirrors github.com/github/gitignore Node.gitignore pattern for .env files
read: {
"*": "allow",
"*.env": "ask",
"*.env.*": "ask",
"*.env.example": "allow",
},
// altimate_change start - bash safety defaults for destructive file/git/DDL commands
// Safety defaults for bash commands.
// IMPORTANT: "*": "ask" must come FIRST because evaluation uses last-match-wins.
//
// "ask" = user sees prompt and can approve. Used for destructive file/git
// commands that are common in legitimate workflows (rm -rf ./build,
// git push --force after rebase, git clean in CI).
// "deny" = blocked entirely, no prompt. Used for database DDL that is
// almost never intentional in an agent context.
//
// Users can override any of these in altimate-code.json.
bash: {
"*": "ask",
"rm -rf *": "ask",
"rm -fr *": "ask",
"git push --force *": "ask",
"git push -f *": "ask",
"git reset --hard *": "ask",
"git clean -f *": "ask",
"DROP DATABASE *": "deny",
"DROP SCHEMA *": "deny",
"TRUNCATE *": "deny",
"drop database *": "deny",
"drop schema *": "deny",
"truncate *": "deny",
},
// altimate_change end
})
const user = Permission.fromConfig(cfg.permission ?? {})
// altimate_change start - safety deny rules that cannot be overridden by wildcard allows
// Safety deny rules that CANNOT be overridden by wildcard allows.
// Appended after user config so they always take precedence via last-match-wins.
// Users who need to override must use specific patterns like
// `"DROP DATABASE test_db": "allow"` — wildcard `bash: "allow"` won't work.
// Both UPPER and lowercase variants are included because Wildcard.match
// is case-sensitive on Linux/macOS.
const safetyDenials = Permission.fromConfig({
bash: {
"DROP DATABASE *": "deny",
"DROP SCHEMA *": "deny",
"TRUNCATE *": "deny",
"drop database *": "deny",
"drop schema *": "deny",
"truncate *": "deny",
"Drop Database *": "deny",
"Drop Schema *": "deny",
"Truncate *": "deny",
},
// SQL write safety denials
sql_execute_write: {
"DROP DATABASE *": "deny",
"DROP SCHEMA *": "deny",
"TRUNCATE *": "deny",
"drop database *": "deny",
"drop schema *": "deny",
"truncate *": "deny",
"Drop Database *": "deny",
"Drop Schema *": "deny",
"Truncate *": "deny",
},
})
// Combine user config with safety denials so every agent inherits them
const userWithSafety = Permission.merge(user, safetyDenials)
// altimate_change end
const agents: Record<string, Info> = {
// altimate_change start - 4 modes: builder, analyst, reviewer, dbt-optimizer (replaces upstream single "build" agent)
builder: {
name: "builder",
description: "Create and modify dbt models, SQL, and data pipelines. Full read/write access.",
prompt: PROMPT_BUILDER,
options: {},
permission: Permission.merge(
defaults,
Permission.fromConfig({
question: "allow",
plan_enter: "allow",
sql_execute_write: "ask",
}),
userWithSafety,
),
mode: "primary",
native: true,
},
analyst: {
name: "analyst",
description: "Read-only data exploration and analysis. Cannot modify files or run destructive SQL.",
prompt: PROMPT_ANALYST,
options: {},
permission: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
// SQL read tools
sql_execute: "allow",
altimate_core_validate: "allow",
sql_analyze: "allow",
sql_translate: "allow",
sql_optimize: "allow",
lineage_check: "allow",
sql_explain: "allow",
sql_format: "allow",
sql_fix: "allow",
sql_autocomplete: "allow",
sql_diff: "allow",
// SQL writes denied
sql_execute_write: "deny",
// Warehouse/schema/finops
warehouse_list: "allow",
warehouse_test: "allow",
warehouse_discover: "allow",
schema_inspect: "allow",
schema_index: "allow",
schema_search: "allow",
schema_cache_status: "allow",
schema_detect_pii: "allow",
schema_tags: "allow",
schema_tags_list: "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",
// Core tools
altimate_core_check: "allow",
altimate_core_rewrite: "allow",
// Read-only file access
read: "allow",
grep: "allow",
glob: "allow",
webfetch: "allow",
websearch: "allow",
question: "allow",
tool_lookup: "allow",
// Bash: last-match-wins — "*": "deny" MUST come first, then specific allows override
bash: {
"*": "deny",
"ls *": "allow",
"grep *": "allow",
"cat *": "allow",
"head *": "allow",
"tail *": "allow",
"find *": "allow",
"wc *": "allow",
"dbt list *": "allow",
"dbt ls *": "allow",
"dbt debug *": "allow",
},
// Training
training_save: "allow",
training_list: "allow",
training_remove: "allow",
}),
userWithSafety,
),
mode: "primary",
native: true,
},
// reviewer agent: dbt PR review verdict engine
reviewer: {
name: "reviewer",
description:
"dbt PR reviewer. Runs the dbt_pr_review verdict engine (lineage, equivalence, PII, grade) plus read-only analysis tools and posts findings. Edit/write tools are denied; bash prompts for approval.",
prompt: PROMPT_REVIEWER,
options: {},
permission: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
// The verdict engine + the read-only analysis tools it composes.
dbt_pr_review: "allow",
impact_analysis: "allow",
altimate_core_check: "allow",
altimate_core_grade: "allow",
altimate_core_equivalence: "allow",
altimate_core_column_lineage: "allow",
altimate_core_compare: "allow",
lineage_check: "allow",
sql_analyze: "allow",
sql_diff: "allow",
schema_detect_pii: "allow",
// Writes denied — review never mutates the project.
sql_execute_write: "deny",
// Read-only file + repo access (structured tools, not bash).
read: "allow",
grep: "allow",
glob: "allow",
list: "allow",
tool_lookup: "allow",
// Reviews routinely span sibling repos and skill dirs; without this
// the "*" deny above hard-fails read/grep/glob outside the project
// (#978). "ask" keeps the user in the loop; whitelisted dirs stay
// frictionless.
external_directory: readonlyExternalDirectory,
// Read-only web access so the reviewer can pull PR/issue URLs.
webfetch: "allow",
websearch: "allow",
// Bash PROMPTS instead of hard-denying (#978: `gh pr view` is the
// primary way to review a PR URL). A string-prefix allowlist can't
// safely bound argv (redirects ride inside the matched command), so
// every bash command requires explicit user approval here — the
// reviewer still never runs shell commands silently.
bash: "ask",
}),
// altimate_change start — reviewer safety must not be overridable by a permissive user
// config (e.g. global `permission: {"*":"allow"}` or `bash:"allow"`). Merge user config,
// THEN re-apply the reviewer read-only invariants, THEN safetyDenials LAST so DDL denies
// still win over the reviewer's bash:"ask". (edit covers write/edit/apply_patch.)
user,
Permission.fromConfig({
bash: "ask",
edit: "deny",
sql_execute_write: "deny",
}),
safetyDenials,
// altimate_change end
),
mode: "primary",
native: true,
},
// dbt-optimizer agent: dbt project optimization — scan (read-only allowlist),
// propose candidates, apply user-selected fixes (edit/bash prompt), report impact.
"dbt-optimizer": {
name: "dbt-optimizer",
description:
"Scan a dbt project for fixable issues — performance, materialization, repeated logic, missing tests/docs — and propose targeted fixes with cost and impact reporting. File edits and shell commands prompt for approval by default (explicit user config can relax them); the direct SQL write tool is denied non-overridably, and dbt builds run only as user-approved shell commands (the agent confirms a dev target before building).",
prompt: PROMPT_OPTIMIZER,
options: {},
permission: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
// Read-only project access (scan phase)
read: "allow",
grep: "allow",
glob: "allow",
list: "allow",
question: "allow",
tool_lookup: "allow",
todowrite: "allow",
todoread: "allow",
webfetch: "allow",
websearch: "allow",
// Scans routinely need paths outside the worktree (e.g. dbt profiles,
// package dirs); "ask" instead of hard-failing on the "*" deny.
external_directory: readonlyExternalDirectory,
// SQL analysis + verified rewrites
sql_execute: "allow",
sql_analyze: "allow",
sql_optimize: "allow",
sql_explain: "allow",
sql_diff: "allow",
sql_format: "allow",
sql_fix: "allow",
altimate_core_validate: "allow",
altimate_core_check: "allow",
altimate_core_grade: "allow",
altimate_core_rewrite: "allow",
altimate_core_equivalence: "allow",
altimate_core_compare: "allow",
altimate_core_column_lineage: "allow",
altimate_core_parse_dbt: "allow",
altimate_core_testgen: "allow",
// dbt project structure + blast radius
dbt_manifest: "allow",
dbt_lineage: "allow",
dbt_unit_test_gen: "allow",
impact_analysis: "allow",
lineage_check: "allow",
schema_inspect: "allow",
schema_search: "allow",
// schema_index crawls the warehouse and REWRITES the persistent
// global schema cache (~/.altimate-code/schema-cache.db) — a
// mutation the read-only scan must not run unprompted.
schema_index: "ask",
schema_cache_status: "allow",
warehouse_list: "allow",
warehouse_test: "allow",
// Cost evidence
finops_query_history: "allow",
finops_analyze_credits: "allow",
finops_expensive_queries: "allow",
finops_warehouse_advice: "allow",
finops_unused_resources: "allow",
// Fix phase: every file change and shell command prompts for approval
edit: "ask",
bash: "ask",
// Warehouse writes never
sql_execute_write: "deny",
// Training: list freely, but mutations prompt — training writes
// persistent memory outside the edit permission, so an injected
// instruction in scanned SQL/YAML must not be able to silently
// poison future sessions during the read-only scan.
training_save: "ask",
training_list: "allow",
training_remove: "ask",
}),
// Merge user config, THEN re-apply the warehouse-write invariant so a
// permissive global config (e.g. `"*": "allow"`) can't turn the scan
// into a silent writer, THEN safetyDenials LAST so DDL denies always win.
user,
Permission.fromConfig({
sql_execute_write: "deny",
}),
safetyDenials,
),
mode: "primary",
native: true,
},
// altimate_change end
plan: {
name: "plan",
description: "Plan mode. Disallows all edit tools.",
options: {},
permission: Permission.merge(
defaults,
Permission.fromConfig({
question: "allow",
plan_exit: "allow",
task: {
general: "deny",
},
external_directory: {
[path.join(Global.Path.data, "plans", "*")]: "allow",
},
edit: {
"*": "deny",
[path.join(".opencode", "plans", "*.md")]: "allow",
[path.relative(ctx.worktree, path.join(Global.Path.data, path.join("plans", "*.md")))]: "allow",
},
}),
// altimate_change start - inherit safety denials
userWithSafety,
// altimate_change end
),
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: Permission.merge(
defaults,
Permission.fromConfig({
todowrite: "deny",
}),
// altimate_change start - inherit safety denials
userWithSafety,
// altimate_change end
),
options: {},
mode: "subagent",
native: true,
},
explore: {
name: "explore",
permission: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
grep: "allow",
glob: "allow",
// altimate_change start — restore codesearch for explore (dropped by the v1.17.9 merge;
// the tool gates on this permission and silently degrades to local grep without it)
codesearch: "allow",
// altimate_change end
list: "allow",
bash: "allow",
webfetch: "allow",
websearch: "allow",
read: "allow",
external_directory: readonlyExternalDirectory,
}),
// altimate_change start - inherit safety denials
userWithSafety,
// altimate_change end
),
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: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
}),
// altimate_change start - inherit safety denials
userWithSafety,
// altimate_change end
),
options: {},
},
title: {
name: "title",
mode: "primary",
options: {},
native: true,
hidden: true,
temperature: 0.5,
permission: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
}),
// altimate_change start - inherit safety denials
userWithSafety,
// altimate_change end
),
prompt: PROMPT_TITLE,
},
summary: {
name: "summary",
mode: "primary",
options: {},
native: true,
hidden: true,
permission: Permission.merge(
defaults,
Permission.fromConfig({
"*": "deny",
}),
// altimate_change start - inherit safety denials
userWithSafety,
// altimate_change end
),
prompt: PROMPT_SUMMARY,
},
}
for (const [key, value] of Object.entries(cfg.agent ?? {})) {
if (value.disable) {
delete agents[key]
continue
}
let item = agents[key]
if (!item)
item = agents[key] = {
name: key,
mode: "all",
// altimate_change start - new agents inherit safety denials
permission: Permission.merge(defaults, userWithSafety),
// altimate_change end
options: {},
native: false,
}
if (value.model) {
// altimate_change start — re-brand fork ProviderID/ModelID to core ProviderV2.ID/ModelV2.ID (identity at runtime)
const parsed = Provider.parseModel(value.model)
item.model = {
providerID: ProviderV2.ID.make(parsed.providerID),
modelID: ModelV2.ID.make(parsed.modelID),
}
// altimate_change end
}
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 ?? {})
// altimate_change start - re-apply safety denials AFTER user config so they cannot be overridden
item.permission = Permission.merge(
item.permission,
Permission.fromConfig(value.permission ?? {}),
safetyDenials,
)
// Evaluation is last-match-wins, so a per-agent `permission` override
// (merged just above) would outrank the invariants baked into the native
// definitions. Re-apply the optimizer's warehouse-write deny here so
// `agent."dbt-optimizer".permission.sql_execute_write: "allow"` cannot turn
// the scan into a warehouse writer.
if (key === "dbt-optimizer" && item.native) {
item.permission = Permission.merge(
item.permission,
Permission.fromConfig({ sql_execute_write: "deny" }),
safetyDenials,
)
}
// altimate_change end
}
// Ensure Truncate.GLOB is allowed unless explicitly configured
for (const name in agents) {
const agent = agents[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
agents[name].permission = Permission.merge(
agents[name].permission,
Permission.fromConfig({ external_directory: { [Truncate.GLOB]: "allow" } }),
)
}
const get = Effect.fnUntraced(function* (agent: string) {
// altimate_change start — "build" alias for "builder" (renamed agent)
if (!agents[agent] && agent === "build") return agents["builder"]
// altimate_change end
return agents[agent]
})
const list = Effect.fnUntraced(function* () {
const cfg = yield* config.get()
return pipe(
agents,
values(),
sortBy(
// altimate_change start - default agent is "builder" not "build"
[(x) => (cfg.default_agent ? x.name === cfg.default_agent : x.name === "builder"), "desc"],
// altimate_change end
[(x) => x.name, "asc"],
),
)
})
const defaultInfo = Effect.fnUntraced(function* () {
const c = yield* config.get()
if (c.default_agent) {
const agent = agents[c.default_agent]
if (!agent) throw new Error(`default agent "${c.default_agent}" not found`)
if (agent.mode === "subagent") throw new Error(`default agent "${c.default_agent}" is a subagent`)
if (agent.hidden === true) throw new Error(`default agent "${c.default_agent}" is hidden`)
return agent
}
const visible = Object.values(agents).find((a) => a.mode !== "subagent" && a.hidden !== true)
if (!visible) throw new Error("no primary visible agent found")
return visible
})
const defaultAgent = Effect.fnUntraced(function* () {
return (yield* defaultInfo()).name
})
return {
get,
list,
defaultInfo,
defaultAgent,
} satisfies State
}),
)
return Service.of({
get: Effect.fn("Agent.get")(function* (agent: string) {
return yield* InstanceState.useEffect(state, (s) => s.get(agent))
}),
list: Effect.fn("Agent.list")(function* () {
return yield* InstanceState.useEffect(state, (s) => s.list())
}),
defaultInfo: Effect.fn("Agent.defaultInfo")(function* () {
return yield* InstanceState.useEffect(state, (s) => s.defaultInfo())
}),
defaultAgent: Effect.fn("Agent.defaultAgent")(function* () {
return yield* InstanceState.useEffect(state, (s) => s.defaultAgent())
}),
generate: Effect.fn("Agent.generate")(function* (input: {
description: string
model?: { providerID: ProviderV2.ID; modelID: ModelV2.ID }
}) {
const cfg = yield* config.get()
const model = input.model ?? (yield* provider.defaultModel())
const resolved = yield* provider.getModel(
// altimate_change start — re-brand core/fork ID union to fork ProviderID/ModelID (identity at runtime)
ProviderID.make(model.providerID),
ModelID.make(model.modelID),
// altimate_change end
)
const language = yield* provider.getLanguage(resolved)
const tracer = cfg.experimental?.openTelemetry
? Option.getOrUndefined(yield* Effect.serviceOption(OtelTracer.OtelTracer))
: undefined
const system = [PROMPT_GENERATE]
yield* plugin.trigger("experimental.chat.system.transform", { model: resolved }, { system })
const existing = yield* InstanceState.useEffect(state, (s) => s.list())
// TODO: clean this up so provider specific logic doesnt bleed over
const authInfo = yield* auth.get(model.providerID).pipe(Effect.orDie)
const isOpenaiOauth = model.providerID === "openai" && authInfo?.type === "oauth"
const params = {
experimental_telemetry: {
isEnabled: cfg.experimental?.openTelemetry,
tracer,
metadata: {
userId: cfg.username ?? "unknown",
},
},
temperature: 0.3,
messages: [
...(isOpenaiOauth
? []
: 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: Object.assign(
Schema.toStandardSchemaV1(GeneratedAgent),
Schema.toStandardJSONSchemaV1(GeneratedAgent),
),
} satisfies Parameters<typeof generateObject>[0]
if (isOpenaiOauth) {
return yield* Effect.promise(async () => {
const result = streamObject({
...params,
providerOptions: ProviderTransform.providerOptions(resolved, {
instructions: system.join("\n"),
store: false,
}),
onError: () => {},
})
for await (const part of result.fullStream) {
if (part.type === "error") throw part.error
}
return result.object
})
}
return yield* Effect.promise(() => generateObject(params).then((r) => r.object))
}),
})
}),
)
// altimate_change start — Layer.suspend defers facade .defaultLayer reads past circular module-init
export const defaultLayer = Layer.suspend(() =>
layer.pipe(
Layer.provide(Plugin.defaultLayer),
Layer.provide(Provider.defaultLayer),
Layer.provide(Auth.defaultLayer),
Layer.provide(Config.defaultLayer),
Layer.provide(Skill.defaultLayer),
Layer.provide(LocationServiceMap.layer),
),
)
// altimate_change end
const locationServiceMapNode = LayerNode.make(LocationServiceMap.layer, [])
// altimate_change start — upstream_fix: thunk defers reading cyclically-imported facade
// `.node` exports (Plugin/Provider/...) until buildLayer runs, avoiding load-time undefined.
export const node = LayerNode.make(layer, () => [
Config.node,
Auth.node,
Plugin.node,
Skill.node,
Provider.node,
locationServiceMapNode,
])
// altimate_change end
// altimate_change start — restore the imperative Promise wrapper upstream removed in the
// Effect-only migration; the HTTP server consumes Agent.list() directly.
const { runPromise: runAgent } = makeRuntime(Service, defaultLayer as Layer.Layer<Service>)
export async function list() {
return runAgent((s) => s.list())
}
export async function get(agent: string) {
return runAgent((s) => s.get(agent))
}
export async function defaultAgent() {
return runAgent((s) => s.defaultAgent())
}
// altimate_change end
export * as Agent from "./agent"