Commit Graph

167 Commits

Author SHA1 Message Date
Luis Pater
47f18e4d82 fix(pluginhost): preserve scheduler routing across reconfigure, hot reload, and dir errors
- Keep the previous registration on explicit reconfigure rejection, require rollback confirmation after post-accept registration failures, and preserve the current snapshot when reading the plugin directory fails.
- Coordinate scheduler picks across hot reloads with atomic active-record discovery, bounded reload waiting, a single generation-aware retry, and full-tier candidate preservation for replacement schedulers.
- Add deterministic regression tests covering rejected and post-accept reconfigure failures, hot-reload waiting and retries, concurrent publish discovery, across-priorities upgrades, and directory read errors.

Closes: #8519
2026-11-27 00:48:00 +08:00
Luis Pater
830b9cac8f test(pluginhost): align unix plugin reload test with fresh-image contract
- Update the third Open assertions in TestUnixPluginReloadAfterShutdownUsesReplacedFile to verify that reopening unchanged plugin content maps a fresh handle and distinct shadow copy instead of reusing a shut-down resident image.
- Assert that the freshly mapped image starts with the baseline shutdown call count rather than inheriting the shut-down image's package globals.

Closes: #8516
2026-11-27 00:25:24 +08:00
Luis Pater
0aaf6d1c3a Merge pull request #8515 from router-for-me/acp
feat(home): add local plugin executor dispatch
2026-11-26 20:00:35 +08:00
hkfires
6acc778c0f feat(home): add local plugin executor dispatch
Authorize acp/ models via Home local-plugin-dispatch and run
the selected plugin executor without upstream credentials.
Validate plugin version, config digest, host/Home fences, and
the authorized model across execute, stream, and count paths,
while falling back to credential dispatch for legacy Home.

Preserve before-auth interception, usage attribution, payload
finalization, and router exclusions for delegated requests.
Expose static executor models and avoid reusing resident
shadow plugin images on reload.
2026-11-26 19:16:36 +08:00
Luis Pater
8fa71b6203 test(pluginhost): isolate usage capture across home executor tests
- Drain the global default usage queue via a FIFO barrier in registerTestUsagePlugin before registering capture plugins so queued records from earlier tests are not delivered to subsequent tests.
- Assign unique credential IDs per TestHomeExecutorDispatchLifecycleRejections subtest and wait for the cancellation usage record in TestHomePluginDispatchReleasesOnStreamCancellation to prevent async cross-test bleed.
- Add a deterministic channel-gated regression test verifying that registerTestUsagePlugin drains preexisting queued usage records before capture registration.

Closes: #8163
2026-11-26 03:30:26 +08:00
Luis Pater
b47cd8e8f9 Merge pull request #8119 from router-for-me/home
feat(home): delegate Home dispatch to plugin executors
2026-11-25 18:13:04 +08:00
hkfires
4c8df6d7f9 fix(pluginhost): gate home executor dispatch on lifecycle state
Bind Home executor adapters to the exact loaded plugin instance
and require it to remain enabled, unfused, and not suspended with
matching executor capabilities before dispatch.

Suspend Home dispatch at the start of quiesce, restore it only
when a recovered instance republishes capabilities, and recheck
availability immediately before execute, streaming, and token
counting. Map closed-client and plugin_quiesced races to the
Home executor unavailable error so dispatch can reselect instead
of surfacing a plugin lifecycle failure as an upstream error.
2026-11-25 17:57:59 +08:00
hkfires
27e7618dc8 fix(home): report antigravity project discovery failures
Publish upstream 401 and 429 responses from Antigravity project
discovery during home auth preparation so credential failures are
attributed using the effective token and upstream model.

Thread the upstream model through prepareHomeRequestAuth via
context and generalize the home credential failure publisher to
support non-401 statuses. Add coverage for execute, stream, and
count paths, including delegated plugins and refreshed tokens.
2026-11-25 17:36:53 +08:00
hkfires
ad2edae0b6 feat(home): delegate Home dispatch to plugin executors
Advertise ready executor plugins and their supported credential
providers in Home auth dispatch, and let Home select a plugin via
executor_plugin. Resolve the live plugin bound to the credential
provider, prepare credentials through the provider preparer
including Antigravity token refresh, and preserve the upstream
model and model info for plugin execution.

Add the ExecutorAuthProviders capability over the plugin RPC
boundary and surface unavailable Home plugin executors as a
terminal 503 without retrying other credentials.
2026-11-25 16:29:20 +08:00
hkfires
bc74887abb Fix cross-platform tests and Git worktree handling 2026-11-25 16:00:11 +08:00
Luis Pater
60abf6ba15 fix(pluginhost): advertise Windows plugin support without cgo
- Select the plugin-capable support flag on Windows even when CGO is disabled.
- Add a regression test for Windows no-CGO build constraints.

Closes: #7977
2026-11-24 08:36:11 +08:00
Luis Pater
254d0c2c0c fix(pluginhost): fall through to next scheduler plugin when PickAuth declines
- Iterate active scheduler plugins in priority order in Host.PickAuth, propagating accumulated ExcludeCandidates across declining schedulers and merging them into DelegateBuiltin responses while preserving explicit termination on selection, rejection, or error.
- Aggregate SchedulerWantsAcrossPriorities across active schedulers, supply the full available candidate pool from auth.Manager when multiple schedulers are active while narrowing each non-across scheduler to the highest remaining tier, and include slice length in metadataCloneVisit to prevent overlapping-slice cloning corruption.
- Update and expand unit and manager integration tests covering multi-scheduler fallback, exclusion propagation, per-scheduler tier narrowing, and metadata cloning isolation.

Closes: #7781
2026-11-22 14:02:46 +08:00
Luis Pater
221d5e0818 fix(auth): check active plugin scheduler in affinity lookup and normalize mixed legacy provider keys
- Use hasPluginScheduler() in LookupSessionAffinity so attached plugin hosts without an active scheduler plugin do not falsely return unsupported.
- Normalize executorKeyFromAuth with canonicalSchedulingProvider in pickNextMixedLegacy and warnLogAuthUnavailable to match providerSet keys across all scheduling paths.
- Add regression tests covering inactive plugin scheduler state in LookupSessionAffinity and host.affinity.lookup, plus provider alias handling in pickNextMixedLegacy and warnLogAuthUnavailable.

Closes: #7761
2026-11-21 20:26:16 +08:00
Luis Pater
6e7a1b294a fix(api): decode gzip request bodies and honor Content-Encoding on Claude routes
- Add gzip/x-gzip support to the shared request body decoder with the configured decoded-size cap, and drop Content-Encoding after a successful decode so nothing downstream decodes or forwards it again.
- Switch ClaudeMessages and ClaudeCountTokens to handlers.ReadRequestBody, and mirror the change in the plugin auth pre-decode path (gzip support, plus /v1/messages and /v1/messages/count_tokens in handlerDecodesBody) and the request-log capture decoder.

Closes: #7711
2026-11-20 10:49:38 +08:00
Luis Pater
5bfae62919 feat(plugin): support credential-scoped after-auth request termination
- Add TerminateScope to plugin and executor after-auth interceptor responses so plugins can refuse a single selected credential with exact scope "credential" while keeping request-scoped termination as default.
- Exclude refused credentials for the remainder of the request across normal, count, streaming, Home dispatch, retry rounds, and Antigravity credits fallback without mutating shared cooldown state.
- Preserve real upstream error precedence over plugin credential refusals and plugin refusal precedence over local non-upstream errors, with regression tests across pluginhost, handlers, and auth conductor paths.

Closes: #7656
2026-11-19 23:59:02 +08:00
hkfires
edab77507b feat(home): enable home-backed codex continuity
Negotiate the scheduler protocol from Home config and use it to
gate Codex continuity through Home instead of a local plugin
scheduler. Send transport-safe scheduler context with auth
dispatch and propagate the returned selection ID through
execution metadata and usage reporting, preserving scheduler
completion feedback even when local statistics are disabled.

Run pre-admission and pre-output 429 continuity gates with
bounded cooldown waits for Home streaming and non-streaming
execution, handle scheduler_rejected as a terminal pick
failure preferring the last upstream error, and preserve the
upstream attempt provider across retry-round errors.
2026-11-19 20:59:09 +08:00
Luis Pater
bd2e0a98a6 feat(plugin): add explicit Kind field to ResponseInterceptRequest
- Add Kind as the leading field on pluginapi.ResponseInterceptRequest with model_list, execution, and count_tokens constants, and document fallback and open-map metadata rules.
- Populate Kind across all five response interceptor construction sites (auth-manager execute/count, plugin-executor execute/count, and WriteModelListResponse) and verify leading-byte RPC serialization and /v1/models/{id} detail routing.

Closes: #7655
2026-11-19 00:26:16 +08:00
Luis Pater
76bae1fe41 fix(pluginhost): move reload test constructors out of cgo preamble
- Move C constructor definitions and mutable test hook state from the //export cgo preamble in main.go into a dedicated hooks.c translation unit so cgo does not emit duplicate constructors.
- Append grandchild PIDs safely with pre-fork lock setup and verify exact child count and descriptor lock release during test cleanup.
- Add a cgo preprocessing regression test verifying that _cgo_export.h, _cgo_export.c, and main.cgo2.c contain no constructor definitions.

Closes: #7647
2026-11-18 20:26:44 +08:00
Luis Pater
f7b3ccdff9 feat(pluginhost): expose cache write TTL token counts in usage.handle
- Add optional CacheCreation5mTokens and CacheCreation1hTokens pointer fields to pluginapi.UsageDetail while preserving aggregate CacheCreationTokens.
- Forward independent pointer copies via coreusage.CloneInt64Ptr in usageAdapter.HandleUsage to preserve missing versus explicit zero values across streaming and non-streaming paths.
- Add SDK, adapter, RPC schema, and Claude streaming/non-streaming regression tests.

Closes: #7630
2026-11-17 20:34:47 +08:00
sususu98
687caf786b feat(plugin): add optional executor usage attribution 2026-11-17 17:56:16 +08:00
Luis Pater
72f7b6b88e test(pluginhost): expect clamped 10s retry-after floor in rpc error test
- Update TestPluginErrorCarriesRetryAfterIntoCooldownAndHTTPHeader to expect the 10s pool Retry-After header after commit 4da9f685.
- Update the model NextRetryAfter assertion and comment to reflect the 10s minQuotaCooldownFloor clamp applied by MarkResult.

Closes: #7607
2026-11-17 03:29:45 +08:00
Luis Pater
7fcdfcfe17 feat(plugin): add bounded Codex scheduler continuity hook
- Add optional `scheduler.continuity` plugin ABI/RPC hook with bounded `pre_admission` and `pre_output_429` wait gates, persisted cooldown provenance separation, and SSE/WebSocket keepalive handoff.
- Enforce per-request continuity budgets, `disable_cooling` retry limits, and stable turn `RequestID` across SSE bootstrap retries and WebSocket in-place failover.
- Add race-verified unit and handler integration tests covering continuity gates, cooldown provenance, keepalive suppression, and session isolation.

Closes: #7589
2026-11-17 03:22:51 +08:00
Luis Pater
508f8708d0 chore: replace standard JSON package with moego JSON throughout the project 2026-11-16 09:58:12 +08:00
Luis Pater
b4fdfdece3 chore: replace standard regexp with moego regexp throughout the project 2026-11-16 03:02:43 +08:00
Luis Pater
95ebe39c1d fix(management): preserve plugin credential identities in v8 upload and delete
- Reconcile v8 credential uploads through SynthesizeAuthFile without redundant local store rewrites, preserving plugin-assigned IDs, FileName values, multi-record expansions, and symlinked destinations while retiring stale records from overwritten files.
- Pass synthesis fallback AuthDir out-of-band during plugin parsing so omitted IDs resolve relative to AuthDir without mutating AuthParseRequest.Host or overriding explicit path-based IDs.
- Remove all in-memory auth records backed by a deleted file in v8 credential deletion and snapshot handler config under lock for race-free synthesis.

Closes: #7557
2026-11-15 15:47:48 +08:00
Luis Pater
22d40703f2 feat(scheduler): support ExcludeCandidates in plugin scheduler fallback and delegation
- Add ExcludeCandidates with PascalCase and snake_case ojson decoding to pluginapi.SchedulerPickResponse and preserve normalized exclusions in pluginhost when unhandled or delegated.
- Filter excluded auth IDs per selection pass in Manager before priority tiering and built-in selector evaluation so healthy lower-priority credentials can promote without mutating caller tried state.
- Add unit tests covering JSON/RPC compatibility, host normalization, priority promotion, session affinity, and cooldown/empty-pool errors.

Closes: #7535
2026-11-14 19:12:07 +08:00
Luis Pater
7904efd799 feat(management): expose registered plugin runtime priority on v8 plugin listing
- Add Priority *int to pluginListEntry, populated from the host RegisteredPlugins snapshot so clients can verify effective ordering, including zero and negative values.
- Gate exposure to the maintained v8 route while leaving the deprecated v0 response shape unchanged, and add RegisterPluginWithPriorityForTest to cover non-default priorities in tests.

Closes: #7522
2026-11-14 03:36:51 +08:00
Luis Pater
5b63e29acf fix(pluginhost): keep OAuth plugin models credential-bound and catalog-safe
- Default credential-bound plugin executors to OAuth model scope and skip static ModelRegistry clients unless ExecutorModelScopeStatic is explicitly set.
- Keep StaticModels catalog collection enabled for OAuth-scoped plugins without leaking static models into ModelRegistry or credential fallback appends.
- Decouple OAuth executor provider binding from catalog provider names and add regression coverage for exclusions, aliases, disabled state, and management catalog definitions.

Closes: #7512
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-13 23:09:47 +08:00
Luis Pater
14e577174a fix(pluginhost): support credential-scoped rate limit errors from plugin executors
- Add optional credential_scoped metadata and documented routing/cooldown error code constants to pluginabi.Error so plugin executors can report account-wide 429 limits.
- Preserve credential-scoped classification on rpcError across synchronous RPC envelopes and streaming error callbacks while prioritizing credential quota scope over model-only or cooldown-skipping error codes.
- Recognize credential_quota error codes in core auth cooldown classification and cover whole-credential cooldown propagation and error events with regression tests.

Closes: #7359
2026-11-09 03:19:45 +08:00
Luis Pater
0074897481 feat(pluginhost): expose token modality details in usage.handle
- Extend pluginapi.UsageDetail with optional modality token counters matching core usage.Detail.
- Forward independent pointer copies of modality counters in usageAdapter.HandleUsage so plugins receive full breakdown details.
- Add adapter, SDK, and RPC regression tests covering populated, explicit zero, and absent modality counters.

Closes: #7352
2026-11-08 20:52:39 +08:00
Luis Pater
b5b724d06d fix(pluginhost): reuse content-addressed plugin shadow copies across restarts
- Reuse existing content-addressed shadow binaries in `<plugin_dir>/.shadow` (with a per-directory shared cache fallback) and verify target digests before creating any temporary files.
- Publish shadow binaries without unlinking active targets and coordinate plugin loading with stale shadow cleanup via OS-level file locks.
- Add regression tests covering cross-restart shadow reuse, zero-write cache hits, fallback isolation, and concurrent load/prune coordination.

Closes: #7323
2026-11-07 18:10:39 +08:00
Luis Pater
482efbf5a7 feat(auth): enhance OAuth provider handling with explicit hints and metadata preservation 2026-11-07 04:38:59 +08:00
Luis Pater
1c53721167 fix(auth): keep count_tokens 501 and unsupported capability responses availability-neutral
- Classify HTTP 501 and typed unsupported count_tokens errors as availability-neutral in isCountTokensEndpointNotFoundError while preserving explicit model-not-found, auth, and quota cooldowns.
- Expose ErrorCode() on plugin RPC and auth error types so resultErrorFromError retains structured plugin error codes during count_tokens execution.
- Add regression tests verifying that repeated count_tokens 501 responses neither suspend inference availability nor extend active model cooldowns.

Closes: #7271
2026-11-05 19:25:12 +08:00
Luis Pater
6e10359968 fix(pluginhost): abort hot reload on quiesce failure and coordinate usage replay
- Abort replacement loading and roll back the active plugin when plugin.quiesce fails with an operational error or panic while keeping unsupported-method fallback.
- Drain in-flight usage calls before quiescing and queue replacement-window usage records for ordered replay after replacement or rollback recovery.
- Retain held usage records across failed rollback recovery and bound synchronous replay so ApplyConfig cannot overlap native lifecycle calls or starve under load.

Closes: #7232
2026-11-04 03:29:11 +08:00
Luis Pater
04208efa8b fix(pluginhost): preserve disabled auth state across plugin refreshes
- Add preserveAuthDisabledState helper that carries the host-side Disabled flag and StatusDisabled into plugin refresh results so a minimal AuthData response no longer re-enables operator-disabled credentials.
- Apply the preservation in both Host.RefreshAuth and executorAdapter.Refresh backfill paths, and cover both directions plus the status-only edge case with regression tests.

Closes: #7225
2026-11-03 13:00:28 +08:00
Luis Pater
dde469d3c2 fix(pluginhost): isolate unix plugin dlopen crashes with a preflight subprocess probe
- Run an out-of-process preflight dlopen and initialization probe before mapping dynamic plugin libraries into the host process so fatal signals such as SIGILL do not crash-loop the gateway.
- Cache only deterministic probe outcomes with bounded stderr collection and non-blocking stdio handling across inherited child descriptors.
- Pin baseline Go and CGO CPU architecture flags in the plugin example build recipe and document baseline ISA flags for prebuilt c-shared plugin releases.

Closes: #7220
2026-11-03 11:49:10 +08:00
Luis Pater
6e6afab99a refactor: migrate gjson, sjson, and base64 to MoeForge/moego
- Replace tidwall/gjson and tidwall/sjson with github.com/MoeForge/moego/ojson
  and encoding/base64 with github.com/MoeForge/moego/base64 across the main
  module and examples
- Introduce cross-method *ojson.Doc request rewriting pipelines across
  thinking, signature, client/codex, runtime/executor/helps, pluginhost, and
  all provider executors with FinalizePayloadDoc as the final semantic barrier
- Convert all consecutive JSON mutations (>= 2 Set/SetRaw/Delete operations)
  to batch edits on ojson.Doc
- Upgrade read-only byte paths to ojson.GetBytesNoCopy,
  ojson.GetManyBytesNoCopy, and util.ParseGJSONBytesNoCopy with explicit
  strings.Clone ownership protection across streaming and persistent state
- Use base64.StdEncoding.ValidateString for zero-allocation signature checks
  and base64.EncodeDataURL for single-allocation data URL construction
2026-11-03 03:05:04 +08:00
sususu98
d7af371173 Merge pull request #7167 from sususu98/fix/pluginhost-model-stream-ownership-7159
fix(pluginhost): scope model execution streams to the owning plugin and instance
2026-11-02 18:22:07 +08:00
sususu
d96b194168 fix(pluginhost): reject model stream registration after concurrent teardown 2026-11-02 18:09:08 +08:00
Luis Pater
53ff2f9e74 feat(pluginhost): expose per-entry name and logo for multi-entry OAuth plugins
- Add AuthProviderEntry and AuthProviderEntries in sdk/pluginapi, forward entries over auth.identifier RPC, and send multi_auth_providers in lifecycle requests.
- Normalize per-entry OAuth display metadata with plugin metadata fallbacks in RegisteredPluginInfo while preserving legacy fields when entries are omitted.
- Expose HTML-sanitized oauth_provider_entries in management plugin list responses alongside oauth_provider and oauth_providers.

Closes: #7170
2026-11-01 22:46:17 +08:00
Luis Pater
f7331b5197 fix(pluginhost): deframe same-format plugin executor streams and gate hooks 2026-11-01 21:29:23 +08:00
Luis Pater
aca8dfe0f4 Merge pull request #7154 2026-11-01 21:29:23 +08:00
sususu
3698b1597a fix(pluginhost): scope model execution streams to the owning plugin and instance
Bind modelStreamBridge entries to the caller's plugin ID and callback instance
so host.model.stream_read and host.model.stream_close reject cross-plugin or
cross-instance access. Also close model streams when callback instances or
plugins are torn down.

Fixes #7159
2026-11-01 20:17:56 +08:00
Rick7C2
41c03b7451 fix(pluginhost): normalize same-format plugin executor streams through the stream translator
Plugin executor streams whose output format equaled the requested format bypassed stream translation, so SSE-framed chunks ("data: {...}" plus "data: [DONE]") reached the OpenAI/Gemini handlers unchanged. Those handlers add their own "data:" prefix and terminal marker, producing a doubled "data: data:" prefix and a duplicated [DONE] on the wire.

Built-in executors always run TranslateStream, and the registered same-format translators strip that framing. Route same-format plugin executor streams through the same translation instead of returning the channel or payload unchanged. Formats without a same-format translator keep the existing behavior via the TranslateStream fallback, which returns the payload unchanged, and the OpenAI Responses usage-details fixup still runs after translation.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-01 06:55:20 +00:00
sususu
fd02b720e6 fix(proxy): stamp keepalive on uTLS dialers, rebind stale compat executors, and close retired pools outside fence lock 2026-11-01 14:20:38 +08:00
Luis Pater
a8dbebabdf feat(pluginhost): allow plugins to register multiple OAuth login entries
- Add Capabilities.AuthProviders and MultiAuthProvider (Identifiers() []string) in sdk/pluginapi, bump sdk/pluginabi.SchemaVersion to 10, and forward AuthProviders in sdk/pluginhost
- Extend internal/pluginhost to register, expose, and route multiple OAuth login identifiers per plugin across StartLogin, PollLogin, RefreshAuth, ParseAuths, and ExchangeCallback, while preserving per-credential oauth_provider/portal attribution for shared credential providers
- Expose oauth_providers alongside primary oauth_provider in RegisteredPluginInfo and GET /v0/management/plugins, and support target-credential re-login (StartOAuthV8) across sibling portals

Closes: #7126
2026-10-31 20:20:16 +08:00
Luis Pater
bc81923ba6 feat(pluginhost): allow model registrars to publish models for multiple providers
- Add ProviderModels, Registrations, MultiProviderModels, and SchemaVersionMultiProviderModels so a single plugin can register model catalogs across multiple providers while preserving single-provider compatibility.
- Track per-plugin provider sets and multi-provider model registrations in the plugin host for catalog aggregation, per-auth model discovery matching, and targeted unload cleanup.

Closes: #7115
2026-10-30 14:38:48 +08:00
Luis Pater
0fe38224e5 feat(pluginhost): support raw request body byte-range patching
Existing request interceptors wrap the full request body in a JSON RPC envelope with Base64 encoding and skip subsequent duplex WebSocket business frames, causing ~3.33x memory and CPU amplification when rewriting small fields such as Codex `<timezone>` and `<current_date>` in large contexts.

- Add schema v8 raw request body patch methods (`request.patch_body_before` and `request.patch_body_after`) and capabilities (`request_interceptor_patch_body_before/after`, `request_body_patcher_before/after`) that pass raw `Body []byte` directly across the C ABI without JSON/Base64 request wrapping
- Add `RequestBodyEdit`, `RequestBodyPatchResponse`, and `RequestBodyPatcher` in `sdk/pluginapi` with single-pass host splicing, bounds/overlap validation, `json.Valid` verification, no-op original body reuse, and sequential multi-plugin chaining
- Eliminate redundant full-body slice clones in handler/conductor request interceptor application paths
- Run before-auth and after-auth request interceptors on subsequent duplex WebSocket `response.create`, `response.append`, and `response.steer` messages

Closes: #7072
2026-10-28 21:38:42 +08:00
Luis Pater
e324e4814c perf(pluginhost): allow frontend auth providers to opt out of request body delivery
- Let schema v7+ frontend auth providers opt out of receiving request bodies via frontend_auth_provider_omit_body / frontend_auth_omit_body so metadata-only auth plugins skip reading, decoding, cloning, and marshaling the request body during authentication.
- Avoid cloning the buffered request body slice before JSON serialization when invoking RPC-backed frontend auth providers that still inspect the body.

Closes: #7071
2026-10-28 20:42:52 +08:00
Luis Pater
6fe654bfc6 perf(pluginhost): gate request interceptor body delivery behind schema v7 opt-out
- Bump plugin SchemaVersion to 7 and let request interceptors declare per-phase body opt-out via request_interceptor_omit_body_before/after capabilities, so metadata-only plugins no longer pay for body cloning, Base64 encoding, and cross-ABI copies.
- Skip the body clone in interceptRequest for schema v7+ plugins that opt out of the current phase while preserving chain state, blind body replacement, and termination semantics.

Closes: #6998
2026-10-26 16:47:13 +08:00