Repository navigation
feat(ai): OpenAI-compatible endpoint and authenticated proxy availability (L12) - #2829
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
Merging this PR will not alter performance
Comparing Footnotes
|
|
@coderabbitai review |
Action not completed
|
|
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>
* 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>



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/v1401.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.
doGenerateexercises the typed custom fetch extension; callerinclude_usageis preserved.Staging Verification (REQUIRED for all code changes — merge-blocking)
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 modelgpt-5.4-mini, explicit SAM mode and a temporary project-scoped platform-managed null-credential binding. Task01M7M3K1C0HX987DXBPVXSREWB/session519012cd-32e6-4047-9763-21923ec35957 persisted assistant chunksL,12,_CHAT,_OK, which independently concatenate to the expectedL12_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 Trace
apps/api/src/services/admin-settings-mutations.ts:updateAdminSettings→ registeredllm-endpoint-settings.tsdefinitions → 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, diagnosiscomplete, raw SAM loop and Mastra operatorresolveOperatorModel.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
CodeRabbit Review Evidence
CodeRabbit Notes
PR marked ready and
coderabbit-reviewlabel 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.tomledit excluded.Agent Preflight (Required)
Classification
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_providerat06:37:40.440;ai_proxy.responses.forwardmodelgpt-5.4-mini at06:37:58.458; same-workspaceai_proxy.responses.responseHTTP200 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).