Repository navigation
refresh: merge upstream dev d61cca122d + Claude usage credits (2.100.0-vadymhimself.3) - #48
Open
vadymhimself wants to merge 86 commits into
Open
vadymhimself wants to merge 86 commits into
vadymhimself wants to merge 86 commits into
Conversation
) * fix(windows): exclude foreign users from stop candidates Use creation-bound owner SID evidence to exclude confirmed foreign user processes from checked and guarded stop candidates without expanding terminate authority. Keep unknown and service identities conservative, retain ancestry rows, and cover stop and confirmation regressions. * test(windows): exercise the live owner snapshot pipeline Make current-owner lookup failure explicitly retain unknown ownership and add a Windows-only test of the bounded real PowerShell/CIM snapshot using an owned harmless cmd wrapper. * fix(windows): bound optional snapshot owner enrichment * test(windows): cover owner lookup exhausting snapshot budget Advance the controlled clock inside the owner-query mock and require zero refresh calls, unknown ownership, and every process row retained. The available-budget case now verifies the exact 32-candidate cap. Linux Bun 1.4.4: evidence tests 12 pass, 6 Windows-only skips; typecheck and privacy scan pass. The PowerShell cases were not run. * fix(windows): require owner proof before checked service stop * fix(windows): bind checked stops to verified task instances Read the Task Scheduler definition losslessly and keep the running instance objects through the ownership check and stop. Prioritize this installation's wrapper paths in the bounded owner scan and clarify the unconfirmed-exit guidance on ARM64. * fix(windows): close checked task stop gaps Reauthorize the updater after validating Scheduler instance proof and honor both stop deadlines before dispatch. Preserve a typed refusal. Accept an owned disabled task in stop proof and treat queued tasks as active during final confirmation. * fix(windows): make the optional account-name fallback explicit --------- Co-authored-by: JUN <jun@lidgeai.com>
* test(server): budget image and search relay fixtures * test(server): tighten in-process timeouts and surface early image failures
…per-turn (lidge-jun#8549) * feat(jev): decide effort on every pinned turn with sessionPin.effort per-turn * fix(jev): skip client-owned effort and retain failed pin decision telemetry * fix(cli): label pinned JEV requests without implying no decision * fix(gui): retain JEV pin effort in the classic TTL editor * docs(jev): mirror per-turn pin examples in Spanish * fix(jev): revalidate pinned effort decisions and preserve live pin updates * fix(jev): attribute per-turn pins to the final selection * Retain JEV model usage from unsuccessful terminals --------- Co-authored-by: JUN <jun@lidgeai.com>
…idge-jun#8906) * fix(update): keep the configured pnpm store during update planning * test(update): isolate pnpm store fixture from the caller environment --------- Co-authored-by: Oliver Mee <102673257+oliver-mee@users.noreply.github.com>
* feat(providers): add LLMTR to the free directory Seed the six standing zero-price chat models, keep live discovery of the paid catalog, and record the daily-quota bounds. Checked 2026-10-29. * fix(providers): filter LLMTR live discovery to chat models A directory row can carry a discovery filter for its exact fixed key destination. LLMTR keeps rows that list CHAT_COMPLETIONS and /v1/chat/completions, and the note no longer calls promotional or bring-your-own-key rows paid. * fix(providers): make LLMTR an inert reference row in the free directory Drop the base URL, seeded models, hybrid discovery and the directory discovery fallthrough in model-discovery.ts, so the row routes nothing and follows the reference-row pattern used for Perch. This also removes the agnes/agnes-3.0-flash and agnes/agnes-2.5-flash ids, which are no longer in the live catalog. The test now pins the row to reference only. The layout fixture entry for the test file moves to its own line so it no longer overlaps changes on dev. --------- Co-authored-by: knowhy <194148385+knowhycodata@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com>
…8825) * fix(pool): report inert on the unified pool-settings read /api/pool/settings 응답과 ocx account pool 출력에 inert를 넣는다. 일반 OAuth 풀은 pool.kernel이 꺼져 있으면 strategy·stickyLimit·autoSwitchThreshold를 저장만 하고 적용하지 않는데, 공통 응답에는 이 표시가 빠져 있었다. 옛 /api/oauth/accounts/pool 응답과 CLI 스키마(account-policy-dto)는 이미 inert를 다룬다. Codex·Anthropic 선택기는 kernel과 무관하게 설정을 쓰므로 false로 답한다. * docs(pool): document the unified inert marker in Spanish and in the management-API structure doc * docs(i18n): mirror the pool-settings inert note in Korean and Russian 영어 management-api.md의 /api/pool/settings 행에 넣은 inert 설명을, 같은 행을 영어와 함께 고쳐 온 ko·ru 번역본에도 넣는다(105313877과 같은 범위). es는 8dbc507bb에서 반영됐다. --------- Co-authored-by: yazzang-homelab <278053055+yazzang-homelab@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com> Co-authored-by: root <root@pve3.local>
…ervice ban without opt-in (lidge-jun#8826) * fix(oauth): pause a Cloud Code Assist account on its first Terms of Service ban without opt-in * fix(oauth): grant the Cloud Code Assist ban default only to first-party Google sends 메인테이너 보안 리뷰 P1 반영. opt-in 없는 기본 정책은 adapter·googleMode만 보고 켜져서, baseUrl을 바꾼 중계 서버가 돌려준 거절도 믿고 계정을 멈출 수 있었다. 이제 기본 정책은 authMode oauth이고 baseUrl이 Google 자체 Cloud Code Assist 호스트(isCanonicalAntigravityUrl: https, 기본 포트, cloudcode-pa 또는 daily-cloudcode-pa)일 때만 성립한다. 관찰자는 보내는 공급자와 최종 전송 목적지(physical 보고에 destination 추가)도 같은 허용 목록으로 확인한다. 명시적 enabled: true는 사용자 지정 엔드포인트에서도 그대로 동작한다. --------- Co-authored-by: yazzang-homelab <278053055+yazzang-homelab@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com> Co-authored-by: root <root@pve3.local>
…un#8905) * test: isolate updater and client fixtures from host installs * test(codex): pin the fixture Node interpreter for npm and process scans
* fix(opencode): select the Connect protocol per model * test(opencode): expect the per-model Chat override on a direct Chat route; document the perModel matrix exception --------- Co-authored-by: JUN <jun@lidgeai.com>
lidge-jun#8897) * fix(adapters): replay a Google 429 only when it carries retry evidence Cloud Code Assist answers a request-shape or policy rejection with a bare 429 RESOURCE_EXHAUSTED: no Retry-After, no details[], no rate-limit wording. The Google transient ladder replayed the same bytes three times per turn and got the same refusal three times, so a caller saw sendCount: 3 and rate_limit_exceeded for a request that no replay could clear, on an account whose quota was untouched. Decide replayability from evidence instead of the status code: a Retry-After header, a RetryInfo.retryDelay/quotaResetDelay detail, a transient-rate-limit phrase, or a structured ErrorInfo.reason. Hard quota exhaustion keeps its existing non-retry path and is classified first. Observed shapes behind the split (same account, minutes apart): - capacity: RESOURCE_EXHAUSTED with details[].reason=RATE_LIMIT_EXCEEDED; - rejection: RESOURCE_EXHAUSTED, message 'Resource has been exhausted (e.g. check quota).', no details, no Retry-After. Tests: bun test tests/adapters/google/google-vertex-http.test.ts bun test tests/adapters/google/google-errors.test.ts bun test tests/server/server-google-antigravity-oauth-429-budget.test.ts (100 pass, 0 fail); bun run typecheck; bun run structure:check; bun run privacy:scan. * fix(adapters): address review on the Google 429 evidence gate - Read one envelope shape everywhere: googleErrorEnvelope unwraps error[0] so the reason path agrees with the retry-delay extractor. - Only a detail typed google.rpc.ErrorInfo speaks for the rate-limit verdict; a foreign @type may carry an unrelated field named reason. - An explicit retryDelay/quotaResetDelay of '0s' is evidence (the provider named a wait) even though it is not a caller-facing Retry-After. - Match message-level wording against the decoded error.message/status, never the whole body: a BadRequest field violation that quotes 'rate limit' describes a request-shape verdict and must not authorize a replay. - Keep Google's documented pay-as-you-go wording ('Please try again later') retryable via a needle scoped to the evidence predicate only, so quota classification is unchanged. - inventory.md states the contract precisely: recognized ErrorInfo reason, bounded display-safe body read, explicit 0s. * fix(adapters): compare detail @type by full last segment - detailTypeMatches compares the final ProtoJSON path segment whole, so a foreign 'relay.notgoogle.rpc.ErrorInfo' no longer authorizes a replay and the canonical google.rpc.ErrorInfo still does. - A wait is only evidence from the message that owns it: retryDelay from RetryInfo, quotaResetDelay from ErrorInfo.metadata. A foreign detail that spells either field states no wait the provider will honor. - inventory.md distinguishes the JSON wording check (error.message/status) from the plain-text fallback (whole body). - Tests: foreign types whose last segment is ErrorInfo, a retryDelay on a foreign detail, and a plain-text 429. * fix(adapters): validate Google 429 retry evidence Require a declared detail type to match its owning message and evaluate each retry duration independently. Use the retry scheduler's Retry-After parser to decide whether the header permits a replay. Pin physical send counts and Retry-After timing with adapter tests. Document the bounded body evidence and the user-visible retry behavior. --------- Co-authored-by: naipi11 <naipi122899@gmail.com> Co-authored-by: JUN <jun@lidgeai.com>
…rage) account (lidge-jun#8901) * Explain xAI OAuth Legacy privacy mode refusals Recognize the exact Grok Build privacy settings marker on HTTP 403 and show fixed guidance in inference, discovery and quota diagnostics. Preserve credential health and cover the OAuth failure paths with regression tests. * fix(xai): allow eligible combo fallback after a privacy refusal * fix(xai): classify privacy refusals across the inference body limit * fix(catalog): distinguish xAI privacy refusals in warning deduplication * docs(grok): restore the Spanish manual recipe anchor * fix(xai): preserve privacy guidance after a reset replacement Classify the bounded Grok OAuth replacement error after cancellation handling and keep the fixed 403 non-replayable on both Responses paths. * fix(responses): keep combo recovery ahead of xAI privacy guidance * fix(catalog): order xAI discovery publications by observation * fix(responses): retain exact no-retry header on privacy reset errors
…ota (lidge-jun#8888) * feat(codex): support Business/Enterprise group-based spend_control quota OpenAI Business/Enterprise accounts (/backend-api/wham/usage) can omit rate_limit and credits.balance while reporting monthly allowance and remaining credits under spend_control.individual_limit (source: group_based_spend_controls). Extract that limit into monthlyPercent, monthlyResetAt, monthlyIsPrimaryWindow, and credits.balance across parseUsageQuota, parseMainPolicyUsageQuota, and isValidWhamHistoryObservation. * fix(codex): do not publish an invalid spend_control used_percent as a monthly reading parseUsageQuota clamped an out-of-range individual_limit.used_percent (for example -1) to 0 and published it as monthlyPercent, which overwrote a stored exhausted reading. Validate the raw value with isInvalidPolicyUsagePercent first, matching the policy and history validators, so an invalid reading leaves the monthly tuple unset and the merge carries the stored one forward. Addresses the CodeRabbit finding on lidge-jun#8888. * fix(codex): reject malformed group spend percentages Keep invalid group readings out of monthly snapshots and policy evidence. Only an absent reading can use the reached-control exhaustion fallback. * fix(codex): expose group credit balances on account rows Normalize WHAM credit balances for quota snapshots and both account probes, then document the Business and Enterprise quota behavior. --------- Co-authored-by: JUN <jun@lidgeai.com>
…-jun#8807) * fix(advisor): enforce effective tool choice before consultation * fix(advisor): preserve buffered worker usage on tool-choice refusal * test: isolate excerpt masking complexity from SSE serialization * fix(advisor): honor caller tool selector identity * fix(advisor): preserve explicitly selected hosted Messages Advisor * fix(advisor): validate hosted choices before dispatch * fix(advisor): continue fallback past incompatible hosted choices * fix(advisor): preserve caller tool choice in delivery guards * fix(advisor): authorize resolved caller tool identities * fix(advisor): bind qualified tool choices to their namespace * fix(advisor): admit qualified synthetic root tool choices --------- Co-authored-by: JUN <jun@lidgeai.com>
…d API setting (lidge-jun#8860) * feat(claude): expose native passthrough in the Claude Code settings API and CLI claudeCode.nativePassthrough could only be changed by hand-editing config. With it on (the default), bare claude-*/anthropic* requests from Claude Code go straight to Anthropic with the caller's own sk-ant-* credential, so an enabled Anthropic account pool never sees Claude Code's main traffic. - GET /api/claude-code reports nativePassthrough (false only when stored false); PUT accepts a boolean, stores false and deletes the key for true, the same default-on shape as autoContext and injectAgents. - ocx claude config set --native-passthrough <on|off>; status prints the nativePassthrough line through the generic summary. - Capability metadata and the generated ocx skill surface list the flag. Routing semantics are unchanged. The setting is not a system-env input: wantsNativePassthrough reads the live config per request, the PUT already re-syncs generated agents, and launch context windows follow from the next ocx claude launch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(gui): add a native Claude passthrough toggle to the Claude Code settings The Claude Code settings card gets one Save-bar toggle beside the auth mode. Its hint says what each position does: on (default) sends Claude models to Anthropic with Claude Code's own login; off routes them through OpenCodex's Anthropic accounts so the Claude account pool applies; running Claude Code sessions need a relaunch. A state cached by an older page, or read from an older proxy, has no field and reads as on. Strings are added to every locale. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(claude-code): document the native passthrough switch and its effect on the account pool The passthrough section in every locale now names the CLI flag and the dashboard toggle, says that with passthrough off Claude models are routed through the configured Anthropic accounts (so the account pool applies), and that running sessions need a relaunch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(claude-code): state when passthrough and the account pool apply CodeRabbit findings on lidge-jun#8860. The toggle copy and the guide said Claude models go to Anthropic with Claude Code's login when on, and that the account pool applies when off. Both overstated: - Passthrough serves only a bare Claude id (no alias or modelMap hit) that arrives with Claude Code's own Anthropic credential; anything else is routed even with the setting on. - With it off, the configured route picks the provider (a modelMap entry to another provider's model goes there either way). Stored Anthropic accounts serve Anthropic OAuth routes, a second account adds 429 failover, and the proactive pool needs anthropicAccountPool.enabled. Updated the dashboard description in all 11 locales and the guide paragraph in all 9. Locale guides link to their own translated pool heading where one exists and name the pool without a link where the section is not translated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(gui): move the native passthrough switch under the Claude account pool The switch decides whether Claude Code's own traffic can reach the Anthropic account pool at all, so it now sits directly below the pool card in Providers → Anthropic Claude → Accounts (anthropic instance) instead of on the Claude Code page. ClaudeNativePassthroughSetting reads GET /api/claude-code and saves only { nativePassthrough } through the existing patch, immediately, like the pool card. The Claude Code page no longer carries the field, so its full-form Save cannot overwrite a value changed here. Adds a load-failure string in all 11 locales, moves the GUI tests to the new component, and points the guide (9 locales) and the structure doc at the new location. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(gui): show the passthrough switch for API-key Anthropic and retry a failed load Review follow-ups on the moved switch: - The switch was rendered only for an OAuth Anthropic row, but the setting applies to Claude Code whatever the Anthropic row's auth mode. An API-key anthropic row now shows it too (there is no pool card there). - GET /api/claude-code gathers the catalog and can answer 503 while it is busy. A failed load now offers Retry instead of leaving the switch disabled until the tab is reopened. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(claude-code): state routing precedence when passthrough is off CodeRabbit follow-up on lidge-jun#8860. With passthrough off, an unmapped bare Claude id is claimed first by an enabled `anthropic` or `anthropic-*` provider (routeByKnownModelPattern in src/router.ts), then by the usual order: a provider listing the model, an alias, the default provider. The copy said "the configured route decides" and tied stored Anthropic accounts and the pool to every route. The dashboard hint (11 locales) and the guide (9 locales) now state that precedence, that stored Anthropic accounts serve Anthropic OAuth routes, and that the pool applies to those routes when enabled. Also drops a stale structure sentence that still placed the switch on the Claude Code page behind its Save bar. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(claude-code): give the full routing order when passthrough is off CodeRabbit follow-up on lidge-jun#8860. An enabled provider whose `defaultModel` is the requested Claude id wins before the `anthropic`/`anthropic-*` name pattern (src/router.ts: configured-default-model, then routeByKnownModelPattern, then configured-model-list, alias, default provider). The guide (9 locales) now lists that order. The dashboard hint (11 locales) no longer enumerates routing steps at all: it says the models follow OpenCodex's normal model routing, and that stored accounts and the pool apply when that routing picks an Anthropic OAuth provider. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(claude): require confirmed native passthrough saves * fix(claude): preflight passthrough writes and refresh ambiguous saves --------- Co-authored-by: seongwoong <seongwoong@mobilint.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JUN <jun@lidgeai.com>
…8598) * feat(codex): add codexAuthMethod device-only login policy Operators of a headless hub can set codexAuthMethod to "device-only" so every Codex pool add and reauthentication uses the device-code grant, including the dashboard's Re-authenticate action and ocx account login openai, which previously started a localhost browser login. The login response reports authMethod so the dashboard and CLI say the proxy requires it and wait the full device-grant window. Absent or "auto" keeps the existing behavior. Closes lidge-jun#8082 * fix(cli): say a restart is needed after setting codexAuthMethod * fix(gui): say the device-only notice covers Codex pool accounts * docs(es): mirror the codexAuthMethod setting and device-only login note * test(codex): read the device-only locale sources through repoPath * fix(cli): refuse a JSON wait or --code when the proxy imposes device-only login * fix(gui): scope the Chinese device-only notice to the login method, not the accounts * test(layout): register the device-only test in the codex-collision shard to keep layout.json under its cap * fix(cli): refuse --code - under device-only before reading stdin; document the pool-login policy * fix(config): keep active Codex login policy until restart * fix(auth): bind Codex pool publication to its own OAuth flow * fix(cli): cancel abandoned Codex code input and report invalid policy * fix(cli): limit config validation to the fixed policy warning * fix(codex): retain the exact OAuth outcome for a pending pool login * docs(codex): localize browser cancellation and device policy * fix(cli): bound Codex login cleanup and report its flow ID * test(codex-auth): register the cancel-ownership fixture under its own state-store name --------- Co-authored-by: JUN <jun@lidgeai.com>
…in the update lint (lidge-jun#8917)
…d-stop helper test (lidge-jun#8921)
…lidge-jun#8815) * fix(anthropic): withhold hosted advisor under captured spend ceilings * test: align spend fixtures with authenticated target binding * fix(advisor): preserve main accounting during hosted ceiling checks * fix: preserve hosted Advisor ceilings across budget holders Share a read-only numeric ceiling snapshot for legacy and observerless budget holders, including derived scopes, while preserving authoritative captured answers and ordinary main-model accounting. Normalize a withheld Advisor's named choice only after the final tool catalog is known. Preserve client and proxy Advisor ownership, rebuild delivery maps with retention accounting, and cover both supported forced-choice model behaviors. Add focused budget, wire, and compatibility regressions and synchronize the owning contracts and user guidance. * fix(advisor): recheck captured spend policy after credential changes * fix(advisor): apply captured ceiling to the effective provider wire Pass each physical builder's resolved provider to the hosted Advisor guard and use the initial resolved provider before optional planning. Preserve captured spend targets and monotonic withholding across credential replacements. Cover proactive selection, aliases, model wire overrides and pinned-wire key rotation, and clarify the per-send contract. * fix(advisor): retain completed web replay when withholding hosted advice Remove only Advisor call/result blocks from already validated replay runs. Preserve other completed exchanges, their original anchor/order and existing destination restrictions. Cover interleaved search/fetch replay, proxy and spend withholding, unlimited/gateway controls, and source-container immutability. * docs(advisor): clarify optional forwarding and keep the spend contract within its budget * Keep hosted Advisor spend admission across fallback * Bind hosted Advisor spend to the serialized Anthropic key Use the captured pool and root ceilings before the default tracker starts accounting. * Fail closed on ambiguous hosted Advisor credentials * Bind hosted Advisor to the post-rewrite credential * Count hosted Advisor workflow sends at physical dispatch * Defer hosted Advisor continuation accounting until dispatch --------- Co-authored-by: JUN <jun@lidgeai.com>
…#8803) * fix(link): restore Child file routes before shutdown Fence all Link stop paths before restoring link-owned file routes and releasing the listener. Keep the listener on cleanup refusal, preserve explicit parent stops across restart rollback, and require an attested fence capability before stopping an older runtime. * test(client): align Link stop fixture and Spanish lifecycle guidance * ci: refresh shard duration weights from completed Linux jobs * ci: pin reviewed shard timings in release evidence policy * fix(link): retain listeners when native restoration refuses Keep the stopped sync fence and bound listener for native Codex/Grok refusal after file cleanup. Treat configured port 0 as ephemeral during stopped-client preflight while still requiring a concrete, proven-dead recorded endpoint. Add real listener and CLI regressions for both reviewed shutdown boundaries, and synchronize the lifecycle contracts and guides. * fix(link): validate native teardown owners before shutdown * fix(link): allow a later recycle after canceling its timer * Isolate Desktop stop diagnostics in parent fixture * Bind Link Child shutdown to the serving connection and stop owner * Require native Hub stop ownership evidence * Keep stop guard helpers in the teardown module * Keep file cleanup fixture independent of host Codex discovery * fix(link): fence Child stop to the attested process Classify tracked and discovered runtimes before stopping their managers. Recheck the Child's creation identity at termination, including escalation, and use a process handle where supported. Keep restart rollback behind an active parent stop and report surviving Link file-route evidence. Give operators an ordered transition from legacy Children and isolate the stop fixtures from host Codex discovery and service ownership. * test(link): isolate all stop fixtures from Codex discovery Keep synchronous and asynchronous catalog probes inside the fixture. The host Node launcher was creating runtime installations in temporary homes after fixture exit, adding unbounded work to suite cleanup. * fix(link): require verified Child stop and recovery evidence * test(link): cover mandatory stop receipts and preserve Hub race checks * fix(link): treat malformed stop-owner evidence as unverified * fix(link): verify stop handoff evidence and retry contended fences Require a valid process creation identity and keep ambiguous argv observations unverified. Bind the parent-verified receipt bytes for other endpoints to the current teardown claim. Refresh the restore guard on each config-lock attempt. Reuse the bounded retry for rollback publication and activate observers once the record is published. Require literal absence of systemd records before admitting offline cleanup. * fix(link): close refused rollbacks and preserve standalone stop Close an unpublished rollback listener synchronously on lock contention. Keep Link stop fencing and require client evidence before invoking preflight. Restore standalone manager, endpoint, and update teardown behavior. * fix(link): refuse stop for unclassified live runtime Require positive standalone health or a manager bound to the tracked PID before the ordinary stop path can terminate a process when Link evidence is missing. A missed role probe cannot authorize a manager stop or the numeric TERM/KILL fallback. * fix(stop): accept verified standalone runtime records Use the tracked PID's recorded creation identity when health attestation is unavailable. For older records, require matching start argv, process home and listener ownership before taking the ordinary standalone path. * fix(stop): verify legacy Windows and wildcard listeners Use Windows owner SID, start arguments and exact listener ownership when legacy records lack a creation stamp and the process environment cannot be read through CIM. Verify Linux wildcard bindings through their own socket inodes while retaining exact loopback checks. * fix(stop): verify relative homes for legacy foreground runtimes * fix(stop): bind legacy Unix stop to the home directory identity Accept alternate paths to the same home and revalidate the pinned directory before stopping a service manager or signaling the recorded process. * fix(cli): preserve sibling stop ownership Refuse conflicting Link and guarded service ownership before a sibling can mutate shared state. Keep the sibling receipt guard independent of Link preflight, and update the affected CLI source oracles. * fix(cli): stop attested native Link siblings Verify the serving Link and process incarnation, then stop only the sibling process. Leave shared routing, teardown receipts and the service manager untouched, and continue refusing conflicting ownership. * fix(cli): accept the Link sibling shutdown marker after TERM * test(link): reap stop fixture owners and order recovery timers * test(ci): isolate the Link Child stop suite in a bounded lane * fix(ci): honor per-file serial deadlines in hosted batches * test(ci): split and rebalance Link stop tests Keep Link stop, recovery, and sibling teardown tests in separate fresh processes. Move the cases intact and use the existing batch deadlines. Refresh the Linux weights for the split files and stale measurements from PR lidge-jun#8803's hosted logs. Spread the split across three shards and account for expensive files the previous table assigned the median weight. --------- Co-authored-by: JUN <jun@lidgeai.com>
…indow is present (lidge-jun#8889) * feat(anthropic): support Enterprise plan resolution and extra_usage monthly quota Anthropic Enterprise accounts return rate_limit_tier: 'default_claude_ai' alongside organization_type: 'claude_enterprise' on /api/oauth/profile, and omit 5h/weekly windows on /api/oauth/usage while reporting monthly usage under extra_usage. Prefer known canonical tiers before falling back to unfamiliar raw tier strings, and extract extra_usage into monthlyPercent/monthlyResetAt when standard 5h/weekly/custom windows are absent. * feat(anthropic): report monthly usage from extra_usage when no plan window is present Usage-based Enterprise seats return five_hour/seven_day as null and limits as [], and report credit usage only under extra_usage. The probe discarded that as response_unusable, and the advisory projection published no window, so an exhausted seat ranked as unknown. When no plan window exists and extra_usage.is_enabled is true, report monthlyPercent from utilization (or used_credits over monthly_limit) in both the display and advisory projections. No reset time is read or invented: the percentage follows the credit balance and falls when credits reset. Accounts that report any plan window are unchanged. This drops the earlier plan-label change, so the pull request no longer touches src/oauth. * fix(anthropic): treat an inactive scoped row as a reported plan window for the monthly reading anthropicExtraUsageMonthlyPercent only checked the active buckets, so an inactive weekly_scoped row (display-only) next to an enabled extra_usage still produced a monthly bar, contradicting the documented rule that any reported plan window keeps current behavior. Suppress the reading when either the active or the display-only buckets are non-empty, in both the display and advisory projections. Addresses the CodeRabbit finding on lidge-jun#8889. * Fix Anthropic monthly quota fallback transitions * fix(anthropic): retire stale monthly quota evidence * fix(anthropic): persist monthly quota retirement across probes * fix(anthropic): report unusable quota while retiring monthly fallback * docs(es): sync OpenCode per-model protocol guidance * fix(quota): preserve Anthropic retirement diagnostics on refresh --------- Co-authored-by: JUN <jun@lidgeai.com>
* fix(claude): apply per-model compact windows at launch Generate session-only modelSettings from the live context-window map so model switches use a compact window below each smaller model's input limit. Preserve the common default for larger models without writing Claude Code settings files. Keep explicit compact environment variables, --settings and --autocompact authoritative. Leave native fallback and Desktop launch paths unchanged. * fix(claude): limit compact settings to pickable selectors * fix(claude): bound compact settings command-line size * docs(claude): clarify compact settings precedence and fallback * fix(claude): budget escaped Windows launcher arguments * fix(claude): preserve Remote Control launch arguments * fix(claude): preserve Remote Control argv after global options * docs(es): translate OpenCode per-model protocol guidance * fix(claude): skip compact settings on Remote Control tokens --------- Co-authored-by: JUN <jun@lidgeai.com>
…idge-jun#8773) * feat(reasoning): opt in to Chat raw reasoning on the summary channel * test(reasoning): allow cold-start response integration * docs(reasoning): record PR validation status * docs(reasoning): document rawReasoningAsSummary side effect and Spanish parity Address the maintainer review on lidge-jun#8773: - Spanish providers table now carries the rawReasoningAsSummary row after hideRawReasoning, its showThinkingSummary exception clause, and both display fields in the save and PATCH sentences. - English rawReasoningAsSummary row names the omitted-summary side effect: with the option on, provider-authored summaries on that route are visible too, so the expandable surface is not raw-only. - English "What a provider save keeps" and the PATCH paragraph name both hideRawReasoning and rawReasoningAsSummary. * ci: re-run PR gates after merge * Fix raw reasoning replay and negotiated display policy --------- Co-authored-by: reisen-ww <reisen-ww@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com>
…jun#8926) * test(windows): give the PowerShell-backed proofs the spawn budget * test(windows): bound each PowerShell scenario group by a shared 60 s window * test(windows): run the owner-enrichment budgets in one bounded test
…idge-jun#8924) * fix(link): retry owned reverse forwards and report relay degradation * fix(link): report pending forward retries and relay failures Keep multi-route retries in their current round while exposing the confirmed forward conflict and scheduled retry in tunnel diagnostics. Count relay cancellations separately and apply the delivery evidence window to relay authentication. Document relayHealth in the generated capability guide. * fix(link): count upstream read errors after streaming starts
…idge-jun#8803)" (lidge-jun#8930) This reverts commit aa0bb80. The dev batch run 44421764707 at 4f757e9 is red on windows 7-10/14: the parent/Link stop and recovery tests added by lidge-jun#8803 hit their 15 s fixture deadline with exit 137, which means the `ocx stop` child is still running on Windows. Revert to restore the last green stop path (run 44386662799 at c38d6ee) while the Windows behaviour is fixed forward in a new PR.
* fix(messages): make fragmented model echo progress in linear time * fix(messages): refresh the stall deadline on raw body bytes * Frame native Messages model echo across CRLF chunks * Fail native Messages idle tests when the request settles early * Complete native Messages model echo on bare CR * fix(messages): honor SSE data and scan boundaries * fix(messages): bound native model echo and retain SSE controls * fix(messages): retain canonical framing for error-tagged starts * fix(messages): preserve SSE boundaries and effective event on model echo * test(messages): assert retained event fields in differential replay * test(messages): retain the bare-CR data field in expected bytes --------- Co-authored-by: JUN <jun@lidgeai.com>
…n#7308) (lidge-jun#8927) * fix(anthropic): carry opt-in one-shot image-413 recovery Summarize older image-bearing units and resend once within the original request budget. Fence both sends to the refusing credential and Messages destination. Co-authored-by: S0RYUASUKA <64878945+S0RYUASUKA@users.noreply.github.com> * fix(anthropic): enforce image-context recovery boundaries Reserve the summary and resend separately before their physical sends. Disable summary reasoning and verify its serialized output ceiling. Preserve instructions by refusing cuts that would replace them. Co-authored-by: S0RYUASUKA <64878945+S0RYUASUKA@users.noreply.github.com> * fix(anthropic): settle and keep alive image-context recovery Tie summary and resend usage to their physical spend receipts. Preserve client cancellation during refusal reads and drive the live media watchdog while recovery is pending. Suppress the first-party Opus adaptive-thinking default only on the recovery summary. Co-authored-by: S0RYUASUKA <64878945+S0RYUASUKA@users.noreply.github.com> * fix(responses): settle continuation usage on its own send Bind raw adapter usage to the dispatch receipt before terminal aggregation. Preserve the final-usage fallback only when other known spend cannot be included in it. Co-authored-by: S0RYUASUKA <64878945+S0RYUASUKA@users.noreply.github.com> * fix(responses): scope per-send spend to image-context recovery Settle image recovery receipts from raw success or HTTP-failure usage and retain estimates when usage is unknown. Keep the ordinary continuation journal compatible with dev. Co-authored-by: S0RYUASUKA <64878945+S0RYUASUKA@users.noreply.github.com> --------- Co-authored-by: S0RYUASUKA <64878945+S0RYUASUKA@users.noreply.github.com>
…er (lidge-jun#8794) * feat(server): record request peer scope and the subagent-fallback fact Adds two request facts that a local-only, interactive-only provider needs and that a client cannot forge: - src/lib/request-peer-scope.ts: an AsyncLocalStorage snapshot {local} fixed per HTTP request from the listener and the kernel-observed peer address, and per WebSocket socket at its upgrade (Remote Link sockets are never local). No snapshot means not local. - IncomingMeta.subagentFallback: set only where subagent fallback actually moves the route (both selection sites in request-prepare), carried through runTurn and the image/web-search sidecars alongside comboAttempt. No provider reads them yet; the Antigravity ACP provider does next. * feat(agy-acp): official Antigravity CLI over ACP as a separate provider Adds the antigravity-acp provider (adapter agy-acp): each turn launches the official Antigravity CLI as `agy acp --sandbox` in an empty private workspace and talks the Agent Client Protocol over stdio. The CLI owns its Google sign-in; OpenCodex never reads or stores it. The existing google-antigravity provider is unchanged. Owner decision on lidge-jun#8480: one account, no rotation, no remote sharing, Gemini models only, interactive and user-directed use only. - Policy: 403 agy_acp_interactive_only for x-codex-parent-thread-id, combo members and fallback-routed turns; 403 agy_acp_local_only for any non-local peer. Checked in a pipeline preflight before sidecars and again in runTurn before any probe or spawn. - Config: a pure, import-free resolver refuses ACP rows with credentials or non-Gemini models, as combo targets, and as subagent fallbacks. - Protocol: phase-aware Gemini model proof, every permission request refused, no --dangerously-skip-permissions, fixed error text only. - Tests use a fake ACP child; docs, provider counts, structure notes. Closes lidge-jun#8480 * fix(agy-acp): refuse combo decision calls and declared-proxy peers Review round 1 on the Antigravity ACP provider: - A JEV combo's decisionModel could route the combo's automated decision call to antigravity-acp: it carries no conversation headers and is not a combo member. Config now refuses a decisionModel that resolves to an ACP provider, and a typed IncomingMeta.internalDecisionCall fact is refused like a combo member at the preflight and in runTurn. - A loopback peer the operator declared in dashboardTrustedProxy.proxyAddresses is a reverse proxy, so on the public listener it is no longer classified as local. - Config also refuses anthropicAccountPool and codexAccountMode on an ACP row; server tests cover a non-local request end to end over HTTP and WebSocket; docs and the registry note state the proxy caveat. * docs(agy-acp): name combo decision calls wherever the refused signals are listed Review round 2 nits: the refusal message, the adapter reference (EN, es) and structure/adapters/registry.md now list the combo decision call and the declared-proxy rule alongside the other signals. * fix(gui): show antigravity-acp as a ready subscription CLI with its own mark The new keyless provider surfaced three dashboard defects, caught by the GUI icon-wiring guard on PR CI: - no icon row, so the committed Antigravity mark was unused (GUI and the native menu-bar table, which must stay identical); - the configured row read as Needs setup / Missing credentials, and the add-provider form offered it as a free tier; - its name rendered as "Antigravity Acp". agy-acp now joins claude-cli as a subscription CLI adapter, each with its own add-provider warning (agy acp, interactive local use only, a Gemini API key for programmatic work) in all 11 locales; the row is ready without a key, is not priced as free, and keeps the brand name. * fix(server): tolerate a server without requestIP when recording peer scope test:changed showed direct createServeOptions callers (advisor caller-policy and reasoning-archive HTTP tests) passing a server object with no requestIP, which the new peer-scope wrapper called unconditionally. Call it optionally: a peer that cannot be observed is not local, so the Antigravity ACP provider still fails closed and nothing else changes. Also registers agy-acp-preflight.ts in the Responses core module inventory that tests/responses/responses-core-modules.test.ts checks. * fix(gui): the ACP warning names only the fallback the proxy refuses Review round 3: the add-provider warning said OpenCodex refuses "fallback routing", but the policy refuses subagent fallback only (routing-profile fallback is not one of the owner-approved signals). All 11 locales now say subagent turns, combos and subagent fallback routing. Also pins that a peer the server cannot report (no requestIP) is never local. * fix(agy-acp): refuse unattended Codex turns and reverse-proxied peers Merge-manager security review of 2f2658e (owner interactive-only and local-only rules): - Codex memory turns (x-openai-subagent: memory_consolidation, x-openai-memgen-request, memory turn metadata in the header or the body copy) and spawned threads (isThreadSpawnRequest) arrive without x-codex-parent-thread-id. The policy now refuses them at the preflight and in runTurn, and config rejects memoryModels phases and an enabled shadowCallIntercept target that select an ACP provider. - A same-machine reverse proxy or tunnel (nginx, cloudflared, tailscale serve) relays remote clients from 127.0.0.1. A request carrying a forwarding header (Forwarded, X-Forwarded-*, X-Real-IP, Via, CF-Connecting-IP, Tailscale-User-Login, ...) is no longer local, over HTTP and at the WebSocket upgrade. Forging one only gets a refusal. Each fix has a test that fails with its guard removed. * fix(agy-acp): refuse unattended HTTP and WebSocket turns * fix(agy-acp): redact config issues and preserve valid disk settings * fix(cli): initialize keyless providers without credentials * fix(agy-acp): account for every physical prompt send * fix(agy-acp): keep turn workspaces outside home and await Windows tree kill * docs(agy-acp): explain proxy locality and prompt limits * docs(agy-acp): keep locality guidance within structure constraints * fix(agy-acp): close prompt and cleanup races from review * fix(agy-acp): preserve unattended config repairs and redact diagnostics * fix(agy-acp): require confirmed Windows tree cleanup * fix(init): restore optional LiteLLM key entry * fix(agy-acp): validate the CLI version probe * docs(es): restore the A6API quota anchor * fix(agy-acp): redact credentials from streamed responses * fix(agy-acp): confirm process tree exit before workspace removal * fix(config): preserve sibling ACP fallback chains on load * fix(agy-acp): require private Windows workspace ACLs * fix(config): redact minted credentials from ACP repair paths * fix(agy-acp): require Antigravity CLI 1.5.3 * fix(agy-acp): stream credential values without masking header prose * fix(agy-acp): reap the child on prompt serialization failure * fix(agy-acp): preserve dispatch refusals when cleanup is unconfirmed * docs(agy-acp): describe POSIX process-group cleanup scope * fix(agy-acp): report stream activity while redaction buffers * fix(agy-acp): classify WebSocket turns by frame provenance * fix(agy-acp): remove workspaces after confirmed spawn failure * fix(init): show the ACP default-model validation error * test(config): isolate each ACP backup logging fixture * test(docs): check A6API anchors outside fences and comments * fix(agy-acp): mask Remote Workspace device credentials * fix(agy-acp): reject nested selector groups * fix(agy-acp): reject incomplete option snapshots * fix(agy-acp): reprove the model against each selector snapshot * fix(agy-acp): enforce the frame limit on complete lines * fix(config): escape control characters in ACP repair warnings * test(agy-acp): compete with a session-scoped update on budget denial * fix(settings): refuse ACP memory targets before saving * fix(config): preserve canonical OpenAI fallbacks with an ACP default * fix(config): share built-in model alias rules with ACP validation * fix(agy-acp): report private workspace removal failures * fix(agy-acp): sync provider catalog with the CLI minimum * test(config): distinguish conservative ACP validation from routing * fix(agy-acp): require confirmed POSIX cleanup before accepting a version * fix(agy-acp): preserve answer and reasoning arrival order * fix(agy-acp): redact minted catalog-read tokens and keep setup links for existing init presets * fix(agy-acp): refuse Codex automatic compaction turns before the version probe * fix(agy-acp): keep unattended-turn policy across HTTP bridges Classify Codex turn markers before Chat and Compact translate the request. Carry the result as an internal option through Responses preflight and adapter dispatch. Preserve the proxy-authored refusal code when Chat projects the error. Exercise the three HTTP routes and Responses WebSocket with fake agy, including the manual-compaction control and exact process counts. * test(catalog): accept the bare-family predicate import that now owns the reserved reviewer set * fix(agy-acp): keep CLI-owned sign-in out of key login * fix(agy-acp): bind version checks to executable identity * fix(agy-acp): reject unattended configuration targets * fix(agy-acp): validate spawn and session lifecycle boundaries * fix(agy-acp): mask OAuth fields without blocking safe output * fix(agy-acp): preserve pre-send policy across HTTP routes * test(agy-acp): verify selected model and harden fixture waits * fix(agy-acp): reject managed defaults on the settings route * test(agy-acp): cover symlink retargeting after the probe * docs(agy-acp): clarify streaming errors and workspace cleanup * fix(agy-acp): resume credential scanning after OAuth values * docs(agy-acp): mirror output redaction in Spanish * fix(agy-acp): harden turn handling and config recovery * test(docs): respect inline code when scanning comments * test(agy-acp): exercise OAuth separator framing * fix(agy-acp): redact OAuth values across JSON separators
…(carries lidge-jun#8882) (lidge-jun#8900) Same-account credential recovery now records each upstream attempt and its outcome, and every physical upstream send is charged exactly once against the shared request send budget at guarded dispatch: generic HTTP and adapter-owned sidecars, hosted search/media allowances, the Zed support executor with a single-owner pacing lease, M365 Copilot chat sends (reservation refunded when final admission refuses), lidge-jun#8927 image-413 recovery resends, and lidge-jun#8894 same-model capacity retries. Carries lidge-jun#8882. Co-authored-by: Vadym O <bolein95@gmail.com>
…un#8818) * fix(claude): fill the unset Fable tier with claude-fable-5-2 Claude Code 2.1.323 resolves `--model fable` to `claude-fable-5-2`. The native tier table still held `claude-fable-5-1` (recorded against 2.1.296), and an unset tier slot is filled from that table, so the filled ANTHROPIC_DEFAULT_FABLE_MODEL overrode the CLI's own alias and kept `--model fable` and the /model Fable entry on 5.1 behind the proxy. Bump the native Fable tier, the dashboard's mirror of that fill, and the env-var table in the Claude Code guide. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Assisted-by: claude-code:claude-ocx-teamclaude--claude-fable-5-2 Agent-Trace: 818ca99d-a13b-406d-a79e-1258a98a2c7f * revert the dashboard mirror; keep this change to the server tier The dashboard's copy of the native fill is left as it is on dev so this pull request carries no change to the dashboard package. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Assisted-by: claude-code:claude-ocx-teamclaude--claude-fable-5-2 Agent-Trace: 27ef1820-7fcb-47b9-b0cc-f83d587d4f41 * fix(claude): keep manual Fable tiers in sync Co-authored-by: fivetaku <fivetaku@naver.com> * fix(claude): gate automatic Fable 5.2 by CLI version * fix(claude): bound version probes and defer system Fable defaults * fix(gui): leave automatic Claude Fable out of manual launch * fix(claude): keep daemon version probing off launcher state reads --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: JUN <jun@lidgeai.com>
* feat(providers): add AbliteratedLLM API-key preset Add AbliteratedLLM as an ordinary API-key preset on openai-chat at https://api.abliteratedllm.dev/v1. Discovery reads the public GET /v1/models, which answers 200 for any Bearer value, so key validation reports unknown. Seed the 15-model catalog listed on 2026-11-14 with its context windows, input modalities and the default model's output cap, and pin the documented low/medium/high reasoning_effort ladder. The preset note and the catalog entry state the routing observed on 2026-11-15 instead of promising zero retention for every model: GET /v1/models listed glm-5.3-flash-abliterated (variant "abliterated") and 14 models with provider_label "Stock model". None was labelled "Official DeepSeek API", the privacy policy's label for requests forwarded to DeepSeek's own API; the listed models, the DeepSeek ones included, run on Fireworks AI with zero data retention. The English and Spanish entries go on guides/api-key-catalog.md. Every locale's provider guide and quickstart, and structure/ops/docs-and-release.md, recount the documented totals to 109 presets and 88 key-based. * docs(providers): say the key is validated where the provider can check one * feat(providers): seed AbliteratedLLM models instead of live discovery from its public catalog --------- Co-authored-by: lidge-jun <jun@lidgeai.com>
…#8943) * Fix gateway client restore after profile or settings edits * Preserve agy recovery journals when profile restore is unverified * fix(integrations): explain agy profile restore refusals
Hosted ubuntu-latest shards were cancelled at the 15-minute wall in their last batches with no failing tests (lidge-jun#8651 shard 1 at batch 62/65 and shard 5 at 66/66; also lidge-jun#8585, lidge-jun#8645, lidge-jun#8841, lidge-jun#8861, lidge-jun#8887). A cancelled shard is neither a pass nor a fail, so it blocked merges without evidence of a fault. Raise only the test job's timeout-minutes to 20 and pin the new ci.yml blob with an appended release-evidence policy entry. A shard far beyond 20 minutes is still treated as wedged.
…d a configured credit price (lidge-jun#8452) * feat(usage): cost credit-billed provider rows from providerCredits and a configured credit price Closes lidge-jun#8309 * fix(usage): drop an invalid credit price at load and resolve it for account-suffixed rows * docs(providers): document providers.<name>.creditPriceUsd The new field had no user-facing documentation, and the Kiro credits section still said the credit value "does not replace USD cost estimates", which this change makes false when a price is configured. - guides/providers.md: the Kiro credits section now documents the opt-in price, the credits x price rule, the refused-row zero, the output-without-credits fallback and the account-suffixed resolution. - reference/configuration/providers.md: the provider field table lists creditPriceUsd beside modelCosts, including the validation and load-degradation behavior. Refs lidge-jun#8309 * docs(providers): move Kiro credit pricing into its own guide page The Kiro request-credit section in guides/providers.md and the creditPriceUsd row in reference/configuration/providers.md both sat at the 1999-line cap, so documenting the new opt-in had nowhere to grow. The guide's completion-guardrail, refusal and metering material moves to guides/kiro-request-credits.md, linked from both pages and listed in the sidebar with translations for every existing locale. The configuration row keeps one sentence and a link. The new page states the price is opt-in, needs a finite number of 0 or more, and re-estimates already-logged rows. It also records the limit review raised: a model with no token price of its own stays unpriced, so kiro-auto is not costed by the credit price alone. * docs(providers): restore the config reference's paragraph break The reference file sat at its 1999-line cap when the Kiro move was written, so the move also dropped one of the two blank lines before "Across these strategies" to stay inside it. dev has since shortened the same file to 1995 lines, so the deletion is no longer needed and leaves unrelated whitespace in the diff. Restore it; the branch diff is now only the creditPriceUsd row. Refs lidge-jun#8309 * fix(usage): name the credit billing basis instead of serving zero components A provider priced in credits (Kiro) returned `{input:0, output:0, cacheRead:0, cacheWrite:0, total:X}`. The Logs detail panel rendered those four zeros as token component charges of $0.0000 beside a nonzero total, which reads as a measured allocation the proxy never had. The estimate now carries an optional `billing` basis. `{ source: "provider-credits", providerCredits, creditPriceUsd }` says the total is `credits x price` and the component fields are not a split. A Combo claims that basis only when every attempt shared one credit price and the summed credits still reproduce the total; attempts billed differently, or at different prices, report `{ source: "mixed" }` so the parent total stays real while the split remains per attempt. No component allocation is invented at any level. Absent `billing` is a token price, which is what every older row and every client that ignores the field already reads. Bounding the price alone cannot keep the product representable, so `src/usage/credit-billing.ts` owns both factors: `creditPriceUsd` is limited to 0..1,000,000 at the config schema and the load-degradation path, a single attempt may report at most 1,000,000,000 credits, and one token bucket of a priced row at most 1,000,000,000,000 tokens. `1e308 x 1e308` is `Infinity`, which `JSON.stringify` writes as `null`; both a present-but-unrepresentable credit reading and an overflowing token bucket now fail closed instead of inventing an amount. A credit-priced row whose credit count or price cannot produce a representable charge is unavailable with the new `credit_cost_unrepresentable` reason rather than falling back to a token estimate, and an absurd token count on a token-priced row is `invalid_usage` rather than `price_unmatched`. A credit charge still never reads the token buckets, so an absurd token count does not discard a charge it never used. The detail panel labels a credit or mixed total "Estimated cost" instead of "API list-price equivalent", prints `<credits> credits x <price> per credit` with a significant-digit unit price, and omits the four token rows. Token- priced rows keep their existing breakdown and heading. Verified against a live proxy: a Kiro row renders "Credit-priced total $0.0780 / 1.95 credits x $0.04 per credit" with zero "$0.0000" rows, where the pre-fix build showed "API list-price equivalent" and four of them; a mixed Combo renders "Combined total (per-attempt basis)" with each attempt's own charge. Covered by tests/usage/usage-provider-credit-price.test.ts (bounds, provenance, mixed aggregation, overflow), tests/server/management-api-logs-metrics.test.ts (DTO) and gui/tests/logs-cost-credit-billing.test.tsx (rendered detail). Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(usage): tie cost provenance to the basis that produced the amount lidge-jun#8452 taught the estimate to carry a `billing` basis, but the provenance around it still came from the token rate that was resolved on the way in. A credit charge is `providerCredits x creditPriceUsd`; the catalog rates were consulted only to decide whether the row falls back to them. The result was a credit total printing the token catalog key as its "Price source" and `>=` over an exact amount, plus `cache_detail_missing`, `expected_price_overlay` and `provider_cost_overlay` reasons describing a price nobody was charged. Provenance now follows the basis: - `src/usage/cost.ts` sets `priorityLowerBound` only when the amount came from a token rate. A credit charge is exact for its configured price, so the token-rate floor stops at the fallback path instead of riding along. A combo of all-credit attempts therefore never reports one, and a mixed combo's parent does not either while its token leg keeps its own. - `src/server/management/shared.ts` derives `estimateReasons` per attempt. A credit-only row drops the token-price reasons and keeps `usage_estimated`, because the credits really were derived from that reading. A mixed combo collects cache/overlay provenance from its token-priced legs, using their own usage and persisted cache evidence, so real uncertainty survives. No token allocation is synthesized for a credit leg. - `gui/src/pages/logs-cost-format.ts` gains `effectivePriorityLowerBound` and `estimateReasonsForBilling`. The detail panel renders reasons through it, and the conversation total no longer aggregates a credit charge as a floor. These also guard a row seeded by an older build or served by an older proxy, where the marker and reasons were already persisted. Absent `billing` still means token-priced, so a legacy row keeps its provenance. The current and classic Logs pages omit the matched key and price source for a credit or mixed total and keep them for token-priced attempts, so the per-attempt table still names each leg's own rate. Covered by tests/usage/usage-provider-credit-price.test.ts (pure credit, attempt, all-credit combo, mixed combo), tests/server/management-api-logs- metrics.test.ts (production `requestLogDto` with `estimate.price` populated, credit/token/mixed/overlay), gui/tests/logs-cost-lower-bound.test.ts (formatter guards) and gui/tests/logs-cost-billing-provenance{-classic,}.test.tsx (rendered current and classic pages). Reverting the production changes makes 4 estimator, 4 API and 6 GUI cases fail; with them the focused suites pass. Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(usage): keep a mixed combo's floor when its token leg is one A mixed Combo sums an exact credit charge with a token-priced attempt. The aggregate marker required every attempt to be a lower bound, so one exact credit leg erased the floor the token leg earned: `credits x price + >=token` is still `>=` the true total, and hiding it understated the uncertainty. `estimateComboCost` now consults only the token-priced legs of a credit-bearing combo. A credit leg's own catalog rate still contributes nothing, because that rate priced neither the leg nor the total, so an exact token leg beside a credit leg whose catalog rate happened to be a floor stays exact. Token-only combos keep their existing all-attempts rule, and a credits-only combo stays exact. `gui/src/pages/logs-cost-format.ts` applies the same rule to a row seeded by an older build or served by an older proxy: only the credits-only basis strips the marker and the token-price reasons. Legacy rows without `billing` remain token-priced. Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(usage): preserve credit cost evidence through ledger Retain mixed-combo lower bounds and reject nonfinite aggregate tokens. Keep invalid credit readings distinguishable from absent observations, and leave missing no-output credit charges unavailable instead of inventing zero. Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(usage): preserve incomplete credit evidence and cost floors Keep partial Kiro retry metering from becoming a complete credit charge. Render conservative cost bounds and retain small credit amounts across both dashboards. Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * test(usage): pin incomplete credit evidence across retries A retry that loses one attempt's credit reading, or ends in an HTTP failure after the first attempt metered credits, must stay incomplete instead of costing the request from the first reading alone. Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(usage): preserve incomplete retry credit evidence Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * docs(usage): keep usage contract within line budget Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(usage): account for missing retry usage Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(kiro): mark dispatched retry failures incomplete Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> * fix(gui): keep credit billing details out of the classic dashboard * fix(usage): aggregate credit readings in the dev request-log module * fix(api): omit invalid credit readings from logs and request history * docs(kiro): localize the request credits guide and sidebar * fix(gui): preserve token-only conversation cost floor rules * fix(usage): count credit evidence for completion retries ending at EOF * fix(usage): carry credit evidence across metered sidecar legs * fix(api): preserve credit pricing through provider form saves * docs(kiro): describe USD charges in the Combo attempt table * test(gui): restore the token-only Priority lower-bound expectation * fix(usage): import the credit-price bound from credit-billing to break the leaf-validators cycle * refactor(management): move omitted-field preservation out of provider-routes to keep it under the size cap * fix(kiro): address request credit accounting review * fix(kiro): retain incomplete credits after initial send replays * test(usage): reproduce false mixed Combo cost floors * fix(usage): require known floors for mixed Combo costs * test(usage): reproduce mixed Combo floors with unobserved cache * fix(usage): require observed cache for exact mixed Combo legs * test(gui): cover cache provenance in mixed Combo floor rendering * fix(web-search): settle worker usage at physical dispatch * test(advisor): report simulated worker dispatches * test(images): report simulated refusal-path dispatches * fix(web-search): retain adapter budget across owner rotation * docs: reflow provider reference to fit the file-size ratchet * Preserve incomplete hosted-search credits on credential refusal --------- Co-authored-by: svc-aibot-363 <271381517+svc-aibot-363@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com>
…-jun#8816) * fix(responses): scope keyless loopback replay to its WebSocket Bind replay for loopback Responses clients without a context principal to the admitted WebSocket and its handshake thread. Keep scoped entries in bounded memory and release them when the socket closes. Preserve the durable replay path for callers with a principal and keep scoped writes isolated from snapshots and spill storage. Carry dev's peer-local classification alongside the replay scope during the upgrade. Co-authored-by: luvs01 <luvs01@users.noreply.github.com> * fix(responses): close replay admission and persistence review boundaries Recheck scope lifetime before mutation, reject scoped spill intake, share credential-first replay ownership, and refuse missing strict replay IDs before upstream dispatch. Preserve legacy undefined-owner behavior and durable entries across cold snapshot errors and declined scoped writes. Strengthen persistence, credential, HTTP, in-flight and fixture teardown regressions; document the strict continuation boundary in English, Korean and Spanish. * fix(responses): preserve strict replay refusal and snapshot retention Record zero-send native refusal attribution without entering recovery or upstream dispatch. Skip malformed spill digests and reserve snapshot load retries for filesystem failures. Co-authored-by: luvs01 <luvs01@hanmail.net> * fix(tests): include replay owner in Responses source inventory Cover the shared credential-first replay owner in the existing module graph, line-budget and source-oracle checks. Preserve all assertion and time limits. * ci: keep dev's timing table in the replay-scope PR Co-authored-by: luvs01 <luvs01@hanmail.net> * ci: keep dev's workflow timeout out of this replay PR The 18-minute shard timeout is a CI policy change tracked separately in lidge-jun#8940; this PR keeps dev's .github/workflows/ci.yml and release-evidence policy unchanged. Co-authored-by: luvs01 <luvs01@hanmail.net> --------- Co-authored-by: JUN <jun@lidgeai.com> Co-authored-by: luvs01 <luvs01@users.noreply.github.com>
…jun#7806) * feat(codex): reduce repeated uploads and continuation storage Reuse acknowledged Codex history on caller-scoped sockets and bound stored continuation size. Admit cache-miss resends against the selected account, pool, and shared send budget. Co-authored-by: Hylouis233 <88263959+Hylouis233@users.noreply.github.com> * fix(responses): count Codex cache recovery on credential replay Co-authored-by: Hylouis233 <88263959+Hylouis233@users.noreply.github.com> --------- Co-authored-by: JUN <jun@lidgeai.com>
… and Google outbound fidelity (lidge-jun#8771) * docs(devlog): Google protocol parity roadmap against CLIProxyAPI Adds devlog/_plan/261115_google_protocol_cpa_parity: a 73-row parity matrix comparing CLIProxyAPI (e96d4c4) with opencodex dev (d842c13) and PR lidge-jun#8742 (d21ed22) for generateContent, the Interactions API and the Live API, inbound and outbound (AI Studio, Vertex, Antigravity); Google primary-doc facts; the three lane research appendices; and diff-level phase docs 010-070 (Interactions inbound and state, Gemini inbound fidelity, Google error classification, response and request fidelity, delivery). Folded one independent audit round. * feat(gemini): Interactions API inbound on the Chat path Adds POST /v1beta/interactions and the stable POST /v1/interactions. A new codec (src/protocols/codecs/gemini-interactions.ts) maps the create body (string, content or step input; system_instruction; function tools; generation_config incl. thinking_level, thinking_summaries and tool_choice; text response_format) onto one Chat Completions body, and maps the answer back to an Interaction (object "interaction", Google's total_* usage names, requires_action for tool turns, incomplete for length and content filters) or to the Interactions SSE vocabulary (interaction.created, step.start, step.delta, step.stop, interaction.completed, error). Requests the proxy cannot honor are 400s: agent, background, webhook_config, environment, agent_config, hosted tools, non-text content or output, and previous_interaction_id until stored interactions land. The path classifier also owns /v1beta|v1/interactions/{id} (GET, DELETE -> 404) and .../{id}/cancel (POST -> 501), with geminiRouteAllows giving the by-id route two methods for the 405 Allow header and the loopback allowlist. Parity row INT-01..12, 18, 19 in devlog/_plan/261115_google_protocol_cpa_parity/001_parity_matrix.md. * feat(gemini): Interactions state for previous_interaction_id, get and delete Stored interactions live in a process-memory store (src/server/gemini-interactions-store.ts) owned by the salted principal of the data-plane key the caller presented, or one shared "loopback" owner for keyless loopback callers; any other owner sees a missing id. Bounds: 24 h from the last write, 1,000 entries / 64 MiB in total, 200 entries / 16 MiB per owner, and per entry the smaller of 8 MiB and the inbound body limit. The store is on the app-owned memory roster as gemini_interactions (README retained-store count 14 -> 15 in all eight pages). previous_interaction_id continues the stored history; tools, system_instruction and generation_config stay interaction-scoped. A chained function_result must answer a pending call of the stored turn's last answer and lead the input; a resend of those calls is dropped. Turns are stored only after they settle (inside the bridge's frames() for streams). GET returns the stored resource with its input steps, DELETE answers {}, cancel 400 for an owned interaction and 404 otherwise. Buffered answers report x-opencodex-interaction-stored. Parity rows INT-13, INT-14, INT-15. * feat(gemini): carry thought signatures on the Chat wire; countTokens and limits Gemini 3 rejects a replayed functionCall that lost its thoughtSignature. The Chat wire now carries it on tool_calls[].extra_content.google.thought_signature, the carrier the Responses wire already uses: - inbound: src/chat/inbound.ts (bridge) and the Antigravity chat-ir lane read a normalized value, so a malformed or oversized echo is dropped instead of failing the request; - outbound: src/chat/outbound.ts copies a function_call item's extra_content onto streamed, buffered and SSE-folded tool calls, and the direct-encoder lane passes the adapter's provider metadata through adapter-events to the Chat encoder; - native Chat declines a body carrying extra_content (opaque-state-stripped) unless the destination is a Google host, so Google's opaque state never reaches another vendor; - the Gemini inbound codec (lidge-jun#8742) maps thoughtSignature to and from that carrier. Also on the Gemini inbound surface: :countTokens answers a local estimate under the key's model scope (embed methods stay 501), model resources carry inputTokenLimit/outputTokenLimit when configured or known from model metadata and advertise countTokens, `$alt=sse` is accepted, and STATUS_NAMES follows the google.rpc HTTP mapping (405 UNIMPLEMENTED). Parity rows IN-09, CW-01, IN-05, IN-12, IN-03, IN-13. * feat(google): classify errors by ErrorInfo and RetryInfo; quarantine TOS suspensions Google states why it refused and when to retry in typed google.rpc details, which opencodex ignored in favor of prose. A new src/adapters/google-error-details.ts reads ErrorInfo.reason, RetryInfo.retryDelay, ErrorInfo.metadata.quotaResetDelay and an "after <duration>" phrase in protobuf or Go duration syntax ("30s", "1h2m3s"). - QUOTA_EXHAUSTED and INSUFFICIENT_G1_CREDITS_BALANCE are quota exhaustion on every Google label; RATE_LIMIT_EXCEEDED is a transient rate limit on Antigravity even with quota-like prose (CPA's rule); AI Studio and Vertex keep the prose rule. - A retry delay stated only in the 429 body now floors the next send like Retry-After, and a delay past the retry ceiling returns the 429 with that Retry-After. - A 403 with a typed ErrorInfo TOS_VIOLATION (object root, code 403, PERMISSION_DENIED) gets a fixed "Antigravity account suspended (TOS_VIOLATION)" message that never echoes Google's appeal text; dispatch quarantines that account through the existing fenced path and rotates. The hold is stored as verify_account plus needsReauthCause "tos_violation", so builds that do not know the cause still keep the account out of the pool; it shows as needs-reauth(tos) and health "Account suspended". Parity rows AG-X1, AG-X2, AG-X3. * feat(google): report thinking and tool-use tokens; fail closed on every Google mode Google response fidelity, parity rows OUT-V38, OUT-V42, AG-R7, OUT-V40, OUT-V43 (devlog 050). - Usage: output tokens are candidatesTokenCount + thoughtsTokenCount and input includes toolUsePromptTokenCount, so output includes reasoning as on every other adapter and the Gemini inbound codec's subtraction becomes exact. - Fail closed on AI Studio as on Vertex and Antigravity: MALFORMED_FUNCTION_CALL, MAX_TOKENS after a started call, and UNEXPECTED_TOOL_CALL / MALFORMED_RESPONSE when no visible output (non-thought text, inline image or function call) reached the client in the whole turn. The error carries status 502 / upstream_error, so its HTTP outcome no longer depends on message wording (Vertex MALFORMED_FUNCTION_CALL moves from 400 to 502). - IMAGE_SAFETY, IMAGE_PROHIBITED_CONTENT and MALFORMED_RESPONSE with output end as content_filter; the request log keeps MALFORMED_RESPONSE and MISSING_THOUGHT_SIGNATURE. - promptFeedback.blockReason with no candidates is a 400 invalid_prompt naming only the reason enum: a terminal refusal for Codex and a hard stop for combos, never echoing Google's message. - The new test registrations move to the adapters layout shard; layout.json was over 2000 lines. Release note: AI Studio turns that ended with MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL or MALFORMED_RESPONSE and no visible output used to complete empty and now fail with 502; reported Google output tokens now include thinking tokens. * feat(google): Vertex us/eu rep hosts, inline audio, and error tool results Google request fidelity, parity rows OUT-V04, OUT-V29, OUT-V27 (devlog 060). - Vertex project endpoints for the us and eu multi-regions use aiplatform.{us,eu}.rep.googleapis.com (CPA's vertexBaseURL table); global and regions are unchanged. vertexHostForLocation runs after the existing location validation, so the authority still cannot be changed by configuration. - WAV and MP3 audio parts are sent as inline_data on every Google mode instead of a text marker; Claude models on Antigravity keep the marker (Antigravity hands them an Anthropic message). - A tool result flagged isError is sent as functionResponse.response.error, the key Google documents for a failed call and CPA writes on its Gemini and Antigravity translators. - AG-M1 (nest Antigravity tool-result images) is deferred: ADR-7279 extends nesting only with live upstream evidence for a route, and the pinned CCA layouts were live fixes. Release note: Vertex providers configured with location us or eu now call the rep hosts. * docs(devlog): record shipped parity rows in the Google CPA matrix Rows closed by 010-060 now name their commit; AG-M1 stays deferred (ADR-7279 evidence bar). * docs: Gemini API and Interactions endpoints, Google 429 and suspension handling proxy-formats gains the /v1beta/models and /v1beta/interactions section and overview rows; adapters documents typed 429 handling; providers-accounts documents needs-reauth(tos). English and Spanish; docs-site build passes (775 pages). * fix(gemini): body admission for countTokens; keep AI Studio's body retry wait Independent review round 1. - :countTokens reads, decodes and parses a body but ran outside the shared inbound-body allowance, so concurrent encoded or raised-limit bodies were not bounded in aggregate. isGeminiBodyPath now covers it and the dispatcher runs it inside runAdmittedBodyWork (no turn slot); a saturated allowance queues it and refuses with the Google-shaped 503. - AI Studio returns raw upstream errors, so a 429 whose wait is stated only in the body (RetryInfo, quotaResetDelay) and exceeds the retry ceiling, or is quota exhaustion, reached callers without Retry-After. The raw answer is now copied with that header; Google's body and status are unchanged and an explicit upstream header still wins. - Interactions is_error to Google's response.error is deferred as matrix row INT-20. * fix(google): keep a 429's body retry wait on the last attempt; resync README hashes Review round 2 and PR CI. - Running out of retry attempts (or the send budget) returned the final 429 before its body was read, so a wait stated only in RetryInfo or quotaResetDelay never became Retry-After. Every final answer now goes through finalGoogleAnswer, raw (AI Studio) or normalized (Vertex, Antigravity); an explicit upstream header still wins. - readme/i18n-manifest.json: the retained-store count edit in README.md was mirrored in every locale in the same commit, so each locale's source hash now names the current README. * fix(gui): check the gateway-client action status before reading its body lidge-jun#8742's action client parsed every answer as an action body, which react-doctor's no-fetch-response-used-without-status-check rule blocks (it fails lidge-jun#8742's own run too). It now branches on the status first: a 2xx or one of the route's refusals (400, 404, 409) is read for its code, and any other status is reached but has no body to parse. No visible change. Co-authored-by: Andrew <wsy1731095638@gmail.com> * fix(gemini): CodeRabbit round on the Google parity branch - Retry delays: only a positive delay counts, and a typed RetryInfo outranks quotaResetDelay and untyped details regardless of order. - Interactions store: a write evicts only its own owner's entries, also at the global limits; when the store is full and the writer owns nothing, the interaction is not kept, so one key never removes another key's history. Only the app-owned memory budget evicts across owners. - Interactions codec: a conversation-level system/developer turn keeps its position, and thinking_summaries "none" reaches Chat as include_reasoning false. - Gemini codec: enum/const/default/example(s) values are copied, not lower-cased; an explicit includeThoughts false is carried. - Model discovery reports a configured output limit as outputTokenLimit. - ocx account gives "Account suspended" an appeal action. - Unknown /v1beta/* paths are a JSON 404 instead of the dashboard page. - Docs: best-effort Interactions retention with its limits, rejected input types, safety_settings ignored, streamed 502 after output; one-line inventory table row. Each code fix has a regression test that failed before it. * fix(gemini): normalize schemas under property names that look like keywords CodeRabbit follow-up. normalizeSchema copied the value of a property named enum, const, default, example or examples as a literal, so its schema kept an upper-case type. Schema maps (properties, patternProperties, $defs, definitions) now normalize every value as a schema while their names stay data; literal keywords inside a schema are still copied verbatim. Also: discovery coverage for a configured output limit overriding generated metadata, and the proxy-formats docs (en/es) name the per-interaction storage limit and the x-opencodex-interaction-stored header. * docs(devlog): plan the agy acp provider (lidge-jun#8480) and add its parity row Owner decision on lidge-jun#8480: a separate local provider over the official agy acp transport. 080 is the diff-level plan; AG-ACP is the matrix row. Implementation ships as its own PR from dev. * docs(devlog): revise the agy acp plan after audit round 1 Resolves B1-B6: fallback bit on the run-turn and sidecar paths, apiKeyPool and resolved-target config checks, state-tracked option selection, --sandbox with request-review and a private workspace, fixed error text, a complete terminal table. * docs(devlog): revise the agy acp plan after audit round 2 R2-1 pure structural selector resolution for config checks; R2-2 the permission engine is the promised boundary and --sandbox is unpromised hardening; R2-3 fail closed when the Gemini model proof is lost. * docs(devlog): phase-aware model proof in the agy acp plan (audit round 3) * fix(google): preserve retry and account trust across the rebase * fix(gemini): bound interaction retention and protect resource responses * fix(google): fall back to a body delay for invalid Retry-After * fix(gui): identify suspended OAuth accounts and show appeal guidance * docs(google): record parity gaps and shipped ACP locality * fix(google): validate Retry-After once before replay * fix(gemini): publish custom model input limits in discovery * test(antigravity): cover redaction in terminal suspension responses * docs(google): keep retry guidance within combined-tree limits * test(retry): cover fractional delays and Google header precedence * fix(google): keep strict Retry-After parsing at the adapter boundary * fix(gemini): honor ACP turn policy on Interactions ingress --------- Co-authored-by: Andrew <wsy1731095638@gmail.com>
… name (lidge-jun#8859) * feat(anthropic): keep one OAuth account per organization One Claude account (one account.uuid) can belong to several organizations, and each OAuth grant is scoped to exactly one of them with its own subscription and limits. The store matched Anthropic rows by account identity only, so logging in to a second organization overwrote the first organization's row and its grant. Record the grant's organization inside the private bearer-bound proof (token response, else the same bearer's profile read) and treat it as a slot scope, never as identity: - login and Claude Code import write the same-organization row, else a row whose organization is unknown; a proven other organization gets a new row. Organization-less rows are asked through their own unexpired bearer before the store lock; the answer is honored only while the row still holds that bearer and is never written to it. - reauth refuses a grant for another organization, or one another row of the account already proves. - CLI continuity, the cross-pool duplicate check and plan labels treat proven different organizations as different accounts. - own-grant refresh keeps the stored organization when the response does not repeat it, and never throws over it after rotation. Unknown on either side keeps the historical same-account replacement, so existing rows are never duplicated by re-login. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(anthropic): state when another organization can still replace an account Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(oauth): keep plan.ts free of node:crypto for the GUI bundle The GUI build compiles src/oauth/plan.ts through anthropic-subscription, and its tsconfig has no Node types, so the bearer hash broke tsc -b. Callers already pass store-normalized, bearer-bound proofs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(anthropic): qualify when organization evidence separates accounts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(anthropic): an unknown organization still meets the held-elsewhere refusal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(oauth): recheck reauth organization slots inside the serialized writer The reauth organization-conflict and held-elsewhere checks read a store snapshot before awaiting saveAccountCredential, which then overwrote the row unconditionally after the queue and file lock. A login for the same organization committed in between could leave two rows on one organization and overwrite the original grant. saveAccountCredential gains an assertAccounts hook that runs against the rows the writer loaded, before the row changes; reauth passes anthropicReauthSlotRefused (same account, no proven conflicting organization, organization not held by another row) there as well as in the early check. Profile reads stay outside the lock. Adds a queue-barrier regression that commits the competing login before the queued reauth, plus own-organization and unreported-organization controls under the same schedule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(anthropic): show each account's organization name in the dashboard One Claude account can now hold a pool row per organization, but the rows were indistinguishable in the dashboard. The profile read that already supplies the subscription tier also returns organization.name. Store it as display-only credential metadata (organizationName) with the plan's lifecycle: normalized on load, set from the same bearer's profile only for the organization that profile proves, carried through an unread profile, cleared by an observed unknown, and never inherited across accounts or organizations. It never enters the private identity proof. Anthropic account summaries expose it and the provider auth panel shows it as a secondary line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(anthropic): keep organization labels with the grant they describe Two CodeRabbit findings on lidge-jun#8859: - Adopting Claude Code's rotated refresh token on an unchanged access bearer retained the bearer-bound proof but merged the organization name against a disk credential without it, so the name was dropped. The name merge now sees the retained proof. - A profile that names another organization than the token response still supplied its tier. Such a profile observed a different grant, so neither its tier nor its name is applied; both stay unobserved and the stored labels survive the merge. A profile with no organization cannot confirm the token response's either. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(oauth): fold the reauth guard and label merge into helpers Rebasing onto dev left src/oauth/index.ts at 2,003 lines (the file-size ratchet stops new files at 2,000) and the account-pool structure page at 605 lines (budget 600), because dev grew both files. No behavior change: - anthropicReauthSlotGuard (anthropic-login-slot.ts) is the writer-side half of the reauth organization check that runLogin built inline. - withMergedOAuthLabels (plan.ts) merges the plan and organization name onto a fresh credential; the reauth path and the store's login path both built that object by hand. - oauthOrganizationNameSummary (plan.ts) is the account-summary projection of the validated name. - The organization paragraph in the structure page joins the preceding line, so the page keeps dev's line count. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Bind Anthropic OAuth grants to organization slots * Guard Anthropic OAuth organization binding across credential writes * Guard stale Anthropic login slots and retain exchange scope * Preserve Anthropic exchange scope during browser login * Fix Anthropic email-only login slot matching * Preserve account boundaries in Anthropic email-only login * Merge origin/dev and fit Anthropic account pool doc budget * fix(oauth): keep organization scope on email-only reauth, unproven refresh and CLI rotation CodeRabbit findings on lidge-jun#8859 at df4827b. Each code fix has a regression case that fails without it. - Email-only reauth: anthropicReauthSlotGuard returned when the login carried no account UUID, before comparing its organization with the target row's. A grant for organization B could replace a row proven for A. The target-organization check now runs first; only the sibling match still needs the account UUID. - Own-grant refresh without account proof: when the refresh response and the profile read gave no proof, the rotated row lost its organization. mergeAnthropicIdentity now keeps it as an organization scope bound to the new bearer, never as an account identity. - Full Claude Code rotation: the adoption writer accepted a same-account row of unknown organization in the other pool. It now applies the cross-pool registration rule under the writer lock; a refusal leaves the old row and its refresh intent untouched. Tests: the queued-reauth case now depends on the newly committed sibling (the reauth's own profile read is unavailable), and its queue wait is bounded so a failed setup releases the held writer. Docs (en, es): bare `ocx login anthropic` imports a usable Claude Code credential, so a second organization needs `--headless`; recovery steps for an ambiguous email match; the expired legacy-token exception in the Spanish page. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(oauth): require matching Anthropic scope for email-only reauth Use the Anthropic slot email comparison for reauth and require the current target to prove the same organization under the writer lock. Preserve unidentified legacy rows when scoped email-only sign-in cannot prove an existing match. * fix(anthropic): close slot gaps for email-only logins and same-bearer scope Address the second review round on the per-organization account slots: - A login that carries the account UUID now reuses the single UUID-less row an earlier email-only sign-in left in the same proven organization instead of appending a duplicate. A row of another known UUID is never reused and a second same-email row in that organization is refused as ambiguous. - An email-only reauth refuses, under the writer lock, when another row of the proven organization has the target's email. - An email-only reauth also probes its legacy target (stored UUID, matching email, no saved organization) through the target's own bearer, so the same organization passes; another organization, another account or an unavailable profile still fail. - On the same bearer a fresh organization proof replaces a retained exchange scope; the retained scope applies only when no fresh proof names one. - Await the pending result in the test finally block; describe the CLI generation re-read and the token-refresh wording accurately in the docs. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(anthropic): require continuity for UUID slot recovery * fix(anthropic): reject duplicate refresh tokens on login Check refresh-token ownership against the selected slot under the auth-store writer lock. Ask the user to retry if another slot owns the grant, and keep the append fallback for distinct tokens. * fix(anthropic): enforce refresh token ownership on reauth Share the locked same-pool refresh token check between sign-in and reauthentication, excluding the slot being updated. * test(oauth): give distinct Anthropic accounts distinct refresh tokens * Extract OAuth reauth identity precheck from index --------- Co-authored-by: seongwoong <seongwoong@mobilint.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JUN <jun@lidgeai.com>
…un#8180) * feat(routing): add reset-near-weighted account pool strategy * fix(routing): preserve Anthropic session hold and round-robin cursor * fix(api): round-trip weighted strategy only for supported pools * fix(gui): preserve weighted pool settings and localize controls * fix(routing): restrict reset-near weighting to fresh supported windows Co-authored-by: vibewriter-hand <337401476+vibewriter-hand@users.noreply.github.com> * test(layout): register weighted routing policy coverage * fix(api): advertise the weighted strategy for Codex settings * docs(accounts): synchronize weighted routing references and CLI surface * fix(routing): require five-hour evidence and reset stale weighted scores * fix(quota): preserve Anthropic observation ownership across probe fallback * fix(quota): bind Anthropic evidence to credential revisions * test(anthropic): preserve current quota during threshold edit race * fix(quota): keep Anthropic ownership outside persisted quota rows --------- Co-authored-by: JUN <jun@lidgeai.com>
…commentary-only degenerate completions (lidge-jun#8645) * fix(combos): cool a target after a committed output_limit or stall_timeout terminal A combo child that commits output and then ends incomplete was delivered as-is with no health signal: the hop path only sees pre-commit failures, so the next request picked the same target and burned the same budget again (observed: devin/swe-2-flash at effort=max generated its full 131072-token ceiling on a 127k-token compact, then repeated the pattern). Request-log finalization now reports the serving attempt's terminal to a registered combos handler, which records a bounded cooldown for the capacity/silence failureDetail codes only. Effort and context config are untouched; the next pick simply routes around the exhausted target. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(combos): hop a combo target that ends its turn on commentary-only prelude A combo child could end response.completed carrying only reasoning items and phase:"commentary" messages — progress text announcing work, no tool call and no final answer. The client saw a clean completion and the agentic turn died silently mid-task (observed: devin/swe-2-flash returned 63 output tokens after a 55-minute turn, freezing a Codex thread mid-investigation). The stream preflight already buffers the prefix before the client sees anything, so holdable prelude can stay replayable: reasoning frames and explicitly commentary-phase message items (plus their item-scoped content frames, correlated by item_id) no longer commit output. A completed or incomplete terminal whose entire output is that prelude now returns the same retryable failure shape as a zero-output terminal, letting the combo hop to the next target and cool the degenerate one through the existing failure path. Final answers, tool calls, unidentified items, and every non-degeneratePrelude caller are unchanged. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(combos): cool committed stall terminals regardless of attempt status A stall_timeout that breaks mid-stream surfaces to the client as a 5xx attempt status, so gating the committed-terminal cooldown on status < 400 silenced exactly the case it exists for — observed live: devin/swe-2-flash stalled after 334s of committed output, recorded a 502 attempt, and was re-picked 13s later inside the intended 60s cooldown window. The incomplete terminal itself is the proof the target ran; drop the status gate and keep locallyAnswered as the only attempt-level exclusion. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(combos): close degenerate-hop replay and guardrail gaps from review - isDegenerateStreamTerminal now inspects both output carriers (event.output and response.output), so a tool call or final answer that exists only at event level can no longer be discarded by a hop. - The requiredToolPrelude commitment check honors degenerateTerminal, so a commentary-only response.incomplete under both options stays hop-eligible instead of being committed by the terminal snapshot rule. - Incomplete degenerate evidence now preserves every zero-output replay guard: retryable-reason allowlist (adapter_eof, missing_terminal_event, upstream_stall_timeout, or absent), isPausedTurn, end_turn !== false, and incomplete_details.retryable !== false. max_output_tokens and content_filter keep their own contracts and never hop as degenerate. - Cooldown expiry assertions capture the clock after the write so the boundary checks are deterministic. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(combos): preserve longer live cooldowns over committed-terminal writes coolComboTargetForCommittedTerminal now skips its write when the target already carries a cooldown expiring later than the committed-terminal proposal, so a server Retry-After or reset stays authoritative instead of being shortened to the local 10-minute/60-second fallback. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(combos): honor non-retryable verdicts on every incomplete reason end_turn:false and incomplete_details.retryable:false now outrank every defined incomplete reason in retryableZeroOutputTerminal, not only max_output_tokens, so an upstream stall marked non-retryable can no longer hop. The degenerate-terminal reason check validates the type before set membership so malformed upstream reasons cannot throw inside the inspector. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(combos): pin the preserved cooldown original expiry boundary Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(combos): cover committed stall cooldown through addFinalRequestLog Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(combos): type the final-log stall regression with beginRequestAttempt Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(combos): rework committed cooldown triggers, alias keys, and hold bounds - Only cool output_limit when turn is unpaused and output reaches target ceiling - Carry comboTarget, writerGeneration, outputCeiling through logCtx and record cooldown under pick.target - Bound degeneratePrelude reasoning hold with COMBO_REQUIRED_TOOL_REASONING_HOLD_MS (1000ms) to preserve TTFT - Extract committed terminal log reporting into request-log-committed-terminal.ts to enforce file-size ratchet - Split committed terminal cooldown tests into combo-committed-terminal-cooldown.test.ts and register in layout files - Add tests covering caller-allowance, pause_turn, alias-key cooldown, and reasoning hold TTFT * fix(combos): carry paused mark child to parent, document boundaries, and require non-empty prelude * fix(combos): use serving target usage and ceiling for cooldown * fix(combos): preserve conservative preflight replay guards * docs(combos): describe committed cooldowns and prelude timing * fix(combos): bound stream prelude and preserve replay vetoes * Translate combo terminal cooldown and preflight hold * fix(combo): honor both terminal replay veto carriers * Honor replay vetoes after the native required-tool rewrite * Preserve upstream errors on commentary-only combo terminals * Drive committed combo cooldowns from structured terminal reasons * Preserve upstream verdicts in mandatory-tool streams * Suppress success effects for error-bearing Responses completions * Preserve Responses completion verdicts in buffered delivery * Keep buffered committed Responses terminals on the serving combo target * Carry the earlier dev-merge resolutions into the rebased series Merge a494f2f resolved combo stream preflight against dev with three changes that lived only in the merge commit and are dropped by a linear rebase: clear the degenerate terminal evidence when payload classification throws, pass hopEvidence without a non-null assertion, and judge moderation refusals against the whole hop evidence frame. It also dropped two trailing blank lines. This restores that resolved content. * Keep request-log.ts under the file-size threshold after the dev rebase Current dev grew src/server/request-log.ts to 1990 lines, and this branch adds twelve, so the rebased file reached 2002 and the file-size ratchet reported it as NEW_OVERSIZED. Share one doc comment across the three combo selection fields and inline the CommittedIncompleteReason type import. No behavior changes. * Keep request-log.ts under the file-size threshold after the second dev rebase Current dev grew src/server/request-log.ts to 1993 lines (lidge-jun#8887), so this branch's additions pushed the rebased file to 2002 and past the file-size ratchet's NEW_OVERSIZED threshold. Move the four internal combo serving fields this branch adds to RequestLogContext into CommittedComboLogFields in request-log-committed-terminal.ts, which RequestLogContext now extends. Type declarations only; no behavior changes. --------- Co-authored-by: Omar <13569609+omar391@users.noreply.github.com> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com>
* fix(responses): reject repeated Chat work announcements Honor the provider continuation guard in hosted-search Chat turns and fail a repeated short work announcement after the bounded re-ask. Preserve tool results, opt-outs and usage accounting. * fix(responses): Fixed Chat continuation request classification * Classified the dispatched iteration request, including tools-disabled recovery. * Kept non-Chat iteration bounds unchanged and covered both boundary regressions. * Reserve search loop retry slots only when Chat recovery is authorized * docs(es): explain hosted Chat terminal continuation failures * Order hosted-search continuation instructions once * fix(web-search): fund the hosted Chat terminal re-ask in the default send allowance The re-ask is one more loop iteration (terminalContinuations in the loop bound), and since lidge-jun#8900 every hosted iteration is charged at guarded dispatch, so a turn that used every other slot was refused before the re-ask under the default hosted allowance. Count that iteration when sizing the allowance; explicit and Combo caps still never expand. Add regressions for the re-ask's send-budget and spend-ceiling accounting (one- and two-send caps, a one-token pool ceiling, ledger settlement, default allowance; streamed and buffered) and document the accounting in en/es provider reference and the search data-plane notes. --------- Co-authored-by: JUN <jun@lidgeai.com>
…family rotation, verified Vertex ADC (lidge-jun#8740) * feat(accounts): read-only per-account Antigravity probe and manual model discovery Original PR: lidge-jun#8642 * fix(antigravity): scope round-robin and session affinity per quota family Original PR: lidge-jun#8664 * feat(gui): per-account quota table on the Providers accounts tab Original PR: lidge-jun#8721 * fix(vertex): show gcloud ADC credentials as verified once a token is minted Original PR: lidge-jun#8720 * fix(gui): tighten the account quota table, probe line and discovery panel Drop the table's Actions column (it duplicated the card buttons and overflowed), show one cell for a row with no reading and a dash for a pool an account lacks, label remaining as "% left" beside cards that show "% used", keep Test all in the header action group, show card plans by product name, omit evidence for a usable probe, and hide model discovery while live discovery is off. * fix(gui): a verified Vertex ADC row keeps the host-credentials auth label Once vertexCredentialVerified was true the row fell through to "API key". * fix(cli): models discover exits nonzero when the server reports a failed discovery * fix(quota): an Antigravity probe re-reads the roster so a pause made mid-run suppresses its request * fix(models): discovery refresh reports GET's arrival state and fetches even when catalog convergence gathers nothing * fix(vertex): a failed older ADC exchange no longer erases a newer exchange's verification * fix(oauth): Antigravity model-listing reroutes skip a sibling whose quota family is exhausted * fix(gui): a late initial read no longer replaces refreshed arrivals, and a Vertex verification change resets the probe * fix(gui): the account table marks a next account only under reset-first * docs(structure): account plan badges show mapped names; the next marker needs reset-first * feat(gui): make the account quota table the one OAuth account list The Accounts tab showed every account twice: the compact quota table on top and the older per-account cards below it. The table now carries each card's controls (pause/resume, reauthenticate, test, alias, remove, reset grants and coupons) in an actions column, and a detail line under a row keeps the hints, probe result, Anthropic per-account threshold and any quota window no pool column shows. The card list is removed for generic OAuth providers. Below a 900px container width the rows stack (account, plan and status, then one line per pool, then the controls) so no button needs sideways scrolling; above it the actions column stays pinned to the right edge. * feat(gui): show an upstream-banned account as one red row in the account list An account auto-paused with reason account_permission_denied now reads "Banned upstream" in the status column, and its quota cells are replaced by one notice (automatic refresh stopped) with a "View reason" disclosure that shows the redacted upstream message, pause time and HTTP status when the server recorded them. Resume stays the manual way back. needsReauthReason verify_account reads "Verification needed" instead of the generic sign-in flag. pauseDetails gains the optional message and statusCode fields. * fix(gui): stack account rows below 1100px so the pinned actions never cover the status At a 980px container the English table is wider than its box, and the right-pinned actions column sat on top of the status column. The provider workspace caps content at about 960px, so the stacked layout is now the one the dashboard shows; the table layout stays for wider containers. * fix(accounts): keep the last good model list on Discover now; show the ban notice without quota readings; treat an expired token as routine * test(accounts): cover banned rows, verification flag, probe controls, and expired-token flag * Test account probe transport and management boundaries * Harden stored-account probes and finish dashboard and CLI parity * Document discovery within the catalog reference budget * Give the OAuth quota table room for desktop columns * Require a live observation for manual model discovery * Scope manual discovery and keep Antigravity account probes read-only Respect model discovery cooldown, join concurrent requests, and keep manual discovery and arrival processing scoped to the requested provider. Bound pinned error bodies for per-account probes and resolve CLI targets through a passive store read. Preserve stale quota diagnostics and render unknown tier IDs as text. * Keep full provider policy context for scoped model discovery Scope the captured provider fetches while retaining the configuration that decides alias ownership and catalog projection. * Share scoped and full catalog provider discovery Join in-flight discovery at the provider boundary under the same resolved credential and policy. Fence model cache publication so delayed results cannot replace a newer roster, while preserving discovery backoff. Derive and publish combo omissions only during full gathers. * Fence shared catalog discovery by credential and outcome * Resolve provider workspace React Doctor findings * Preserve caller-local Copilot rows after supersession * Fence model discovery at admission and catalog publication * Cover superseded discovery on model listing routes * Project superseded discovery for model listing reads * Keep superseded Claude listings from replacing Desktop aliases * Preserve complete Desktop snapshots when discovery is superseded Keep the last complete snapshot while its aliases still resolve to the same routes. Report a retryable 503 when no usable snapshot exists so connected apply keeps the previous static profile. Keep the existing Anthropic listing projection and exercise the production apply path. * Document Desktop snapshot retries in the Spanish API reference Keep the English and Spanish response identifiers in sync with the Desktop snapshot retry contract. * Bind Desktop snapshot retries to listing policy * fix(desktop): retry superseded model snapshots * test(gui): update OAuth account quota table assertions * Extract Anthropic model listing from server serve options * fix(gui): show pause evidence in banned quota rows --------- Co-authored-by: JUN <jun@lidgeai.com>
…ilities and filters per request (lidge-jun#8651) * feat(combos): capabilityPolicy "union" advertises member capabilities and filters per request A combo publishes the intersection of its members' capabilities, so one text-only backup hides image input and one narrow effort ladder caps the whole picker. That made "subscription first, then fall back" combos lose images and effort tiers whenever the fallback list was mixed. Add an opt-in combo field, capabilityPolicy: "intersection" (default, unchanged behavior and normalized shape) | "union": - Catalog: input modalities are the union of the members'; with reasoningEffortMode "adaptive" the effort ladder is the rank-ordered union of the non-empty ladders. Context, input and output limits stay the minimum. A union combo is never omitted as incompatible_modalities. - Request: for an image-bearing request a member proven text-only stays eligible while the vision sidecar is enabled (the child describes the image, keeping the configured order and the prompt cache); with the sidecar disabled it is skipped. The filter joins recoveryEligible, so it applies on every selection path and never bypasses the metered gate. - When every enabled member would be skipped, onUnservable "degrade" (default) dispatches anyway and the child strips the images with a warning; "reject" answers 400 before any send. - Dispatch lowers a caller effort the selected member's known ladder lacks to its highest rung at or below, with a debug line. Both fields are sparse in the normalized config, the stored config and the management API, and a PUT that omits them keeps the stored values. * test(combos): pin union filtering under failover and round-robin and sparse defaults; document the degradation order * feat(combos): capabilityPolicy "union" advertises the largest context window and skips members that cannot hold the input Under union the catalog row takes the largest contextWindow, maxInputTokens and autoCompactTokenLimit; maxOutputTokens stays the minimum. The request gate parses the turn once, estimates its input per member and skips a member whose input ceiling cannot hold it. When none can, onUnservable "degrade" sends to the largest window under the loose direct admission (comboContextDegraded) and warns; "reject" answers 400 before any send. Intersection is unchanged. * docs(es): mirror the union capabilities section and capabilityPolicy/onUnservable rows * fix(combos): apply request capabilities to admitted targets and native effort * docs(combos): specify catalog limits and union dispatch policy * Honor per-request combo capabilities on native and translated paths * fix(combos): enforce admitted image serving before degradation * test(combos): reproduce stale JEV capabilities and union catalog limits * fix(combos): refresh JEV capability and publish minimum limits * test(combos): cover JEV pin release and client effort clamp * fix(combos): refresh JEV eligibility from one live combo snapshot * Revalidate live JEV combo consent and eligibility before dispatch * fix(combos): rerun ingress admission after JEV decisions * fix(combos): keep lazy decision credentials out of admission snapshots * fix(combos): retain refreshed admission policy through JEV dispatch * fix(combos): revalidate protocol and tool eligibility after JEV * Include named hosted Advisor in union combo admission * Register combo admission snapshot in Responses owner inventory * Recheck combo spend consent before child dispatch * Test JEV admission snapshot accessors and exception accounting * Preserve JEV decision usage and snapshot only data descriptors * Revalidate live combo admission and preserve paid decision usage * Recheck key scope before JEV decisions and preserve combo refusals * Restore Chat Completions combo refusal code * fix(combos): admit from a request-start snapshot and recheck spend before paid sends Combo admission (capability gate, vision and sidecar settings, member capabilities, protocols and the post-decision JEV readmission) now reads one detached copy of the config taken when the request starts. The live readmission loop that re-snapshotted the config after the paid decision, and retried on persisted config-generation churn, is gone: a mid-request edit to capabilities, sidecars, protocols or the roster applies to the next request. Immediately before every paid send (the JEV decision call and each combo child dispatch, including failover, cooldown retries and pinned sends) the combo rechecks only live metered consent and the intersection of the ingress scope with the key's current scope. A member failing either is skipped and an eligible sibling may run; otherwise the existing refusal or exhaustion response is returned. The paid decision is recorded before any post-decision refusal, cancellation or exception, so its usage is persisted exactly once. * docs(combos): document the in-flight snapshot and paid-send recheck contract The JEV structure doc, runtime consent section, service logging and usage attribution now describe one request-start admission snapshot with live consent and key-scope rechecks before each paid send, replacing the removed post-decision readmission loop. The English and Spanish combo guides state the user-visible rule and correct the Chat Completions combo refusal code (503 server_error/server_is_overloaded). * fix(combos): plan combo image descriptions with request-start sidecar settings Combo admission read visionSidecar from the live config after awaiting the first describe probe's credential, and the admitted child planned its own description from the live config again. Disabling the sidecar while a request was in flight could therefore flip that request to omission, or to a 400 under onUnservable "reject", although the documented contract is that sidecar edits apply from the next request. The combo now builds its Vision Sidecar settings synchronously from the request-start admission snapshot (which now also copies "reasoning") and passes them as comboVisionSidecar to every canDescribeComboImages probe and to the child it dispatches. responsesVisionConfig applies them only to vision planning; helper credentials and the paid-send consent and key-scope rechecks still read live config. * docs(structure): keep error-detail within the 600-line budget after rebasing onto dev dev grew structure/data-planes/error-detail.md to 599 lines while this branch added five, so the rebased union was 604 and failed structure:check. Fold the combo-ladder scope sentence into the local-refusal paragraph and reflow the combo-exhaustion 503 sentence onto one line; wording is unchanged. * docs(structure): keep error-detail within the 600-line budget after lidge-jun#8907 lidge-jun#8907 added a line to structure/data-planes/error-detail.md, so the rebased union reached 601 lines and failed structure:check. Reflow the combo-exhaustion 503 sentence onto the local-refusal line; wording is unchanged. * docs(structure): keep error-detail within the 600-line budget after merging dev * test(combos): size the small context member for dev's default output reserve lidge-jun#8585 makes combo admission keep at least 1,024 tokens of output room when the caller declares no max_output_tokens. The union context-window cases gave the small member a 1,000-token window, which can no longer admit even a short turn. Raise it to 2,000 so the long body still overflows it and a short turn still fits; assertions unchanged. * docs(combos): describe union context filtering with the combo admission reserve and margin Since lidge-jun#8585 the union gate applies the strict combo admission check (1.1x input margin plus output reserve). Point the English and Spanish Context and Nothing-can-serve bullets at the context-window refusal rules. --------- Co-authored-by: JUN <jun@lidgeai.com>
…un#8757) * feat: add source-preserving Gemini native Antigravity ingress * fix: enforce native Gemini budgets and harden streaming boundaries * test: isolate ingress fixtures from external services and DNS * test: keep remaining native transport fixtures offline * fix: recheck queued Gemini accounts and classify buffered errors * test: isolate Messages context fixtures from native upstream WebSocket * feat: opt into native Antigravity on shared Gemini routes * Require operator consent for native Gemini passthrough * Cover native Gemini response delivery boundaries * Protect native Gemini response delivery * Remove unused synthetic email from Gemini fixture * Make Gemini interactions route test independent of dashboard build --------- Co-authored-by: Liang-Psych <19504206+Liang-Psych@users.noreply.github.com> Co-authored-by: JUN <jun@lidgeai.com>
…ient (lidge-jun#8881) * fix(responses): report the final terminal-guard leg's usage to the client (lidge-jun#8877) The terminal continuation guard re-asks inside one turn, and each leg re-sends the whole conversation. Summing both legs into the client terminal made Chat Completions clients read about twice the real context as prompt_tokens and auto-compact early. The delivery now hands the re-asked legs to the request log through onHiddenUsage, and the client terminal keeps the final leg's usage, the same split the web-search loop uses. * fix(responses): keep a re-ask inside the empty-completion retry off the client usage (lidge-jun#8877) The empty-completion retry builds its own terminal guard. Pass it the delivery's onHiddenUsage too, so a re-ask there reports the final leg's usage to the client while the request log still meters every leg. Pin the max_tokens final leg: it reports its own usage, like any completed leg. * docs(responses): explain terminal guard usage accounting * Keep terminal continuation usage on the issuing OAuth account * fix(responses): settle each re-ask leg on its own send and keep the sum on unsuccessful terminals - Spend ledger (lidge-jun#8902): the transport parse wrapper binds each physical response's usage to the routed send that produced it, so a terminal-guard re-ask, an empty-completion retry and a hosted-search re-ask settle every reservation with its own usage. The last routed send falls back to the aggregate net of the others; a send with no reading stays unresolved. Single-send requests keep the aggregate settlement. - Client usage: the guard splits usage only for a successful terminal; a done cut at a truncating stop reason keeps the sum like incomplete/error. After a hosted-search re-ask, failed and incomplete terminals carry the summed usage and the bridge reports that sum once. - Credits (lidge-jun#8452): a parsed leg without usage marks its issuing attempt's credit total incomplete instead of leaving the parser-built total complete. - Docs: structure/runtime.md notes the outer empty-completion merge (client 25 vs log 35); en/es proxy-formats updated in parity. Drop the undeclared addAccount option from the OAuth fixture. * fix(usage): keep credit marks per attempt, settle in-parse retries once, carry failed Chat usage Three accounting gaps left by the per-leg settlement: - The missing-credit mark was keyed by the live attempt object, which an OAuth rotation reuses for the replacement. A usage-less leg on account A made account B's own 3 credits persist as -1. The mark is now keyed by attempt ordinal and resolved against that ordinal when the parse closes; the request-wide credit total stays incomplete while B keeps its reading. - The per-send recorder was bound at parse start, but Kiro dispatches its completion retry inside that parse and reports one usage for both sends. All of it settled on send 1 and send 2 stayed unresolved at its reservation. The usage now covers every routed send booked since the parse started: the newest carries it, the older ones settle at zero. - A failed Chat terminal ends in an {error} frame, so the summed usage the failed terminal carries never reached the Chat wire. Both Chat encoders now emit it on a choices: [] chunk before the error frame when the client set stream_options.include_usage. * fix(spend): settle an in-parse Kiro retry with its own response's reading Kiro's bounded completion retry is dispatched from inside the first response's parse, and the terminal it yields sums both sends. When the retry fails without metering, that terminal carries only send 1's reading, yet the ledger spread it over every send booked during the parse: send 1 settled at 0 and the retry at 1,550, releasing the retry's reservation for tokens it never reported. Kiro now reports each physical response's reading through src/lib/response-send-readings.ts as soon as it is read, keyed by the response its parse was handed. The transport binds the first reading to the issuing send and each later one to the newest routed send, and ignores the summed terminal for the ledger when readings were reported. Each send settles with its own reading; a retry whose response reported nothing stays unresolved at its reservation. The zero-settlement span binding is removed. * fix(spend): leave a Kiro retry unresolved when only its usage was estimated Kiro reported each physical response's attempt usage on the per-send readings channel, including the local estimate it builds when a response carries no tokenUsage frame. A metered first send followed by an empty HTTP 200 retry (or a retry with a credit meter alone) then settled the retry with that estimate (0 or 12 tokens in the fixtures) and released its reservation, although Kiro reported nothing for it. Kiro now reports a reading only for upstreamReported, non-estimated usage, and reports the retry as absent on its HTTP-failure and post-send factory failure paths. The transport turns an absent reading into an explicit unmetered mark, and both ledger paths (seeded and legacy) leave a marked send unresolved instead of settling it with the aggregate net of the other sends. The client terminal and request log keep the estimate. * fix(spend): settle an estimated Kiro send whose retry never dispatched Kiro marked an estimated first response unmetered as soon as it decided to retry, before the send budget admitted the retry. When a one-send budget refused the retry before dispatch, the first response was still the request's only routed send, yet the mark kept it unresolved at its full reservation instead of settling the estimate as a single send always did. Under a 3,000-token pool ceiling the leaked reservation refused the next identical request. Kiro now reports an estimated first response as absent only once the retry's physical send happens. A metered first response still reports its reading immediately, and a retry that dispatches keeps the explicit unmetered mark on the first send. * fix(spend): settle an estimated Kiro send whose retry timed out before dispatch When the Kiro completion retry's attempt deadline expired before its dispatch receipt, the retry transport returned a synthetic HTTP 504 with no send behind it. The parser still reported the first response's missing reading and an unmetered mark for the retry after the factory returned. Both landed on the request's only routed send, which then stayed unresolved at its reservation instead of settling with the request total. Kiro now reports those post-return readings only when the retry actually dispatched, matching the budget-refusal and factory-throw paths. The usage e2e covers the timeout row with and without a pool ceiling. --------- Co-authored-by: JUN <jun@lidgeai.com>
…jun#8586) * fix(responses): infer phases from terminal snapshot tool work * test: isolate sandbox service identity from live install * test(catalog): bind child reaper assertions to the target process * test: prepare derived caches and bound real process fixtures * test(update): include refusal control in recovery budget * test(catalog): use the existing child-process suite budget * fix(responses): compute snapshot continuation in one scan * test(catalog): measure rejection from the actual deadline * fix(test): strip Windows live environment names regardless of case * Keep live install state out of Bun tests * Fix nested Bun test environment and dotenv guidance --------- Co-authored-by: JUN <jun@lidgeai.com>
… update lint (lidge-jun#8962) lidge-jun#8911 made src/update/managed-release.ts import trustedManagedReleaseOptIn from ../cli/launcher-context. The update lint had no reviewed entry for that edge, so the Windows shards reported an unreviewed static dependency and a raw imported capability reference. The accessor only reads the launch context bound at startup.
Throw EACCES for the legacy NSS directory lookup so the trust regression covers a stat failure independently of OS-specific path length errors.
…-jun#8966) Wait for the owned fixture home to admit native-main traffic before the first Desktop listing. Pin the entitlement version across the listing sequence so the withdrawal assertion exercises the seeded grant.
…idge-jun#8965) The Windows process snapshot gained owner enrichment in lidge-jun#8817: up to 32 GetOwnerSid calls plus refresh reads, bounded by a 1.5 s stopwatch that starts when the owner loop starts. That budget never counted PowerShell startup or the Win32_Process query, which already ran inside the same 5 s enumeration cap. On a fresh GitHub-hosted runner the combined helper outran the cap, windowsProcessSnapshot returned null, and `ocx service install` refused with "the process list could not be read" (service-lifecycle windows-schtasks, dev 62ffebb). Measured on a Windows x64 desktop: the pre-lidge-jun#8817 script took ~0.65 s; the current one takes 1.4-1.6 s with 7 candidates and ~2.3 s with 47, of which the owner loop is ~0.8-1.6 s. Output stays at 116-145 KB against the 16 MB buffer and every row parses. Owner reads now also stop being admitted once the helper is within SNAPSHOT_OWNER_RESERVE_MS (2 s) of the caller's cap, measured from the helper process's own start time, which leaves room for one in-flight 1 s CIM call plus serialization. Skipped owners stay unknown, so binding still refuses an unverified wrapper; the table itself is no longer lost to optional evidence. Fixes dev service-lifecycle windows-schtasks.
…n#8967) Follow-up to lidge-jun#8965: the cap-reached case only exercised the cutoff before each owner read. The new cap-during-owner case moves the cutoff into the past during the first owner read and requires no refresh read.
* feat(step-cli): run StepCode as a Step Plan transport
Adds a `step-cli` preset that spends a Step Plan subscription through StepCode's own
harness instead of calling api.stepfun.com/step_plan directly.
The StepCode CLI exposes `step --sdk-stdio`, a length-prefixed framed protocol with
`sdk-tools` and `permission-callback` capabilities. That surface fits this repository's
tool-ownership contract better than the capture-only MCP server the sibling CLI routes
stage: the client's catalog is declared as inline-schema SDK tools, a call returns as a
`sdk_tool.invoke` reverse request, and no MCP server is written and no tool ever executes
inside StepCode.
Three contract decisions differ from the other CLI families and are documented in
structure/providers/step-cli-transport.md:
- Its own wire, which is not `--mode rpc`'s newline-delimited JSONL. A peer that mixes the
two is answered with silence, so the envelope guard and the decoder are strict.
- One process per conversation. `query.input` reduces every message to text and images, so
an assistant turn, a declared tool call and its result cannot be replayed through the
wire. Sessions are keyed by the handle the client echoes back through `providerState`,
and a process that dies is reported rather than restarted, because tool results already
delivered are not replayable here.
- A bounded tool-result window. StepCode's `SDK_TOOL_TIMEOUT_MS` is 120s and a late answer
produces a `permission_denied` message inside the model's context, so the hold timer is
shorter and reports `step_cli_tool_result_too_late`.
No credential is injected: the CLI resolves its own `step login`, so the child environment
adds only `USER` and a redirected session directory. Handshake rejects a runtime that does
not advertise `sdk-tools`, because such a runtime answers text only while looking healthy.
Verified against a signed-in Step Plan account and a real `step` process: initialize,
query.start with inline tool schemas, permission.request, sdk_tool.invoke, and a final
assistant message that used the tool result.
* fix(step-cli): keep conversations alive across requests and deliver tool results
The first live run against a real `step` process surfaced four defects that no unit
test could have found, each fixed here with the evidence that located it:
- `runTurn` returned right after `query.input` was acknowledged, so the response
reached the client with no terminal event (`incomplete_details.reason =
adapter_eof`). It now awaits the turn's own completion, raced against the
client's abort.
- The framed protocol nests the projected message as `{queryId, message: {...}}`,
unlike `step --mode json` which prints `type` at the top level. Reading
`payload.type` made every turn look idle until it timed out.
- `sdk_tool.invoke` carries the descriptor's BARE `toolName` alongside
`serverName`, not the registered `<serverName>__<toolName>` name. The miss fell
into a denial, and a denial carrying only `{message}` is not a denial to
StepCode: it renders an EMPTY tool result, which the model reports as a command
that ran and produced nothing. `refuseToolCall` now answers with an error frame.
- Nothing owned state across a request boundary. `createStepCliAdapter` runs once
per request, so the session pool and the active turn lived in a closure that was
already gone when the next request arrived: every continuation started a fresh
process and orphaned the tool call it was supposed to release. Both moved to
module scope, following `devin/trajectory.ts`, and the conversation is keyed by
the thread identity Codex sends on every request rather than by persisted
provider state, which is what `devin`, `zed`, `cursor` and `google` all do.
A turn that answers a captured call now delivers the result and does not re-prompt:
the model already has the instruction and is mid-query.
Verified end to end against a signed-in Step Plan account and the installed CLI:
turn 1 returns `function_call shell {"cmd":"echo LIVE_BRIDGE_OK"}`, the client runs
it, and turn 2 returns the command's real output.
* fix(step-cli): keep registry bookkeeping files within their budgets
Three bookkeeping files were rewritten with a JSON pretty-printer instead of surgical
edits, so registering five test files reformatted the whole document:
scripts/test-layout/layout.json 1965 -> 2317 lines
tests/fixtures/test-layout-expected.json 1349 -> 2442 lines
structure/manifest.json 979 -> 1029 lines
The first two crossed the ratchet's 2000-line ceiling for an unlisted file, which is
why `file-size ratchet: repository` failed on this branch and passed at the baseline.
Restored each from 2a3fd00 and re-applied the additions as anchored insertions, so the
only delta is the five registrations (1970 / 1352 / 988 lines).
The preset totals in the docs were the other honest gate: the registry gained one
preset, so all eight locales' guides and quickstarts and the structure ops record now
state 106 presets and 86 key-based.
* fix(step-cli): address every CodeRabbit finding on lidge-jun#7267
Ten findings, all verified against the code rather than dismissed. Three were Major and two of
those were cross-client data leaks that the existing suite could not see — which is the point:
a green suite said the old `default` conversation handle was fine, because nothing tested what
happens when two clients have no identity at all.
Security / data integrity:
- `conversationHandle` returned the shared string `"default"` when a request carried no thread,
session or previous-response identity. Claude Code, Grok Build and generic Chat clients all send
such requests, so unrelated clients shared one StepCode process: one could read another's
context, and a held tool result from one could be delivered into another's query. It now returns
undefined and the caller mints a private ref, so an identity-less request gets its own process.
Verified live against two identity-less requests carrying different tokens: neither saw the other.
- A held tool result was matched by POSITION in the transcript instead of by call id, so a client
that followed a tool call with a user message instead of a result had an older result delivered as
the answer to the current call. The pool now remembers the call id beside the frame id, delivery
requires `toolCallId` to match, and a mismatch refuses the call.
- A client abort left the query running inside StepCode. Since it serves one query at a time, the
next request for that conversation would be rejected or blocked. The abort path now interrupts the
query and closes the session when the interrupt cannot be confirmed.
Stability:
- Concurrent `open()` calls for one conversation each spawned a process; the second
`#entries.set` orphaned the first with an unreleasable held tool call. Opens are now coalesced on
an in-flight promise keyed by handle.
- When a held call expired, no turn received the expiry and no answer reached the runtime, so
StepCode waited out its own 120s window and a later turn could re-emit a duplicate tool call. The
expiry is now answered with a refusal and never re-dispatched.
- stderr was decoded per chunk with `toString("utf8")`, so a CJK character split across chunks
became U+FFFD and the not-signed-in detection that matches 未登录 could stop firing. The stream
is now `setEncoding("utf8")`.
- A spawn `error` (e.g. ENOENT) closed the session without stopping the idle sweep.
Diagnostics / maintenance:
- An undersized length prefix reported "exceeds max frame size" with FRAME_TOO_LARGE, pointing at
the ceiling when the real fault is a truncated stream. It now has FRAME_TOO_SMALL and its own text.
- `STEP_CLI_TOOL_SERVER` was defined twice; the bridge now re-exports the single definition.
- The expiry test slept 560ms of wall clock and went flaky on slow runners. It now injects timers.
Every finding has a regression test (tests/adapters/step-cli-conversation.test.ts plus additions to
step-cli-session.test.ts and step-cli-tool-result.test.ts): 60 step-cli tests, and the full focused
set of 130 across layout, ratchet, preset counts, conformance and registry parity.
Live re-verified after the fixes: turn 1 returns the client's `function_call`, turn 2 returns the
command's real output.
* fix(step-cli): release the runtime's query slot, serialise concurrent turns
Two more defects, both found by driving the real CLI rather than the suite. Neither was
reachable from the previous round's tests, which is the point: the suite exercised tool
continuations and identity-less requests, and both defects lived one layer below that.
A multi-turn conversation could not exist. StepCode's `#maybeFinish` refuses to finish a
query whose input has not ended, and this adapter never sent `query.input_end` — so the
runtime's single query slot was never released and the second turn on a conversation failed
with SESSION_BUSY. The missing call also explains why the tool path worked: a captured call
keeps its query open on purpose, and every earlier live test went through that path. Only a
plain text conversation reaches the broken branch. `query.input_end` is now sent when a turn
settles with a completion, and deliberately NOT when a tool call is captured, because that
query is still owed the client's result.
Concurrent turns on one conversation corrupted each other. This proxy's turn state is keyed
by the single process StepCode serves one query from, so two overlapping turns overwrote each
other's runtime, interrupted each other's query and closed each other's session. Measured
before the fix: two concurrent requests on one `thread-id` both failed, one with
SESSION_NOT_FOUND and the other with step_cli_session_closed. Turns are now queued per
conversation, with a small cap so a pile-up is refused rather than grown.
The queue made a second, subtler failure visible — a turn that waits for a terminal event with
neither a client abort nor a CLI event would hold that queue for the life of the process, so
waiting now has a hard deadline far above StepCode's own 120s tool window.
A third fix falls out of the measurement: a turn settles when the CLI reports `turn_complete`,
which can precede the runtime freeing its slot, so `query.start` retries while the runtime
reports itself busy. The retry is message-based rather than `instanceof StepSessionError`, so a
change of error class cannot silently turn a handover race back into a hard failure.
Verified against the real CLI after the fixes: three consecutive text turns on one thread all
complete with the right answers (TURN1/2/3_DONE), and two concurrent requests on one thread
both complete with distinct answers and no cross-talk. step-cli is now 80 tests; the broader
focused set (layout, ratchet, preset counts, conformance, registry parity) is 130.
* fix(step-cli): make the tool-catalog ceiling legible, verified against real Codex
A stock Codex 0.162.0 client was pointed at this route for the first time, and it failed
immediately: "Invalid StepCode tool catalog: tool catalog exceeds tool count limit".
Measured rather than guessed: Codex declared 1749 tools / 2.5 MB, because it flattens every
MCP server's tools into the function catalog. The shared CLI-family ceiling is 128 tools /
2 MiB — the same bound `qoder`, `codebuddy` and `claude-cli` enforce from the same
`buildCodingAgentToolCatalog` — so this is a family constraint, not a step-cli defect, and
raising it is a maintainer decision rather than something to slip into this PR.
What this changes is the refusal. "exceeds tool count limit" cannot distinguish an oversized
catalog from a malformed one, so an operator reading it had no way to know 1749 tools were
involved or that the bound is family-wide. It now names the declared count, the ceiling, and
the operator action (disable or narrow MCP servers for this provider). Failing closed is
deliberate: a tool the client believes exists but that never reaches the model is worse than a
refusal.
Same client, with MCP servers stripped, drives the route end to end:
text turn -> codex replies CLEAN_CODEX_OK
tool turn -> codex runs /bin/zsh -lc 'echo CLEAN_TOOL_OK' (succeeded in 0ms)
and reports the output verbatim
So the tool really is executed by the client, which is the whole point of the route.
The constraint is now stated in the registry note, the structure contract and the docs-site
section with the measured numbers, so nobody has to rediscover it by hitting it.
step-cli is 81 tests; the broader focused set stays at 130.
* fix(step-cli): close live StepCode processes when the proxy stops
A 14-turn conversation on one thread held up: 0 failures, and exactly one `step` process
for all 14 turns, which is the reuse this route is built on. The same run also surfaced a
leak — a `step` process from an earlier probe was still alive after its proxy had been
stopped.
The sibling CLI routes cannot leak this way: they spawn a child per request and kill it in
a `finally`, so it cannot outlive a turn. This route deliberately keeps a process alive for a
whole conversation, so nothing was killing it on shutdown, and an orphaned `step` holds the
user's subscription session open. Sessions now register through `registerOptionalShutdownHook`,
which `server/lifecycle.ts` runs on stop.
Measured after the change: one `step` process during a turn, zero after the proxy is stopped
(previously one survived).
Tests: 82 step-cli tests, the broader focused set unchanged at 130.
* fix(step-cli): forward non-text tool results instead of collapsing them
A tool result is not necessarily text. `latestToolResult` concatenated only the text
parts and dropped everything else, which for a result carrying an image meant an empty
text block reached the model — the same misleading-"the tool returned nothing" failure the
wrong-call path already had, in a second place.
Content is now projected onto the blocks StepCode's SDK tool accepts (`text`, and `image`
as base64 + media type). Block boundaries are preserved rather than concatenated, because
StepCode maps each block 1:1 and joining would erase the difference between e.g. a tool's
stdout and its stderr. An inline `data:` image is forwarded; a remote URL cannot be, so it
becomes a note the model can act on instead of vanishing; a result with nothing readable
says so rather than looking empty.
Scope note: on the standard Codex path this layer is upstream of the adapter —
`src/vision/image-rewrite.ts` already rewrites image tool results to an explanatory
`[image omitted: this model is text-only ...]` placeholder for a text-only row. A live run
confirmed the model receives that explanation rather than an empty result, so this change
is the residual path (clients outside the vision rewrite, or a disabled sidecar), not the
fix for that case.
Live checks this round, against the real CLI:
real client abort mid-turn -> 0 step processes left, and the same thread's next
request completes normally
three threads concurrently -> all completed, each with its own answer, no cross-talk
four conversations -> four processes, all reclaimed on proxy stop
* fix(step-cli): refuse a busy conversation with an explained, retryable error
The per-conversation queue added last round caps how many turns may wait, and the refusal
threw straight out of `runTurn` — an unhandled rejection, not an event on the stream. Every
other failure on this route becomes an error event, so this one path handed the caller a
generic failure instead of saying what happened. It now emits a retryable 409
(`step_cli_conversation_busy`) naming the conversation and the queue depth, then closes the
session it had just opened.
That refusal is the only thing standing between a retry storm and an unbounded wait, so it now
has its own coverage: turns on one conversation run in arrival order, separate conversations
never wait on each other, and a pile-up past the cap is refused instead of queued.
Also verified this round, against the real CLI:
a compaction turn arriving WHILE a tool call is held -> produces the synthetic `compaction`
item with no error, and the same conversation's next ordinary turn still completes. The
concern that a compaction turn would park state on the parent conversation (a bug cursor hit
in the same area) does not apply here.
step-cli is 90 tests; the broader focused set stays at 130.
* fix(step-cli): register the turn before delivering a held tool result
Answering a held `sdk_tool.invoke` unblocks the CLI, and the CLI may answer with frames the
moment it does. The turn was registered AFTER that delivery, so any frame arriving in between
found no runtime to route it to, was dropped, and the turn then waited out its deadline on a
model that had already answered.
The turn is now registered first and the result delivered second. The decision about what this
turn IS (answer to the held call, abandoned call, or a fresh user message) was also hoisted
above the delivery so nothing inspects the transcript after a side effect.
The regression test makes the race deterministic rather than timing-dependent: the fake emits
`turn_complete` synchronously INSIDE `resolveHeldToolResult`. Reverting the order turns that
test red and restoring it turns it green, which is how the fix was confirmed to be the thing
the test is actually pinning.
step-cli is 91 tests; the broader focused set stays at 130.
* refactor(step-cli): split the adapter into five modules with a one-way graph
`adapter.ts` had grown to 957 lines carrying eight unrelated concerns: process lifetime, turn
runtime state, conversation serialisation, pool registry, shutdown wiring, frame mapping,
request projection and error wording. Everything about this route is now readable in one place
per concern, and the turn loop is the only thing left in the file that decides anything.
adapter.ts orchestration only: what one turn is, in what order, when it is terminal
conversation.ts conversation identity (which thread owns which process) and turn ordering
events.ts what the CLI says and what this peer owes it back
projection.ts pure request/response conversions, testable without a session
registry.ts the state that must outlive a request, plus shutdown wiring
errors.ts failure text and the status a client can retry on
The dependency graph is one-way: adapter → {conversation, events, projection, registry, errors},
events → {projection, registry, registry → pool, and nothing imports adapter. Two edges had to be
cut to keep it that way — `poolFor` now takes the session handlers as an argument instead of
importing `events`, and the idle timeout moved to `registry` where the pool that uses it lives.
`adapter.ts` went 957 → 394 lines. Behaviour is unchanged: 91 step-cli tests and the broader
focused set (121) pass, and the gates are green. The tests now import each symbol from the module
that owns it, so a move shows up as an import error rather than a silently relocated export.
Also removed a stray block left in `driveTurn` by an earlier patch.
* refactor(step-cli): keep modules from reaching into each other's state
Post-split review found the split was only half done: `events` and `adapter` were still
reading and writing `registry`'s WeakMaps directly (`turnRuntimes.get/delete`,
`lastAssistantUsage.set`, `lastQueryId.get/set`). That is exactly the coupling the split was
meant to remove, and it would have pinned the storage shape into three call sites.
`registry` now exposes semantic accessors — `beginTurn`, `currentTurn`, `endTurn`,
`recordAssistantUsage`, `assistantUsage`, `rememberQuery`, `currentQuery`, `forgetQuery` — and
the maps stay private to it. "Who owns this session's turn" is answered in one module.
Behaviour unchanged: 91 step-cli tests, the 130-test focused set, and the gates all pass, and
the full suite was compared against the clean baseline worktree in an interleaved window
(mine 160/0 and 160/0; baseline 159/1 and 160/0) after an un-interleaved comparison had
produced 66 phantom differences under load.
The structure contract now records the module layout and why the two dependency edges are cut
the way they are.
* docs(step-cli): name the remaining modules in the contract's layout table
The table listed six modules and then jumped to 'the framed transport itself', so
`env.ts`, `profiles.ts` and `constants.ts` were undocumented even though `session.ts`
depends on all three. Found while checking the refactor's dependency graph: the layering only
holds if those edges are written down.
* fix(step-cli): recover a turn that ends without a terminal event
The guard deciding "nothing terminated this turn" read
`if (!currentTurn(session) !== undefined) return;`. `currentTurn` returns a
turn or `undefined`, so `!currentTurn(...)` is always a boolean, and a
boolean is never `undefined` — the comparison was therefore always true and
every statement after it was dead code.
Introduced by the `refactor(step-cli): keep modules from reaching into each
other's state` commit, which mechanically rewrote the correct
`if (!turnRuntimes.has(session)) return;` while introducing the semantic
accessors: the opposite of that commit's stated goal.
Impact: on a client abort or the ten-minute terminal deadline, the recovery
never ran — no `step_cli_turn_abandoned`, no settle, no interrupt, no close.
The turn kept its registration and its query kept running inside StepCode,
which serves one query per process, so the next request on that conversation
collided with the abandoned one. A stream that simply stops is also
indistinguishable from a hung proxy.
The suite could not have caught it: on every tested path a terminal event
ends the turn first, which makes the guard's wrong branch indistinguishable
from the right one. Added coverage for the two paths that reach it — the
client abort and the deadline, the latter driven by an injected timer rather
than a ten-minute sleep — plus the normal-completion case that must NOT
recover, so the fix cannot be a blunt always-recover.
Also drops four orphaned doc comments the same refactor left behind.
* chore(repo): keep Bun's build cache out of history
Two 59.8 MB copies of Bun's on-disk build cache reached this branch's
history through a broad `git add -A`. Bun writes `<hash>-00000000.bun-build`
into whichever directory it runs in — here, the repository root — and the same
file reappears under a new hash on the next run, so a committed copy is pure
weight that nothing in the build, typecheck, or test path ever reads.
An ignore rule is necessary but not sufficient, for the same reason this repo
already guards `go/` and `.codexclaw/`: once a path is tracked, `.gitignore`
stops applying to it entirely. So the assertion belongs next to those, against
the real index.
This is the same shape as the mistakes this file already documents — `go/`'s
config_parity.go committed three times, the root `docs/` folder at 4.9 MB —
which is why the guard is an index assertion rather than another comment.
* chore(step-cli): drop a write-only turn field and duplicated doc blocks
`StepTurnRuntime.done` was assigned in `beginTurn` and never read by
anything: `driveTurn` awaits the local promise it created, and the runtime
needed only `settle` for the other callers. A field nothing consumes reads
as if it were part of the contract, so the next reader has to prove it
unused before trusting the surrounding code.
Also collapses the duplicated doc comment on `lastQueryId` and the orphaned
one-shot line that lost its declaration when `MAX_QUEUED_TURNS` moved to
`conversation.ts`. Both are leftovers of the module split.
* fix(step-cli): keep queue refusals off the owner's session and guard a held call with no result
Addresses review at 17ce58e: a turn refused at MAX_QUEUED_TURNS never owned the conversation, so it no longer closes the session serving the accepted turn and its queue. A held call followed by user text with no toolResult no longer dereferences an undefined result; the held frame is refused and the new text runs. Both covered through runTurn with an injected session.
* test(layout): register step-cli tests in their own explicit shard
Adding the seven step-cli entries to layout.json took it to 2006 lines,
past the file-size ratchet's 2000-line threshold. Move them into
layout-step-cli.json and list it in explicitShards, as the other
feature shards do, which brings layout.json back to its 1999 lines on dev.
* docs(structure): fold the StepCode transport pointer into the coding-agent paragraph
Keeps structure/providers-and-adapters.md within its 600-line budget after merging dev.
* fix(step-cli): bind caller and query ownership through shutdown
Namespace sessions and held calls by the admitted principal and physical
provider. Keep keyless requests private and close failed handshakes.
Correlate runtime callbacks and declared permissions with the exact query,
retain the held call's catalog, and drain an abandoned query before its
replacement acquires a turn. Latch pool shutdown and drain outstanding opens.
Reuse the coding-agent Windows process-tree terminator with a deadline and
verify OS exit before releasing handles. Preserve bounded POSIX group cleanup.
Port the independent review probes into registered adapter regressions.
Baseline b833c1f: 1 pass / 13 fail. Fixed focused run: 325 pass / 0 fail.
Typecheck, structure, privacy and documentation build passed.
Co-authored-by: Hong Liu <88263959+Hylouis233@users.noreply.github.com>
* fix(step-cli): retain cleanup ownership through termination failures
Reserve closing and quarantined handles, bound termination to two attempts,
and drain cleanup receipts started before pool shutdown. Retain failed pools
through registry clears so they cannot admit replacement processes.
Co-authored-by: Hong Liu <88263959+Hylouis233@users.noreply.github.com>
* test(step-cli): bound registry fixture lifetime and spawn deadlines
Flush the isolated registry observations and exit the fake-only helper when
they are complete. Await its subprocess asynchronously with the named
internal deadline below the spawn test budget. Preserve quarantine assertions.
Publish native fixture PIDs atomically after reproducing a partial JSON read.
Co-authored-by: Hong Liu <88263959+Hylouis233@users.noreply.github.com>
* test(step-cli): warm the registry fixture and wait for native reaping
* docs(step-cli): publish English and Spanish guides and recount presets
* docs(structure): record shared Windows taskkill deadline
* fix(gui): classify StepCode as a paid subscription CLI
* fix(gui): use adapter-specific subscription details in classic setup
* fix(step-cli): correlate official SDK callbacks to the active query
* fix(step-cli): classify child failures before publishing errors
* fix(step-cli): await shutdown and confirm POSIX process-group exit
* fix(step-cli): resolve executable and workspace before spawn
* fix(step-cli): keep tree cleanup within the proxy stop window
Await an asynchronous Windows taskkill receipt and cap concurrent
session cleanups across pools. Preserve cleanup retries, quarantine, and
the synchronous process-tree helper used by other CLI adapters.
Use the configured drain deadline and the controller's exit grace for
the optional teardown join, leaving time for listener cleanup and exit.
* fix(step-cli): use the proxy stop deadline for tree cleanup
Share the stop deadline with active and queued session closes, and
escalate before the deadline to leave time for exit confirmation.
Sweep remaining owned POSIX groups synchronously on incomplete
shutdown and start queued Windows tree kills even if slots are busy.
* fix(step-cli): require ownership for process group cleanup
Keep POSIX group disappearance sticky across probes, retries, and
emergency teardown. Revalidate through the unreaped leader after a
failed attempt, and report unverified cleanup without signalling
the group.
Exercise the emergency sweep with an inert process table and wait
for actual fake-child cleanup in the run-turn shutdown test.
* fix(step-cli): limit process group signals to live leaders
Use the detached child handle to gate every POSIX group signal and to
confirm exit after escalation. Quarantine the session if its leader
exits before group termination, including during an emergency sweep.
* test(gui): verify shared subscription CLI warning copy
* docs(step-cli): record accepted POSIX cleanup risk
* chore(step-cli): reconcile preset counts and layout with dev
* fix(step-cli): guard process cleanup and cancelled dispatch
* docs(step-cli): record the accepted Windows cleanup risk
* docs(providers): recount presets after rebasing StepCode
* test(step-cli): cover cleanup rejection after terminal event
* fix(step-cli): handle terminal cleanup rejection
---------
Co-authored-by: mavis <mavis@local>
Co-authored-by: Hylouis233 <Hylouis233@users.noreply.github.com>
Co-authored-by: JUN <243035832+lidge-jun@users.noreply.github.com>
Co-authored-by: JUN <jun@lidgeai.com>
Brings 82 upstream commits, including: - lidge-jun#8889: extra_usage monthly reading - lidge-jun#8815: hosted advisor spend ceilings - lidge-jun#8900: sealed credential refusals Conflicts were resolved so that both upstream behavior and every AR contract survive. Where upstream restructured a module (cache-provenance, physical-send callbacks, sealed refusals, observeNativeMessagesChunks), the overlay was adapted to the new structure. Co-Authored-By: Claude Code <noreply@anthropic.com>
The OAuth usage endpoint reports usage credits ("extra usage") in its `spend` row: amount spent, monthly spend cap, prepaid balance and the reason credits are off (e.g. `out_of_credits`). Upstream reads only an on/off/used-up state, plus a monthly percent for seats without plan windows. No amounts reach the operator.
This parses `spend` (falling back to `extra_usage` minor units) into a display-only `claudeUsageCredits` quota field. `ocx account list anthropic --quota` renders it as e.g. `credits $17.30 of $100.00 off (out_of_credits)`. The field never feeds routing or exhaustion, so `creditsUsd` semantics are unchanged.
Co-Authored-By: Claude Code <noreply@anthropic.com>
- Return the committed version line to plain upstream 2.100.0. Fork builds stamp `-vadymhimself.N` at pack time only, so the release version-line and preflight tests hold. - Count our `xai-apikey` preset in the docs (113 presets, 91 key-based) across every locale and the structure ops record. - Move `normalizeCostTokens` into the leaf module `src/usage/cost-tokens.ts`. cache-provenance shares the pricing decomposition without the import cycle that the cycle ratchet rejects. - In upstream's committed-terminal cooldown fixture, record each attempt's send. The AR physical-attempt invariant counts only attempts that reached upstream. Co-Authored-By: Claude Code <noreply@anthropic.com>
…bridge Upstream lidge-jun#8815 withholds or refuses the hosted Advisor when a token spend ceiling applies. The AgentRadar exact canonical relay sends caller bytes unchanged, so on a hosted gateway it forwarded the Advisor declaration anyway. That consults a larger model outside the ceiling. Route a hosted canonical turn that declares or replays the Advisor to the bridge whenever a spend ceiling is configured. Without a ceiling the exact native relay is unchanged. Also add the regression and the credits parser test to `test:gateway-quota`. Co-Authored-By: Claude Code <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This refreshes the fork's
main(the upstream-derived AR line) onto current upstreamdevd61cca122d, a merge of 82 upstream commits, and adds a Claude usage credits view.52184b0c19merge commit. It brings in upstream feat(anthropic): report monthly usage from extra_usage when no plan window is present lidge-jun/opencodex#8889 (extra_usage), fix(anthropic): withhold hosted advisor under captured spend ceilings lidge-jun/opencodex#8815 (hosted Advisor spend ceilings), fix(usage): retain same-account credential recovery attempt outcomes (carries #8882) lidge-jun/opencodex#8900 (sealed credential refusals) and the rest. Three parallel lanes resolved 51 conflicted files, keeping both upstream behavior and every AR contract and adapting the overlay where upstream restructured modules: cache-provenance, physical-send callbacks, sealed refusals andobserveNativeMessagesChunks.22515250ddfeat(anthropic): Claude usage credits. It parses the OAuth usagespendrow (falling back toextra_usage) into a display-onlyclaudeUsageCreditsquota field. The field never feeds routing, socreditsUsdsemantics are unchanged.ocx account list anthropic --quotanow shows, for example:credits $17.30 of $100.00 off (out_of_credits)credits $0.00 of $0.00 off (org_level_disabled_until)882ac28e55post-merge contract fixes:2.100.0. Fork builds stamp-vadymhimself.Nonly at pack time.xai-apikey(113 presets, 91 key-based).cost-tokens.tsmodule breaks a new import cycle.1f4efcab86real quota-burn fix found by hosted-mode triage. Under a spend ceiling, the hosted exact canonical relay forwarded the caller's hosted Advisor: one wire, where upstream refuses with zero. Such turns now take the bridge, which withholds or refuses the Advisor. Without a ceiling the exact relay is unchanged. A regression test was added totest:gateway-quota(mutation-checked).Verification
All runs used pinned Bun 1.4.4 with an isolated
HOME/OPENCODEX_HOME.Typecheck, structure, privacy,
git diff --checkand the file-size ratchet pass.bun run test:gateway-quota: 550 pass / 0 fail across 31 files.Full suites, run sequentially on this machine:
d61cca122dFlag off: after the post-merge fixes, every failing name not in upstream's set passes on targeted rerun (one 925 s straggler passed alone in 4 s). The full flag-off suite was not rerun after the fixes.
Flag on: 120 names fail that were not in the previous candidate's triaged flag-on set. They are triaged in
/private/tmp/ocx-r2-on-triage.json:p<hex6>labels;.27behavior: headerless-429 rotation, hash seat, exact-source caller bytes, strict tap;This is not a green flag-on suite.
Package
2.100.0-vadymhimself.3(sha2564080e7485934d17aa6a0758b1865e64a05b6adbeb558d6eb48f54ef82ff0b552):/healthz200, dashboard 200..3withOPENCODEX_AGENTRADAR=1. The liveocx account list anthropic --quotashows the credits column for every account with a usable token.The fork's GitHub Actions is still disabled, so there is no CI result. Not yet soaked on the Mini.
Known follow-ups
spend.identityceiling are refused before dispatch, where upstream serves them with the Advisor withheld. This is fail-closed, with no burn. No ceiling is configured on the laptop or the Mini.Checklist
🤖 Generated with Claude Code