返回 DeepSeek-Reasonix
boot.go
根目录 / internal / boot / boot.go
1 // Package boot assembles a ready-to-drive control.Controller from configuration:
2 // it loads config, resolves the model(s), builds the tool registry (built-ins +
3 // plugins), wires the permission gate, and constructs the executor — optionally
4 // wrapping it in a two-model Coordinator. It is the one place that turns "what the
5 // user configured" into "a Controller a frontend can drive", so every frontend —
6 // the terminal TUI, the HTTP/SSE server, the desktop webview — shares the exact
7 // same assembly instead of each re-deriving it. Frontends pass only a sink and a
8 // couple of run knobs; everything else comes from config.
9 package boot
10
11 import (
12 "context"
13 "errors"
14 "fmt"
15 "io"
16 "log/slog"
17 "os"
18 "path/filepath"
19 "runtime"
20 "slices"
21 "strconv"
22 "strings"
23 "sync/atomic"
24 "time"
25
26 "reasonix/internal/ablation"
27 "reasonix/internal/agent"
28 "reasonix/internal/agentpreset"
29 "reasonix/internal/billing"
30 "reasonix/internal/browser"
31 "reasonix/internal/capability"
32 "reasonix/internal/command"
33 "reasonix/internal/config"
34 "reasonix/internal/control"
35 "reasonix/internal/environment"
36 "reasonix/internal/event"
37 "reasonix/internal/extension"
38 "reasonix/internal/extension/dispatch"
39 "reasonix/internal/extension/protocol"
40 "reasonix/internal/extension/providerext"
41 "reasonix/internal/extension/sidecar"
42 "reasonix/internal/extension/uihub"
43 "reasonix/internal/gitcmd"
44 "reasonix/internal/guardian"
45 "reasonix/internal/history"
46 "reasonix/internal/hook"
47 "reasonix/internal/imageinput"
48 "reasonix/internal/installsource"
49 "reasonix/internal/jobs"
50 "reasonix/internal/lsp"
51 "reasonix/internal/mcplaunch"
52 "reasonix/internal/memory"
53 "reasonix/internal/migration"
54 "reasonix/internal/netclient"
55 "reasonix/internal/outputstyle"
56 "reasonix/internal/permission"
57 "reasonix/internal/persistentshell"
58 "reasonix/internal/plugin"
59 "reasonix/internal/productdocs"
60 "reasonix/internal/provider"
61 "reasonix/internal/sandbox"
62 "reasonix/internal/secrets"
63 "reasonix/internal/session"
64 "reasonix/internal/sessioncontext"
65 "reasonix/internal/sessiontemp"
66 "reasonix/internal/skill"
67 "reasonix/internal/skill/skillwatch"
68 "reasonix/internal/stats"
69 "reasonix/internal/taskmonitor"
70 "reasonix/internal/tool"
71 "reasonix/internal/tool/builtin"
72 "reasonix/internal/tool/sessiontool"
73 )
74
75 // ErrUnknownModel is returned by Build when the configured model can't be
76 // resolved to a provider — e.g. a default_model left over from a renamed or
77 // removed provider. Callers can detect it (errors.Is) to re-run setup.
78 var ErrUnknownModel = errors.New("unknown model")
79
80 func agentKeepPolicy(keep []string) agent.KeepPolicy {
81 if keep == nil {
82 return agent.KeepErrors | agent.KeepUserMarked
83 }
84 var p agent.KeepPolicy
85 for _, k := range keep {
86 switch strings.TrimSpace(k) {
87 case "errors":
88 p |= agent.KeepErrors
89 case "user_marked":
90 p |= agent.KeepUserMarked
91 }
92 }
93 return p
94 }
95
96 // Options carries the per-run knobs a frontend chooses; everything else is
97 // read from configuration. Model "" falls back to default_model; MaxSteps 0
98 // uses automatic execution; RequireKey fails fast on a missing key.
99 type Options struct {
100 BackgroundScope *jobs.SessionBackgroundScope
101 // ModelSettings supplies an immutable desktop credential-proxy resolver.
102 // The bundle contains virtual tunnel credentials only and stays in memory.
103 ModelSettings *config.ModelRuntimeSettings
104 Model string
105 MaxSteps int
106 MaxStepsKey string
107 RequireKey bool
108 Sink event.Sink
109 // EffortOverride is a session-local reasoning effort override. Nil means use
110 // the resolved provider config; a non-nil empty string means provider default.
111 EffortOverride *string
112 // EffortModel binds an inherited override to its original model. Empty
113 // means this build received an explicit selection for Options.Model.
114 EffortModel string
115 // ConfigSnapshot is an optional, caller-owned immutable configuration for
116 // this assembly. Desktop passes the snapshot used to resolve the selection
117 // so a concurrent settings edit cannot change another role halfway through.
118 ConfigSnapshot *config.Config
119 // PermissionAllow adds process-local allow rules (for example CLI
120 // --allowed-tools). They override configured ask rules but never deny rules
121 // and are not persisted.
122 PermissionAllow []string
123 // AdditionalDirs grants this session's file writers and sandboxed shell
124 // access to extra directories without changing persisted sandbox config.
125 AdditionalDirs []string
126 // Stderr is the writer for diagnostic warnings and plugin subprocess
127 // stderr output. When nil, defaults to os.Stderr. Interactive terminal
128 // frontends must provide a private diagnostic writer (or io.Discard) so
129 // background output cannot corrupt the TUI's terminal raw mode.
130 Stderr io.Writer
131 // WorkspaceRoot is the project root directory for config, skills, memory,
132 // commands, hooks, and tool confinement. When empty, the current working
133 // directory is used (CLI default). Desktop tabs pass their project root here
134 // so each tab loads its own config/skills/hooks without changing the process
135 // cwd — enabling concurrent multi-project sessions.
136 WorkspaceRoot string
137 // StatsSource labels this frontend's usage records (desktop/cli/serve).
138 // Empty disables usage recording for this controller.
139 StatsSource string
140 // FileBranchesOnly keeps fork/branch/switch/rewind on separate session
141 // files instead of heads inside a schema-2 log.
142 FileBranchesOnly bool
143 TaskStore taskmonitor.WriteStore // Authoritative store, never a SQLite catalog.
144 // OnConfigLoadWarnings accepts resilient-loader warnings. Returning true
145 // lets boot suppress the duplicate migration diagnostic.
146 OnConfigLoadWarnings func([]string) bool
147 // ExtraPlugins are session-scoped MCP servers supplied by a host transport
148 // (for example ACP session/new). They are connected eagerly for this
149 // controller but are not persisted to reasonix.toml.
150 ExtraPlugins []plugin.Spec
151 // AgentPreset and TokenMode are retired compatibility inputs. Recognized
152 // values use standard execution; unknown values keep the standard default.
153 AgentPreset string
154 TokenMode string
155 // SessionDir overrides where persisted chat transcripts are written. When
156 // empty, the shared CLI/global session directory is used.
157 SessionDir string
158 // SessionService is shared by all controllers on one host. Rebuild injects
159 // the previous service/runtime so model changes keep the immutable session
160 // identity and writer owned by the same SessionRuntime.
161 SessionService *session.Service
162 SessionCreateService *session.Service
163 SessionRuntime *session.Runtime
164 SessionHostID string
165 SessionCreateOptions session.CreateOptions
166 // NativeLegacySession keeps a controller on the path-addressed session
167 // backend. Hosts set it only when opening an existing legacy transcript;
168 // fresh and already-canonical sessions continue to use SessionService.
169 NativeLegacySession bool
170 // SharedHost is an optional plugin.Host shared across controllers for the
171 // same workspace root. When set, boot.Build reuses its running clients
172 // instead of creating new subprocesses, and the caller manages the host's
173 // lifecycle. When nil, Build creates and owns a new host as before.
174 SharedHost *plugin.Host
175 // SharedSkillWatchService is a caller-owned host watcher; nil gives Build its own.
176 SharedSkillWatchService *skillwatch.Service
177 // MCPHostProfile is the capability surface for hosts Build creates;
178 // ignored when SharedHost is set (it fixed its own profile).
179 MCPHostProfile plugin.HostProfile
180 // CleanupPendingReconciler retries delayed physical cleanup for session
181 // artifacts left by a previous process. Nil uses the core physical-delete
182 // reconciler; frontends with different deletion semantics can override it.
183 CleanupPendingReconciler func(sessionDir string) error
184 // ApprovalTimeout bounds how long a tool-approval or ask prompt blocks for a
185 // user decision. Zero (default) waits forever — correct for an interactive
186 // terminal. Headless/bot frontends pass a positive value so an unanswered
187 // prompt can't wedge the session indefinitely (#4626, #4402).
188 ApprovalTimeout time.Duration
189 // HeadlessApprovalMode selects the non-interactive tool-approval contract
190 // (control.ToolApprovalAuto/DontAsk/Yolo) applied to every headless-only gate
191 // this boot constructs: the top-level executor, task/read_only_task,
192 // writer-capable skill sub-agents, and the planner runner. Empty (or "ask")
193 // keeps the default fail-closed headless gate. Callers that later call
194 // Controller.ApplyHeadlessApprovalMode with a
195 // different mode than they passed here should also pass it here, or
196 // sub-agent gates will not match the parent executor's mode.
197 HeadlessApprovalMode string
198 // Session recovery and transition hooks let frontends keep local ownership metadata aligned.
199 SessionRecoveryMeta func(control.SessionRecoveryRequest) agent.BranchMeta
200 OnSessionRecovered func(control.SessionRecoveryInfo) error
201 OnSessionTransition func(control.SessionTransitionInfo) error
202 OnSessionRotation func(context.Context, control.SessionRotationRequest) (control.SessionRotationPlan, error)
203 BeforeInboxDispatch func(*control.Controller) (func(), error)
204 // OnSessionTitleChanged lets a host project the canonical BranchMeta title
205 // into compatibility indexes and refresh notifications after the current
206 // conversation renames itself through set_session_title.
207 OnSessionTitleChanged sessiontool.TitleChangedFunc
208 // SubagentParentLive reports whether this process currently owns or is
209 // building the parent session. Desktop uses it to avoid probing a live tab's
210 // lease during stale-subagent cleanup. Nil preserves lease-only cleanup.
211 SubagentParentLive func(sessionPath string) bool
212 // FileOverlay and TerminalRunner let a host transport (ACP) serve file
213 // content from editor buffers and run foreground bash in a host terminal.
214 // Both only change where tool I/O happens — tool names, descriptions, and
215 // schemas stay byte-identical, so the provider-visible surface is unchanged.
216 FileOverlay builtin.FileOverlay
217 TerminalRunner builtin.TerminalRunner
218 // BrowserExecutor attaches the host's browser; nil registers nothing. Its
219 // tools are registry-only: use_capability reaches them while the provider-
220 // visible surface never changes, so the cached prompt prefix stays identical.
221 BrowserExecutor browser.Executor
222 // ProviderResolver routes every model role through a caller-owned provider
223 // catalog. Nil preserves local behavior.
224 ProviderResolver provider.Resolver
225 // Ablation switches subsystems off for a benchmark arm, and is also the
226 // process-local hard override supervised ACP workers use to force the planner
227 // off. It wins over user/project configuration without mutating config or
228 // changing the provider-visible prompt/tool surface. The zero value runs
229 // everything.
230 Ablation ablation.Set
231 // SandboxNetworkOverride and WorkspaceOnly are process-local hard bounds for
232 // supervised ACP workers. Nil/false preserve normal Reasonix config.
233 SandboxNetworkOverride *bool
234 SandboxBashOverride string
235 WorkspaceOnly bool
236 PinnedContextLoader control.PinnedContextLoader
237 SessionTemp *sessiontemp.Manager // session-private temp manager; Rebuild reuses old's
238 WorkspaceRepo gitcmd.Repo // git identity the session opened with; Rebuild reuses old's
239 PersistentShell *persistentshell.Manager
240 RuntimeReload
241 // deferPublish keeps a replacement generation private until migration and
242 // commit succeed. Cold BuildRuntime leaves this false and publishes at boot.
243 deferPublish bool
244 }
245
246 func recoveryHeadlessMode(opts Options) bool {
247 return strings.TrimSpace(opts.HeadlessApprovalMode) != ""
248 }
249
250 // build is the assembly body behind BuildRuntime (and the Build compat
251 // wrapper): it loads config, resolves the model(s), wires the full runtime,
252 // and freezes the extension kernel snapshot from the objects it just
253 // assembled. The returned controller owns plugin subprocesses; call Close
254 // (via Controller.Close) to release them.
255 func build(ctx context.Context, opts Options) (*BuildResult, error) {
256 ctx, opts, owner, fileWriteReceipt := bindRuntimeOwner(ctx, opts)
257 stderr := opts.Stderr
258 if stderr == nil {
259 stderr = os.Stderr
260 }
261 root := ResolveWorkspaceRoot(opts.WorkspaceRoot)
262 repo := workspaceRepo(ctx, opts.WorkspaceRepo, root)
263 additionalDirs, err := normalizeAdditionalDirs(root, opts.AdditionalDirs)
264 if err != nil {
265 return nil, err
266 }
267 // Import v1/v0.5 config before Load so this boot sees the new config + ~/.env.
268 // CLI Run also calls this before config-only commands; keep a shared fallback.
269 migrated, migErr := config.MigrateLegacyIfNeededForRoot(root)
270 deepSeekProtocolMigrated, deepSeekProtocolMigErr := config.ApplyUserConfigUpgradesOnStartup(config.UserConfigPath())
271 stepLimitsMigrated, stepLimitMigErr := config.MigrateLegacyAgentStepLimitsForRoot(root)
272 redactToolOutputMigrated, redactToolOutputMigErr := config.MigrateLegacyRedactToolOutputForRoot(root)
273 memoryCompilerMigrated, memoryCompilerMigErr := config.MigrateLegacyMemoryCompilerForRoot(root)
274 multiThresholdMigrated, multiThresholdMigErr := config.MigrateLegacyMultiThresholdCompactionForRoot(root)
275 config.MigrateLegacyMCPTiersForRoot(root)
276 cfg, opts, err := resolveBuildSelection(root, opts)
277 if err != nil {
278 return nil, err
279 }
280 liveSettings := newLiveRuntimeSettings(cfg.Agent.CompactRatio)
281 deepSeekProtocolMigErr = deepSeekProtocolMigrationNoticeError(handleConfigLoadWarnings(opts, cfg), deepSeekProtocolMigErr)
282 if err := preflightRoleReasoning(cfg, opts, opts.ProviderResolver, false); err != nil {
283 return nil, err
284 }
285 // Arm the credential-protection layers from the user-global [secrets]
286 // section before any tool, hook, or plugin subprocess can spawn. Package
287 // globals are correct here because [secrets] is user-global (project
288 // reasonix.toml cannot override it), so concurrent workspaces agree.
289 secrets.SetFilterSubprocessEnv(cfg.Secrets.FilterSubprocessEnv)
290 secrets.SetProtectSensitiveFiles(cfg.Secrets.ProtectSensitiveFiles)
291 secrets.RegisterCredentialEnvKeys(cfg.CredentialEnvNames())
292
293 // Serialize the frontend's sink once: background jobs (below) emit from their
294 // own goroutines, which can overlap a running turn's emission, so every emitter
295 // shares this synchronized sink. It is created before extension preflight so
296 // sidecar warnings and host/ui/* publishes land on the same channel as every
297 // later notice. The job manager is session-scoped — its jobs outlive a turn
298 // and are cancelled by Controller.Close.
299 //
300 // CostQuote must run before every host consumer (stats recorder, CLI
301 // metrics via opts.Sink, ACP/eventwire bridges, Desktop) so all see the
302 // same occurrence-time quote. Order from the agent:
303 // GoalUsageTee → Sync → CostQuote → [Recorder] → frontend
304 // The controller coalesces before its ledger so every consumer shares boundaries.
305 quoteCtx := &event.QuoteContext{
306 DisplayRequest: billing.DisplayRequest{
307 Currency: cfg.ExplicitDisplayCurrency(),
308 Source: billing.DisplaySourceExplicit,
309 },
310 BillingModeForModel: func(modelRef string) string {
311 entry, ok := cfg.ResolveModel(modelRef)
312 if !ok {
313 return ""
314 }
315 return entry.ProviderBillingMode()
316 },
317 PricingContextForModel: func(modelRef string) billing.PricingContext {
318 entry, ok := cfg.ResolveModel(modelRef)
319 if !ok {
320 return billing.PricingContext{}
321 }
322 return entry.PricingContextForModel(entry.Model)
323 },
324 }
325 // Innermost: frontend sink (CLI metrics/ACP/Desktop bridge live here).
326 quoted := opts.Sink
327 // Record billable usage after quoting so history JSONL can store CostQuote.
328 if source := strings.TrimSpace(opts.StatsSource); source != "" {
329 quoted = stats.NewRecorder(quoted, config.StatsDir(), source)
330 }
331 quoted = event.NewCostQuoteSink(quoted, quoteCtx)
332 sink := event.Sync(quoted)
333
334 // Both sink wraps must complete BEFORE the extension UI hub closes over the
335 // sink variable: a sidecar publish during preflight lands on this closure
336 // from a wire-handler goroutine, and any later reassignment races it.
337 // Goal token-budget accounting: the controller detects this tee and
338 // attributes billable usage to the active goal turn's recorder. Both the
339 // tee must ride the shared sink agents emit into directly.
340 sink = control.NewGoalUsageTee(sink)
341
342 // Extension preflight (stages 5b/7): start the installed, enabled v2 runtime
343 // packages ONCE, here, before model resolution, so plugin-namespaced refs
344 // (plugin/<plugin>/<provider>/<model>) resolve on the very first boot and the
345 // same sidecar generation feeds the executor, planner, guardian, sub-agents,
346 // the snapshot assembly, and the frontend catalog. With no runtime package
347 // installed preflight is a no-op and the whole build below takes the
348 // untouched pre-sidecar path. The generation moves up with it: the sidecar
349 // handshake's session context carries this build's generation, and a fresh
350 // controller has no session path yet, so the session ID is generation-scoped
351 // (the handshake only requires a stable, non-empty identity).
352 generation := nextRuntimeGeneration()
353 sessionID := fmt.Sprintf("boot-%d", generation)
354 proxySpec := cfg.NetworkProxySpec()
355 extWarn := func(msg string) {
356 redacted := secrets.RedactCredentials(msg)
357 slog.Warn("boot: extension runtime: "+redacted, "root", root)
358 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: redacted})
359 }
360 // Stage 8a: the host extension UI hub serves every sidecar's host/ui/* calls
361 // for this generation — publications become frontend events through the
362 // controller sink, blocking prompts ride the controller's Ask channel. The
363 // controller only exists after control.New below, so both seams indirect
364 // through ctrlRef; traffic before that (a sidecar publishing during its
365 // handshake) falls back to the same sink directly, matching the emission the
366 // controller would have made.
367 var ctrlRef atomic.Pointer[control.Controller]
368 // Readiness signals for gateExtensionUIRequest: a sidecar may legally
369 // issue host/ui/request right after extension/initialized, before the
370 // controller exists. ready closes at ctrlRef.Store; failed closes on any
371 // build error before the RuntimeSet takes ownership (the pendingMgr defer
372 // below), so a startup request never hangs a dying build.
373 controllerReady := make(chan struct{})
374 controllerBuildFailed := make(chan struct{})
375 extUIHub := uihub.New(uihub.Options{
376 SessionID: sessionID,
377 Generation: generation,
378 Owner: owner,
379 Emit: func(ev event.Event) {
380 if c := ctrlRef.Load(); c != nil {
381 c.EmitExtensionEvent(ev)
382 return
383 }
384 sink.Emit(ev)
385 },
386 Request: func(reqCtx context.Context, req uihub.HubRequest) (map[string]any, bool, error) {
387 return gateExtensionUIRequest(reqCtx, ctrlRef.Load, controllerReady, controllerBuildFailed,
388 func(c *control.Controller) (map[string]any, bool, error) {
389 return uihub.AskRequestFunc(c.Ask)(reqCtx, req)
390 })
391 },
392 Warn: func(msg string) {
393 slog.Warn("boot: extension UI hub: "+msg, "root", root)
394 },
395 })
396 extensionMgr, err := preflightExtensionRuntimes(ctx, config.ReasonixHomeDir(), extensionBoot{
397 session: protocol.SessionContext{SessionID: sessionID, WorkspaceRoot: root, Generation: generation},
398 ui: extUIHub,
399 onWarning: extWarn,
400 }, opts.Extensions, planForPreflight(opts, generation))
401 if err != nil {
402 return nil, fmt.Errorf("boot: %w", err)
403 }
404 // Until the RuntimeSet takes ownership at snapshot assembly, every error
405 // path between here and there must retire the preflighted sidecars — no
406 // process may outlive a failed build.
407 pendingMgr := extensionMgr
408 defer func() {
409 if pendingMgr != nil {
410 close(controllerBuildFailed)
411 _ = pendingMgr.Close()
412 }
413 }()
414
415 // The build's provider resolution base: the caller-owned broker when
416 // injected, the local config-backed resolver otherwise. When a started
417 // sidecar declares providers, fold them in NOW (stage 7) with the
418 // provider:<ref> slot claims from the same manifest data the kernel's
419 // ReplaceClaims pass uses, so first-boot model resolution sees them. A
420 // conflict with the base catalog that lacks the plugin's claim is fatal,
421 // the same class as a required runtime that cannot start: booting without
422 // the declared provider would silently change what the session is.
423 modelCapabilities := config.NewModelCapabilityResolver()
424 baseResolver := opts.ProviderResolver
425 if baseResolver == nil {
426 baseResolver = NewLocalProviderResolverWithCapabilities(cfg, proxySpec, modelCapabilities)
427 }
428 effectiveResolver := opts.ProviderResolver
429 if effectiveResolver == nil {
430 effectiveResolver = baseResolver
431 }
432 var extensionResolver provider.Resolver
433 if extensionMgr != nil {
434 declares := false
435 for _, client := range extensionMgr.Clients() {
436 if len(client.Handshake().Providers) > 0 {
437 declares = true
438 break
439 }
440 }
441 if declares {
442 claims, claimsErr := resolveReplacementClaims(extensionMgr.Contributions())
443 if claimsErr != nil {
444 return nil, fmt.Errorf("boot: %w", claimsErr)
445 }
446 merged, mergeErr := mergeSidecarProviders(baseResolver, extensionMgr, claims, owner)
447 if mergeErr != nil {
448 return nil, fmt.Errorf("boot: %w", mergeErr)
449 }
450 installSidecarStreamRouters(extensionMgr, merged)
451 effectiveResolver = merged
452 extensionResolver = merged
453 }
454 }
455
456 // Fall through a keyless default_model to the next configured chat model
457 // instead of hard-failing every command on "missing env X_API_KEY" (issue
458 // #6996). The fallback only kicks in when the caller did not pass an
459 // explicit opts.Model; explicit choices still fail loudly.
460 if err := preflightRoleReasoning(cfg, opts, effectiveResolver, true); err != nil {
461 return nil, err
462 }
463 modelName := opts.Model
464 if modelName == "" {
465 if resolved, _, ok := cfg.ResolveNewSessionChatModel(); ok {
466 modelName = resolved
467 }
468 }
469 // opts.AgentPreset/opts.TokenMode now seed the session quality floor (see
470 // the SetQualityFloor call after control.New); light folds to standard.
471 keepPolicy := agentKeepPolicy(cfg.Agent.Keep)
472 // Entry resolution: the caller-owned broker is authoritative for every
473 // ref; the extension-merged resolver only owns plugin refs — a config ref
474 // keeps the full config entry (kind, endpoint, credentials, balance URL,
475 // missing-key notice), exactly as without extensions installed.
476 entryResolver := opts.ProviderResolver
477 if entryResolver == nil && extensionResolver != nil && providerext.PluginRefOwner(modelName) != "" {
478 entryResolver = extensionResolver
479 }
480 entry, modelRef, err := resolveModelEntry(entryResolver, cfg, modelName)
481 if err != nil {
482 return nil, err
483 }
484 if opts.EffortOverride != nil {
485 entry.Effort = *opts.EffortOverride
486 if entry.Kind == "anthropic" && strings.TrimSpace(entry.Effort) != "" && strings.TrimSpace(entry.Thinking) == "" {
487 entry.Thinking = "adaptive"
488 }
489 }
490 // RequireKey fails fast on a missing credential (run/serve); plugin-
491 // namespaced refs carry no config credential — the extension provider holds
492 // its own keys — so the merged resolver's resolution is their only gate.
493 authentication := authenticationStateForModelEntry(entry, modelRef)
494 if opts.RequireKey && opts.ProviderResolver == nil && providerext.PluginRefOwner(modelName) == "" {
495 if err := cfg.Validate(modelName); err != nil {
496 if entry.RequiresAPIKey() && entry.APIKey() == "" {
497 authentication.Message = err.Error()
498 return nil, &control.AuthenticationError{State: authentication}
499 }
500 return nil, err
501 }
502 }
503
504 if migErr != nil {
505 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "Config migration did not complete.", Detail: "config migration from ~/.reasonix failed: " + migErr.Error()})
506 } else if migrated != nil {
507 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: migrated.Notice()})
508 }
509 emitUserConfigUpgradeNotice(sink, cfg, deepSeekProtocolMigrated, deepSeekProtocolMigErr, config.TakeProviderEndpointRepairReceipts(config.UserConfigPath()))
510 if stepLimitsMigrated || cfg.IgnoredLegacyAgentStepLimits() {
511 level := event.LevelInfo
512 text := "Deprecated agent step limits were removed."
513 detail := "[agent].max_steps and planner_max_steps are no longer used; Reasonix now manages interactive progress automatically. " +
514 "Use the CLI --max-steps flag for a one-off run or [bot].max_steps for unattended bot sessions."
515 if stepLimitMigErr != nil {
516 level = event.LevelWarn
517 text = "Deprecated agent step limits were ignored."
518 detail += " The old keys were ignored but could not be removed: " + stepLimitMigErr.Error()
519 }
520 sink.Emit(event.Event{
521 Kind: event.Notice,
522 Level: level,
523 Text: text,
524 Detail: detail,
525 })
526 } else if stepLimitMigErr != nil {
527 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "Deprecated agent step-limit migration did not complete.", Detail: stepLimitMigErr.Error()})
528 }
529 if redactToolOutputMigrated || redactToolOutputMigErr != nil {
530 level := event.LevelInfo
531 text := "Deprecated redact_tool_output setting was removed."
532 detail := "[secrets].redact_tool_output no longer has any effect: ordinary model/tool content and local session/job artifacts now preserve their original text. Explicit diagnostics and reasonix doctor redact-sessions still redact credential values."
533 if redactToolOutputMigErr != nil {
534 level = event.LevelWarn
535 text = "Deprecated redact_tool_output setting was ignored."
536 detail += " The old key could not be removed: " + redactToolOutputMigErr.Error()
537 }
538 sink.Emit(event.Event{Kind: event.Notice, Level: level, Text: text, Detail: detail})
539 }
540 if memoryCompilerMigrated || memoryCompilerMigErr != nil {
541 level := event.LevelInfo
542 text := "Deprecated memory_compiler setting was removed."
543 detail := "The Memory v5 execution compiler has been removed from Reasonix: [agent].memory_compiler no longer has any effect, user turns are never replaced by compiled execution contracts, and no compiler state is written. Old transcripts containing compiled turns still display normally."
544 if memoryCompilerMigErr != nil {
545 level = event.LevelWarn
546 text = "Deprecated memory_compiler setting was ignored."
547 detail += " The old key could not be removed: " + memoryCompilerMigErr.Error()
548 }
549 sink.Emit(event.Event{Kind: event.Notice, Level: level, Text: text, Detail: detail})
550 }
551 if multiThresholdMigrated || multiThresholdMigErr != nil {
552 level := event.LevelInfo
553 text := "上下文维护已简化为单一自动压缩阈值。"
554 detail := "Context maintenance now uses a single automatic compact_ratio (default 0.80). soft_compact_ratio, tool_result_snip_ratio, compact_force_ratio, cold_resume_prune, and context_editing were removed from config."
555 if multiThresholdMigErr != nil {
556 level = event.LevelWarn
557 text = "Deprecated multi-threshold compaction keys were ignored."
558 detail += " The old keys could not be removed: " + multiThresholdMigErr.Error()
559 }
560 sink.Emit(event.Event{Kind: event.Notice, Level: level, Text: text, Detail: detail})
561 }
562 migration.MigrateLegacyMemorySources(sink)
563 migration.MigrateLegacySessionSources(sink)
564 if ignored := cfg.IgnoredProjectDefaultModel(); ignored != "" {
565 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "Ignored the project config's default_model.", Detail: fmt.Sprintf("./reasonix.toml sets default_model = %q but no configured provider serves it; using %q from your user config instead. Edit or remove that default_model line to silence this notice.", ignored, cfg.DefaultModel)})
566 }
567
568 // A resolvable model whose API key env is unset would otherwise build fine
569 // (RequireKey is false so the UI stays reachable) and then fail silently on the
570 // first request, showing as an empty/dead model. Surface the cause up front.
571 if !opts.RequireKey && !authentication.Ready() {
572 if authentication.Status == control.AuthenticationCredentialStoreUnavailable {
573 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "The credential store is unavailable.", Detail: "Reasonix could not read its credential file; open credential diagnostics before retrying"})
574 } else {
575 sink.Emit(event.Event{Kind: event.Notice, Text: "Selected model is missing its API key.", Detail: fmt.Sprintf("model %q is selected but its API key %s is not set — requests will fail until you set it", modelName, entry.APIKeyEnv)})
576 }
577 }
578 backgroundScope, err := acquireBackgroundScope(opts.BackgroundScope, root, sink, cfg.BackgroundJobStalledWarningSeconds())
579 if err != nil {
580 return nil, err
581 }
582 workspaceLease := backgroundScope.WorkspaceLease
583 backgroundOwned := false
584 var stagedBackgroundController *control.Controller
585 defer func() {
586 if !backgroundOwned {
587 releaseBackgroundBuild(backgroundScope, stagedBackgroundController)
588 }
589 }()
590 jm := backgroundScope.Manager
591 sessionDir := opts.SessionDir
592 if sessionDir == "" {
593 sessionDir = config.SessionDir()
594 }
595 // The host owns the final-format SessionService. Boot only attaches an
596 // Agent to the exact service/runtime it receives; constructing a service
597 // here would create competing registries over the same writer files during
598 // model switches or multi-tab startup.
599 sessionService := opts.SessionService
600 if err := opts.validateSessionBinding(); err != nil {
601 return nil, err
602 }
603 reconcileCleanupPending := opts.CleanupPendingReconciler
604 if reconcileCleanupPending == nil {
605 reconcileCleanupPending = control.ReconcileCleanupPending
606 }
607 if err := reconcileCleanupPending(sessionDir); err != nil {
608 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "cleanup-pending reconciliation failed: " + err.Error()})
609 }
610
611 // proxySpec was computed during extension preflight (the merged resolver's
612 // local base needs it); validate it before any provider construction.
613 if err := netclient.Validate(proxySpec); err != nil {
614 return nil, err
615 }
616 balanceClient, err := netclient.NewHTTPClient(proxySpec, netclient.TransportOptions{})
617 if err != nil {
618 return nil, err
619 }
620 execProv, err := resolveProvider(effectiveResolver, cfg, proxySpec, provider.Selection{Ref: modelRef, Effort: opts.EffortOverride})
621 if err != nil {
622 return nil, err
623 }
624 shell := sandbox.ResolveShell(cfg.Tools.Shell.Prefer, cfg.Tools.Shell.Path, stderr)
625
626 sysPrompt, err := cfg.ResolveSystemPromptForRoot(root)
627 if err != nil {
628 if !config.IsMissingSystemPromptFile(err) {
629 return nil, err
630 }
631 // A stale missing prompt file must not block startup: warn and fall back
632 // to the inline (or built-in default) system prompt. Other read failures
633 // stay fatal so Reasonix never runs without explicitly configured policy.
634 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: err.Error() + "; falling back to inline/default system prompt"})
635 sysPrompt = cfg.InlineSystemPrompt()
636 }
637 // Output style: fold the selected persona/tone block into the base prompt
638 // before language/memory/skills append, so a "replace" style (keep-coding
639 // false) still keeps those. Applied once, into the cache-stable prefix.
640 if st, ok := outputstyle.Resolve(cfg.Agent.OutputStyle, outputstyle.Dirs()); ok {
641 sysPrompt = outputstyle.Apply(sysPrompt, st)
642 }
643 sysPrompt = appendCorePolicies(sysPrompt)
644 sysPrompt += "\n\n" + sessioncontext.PolicyBlock()
645 sessionContextStatic := sessioncontext.Sections{Workspace: currentWorkspacePromptLine(root)}
646 // Execution modes no longer exist. Host obligations are fact-driven and
647 // never rewrite the cache-stable system prefix or tool schemas.
648 if cfg.EnvironmentEnabled() {
649 shellLabel := resolvedShellLabel(shell, cfg.Tools.Shell.Path, os.Getenv("SHELL"))
650 envSection := environment.FormatSection(
651 environment.RunProbesWithOptions(ctx, environment.DefaultProbes(), environment.ProbeOptions{
652 Overrides: cfg.Environment.Tools,
653 DenyRoots: []string{root},
654 // Persist probe results across restarts so transient probe flaps do
655 // not generate needless session-context replacements.
656 SnapshotDir: config.CacheDir(),
657 }),
658 runtime.GOOS+"/"+runtime.GOARCH,
659 shellLabel,
660 cfg.Environment.Tools,
661 )
662 sessionContextStatic.Environment = envSection
663 }
664 sessionContextStatic.Environment = appendOfflineEnvironmentNote(sessionContextStatic.Environment, cfg.Environment.Offline)
665
666 // Stable memory policy and REASONIX.md / AGENTS.md standing instructions
667 // enter the system prompt. Pinned facts and the background index remain in
668 // the controller-owned session-context snapshot.
669 if _, err := memory.StoreFor(config.MemoryUserDir(), root).MigrateV2(); err != nil {
670 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "Memory metadata migration did not complete.", Detail: err.Error()})
671 }
672 mem := memory.Load(memory.Options{CWD: root, UserDir: config.MemoryUserDir()})
673 sysPrompt = memory.Compose(sysPrompt, mem)
674
675 implicitSkillInvocation := cfg.ImplicitSkillInvocationEnabled()
676 watchSkills := watchSkillsEnabled()
677 // Skills: rediscovery skipped on no-op/interceptor/UI rebuilds when
678 // ReuseAssembly is retained from the previous BuildResult.
679 var skillStore *skill.Store
680 var skills []skill.Skill
681 var allSkillStore *skill.Store
682 var allSkills []skill.Skill
683 skillWatchService, hostOwnedWatch := buildSkillWatchService(opts.SharedSkillWatchService, watchSkills, opts.Stderr)
684 skillCleanup := func() { closeSkillsWithWatcher(skillStore, allSkillStore, &skillWatchService, hostOwnedWatch) }
685 skillsOwned := false
686 defer closeUnownedSkills(&skillsOwned, skillCleanup)
687 canReuseSkills := opts.ReuseAssembly != nil && shouldReuseDiscovery(opts.PreviousPlan) &&
688 opts.ReuseAssembly.ImplicitSkillInvocation == implicitSkillInvocation
689 if canReuseSkills {
690 skills = opts.ReuseAssembly.Skills
691 allSkills = skills
692 skillStore = skill.New(skill.Options{ProjectRoot: root, Stderr: io.Discard, Watch: watchSkills, WatchService: skillWatchService})
693 allSkillStore = skillStore
694 if s := strings.TrimSpace(opts.ReuseAssembly.SystemPrompt); s != "" {
695 sysPrompt = s
696 }
697 } else {
698 skillStore = skill.New(skill.Options{
699 ProjectRoot: root, CustomPaths: cfg.SkillCustomPaths(), PluginPaths: cfg.PluginPackageSkillOwners(),
700 PluginAgentPaths: cfg.PluginPackageAgentOwners(), ExcludedPaths: cfg.SkillExcludedPaths(),
701 DisabledNames: cfg.DisabledSkillNames(), MaxDepth: cfg.SkillMaxDepth(), Stderr: opts.Stderr, Watch: watchSkills,
702 WatchService: skillWatchService,
703 })
704 skillStore.ConfigureInvocationPolicy("", nil)
705 skills = skillStore.List()
706 allSkillStore = skill.New(skill.Options{ProjectRoot: root, CustomPaths: cfg.SkillCustomPaths(), PluginPaths: cfg.PluginPackageSkillOwners(), PluginAgentPaths: cfg.PluginPackageAgentOwners(), ExcludedPaths: cfg.SkillExcludedPaths(), MaxDepth: cfg.SkillMaxDepth(), Stderr: io.Discard, Watch: watchSkills, WatchService: skillWatchService})
707 allSkills = allSkillStore.List()
708 if implicitSkillInvocation {
709 sysPrompt += "\n\n" + skill.InvocationPolicyBlock()
710 }
711 }
712 sysPrompt = config.ApplyOfficialDeepSeekV4ProPersona(sysPrompt, entry)
713
714 reg := tool.NewRegistry()
715 writeRoots := cfg.WriteRootsForRoot(root)
716 writeRoots = appendUniquePaths(writeRoots, additionalDirs...)
717 if opts.WorkspaceOnly {
718 writeRoots = []string{root}
719 }
720 networkEnabled := cfg.Sandbox.Network
721 if opts.SandboxNetworkOverride != nil {
722 networkEnabled = *opts.SandboxNetworkOverride
723 }
724 bashMode := cfg.BashMode()
725 if override := strings.TrimSpace(opts.SandboxBashOverride); override != "" {
726 bashMode = override
727 }
728 forbidReadRoots := RuntimeForbidReadRoots(cfg, root)
729 // managedConfig names the Reasonix-owned config FILES (config.toml,
730 // compatibility TOMLs, legacy v0.x config.json) the file-writers gate behind
731 // a fresh per-write human approval wherever they sit, inside the roots too.
732 // The bash OS-sandbox write roots stay unwidened: config repair goes through
733 // the approval-gated file tools, not raw shell writes.
734 managedConfig := builtin.NewManagedConfigPaths(config.ReasonixManagedConfigPaths())
735 bashSpec := sandbox.Spec{Mode: bashMode, WriteRoots: writeRoots, ForbidReadRoots: forbidReadRoots, Network: networkEnabled}
736 bashSpec.Shell = shell
737 // The session-data guard blocks agent writes into Reasonix's own session
738 // stores (they race the app's saves and surface as conflict-copy loops);
739 // explicit allow_write entries stay a sanctioned escape hatch.
740 allowWriteRoots := cfg.AllowWriteRoots()
741 if opts.WorkspaceOnly {
742 allowWriteRoots = nil
743 }
744 sessionGuard := builtin.NewSessionDataGuard(config.MemoryUserDir(), allowWriteRoots)
745 writeRootSet := sandbox.NewWritableRootSet(writeRoots)
746 bashSpec.ProtectedWriteRoots = sandbox.ProtectedWriteRoots(config.MemoryUserDir())
747 if bashSpec.Mode == "enforce" && !sandbox.Available() {
748 fmt.Fprintln(stderr, "warning: "+sandbox.UnavailableMessage())
749 }
750 searchSpec := builtin.ResolveSearch(cfg.Tools.Search.Engine, cfg.Tools.Search.RgPath, stderr)
751 bashTimeout := time.Duration(cfg.BashTimeoutSeconds()) * time.Second
752 enabledBuiltins := cfg.Tools.Enabled
753 readPathResolver := builtin.NewPathResolver()
754 sessionTemp, persistentShell := sessionManagers(opts)
755 // Register the full built-in inventory for use_capability dispatch. The
756 // provider-visible surface is narrowed later via SetProviderVisibleTools.
757 addBuiltins(reg, enabledBuiltins, writeRoots, writeRootSet, bashSpec, bashTimeout, searchSpec, stderr, root, proxySpec, forbidReadRoots, readPathResolver, sessionGuard, managedConfig, opts.FileOverlay, opts.TerminalRunner, sessionTemp, fileWriteReceipt)
758 bindPersistentShell(reg, persistentShell)
759 addWebSearch(reg, cfg, entry, proxySpec, sink)
760 browserExec, closeBrowser := browserBackend(opts.BrowserExecutor, cfg.Browser, writeRoots)
761 if browserExec != nil {
762 for _, t := range browser.Tools(browserExec) {
763 reg.Add(t)
764 }
765 for _, t := range browser.CapabilityTools(browserExec) {
766 reg.Add(t)
767 }
768 }
769 // Use the caller-supplied shared host when set, so controllers for the same
770 // workspace root reuse running MCP processes (e.g. one CodeGraph daemon
771 // instead of one per tab). Otherwise construct a private host per controller.
772 pluginHost := opts.SharedHost
773 if pluginHost == nil {
774 pluginHost = plugin.NewHostWithProfile(opts.MCPHostProfile)
775 }
776
777 // Enabled MCP servers enter the tool catalog at boot. Cached schemas
778 // register placeholders without starting processes; cache-miss servers get
779 // a single background catalog discovery. First real tool call uses
780 // EnsureConnected so parent/child/tab runtimes share one process.
781 pluginSpecOptions := PluginSpecOptions{
782 DefaultStartupTimeout: time.Duration(cfg.MCPStartupTimeoutSeconds()) * time.Second,
783 DefaultCallTimeout: time.Duration(cfg.MCPCallTimeoutSeconds()) * time.Second,
784 LaunchManager: mcplaunch.ForWorkspace(config.ReasonixHomeDir(), root),
785 ConfigSource: "workspace_config",
786 StateHome: config.ReasonixHomeDir(),
787 WriterRoots: writeRoots,
788 ForbidReadRoots: forbidReadRoots,
789 Network: networkEnabled,
790 PackageOwners: pluginPackageOwners(cfg),
791 OAuthHTTPClient: balanceClient,
792 }
793 autoStartEntries := cfg.EnabledPlugins(root, config.DefaultMCPActivationStore())
794 emitProjectMCPDecisionNotice(sink, cfg, root)
795 enabledMCPNames := make(map[string]bool, len(autoStartEntries))
796 for _, enabled := range autoStartEntries {
797 if name := strings.TrimSpace(enabled.Name); name != "" {
798 enabledMCPNames[name] = true
799 }
800 }
801 // Legacy eager/background tiers are still parsed for config compatibility
802 // but no longer change process start timing. Keep the partition only so
803 // demotion notices remain meaningful for chronically slow eager configs.
804 eagerEntries, bgEntries := partitionByTier(autoStartEntries)
805 extraSpecs := applyDefaultMCPStartupTimeout(
806 applyDefaultMCPCallTimeout(
807 applyKnownPluginOverrides(opts.ExtraPlugins, root),
808 pluginSpecOptions.DefaultCallTimeout,
809 ),
810 pluginSpecOptions.DefaultStartupTimeout,
811 )
812 for i := range extraSpecs {
813 if strings.TrimSpace(extraSpecs[i].WorkspaceRoot) == "" {
814 extraSpecs[i].WorkspaceRoot = root
815 }
816 if extraSpecs[i].LaunchManager == nil {
817 extraSpecs[i].LaunchManager = pluginSpecOptions.LaunchManager
818 }
819 if strings.TrimSpace(extraSpecs[i].ConfigSource) == "" {
820 extraSpecs[i].ConfigSource = "host_session"
821 }
822 if !extraSpecs[i].RequireLaunchApproval {
823 // Session-scoped MCP specs arrive through an explicit host/user action
824 // (for example ACP session/new), so they follow installed-server
825 // authorization without another per-tool or per-session prompt.
826 extraSpecs[i].Authorized = true
827 }
828 applyMCPIsolation(&extraSpecs[i], root, pluginSpecOptions)
829 }
830 // Auto-demote: any eager plugin that has been chronically slow (recent
831 // samples repeatedly hit the blocking startup budget) drops to background
832 // for this session. The user keeps eager intent, just doesn't pay for it
833 // on a server that's been misbehaving. A notice surfaces the demotion.
834 var demoteMessages []string
835 budget := plugin.DefaultStartupBudget()
836 kept := eagerEntries[:0]
837 for _, e := range eagerEntries {
838 rec := plugin.Recommend(e.Name, budget, 0)
839 if rec.Demote {
840 demoteMessages = append(demoteMessages, rec.Reason)
841 bgEntries = append(bgEntries, e)
842 continue
843 }
844 kept = append(kept, e)
845 }
846 eagerEntries = kept
847
848 eagerSpecs := PluginSpecsForRootWithOptions(eagerEntries, root, pluginSpecOptions)
849 bgSpecs := PluginSpecsForRootWithOptions(bgEntries, root, pluginSpecOptions)
850
851 eagerSpecs = append(eagerSpecs, extraSpecs...)
852
853 // Apply caller-supplied stderr override to every spec across tiers.
854 if opts.Stderr != nil {
855 for i := range eagerSpecs {
856 eagerSpecs[i].Stderr = opts.Stderr
857 }
858 for i := range bgSpecs {
859 bgSpecs[i].Stderr = opts.Stderr
860 }
861 }
862
863 // Host-session ExtraPlugins (for example ACP session servers) are explicit
864 // for this controller and still take a short readiness probe so recovery and
865 // session-scoped servers are deterministic. User/project config MCP stays
866 // catalog-first and process-idle until first real tool call.
867 if len(extraSpecs) > 0 {
868 for _, s := range extraSpecs {
869 if pluginHost.HasClient(s.Name) {
870 if tools, err := pluginHost.ToolsFor(ctx, s.Name); err == nil {
871 for _, t := range tools {
872 reg.Add(t)
873 }
874 continue
875 }
876 }
877 addCtx, addCancel := context.WithTimeout(ctx, 5*time.Second)
878 tools, err := pluginHost.EnsureConnectedWithLifecycle(ctx, addCtx, s, 0)
879 addCancel()
880 if err != nil {
881 if plugin.IsServerAlreadyConnected(err) {
882 if tools, err2 := pluginHost.ToolsFor(ctx, s.Name); err2 == nil {
883 for _, t := range tools {
884 reg.Add(t)
885 }
886 continue
887 }
888 }
889 // Leave a catalog entry for diagnostics; failures surface in /mcp.
890 cs, _ := plugin.LoadCachedSchemaForSpec(s)
891 for _, t := range plugin.LazyToolset(s, cs, pluginHost, reg, ctx, false) {
892 reg.Add(t)
893 }
894 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn,
895 Text: "An MCP server failed to start.", Detail: fmt.Sprintf("mcp %s: %v", s.Name, err)})
896 continue
897 }
898 for _, t := range tools {
899 reg.Add(t)
900 }
901 }
902 }
903
904 // Configured enabled MCP: cache-hit placeholders without starting processes;
905 // cache-miss servers get one background catalog discovery.
906 registerEnabledMCP := func(specs []plugin.Spec) {
907 for _, s := range specs {
908 if pluginHost.HasClient(s.Name) {
909 tools, err := pluginHost.ToolsFor(ctx, s.Name)
910 if err == nil {
911 for _, t := range tools {
912 reg.Add(t)
913 }
914 continue
915 }
916 }
917 cs, _ := plugin.LoadCachedSchemaForSpec(s)
918 // Only kick a process for catalog discovery when no usable schema is
919 // cached. Cache-hit sessions stay process-idle until first tool call.
920 kick := cs == nil || len(cs.Tools) == 0
921 for _, t := range plugin.LazyToolset(s, cs, pluginHost, reg, ctx, kick) {
922 reg.Add(t)
923 }
924 }
925 }
926 // eagerSpecs already includes extraSpecs; avoid double
927 // registration of host-session servers that connected above.
928 configSpecs := append(append([]plugin.Spec{}, eagerSpecs...), bgSpecs...)
929 if len(extraSpecs) > 0 {
930 extraNames := map[string]bool{}
931 for _, s := range extraSpecs {
932 extraNames[s.Name] = true
933 }
934 filtered := configSpecs[:0]
935 for _, s := range configSpecs {
936 if extraNames[s.Name] {
937 continue
938 }
939 filtered = append(filtered, s)
940 }
941 configSpecs = filtered
942 }
943 registerEnabledMCP(configSpecs)
944
945 for _, msg := range demoteMessages {
946 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: msg})
947 }
948
949 cleanup := func() {
950 skillCleanup()
951 pluginHost.Close()
952 }
953 if opts.SharedHost != nil {
954 // The caller owns the shared host's lifecycle; the controller must not
955 // close it. A no-op cleanup keeps Controller.Close happy without
956 // shutting down MCP processes that other controllers still use.
957 cleanup = skillCleanup
958 }
959
960 // addTools registers tools on reg and returns the names that were added.
961 addTools := func(reg *tool.Registry, tools []tool.Tool) []string {
962 names := make([]string, 0, len(tools))
963 for _, t := range tools {
964 if t == nil {
965 continue
966 }
967 reg.Add(t)
968 names = append(names, t.Name())
969 }
970 return names
971 }
972
973 // LSP tools resolve their servers on PATH and spawn lazily on first query, so
974 // registering them is cheap even when no server is installed (a query then
975 // returns an install hint). The manager is session-scoped; chain its shutdown
976 // into the controller's cleanup so servers stop with the session, not the turn.
977 var lspMgr *lsp.Manager
978 lspToolsAdded := false
979 addLSPTools := func() []string {
980 if lspMgr == nil || lspToolsAdded {
981 return nil
982 }
983 lspToolsAdded = true
984 return addTools(reg, lsp.Tools(lspMgr))
985 }
986 if cfg.LSP.Enabled {
987 lspMgr = lsp.NewManager(root, verifiedLSPSpecs(cfg))
988 addLSPTools()
989 prev := cleanup
990 cleanup = func() { prev(); lspMgr.Close() }
991 }
992
993 maxSteps := max(opts.MaxSteps, 0)
994 subagentStore, err := newSubagentStore(sessionDir, opts.SubagentParentLive)
995 if err != nil {
996 return nil, err
997 }
998 if subagentStore != nil {
999 subagentStore.WithDestroyedChecker(jm.IsDestroying)
1000 }
1001
1002 // Permission policy gates every tool call. With no HeadlessApprovalMode
1003 // (interactive bootstrap), the temporary gate preserves the legacy behavior
1004 // until chat/desktop installs an interactive gate. A real headless caller
1005 // such as `reasonix run` always supplies a mode: Ask fails closed, Auto
1006 // allows ordinary writer fallbacks, and DontAsk denies them (#6927).
1007 // The selected contract is also applied to sub-agents, so they cannot be a
1008 // weaker path around the parent gate.
1009 // Sub-agents always run headless: they have no UI to answer a prompt, so they
1010 // inherit this same gate.
1011 policy := permission.New(cfg.Permissions.Mode, cfg.Permissions.Allow, cfg.Permissions.Ask, cfg.Permissions.Deny).
1012 WithSessionAllow(opts.PermissionAllow)
1013 emitUnmatchableRuleNotice(sink, cfg.Permissions.Allow, cfg.Permissions.Ask, cfg.Permissions.Deny)
1014 headlessGate := control.NewSharedHeadlessGate(policy, opts.HeadlessApprovalMode)
1015
1016 var resolvedHooks []hook.ResolvedHook
1017 if opts.ReuseAssembly != nil && shouldReuseDiscovery(opts.PreviousPlan) {
1018 resolvedHooks = opts.ReuseAssembly.Hooks
1019 } else {
1020 resolvedHooks = hook.Load(hook.LoadOptions{ProjectRoot: root})
1021 }
1022 hookRunner := newBootHookRunner(resolvedHooks, root, shell, sink)
1023 // The `task` tool spawns sub-agents that reuse the parent's provider and
1024 // tool registry. Wired here after the built-ins / plugins are loaded so
1025 // sub-agents inherit the full tool set (minus `task` itself, to keep
1026 // nesting out of the picture). It registers into the same reg the
1027 // executor uses, so the model surfaces it like any other tool.
1028 resolveSubagentProvider := func(modelRef, effort string) (provider.Provider, *provider.Pricing, int, error) {
1029 me, selectedRef, err := subagentModelSelection(cfg, effectiveResolver, entry, modelRef)
1030 if err != nil {
1031 return nil, nil, 0, err
1032 }
1033 var effortOverride *string
1034 if strings.TrimSpace(effort) != "" {
1035 normalized, err := config.NormalizeEffort(&me, effort)
1036 if err != nil {
1037 if effectiveResolver == nil {
1038 return nil, nil, 0, err
1039 }
1040 normalized = effort
1041 }
1042 me.Effort = normalized
1043 effortOverride = &normalized
1044 if me.Kind == "anthropic" && strings.TrimSpace(me.Effort) != "" && strings.TrimSpace(me.Thinking) == "" {
1045 me.Thinking = "adaptive"
1046 }
1047 }
1048 p, err := resolveProvider(effectiveResolver, cfg, proxySpec, provider.Selection{Ref: selectedRef, Effort: effortOverride})
1049 if err != nil {
1050 return nil, nil, 0, err
1051 }
1052 return p, me.Price, me.ContextWindow, nil
1053 }
1054 subagentIdentity := func(modelRef, effort string) (string, string) {
1055 return subagentEffectiveIdentity(cfg, opts.ProviderResolver, modelName, entry, modelRef, effort)
1056 }
1057 taskModel := firstNonEmpty(cfg.Agent.SubagentModels["task"], cfg.Agent.SubagentModel)
1058 subagentEffort := subagentEffortDefault(cfg, entry, sink)
1059 maxSubagentDepth := agent.NormalizeMaxSubagentDepth(cfg.Agent.MaxSubagentDepth)
1060 maxSubagentConcurrency, maxParallelWriters := agent.NormalizeConcurrencyLimits(
1061 cfg.Agent.MaxSubagentConcurrency, cfg.Agent.MaxParallelWriters,
1062 )
1063 subagentScheduler := agent.NewSubagentScheduler(maxSubagentConcurrency, maxParallelWriters)
1064 profileLookup := func(name string) (agent.ProfileDefinition, bool) {
1065 sk, ok := skillStore.Read(name)
1066 if !ok || sk.RunAs != skill.RunSubagent {
1067 return agent.ProfileDefinition{}, false
1068 }
1069 return agent.ProfileFromSkill(skillStore.Prepare(sk)), true
1070 }
1071 profileConfigModel := func(profile string) string {
1072 for _, key := range SubagentModelKeys(profile) {
1073 if m := strings.TrimSpace(cfg.Agent.SubagentModels[key]); m != "" {
1074 return m
1075 }
1076 }
1077 return ""
1078 }
1079 profileConfigEffort := func(profile string) string {
1080 for _, key := range SubagentModelKeys(profile) {
1081 if e := strings.TrimSpace(cfg.Agent.SubagentEfforts[key]); e != "" {
1082 return e
1083 }
1084 }
1085 return ""
1086 }
1087 bashSandboxEnforced := bashSpec.Enforce
1088 taskToolAdded := false
1089 readOnlyTaskToolAdded := false
1090 var taskTool *agent.TaskTool
1091 // capRuntime is assigned after MCP specs load; closures capture the variable
1092 // so task tools created later still receive the session-shared substrate.
1093 var capRuntime *agent.MCPCapabilityRuntime
1094 visionProviderResolver := func(ref string) (provider.Provider, error) {
1095 ve, ok := resolveOptionalEntry(effectiveResolver, cfg, strings.TrimSpace(ref))
1096 if !ok || ve == nil || strings.TrimSpace(ve.Model) == "" {
1097 return nil, fmt.Errorf("unknown vision model %q", ref)
1098 }
1099 return resolveProvider(effectiveResolver, cfg, proxySpec, provider.Selection{Ref: modelRefFromEntry(ve)})
1100 }
1101 visionModelSelector := func(currentRef, _ string) (string, bool) {
1102 current, ok := resolveOptionalEntry(effectiveResolver, cfg, strings.TrimSpace(currentRef))
1103 if !ok || current == nil {
1104 return "", false
1105 }
1106 for i := range cfg.Providers {
1107 p := &cfg.Providers[i]
1108 if p.Name != current.Name || !p.Configured() {
1109 continue
1110 }
1111 models := p.ModelList()
1112 ordered := make([]string, 0, len(models))
1113 if d := p.DefaultModel(); d != "" {
1114 ordered = append(ordered, d)
1115 }
1116 for _, model := range models {
1117 if model != "" && model != p.DefaultModel() {
1118 ordered = append(ordered, model)
1119 }
1120 }
1121 for _, model := range ordered {
1122 candidate, found := cfg.ResolveModel(p.Name + "/" + model)
1123 if found && candidate.Configured() && modelCapabilities.Resolve(candidate).State == config.CapabilitySupported {
1124 return candidate.Name + "/" + candidate.Model, true
1125 }
1126 }
1127 }
1128 return "", false
1129 }
1130
1131 imageConfig := &imageinput.Config{Model: cfg.Agent.VisionModel, Resolve: visionProviderResolver, Select: visionModelSelector}
1132 newTaskTool := func() *agent.TaskTool {
1133 return agent.NewTaskToolWithOptions(agent.TaskToolOptions{
1134 ImageInput: imageConfig,
1135 Provider: execProv,
1136 Pricing: entry.Price,
1137 QuoteContext: quoteCtx,
1138 HooksForSession: func(id string) agent.ToolHooks { return hookRunner.ForSession(id) },
1139 ParentRegistry: reg,
1140 MaxSteps: maxSteps,
1141 ContextWindow: entry.ContextWindow,
1142 RecentKeep: cfg.Agent.RecentKeep,
1143 SoftCompactRatio: cfg.Agent.SoftCompactRatio,
1144 ToolResultSnipRatio: cfg.Agent.ToolResultSnipRatio,
1145 CompactRatio: cfg.Agent.CompactRatio,
1146 CompactRatioSource: liveSettings.compactRatio,
1147 CompactForceRatio: cfg.Agent.CompactForceRatio,
1148 ContextEditing: cfg.Agent.ContextEditing,
1149 Temperature: cfg.Agent.Temperature,
1150 ArchiveDir: config.ArchiveDir(),
1151 SysPrompt: "",
1152 Gate: headlessGate,
1153 KeepPolicy: keepPolicy,
1154 SubagentModel: taskModel,
1155 SubagentEffort: firstNonEmpty(cfg.Agent.SubagentEfforts["task"], subagentEffort),
1156 ResolveProvider: resolveSubagentProvider,
1157 }).
1158 WithTranscripts(subagentStore, root, modelName, entry.Effort).
1159 WithTranscriptIdentityResolver(subagentIdentity).
1160 WithMaxSubagentDepth(maxSubagentDepth).
1161 WithAblation(opts.Ablation).
1162 WithWorkspaceLease(workspaceLease).
1163 WithScheduler(subagentScheduler).
1164 WithProfileLookup(profileLookup).
1165 WithProfileConfigResolvers(profileConfigModel, profileConfigEffort).
1166 WithBashSandboxEnforced(bashSandboxEnforced).
1167 WithCapabilityRuntime(capRuntime).
1168 WithWriteRoots(writeRootSet).WithImageRequestResolver(controllerImageResolver{ctrlRef.Load})
1169 }
1170 addTaskTool := func() string {
1171 if opts.Ablation.Off(ablation.Subagent) {
1172 return "task tool is disabled for this run."
1173 }
1174 if taskToolAdded {
1175 return "task tool is already enabled."
1176 }
1177 taskToolAdded = true
1178 if taskTool == nil {
1179 taskTool = newTaskTool()
1180 }
1181 // The registry exports schemas in stable name order. Keep this surface
1182 // static: profile names and result refs never enter provider-visible
1183 // schemas, and the result reader does not change between turns.
1184 reg.Add(taskTool)
1185 reg.Add(agent.NewParallelTasksTool(taskTool, reg))
1186 reg.Add(agent.NewFleetTool(taskTool))
1187 reg.Add(agent.NewSubagentResultTool(taskTool))
1188 return "enabled task."
1189 }
1190 addReadOnlyTaskTool := func() string {
1191 if opts.Ablation.Off(ablation.Subagent) {
1192 return "read_only_task tool is disabled for this run."
1193 }
1194 if readOnlyTaskToolAdded {
1195 return "read_only_task tool is already enabled."
1196 }
1197 readOnlyTaskToolAdded = true
1198 if taskTool == nil {
1199 taskTool = newTaskTool()
1200 }
1201 reg.Add(agent.NewReadOnlyTaskTool(taskTool))
1202 return "enabled read_only_task."
1203 }
1204 addTaskTool()
1205 addReadOnlyTaskTool()
1206
1207 // Product documentation, session, and memory tools are always present on the
1208 // unified host registry for every role setting. Provider-visible surface stays
1209 // lean via use_capability; these tools are dispatchable without schema growth.
1210 docsToolAdded := false
1211 addDocsTool := func() string {
1212 if docsToolAdded {
1213 return "docs is already enabled."
1214 }
1215 docsToolAdded = true
1216 reg.Add(productdocs.NewTool())
1217 return "enabled docs."
1218 }
1219 sessionToolsAdded := false
1220 addSessionTools := func() string {
1221 if sessionToolsAdded {
1222 return "sessions are already enabled."
1223 }
1224 sessionToolsAdded = true
1225 // history and memory are the BM25-backed surfaces; the ablation arm drops
1226 // only those two and leaves the direct-access tools alone, so a lost solve
1227 // is attributable to retrieval and not to a missing session reader.
1228 if opts.Ablation.Off(ablation.Retrieval) {
1229 reg.Add(sessiontool.NewListSessionsTool(sessionDir))
1230 reg.Add(sessiontool.NewReadSessionTool(sessionDir))
1231 return "enabled list_sessions, read_session."
1232 }
1233 reg.Add(history.NewIndexedTool(history.Options{SessionDir: sessionDir, GlobalSessionDir: config.SessionDir(), ArchiveDir: config.ArchiveDir()}))
1234 reg.Add(sessiontool.NewListSessionsTool(sessionDir))
1235 reg.Add(sessiontool.NewReadSessionTool(sessionDir))
1236 return "enabled history, list_sessions, read_session."
1237 }
1238 memoryToolsAdded := false
1239 addMemoryTools := func() string {
1240 if memoryToolsAdded {
1241 return "memory tools are already enabled."
1242 }
1243 memoryToolsAdded = true
1244 if opts.Ablation.Off(ablation.Retrieval) {
1245 reg.Add(memory.NewRememberTool(mem.Store))
1246 reg.Add(memory.NewForgetTool(mem.Store))
1247 return "enabled remember, forget."
1248 }
1249 reg.Add(memory.NewRecallTool(mem.Store))
1250 reg.Add(memory.NewRememberTool(mem.Store))
1251 reg.Add(memory.NewForgetTool(mem.Store))
1252 return "enabled memory, remember, forget."
1253 }
1254 addDocsTool()
1255 addSessionTools()
1256 addMemoryTools()
1257
1258 // The `ask` tool puts structured multiple-choice questions to the user. It
1259 // reaches them through the Asker on the call context, which interactive
1260 // frontends wire to the controller (EnableInteractiveApproval); a headless run
1261 // has none, so ask resolves to "decide for yourself".
1262 registerInteractiveAgentTools(reg)
1263
1264 // Skill tools: read_only_skill is a narrow explicitly read-only entry point; the
1265 // full skills source adds run_skill / install_skill plus the dedicated
1266 // subagent wrappers (explore / research / review / security_review). Read-only
1267 // subagent skills run ephemerally with the same registry boundary as
1268 // read_only_task, so they cannot write, install, mutate memory, resume/fork
1269 // transcripts, or delegate further.
1270 //
1271 subagentSkillOptions := liveSettings.skillOptions(newSubagentSkillOptionsFactory(cfg.Agent, quoteCtx, headlessGate, keepPolicy, maxSubagentDepth, opts.Ablation, workspaceLease, writeRootSet, hookRunner, childImageRouting{ctrlRef.Load, imageConfig}))
1272 readOnlySkillRunner := func(sctx context.Context, sk skill.Skill, task string, runOpts skill.SubagentRunOptions) (string, error) {
1273 if strings.TrimSpace(runOpts.ContinueFrom) != "" || strings.TrimSpace(runOpts.ForkFrom) != "" {
1274 return "", fmt.Errorf("read_only_skill does not support continue_from/fork_from")
1275 }
1276 releaseSlot, err := subagentScheduler.Acquire(sctx, agent.AcquireRequest{
1277 Writer: false,
1278 Nested: agent.SubagentDepth(sctx) > 0,
1279 Label: sk.Name,
1280 })
1281 if err != nil {
1282 return "", err
1283 }
1284 defer releaseSlot()
1285 sk = skill.WithCodeGraphTools(sk, skill.CodeGraphReadTools(reg))
1286 prov, price, ctxWin := execProv, entry.Price, entry.ContextWindow
1287 modelRef := subagentModelRef(cfg, sk)
1288 effortRef := subagentEffortRef(cfg, sk, subagentEffort)
1289 if modelRef != "" || effortRef != "" {
1290 p, pr, cw, err := resolveSubagentProvider(modelRef, effortRef)
1291 if err != nil {
1292 return "", fmt.Errorf("read-only subagent skill %q profile: %w", sk.Name, err)
1293 }
1294 prov, price, ctxWin = p, pr, cw
1295 }
1296 childDepth := agent.SubagentDepth(sctx) + 1
1297 if childDepth > maxSubagentDepth {
1298 return "", fmt.Errorf("subagent delegation depth limit reached (max_subagent_depth=%d)", maxSubagentDepth)
1299 }
1300 subReg := agent.ReadOnlySubagentToolRegistryForDepthWithRuntime(reg, sk.AllowedTools, childDepth, maxSubagentDepth, capRuntime)
1301 if subReg.Len() == 0 {
1302 return "", fmt.Errorf("read_only_skill: skill %q has no read-only tools available", sk.Name)
1303 }
1304 steps := maxSteps
1305 if steps > 0 {
1306 if steps /= 2; steps < 5 {
1307 steps = 5
1308 }
1309 }
1310 // Custom and named built-in profiles fully control their system prompt
1311 // (no implicit concise/DefaultReadOnlyTaskSystemPrompt overlay).
1312 sysPrompt := strings.TrimSpace(sk.Body)
1313 if sysPrompt == "" {
1314 sysPrompt = agent.DefaultReadOnlyTaskSystemPrompt
1315 }
1316 task, runOptions := reviewSubagentSkillOptions(sctx, sk.Name, task, steps, price, ctxWin, childDepth, subagentSkillOptions)
1317 usageModelRef, _ := subagentIdentity(modelRef, effortRef)
1318 runOptions.ModelRef = usageModelRef
1319 // Review gates consume typed, host-verifiable reports so a review
1320 // cannot end in unverifiable prose. Review skills run only for
1321 // mid/high-risk work under the standard policy.
1322 runOptions.RequireReviewReportKind = ""
1323 // Provider serializers decide whether these images are wire-visible from
1324 // the child model's own vision capability. Text-only children retain the
1325 // attachment metadata locally but never receive image parts on the wire.
1326 childCtx := agent.WithUserImages(sctx, agent.SubagentImageCandidates(sctx))
1327 return runReadOnlySkillSession(childCtx, prov, subReg, task, runOptions, agent.NestedSink(sctx, event.Discard), sysPrompt, agent.RunReadOnlySubAgentWithSession)
1328 }
1329 // Writer-capable subagent skills reuse the sub-agent machinery via this
1330 // runner: an isolated loop with the skill body as system prompt, a tool set
1331 // scoped to the skill's allowed-tools (minus recursive meta-tools), optional
1332 // per-skill model, and resumable transcripts when the parent session supports
1333 // them. Its tool activity nests under the invoking call, like `task`.
1334 skillRunner := func(sctx context.Context, sk skill.Skill, task string, runOpts skill.SubagentRunOptions) (string, error) {
1335 // Writer skills without write_paths claim the whole workspace so they
1336 // cannot race fleet/task writers that declared disjoint paths.
1337 acq := agent.AcquireRequest{
1338 Writer: !sk.ReadOnly,
1339 Nested: agent.SubagentDepth(sctx) > 0,
1340 Label: sk.Name,
1341 }
1342 if !sk.ReadOnly {
1343 whole, werr := agent.WholeWorkspaceWriteClaim(root)
1344 if werr != nil {
1345 return "", fmt.Errorf("subagent skill %q write claim: %w", sk.Name, werr)
1346 }
1347 acq.WritePaths = whole
1348 }
1349 releaseSlot, err := subagentScheduler.Acquire(sctx, acq)
1350 if err != nil {
1351 return "", err
1352 }
1353 defer releaseSlot()
1354 sk = skill.WithCodeGraphTools(sk, skill.CodeGraphReadTools(reg))
1355 prov, price, ctxWin := execProv, entry.Price, entry.ContextWindow
1356 modelRef := subagentModelRef(cfg, sk)
1357 effortRef := subagentEffortRef(cfg, sk, subagentEffort)
1358 if modelRef != "" || effortRef != "" {
1359 p, pr, cw, err := resolveSubagentProvider(modelRef, effortRef)
1360 if err != nil {
1361 return "", fmt.Errorf("subagent skill %q profile: %w", sk.Name, err)
1362 }
1363 prov, price, ctxWin = p, pr, cw
1364 }
1365 childDepth := agent.SubagentDepth(sctx) + 1
1366 if childDepth > maxSubagentDepth {
1367 return "", fmt.Errorf("subagent delegation depth limit reached (max_subagent_depth=%d)", maxSubagentDepth)
1368 }
1369 // A read-only skill (builtin review/security-review, or frontmatter
1370 // `read-only: true`) gets its promise enforced at the tool boundary:
1371 // writer tools are stripped and bash runs under the read-only
1372 // command policy. Transcripts recorded against the writer-capable
1373 // registry stop matching on continue_from (schema-hash check reports
1374 // the mismatch).
1375 subReg, childWriteRoots := skillSubagentRegistry(sk, reg, childDepth, maxSubagentDepth, capRuntime, writeRootSet)
1376 continueFrom := strings.TrimSpace(runOpts.ContinueFrom)
1377 legacyForkFrom := strings.TrimSpace(runOpts.ForkFrom)
1378 if continueFrom != "" && legacyForkFrom != "" {
1379 return "", fmt.Errorf("continue_from and fork_from are mutually exclusive; pass only continue_from")
1380 }
1381 parentID, parentSink, _, _ := agent.CallContext(sctx)
1382 if runOpts.HostInitiated {
1383 parentID = ""
1384 }
1385 parentSession := agent.ParentSession(sctx)
1386 var run *agent.SubagentRun
1387 if subagentStore == nil || parentSession == "" {
1388 // Headless runs (e.g. `reasonix run`) have no persistent session to
1389 // own a transcript. Run the skill sub-agent ephemerally, as before
1390 // persisted transcripts existed, instead of failing. Continuation needs
1391 // a persisted owner, so it errors here.
1392 if continueFrom != "" || legacyForkFrom != "" {
1393 return "", fmt.Errorf("subagent continuation requires a persisted session; none is active in this run")
1394 }
1395 run = agent.EphemeralSubagentRun(sk.Body)
1396 } else {
1397 identityModel, identityEffort := subagentIdentity(modelRef, effortRef)
1398 spec := agent.SubagentSpec{
1399 Kind: "skill",
1400 Name: sk.Name,
1401 WorkspaceRoot: root,
1402 ParentSession: parentSession,
1403 ParentToolCallID: parentID,
1404 SystemPrompt: sk.Body,
1405 Registry: subReg,
1406 Model: identityModel,
1407 Effort: identityEffort,
1408 }
1409 var prepErr error
1410 if continueFrom != "" {
1411 run, prepErr = subagentStore.PrepareContinue(continueFrom, spec)
1412 } else if legacyForkFrom != "" {
1413 run, prepErr = subagentStore.PrepareLegacyForkFrom(legacyForkFrom, spec)
1414 } else {
1415 run, prepErr = subagentStore.PrepareFresh(spec)
1416 }
1417 if prepErr != nil {
1418 return "", prepErr
1419 }
1420 }
1421 defer run.Release()
1422 steps := maxSteps
1423 if steps > 0 {
1424 if steps /= 2; steps < 5 {
1425 steps = 5
1426 }
1427 }
1428 task, runOptions := reviewSubagentSkillOptions(sctx, sk.Name, task, steps, price, ctxWin, childDepth, subagentSkillOptions)
1429 if run.Ref != "" {
1430 // A resumed skill has a new call ID but keeps the same transcript.
1431 runOptions.Hooks = hookRunner.ForSession("subagent:" + run.Ref)
1432 }
1433 runOptions.WriteRoots = childWriteRoots
1434 usageModelRef, _ := subagentIdentity(modelRef, effortRef)
1435 runOptions.ModelRef = usageModelRef
1436 announceSkillSubagentStart(parentSink, parentID, sk.Name, usageModelRef, effortRef, run, continueFrom != "" || legacyForkFrom != "")
1437 // Review gates consume typed, host-verifiable reports so a review
1438 // cannot end in unverifiable prose. Review skills run only for
1439 // mid/high-risk work under the standard policy.
1440 runOptions.RequireReviewReportKind = ""
1441 var answer string
1442 // The child provider owns the final vision decision, as in read-only runs.
1443 childCtx := agent.WithUserImages(sctx, agent.SubagentImageCandidates(sctx))
1444 agent.EmitSubagentLifecycle(parentSink, "child_running", parentID, sk.Name, usageModelRef, effortRef, run, nil)
1445 if sk.ReadOnly {
1446 answer, err = agent.RunReadOnlySubAgentWithSession(childCtx, prov, subReg, run.Session, task,
1447 runOptions, agent.NestedSink(sctx, event.Discard))
1448 } else {
1449 answer, err = agent.RunSubAgentWithSession(childCtx, prov, subReg, run.Session, task,
1450 runOptions, agent.NestedSink(sctx, event.Discard))
1451 }
1452 if err != nil {
1453 return finishSkillSubagentFailure(sctx, taskTool, subagentStore, parentSink, parentID, sk.Name, usageModelRef, effortRef, task, run, err)
1454 }
1455 if err := saveSubagentCompleted(subagentStore, run); err != nil {
1456 return finishSkillSubagentFailure(sctx, taskTool, subagentStore, parentSink, parentID, sk.Name, usageModelRef, effortRef, task, run, err)
1457 }
1458 agent.EmitSubagentLifecycle(parentSink, "child_completed", parentID, sk.Name, usageModelRef, effortRef, run, &agent.SubagentOutcome{Status: agent.SubagentOutcomeCompleted, FinalAnswer: answer})
1459 return agent.FormatSubagentRunResult(answer, run, false), nil
1460 }
1461 skillProfile := func(sk skill.Skill) *event.Profile {
1462 model, effort := subagentModelRef(cfg, sk), subagentEffortRef(cfg, sk, subagentEffort)
1463 if model == "" && effort == "" {
1464 return nil
1465 }
1466 return &event.Profile{Model: model, Effort: effort}
1467 }
1468 var cmds []command.Command
1469 if opts.ReuseAssembly != nil && shouldReuseDiscovery(opts.PreviousPlan) {
1470 cmds = opts.ReuseAssembly.Commands
1471 } else {
1472 cmds, _ = command.LoadRoots(config.CommandRootsForRoot(root)...)
1473 }
1474 slashCommandAdded := false
1475 slashCommandIncludesSkills := false
1476 addSlashCommandTool := func(includeSkills bool) string {
1477 if slashCommandAdded && (!includeSkills || slashCommandIncludesSkills) {
1478 return "slash commands are already enabled."
1479 }
1480 // Expose loaded slash commands to the model via slash_command. In economy
1481 // mode skills join this list only after the skills source is enabled.
1482 var slashEntries []command.SlashEntry
1483 if includeSkills && implicitSkillInvocation {
1484 for _, sk := range skillStore.SlashList() {
1485 slashEntries = append(slashEntries, command.SlashEntry{
1486 Name: sk.SlashName(),
1487 Description: sk.Description,
1488 Render: func(args []string) string {
1489 return skill.RenderInvocation(skillStore.Prepare(sk), strings.Join(args, " "))
1490 },
1491 })
1492 }
1493 }
1494 for _, cmd := range cmds {
1495 if cmd.Hidden {
1496 continue
1497 }
1498
1499 slashEntries = append(slashEntries, command.SlashEntry{
1500 Name: cmd.Name,
1501 Description: cmd.Description,
1502 ArgHint: cmd.ArgHint,
1503 Render: func(args []string) string { return cmd.Render(args) },
1504 })
1505 }
1506 reg.Add(command.NewSlashCommandTool(slashEntries))
1507 slashCommandAdded = true
1508 slashCommandIncludesSkills = slashCommandIncludesSkills || includeSkills
1509 return "enabled slash_command."
1510 }
1511 installSourceAdded := false
1512 addInstallSourceTool := func() string {
1513 if installSourceAdded {
1514 return "install_source is already enabled."
1515 }
1516 installSourceAdded = true
1517 reg.Add(installsource.NewTool(installsource.Options{
1518 ProjectRoot: root,
1519 HTTPClient: balanceClient,
1520 ConnectMCP: func(e config.PluginEntry) (installsource.MCPConnectResult, error) {
1521 spec := pluginSpecFromEntryWithOptions(e, root, pluginSpecOptions)
1522 if opts.Stderr != nil {
1523 spec.Stderr = opts.Stderr
1524 }
1525 // Applying an install plan is already an explicit user decision.
1526 // Project-scoped installs retain project provenance, but record the
1527 // exact durable launch grant now so neither this connection nor the
1528 // next session asks the user to authorize the same install again.
1529 launchAuthorized := false
1530 if spec.RequireLaunchApproval {
1531 if err := plugin.AuthorizeSpecLaunch(ctx, spec); err != nil {
1532 return installsource.MCPConnectResult{}, err
1533 }
1534 launchAuthorized = true
1535 }
1536 tools, err := pluginHost.Add(ctx, spec)
1537 if err != nil {
1538 // The install did not complete, so do not retain consent for a
1539 // server that never connected. Replacement rollback reauthorizes
1540 // the previous project entry before reconnecting it.
1541 if launchAuthorized && spec.LaunchManager != nil {
1542 _ = spec.LaunchManager.Revoke(spec.Name)
1543 }
1544 return installsource.MCPConnectResult{}, err
1545 }
1546 reg.RemovePrefix(plugin.ToolPrefix(spec.Name))
1547 for _, t := range tools {
1548 reg.Add(t)
1549 }
1550 // Disconnect closes the server and drops its namespaced tools.
1551 // Used by the install_source rollback path when SaveTo fails.
1552 disconnect := func() {
1553 if prefix, ok := pluginHost.Remove(spec.Name); ok {
1554 reg.RemovePrefix(prefix)
1555 }
1556 if spec.LaunchManager != nil {
1557 _ = spec.LaunchManager.Revoke(spec.Name)
1558 }
1559 }
1560 return installsource.MCPConnectResult{
1561 ToolCount: len(tools),
1562 Disconnect: disconnect,
1563 }, nil
1564 },
1565 OnDisconnect: func(serverName string) bool {
1566 if prefix, ok := pluginHost.Remove(serverName); ok {
1567 reg.RemovePrefix(prefix)
1568 return true
1569 }
1570 return false
1571 },
1572 }))
1573 return "enabled install_source."
1574 }
1575 readOnlySkillToolsAdded := false
1576 addReadOnlySkillTools := func() string {
1577 if !implicitSkillInvocation {
1578 return "automatic skill invocation is disabled; use an explicit /skill command instead."
1579 }
1580 if readOnlySkillToolsAdded {
1581 return "read_only_skill tool is already enabled.\n\n" + skill.ReadOnlyIndexBlock(skills)
1582 }
1583 readOnlySkillToolsAdded = true
1584 reg.Add(skill.NewReadOnlySkillTool(skillStore, gateSubagentArm(opts.Ablation, readOnlySkillRunner), skillProfile))
1585 return "enabled read_only_skill. Use read_only_skill for inline skills or read-only subagent skills on the next model request.\n\n" + skill.ReadOnlyIndexBlock(skills)
1586 }
1587 skillToolsAdded := false
1588 addSkillTools := func() string {
1589 if !implicitSkillInvocation {
1590 return "automatic skill invocation is disabled; use an explicit /skill command instead."
1591 }
1592 if skillToolsAdded {
1593 return "skills are already enabled.\n\n" + skill.IndexBlock(skills)
1594 }
1595 skillToolsAdded = true
1596 addReadOnlySkillTools()
1597 reg.Add(skill.NewRunSkillTool(skillStore, gateSubagentArm(opts.Ablation, skillRunner), skillProfile))
1598 reg.Add(skill.NewReadSkillTool(skillStore))
1599 reg.Add(skill.NewInstallSkillTool(skillStore, nil))
1600 for _, t := range builtinSubagentTools(opts.Ablation, skillStore, skillRunner, skillProfile) {
1601 reg.Add(t)
1602 }
1603 addSlashCommandTool(implicitSkillInvocation)
1604 return "enabled skills. Use run_skill/read_skill/read_only_skill or the dedicated skill tools on the next model request.\n\n" + skill.IndexBlock(skills)
1605 }
1606 addInstallSourceTool()
1607 if implicitSkillInvocation {
1608 addSkillTools()
1609 } else {
1610 addSlashCommandTool(false)
1611 }
1612
1613 // Session-shared MCP runtime: Host, specs, and connection snapshots. Each
1614 // agent gets its own use_capability frontend (ledger/audit isolation) while
1615 // reusing processes. Delivery puts a frontend on the executor registry;
1616 // dual-model Planner and all task/fleet sub-agents get their own frontends
1617 // without inheriting dynamic mcp__* schemas.
1618 var capLedger *capability.Ledger
1619 var capAudit *capability.Audit
1620 capEntries, capSpecs := capabilityServerInventory(cfg.Plugins, root, pluginSpecOptions, extraSpecs, enabledMCPNames)
1621 cachedTools, cacheKeyOK := capability.LoadCachedToolsForSpecs(capSpecs, pluginHost.Profile())
1622 skillStore.ConfigureToolBindings(func(sk skill.Skill) []tool.MCPBinding {
1623 return skillMCPBindings(sk, reg, capSpecs, cachedTools, cacheKeyOK)
1624 })
1625 var capProxy *agent.UseCapabilityTool
1626 // Catalog closes over capRuntime so proxy-connected tools stay routable.
1627 // Include non-provider-visible tools that use_capability can dispatch while
1628 // omitting replay-only compatibility aliases from discovery.
1629 catalogFn := func() capability.Catalog {
1630 conn := map[string]bool{}
1631 failedNow := map[string]string{}
1632 if pluginHost != nil {
1633 for _, n := range pluginHost.ServerNames() {
1634 conn[n] = true
1635 }
1636 for _, failure := range pluginHost.Failures() {
1637 failedNow[failure.Name] = failure.Error
1638 }
1639 }
1640 skillSnapshot, skillSnapshotErr := skillStore.Snapshot(ctx)
1641 catOpts := capability.CatalogOptions{
1642 Tools: reg.CapabilityContractEntries(),
1643 Skills: skillSnapshot.Candidates,
1644 Plugins: cfg.Plugins,
1645 Connected: conn,
1646 Failed: failedNow,
1647 CachedTools: cachedTools,
1648 CacheKeyOK: cacheKeyOK,
1649 CatalogIncomplete: skillSnapshotErr != nil || !skillSnapshot.Complete,
1650 CatalogStale: skillSnapshot.Stale,
1651 }
1652 if capRuntime != nil {
1653 catOpts.Plugins, catOpts.CachedTools, catOpts.CacheKeyOK, catOpts.Disabled, catOpts.ProxyTools = capRuntime.CapabilityCatalogState()
1654 }
1655 return capability.BuildCatalog(catOpts)
1656 }
1657 // Always build the capability runtime and provider-visible use_capability
1658 // proxy so all three role settings share one tool schema.
1659 capRuntime = agent.NewMCPCapabilityRuntime(ctx, pluginHost, capSpecs, reg, catalogFn)
1660 capRuntime.ConfigureServers(capEntries, capSpecs, enabledMCPNames)
1661 capLedger = capability.NewLedger()
1662 capAudit = &capability.Audit{}
1663 capProxy = capRuntime.NewFrontend(capLedger, capAudit)
1664 reg.Add(capProxy)
1665 skillStore.ConfigureInvocationPolicy("", func(requires []string) []string {
1666 connected := map[string]bool{}
1667 failedNow := map[string]string{}
1668 if pluginHost != nil {
1669 for _, name := range pluginHost.ServerNames() {
1670 connected[name] = true
1671 }
1672 for _, failure := range pluginHost.Failures() {
1673 failedNow[failure.Name] = failure.Error
1674 }
1675 }
1676 catOpts := capability.CatalogOptions{
1677 Tools: reg.CapabilityContractEntries(),
1678 Skills: skillStore.List(),
1679 Plugins: cfg.Plugins,
1680 Connected: connected,
1681 Failed: failedNow,
1682 CachedTools: cachedTools,
1683 CacheKeyOK: cacheKeyOK,
1684 }
1685 if capRuntime != nil {
1686 catOpts.Plugins, catOpts.CachedTools, catOpts.CacheKeyOK, catOpts.Disabled, catOpts.ProxyTools = capRuntime.CapabilityCatalogState()
1687 }
1688 catalog := capability.BuildCatalog(catOpts)
1689 _, missing := catalog.RequiresReady(requires)
1690 return missing
1691 })
1692
1693 execSess := newObservedSession(sysPrompt)
1694 executor := agent.New(execProv, reg, execSess, agent.Options{
1695 ImageInput: imageConfig,
1696 MaxSteps: maxSteps,
1697 MaxStepsKey: opts.MaxStepsKey,
1698 Temperature: cfg.Agent.Temperature,
1699 TaskBudget: taskBudgetFromConfig(cfg),
1700 Pricing: entry.Price,
1701 QuoteContext: quoteCtx,
1702 ModelRef: modelRef,
1703 Gate: headlessGate,
1704 Hooks: hookRunner,
1705 Jobs: jm,
1706 // Parent write reservation at the executor entry covers all writers
1707 // (including late Economy/MCP adds) without wrapping tool schemas.
1708 WriteScheduler: subagentScheduler,
1709 WriteWorkspaceRoot: root,
1710 SessionTemp: sessionTemp,
1711 WriteRoots: writeRootSet,
1712 HomeDir: userHomeDir(),
1713 StateRoot: config.MemoryUserDir(),
1714 Ablation: opts.Ablation,
1715 WorkspaceLease: workspaceLease,
1716 CapabilityLedger: capLedger,
1717 CapabilityAudit: capAudit,
1718 ContextWindow: entry.ContextWindow,
1719 MaxOutputTokens: entry.MaxOutputTokens,
1720 SoftCompactRatio: cfg.Agent.SoftCompactRatio,
1721 ToolResultSnipRatio: cfg.Agent.ToolResultSnipRatio,
1722 CompactRatio: cfg.Agent.CompactRatio,
1723 CompactRatioSource: liveSettings.compactRatio,
1724 CompactForceRatio: cfg.Agent.CompactForceRatio,
1725 ContextEditing: cfg.Agent.ContextEditing,
1726 RecentKeep: cfg.Agent.RecentKeep,
1727 ArchiveDir: config.ArchiveDir(),
1728 KeepPolicy: keepPolicy,
1729 ReasoningLanguage: config.ReasoningLanguageForEntry(entry, cfg.ReasoningLanguage()),
1730 PlanModeReadOnlyCommands: cfg.Agent.PlanModeReadOnlyCommands,
1731 SubagentDepth: 0,
1732 MaxSubagentDepth: maxSubagentDepth,
1733 MissingReasoningWarnStateDir: config.MissingReasoningWarnStateDir(),
1734 }, sink)
1735 reg.Add(sessiontool.NewSetSessionTitleEventTool(
1736 func() string {
1737 if controller := ctrlRef.Load(); controller != nil {
1738 if ref, ok := controller.SessionRef(); ok {
1739 return ref.SessionID
1740 }
1741 }
1742 return ""
1743 },
1744 func(ctx context.Context, title string) error {
1745 controller := ctrlRef.Load()
1746 if controller == nil {
1747 return errors.New("current session is unavailable")
1748 }
1749 if err := controller.SetSessionTitle(ctx, title); err != nil {
1750 return err
1751 }
1752 if opts.OnSessionTitleChanged != nil {
1753 ref, _ := controller.SessionRef()
1754 return opts.OnSessionTitleChanged(sessionDir, ref.SessionID, title)
1755 }
1756 return nil
1757 },
1758 ))
1759
1760 var runner agent.Runner = executor
1761 label := entry.Model
1762 // A distinct planner_model wraps the executor in a Coordinator with its own
1763 // session (cache stability), the standing memory context, read-only research
1764 // tools and its own hook session, so it inspects code without side effects.
1765 pm := effectivePlannerModel(cfg, opts)
1766 pe, plannerResolved := resolveOptionalEntry(effectiveResolver, cfg, pm)
1767 if pm != "" && !plannerResolved {
1768 return nil, fmt.Errorf("planner_model %q is not a configured provider", pm)
1769 }
1770 if pm != "" && plannerResolved {
1771 plannerProv, err := resolveProvider(effectiveResolver, cfg, proxySpec, provider.Selection{Ref: modelRefFromEntry(pe)})
1772 if err != nil {
1773 return nil, fmt.Errorf("planner_model %q: %w", pm, err)
1774 }
1775 plannerContext := mem.SystemBlock()
1776 if implicitSkillInvocation {
1777 plannerContext = strings.TrimSpace(plannerContext + "\n\n" + skill.ReadOnlyInvocationPolicyBlock())
1778 }
1779 plannerSess := agent.NewSession(agent.PlannerPromptWithContext(plannerContext))
1780 // Planner owns an independent ledger/audit and use_capability frontend
1781 // so its MCP calls cannot satisfy or poison Executor Delivery gates.
1782 plannerLedger := capability.NewLedger()
1783 plannerAudit := &capability.Audit{}
1784 plannerTools := agent.PlannerToolRegistry(reg)
1785 if capRuntime != nil {
1786 // Replace any cloned parent frontend with one bound to the
1787 // planner ledger (PlannerToolRegistry clones with nil ledger).
1788 if _, ok := plannerTools.Get("use_capability"); ok {
1789 plannerTools.RemovePrefix("use_capability")
1790 }
1791 plannerTools.Add(capRuntime.NewFrontend(plannerLedger, plannerAudit))
1792 }
1793 plannerOpts := agent.Options{
1794 ImageInput: imageConfig,
1795 MaxSteps: 0,
1796 Gate: headlessGate,
1797 Hooks: hookRunner.ForRole("planner"),
1798 ModelRef: modelRefFromEntry(pe),
1799 QuoteContext: quoteCtx,
1800 ContextWindow: pe.ContextWindow,
1801 SoftCompactRatio: cfg.Agent.SoftCompactRatio,
1802 ToolResultSnipRatio: cfg.Agent.ToolResultSnipRatio,
1803 CompactRatio: cfg.Agent.CompactRatio,
1804 CompactRatioSource: liveSettings.compactRatio,
1805 CompactForceRatio: cfg.Agent.CompactForceRatio,
1806 ContextEditing: cfg.Agent.ContextEditing,
1807 RecentKeep: cfg.Agent.RecentKeep,
1808 ArchiveDir: config.ArchiveDir(),
1809 KeepPolicy: keepPolicy,
1810 ReasoningLanguage: config.ReasoningLanguageForEntry(pe, cfg.ReasoningLanguage()),
1811 PlanModeReadOnlyCommands: cfg.Agent.PlanModeReadOnlyCommands,
1812 CapabilityLedger: plannerLedger,
1813 CapabilityAudit: plannerAudit,
1814 MissingReasoningWarnStateDir: config.MissingReasoningWarnStateDir(),
1815 WriteRoots: writeRootSet,
1816 HomeDir: userHomeDir(),
1817 StateRoot: config.MemoryUserDir(),
1818 }
1819 runner = agent.NewCoordinatorWithPlannerPolicy(plannerProv, plannerSess, pe.Price, plannerTools, plannerOpts, executor, cfg.Agent.Temperature, sink, control.NewPlannerPolicy())
1820 label = entry.Model + " + planner " + pe.Model
1821 }
1822 imageEnabled := runtimeImageEnabled(execProv, modelCapabilities.Resolve(entry).AcceptsImages(cfg.Agent.VisionModel != ""))
1823 imageSnapshot := config.ModelCapabilitySnapshot(cfg, modelCapabilities)
1824 ctrlOpts := control.Options{
1825 Authentication: authentication,
1826 AuthenticationForModel: authenticationReader(cfg, opts.ProviderResolver),
1827 ModelSettingsRevision: cfg.ModelRuntimeFingerprint(modelRef),
1828 ModelSettingsCurrent: runtimeModelSettingsReader(root, modelName, modelRef, opts.ModelSettings),
1829 ModelSettingsContinuation: runtimeModelContinuationReader(root, modelName, cfg, opts.ModelSettings, opts.ProviderResolver, extensionResolver),
1830 ModelConnectionTarget: config.SafeModelConnectionTarget(config.ProviderEffectiveRequestURL(entry)),
1831 FrozenImageInput: &imageEnabled,
1832 ImageCapabilityChanged: runtimeImageCapabilityReader(root, modelName, imageSnapshot, opts.ModelSettings),
1833 TaskBudget: taskBudgetFromConfig(cfg),
1834 GoalTokenBudget: cfg.Agent.GoalTokenBudget,
1835 Runner: runner,
1836 Executor: executor,
1837 Sink: sink,
1838 Policy: policy,
1839 SubagentGate: headlessGate,
1840 Label: label,
1841 ModelRef: modelRef,
1842 ModelIdentity: cfg.ModelSelectionIdentity(modelRef),
1843 ResolveSessionModel: cfg.ResolveSavedModel,
1844 VisionModel: cfg.Agent.VisionModel,
1845 VisionProviderResolver: visionProviderResolver,
1846 VisionModelSelector: visionModelSelector,
1847 ModelCapabilityResolver: modelCapabilities.Resolve,
1848 SystemPrompt: sysPrompt,
1849 PinnedContextLoader: opts.PinnedContextLoader,
1850 SessionDir: sessionDir,
1851 SessionService: sessionService,
1852 SessionCreateService: opts.SessionCreateService,
1853 SessionRuntime: opts.SessionRuntime,
1854 ExclusiveSession: sessionService != nil && !opts.NativeLegacySession,
1855 NativeLegacySession: opts.NativeLegacySession,
1856 Host: pluginHost,
1857 Commands: cmds,
1858 Skills: skills,
1859 AllSkills: allSkills,
1860 SkillStore: skillStore,
1861 AllSkillStore: allSkillStore,
1862 DisableImplicitSkillInvocation: !implicitSkillInvocation,
1863 SkillRunner: skillRunner,
1864 ReadOnlySkillRunner: readOnlySkillRunner,
1865 SkillProfile: skillProfile,
1866 Hooks: hookRunner,
1867 Memory: mem,
1868 // Indirection: the cleanup variable gains the extension runtime set at
1869 // the end of build (snapshot assembly runs after control.New), and the
1870 // controller must observe the final chain at Close time.
1871 Cleanup: func() { cleanup() },
1872 BalanceURL: entry.BalanceURL,
1873 BalanceKey: entry.APIKey(),
1874 BalanceClient: balanceClient,
1875 Jobs: jm,
1876 BackgroundScope: backgroundScope,
1877 BackgroundSink: sink,
1878 TaskStore: opts.TaskStore,
1879 WorkspaceLease: workspaceLease,
1880 Registry: reg,
1881 PluginCtx: ctx,
1882 MCPDefaultCallTimeout: pluginSpecOptions.DefaultCallTimeout,
1883 MCPConfigureSpec: func(spec *plugin.Spec) {
1884 if spec == nil {
1885 return
1886 }
1887 spec.LaunchManager = pluginSpecOptions.LaunchManager
1888 if strings.TrimSpace(spec.ConfigSource) == "" {
1889 spec.ConfigSource = pluginSpecOptions.ConfigSource
1890 }
1891 if spec.DefaultStartupTimeout <= 0 {
1892 spec.DefaultStartupTimeout = pluginSpecOptions.DefaultStartupTimeout
1893 }
1894 applyMCPIsolation(spec, root, pluginSpecOptions)
1895 },
1896 CapabilityRuntime: capRuntime,
1897 WorkspaceRoot: root,
1898 WorkspaceRepo: repo,
1899 ExternalFolderToolRefs: readPathResolver,
1900 ResponseLanguage: cfg.ResponseLanguage(),
1901 ReasoningLanguage: config.ReasoningLanguageForEntry(entry, cfg.ReasoningLanguage()),
1902 SessionContextStatic: sessionContextStatic,
1903 DisableColdResumePrune: !cfg.ColdResumePruneEnabled(),
1904 FileBranchesOnly: opts.FileBranchesOnly,
1905 Shell: shell,
1906 ApprovalTimeout: opts.ApprovalTimeout,
1907 Ablation: opts.Ablation,
1908 WriteRoots: writeRootSet,
1909 BashSandboxEnforced: bashSpec.Enforce() && sandbox.Available(),
1910 OnPersistWriteAccess: projectWriteAccessPersister(root),
1911 OnRemember: func(rule string) control.RememberResult {
1912 return rememberPermissionRule(root, rule)
1913 },
1914 OnRememberPlanModeReadOnlyCommand: func(prefix string) control.PlanModeReadOnlyCommandTrustResult {
1915 return rememberPlanModeReadOnlyCommand(root, prefix)
1916 },
1917 SessionRecoveryMeta: opts.SessionRecoveryMeta,
1918 OnSessionRecovered: opts.OnSessionRecovered,
1919 OnSessionTransition: opts.OnSessionTransition,
1920 OnSessionRotation: opts.OnSessionRotation,
1921 BeforeInboxDispatch: opts.BeforeInboxDispatch,
1922 // The merged catalog lets frontends enumerate sidecar providers.
1923 ProviderResolver: extensionResolver,
1924 RuntimeGeneration: generation,
1925 RuntimeOwner: owner,
1926 // Share the Manager already bound into bash/grep so tools and the
1927 // Controller observe the same temporary generation across rebuilds.
1928 SessionTemp: sessionTemp,
1929 PersistentShell: persistentShell,
1930 }
1931 if opts.ModelSettings != nil {
1932 ctrlOpts.ModelSettingsSourceRevision = opts.ModelSettings.Revision
1933 }
1934 // Guardian: when guardian_model is configured, spawn an LLM safety reviewer
1935 // that can auto-allow safe Ask decisions and annotate risky ones before
1936 // escalating to the human approval prompt.
1937 if guardianModel := cfg.Agent.GuardianModel; guardianModel != "" {
1938 ge, ok := resolveOptionalEntry(effectiveResolver, cfg, guardianModel)
1939 if !ok {
1940 return nil, fmt.Errorf("guardian_model %q is not a configured provider", guardianModel)
1941 }
1942 pProv, err := resolveProvider(effectiveResolver, cfg, proxySpec, provider.Selection{Ref: modelRefFromEntry(ge)})
1943 if err != nil {
1944 return nil, fmt.Errorf("guardian_model %q: %w", guardianModel, err)
1945 }
1946 guardianReg := agent.FilterReadOnlyRegistry(reg, agent.SubagentMetaTools()...)
1947 ctrlOpts.Guardian = guardian.NewSession(pProv, guardianReg, guardian.PolicyPrompt(), modelRefFromEntry(ge), cfg.Agent.GuardianTemperature, ge.Price, sink)
1948 sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelInfo, Text: fmt.Sprintf("guardian enabled · model=%s", ge.Model)})
1949 }
1950 // Goal evaluator is not implied by the main model, guardian, or recovery
1951 // reviewer. Controllers that want one inject it explicitly; otherwise Goal
1952 // uses the deterministic host policy.
1953 ctrl := newControllerWithImageRoutes(ctrlOpts, cfg)
1954 stagedBackgroundController = ctrl
1955 if opts.BackgroundScope == nil {
1956 ctrl.PublishBackgroundScope()
1957 }
1958 // Validate and consume retired role inputs without changing runtime policy.
1959 _, _ = agentpreset.Normalize(firstNonEmpty(opts.AgentPreset, opts.TokenMode))
1960 // Publish the controller to the extension UI hub's indirection: from here
1961 // on, host/ui/* publishes ride ctrl.EmitExtensionEvent and blocking prompts
1962 // ride ctrl.Ask, exactly as if the hub had been built after control.New.
1963 ctrlRef.Store(ctrl)
1964 close(controllerReady)
1965 if capRuntime != nil {
1966 ctrl.SetCapabilityProxyTools(capRuntime.ConnectedProxyTools)
1967 }
1968 // Task tools created before capRuntime assignment still need the runtime if
1969 // they were built early; re-bind when present.
1970 if taskTool != nil && capRuntime != nil {
1971 taskTool.WithCapabilityRuntime(capRuntime)
1972 }
1973 // Build one role-neutral semantic router so an in-place switch never needs a
1974 // controller rebuild. Host constraints and live capability routing decide whether a turn may call
1975 // it; construction alone does not add a provider request.
1976 var router *capability.SemanticRouter
1977 if modelRef := strings.TrimSpace(cfg.Agent.SubagentModels["capability-router"]); modelRef != "" {
1978 effortRef := strings.TrimSpace(cfg.Agent.SubagentEfforts["capability-router"])
1979 if p, price, _, err := resolveSubagentProvider(modelRef, effortRef); err == nil && p != nil {
1980 usageModelRef, _ := subagentIdentity(modelRef, effortRef)
1981 router = &capability.SemanticRouter{Provider: p, Sink: sink, Model: usageModelRef, Pricing: price, QuoteContext: quoteCtx, Audit: capAudit}
1982 }
1983 }
1984 if router == nil {
1985 router = &capability.SemanticRouter{Provider: execProv, Sink: sink, Model: modelRef, Pricing: entry.Price, QuoteContext: quoteCtx, Audit: capAudit}
1986 }
1987 ctrl.WireCapabilityRouting(cfg.Plugins, capSpecs, router, capAudit)
1988 ctrl.SetCapabilityProxyRouting(true)
1989
1990 // Provider-visible tool surface is identical for every role setting before
1991 // the extension snapshot freezes registry schemas for cache diagnostics.
1992 applyUnifiedProviderToolSurface(reg)
1993
1994 // Freeze the extension kernel's snapshot of exactly what this build wired.
1995 // The snapshot is assembled from the in-hand objects above — discovery
1996 // never re-runs — and assembly must never fail the boot: a kernel error
1997 // degrades to a nil snapshot (logged) while the controller behaves exactly
1998 // as before. The sidecar Manager comes from preflight (started once,
1999 // before model resolution); assembly takes over its ownership and freezes
2000 // the same generation the sidecars were handshaken with. The frozen
2001 // provider catalog is the BASE catalog, exactly as before the preflight
2002 // refactor: sidecar providers enter the snapshot through the Manager's own
2003 // contributions, not through the legacy provider list.
2004 mcpSpecs := enabledMCPSpecs(configSpecs, extraSpecs)
2005 snap, runtimeSet, extensionDispatcher, snapErr := assembleLegacySnapshot(ctx, legacyAssembly{
2006 systemPrompt: sysPrompt,
2007 registry: reg,
2008 skills: skills,
2009 commands: cmds,
2010 hooks: resolvedHooks,
2011 mcpSpecs: mcpSpecs,
2012 providers: baseResolver.Catalog(),
2013 }, generation, extensionBoot{
2014 session: protocol.SessionContext{SessionID: sessionID, WorkspaceRoot: root, Generation: generation},
2015 ui: extUIHub,
2016 onWarning: extWarn,
2017 skipPromptStrategy: shouldSkipPromptStrategy(opts.PreviousPlan),
2018 previousDispatcher: opts.PreviousDispatcher,
2019 }, extensionMgr)
2020 // Ownership of the preflighted Manager transferred to assembly on every
2021 // path: it was either closed inside or registered into the RuntimeSet.
2022 pendingMgr = nil
2023 if snapErr != nil {
2024 // These assembly failures are fatal rather than degradable: two
2025 // runtimes claiming the same replacement slot (the kernel's
2026 // ReplaceClaims verdict) and a failed system_prompt.build strategy
2027 // ruling (the slot owner is required-class, so dispatch surfaces its
2028 // failure as one of these types) mean the extension contract the user
2029 // installed cannot be honored; booting without it would silently
2030 // change what the session is. (A required runtime that cannot start
2031 // fails earlier, in preflight, with the same fatality.)
2032 var requiredErr *sidecar.RequiredStartError
2033 var slotErr *extension.SlotConflictError
2034 var blockErr *dispatch.BlockError
2035 var failureErr *dispatch.FailureError
2036 var violationErr *dispatch.ViolationError
2037 if errors.As(snapErr, &requiredErr) || errors.As(snapErr, &slotErr) ||
2038 errors.As(snapErr, &blockErr) || errors.As(snapErr, &failureErr) || errors.As(snapErr, &violationErr) {
2039 ctrl.ReleaseResources()
2040 return nil, fmt.Errorf("boot: %w", snapErr)
2041 }
2042 slog.Warn("boot: extension snapshot assembly failed; continuing without a runtime snapshot", "err", snapErr)
2043 runtimeSet = extension.NewRuntimeSet(generation)
2044 // Assembly retired the preflighted Manager on the error path; the
2045 // controller must not bind a hub or expose a manager whose sidecars
2046 // are already shut down.
2047 extensionMgr = nil
2048 }
2049 // The stage-7 provider merge happened at preflight, before model
2050 // resolution; BuildResult.ProviderResolver exposes that same merged
2051 // resolver (the base when no sidecar declared providers).
2052 providerResolver := baseResolver
2053 if extensionResolver != nil {
2054 providerResolver = extensionResolver
2055 }
2056 if runtimeSet != nil && runtimeSet.Len() > 0 {
2057 _ = extension.TrackWatcher(runtimeSet.Scope(), "skill-catalogs", func() error { skillCleanup(); return nil })
2058 }
2059 cleanup = wireRuntimeScopeCleanup(runtimeSet, cleanup, opts.SharedHost, pluginHost, lspMgr, opts.SessionTemp, closeBrowser)
2060 ctrl.SetExtensions(extensionDispatcher)
2061 if extensionMgr == nil {
2062 extUIHub = nil
2063 } else {
2064 ctrl.SetExtensionUI(extUIHub)
2065 }
2066 if providerResolver != nil {
2067 ctrl.SetProviderResolver(providerResolver)
2068 }
2069 // Stage 6b2 system-prompt handoff: the 6b1 strategy pass may have replaced
2070 // the prompt while the snapshot was freezing, but the executor session was
2071 // built earlier with the host-composed prompt. Swap in a fresh session
2072 // carrying the final prompt now — before any turn or history resume, so
2073 // the live session and the frozen snapshot describe the same session.
2074 if snap != nil {
2075 if final := snap.SystemPrompt(); final != sysPrompt {
2076 ctrl.ApplyExtensionSystemPrompt(final)
2077 }
2078 }
2079 assembly := &ReusedAssembly{
2080 SystemPrompt: sysPrompt,
2081 Skills: skills,
2082 Commands: cmds,
2083 Hooks: resolvedHooks,
2084 Registry: reg,
2085 ImplicitSkillInvocation: implicitSkillInvocation,
2086 }
2087 skillsOwned = true
2088 backgroundOwned = true
2089 return finalizeBuildResult(withRuntimeConfiguration(&BuildResult{Controller: ctrl, Snapshot: snap, Runtime: runtimeSet, Owner: owner, Extensions: extensionMgr, Dispatcher: extensionDispatcher, ExtensionUI: extUIHub, ProviderResolver: providerResolver, BaseProviderResolver: baseResolver, Assembly: assembly, SkillWatchService: skillWatchService}, cfg, liveSettings, opts), !opts.deferPublish), nil
2090 }
2091
2092 // effectivePlannerModel centralizes planner precedence. Every role setting
2093 // builds the configured planner so later in-place switches retain the same
2094 // runtime; explicit Plan, approval, or Goal start decides whether it is invoked.
2095 func effectivePlannerModel(cfg *config.Config, opts Options) string {
2096 if cfg == nil || opts.Ablation.Off(ablation.Planner) {
2097 return ""
2098 }
2099 return strings.TrimSpace(cfg.Agent.PlannerModel)
2100 }
2101
2102 // rememberPermissionRule files a workspace's "always" under the user's home:
2103 // the checkout's reasonix.toml cannot grant allow rules, since a clone could
2104 // have written them.
2105 func rememberPermissionRule(workspaceRoot, rule string) control.RememberResult {
2106 store := config.NewProjectGrantStore(config.ReasonixHomeDir())
2107 result := control.RememberResult{Rule: strings.TrimSpace(rule), Path: store.Path()}
2108 root := strings.TrimSpace(workspaceRoot)
2109 if root == "" {
2110 root, _ = os.Getwd()
2111 }
2112 result.Err = store.Update(root, func(g config.ProjectGrant) (config.ProjectGrant, error) {
2113 if coveredBy := coveredPermissionRule(g.Allow, result.Rule); coveredBy != "" {
2114 result.CoveredBy = coveredBy
2115 return g, nil
2116 }
2117 g.Allow = append(pruneCoveredPermissionRules(g.Allow, result.Rule), result.Rule)
2118 return g, nil
2119 })
2120 if result.Err != nil {
2121 slog.Warn("persist permission rule", "rule", rule, "err", result.Err)
2122 }
2123 result.Saved = result.Err == nil && result.CoveredBy == ""
2124 return result
2125 }
2126
2127 func rememberPermissionConfigPath(workspaceRoot string) string {
2128 workspaceRoot = strings.TrimSpace(workspaceRoot)
2129 if workspaceRoot != "" {
2130 return filepath.Join(workspaceRoot, "reasonix.toml")
2131 }
2132 path := config.SourcePath()
2133 if path == "" {
2134 path = "reasonix.toml" // match Config.Save() fallback
2135 }
2136 return path
2137 }
2138
2139 func rememberPlanModeReadOnlyCommand(workspaceRoot, prefix string) control.PlanModeReadOnlyCommandTrustResult {
2140 prefix = strings.TrimSpace(prefix)
2141 path := rememberPermissionConfigPath(workspaceRoot)
2142 result := control.PlanModeReadOnlyCommandTrustResult{Prefix: prefix, Path: path}
2143 if prefix == "" {
2144 result.Err = fmt.Errorf("empty plan-mode read-only command prefix")
2145 return result
2146 }
2147 unlock, err := config.LockConfigFileEdits(path)
2148 if err != nil {
2149 result.Err = err
2150 return result
2151 }
2152 defer unlock()
2153 edit, err := config.LoadForEditReadOnlyStrict(path)
2154 if err != nil {
2155 result.Err = err
2156 return result
2157 }
2158 if coveredBy := coveredPlanModeReadOnlyCommand(edit.Agent.PlanModeReadOnlyCommands, prefix); coveredBy != "" {
2159 result.CoveredBy = coveredBy
2160 return result
2161 }
2162 edit.Agent.PlanModeReadOnlyCommands = append(edit.Agent.PlanModeReadOnlyCommands, prefix)
2163 if err := edit.SaveTo(path); err != nil {
2164 slog.Warn("persist plan-mode read-only command trust", "prefix", prefix, "err", err)
2165 result.Err = err
2166 return result
2167 }
2168 result.Saved = true
2169 return result
2170 }
2171
2172 func coveredPlanModeReadOnlyCommand(existing []string, candidate string) string {
2173 candidateFields := strings.Fields(strings.TrimSpace(candidate))
2174 if len(candidateFields) == 0 {
2175 return ""
2176 }
2177 for _, item := range existing {
2178 itemFields := strings.Fields(strings.TrimSpace(item))
2179 if len(itemFields) == 0 || len(itemFields) > len(candidateFields) {
2180 continue
2181 }
2182 matches := true
2183 for i, field := range itemFields {
2184 if candidateFields[i] != field {
2185 matches = false
2186 break
2187 }
2188 }
2189 if matches {
2190 return strings.Join(itemFields, " ")
2191 }
2192 }
2193 return ""
2194 }
2195
2196 func coveredPermissionRule(rules []string, rule string) string {
2197 for _, existing := range rules {
2198 if permission.RuleCoversString(existing, rule) {
2199 return strings.TrimSpace(existing)
2200 }
2201 }
2202 return ""
2203 }
2204
2205 func pruneCoveredPermissionRules(rules []string, rule string) []string {
2206 out := rules[:0]
2207 for _, existing := range rules {
2208 if strings.TrimSpace(existing) == "" || permission.RuleCoversString(rule, existing) {
2209 continue
2210 }
2211 out = append(out, existing)
2212 }
2213 return out
2214 }
2215
2216 func firstNonEmpty(vals ...string) string {
2217 for _, v := range vals {
2218 if strings.TrimSpace(v) != "" {
2219 return strings.TrimSpace(v)
2220 }
2221 }
2222 return ""
2223 }
2224
2225 func subagentModelRef(cfg *config.Config, sk skill.Skill) string {
2226 if cfg != nil {
2227 for _, key := range SubagentModelKeys(sk.Name) {
2228 if m := strings.TrimSpace(cfg.Agent.SubagentModels[key]); m != "" {
2229 return m
2230 }
2231 }
2232 }
2233 if m := strings.TrimSpace(sk.Model); m != "" {
2234 return m
2235 }
2236 if cfg == nil {
2237 return ""
2238 }
2239 return strings.TrimSpace(cfg.Agent.SubagentModel)
2240 }
2241
2242 func subagentEffortRef(cfg *config.Config, sk skill.Skill, defaultEffort string) string {
2243 if cfg != nil {
2244 for _, key := range SubagentModelKeys(sk.Name) {
2245 if e := strings.TrimSpace(cfg.Agent.SubagentEfforts[key]); e != "" {
2246 return e
2247 }
2248 }
2249 }
2250 if e := strings.TrimSpace(sk.Effort); e != "" {
2251 return e
2252 }
2253 return defaultEffort
2254 }
2255
2256 // SubagentModelKeys returns the cfg.Agent.SubagentModels/SubagentEfforts map
2257 // keys that resolve for a subagent name, in precedence order: the exact name
2258 // first, then its underscore/hyphen alias variants (the dedicated tool
2259 // security_review dispatches the skill security-review, so either spelling in
2260 // config must reach it). Any surface that reads OR clears these maps must
2261 // iterate this same key set — an exact-key delete leaves an alias entry
2262 // silently active.
2263 func SubagentModelKeys(name string) []string {
2264 name = strings.TrimSpace(name)
2265 if name == "" {
2266 return nil
2267 }
2268 keys := []string{name}
2269 for _, alias := range []string{
2270 strings.ReplaceAll(name, "-", "_"),
2271 strings.ReplaceAll(name, "_", "-"),
2272 } {
2273 if alias == "" {
2274 continue
2275 }
2276 seen := slices.Contains(keys, alias)
2277 if !seen {
2278 keys = append(keys, alias)
2279 }
2280 }
2281 return keys
2282 }
2283
2284 func currentWorkspacePromptLine(root string) string {
2285 if root == "" {
2286 return ""
2287 }
2288 return "Current workspace: " + strconv.Quote(root)
2289 }
2290
2291 // ResolveWorkspaceRoot is the workspace a session in the current directory uses:
2292 // explicit, else the nearest git root, else the working directory.
2293 func ResolveWorkspaceRoot(explicit string) string {
2294 if explicit != "" {
2295 return explicit
2296 }
2297 wd, err := os.Getwd()
2298 if err != nil {
2299 return ""
2300 }
2301 if root, ok := nearestGitRoot(wd); ok {
2302 return root
2303 }
2304 return wd
2305 }
2306
2307 func normalizeAdditionalDirs(root string, dirs []string) ([]string, error) {
2308 if len(dirs) == 0 {
2309 return nil, nil
2310 }
2311 base := strings.TrimSpace(root)
2312 if base == "" {
2313 base = "."
2314 }
2315 if !filepath.IsAbs(base) {
2316 abs, err := filepath.Abs(base)
2317 if err != nil {
2318 return nil, fmt.Errorf("resolve workspace root: %w", err)
2319 }
2320 base = abs
2321 }
2322
2323 var out []string
2324 for _, raw := range dirs {
2325 dir := strings.TrimSpace(raw)
2326 if dir == "" {
2327 continue
2328 }
2329 if !filepath.IsAbs(dir) {
2330 dir = filepath.Join(base, dir)
2331 }
2332 dir, err := filepath.Abs(filepath.Clean(dir))
2333 if err != nil {
2334 return nil, fmt.Errorf("resolve additional directory %q: %w", raw, err)
2335 }
2336 real, err := filepath.EvalSymlinks(dir)
2337 if err != nil {
2338 return nil, fmt.Errorf("resolve additional directory %q: %w", raw, err)
2339 }
2340 info, err := os.Stat(real)
2341 if err != nil {
2342 return nil, fmt.Errorf("inspect additional directory %q: %w", raw, err)
2343 }
2344 if !info.IsDir() {
2345 return nil, fmt.Errorf("additional path %q is not a directory", raw)
2346 }
2347 out = appendUniquePaths(out, filepath.Clean(real))
2348 }
2349 return out, nil
2350 }
2351
2352 func appendUniquePaths(base []string, extra ...string) []string {
2353 out := append([]string(nil), base...)
2354 seen := make(map[string]struct{}, len(out))
2355 for _, path := range out {
2356 seen[pathComparisonKey(path)] = struct{}{}
2357 }
2358 for _, path := range extra {
2359 path = filepath.Clean(path)
2360 key := pathComparisonKey(path)
2361 if _, ok := seen[key]; ok {
2362 continue
2363 }
2364 seen[key] = struct{}{}
2365 out = append(out, path)
2366 }
2367 return out
2368 }
2369
2370 // RuntimeForbidReadRoots returns the configured deny roots plus Reasonix's
2371 // global credential file when the host can enforce that read boundary without
2372 // changing the caller's own ACL. It always registers the corresponding
2373 // credential environment names for subprocess filtering. Runtime tool
2374 // assemblers outside Build must use this helper instead of reading the config
2375 // roots directly.
2376 //
2377 // Provider and bot credentials are loaded into the parent process from this
2378 // file. macOS/Linux also hide the file from readers, shell commands, and MCP
2379 // servers when the optional broad sensitive-file denylist is off. Windows only
2380 // filters the values from child environments: WRITE_RESTRICTED does not confine
2381 // reads, and denying the caller SID would also lock out the host. Project .env
2382 // files retain their existing behavior.
2383 func RuntimeForbidReadRoots(cfg *config.Config, root string) []string {
2384 return runtimeForbidReadRootsForGOOS(cfg, root, runtime.GOOS)
2385 }
2386
2387 func runtimeForbidReadRootsForGOOS(cfg *config.Config, root, goos string) []string {
2388 if cfg == nil {
2389 return nil
2390 }
2391 secrets.RegisterCredentialEnvKeys(cfg.CredentialEnvNames())
2392 base := cfg.ForbidReadRootsForRoot(root)
2393 // WRITE_RESTRICTED constrains writes only. Keep filtering credential values
2394 // on Windows without denying the caller SID, which would also lock out the
2395 // host settings process and could survive a crash.
2396 if goos == "windows" {
2397 return append([]string(nil), base...)
2398 }
2399 base = appendUniquePaths(base, config.HostSecretReadRoots()...)
2400 credentialPath := strings.TrimSpace(config.UserCredentialsPath())
2401 if credentialPath == "" {
2402 return append([]string(nil), base...)
2403 }
2404 info, err := os.Stat(credentialPath)
2405 if err != nil || info.IsDir() {
2406 return append([]string(nil), base...)
2407 }
2408 if real, err := filepath.EvalSymlinks(credentialPath); err == nil {
2409 credentialPath = real
2410 }
2411 return appendUniquePaths(base, credentialPath)
2412 }
2413
2414 func pathComparisonKey(path string) string {
2415 path = filepath.Clean(path)
2416 if abs, err := filepath.Abs(path); err == nil {
2417 path = abs
2418 }
2419 if real, err := filepath.EvalSymlinks(path); err == nil {
2420 path = real
2421 }
2422 if runtime.GOOS == "windows" {
2423 return strings.ToLower(path)
2424 }
2425 return path
2426 }
2427
2428 func nearestGitRoot(start string) (string, bool) {
2429 dir, err := filepath.Abs(start)
2430 if err != nil {
2431 dir = filepath.Clean(start)
2432 }
2433 for {
2434 if isGitMarker(filepath.Join(dir, ".git")) {
2435 return dir, true
2436 }
2437 next := filepath.Dir(dir)
2438 if next == dir {
2439 return "", false
2440 }
2441 dir = next
2442 }
2443 }
2444
2445 func isGitMarker(path string) bool {
2446 fi, err := os.Stat(path)
2447 return err == nil && (fi.IsDir() || fi.Mode().IsRegular())
2448 }
2449
2450 func newSubagentStore(sessionDir string, parentLive func(sessionPath string) bool) (*agent.SubagentStore, error) {
2451 sessionDir = strings.TrimSpace(sessionDir)
2452 if sessionDir == "" {
2453 return nil, nil
2454 }
2455 store := agent.NewSubagentStore(filepath.Join(sessionDir, "subagents")).WithParentSessionProbe(parentLive)
2456 if _, err := store.CleanupStaleRunning(); err != nil {
2457 return nil, fmt.Errorf("cleanup stale subagents: %w", err)
2458 }
2459 return store, nil
2460 }
2461
2462 func subagentEffectiveIdentity(cfg *config.Config, resolver provider.Resolver, baseModelRef string, base *config.ProviderEntry, modelRef, effort string) (string, string) {
2463 var entry config.ProviderEntry
2464 if base != nil {
2465 entry = *base
2466 }
2467 ref := strings.TrimSpace(modelRef)
2468 explicit := ref != ""
2469 if explicit {
2470 ref = childModelRef(cfg, base, ref)
2471 } else {
2472 ref = strings.TrimSpace(baseModelRef)
2473 }
2474 if explicit && cfg != nil && ref != "" {
2475 if resolved, ok := cfg.ResolveModel(ref); ok {
2476 entry = *resolved
2477 } else if resolved := syntheticEntryFromResolver(resolver, ref); strings.TrimSpace(resolved.Name) != "" {
2478 entry = *resolved
2479 } else {
2480 entry.Model = ref
2481 }
2482 } else if explicit {
2483 if resolved := syntheticEntryFromResolver(resolver, ref); strings.TrimSpace(resolved.Name) != "" {
2484 entry = *resolved
2485 } else {
2486 entry.Model = ref
2487 }
2488 } else if base == nil && ref != "" {
2489 if resolved := syntheticEntryFromResolver(resolver, ref); strings.TrimSpace(resolved.Name) != "" {
2490 entry = *resolved
2491 } else if cfg != nil {
2492 if resolved, ok := cfg.ResolveModel(ref); ok {
2493 entry = *resolved
2494 }
2495 }
2496 }
2497 if rawEffort := strings.TrimSpace(effort); rawEffort != "" {
2498 if normalized, err := config.NormalizeEffort(&entry, rawEffort); err == nil {
2499 entry.Effort = normalized
2500 } else {
2501 entry.Effort = rawEffort
2502 }
2503 }
2504 modelID := strings.TrimSpace(entry.Name)
2505 model := strings.TrimSpace(entry.Model)
2506 if modelID != "" && model != "" {
2507 modelID += "/" + model
2508 } else if model != "" {
2509 modelID = model
2510 } else if modelID == "" {
2511 modelID = ref
2512 }
2513 return modelID, strings.TrimSpace(config.EffectiveEffort(&entry))
2514 }
2515
2516 // addBuiltins adds enabled built-in tools to reg. An empty list means all of
2517 // them. writeRoots confines the file-writing built-ins to the workspace: after
2518 // the (unconfined) defaults are added, each enabled writer is replaced by an
2519 // instance bound to writeRoots (preserving registry order).
2520 // forbidReadRoots confines the read/list/search built-ins so they cannot peek at
2521 // the listed directories.
2522 // When workDir is non-empty, tools resolve relative paths against it instead of
2523 // the process cwd, enabling concurrent multi-project sessions.
2524 // sessionGuard blocks writer-tool targets inside Reasonix's own session stores
2525 // and makes bash warn when a command references them. managedConfig names the
2526 // Reasonix-owned config files writable outside writeRoots after a fresh
2527 // per-write human approval.
2528 func addBuiltins(reg *tool.Registry, enabled, writeRoots []string, writeRootSet *sandbox.WritableRootSet, bashSpec sandbox.Spec, bashTimeout time.Duration, searchSpec builtin.SearchSpec, stderr io.Writer, workDir string, proxySpec netclient.ProxySpec, forbidReadRoots []string, readPathResolver *builtin.PathResolver, sessionGuard builtin.SessionDataGuard, managedConfig builtin.ManagedConfigPaths, overlay builtin.FileOverlay, terminal builtin.TerminalRunner, sessionTemp *sessiontemp.Manager, fileWriteReceipt func(path string, hadPrior bool, prior []byte)) {
2529 // If a workspace directory is set, use workspace-bound tools that resolve
2530 // paths relative to that directory. Otherwise fall back to the process-cwd
2531 // compile-time builtins.
2532 if workDir != "" {
2533 ws := builtin.Workspace{Dir: workDir, WriteRoots: writeRoots, WriteRootSet: writeRootSet, ForbidReadRoots: forbidReadRoots, Bash: bashSpec, BashTimeout: bashTimeout, Search: searchSpec, ProxySpec: proxySpec, ReadPaths: readPathResolver, SessionGuard: sessionGuard, ManagedConfig: managedConfig, FileOverlay: overlay, Terminal: terminal, SessionTemp: sessionTemp, FileWriteReceipt: fileWriteReceipt}
2534 for _, t := range ws.Tools(enabled...) {
2535 reg.Add(t)
2536 }
2537 return
2538 }
2539
2540 if len(enabled) == 0 {
2541 for _, t := range tool.Builtins() {
2542 reg.Add(t)
2543 }
2544 } else {
2545 for _, name := range enabled {
2546 name = canonicalBuiltinName(name)
2547 if t, ok := tool.LookupBuiltin(name); ok {
2548 reg.Add(t)
2549 } else {
2550 fmt.Fprintf(stderr, "warning: unknown built-in tool %q\n", name)
2551 }
2552 }
2553 }
2554 // Replace unconfined defaults with confined instances, preserving registry order: file-writers bound to the workspace, read tools
2555 // bound to forbid-read roots, bash to the OS sandbox, web_fetch to the proxy.
2556 // Only replace tools actually enabled/present.
2557 bashTool := builtin.ConfineBash(bashSpec, sessionGuard, bashTimeout)
2558 if rebound, ok := builtin.BindSessionTemp(bashTool, sessionTemp); ok {
2559 bashTool = rebound
2560 }
2561 searchTool := builtin.ConfineSearch(searchSpec, bashSpec, forbidReadRoots)
2562 if rebound, ok := builtin.BindSessionTemp(searchTool, sessionTemp); ok {
2563 searchTool = rebound
2564 }
2565 writers := builtin.ConfineWriters(writeRoots, sessionGuard, managedConfig)
2566 for i, writer := range writers {
2567 writers[i] = builtin.BindFileWriteReceipt(writer, fileWriteReceipt)
2568 }
2569 confined := append(writers,
2570 searchTool,
2571 builtin.ConfineWebFetch(proxySpec))
2572 confined = append(confined, builtin.ConfineReaders(forbidReadRoots)...)
2573 for i, tl := range confined {
2574 confined[i] = builtin.BindWriteRootSet(tl, writeRootSet)
2575 }
2576 for _, t := range confined {
2577 if _, ok := reg.Get(t.Name()); ok {
2578 reg.Add(t)
2579 }
2580 }
2581 registerShellBuiltin(reg, bashTool, writeRootSet)
2582 }
2583
2584 // partitionByTier splits configured plugin entries into eager (block boot until
2585 // ready) and background (placeholder + start spawn now). Entries with an empty,
2586 // legacy lazy, or unrecognised tier land in background.
2587 func partitionByTier(entries []config.PluginEntry) (eager, bg []config.PluginEntry) {
2588 for _, e := range entries {
2589 switch e.ResolvedTier() {
2590 case "eager":
2591 eager = append(eager, e)
2592 default:
2593 bg = append(bg, e)
2594 }
2595 }
2596 return eager, bg
2597 }
2598
2599 // PluginSpecs maps configured plugin entries to plugin.Spec, expanding ${VAR}
2600 // references. Exported so custom assemblers can connect the config's plugins
2601 // alongside their own (e.g. ACP's per-session MCP servers).
2602 func PluginSpecs(entries []config.PluginEntry) []plugin.Spec {
2603 return PluginSpecsForRoot(entries, "")
2604 }
2605
2606 // PluginSpecsForRoot maps configured plugin entries to plugin.Spec and applies
2607 // workspace-aware compatibility overrides for known cwd-sensitive servers.
2608 func PluginSpecsForRoot(entries []config.PluginEntry, workspaceRoot string) []plugin.Spec {
2609 return PluginSpecsForRootWithOptions(entries, workspaceRoot, PluginSpecOptions{})
2610 }
2611
2612 // PluginSpecsForRootWithOptions maps configured plugin entries to plugin.Spec
2613 // and injects runtime policy such as the global MCP call timeout.
2614 func PluginSpecsForRootWithOptions(entries []config.PluginEntry, workspaceRoot string, opts PluginSpecOptions) []plugin.Spec {
2615 specs := make([]plugin.Spec, len(entries))
2616 for i, e := range entries {
2617 specs[i] = pluginSpecFromEntryWithOptions(e, workspaceRoot, opts)
2618 }
2619 return specs
2620 }
2621
2622 func pluginSpecFromEntryWithOptions(e config.PluginEntry, workspaceRoot string, opts PluginSpecOptions) plugin.Spec {
2623 e = e.ExpandedPlugin() // resolve ${VAR} / ${VAR:-default} from the environment
2624 configSource := strings.TrimSpace(string(e.Source))
2625 if configSource == "" {
2626 configSource = opts.ConfigSource
2627 }
2628 spec := plugin.ApplyKnownOverrides(plugin.Spec{
2629 Name: e.Name,
2630 Package: strings.TrimSpace(opts.PackageOwners[e.Name]),
2631 Type: e.Type,
2632 Command: e.Command,
2633 Args: e.Args,
2634 Env: e.Env,
2635 URL: e.URL,
2636 Headers: e.Headers,
2637 DefaultStartupTimeout: opts.DefaultStartupTimeout,
2638 StartupTimeout: secondsDuration(e.StartupTimeoutSeconds),
2639 DefaultCallTimeout: opts.DefaultCallTimeout,
2640 CallTimeout: secondsDuration(e.CallTimeoutSeconds),
2641 ToolTimeouts: toolTimeoutDurations(e.ToolTimeoutSeconds),
2642 WorkspaceRoot: strings.TrimSpace(workspaceRoot),
2643 LaunchManager: opts.LaunchManager,
2644 ConfigSource: configSource,
2645 Authorized: e.Source.UserAuthorized(),
2646 OAuthHTTPClient: opts.OAuthHTTPClient,
2647 }, workspaceRoot)
2648 if e.Source.ProjectScoped() && strings.TrimSpace(spec.Dir) == "" {
2649 spec.Dir = workspaceRoot
2650 }
2651 applyMCPIsolation(&spec, workspaceRoot, opts)
2652 return spec
2653 }
2654
2655 func pluginPackageOwners(cfg *config.Config) map[string]string {
2656 out := map[string]string{}
2657 if cfg == nil {
2658 return out
2659 }
2660 for _, configured := range cfg.Plugins {
2661 if owner, ok := cfg.PluginPackageOwner(configured.Name); ok {
2662 out[configured.Name] = owner
2663 }
2664 }
2665 return out
2666 }
2667
2668 func skillMCPBindings(sk skill.Skill, reg *tool.Registry, specs []plugin.Spec, cachedTools map[string][]plugin.CachedTool, cacheKeyOK map[string]bool) []tool.MCPBinding {
2669 var out []tool.MCPBinding
2670 liveServers := map[string]bool{}
2671 if reg != nil {
2672 bindings := reg.MCPBindings()
2673 out = make([]tool.MCPBinding, 0, len(bindings))
2674 for _, binding := range bindings {
2675 liveServers[binding.Server] = true
2676 }
2677 out = append(out, skill.ToolBindingsForSkill(sk, bindings)...)
2678 }
2679 // A valid cached schema also supplies stable bindings for an on-demand
2680 // package server before it is connected. The skill can then route through
2681 // use_capability without inventing Reasonix's canonical name.
2682 for _, spec := range specs {
2683 if spec.Package != sk.Plugin || liveServers[spec.Name] || !cacheKeyOK[spec.Name] {
2684 continue
2685 }
2686 for _, cached := range cachedTools[spec.Name] {
2687 visible := cached.Name
2688 if spec.StripRawPrefix != "" {
2689 visible = strings.TrimPrefix(visible, spec.StripRawPrefix)
2690 }
2691 out = append(out, tool.MCPBinding{
2692 Package: spec.Package,
2693 Server: spec.Name,
2694 RawName: cached.Name,
2695 VisibleName: visible,
2696 CallableName: plugin.ModelToolName(spec.Name, visible),
2697 CapabilityID: "mcp-tool:" + spec.Name + "/" + cached.Name,
2698 })
2699 }
2700 }
2701 return out
2702 }
2703
2704 func applyMCPIsolation(spec *plugin.Spec, workspaceRoot string, opts PluginSpecOptions) {
2705 if spec == nil {
2706 return
2707 }
2708 // Authorized user MCP defaults to trusted host process mode. Confined mode
2709 // is opt-in for internal managed deployments/tests and is never selected by
2710 // ordinary install paths.
2711 if spec.ProcessMode == "" {
2712 spec.ProcessMode = plugin.MCPProcessHost
2713 }
2714 if strings.TrimSpace(opts.StateHome) == "" {
2715 return
2716 }
2717 stateDir := plugin.MCPStateDir(opts.StateHome, workspaceRoot, spec.Name)
2718 spec.StateDir = stateDir
2719 if spec.ResolvedProcessMode() != plugin.MCPProcessConfined {
2720 // Host mode still gets a private state/cache/temp tree; only the OS
2721 // command sandbox is omitted so local app integrations keep working.
2722 return
2723 }
2724 writerRoots := appendUniquePaths([]string{stateDir}, opts.WriterRoots...)
2725 spec.Sandbox = sandbox.Spec{
2726 Mode: "enforce", WriteRoots: writerRoots,
2727 ForbidReadRoots: append([]string(nil), opts.ForbidReadRoots...),
2728 Network: opts.Network, MinimalWrites: true,
2729 }
2730 }
2731
2732 func secondsDuration(seconds int) time.Duration {
2733 if seconds <= 0 {
2734 return 0
2735 }
2736 return time.Duration(seconds) * time.Second
2737 }
2738
2739 func toolTimeoutDurations(seconds map[string]int) map[string]time.Duration {
2740 if len(seconds) == 0 {
2741 return nil
2742 }
2743 out := make(map[string]time.Duration, len(seconds))
2744 for name, sec := range seconds {
2745 name = strings.TrimSpace(name)
2746 if name == "" || sec <= 0 {
2747 continue
2748 }
2749 out[name] = time.Duration(sec) * time.Second
2750 }
2751 if len(out) == 0 {
2752 return nil
2753 }
2754 return out
2755 }
2756
2757 func applyKnownPluginOverrides(specs []plugin.Spec, workspaceRoot string) []plugin.Spec {
2758 out := make([]plugin.Spec, len(specs))
2759 for i, spec := range specs {
2760 out[i] = plugin.ApplyKnownOverrides(spec, workspaceRoot)
2761 }
2762 return out
2763 }
2764
2765 func applyDefaultMCPCallTimeout(specs []plugin.Spec, timeout time.Duration) []plugin.Spec {
2766 if len(specs) == 0 || timeout <= 0 {
2767 return specs
2768 }
2769 out := make([]plugin.Spec, len(specs))
2770 for i, spec := range specs {
2771 out[i] = spec
2772 if out[i].DefaultCallTimeout <= 0 {
2773 out[i].DefaultCallTimeout = timeout
2774 }
2775 }
2776 return out
2777 }
2778
2779 func applyDefaultMCPStartupTimeout(specs []plugin.Spec, timeout time.Duration) []plugin.Spec {
2780 if len(specs) == 0 || timeout <= 0 {
2781 return specs
2782 }
2783 out := make([]plugin.Spec, len(specs))
2784 for i, spec := range specs {
2785 out[i] = spec
2786 if out[i].DefaultStartupTimeout <= 0 {
2787 out[i].DefaultStartupTimeout = timeout
2788 }
2789 }
2790 return out
2791 }
2792
2793 // MCPStartupNotice formats the warning shown when configured MCP servers failed
2794 // to connect, naming the first few; ok is false when none failed.
2795 func MCPStartupNotice(failures []plugin.Failure) (text, detail string, ok bool) {
2796 if len(failures) == 0 {
2797 return "", "", false
2798 }
2799 names := make([]string, 0, min(len(failures), 3))
2800 details := make([]string, 0, len(failures))
2801 for i, f := range failures {
2802 if i >= 3 {
2803 continue
2804 }
2805 names = append(names, f.Name)
2806 }
2807 for _, f := range failures {
2808 line := f.Name
2809 if strings.TrimSpace(f.Error) != "" {
2810 line += ": " + strings.TrimSpace(f.Error)
2811 }
2812 details = append(details, line)
2813 }
2814 more := ""
2815 if len(failures) > len(names) {
2816 more = fmt.Sprintf(" (+%d more)", len(failures)-len(names))
2817 }
2818 return "Some MCP servers failed to start; run /mcp for details.", fmt.Sprintf("%d MCP server(s) failed to start: %s%s\n%s",
2819 len(failures), strings.Join(names, ", "), more, strings.Join(details, "\n")), true
2820 }
2821
2822 func providerNames(cfg *config.Config) string {
2823 names := make([]string, len(cfg.Providers))
2824 for i, p := range cfg.Providers {
2825 names[i] = p.Name
2826 }
2827 return strings.Join(names, "/")
2828 }
2829
2829 lines GO