Skip to content

feat(ai): OpenAI-compatible endpoint and authenticated proxy availability (L12) - #2829

Merged
simple-agent-manager[bot] merged 13 commits into
mainfrom
sam/self-host-landing-slice-2svmp5
Nov 17, 2026
Merged

simple-agent-manager[bot] merged 13 commits into
mainfrom
sam/self-host-landing-slice-2svmp5

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

L12 lands the OpenAI-compatible endpoint and AI proxy availability slice from the self-host integration onto current packages/ai-proxy, without self-host runtime code. Admin endpoint settings override Workers AI, task titles, diagnosis and SAM agent inference; unreadable configuration refuses routing rather than sending prompts to a different provider. A complete Cloudflare gateway remains available without extra availability reads; direct upstream requires explicit consent. Availability runs after authentication, preserving unauthenticated /ai/v1 401.

Custom credential URLs are served through guarded passthrough or receive agent-key 404. All three passthrough fetch sites now recheck every redirect; the outbound-fetch baseline drops accordingly. Runtime callback and passthrough preparation splits keep modified source files at 500 lines or less. The change preserves main's measured usage callbacks and adds local monthly spend enforcement using existing counters when there is no addressable gateway; unknown custom model pricing is $0, with token budgets still enforced.

Production read-only recheck, 2026-11-17 02:37 UTC: 0 custom base URL configurations; 0 OpenAI-compatible credentials. No production data changed.

Rule 74 condition: operator-enabled proxy and an addressable gateway, or explicit direct-upstream consent. Signal: account ID AND gateway ID, not gateway ID alone. Caller inventory: AI admission/protocol routes and agent-key/catalog/profile fallback await availability; billing/cost cron/budget reporting use the shared addressability predicate.

Validation

Final Sonar duplication cleanup reuses existing callback identity projections and response helpers, preserving query count/auth order. Final security108tests, performance123tests, title/endpoint41tests and raw SAM/proxy134tests passed; all62 root lint/typecheck/build tasks pass. Non-test source growth is1,064netlines including split overhead.

  • Root lint, typecheck and build: 62 tasks passed on the final implementation.
  • Full root suite executed: all other package suites passed; API collected16,476tests (1,079files). Its62failures were15files loaded before corrections; a fresh combined rerun of all15 passes260/260 (JSONsuccess=true). Current-main analytics checks add62/62pass. Final clean full suite remains enforced by CI.
  • 13 endpoint integration tests: actual admin writer → SQLite → cache → target → guarded upstream; 30 warm calls including concurrent fresh D1 facades require one settings read and zero credential reads, then exactly one refresh at TTL.
  • Combined route authentication 401, custom URL 404 for Claude/Codex/OpenCode, and redirect controls at all three passthrough sites.
  • Actual SDK doGenerate exercises the typed custom fetch extension; caller include_usage is preserved.
  • Title/diagnosis settings use at most one quarter of the inference deadline (100ms of a 400ms test budget).
  • Local monthly cap: one existing counter RPC or at most31 daily KV reads in parallel. Retention reaches month-end plus existing grace; TTL-expiring test covers day-one spend and next-month reset. No cron candidate selection change.
  • Mutation proof: raw fetch bypass produces9 redirect failures; removing custom URL gates produces3 failures; availability before auth produces4 failures. Sources restored; all69 security checks pass.

Staging Verification (REQUIRED for all code changes — merge-blocking)

  • Staging deployment green.
  • Live app verified via Playwright.
  • Dashboard, projects and settings workflows confirmed.
  • Live 401, SAM-mode chat through platform proxy, generated task title, SAM agent and configured private-endpoint refusal verified; settings reset.
  • Infrastructure verification: N/A, no infrastructure changes.
  • Mobile/desktop UI audit: N/A, no app UI changes.

Staging Verification Evidence

Both lease queues checked and queue followed. Exact-head staging workflow 44025781549 passed, including actual Cloudflare deployment and smoke tests. Primary lease expires06:41:42UTC. Playwright verified dashboard/projects/settings/adminsettings with zero page errors and unauthenticated /ai/v1401. A real task generated “Verify SAM platform AI proxy communication and task title generation”. SAM operator turn e90730d0-b2b0-465f-a10f-78a609e3005c completed with L12_SAM_OK. Final Instant OpenAI Codex chat used existing catalog model gpt-5.4-mini, explicit SAM mode and a temporary project-scoped platform-managed null-credential binding. Task01M7M3K1C0HX987DXBPVXSREWB/session519012cd-32e6-4047-9763-21923ec35957 persisted assistant chunks L, 12, _CHAT, _OK, which independently concatenate to the expected L12_CHAT_OK. The scratch harness incorrectly searched a single row and reported failure; inspecting its captured persisted output and asserting concatenation proves the requested response. All five cleanup steps passed: stop Instant session, delete project/profile, delete configuration, restore agent settings, sign out. No VM provisioned by that fixture. Private-endpoint project-agent SSE returned the exact private-network refusal and done, with no model output. All three settings were reset and read-back verified. All settings from the first pass restored, owned temporary task/workspace/project/node deleted.

UI Compliance Checklist

N/A: generic existing Admin Settings UI renders registered definitions; no app UI source changes.

End-to-End Verification

  • Data flow traced from input to outcome.
  • Automated capability test crosses real admin storage and actual SDK boundaries.
  • Existing behavior checked against current main implementation, preserving measured usage callbacks.
  • Required live workflow verification complete.

Data Flow Trace

apps/api/src/services/admin-settings-mutations.ts:updateAdminSettings → registered llm-endpoint-settings.ts definitions → platform settings/encrypted credentials → platform-capabilities.ts:resolveLlmEndpointCapability → llm-chat-target.ts:resolveOpenAICompatibleTarget → packages/ai-proxy/src/llm-chat-target.ts:fetchChatTarget → guarded upstream. Consumers: shared completion helper/title, diagnosis complete, raw SAM loop and Mastra operator resolveOperatorModel.

Workspace callback auth/lifecycle → runtime-agent-key.ts → availability → passthrough or platform inference config; a custom URL that cannot be proxied yields404. AI routes authenticate before availability/admission and use the package billing/accounting boundary.

Untested Gaps

All required live workflows passed. The agent response is stored as streamed assistant chunks; the verification must concatenate those chunks. Lease handoff confirmed06:42UTC: holder=null and L17a is on turn. Release workflow44032825778 was dispatched06:39 but stayed queued until natural expiry06:41:42; obsolete queued run cancelled, no staging mutation after cleanup. The default Codex gpt-4.1 reasoning.effort incompatibility is tracked separately in idea01M7M3H6JGEEB7XKP4PWB2JH0V; final fixture selects existing catalog modelgpt-5.4-mini. Cross-isolate URL/key rotation coherence passes real-storage remote-writer and TTL tests.

Post-Mortem

N/A: feature landing with the explicitly required F26 corrections before release. Integration defects (unbounded settings budget, unused enforced flag, duplicated cap predicate, forced include_usage) are covered by regression tests in this PR.

Specialist Review Evidence

  • All local reviewers completed and findings addressed.
Reviewer Status Outcome
security-auditor PASS Final atomic snapshot and all-corrupt-key503 review passed;13endpoint tests. Prior79tests and69restored mutation controls passed.
cloudflare-specialist PASS Joint atomic encrypted URL/key snapshot, local/remote rotation, single-flight/TTL and month-long KV retention tested.
performance-reviewer PASS Final snapshot reviewed: unconfigured1SELECT/TTL,0credential reads; configured refresh adds1atomic batch(2SELECT); warm0D1. Quarter deadline,31 parallel KV reads or1DO; no web bundle growth.
test-engineer PASS Real storage/SDK/route tests, malformed-key and redirect controls, discriminating mutation proofs, metering retention; no blocking test gap. Live staging remains pending.
task-completion-validator PASS A–F implementation coverage and docs/constitution pass; release evidence still required in staging/CI sections. Source growth 1,064netlines including mechanical splits.

CodeRabbit Review Evidence

  • Requested when PR marked ready.
  • Wait ended on an explicit rate-limit response.
  • No review findings received; rate-limit outcome recorded.

CodeRabbit Notes

PR marked ready and coderabbit-review label applied2026-11-17 03:47UTC, runtime head72e237074. Trusted request workflow44012599347 succeeded. CodeRabbit replied “Action not completed — Review rate limited” at03:47:59UTC (response); no review findings arrived. The required wait ends on that explicit response; no manual retrigger or human-review waiver. Archive-only headb77bb6d36 preserves the reviewed runtime candidate; automatic incremental workflow44012765753 also completed.

Exceptions

Existing SAM-assigned isolated workspace/output branch started at fresh origin/main60a11bb and merged current mainca2498f2b before readiness; no additional worktree required. Task-only main push rejected by GH013 required CI, so task record is retained in this feature PR. No cherry-picks. Pre-existing .codex/config.toml edit excluded.

Agent Preflight (Required)

  • Preflight completed before code changes.

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • docs-sync-change
  • security-sensitive-change
  • public-surface-change
  • ui-change
  • infra-change

External References

Installed @mastra/core1.81 types do not expose a custom fetch hook on model routing. Installed @ai-sdk/openai-compatible2.0.87 types expose the hook; the already-resolved version becomes an explicit direct dependency. Official documentation: https://ai-sdk.dev/providers/openai-compatible-providers (customfetch, includeUsage defaultfalse). Actual SDK execution is tested.

Codebase Impact Analysis

apps/api/ admin registry, L11 capability/cache, AI protocol/admission routes, workspace runtime callbacks, title/diagnosis and SAM loop/operator; packages/ai-proxy/ target, availability, budget/accounting; packages/eslint-plugin-sam/ guarded fetch baseline. No schema/env/VM changes.

Documentation & Specs

www configuration reference and Admin Settings guide updated with endpoint keys, routing, cache/budget policy, direct-upstream consent,404 behavior and cost limitations. No new public endpoint or request contract.

Constitution & Risk Check

Principles X/XI/XIII: reuse existing registry/cache/counters/network guard; configurable endpoint/model/private consent/redirect limit; fail closed when settings cannot be trusted. Credentials never follow an unsafe redirect; configuration and key must be an atomic snapshot. Calendar31 bound is an invariant. No new hardcoded internal service URLs or identifiers.

CI follow-up: initial ready run44012881955 APIshard3 passed357files/5213tests but one account-setup suite failed during import because its schema replacement omitted workspace exports used by the shared callback projection. Reproduced the exact failure locally; commit63e52bf3b makes that fixture a partial schema mock preserving its original three overrides.3/3tests now PASS, independent task-completion review PASS. No runtime code changed; awaiting clean full CI on this new head.

Staging integration refresh: clean merge52548163d incorporates main665ac863f (#2823), retaining additive0256 migration and Cloudflare cost feature. The L12 settings types, registry and endpoint documentation are intact; independent completion spot-check PASS. No manual conflict resolution or L12runtime edit. Revalidating builds and focused integration on this head; current fullCI run44018347462.

Post-main-merge validation passed: root lint/typecheck/build62/62tasks and5focusedtestfiles46/46tests (realendpointstorage/cache,accountsetup,CloudflarecostAPI/dailyjobs/snapshot).

Worker CI follow-up: DO shard7 failed two diagnosis race tests that polled a start audit emitted before model setup. The full Worker pool has no model credentials, so the call could finish before cancellation/deadline mutation. Commit27a2436cc replaces polling with an actual model-POST barrier using a scoped fake gateway target and the real cancellation/reconciler methods. Existing terminal-state, null-result, zero-orphan and single-event assertions remain. Baseline2failed/5passed; restored7/7PASS and scopedlintPASS. Removing the cancellation guard or deadline/statusguards separately makes the corresponding race fail with an orphan diagnosis; production source restored byte-for-byte. Independent completion reviewPASS. Runtime source unchanged.

Final full CI passed on27a2436ccb17a7d34211af58a9ea248df9b9028a: https://github.com/raphaeltm/simple-agent-manager/actions/runs/44021678892 . All API/web/package tests, all7Workershards+requiredaggregate, build/typecheck/lint, quality, smoke andSonar aregreen; currentPR0pending/0failed at05:40UTC. Leasedstagingdeploydispatchedonourturnafterbothinstallchecks; liveproofstillpending.

Final live evidence: endpoint private-network refusal through existing project-agent SSE PASS, settings reset/read-back verified and temporary project deleted. One earlier script sign-out request omitted its JSON body and failed; its browser closed with no saved auth state. Final Instant fixture used the corrected sign-out body and cleanup passed. Preexisting default Codex model compatibility is tracked in idea01M7M3H6JGEEB7XKP4PWB2JH0V; final gpt-5.4-mini conversation succeeded without changing runtime defaults.

Final independent Cloudflare evidence for the successful Instant workspace01M7M3K1XJJK9FNDCFE2MH1FC1: agent_key.ai_proxy_sam_provider at06:37:40.440; ai_proxy.responses.forward modelgpt-5.4-mini at06:37:58.458; same-workspace ai_proxy.responses.response HTTP200 at06:38:00.443. Together with persisted assistant chunk concatenation this proves the complete requested SAM platform proxy conversation. Final task-completion-validator release validation PASS; lease handoff confirmed at06:42UTC (holder=null, next task on turn).

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions
github-actions Bot requested a deployment to staging November 17, 2026 02:50 Abandoned
@codspeed

codspeed Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 5 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing sam/self-host-landing-slice-2svmp5 (27a2436) with main (665ac86)2

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

  2. No successful run was found on main (a3d3246) during the generation of this report, so 665ac86 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@simple-agent-manager
simple-agent-manager Bot marked this pull request as ready for review November 17, 2026 03:46
@simple-agent-manager simple-agent-manager Bot added the coderabbit-review Trigger CodeRabbit review for opt-in PRs label Nov 17, 2026
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sonarqubecloud

Copy link
Copy Markdown

@github-actions
github-actions Bot requested a deployment to staging November 17, 2026 05:41 Abandoned
@simple-agent-manager
simple-agent-manager Bot merged commit a2fb0aa into main Nov 17, 2026
45 of 50 checks passed
simple-agent-manager Bot pushed a commit that referenced this pull request Nov 17, 2026
Main (#2829) made fetchWorkersAIChatCompletion resolve a target first: an
admin OpenAI-compatible endpoint, else the Cloudflare gateway, which now
requires CF_ACCOUNT_ID. The brief keeps the one shared path:

- pass purpose 'taskTitle' explicitly (same short-summary model as titles on
  an admin endpoint; Gemma controls are sent only to Cloudflare targets)
- record "no model route" as unavailable_<reason>, not model_call_failed
- capability test runs the routes with the account/gateway vars a deployment
  has, matches the exact AI Gateway Workers AI URL, and adds a no-route case
  (page renders, brief null, nothing sent); proven red without the
  classification
- admin-settings docs: brief on an admin endpoint and with no model route

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
simple-agent-manager Bot added a commit that referenced this pull request Nov 17, 2026
* feat(overview): generated project brief backend (inbox slice I)

Store one brief per project in D1 (project_briefs), read it in the Overview's
aggregated read with closed-claim filtering in one statement, and refresh it in
the background through the SAM AI Gateway with a fingerprint, minimum interval
and daily cap from admin settings.

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

* test(overview): brief capability, facts and reply validation tests

Real routes for the Overview, inbox answer and MCP ask with the model mocked at the
gateway fetch; real SQL for facts visibility and the read's claim filtering. Fixes
the daily cap admitting the first call of a day when the cap is 0.

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

* feat(web): generated brief on the Project Overview (inbox slice I)

One line under Needs you on a phone (expands in place), above it on desktop;
stale text stays dimmed with its age while a new one is made; links built from
item ids; nothing renders when there is no brief.

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

* docs: Project Overview brief, its admin settings and API field

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

* docs: complete admin settings row for the brief

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

* docs: fix admin settings table row

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

* fix(overview): address security, Cloudflare and UI review of the brief

- Read-time re-check of every named ask with the facts' own visibility rule
  (shared SQL), expiry, and named accounts; credential references never reach
  the page.
- Indexes for the brief's facts (trigger runs by sequence, chats by task),
  failed chats driven from failed tasks, sargable date bounds.
- Abandoned claims count toward the interval; a deadline budget inside
  waitUntil; read-first check gate; projectId in gateway metadata; invisible
  characters stripped from titles.
- Phone: the folded line is one control that opens in place (no accidental
  navigation); constant-height age line; stronger dimmed contrast; new-tab cue.

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

* style: lint fixes

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

* fix(web): keep keyboard focus on the brief's toggle across expand and collapse

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

* test(overview): page responds while the model call is pending; review follow-ups

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

* task: archive inbox slice I task file (staging pending in PR)

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

* fix(overview): address CodeRabbit review of the brief

- Quiet write is bound to the check that saw the quiet facts and may clear an
  abandoned (never a live) generation claim.
- The read re-checks named chats with Running now's own predicate (shared
  overviewChatRunningSql) and named automations with the failure rule itself.
- Accounts ranked by urgency before the cap; capped fact lists marked partial
  for the model (moreNotShown), never counted.
- Web: the brief hides when the latest re-read failed; shortened links keep
  their full accessible name.

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

* refactor(overview): SonarCloud findings on the brief

- Explicit comparators for the fingerprint and account sorts (reliability).
- No literal bidi/zero-width characters in tests (security rating).
- Parser split into small checks, number words as a word set, no
  backtracking regexes; refresh generation step extracted; lookup maps and
  helpers instead of nested ternaries; read-only props.

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

* chore(migrations): renumber project_briefs to 0255

Three open PRs added 0253 (#2811 Insights U, #2818 Inbox H1, this one).
Agreed order: 0253 Insights U, 0254 Inbox H1, 0255 this.

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

* fix(overview): space the brief's words around item names

The first live staging brief showed the model writing text parts without
spaces around refs ('Deciding on the' + ref + 'is required'). The parser now
puts one space at every text/ref boundary that has none, except before
punctuation that attaches left. Test uses the real staging reply shape.

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

* fix(overview-brief): route through the L12 model target resolver

Main (#2829) made fetchWorkersAIChatCompletion resolve a target first: an
admin OpenAI-compatible endpoint, else the Cloudflare gateway, which now
requires CF_ACCOUNT_ID. The brief keeps the one shared path:

- pass purpose 'taskTitle' explicitly (same short-summary model as titles on
  an admin endpoint; Gemma controls are sent only to Cloudflare targets)
- record "no model route" as unavailable_<reason>, not model_call_failed
- capability test runs the routes with the account/gateway vars a deployment
  has, matches the exact AI Gateway Workers AI URL, and adds a no-route case
  (page renders, brief null, nothing sent); proven red without the
  classification
- admin-settings docs: brief on an admin endpoint and with no model route

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

* fix(overview-brief): only complete sentences reach the page

Staging (2026-11-17, Gemma 4 26B) wrote "The process for <chat>": a
sentence that stops at its link, with no verb and no full stop.

- prompt: each sentence is complete, with a subject and a verb; the ref is a
  noun inside it; the last part is text ending in a full stop (with example)
- parser: drop a sentence whose last part is not text ending in . ! or ?
  (proven: disabling the rule turns exactly the two fragment tests red)
- rejection fixtures for URL/markup/link/invisible characters now end in a
  full stop, so each is still rejected for its own reason

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

---------

Co-authored-by: Raphaël Titsworth-Morin <raphael@raphaeltm.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch was successfully deployed

No deployments
staging — 27a2436c Deployed Nov 17, 2026 by simple-agent-manager[bot] via queue #3090
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coderabbit-review Trigger CodeRabbit review for opt-in PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant