返回 DeepSeek-Reasonix
runtime.go
根目录 / internal / boot / runtime.go
1 package boot
2
3 import (
4 "context"
5 "fmt"
6 "strings"
7 "sync/atomic"
8
9 "reasonix/internal/command"
10 "reasonix/internal/control"
11 "reasonix/internal/extension"
12 "reasonix/internal/extension/dispatch"
13 "reasonix/internal/extension/protocol"
14 "reasonix/internal/extension/sidecar"
15 "reasonix/internal/extension/uihub"
16 "reasonix/internal/hook"
17 "reasonix/internal/plugin"
18 "reasonix/internal/provider"
19 "reasonix/internal/skill"
20 "reasonix/internal/skill/skillwatch"
21 "reasonix/internal/tool"
22 )
23
24 // BuildResult is the full product of one runtime build: the ready-to-drive
25 // controller plus the extension kernel's frozen view of the same assembly.
26 // Snapshot is nil when kernel assembly failed — boot behavior is never
27 // allowed to depend on it (see build). Runtime is the snapshot's bound
28 // closable set; it holds the extension sidecar Manager when any v2 runtime
29 // package is installed, and its Close is chained into the controller's
30 // cleanup so sidecars die with their controller generation.
31 type BuildResult struct {
32 Controller *control.Controller
33 Snapshot *extension.RuntimeSnapshot
34 Runtime *extension.RuntimeSet
35 // Owner is the session-lineage lifecycle owner. Independent builds receive
36 // independent owners; RebuildFrom reuses the previous owner so only that
37 // lineage's old generation drains.
38 Owner *extension.RuntimeOwner
39 // Extensions is the started extension sidecar Manager (nil when no v2
40 // runtime package is installed). Its lifecycle belongs to Runtime; the
41 // field exists so later stages (and tests) can reach the live clients.
42 Extensions *sidecar.Manager
43 // Dispatcher is the frozen interceptor dispatcher for this runtime
44 // generation (nil when no sidecar started, or when snapshot assembly
45 // degraded). It is immutable and safe for concurrent turns; the
46 // controller receives it through SetExtensions right after assembly.
47 Dispatcher *dispatch.Dispatcher
48 // ExtensionUI is the host extension UI hub for this runtime generation
49 // (stage 8a; nil when no sidecar started). It is bound to the build's
50 // session ID and generation; the controller receives it through
51 // SetExtensionUI right after assembly, and a Rebuild creates a fresh hub
52 // on the new generation.
53 ExtensionUI *uihub.Hub
54 // ProviderResolver is the build's effective provider resolver: the
55 // caller-owned broker when Options.ProviderResolver is set, the local
56 // config-backed resolver otherwise, merged with any extension-hosted
57 // sidecar providers (stage 7). Plugin-namespaced refs route to the owning
58 // sidecar; every other ref resolves through the base resolver.
59 ProviderResolver provider.Resolver
60 // BaseProviderResolver is the pre-sidecar catalog used to re-merge after
61 // a narrow rebuild replaces the Manager (must not re-merge already-merged).
62 BaseProviderResolver provider.Resolver
63 // Plan is the RuntimePlan for this generation (from the previous graph
64 // when Rebuild supplies one; cold start when nil previous).
65 Plan *extension.RuntimePlan
66 // Status is the diagnostic component status snapshot for doctor/UI.
67 Status *extension.RuntimeStatus
68 // Lifecycle tracks component state transitions for this generation.
69 Lifecycle *extension.LifecycleRegistry
70 // Assembly is retained so a subsequent RebuildFrom can skip rediscovery
71 // when the RuntimePlan is no-op or interceptor/UI-only.
72 Assembly *ReusedAssembly
73 // ReusedController is true when a true subgraph rebuild kept the previous
74 // controller pointer (no control.New / BuildRuntime). Callers must not
75 // Close the "old" controller when it is the same pointer as Controller.
76 ReusedController bool
77 // SkillWatchService exposes content-free resource counters to doctor/UI.
78 SkillWatchService *skillwatch.Service
79 // configFingerprint is immutable build-time host configuration, outside the extension graph.
80 configFingerprint string
81 liveSettings *liveRuntimeSettings
82 selection runtimeSelection
83 }
84
85 // runtimeGeneration is the process-wide build generation counter. The first
86 // build gets generation 1 so 0 can mean "no snapshot" on a RuntimeSet built
87 // outside the kernel pipeline.
88 var runtimeGeneration atomic.Uint64
89
90 // nextRuntimeGeneration returns the next build generation. Generations pair
91 // with RuntimeSet.CloseIfGeneration so stale cleanup can never close a newer
92 // runtime's resources.
93 func nextRuntimeGeneration() uint64 { return runtimeGeneration.Add(1) }
94
95 // BuildRuntime runs the full boot assembly and returns the controller
96 // together with the extension kernel's frozen snapshot of the exact resources
97 // the build wired — tools, skills, commands, hooks, MCP servers, providers,
98 // and the composed system prompt. The snapshot is assembled from the in-hand
99 // objects the build itself produced (discovery never re-runs), so it cannot
100 // drift from what the controller actually uses, and it never makes an
101 // otherwise-successful build fail: an assembly error degrades to a nil
102 // Snapshot with a logged warning.
103 func BuildRuntime(ctx context.Context, opts Options) (*BuildResult, error) {
104 return build(ctx, opts)
105 }
106
107 // Build loads config, resolves the model(s), and returns a Controller wrapping a
108 // single Agent, or a two-model Coordinator when agent.planner_model is set. The
109 // returned controller owns plugin subprocesses; call Close (via Controller.Close)
110 // to release them.
111 //
112 // Build is the compatibility wrapper over BuildRuntime: frontends keep their
113 // existing signature. The runtime set is NOT closed here — it is chained into
114 // the controller's cleanup (the way LSP cleanup is chained), so extension
115 // sidecars live exactly as long as their controller.
116 func Build(ctx context.Context, opts Options) (*control.Controller, error) {
117 res, err := BuildRuntime(ctx, opts)
118 if err != nil {
119 return nil, err
120 }
121 return res.Controller, nil
122 }
123
124 // legacyAssembly carries the already-assembled runtime resources the kernel
125 // snapshot is built from. Every field is the exact object the rest of the
126 // build wired into the controller — the snapshot never re-derives anything.
127 type legacyAssembly struct {
128 systemPrompt string
129 registry *tool.Registry
130 skills []skill.Skill
131 commands []command.Command
132 hooks []hook.ResolvedHook
133 mcpSpecs []plugin.Spec
134 providers []provider.Descriptor
135 }
136
137 // extensionBoot carries the extension sidecar launch inputs into snapshot
138 // assembly: the session the sidecars serve, where non-fatal warnings go, and
139 // (stage 8a) the UI hub the sidecars' host/ui/* calls bind to.
140 type extensionBoot struct {
141 session protocol.SessionContext
142 onWarning func(string)
143 ui *uihub.Hub
144 // skipPromptStrategy skips system_prompt.build strategy when the RuntimePlan
145 // is a no-op (or does not affect cache), preserving the previous prompt.
146 skipPromptStrategy bool
147 // previousDispatcher reuses an interceptor chain when the plan is no-op.
148 previousDispatcher *dispatch.Dispatcher
149 }
150
151 func (p extensionBoot) warn(msg string) {
152 if p.onWarning != nil {
153 p.onWarning(msg)
154 }
155 }
156
157 // startExtensionPackages is the sidecar launch seam (tests override it).
158 // previous+plan adopt Unchanged packages without respawn.
159 var startExtensionPackages = sidecar.StartPackagesWithPlan
160
161 // preflightExtensionRuntimes starts enabled runtime packages before model
162 // resolution. Required failures are fatal; optional failures warn. With
163 // prev+plan, only Added/Reloaded start and Unchanged are adopted.
164 func preflightExtensionRuntimes(ctx context.Context, home string, ext extensionBoot, prev *sidecar.Manager, plan *extension.RuntimePlan) (*sidecar.Manager, error) {
165 if strings.TrimSpace(home) == "" {
166 return nil, nil
167 }
168 packages, loadWarnings := sidecar.LoadRuntimePackages(home)
169 if len(packages) == 0 {
170 // No v2 runtime packages: surface the installed-state warnings exactly
171 // as the in-assembly StartPackages call did, and take the untouched
172 // pre-sidecar path (no processes, no Manager).
173 for _, warning := range loadWarnings {
174 ext.warn(warning)
175 }
176 return nil, nil
177 }
178 // The stage-8a UI hub installs as each sidecar's host/ui/* handler; a nil
179 // hub keeps the "ui not available" default. Guard against the typed-nil
180 // trap: a nil *uihub.Hub must stay a nil UIHandler.
181 var ui sidecar.UIHandler
182 if ext.ui != nil {
183 ui = ext.ui
184 }
185 mgr, warnings, err := startExtensionPackages(ctx, home, ext.session, ui, prev, plan)
186 for _, warning := range warnings {
187 ext.warn(warning)
188 }
189 if err != nil {
190 // A required runtime failed: the Manager already shut down whatever
191 // started. The call site treats *RequiredStartError as fatal.
192 return nil, err
193 }
194 if len(mgr.Clients()) == 0 {
195 // Every package was optional and failed: retire the empty Manager and
196 // take the pre-sidecar path with warnings already surfaced.
197 _ = mgr.Close()
198 return nil, nil
199 }
200 return mgr, nil
201 }
202
203 // assembleLegacySnapshot freezes one boot's resources into an extension
204 // kernel snapshot. ConflictCollect is deliberate: the legacy sources already
205 // resolved their clashes inside their own discovery passes, and any residual
206 // dispute must land on the snapshot's Diagnostics without changing whether
207 // the session boots.
208 //
209 // Extension sidecars (stage 5b): mgr is the Manager preflightExtensionRuntimes
210 // started before model resolution; this function takes OVER its ownership —
211 // on every error path it closes mgr, and on success the Manager is registered
212 // into the RuntimeSet at activation, so it dies with its controller
213 // generation. Starting before the builder freezes is load-bearing: the
214 // handshake's declared providers and UI actions can only enter the catalog
215 // from a live handshake, and required-runtime failures must fail the build,
216 // which the activator seam (post-freeze) could only do after the catalog
217 // already settled.
218 //
219 // Dispatch wiring (stage 6b1): with live sidecars the boot also runs the
220 // system_prompt.build strategy BEFORE the freeze, so the frozen snapshot's
221 // SystemPrompt and CacheHash cover the final (possibly replaced) prompt —
222 // the hash honestly attributes the prompt the session was built with rather
223 // than a pre-strategy draft. A strategy failure fails the build because the
224 // slot owner is required-class by definition. After the freeze the boot
225 // builds the generation's Dispatcher from the snapshot's frozen chain and
226 // replacements, and broadcasts the system_prompt.build event with the final
227 // prompt to every observer. The replaced prompt lands in the snapshot; the
228 // build's tail (stage 6b2) swaps the live executor session to the same final
229 // prompt when it differs from the host-composed one the session was built
230 // with, so snapshot and session describe the same session before any turn.
231 // With a nil Manager the path is byte-identical to the pre-sidecar one: no
232 // processes, no contributions, no dispatcher, an empty runtime set.
233 func assembleLegacySnapshot(ctx context.Context, in legacyAssembly, generation uint64, ext extensionBoot, mgr *sidecar.Manager) (*extension.RuntimeSnapshot, *extension.RuntimeSet, *dispatch.Dispatcher, error) {
234 legacy := legacyContributions(in)
235 b := extension.NewBuilder().
236 WithGeneration(generation).
237 WithConflictPolicy(extension.ConflictCollect).
238 AddContributor(extension.ContributorFunc{
239 ContributorName: "boot-legacy",
240 Fn: func(context.Context) ([]extension.Contribution, error) {
241 return legacy, nil
242 },
243 })
244
245 prompt := in.systemPrompt
246 var dispatcher *dispatch.Dispatcher
247 // postFreeze runs after a successful b.Build when sidecars are live: it
248 // builds the generation's dispatcher from the snapshot's own frozen chain
249 // and replacements, then broadcasts system_prompt.build with the final
250 // prompt so observers see exactly what froze.
251 var postFreeze func(snap *extension.RuntimeSnapshot)
252 if mgr != nil && len(mgr.Clients()) > 0 {
253 managed := mgr
254 bindExtensionUI(ext.ui, managed, ext.warn)
255 sidecarContribs := managed.Contributions()
256 b.AddContributor(extension.ContributorFunc{
257 ContributorName: "boot-extension-runtimes",
258 Fn: func(context.Context) ([]extension.Contribution, error) {
259 return sidecarContribs, nil
260 },
261 })
262 b.WithActivator(func(actx context.Context, snap *extension.RuntimeSnapshot) (*extension.RuntimeSet, error) {
263 rs := extension.NewRuntimeSet(snap.Generation())
264 // Track the sidecar manager as a cancelable generation effect so
265 // mid-activation failure and drain share one EffectScope owner.
266 if err := rs.Track(extension.Effect{
267 ID: "sidecar-manager",
268 Owner: "boot",
269 Component: "extension-runtimes",
270 Class: extension.Cancelable,
271 Dispose: func(ctx context.Context) error {
272 _ = ctx
273 return managed.Close()
274 },
275 }); err != nil {
276 _ = managed.Close()
277 return nil, err
278 }
279 // UI hub binding is a reversible generation effect (rebind is free).
280 if err := extension.TrackUIHub(rs.Scope(), snap.Generation()); err != nil {
281 _ = rs.Close()
282 return nil, err
283 }
284 // Per-client MCP/process handles stay under the manager dispose above;
285 // track an event-subscription style teardown for each live client so
286 // EffectScope inventory matches the live process set for doctor.
287 for _, client := range managed.Clients() {
288 pluginID := client.PluginID()
289 _ = extension.TrackEventSubscription(rs.Scope(), "sidecar:"+pluginID, func() error {
290 // Manager.Close already tears down clients; this is inventory.
291 return nil
292 })
293 }
294 _ = actx
295 return rs, nil
296 })
297
298 // Resolve replacement-slot claims over the exact contribution set
299 // the builder will see, mirroring the kernel's claim pass, so a
300 // conflict fails BEFORE any strategy runs and the winning claims
301 // drive the pre-freeze strategy below.
302 claims, err := resolveReplacementClaims(legacy, sidecarContribs)
303 if err != nil {
304 _ = managed.Close()
305 return nil, nil, nil, err
306 }
307 required := requiredRuntimeSet(managed)
308 clients := sidecarClientResolver(managed)
309 dispatchOpts := dispatch.Options{Warn: ext.warn}
310 // system_prompt.build strategy: the slot's owner rules on the
311 // composed prompt before the snapshot freezes. Skipped on no-op plans
312 // so CacheHash stays stable across rebuilds.
313 if !ext.skipPromptStrategy {
314 if _, owned := claims[extension.SlotSystemPrompt]; owned {
315 strategyDispatcher := dispatch.New(nil, claims, clients, required, dispatchOpts)
316 payload := dispatch.SystemPromptPayload{Prompt: prompt, WorkspaceRoot: ext.session.WorkspaceRoot}
317 if err := strategyDispatcher.RunStrategy(ctx, extension.SlotSystemPrompt, extension.PointSystemPromptBuild, &payload); err != nil {
318 _ = managed.Close()
319 return nil, nil, nil, err
320 }
321 prompt = payload.Prompt
322 }
323 }
324
325 postFreeze = func(snap *extension.RuntimeSnapshot) {
326 if ext.previousDispatcher != nil && ext.skipPromptStrategy {
327 dispatcher = ext.previousDispatcher
328 } else {
329 dispatcher = dispatch.New(snap.InterceptorChain(), snap.Replacements(), clients, required, dispatchOpts)
330 }
331 dispatcher.Event(extension.PointSystemPromptBuild, dispatch.SystemPromptPayload{
332 Prompt: prompt, WorkspaceRoot: ext.session.WorkspaceRoot,
333 })
334 }
335 } else if mgr != nil {
336 // Defensive: preflight already retires client-less managers, but a
337 // caller-owned Manager must never leak through assembly either way.
338 _ = mgr.Close()
339 mgr = nil
340 }
341
342 b.WithSystemPrompt(prompt)
343 snap, runtimeSet, err := b.Build(ctx)
344 if err != nil {
345 if mgr != nil {
346 _ = mgr.Close()
347 }
348 return nil, nil, nil, err
349 }
350 if postFreeze != nil {
351 postFreeze(snap)
352 }
353 return snap, runtimeSet, dispatcher, nil
354 }
355
356 // resolveReplacementClaims replays the kernel's slot-claim pass (see
357 // resolveContributions) over the contribution set before the builder freezes:
358 // claims come from every contribution's SlotClaimer payload, winners and
359 // losers alike, and a second claimant is a *SlotConflictError.
360 func resolveReplacementClaims(groups ...[]extension.Contribution) (map[extension.Slot]extension.ContributionSource, error) {
361 claims := extension.NewReplaceClaims()
362 for _, group := range groups {
363 for _, ct := range group {
364 claimer, ok := ct.Payload.(extension.SlotClaimer)
365 if !ok {
366 continue
367 }
368 for _, slot := range claimer.ReplacementSlots() {
369 if err := claims.Claim(slot, ct.Source); err != nil {
370 return nil, err
371 }
372 }
373 }
374 }
375 return claims.Claims(), nil
376 }
377
378 // requiredRuntimeSet marks every started sidecar whose manifest declared the
379 // runtime required:true, the dispatcher's required-class input.
380 func requiredRuntimeSet(mgr *sidecar.Manager) map[string]bool {
381 clients := mgr.Clients()
382 out := make(map[string]bool, len(clients))
383 for _, client := range clients {
384 out[client.PluginID()] = client.Required()
385 }
386 return out
387 }
388
389 // sidecarClientResolver adapts the Manager to the dispatcher's client lookup.
390 // The dispatcher requires an untyped nil for missing clients; Manager.Client
391 // returns a typed *sidecar.Client.
392 func sidecarClientResolver(mgr *sidecar.Manager) func(pluginID string) dispatch.Client {
393 return func(pluginID string) dispatch.Client {
394 if client := mgr.Client(pluginID); client != nil {
395 return client
396 }
397 return nil
398 }
399 }
400
401 // bindExtensionUI finishes the stage-8a hub binding once sidecars are live:
402 // the client resolver routes later /<plugin>:<action> invocations and form
403 // submissions, and each client's handshake-declared UI actions enter the
404 // registry. An invalid declaration degrades to a warning (the plugin's other
405 // contributions are unaffected) rather than failing the build.
406 func bindExtensionUI(hub *uihub.Hub, mgr *sidecar.Manager, warn func(string)) {
407 if hub == nil || mgr == nil {
408 return
409 }
410 hub.SetResolver(func(pluginID string) uihub.ActionClient {
411 if client := mgr.Client(pluginID); client != nil {
412 return client
413 }
414 return nil
415 })
416 for _, client := range mgr.Clients() {
417 actions := client.Handshake().UIActions
418 if len(actions) == 0 {
419 continue
420 }
421 if err := hub.RegisterActions(client.PluginID(), actions); err != nil {
422 warn(fmt.Sprintf("%s: extension UI actions not registered: %v", client.PluginID(), err))
423 }
424 }
425 }
426
427 // legacyContributions maps the assembled runtime resources to kernel
428 // contributions, reusing the extension package's per-kind mappers so scope
429 // attribution stays in one place. Contributions whose IDs predate or violate
430 // the kernel's ID contract are skipped: one pathological legacy name must not
431 // take down the whole snapshot, and the live runtime is untouched either way.
432 func legacyContributions(in legacyAssembly) []extension.Contribution {
433 specByName := map[string]plugin.Spec{}
434 for _, spec := range in.mcpSpecs {
435 specByName[mcpNormalizedServerName(spec.Name)] = spec
436 }
437 var out []extension.Contribution
438 for _, entry := range in.registry.ContractEntries() {
439 if !extension.ValidToolID(entry.Name) {
440 // Legacy MCP name normalization preserves uppercase characters,
441 // which predates the kernel's lowercase tool-ID contract. Such a
442 // tool keeps working in the live registry; it is skipped here
443 // rather than failing the whole snapshot.
444 continue
445 }
446 out = append(out, extension.Contribution{
447 Kind: extension.KindTool,
448 ID: entry.Name,
449 Source: legacyToolSource(entry.Name, specByName),
450 Payload: entry,
451 })
452 }
453 for _, sk := range in.skills {
454 if !kernelID(sk.SlashName()) {
455 continue
456 }
457 out = append(out, extension.SkillContribution(sk))
458 }
459 for _, cmd := range in.commands {
460 if !kernelID(cmd.Name) {
461 continue
462 }
463 out = append(out, extension.CommandContribution(cmd))
464 }
465 perEvent := map[hook.Event]int{}
466 for _, h := range in.hooks {
467 seq := perEvent[h.Event]
468 perEvent[h.Event]++
469 out = append(out, extension.HookContribution(h, seq))
470 }
471 for _, spec := range in.mcpSpecs {
472 if !kernelID(spec.Name) {
473 // A server name outside the kernel ID contract cannot be a
474 // catalog entry; the server's tools still attribute through
475 // specByName above.
476 continue
477 }
478 out = append(out, extension.MCPServerContribution(spec))
479 }
480 for _, desc := range in.providers {
481 if !extension.IsProviderRef(desc.Ref) {
482 // The kernel keys providers on <name>/<model> refs; legacy
483 // catalogs can carry a bare provider name or a model that itself
484 // contains a slash. Those entries stay resolvable through the
485 // ordinary provider path but cannot be catalogued in a v2
486 // snapshot.
487 continue
488 }
489 out = append(out, extension.ProviderContribution(desc))
490 }
491 return out
492 }
493
494 // kernelID mirrors the generic ID hygiene the kernel validates for every
495 // kind (non-empty, no whitespace). The kernel's parse step trims first, so
496 // only interior whitespace or emptiness disqualifies.
497 func kernelID(id string) bool {
498 id = strings.TrimSpace(id)
499 return id != "" && !strings.ContainsAny(id, " \t\n")
500 }
501
502 // legacyToolSource attributes a registry tool to its origin. MCP-backed tools
503 // (the mcp__<server>__<tool> namespace) belong to the server's spec: a
504 // package-owned server attributes to the plugin package, otherwise to the
505 // server itself, both at the plugin tier. Everything else — and any MCP tool
506 // whose server can no longer be matched to a spec — stays at the builtin
507 // tier: the registry is the compile-time default surface, and an
508 // unattributable entry must not masquerade as a higher one. Tool IDs are
509 // unique inside one registry, so in stage 3a the scope is provenance only and
510 // never decides a shadow race.
511 func legacyToolSource(name string, specByName map[string]plugin.Spec) extension.ContributionSource {
512 if server, _, ok := tool.SplitMCPName(name); ok {
513 if spec, found := specByName[server]; found {
514 pluginID := strings.TrimSpace(spec.Package)
515 if pluginID == "" {
516 pluginID = spec.Name
517 }
518 origin := strings.TrimSpace(spec.ConfigSource)
519 if origin == "" {
520 origin = "mcp"
521 }
522 return extension.ContributionSource{Scope: extension.ScopePlugin, PluginID: pluginID, Origin: origin}
523 }
524 }
525 return extension.ContributionSource{Scope: extension.ScopeBuiltin, Origin: "builtin"}
526 }
527
528 // mcpNormalizedServerName returns the server name as it appears inside
529 // mcp__<server>__<tool> registry names, i.e. after the plugin package's name
530 // normalization (invalid characters replaced, collision hash appended).
531 func mcpNormalizedServerName(name string) string {
532 return strings.TrimSuffix(strings.TrimPrefix(plugin.ToolPrefix(name), tool.MCPNamePrefix), "__")
533 }
534
535 // enabledMCPSpecs returns the deduplicated set of MCP server specs a build
536 // enabled: the configured eager/background tiers plus host-session extras.
537 // Names are deduplicated so the kernel catalog holds one entry per server.
538 func enabledMCPSpecs(configSpecs, extraSpecs []plugin.Spec) []plugin.Spec {
539 var out []plugin.Spec
540 seen := map[string]bool{}
541 add := func(spec plugin.Spec) {
542 name := strings.TrimSpace(spec.Name)
543 if name == "" || seen[name] {
544 return
545 }
546 seen[name] = true
547 out = append(out, spec)
548 }
549 for _, spec := range configSpecs {
550 add(spec)
551 }
552 for _, spec := range extraSpecs {
553 add(spec)
554 }
555 return out
556 }
557
558 // gateExtensionUIRequest serves a sidecar's blocking host/ui/request once the
559 // session controller exists. A sidecar may legally ask right after
560 // extension/initialized — while the build is still assembling the controller —
561 // so the preflight hub cannot answer immediately. Rather than failing the
562 // prompt (which would deadlock an extension waiting on its own startup
563 // request), the gate waits for the controller to become ready, for the build
564 // to fail, or for the request context to cancel. serve is only invoked after
565 // load reports a controller.
566 func gateExtensionUIRequest(reqCtx context.Context, load func() *control.Controller, ready <-chan struct{}, failed <-chan struct{}, serve func(*control.Controller) (map[string]any, bool, error)) (map[string]any, bool, error) {
567 if c := load(); c != nil {
568 return serve(c)
569 }
570 select {
571 case <-ready:
572 c := load()
573 if c == nil {
574 return nil, false, fmt.Errorf("extension UI request: controller readiness signalled without a controller")
575 }
576 return serve(c)
577 case <-failed:
578 return nil, false, fmt.Errorf("extension UI request arrived but the session build failed")
579 case <-reqCtx.Done():
580 return nil, false, reqCtx.Err()
581 }
582 }
583
583 lines GO