GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor(session): consolidate autobest + autosteer observers on Adap… · apstenku123/opencode@9e01645

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/opencode
    • src/session
      • autobest-observer.ts
      • autosteer-observer.ts
      • prompt.ts
    • test/session
      • autosteer-observer.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/opencode/src/session/autobest-observer.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/autobest-observer.ts
+17-42Lines changed: 17 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Effect, Layer, Context, Option } from "effect"
1+
import { Effect, Option } from "effect"
22
import { Session } from "./index"
33
import { AdaptiveHooks } from "./adaptive"
44
import { MessageV2 } from "./message-v2"
@@ -58,8 +58,6 @@ export function shouldContinue(input: {
5858
}
5959

6060
export namespace SessionAutobestObserver {
61-
export interface Interface {}
62-
6361
/**
6462
* Legacy deterministic bullet-regex extractor.
6563
* Kept for callers (and existing tests) that expect a synchronous return.
@@ -219,21 +217,17 @@ export namespace SessionAutobestObserver {
219217
if (decision.kind === "a" && candidates.length) {
220218
// Step A: persist the candidate via `applyAutobest` (writes
221219
// `autobest.result` + `autobest.active` history events) and
222-
// record the cycle advance. We deliberately do NOT return an
223-
// Inject directive here — Step A's auto-continuation needs to
224-
// re-enter the loop carrying the original user turn's
225-
// agent/model/provider context, which the bare
226-
// `appendUserText({ synthetic: true })` path that AdaptiveHooks
227-
// Inject uses does not preserve (it tags the synthetic with
228-
// `model = { providerID: "manual", modelID: "manual" }` and
229-
// breaks the next iteration's provider lookup). Round-3 will
230-
// wire a continuation submitter that calls `prompt()` with the
231-
// proper context. See round-3 backlog.
232-
//
233-
// Step B / C below DO Inject — those branches only ever run
234-
// when the loop has already produced an assistant turn this
235-
// cycle, so the next iteration's `lastUser` lookup walks back
236-
// past the synthetic to the original user message.
220+
// record the cycle advance. Returns `Continue` without an
221+
// Inject directive — the runLoop ends this turn at the
222+
// assistant message boundary. Auto-continuation of Step A
223+
// (re-entering the loop carrying the top candidate as the
224+
// next user turn) is deferred: the old inline
225+
// `continuePrompt` path in `prompt.ts` has been removed as
226+
// part of the round-4 consolidation, and the hook-driven
227+
// replacement lives in Step B/C/D where an assistant message
228+
// has already been produced this iteration (so the next
229+
// iteration's `lastUser` lookup walks past the synthetic to
230+
// the original user message and preserves agent/model context).
237231
yield* session
238232
.applyAutobest({ sessionID: args.sessionID, candidates, ts: Date.now() })
239233
.pipe(Effect.ignore)
@@ -310,18 +304,18 @@ export namespace SessionAutobestObserver {
310304
return observer
311305
})
312306

313-
export class Service extends Context.Service<Service, Interface>()("@opencode/SessionAutobestObserver") {}
314-
315307
/**
316308
* Per-instance idempotent registration helper. Safe to call multiple
317309
* times; subsequent calls are no-ops. Intended to be invoked lazily from
318310
* inside an Instance scope (e.g. on the first `runLoop` iteration), which
319311
* is necessary because {@link AdaptiveHooks.register} writes through
320312
* `InstanceState` and cannot run at layer-build time.
321313
*
322-
* Returns the deregister function for the observer; deregister is
323-
* optional — production callers leave the observer registered for the
324-
* lifetime of the instance.
314+
* Round-4 consolidation (migration plan §3.2 #12) removed the legacy
315+
* marker `Service` / `layer` / `defaultLayer`; the observer now registers
316+
* itself directly via this helper and the AdaptiveHooks pipeline is the
317+
* single entrypoint for autobest post-iteration behavior (Step A → D,
318+
* grounding, candidate persistence, cycle advance).
325319
*/
326320
const registeredInstances = new WeakSet<object>()
327321
export const ensureRegistered = Effect.fn("autobest.observer.ensureRegistered")(function* () {
@@ -331,25 +325,6 @@ export namespace SessionAutobestObserver {
331325
const observer = yield* buildObserver()
332326
yield* hooks.register(observer)
333327
})
334-
335-
/**
336-
* Adaptive-hook layer. The observer is registered lazily by the runLoop's
337-
* first iteration (see `prompt.ts`) so we are guaranteed to be inside an
338-
* Instance scope when the registration touches `InstanceState`. Round-1's
339-
* bus-driven `Idle` listener has been removed (migration plan §3.2 #12).
340-
*
341-
* The layer itself is a no-op marker so callers can express the dependency
342-
* in type signatures; the real work happens in {@link ensureRegistered}.
343-
*/
344-
export const layer = Layer.effect(
345-
Service,
346-
Effect.gen(function* () {
347-
// No I/O at layer-build — registration is deferred to first runLoop call.
348-
return Service.of({})
349-
}),
350-
)
351-
352-
export const defaultLayer = layer
353328
}
354329

355330
// MessageV2 referenced for parity with the prior file (kept as transitive type).
Collapse file

‎packages/opencode/src/session/autosteer-observer.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/autosteer-observer.ts
+30-49Lines changed: 30 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -11,42 +11,36 @@ import { SessionAutosteer } from "./autosteer"
1111
import { AdaptiveHooks } from "./adaptive"
1212

1313
/**
14-
* Autosteer observer (round 3).
14+
* Autosteer observer (round 4 consolidation).
1515
*
1616
* Ported to the {@link AdaptiveHooks} pipeline — round 1's
1717
* `Bus.subscribeCallback(SessionStatus.Event.Idle)` has been removed.
18-
* Stagnation detection now runs in a `postIteration` observer so the hook
18+
* Stagnation detection runs in a `postIteration` observer so the hook
1919
* runner arbitrates directive precedence (`break` > `inject` > `continue`)
2020
* between autosteer, autobest, and any other registered observers.
2121
*
22-
* The observer no longer calls `Session.Service.appendUserText` itself —
23-
* that is now the runLoop's responsibility via the `Inject` directive
24-
* plumbing in `prompt.ts`. This avoids racing a bus-thread `appendUserText`
25-
* against the runLoop's next iteration.
22+
* Round-4 consolidation removed the legacy `{inject: true}` back-compat
23+
* path: `evaluateSession` is now pure detection and never appends a user
24+
* message itself. All nudge injection flows through the postIteration
25+
* observer's `Inject` directive, which the runLoop handles by calling
26+
* `Session.Service.appendUserText` with the enclosing turn's
27+
* agent/model/provider context (see `prompt.ts` post-iteration branch).
2628
*
2729
* The Service interface is preserved for the TUI sidebar + server routes
28-
* (autosteering toggle, cumulative nudge count). Tests call
29-
* `evaluateSession` with `{inject: true}` to retain the round-2
30-
* append-user-message side-effect; the hook pathway passes `{inject: false}`.
30+
* (autosteering toggle, cumulative nudge count).
3131
*/
3232
export namespace SessionAutosteerObserver {
3333
export interface Interface {
3434
/** Inspect current counter for a session. */
3535
readonly getCount: (sessionID: SessionID) => Effect.Effect<number>
3636
/**
3737
* Evaluate now against the last two assistant messages. Returns the
38-
* evaluation outcome plus (optionally) the text the runner should
39-
* inject as a synthetic user turn.
40-
*
41-
* @param opts.inject — when `true` (the default, for back-compat with
42-
* the round-2 test suite), performs the legacy side-effect of
43-
* appending a synthetic user message via `Session.Service.appendUserText`
44-
* when a nudge fires. The hook-driven path passes `false`.
38+
* evaluation outcome plus the text the runner should inject as a
39+
* synthetic user turn. Detection-only — after round-4 consolidation
40+
* this method never mutates session state; actual injection happens
41+
* via the registered `postIteration` observer (see layer body).
4542
*/
46-
readonly evaluateSession: (
47-
sessionID: SessionID,
48-
opts?: { inject?: boolean },
49-
) => Effect.Effect<{
43+
readonly evaluateSession: (sessionID: SessionID) => Effect.Effect<{
5044
stagnant: boolean
5145
nudge: boolean
5246
count: number
@@ -93,7 +87,6 @@ export namespace SessionAutosteerObserver {
9387
Service,
9488
Effect.gen(function* () {
9589
const bus = yield* Bus.Service
96-
const session = yield* Session.Service
9790
const config = yield* Config.Service
9891
const adaptive = yield* AdaptiveHooks.Service
9992

@@ -143,7 +136,7 @@ export namespace SessionAutosteerObserver {
143136
return new Map(map) as ReadonlyMap<SessionID, number>
144137
})
145138

146-
const evaluateSession: Interface["evaluateSession"] = (sessionID, opts) =>
139+
const evaluateSession: Interface["evaluateSession"] = (sessionID) =>
147140
Effect.gen(function* () {
148141
const enabled = yield* isEnabled()
149142
if (!enabled) return { stagnant: false, nudge: false, count: 0 }
@@ -182,26 +175,6 @@ export namespace SessionAutosteerObserver {
182175
}
183176
const out = SessionAutosteer.evaluate(state, latest, thresholds)
184177
map.set(sessionID, out.nextState)
185-
186-
if (out.nudge) {
187-
// Backwards-compatible side-effect path — when the caller opts
188-
// into direct injection (default), persist the nudge as a
189-
// synthetic user message exactly as round-2 did.
190-
if (opts?.inject !== false) {
191-
yield* session.appendUserText({
192-
sessionID,
193-
text: SessionAutosteer.NUDGE_TEXT,
194-
synthetic: true,
195-
})
196-
}
197-
const counts = yield* InstanceState.get(nudgeCounts)
198-
const nextLifetime = (counts.get(sessionID) ?? 0) + 1
199-
counts.set(sessionID, nextLifetime)
200-
yield* bus.publish(Event.NudgeInjected, {
201-
sessionID,
202-
count: nextLifetime,
203-
})
204-
}
205178
return {
206179
stagnant: out.stagnant,
207180
nudge: out.nudge,
@@ -210,19 +183,27 @@ export namespace SessionAutosteerObserver {
210183
}
211184
})
212185

213-
// Register postIteration observer — replaces the round-2
214-
// Bus.subscribeCallback(SessionStatus.Event.Idle) path. The runLoop
186+
// Register postIteration observer — this is the single entrypoint
187+
// for autosteer behavior after round-4 consolidation. The runLoop
215188
// invokes `runPostIteration` at the end of each assistant step; we
216-
// evaluate stagnation and surface `Inject` so the runner appends the
217-
// synthetic user message and continues the loop. We pass
218-
// `inject: false` to `evaluateSession` so the runner (not this
219-
// observer) performs the append — prevents double-injection.
189+
// evaluate stagnation and surface `Inject` so the runner appends
190+
// the synthetic user message (with the turn's agent/model/provider
191+
// context preserved) and continues the loop. Cumulative-nudge
192+
// telemetry is updated here so it tracks real nudge injections
193+
// only — evaluateSession itself is detection-only.
220194
yield* adaptive.register({
221195
name: "autosteer",
222196
postIteration: (_state, args) =>
223197
Effect.gen(function* () {
224-
const out = yield* evaluateSession(args.sessionID, { inject: false })
198+
const out = yield* evaluateSession(args.sessionID)
225199
if (!out.nudge || !out.nudgeText) return AdaptiveHooks.Continue
200+
const counts = yield* InstanceState.get(nudgeCounts)
201+
const nextLifetime = (counts.get(args.sessionID) ?? 0) + 1
202+
counts.set(args.sessionID, nextLifetime)
203+
yield* bus.publish(Event.NudgeInjected, {
204+
sessionID: args.sessionID,
205+
count: nextLifetime,
206+
})
226207
return AdaptiveHooks.Inject({
227208
text: out.nudgeText,
228209
source: "autosteer:nudge",
Collapse file

‎packages/opencode/src/session/prompt.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/prompt.ts
+35-84Lines changed: 35 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ import { EffectLogger } from "@/effect"
4949
import { InstanceState } from "@/effect"
5050
import { TaskTool, type TaskPromptOps } from "@/tool/task"
5151
import { SessionRunState } from "./run-state"
52-
import { SessionAutobestObserver, shouldContinue as autobestShouldContinue } from "./autobest-observer"
52+
import { SessionAutobestObserver } from "./autobest-observer"
5353
import { AdaptiveHooks } from "./adaptive"
5454
import { SessionMemoryObserver } from "./memory-observer"
5555
import { dequeueEnrichmentBlock } from "@/memory/turn-hooks"
@@ -78,24 +78,14 @@ export namespace SessionPrompt {
7878
const elog = EffectLogger.create({ service: "session.prompt" })
7979

8080
/**
81-
* Module-level per-session autobest cycle state.
82-
* Tracks iteration count and last stepKind to gate the auto-continue loop.
83-
* Reset on explicit user prompt via `prompt()` so each user-initiated turn
84-
* starts a fresh cycle.
85-
*
86-
* NB: round-1 uses a Map for simplicity. Round-2 should migrate this into
87-
* durable history events (cf. `docs/codex-rs-migration-plan.md` §3.2).
88-
*/
89-
export const autobestCycleState = new Map<string, { iteration: number; stepKind: "a" | "b" | "c" | "d" }>()
90-
export const DEFAULT_AUTOBEST_MAX_ITERATIONS = 3
91-
/**
92-
* Session ids with an in-flight autobest continuation.
93-
* When `prompt()` sees the sessionID is NOT in this set, the incoming prompt
94-
* is treated as user-initiated and resets the cycle counter. When it IS in
95-
* the set, we leave the cycle counter alone and remove the entry so the next
96-
* `prompt()` call resets again.
81+
* Round-4 consolidation (§3.2 #12) retired the module-level
82+
* `autobestCycleState` / `autobestPendingContinuations` maps and the
83+
* inline extract-and-continue block in `runLoop`. Cycle state now lives
84+
* in durable `autobest.cycle.advance` / `autobest.cycle.reset` history
85+
* events managed by the autobest observer. Per-cycle AdaptiveState
86+
* reset at user-message boundary is handled by `adaptive.resetCycleFor`
87+
* in the `prompt()` entrypoint.
9788
*/
98-
export const autobestPendingContinuations = new Set<string>()
9989

10090
/**
10191
* Default per-hook timeout (ms) for {@link runStopHook} when the config
@@ -1469,16 +1459,14 @@ NOTE: At any point in time through this workflow you should feel free to ask the
14691459

14701460
const prompt: (input: PromptInput) => Effect.Effect<MessageV2.WithParts> = Effect.fn("SessionPrompt.prompt")(
14711461
function* (input: PromptInput) {
1472-
// Reset autobest cycle on user-initiated prompts (not autobest continuations).
1473-
if (autobestPendingContinuations.has(input.sessionID)) {
1474-
autobestPendingContinuations.delete(input.sessionID)
1475-
} else {
1476-
autobestCycleState.delete(input.sessionID)
1477-
// Fresh user-message boundary — reset per-cycle AdaptiveState
1478-
// counters. Preserves cross-cycle scratch state such as the
1479-
// injectCount diagnostic counter.
1480-
yield* adaptive.resetCycleFor(input.sessionID)
1481-
}
1462+
// Fresh user-message boundary — reset per-cycle AdaptiveState
1463+
// counters. Preserves cross-cycle scratch state such as the
1464+
// injectCount diagnostic counter. Post round-4 consolidation,
1465+
// autobest auto-continuations re-enter the loop via the
1466+
// AdaptiveHooks `Inject` directive (synthetic user message),
1467+
// which does NOT call `prompt()` — so this reset only fires on
1468+
// truly user-initiated turns as intended.
1469+
yield* adaptive.resetCycleFor(input.sessionID)
14821470

14831471
const session = yield* sessions.get(input.sessionID)
14841472
yield* revert.cleanup(session)
@@ -1523,6 +1511,20 @@ NOTE: At any point in time through this workflow you should feel free to ask the
15231511
.ensureRegistered()
15241512
.pipe(Effect.catchCause(() => Effect.void))
15251513

1514+
// Lazy-register the autobest post-iteration observer. Consolidated
1515+
// in round-4 from the former inline `SessionAutobestObserver.extract`
1516+
// block that lived here — autobest cycle progression (Step A → D),
1517+
// grounding dispatch, and candidate persistence now all happen in
1518+
// the registered observer's `postIteration` callback. Already-
1519+
// resolved services are provided so the ensureRegistered Effect
1520+
// is R-clean at this scope. MCP is optional (observer uses
1521+
// `Effect.serviceOption`), so we don't need to provide it here.
1522+
yield* SessionAutobestObserver.ensureRegistered().pipe(
1523+
Effect.provideService(AdaptiveHooks.Service, adaptive),
1524+
Effect.provideService(Session.Service, sessions),
1525+
Effect.catchCause(() => Effect.void),
1526+
)
1527+
15261528
while (true) {
15271529
yield* status.set(sessionID, { type: "busy" })
15281530
yield* slog.info("loop", { step })
@@ -1857,66 +1859,15 @@ NOTE: At any point in time through this workflow you should feel free to ask the
18571859

18581860
yield* compaction.prune({ sessionID }).pipe(Effect.ignore, Effect.forkIn(scope))
18591861
const out = yield* lastAssistant(sessionID)
1860-
const autobestEnabled = yield* sessions.getAutobestEnabled(sessionID)
1861-
if (autobestEnabled && out.info.role === "assistant") {
1862-
const text = out.parts
1863-
.filter((part): part is MessageV2.TextPart => part.type === "text")
1864-
.map((part) => part.text.trim())
1865-
.filter(Boolean)
1866-
.join("\n")
1867-
const picks = SessionAutobestObserver.extract(text)
1868-
if (picks.length) {
1869-
const applied = yield* sessions
1870-
.applyAutobest({ sessionID, candidates: picks, ts: Date.now() })
1871-
.pipe(Effect.match({ onFailure: () => null, onSuccess: (v) => v }))
1872-
1873-
if (applied && applied.decision.changed && applied.decision.active) {
1874-
// Auto-continue feedback loop — port of
1875-
// `chatwidget.rs::on_autobest_result::submit_user_message`.
1876-
// Per-session iteration is tracked in-memory and gated by shouldContinue.
1877-
const prev = autobestCycleState.get(sessionID) ?? { iteration: 0, stepKind: "a" as const }
1878-
const decision = autobestShouldContinue({
1879-
enabled: autobestEnabled,
1880-
changed: true,
1881-
activeKey: applied.decision.active.key,
1882-
cycle: prev,
1883-
maxIterations: DEFAULT_AUTOBEST_MAX_ITERATIONS,
1884-
})
1885-
if (decision.shouldContinue) {
1886-
autobestCycleState.set(sessionID, {
1887-
iteration: prev.iteration + 1,
1888-
stepKind: "a",
1889-
})
1890-
yield* continuePrompt(sessionID, applied.decision.active.key).pipe(
1891-
Effect.ignore,
1892-
Effect.forkIn(scope),
1893-
)
1894-
} else if (decision.reason === "max-iterations-reached") {
1895-
// Reset so the next user-initiated turn starts a fresh cycle.
1896-
autobestCycleState.delete(sessionID)
1897-
}
1898-
}
1899-
}
1900-
}
1862+
// Autobest extract + cycle advance + auto-continuation are now
1863+
// owned end-to-end by `SessionAutobestObserver` via the
1864+
// AdaptiveHooks `postIteration` pipeline (see ensureRegistered
1865+
// call at the top of `runLoop`). The inline duplicate block
1866+
// was removed during round-4 consolidation.
19011867
return out
19021868
},
19031869
)
19041870

1905-
// Continuation submitter — schedules a synthetic user prompt carrying
1906-
// the autobest top candidate. Delegates to the public `prompt()` helper
1907-
// so the full run-loop pipeline (including compaction / autobest) re-runs.
1908-
const continuePrompt = Effect.fn("SessionPrompt.autobestContinue")(function* (
1909-
sessionID: SessionID,
1910-
text: string,
1911-
) {
1912-
yield* elog.info("autobest.continue", { sessionID, text })
1913-
autobestPendingContinuations.add(sessionID)
1914-
yield* prompt({
1915-
sessionID,
1916-
parts: [{ type: "text" as const, text }],
1917-
} as PromptInput).pipe(Effect.ignore)
1918-
})
1919-
19201871
const loop: (input: z.infer<typeof LoopInput>) => Effect.Effect<MessageV2.WithParts> = Effect.fn(
19211872
"SessionPrompt.loop",
19221873
)(function* (input: z.infer<typeof LoopInput>) {

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.