Skip to content

plugin: run the loop guard's judge on Apple's on-device model (local_model=fm) - #185

Open
Michael Avrukin (mavrukin) wants to merge 5 commits into
microsoft:mainfrom
mavrukin:feat/apple-fm-local-side-calls
Open

Michael Avrukin (mavrukin) wants to merge 5 commits into
microsoft:mainfrom
mavrukin:feat/apple-fm-local-side-calls

Conversation

@mavrukin

@mavrukin Michael Avrukin (mavrukin) commented Nov 9, 2026 •

Copy link
Copy Markdown

Adds local_model=fm, off by default: the loop guard's judge runs on Apple's Foundation Models CLI (/usr/bin/fm, macOS 27 with Apple Intelligence) instead of claude -p / codex exec / …. It costs 0 tokens, and it still answers while the agent's CLI is signed out. On other systems the setting does nothing.

Rationale, method and every result, including what did not work: #186.

Results

Judge, replayed on 302 real loop-guard decision points. I took 502 public SWE-agent trajectories (nebius/SWE-agent-trajectories) and replayed them through this repo's TurnGuard, default thresholds. Each verdict below comes from llm_stuck_judge, through TE's stock claude_call for Haiku and this PR's fm_call for fm. A redirect is stuck with confidence at or above the threshold.

Judge threshold redirected, resolved runs ↓ redirected, context-exhausted runs redirected, other unresolved AUC tokens / call s / call
Haiku 5.5 (current default) 0.70 26/52 (50%) 115/150 (77%) 53/100 (53%) 0.684 6,981 3.9
Haiku 5.5 0.85 10/52 (19%) 63/150 (42%) 21/100 (21%) 0.684 6,981 3.9
fm, this PR (local_judge_confidence 0.9) 0.90 7/52 (13%) 56/150 (37%) 13/100 (13%) 0.639 0 2.0
fm without the floor 0.70 37/52 (71%) 123/150 (82%) 76/100 (76%) 0.639 0 2.0
fm without a schema (free text) 0.70 4/52 (8%) 13/150 (9%) 2/100 (2%) 0.383 0 1.9
  • fm's confidences come in coarse steps (0.65/0.72/0.85/0.92). At the guard's 0.7 it lets nearly every "stuck" verdict through, hence local_judge_confidence=0.9.
  • At that floor fm sits close to Haiku's own trade-off curve, slightly below it (AUC 0.64 vs 0.68). It redirects fewer resolved runs than Haiku at 0.85, and catches fewer loops.
  • The 302 Haiku calls cost 2.1M effective tokens; the same calls on fm cost 0.
  • Without a schema fm can't tell loops from successes: it redirects 9% of exhausted runs' points and 8% of resolved runs' (AUC 0.38). In 182 of its 283 "not stuck" verdicts, the reason contains a loop phrase such as "repeated identical failures". So the judge always passes its verdict schema (fm respond --schema).

Changes

  • plugin/sidecall.py:
    • local_routes: the settings and the platform only, no subprocess.
    • fm_available: runs /usr/bin/fm by its full path, on macOS only.
    • fm_call: prompt on stdin, greedy decoding, optional JSON schema.
    • local_runner, and a role argument to runner_for.
    • Without fm, the call goes to the agent's CLI. A call fm can't answer is logged and goes there too.
  • plugin/judge.py: the judge and the redirect writer each get their own runner. A local stuck verdict below local_judge_confidence spares the turn. A local call is charged 0 tokens.
  • plugin/controller.py: while the host is paused, PostToolUse picks the judge from the settings alone, so no hook runs fm. The judge's own job checks that the model answers. plugin/fold.py: role-aware runner.
  • plugin/config.py: local_model, local_roles (default judge) and local_judge_confidence (0.9), with TE_* variables.
  • Docs: plugin/README.md (On-device side calls) and one sentence in README.md. The plugin's own text makes no claims of effect.
  • Tests: tests/test_local_model.py (29 tests). fm and the platform are faked, so they run on Linux CI. conftest.py fakes fm like the other side calls.
    • python -m pytest tests experiments/tests: 1,315 passed, 22 skipped on 3.13. tests also passes on 3.10.
    • scripts/dead_code.py reports nothing new compared with main.

After review

main was merged in, with no force push. The conflicts were additions next to #187's per-agent model settings; both are kept. Then two commits:

Not covered

  • Only verified on macOS 27.0.1 on an M2 with Claude Code.
  • The judge comparison uses SWE-agent (Llama) trajectories mapped onto TE's tool names, and a shared envelope rather than a per-repo one. It is not a rerun of the paper's arms; that needs the Linux/Docker harness.
  • In my live Claude Code runs, the fm judge answered, and a paused host still got verdicts. I couldn't produce an organic loop that ended in an fm redirect reaching the model, because Haiku 5.5 stops on its own when tests contradict each other.

🤖 Generated with Claude Code

https://claude.ai/code/session_01UporVpn64UvJqEnurKVwza

…model=fm)

macOS 27 ships Apple's Foundation Models CLI at /usr/bin/fm: a ~3B model on the
Neural Engine and GPU, 4,096-token window, no login or key. With local_model=fm
the side calls local_roles names (default: judge) run on it instead of the
agent's CLI, and are charged 0 tokens.

- sidecall: fm_available, fm_call (prompt on stdin, greedy, optional JSON
  schema via `fm respond --schema`), local_runner, and a role argument to
  runner_for. A local call that fails (no fm, model not ready, prompt over the
  window, no reply) falls back to the agent's CLI, so the guard never loses a
  verdict; while that CLI is paused (signed out), the local judge still answers.
- judge: the judge passes its verdict schema; under it the model returns the
  object every time, where in free text it often wraps or contradicts it.
- local_judge_confidence (default 0.9): a stuck verdict from the local judge
  counts only at this floor. Its confidences come in coarse steps
  (0.65/0.72/0.85/0.92), most above judge_confidence (0.7).
- Settings local_model, local_roles, local_judge_confidence (and TE_* vars);
  documented in plugin/README.md. Off by default.
- tests/test_local_model.py; conftest fakes fm like the other side calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t names

An agent cannot read audio: Claude Code's Read rejects an .m4a or .aiff as
binary before any hook sees the call, so a prompt like "implement what the PM
asks in notes/memo.m4a" sends the agent hunting for a transcriber. With
media=audio, the prompt hook finds the audio paths the prompt names, transcribes
each on the Mac with Apple's Speech framework (SpeechAnalyzer), and adds the
transcripts to that prompt's context, as the repository map is added. No model
call, nothing leaves the machine; transcripts are cached by content hash.

- plugin/media.py: path detection (up to 3 files, 50 MB each), the cache, and
  the helper's build.
- plugin/scripts/te-transcribe.swift: the transcriber, compiled once with
  swiftc into <state root>/bin by `te media setup`, or in the background by the
  first prompt that needs it (that prompt goes without). Without macOS 26+ and
  swiftc the mechanism does nothing and says so once.
- controller.user_prompt adds the block on hosts with prompt context; shadow
  logs it without injecting. `te media [status|setup]`.
- Setting media (off|audio), TE_MEDIA; documented in plugin/README.md. Off by
  default. tests/test_media.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@aaron-jx-li Aaron Li (aaron-jx-li) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the careful write-up in #186. We'd like to take the two options separately.

On-device judge (local_model=fm): we can take it with small changes.

  1. controller.py probes fm available inside the PostToolUse hook while the host is signed out. That runs on every tool call, because each hook is a new process. Please check only the config there.
  2. Please call /usr/bin/fm by its full path and only on macOS, instead of looking it up on PATH.
  3. Please point the config.py docstring at #186 instead of quoting the comparison with Haiku.

Audio transcripts (media=audio): we're not taking this one. The plugin reads finished sessions to change what later sessions cost, and transcribing files at prompt time is outside that. It would also be our first compiled helper, which CI can't build or test. If you'd like to keep it, it could live as a separate plugin. For reference, two bugs we found:

  • With repomap=on, outputs = self._inject_map(...) replaces the transcript on the first prompt.
  • Transcription can take up to 45 s inside a prompt hook whose limit is 20 s, and a killed hook also loses the loop guard's new turn.

Could you split the first commit into its own PR, rebased on main?

# Conflicts:
#	plugin/README.md
#	tokeneconomizer/plugin/config.py
Per review on microsoft#185: transcribing files at prompt time is outside what the
plugin does (it reads finished sessions to change what later sessions
cost), and it would be the first compiled helper, which CI cannot build or
test. It may come back as a separate plugin. Removes plugin/media.py,
plugin/scripts/te-transcribe.swift, `te media`, the `media` setting and its
docs, and tests/test_media.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UporVpn64UvJqEnurKVwza
…on macOS only)

Per review on microsoft#185:
- controller: while the agent's CLI is paused, PostToolUse picks the judge
  from the settings alone (sidecall.local_routes: local_model, local_roles
  and the platform; no subprocess). Each hook is a new process, so the old
  `fm available` probe ran on every tool call. The judge's own job checks
  that the model answers, and with none spares the turn.
- sidecall: FM_CLI is /usr/bin/fm, run by its full path (os.access), never
  looked up on PATH, and only on macOS.
- config: the local_judge_confidence docstring points at microsoft#186 instead of
  quoting the comparison with Haiku.
- plugin/README.md: without fm the call goes to the agent's CLI without an
  errors.log line; only a call fm cannot answer is logged. The setting does
  nothing off macOS.
- tests: local_routes runs no subprocess; a paused host's _judge never
  probes fm (fails on the old code); fm_available runs /usr/bin/fm on macOS
  only and never searches PATH. A `_macos` seam lets them run on Linux CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UporVpn64UvJqEnurKVwza
@mavrukin Michael Avrukin (mavrukin) changed the title plugin: on-device side calls (local_model=fm) and audio transcripts (media=audio) on macOS plugin: run the loop guard's judge on Apple's on-device model (local_model=fm) Nov 10, 2026
@mavrukin

Copy link
Copy Markdown
Author

Thanks for the review. This PR is now just local_model=fm. I merged main into the branch rather than rebasing, so there was no force push, and added two commits:

  • plugin: drop media=audio. Audio is out. We'll consider it as a separate plugin, outside TokenEconomizer. You're right about both bugs:
    • With repomap=on, _inject_map replaced the transcript.
    • Up to 3 files × 15 s of transcription could overrun the prompt hook's 20 s limit, and lose the loop guard's new turn with it.
  • plugin: local judge review fixes:
    1. While the host is paused, controller._judge now reads only the config: sidecall.local_routes checks local_model, local_roles and the platform, with no subprocess. The fm available check runs only in the judge's detached job, and if the model doesn't answer, the turn is spared. A new test runs _judge for a paused host with fm and subprocess.run set to fail if called. It fails on the old code.
    2. /usr/bin/fm by its full path, only on macOS. It's never looked up on PATH.
    3. The config.py docstring points at Apple's on-device model (fm) for TokenEconomizer's side calls and audio prompts: approach, rationale and results #186 instead of quoting the Haiku comparison.

The merge with main only conflicted where #187's per-agent paid_model/effort settings sit next to the new ones; both are kept. tests and experiments/tests pass on 3.13, tests passes on 3.10, and scripts/dead_code.py reports nothing new compared with main. I've updated the PR description to match.

@microsoft-github-policy-service

Copy link
Copy Markdown

Michael Avrukin (@mavrukin) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants