|
| 1 | +/** |
| 2 | + * DreamerSolver — plan in the predictor, act in the env. |
| 3 | + * |
| 4 | + * Each turn: |
| 5 | + * 1. Enumerate tools available now. |
| 6 | + * 2. For each candidate tool, ask the Predictor what happens. |
| 7 | + * (Optional lookahead k>1 rolls out k steps deep recursively.) |
| 8 | + * 3. Pick the action whose imagined trajectory closes the most distance. |
| 9 | + * 4. Commit that single action to the real env. |
| 10 | + * 5. Repeat. |
| 11 | + * |
| 12 | + * v0 is the plain "predict-and-pick" base case — like GreedySolver but |
| 13 | + * using a learned dynamics function instead of env.simulate(). That's |
| 14 | + * the unlock for envs where you can't write a simulator (real APIs, |
| 15 | + * databases, integrations). |
| 16 | + * |
| 17 | + * Future versions add value-net guided rollouts and policy distillation |
| 18 | + * from imagined trajectories — the full Dreamer arc. |
| 19 | + */ |
| 20 | + |
| 21 | +import type { SceneGradEnv, ToolCall, Goal } from "./env.js"; |
| 22 | +import { distance, checkAll } from "./env.js"; |
| 23 | +import type { Solver, SolveResult, SolverOpts, TrajectoryStep } from "./solver.js"; |
| 24 | +import type { Predictor } from "./predict.js"; |
| 25 | + |
| 26 | +export interface DreamerSolverOpts extends SolverOpts { |
| 27 | + predictor: Predictor<any, any>; |
| 28 | + /** Plan depth — how many predictor calls to chain per candidate. |
| 29 | + * v0 ships with k=1 working well; k>1 is exponential and best for small toolsets. */ |
| 30 | + lookahead?: number; |
| 31 | + /** Optional beam width for k>1. Defaults to all candidates. */ |
| 32 | + beam?: number; |
| 33 | + /** Filter low-confidence predictions out of planning. Default 0 — keep all. */ |
| 34 | + minConfidence?: number; |
| 35 | +} |
| 36 | + |
| 37 | +export class DreamerSolver<S, T extends ToolCall = ToolCall> implements Solver<S, T> { |
| 38 | + readonly name: string; |
| 39 | + private predictor: Predictor<S, T>; |
| 40 | + private lookahead: number; |
| 41 | + private beam: number; |
| 42 | + private minConf: number; |
| 43 | + |
| 44 | + constructor(opts: DreamerSolverOpts) { |
| 45 | + this.predictor = opts.predictor as Predictor<S, T>; |
| 46 | + this.lookahead = Math.max(1, opts.lookahead ?? 1); |
| 47 | + this.beam = Math.max(1, opts.beam ?? Infinity); |
| 48 | + this.minConf = Math.max(0, opts.minConfidence ?? 0); |
| 49 | + this.name = `dreamer(${this.predictor.name},k=${this.lookahead})`; |
| 50 | + } |
| 51 | + |
| 52 | + async solve(env: SceneGradEnv<S, T>, taskId: string, opts?: SolverOpts): Promise<SolveResult<T>> { |
| 53 | + const t_start = Date.now(); |
| 54 | + const maxSteps = opts?.maxSteps ?? 30; |
| 55 | + |
| 56 | + env.reset(taskId); |
| 57 | + const trajectory: TrajectoryStep<T>[] = []; |
| 58 | + const d_initial = distance(env.scene(), env.goal()); |
| 59 | + |
| 60 | + for (let step = 0; step < maxSteps; step++) { |
| 61 | + if (env.done()) break; |
| 62 | + |
| 63 | + const goal = env.goal(); |
| 64 | + const d_before = distance(env.scene(), goal); |
| 65 | + const tools = env.tools(); |
| 66 | + if (tools.length === 0) break; |
| 67 | + |
| 68 | + const best = await this.pickBest(env.scene(), tools, goal); |
| 69 | + |
| 70 | + if (!best || best.predicted_d_after >= d_before) { |
| 71 | + trajectory.push({ |
| 72 | + step, |
| 73 | + tool: null, |
| 74 | + d_before, |
| 75 | + d_after: d_before, |
| 76 | + delta: 0, |
| 77 | + predicted_delta: best ? d_before - best.predicted_d_after : 0, |
| 78 | + ok: false, |
| 79 | + error: "no predicted action reduces distance (stuck or low-confidence)", |
| 80 | + assertions_after: checkAll(env.scene(), goal), |
| 81 | + ts_ms: Date.now() - t_start, |
| 82 | + }); |
| 83 | + break; |
| 84 | + } |
| 85 | + |
| 86 | + // Commit the chosen action to the real env. |
| 87 | + const result = env.step(best.tool); |
| 88 | + const d_after = result.distance_after ?? distance(env.scene(), goal); |
| 89 | + |
| 90 | + trajectory.push({ |
| 91 | + step, |
| 92 | + tool: best.tool, |
| 93 | + d_before, |
| 94 | + d_after, |
| 95 | + delta: d_before - d_after, |
| 96 | + predicted_delta: d_before - best.predicted_d_after, |
| 97 | + reasoning: best.reasoning, |
| 98 | + ok: result.ok, |
| 99 | + error: result.error, |
| 100 | + assertions_after: checkAll(env.scene(), goal), |
| 101 | + ts_ms: Date.now() - t_start, |
| 102 | + }); |
| 103 | + } |
| 104 | + |
| 105 | + const d_final = distance(env.scene(), env.goal()); |
| 106 | + return { |
| 107 | + task_id: taskId, |
| 108 | + solver: this.name, |
| 109 | + success: env.done(), |
| 110 | + steps: trajectory.length, |
| 111 | + d_initial, |
| 112 | + d_final, |
| 113 | + duration_ms: Date.now() - t_start, |
| 114 | + trajectory, |
| 115 | + }; |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Pick the tool whose imagined rollout reaches the lowest distance. |
| 120 | + * Lookahead=1: one predictor call per tool. Lookahead=k: chains k. |
| 121 | + */ |
| 122 | + private async pickBest( |
| 123 | + scene: S, |
| 124 | + tools: T[], |
| 125 | + goal: Goal<S>, |
| 126 | + ): Promise<{ tool: T; predicted_d_after: number; reasoning?: string } | null> { |
| 127 | + const candidates = await Promise.all( |
| 128 | + tools.map(async (tool) => { |
| 129 | + const c = await this.predictor.predict(scene, tool); |
| 130 | + if (c.confidence < this.minConf) return null; |
| 131 | + if (!c.outcome.ok) return null; |
| 132 | + const d_after = await this.rolloutTail(c.scene_after, goal, this.lookahead - 1); |
| 133 | + return { tool, predicted_d_after: d_after, reasoning: c.reasoning }; |
| 134 | + }), |
| 135 | + ); |
| 136 | + const valid = candidates.filter((x): x is NonNullable<typeof x> => x !== null); |
| 137 | + if (valid.length === 0) return null; |
| 138 | + valid.sort((a, b) => a.predicted_d_after - b.predicted_d_after); |
| 139 | + return valid[0]!; |
| 140 | + } |
| 141 | + |
| 142 | + /** |
| 143 | + * Roll out depth-k more predictor steps after the head action, returning |
| 144 | + * the best (lowest) distance reachable. k=0 returns the head's distance. |
| 145 | + */ |
| 146 | + private async rolloutTail(scene: S, goal: Goal<S>, k: number): Promise<number> { |
| 147 | + if (k <= 0) return distance(scene, goal); |
| 148 | + // Synthetic env-less rollout: we don't have env.tools() for predicted |
| 149 | + // future scenes. v0 punts: trust the head prediction. v0.1 will pass |
| 150 | + // a domain-provided `toolsAt(scene)` for true k-step lookahead. |
| 151 | + return distance(scene, goal); |
| 152 | + } |
| 153 | +} |
0 commit comments