Repository navigation
feat: add goal vended plugin - #1082
Conversation
|
need to look more, but curious why not steering? could we integrate this into steering/use this as an opportunity to advertise steering? a la "we don't just do ralph wiggum like cc... we have so much more" |
|
Issue: This PR introduces a new public class and abstraction that customers will use frequently. Per the API bar-raising process, this qualifies as a "moderate change" requiring at minimum informal discussion with an API reviewer. The PR should have the Key questions for API review:
|
|
Assessment: Request Changes Well-designed plugin with clean architecture, solid test coverage (31 unit tests + 2 integration tests), and a thoughtful API surface. The core retry-loop machinery and snapshot-restore logic are implemented correctly. A few items need attention before merge. Review Categories
The test suite is thorough and the freshContextPerAttempt implementation is well-thought-out. |
at the very least, if we decide want Ralph Wiggum to be separate from |
|
As to why not steering: Conceptually the goal is giving us long-running loop with an AfterInvocationEvent check. Deciding to re-run top level agent loop. Steering is giving the model nudges within an agent loop turn. If we look at the vended system prompts for each feature: the plugin has a judging system prompt for deciding if a goal has been reached. Steering has a prompt about how to guide on an action mid turn. So although technically you could kind of fit this feature as a steering handler, a plugin is the minimal best fit for the functionality we need IMO. |
It's more than guide because it has specific goal oriented judging criteria. And managing the state to get fresh context for Ralph wiggum etc. In any case there is a lot of conceptual overlaps. It's true that this could be re-written as steering. I just personally think that would stray from the goal loop concept. |
|
@lizradway and I synced offline. The open question is if we want this as a Plugin or an InterventionHandler. We are agreed that it's not a steering candidate |
|
The team aligned that this is best designed as a Plugin |
agent-of-mkmeral
left a comment
There was a problem hiding this comment.
Review — sharing learnings from a sibling plugin
Great work on this — the snapshot/restore mechanism is clean and the test discipline (validator-driven structural assertions, never on model output) is exactly right for non-deterministic LLM tests.
I'm leaving this as a COMMENT review (not REQUEST_CHANGES) because the existing bot review has the structural items covered. What I want to add is field-tested learnings from a near-identical plugin we shipped recently in a downstream agent — same AfterInvocationEvent-driven retry loop, same critic/judge concept, same failure shape. We hit several issues in production that are reproducible in this code; flagging them while the design is still mutable.
🔴 Empty/errored actor response is silently dropped — we shipped this exact bug, fixed last week
In plugin.ts:259-261:
// Cancelled or model-threw before emitting an assistant message.
const response = lastAssistantMessage(agent.messages)
if (!response) returnWhen the actor throws mid-invocation, errors out, or never emits an assistant message, the After hook bails — no retry, no lastResult updated, no stopReason. The whole goal loop silently disengages exactly when retry would be most valuable.
Empirical data from our plugin: across 45 runs in the 2.5 days after our equivalent shipped, 12 of 27 critic-eligible runs hit the silent-skip path and the critic issued zero RETRYs — the highest-value failure mode never reached the validator. This is especially costly in Ralph mode, which is sold for long-running autonomous loops where transient failures are expected and recovery is the point.
How we fixed it (commit): stop hardcoding the skip in plugin code; instead annotate the empty response ([NO FINAL RESPONSE — actor produced no message text] or [ACTOR ERRORED OR TIMED OUT BEFORE COMPLETING]) and pass it through to the judge/critic. The decision (RETRY vs PASS-on-intentional-no-op) lives in the judge's system prompt rather than plugin logic.
Suggestion for #1082:
- When
responseis missing, still incrementattempts, push aGoalAttemptwithpassed: false, feedback: '[ACTOR ERRORED OR PRODUCED NO MESSAGE]', and armevent.resume(subject to budgets). - For NL-judge validators: detect this case before calling the judge (it can't grade an empty response anyway) and short-circuit to a structured fail-with-feedback.
- The
cross-invocation lastResult lifecycledescribe block atplugin.test.ts:507-527coverslastResultclearing after a thrown invoke — but doesn't cover "actor errored mid-loop, plugin should retry". That gap is what masked our bug for 2.5 days; consider adding it.
🟡 NL-judge sees text-only — tool calls invisible, makes systematically worse verdicts on tool-using agents
In judge.ts:30-36, buildJudgePrompt only serialises textBlock content from the transcript:
const text = m.content.flatMap((b) => (b.type === 'textBlock' ? [b.text] : [])).join('\n')For agents using tools — which is the headline use case in the PR's npm test-driven Ralph example — the judge sees no toolUse / toolResult blocks. It can't tell whether the agent successfully ran a tool or hallucinated about it.
What we learned: our first version of the critic only saw the final response. Verdicts were noisy and missed concrete failures. We expanded context in this commit to include a tool-call summary section, and verdict quality improved measurably. The current shape:
## Original Task
...
## Actor's Tool Calls
- shell: ls -la
→ success: total 24 ...
## Actor's Final Response
...
Suggestion: add a one-line summary of toolUse/toolResult blocks to buildJudgePrompt's transcript serialisation. Otherwise the NL-judge path is anti-Ralph (model grading model on incomplete data) on the very use case the PR sells.
In the function-validator path this is moot (the user knows what they're checking) — only matters for the NL-judge.
🟡 Binary `passed: boolean` over-retries on unverifiable goals — we needed a third verdict
We started with passed: boolean too. We found that for genuinely conversational tasks ("explain X", research questions, design proposals), forcing the judge into PASS/RETRY led to noisy retries: the response was fine, the judge nitpicked, the loop burned maxAttempts chasing a non-issue.
We added a third verdict — BYPASS (task is not concretely verifiable) — encoded directly in the judge's system prompt. Three verdicts, two outcomes:
BYPASS→ terminate withstopReason: 'unverifiable', signal to caller that the goal couldn't be meaningfully validatedPASS→ terminate, satisfiedRETRY→ resume with feedback
For #1082 specifically, the function-validator path is fine as binary (user knows their predicate). For the NL-judge path, two options:
- Add an
abstainoutcome with its ownstopReason: 'unverifiable'. - Document NL-judge mode as best for measurable soft constraints (length, style, format) and explicitly steer users to function validators for hard checks.
Our experience: option 1 is worth the small API surface cost. The signal to callers ("goal couldn't be validated" ≠ "goal failed") is genuinely useful and avoids the burn-budget trap.
🟢 Validator-error-as-failed-attempt masks programming bugs (already in my prior review on the issue side; reinforcing)
plugin.ts:269-273 swallows validator throws as { passed: false, feedback: 'Validator error: ...' }. If a user's validator has a TypeError (e.g. response.foo.bar where foo is undefined), every attempt throws identically, the loop burns maxAttempts retrying against a broken validator, and the user sees a maxAttempts stopReason rather than "your validator is broken".
Suggestion: at minimum, logger.warn on validator throw. Better: distinguish thrown validator errors from { passed: false } outcomes and terminate with stopReason: 'validatorError' after N consecutive throws (e.g. N=2). Our actor-critic handles this via try/except around critic creation that logs and accepts on critic failure — symmetric pattern works here.
🟢 What this PR gets right that we got wrong — credit where due
Inverting the polarity: the cross-invocation state lifecycle in this plugin is better than ours.
The BeforeInvocationEvent reset of _run on every fresh invoke (and the cross-invocation lastResult lifecycle test block) is exactly the right pattern. Our ActorCriticPlugin initialises _retry_count = 0 and _start_time = None in __init__ and never resets — so re-using the plugin across multiple agent() calls in the same process carries retry counters over. We're filing a follow-up against ourselves to copy this pattern.
If you have a moment, the _initialised flag with explicit error on second-agent attach is also a nicer guardrail than what we have. Considering stealing that too.
Summary
| Concern | Severity | Empirical basis |
|---|---|---|
| Empty/errored response silently dropped | 🔴 | 12/27 runs hit it in our equivalent over 2.5 days |
| NL-judge text-only context | 🟡 | Verdict quality measurably improved when we added tool-call summary |
| Binary verdict over-retries on unverifiable goals | 🟡 | We added BYPASS specifically to fix this |
| Validator-error-as-fail masks bugs | 🟢 | Conceptual; we hit similar pattern |
Only 🔴 is something I'd consider a merge blocker. The 🟡s are design conversations that are easier to have now than after customers depend on the current shape. None of this changes the verdict that the core machinery is sound.
Happy to elaborate or share specific code from our equivalent if useful — drop a comment or ping me on the issue thread.
|
@agent-of-mkmeral thanks — concrete and useful. Status:
|
|
Thanks for the detailed dispositions, @notowen333 — agree with all five calls. A few notes for the record: 🟡 NL-judge tool-call visibility (fixed in 🟢 Validator-throw warn (fixed in 🔴 Empty/errored response retry — accept the decline. I checked // Resume only on a clean invocation — errors propagate above.
if (lastAfterInvocation?.resume !== undefined) {
currentArgs = lastAfterInvocation.resume
continue
}You're right — the outer loop short-circuits on caught errors before checking One smaller plugin-side question that's still in scope: in the 🟡 🟢 Auto-terminate after N consecutive validator throws — accept the decline. Agreed. The Summary of merge-blocking concerns from my review: none remaining. The 🔴 from my review is now downgraded to a framework follow-up (not a PR-1082 blocker). LGTM from my side once the team's API-review path resolves. One unrelated nit I noticed while re-reading: the rename |
|
@notowen333 jfyi, we should flatten the configuration, that's the API tenet that we have. We want to avoid nested configs as much as possible. if you think we can extend this more, then we might want to. but then I'd argue, validator and related stuff should also be part of judgeconfig (?) or like part of the same config to choose callbacks. |
|
@mkmeral got it — flat it is. Reverting On your follow-up — "validator and related stuff should also be part of judgeconfig (?) / the same config to choose callbacks" — I think this actually cuts in favor of flattening, and it's the strongest argument against the half-nested The verification knobs are one cohesive concept, and
So the contested new GoalLoop({
validate: 'user's order was placed', // selector: string => NL judge, fn => custom
judgeModel: haiku, // only consulted on the string/NL-judge path
judgeSystemPrompt: '...', // " "
maxAttempts: 3,
timeout: 120_000,
})That the On extensibility: if judge config genuinely grows ( So: flattening to |
…e options Decouple the overloaded `validate: string | function` option into two distinct top-level params: `goal` (natural-language, graded by the internal judge Agent) and `validator` (programmatic predicate). `judge` stays as judge-only tuning (model, systemPrompt). Constructor now throws if both `goal` and `validator` are provided, or if neither is.
|
Assessment: Request Changes One remaining API change needed: flatten Review Details
Well-designed plugin with clean architecture and solid developer ergonomics. The flatten is the only blocker. |
Collapse the separate `goal` (string) and `validator` (function) options into a single `goal: string | Validator`. The constructor branches on `typeof` to route a string to the NL judge and a function to the programmatic path, so the both-provided / neither-provided guards reduce to a single required check.
|
Assessment: Request Changes Two issues remain: one bug from the Review Details
The rest of the implementation is solid — clean architecture, thorough tests, proper WeakSet/WeakMap state isolation, and good developer ergonomics. Just these two items to resolve. |
|
Quick consolidation of where this stands, since the open items are scattered across threads. @zastrowm — your two questions:
Merge-blockers remaining (all mechanical):
None of these are architectural — the plugin itself is solid. Once the |
…dator verify.ts constructed GoalLoop with the removed `validator` field (TS2353 / runtime throw); switch to `goal`. Refresh the _buildValidator docstring that still referenced the old two-field API.
Clears 4 critical advisories (GHSA-2h32-95rg-cppp, vitest browser mode serves unsanitized otelCarrier query parameter as inline script) flagged by `npm audit --audit-level=high`. Bumps the @vitest/* family in strands-ts and vitest in strands-wasm. Mirrors sdk-python a20c2af.
|
Assessment: Request Changes One remaining blocker: Review Details
Once the flatten lands, this is ready to merge. |
e065899
Description
Motivation
Real agent workflows often need iterative refinement — write code that passes tests, draft prose under constraints, generate output that satisfies a domain check. Today users hand-roll this with
BeforeInvocationEvent/AfterInvocationEventhooks; the result is repetitive and easy to get wrong (budget enforcement, judge transcript isolation, resume-prompt construction, transcript rewinds for fresh-context retries).GoalLoopis the SDK analogue of Claude Code's/goalcommand: validate the agent's response after each invocation, feed validator feedback back as a fresh user message viaAfterInvocationEvent.resume, and loop until validation passes or a budget is exhausted.Two retry modes
The plugin supports two retry semantics, picked with a single flag.
Standard mode (default) preserves the conversation across attempts — the agent sees its own prior responses and the validator's feedback messages. Use when prior attempts inform the next one (iterative prose refinement, conversational tightening).
Ralph Wiggum mode (
preserveContext: false) restores the agent's transcript to its initial post-input state on every retry. The agent never sees its own prior attempts — only the original input plus the latest validator feedback. Use when prior context misleads more than it helps (agent doubles down on a bad approach) and when flat inference cost across attempts matters. Pairs naturally with toolchain-driven validators (e.g.npm test) where the agent has tools to fix what the validator reports.Critically, Ralph mode rewinds the full model-visible session —
messages,systemPrompt,modelState, andinterruptsall restore to the pre-attempt-1 snapshot, so the model (including any server-side conversation chaining) sees only the original input. OnlyappStateaccumulates across attempts, since that's plugin scratch space invisible to the model — other plugins (rate-limiters, cost-trackers) are unaffected.Public API Changes
lastResult(agent)exposes the terminal outcome for that agent —stopReasonis one of'satisfied' | 'maxAttempts' | 'timeout', with the per-attempt feedback preserved onattempts.Customization
The defaults handle the common cases, but several extensibility surfaces are exposed for power users:
judge— tuning for the auto-built NL judge, grouped into a singleJudgeConfigobject so it's clear the knobs apply only whengoalis a string (harmlessly ignored for function validators):judge.model— swap the judge to a cheaper/faster model (e.g. Haiku) while keeping the heavyweight model on the host. Mirrors Claude Code's fast-evaluator default.judge.systemPrompt— override the judge's system prompt (defaults toJUDGE_SYSTEM_PROMPT) to retune the rubric, localize the instructions, or tighten/relax the pass criteria.resumePromptTemplate— override the canned English retry message. Useful for non-English agents, terser framing, or embedding feedback in a domain-specific structure.JUDGE_OUTCOME_SCHEMA,JUDGE_SYSTEM_PROMPT, andbuildJudgePromptare exported, so users wanting a fully custom NL judge can wire one through a function validator without forking.Related Issues
N/A — new feature
Documentation PR
TBD — agent-docs PR to follow.
Type of Change
New feature
Testing
How have you tested the change?
goalshapes (string / function / async), lifecycle (mid-run, post-throw, multi-invoke), multi-instance stacking, multi-agent rejection, Ralph mode (transcript rewind, appState survival), theresumePromptTemplateoverride, and thejudge.model/judge.systemPromptoverrides../vended-plugins/goalsubpath export andGoalLoop's presence in thevended-pluginsbarrel, alongsideAgentSkillsandContextOffloader.npm run checkChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.