Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 0.5.7 (2026-12-01)

### Fixes

- **Schema runs return their result at the step limit**: with `--output-schema`, the last step before the agent's step cap now asks the model to call `StructuredOutput` with the result file it has written, with tool choice forced to it where the model accepts forced tool choice. Before, the last step sent the text-only max-steps prompt, which forbade every tool call, including `StructuredOutput`, so a run that reached the cap failed with `step_limit` even when its result file was ready. Validation and the corrective budget still apply; a run with no valid result on that step still fails with `step_limit` and exit 3. That last step offers only `StructuredOutput`, so a model that cannot be forced to call it cannot run a work tool instead. Runs without `--output-schema` keep the text-only last step. (#268, refs #267)

## 0.5.6 (2026-11-30)

### Features
Expand Down
3 changes: 3 additions & 0 deletions EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,9 @@ Failure reasons are:
- `missing`: prose finishes or rejected tool calls spent the budget, or the
session ended normally without an accepted result.
- `step_limit`: the agent reached its configured step cap without a result.
The last step before the cap asks only for `StructuredOutput`, with tool
choice forced to it where the model accepts forced tool choice, so a result
file already written can still be returned.
- `aborted`: the invocation was cancelled, including SIGINT/SIGTERM.
- `error`: a provider or session error, including stream idle timeout or an
invalid accepted result received from a remote session.
Expand Down
2 changes: 1 addition & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "0.5.6",
"version": "0.5.7",
"name": "@aictrl/cli",
"description": "The headless agent harness for CI, cron jobs, and container workflows",
"type": "module",
Expand Down
21 changes: 16 additions & 5 deletions packages/cli/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ const STRUCTURED_OUTPUT_MISSING =

const STRUCTURED_OUTPUT_REJECTED = `a tool call was rejected; ${STRUCTURED_OUTPUT_MISSING}`

// The last step of a schema run. The text-only max-steps prompt would forbid
// StructuredOutput, the only way to return a result already on disk (#267).
const STRUCTURED_OUTPUT_LAST_STEP =
"The step limit is reached: this is the last step, and no other tool call will run. Call StructuredOutput now with the path of the result file you have written, as it stands."

const STRUCTURED_OUTPUT_SYSTEM_PROMPT = `IMPORTANT: The user has requested structured output. Write your final result as JSON to a file in the working directory, then call the StructuredOutput tool with that file's path. Do NOT respond with plain text.`

export namespace SessionPrompt {
Expand Down Expand Up @@ -732,6 +737,7 @@ export namespace SessionPrompt {

// normal processing
const isLastStep = step >= maxSteps
const notice = isLastStep && contract ? STRUCTURED_OUTPUT_LAST_STEP : reminder
const processor = SessionProcessor.create({
assistantMessage: (await Session.updateMessage({
id: Identifier.ascending("message"),
Expand Down Expand Up @@ -838,15 +844,15 @@ export namespace SessionPrompt {
system,
messages: [
...MessageV2.toModelMessages(msgs, model),
...(reminder
...(notice
? [
{
role: "user" as const,
content: `<system-reminder>${reminder}</system-reminder>`,
content: `<system-reminder>${notice}</system-reminder>`,
},
]
: []),
...(isLastStep
...(isLastStep && !contract
? [
{
role: ProviderTransform.isGeminiTarget(model) ? ("user" as const) : ("assistant" as const),
Expand All @@ -855,9 +861,14 @@ export namespace SessionPrompt {
]
: []),
],
tools,
// The last step of a schema run offers only the protocol tools, so a
// model on auto tool choice cannot run a work tool either (#267).
tools:
isLastStep && contract
? Object.fromEntries(Object.entries(tools).filter(([, definition]) => ToolGuidance.isProtocol(definition)))
: tools,
model,
toolChoice: contract ? structuredToolChoice(model, reminder) : undefined,
toolChoice: contract ? structuredToolChoice(model, notice) : undefined,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Last-step "no other tool will run" unenforced on auto.

🤖 Fix with your agent
Fix this code review finding (aictrl-dev/cli PR #268, packages/cli/src/session/prompt.ts:866):

Problem: Last-step "no other tool will run" unenforced on auto
Detail: On the last step of a schema run the new notice tells the model "no other tool call will run", but the harness only enforces that through `toolChoice`. `structuredToolChoice` returns `"auto"` for every model `ProviderTransform.supportsForcedToolChoice` rejects (Claude Sonnet/Opus 5.5 and Fable/Mythos 5.1, transform.ts L69-75), and the request still carries the full work-tool set (`tools` at L864 is unchanged), so on those models a last-step `bash`/`write`/… call is executed by `SessionProcessor` with its side effects; only the next loop iteration fails `step_limit`. Exposure is unchanged from before this PR (the old last step also offered every tool), so this is a hardening gap in the new path rather than a regression.

Repro: Given `--output-schema` with a step cap on a model without forced tool choice (e.g. claude-sonnet-5-5), when the last-step response calls `bash` instead of `StructuredOutput`, then the command runs before the run fails `step_limit`.
Suggested fix: When `isLastStep && contract`, send only the protocol tool to `processor.process` (e.g. `tools: isLastStep && contract ? { StructuredOutput: tools.StructuredOutput } : tools`) so the "auto" case behaves like the forced one, or soften the wording to "no other tool call will get another turn" so the notice matches what the harness enforces.

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

On the last step of a schema run the new notice tells the model "no other tool call will run", but the harness only enforces that through toolChoice. structuredToolChoice returns "auto" for every model ProviderTransform.supportsForcedToolChoice rejects (Claude Sonnet/Opus 5.5 and Fable/Mythos 5.1, transform.ts L69-75), and the request still carries the full work-tool set (tools at L864 is unchanged), so on those models a last-step bash/write/… call is executed by SessionProcessor with its side effects; only the next loop iteration fails step_limit. Exposure is unchanged from before this PR (the old last step also offered every tool), so this is a hardening gap in the new path rather than a regression.

Repro: Given --output-schema with a step cap on a model without forced tool choice (e.g. claude-sonnet-5-5), when the last-step response calls bash instead of StructuredOutput, then the command runs before the run fails step_limit.

          ...(isLastStep && !contract
            ? [
                {
                  role: ProviderTransform.isGeminiTarget(model) ? ("user" as const) : ("assistant" as const),
                  content: MAX_STEPS,
                },
              ]
            : []),
        ],
        tools,
        model,
        toolChoice: contract ? structuredToolChoice(model, notice) : undefined,
        structured: contract

structured: contract
? {
reject,
Expand Down
31 changes: 31 additions & 0 deletions packages/cli/test/session/output-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,37 @@ test("step cap without a valid result has an explicit failure", async () => {
expect(result.info.error).toMatchObject({ name: "StructuredOutputError", data: { retries: 0 } })
expect(result.outcomes).toEqual([{ status: "failed", reason: "step_limit", attempts: 1 }])
expect(result.requests).toHaveLength(1)
expect(result.requests[0].tool_choice).toEqual({ type: "function", function: { name: "StructuredOutput" } })
}, 15_000)

// #267: the text-only max-steps prompt forbade StructuredOutput, so a run at
// its step cap lost a result it had already written.
test("the last step forces StructuredOutput and returns the result already written", async () => {
const last = await run(["prose", '{"result":"written"}'], 1, { steps: 2 })
expect(last.requests).toHaveLength(2)
expect(last.requests[1].tool_choice).toEqual({ type: "function", function: { name: "StructuredOutput" } })
expect((last.requests[0].tools as unknown[]).length).toBeGreaterThan(1)
expect((last.requests[1].tools as { function: { name: string } }[]).map((tool) => tool.function.name)).toEqual([
"StructuredOutput",
])
const request = JSON.stringify(last.requests[1])
expect(request).toContain("The step limit is reached")
expect(request).not.toContain("MAXIMUM STEPS REACHED")
expect(last.info.error).toBeUndefined()
expect(last.info.structured).toEqual({ result: "written" })
expect(last.outcomes).toEqual([{ status: "accepted", attempts: 2, value: { result: "written" } }])
}, 15_000)

test("a step-cap model without forced tool choice is still asked for StructuredOutput on its last step", async () => {
const result = await run(['{"result":"written"}'], 0, { steps: 1, anthropic: "claude-sonnet-5-5" })
expect(result.requests.map((request) => request.tool_choice)).toEqual([{ type: "auto" }])
// Auto tool choice cannot enforce the call, so the last step offers no work tool.
expect((result.requests[0].tools as { name: string }[]).map((tool) => tool.name)).toEqual(["StructuredOutput"])
const request = JSON.stringify(result.requests[0])
expect(request).toContain("The step limit is reached")
expect(request).not.toContain("MAXIMUM STEPS REACHED")
expect(result.info.structured).toEqual({ result: "written" })
expect(result.outcomes).toEqual([{ status: "accepted", attempts: 1, value: { result: "written" } }])
}, 15_000)

for (const [name, options, reason] of [
Expand Down
Loading