fix(plugin): end ordinary RPCs' plugin work when their caller leaves (#4678)

A plugin model list's deadline and an ordinary RPC's cancellation released
only the caller. inTime raced the hook without stopping it, and host.go
marked only gatewayRequest cancellable, so a cancelled usage or providers
call never told the host: the plugin's task kept running, the host's
pending count kept it, and repeated reads left task after task alive past
their callers. Reported with an offline host-script reproduction that
shows abort reaching none of three pending usage tasks and five model
tasks outliving their deadlines.

The cancellation path a fetch and a gateway request already take now
carries ordinary RPCs too:

- host.go marks every call but init cancellable, so a caller whose
  context ends has the host told (the existing callAborting write), the
  way it already tells it of a stopped fetch. init is left alone: a start
  that overruns is stopped whole.
- host.js registers each ordinary RPC's AbortController; an aborted
  RPC's answer, nobody's then, is not sent.
- the handler is handed the signal: usage passes it to the plugin's
  auth.usage hook as its own options, and a model list's hook options
  carry it, with the listWait deadline aborting the same controller, so
  vendor I/O that supports stopping stops at the deadline or when the
  caller leaves, whichever comes first.

Sign-in renewal and its persistence are untouched: fresh() runs before
the hooks, and an aborted RPC's handler still finishes what it saves.

Refs #4678

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported, narrowed: an aborted ordinary RPC is no longer
answered "Aborted" at once and dropped from pending. It stays pending
until its handler ends, as on main. host.go's stop() closes the host's
stdin and then gives a renewing host up to stopRenewing to save the
rotated token; with the early done(), host.js's own `pending === 0 &&
closed` exit ended the process at once under a cancelled call whose
handler was still renewing or saving (keepSignedIn, set, signOut, a
usage hook mid-refresh). The Go side needs no answer: an aborted call
is released once its abort is written. The signal to the usage and
models hooks, and the listWait deadline aborting the models hook, are
kept as the patch had them.
TestCancelledCallKeepsTheHostTillItsHookEnds is new: a usage hook that
ends 600ms after its abort, then Settle() closing the host's stdin; the
hook's end must reach its trace.

Run on mote (darwin arm64, Go 1.26.8, Bun via testenv): go test -tags
nogui -count=1 ./internal/plugin/... ok 102.8s; -run Plugin
./internal/gateway/ ok 52.1s and ./internal/provider/ ok 13.3s.
Broken by hand: host.js and host.go at main, tests kept:
TestOrdinaryCallCancelTellsTheHost FAIL "the host was told of the
cancellation didn't happen", TestCancelledUsageReachesThePlugin FAIL
"the plugin's usage hook was handed a signal didn't happen",
TestModelListDeadlineTellsTheHook FAIL "the models hook was handed a
signal didn't happen". host.js as the patch had it (early answer):
TestCancelledCallKeepsTheHostTillItsHookEnds FAIL "the host left
before the hook ended; trace: {"signal":"live"}...".
Not tried: the reporter's replay.py against the built host, and a real
plugin's usage hook that passes the signal to its fetch. The reporter's
"host lives on after stdin closes with a task pending" row is unchanged
by design: that is the renewal safeguard.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
ggbdpq
2026-11-06 05:53:23 +08:00
committed by yetone
parent 9f6407321d
commit 3da58c3dfc
5 changed files with 273 additions and 34 deletions
+2
View File
@@ -305,6 +305,8 @@ A plugin sign-in's page is opened once. An `authorize` result may say `opened: t
A plugin sign-in magpie gives up on ends in the host too (#5016). The user's Cancel, or the sign-in's timeout (`signInTimeout`), ends `plugin.Finish`'s context, and `authorize`, `callback` and `apiKey` are cancellable calls (`cancellable` in [`host.go`](../../internal/plugin/host.go)), as a gateway request is: magpie writes `abort` for the call, and `host.js` (`signInSteps`) drops whatever the plugin answers after it, so nothing is saved, and counts the call as done at once. The plugin's own wait is told where the host can tell it: every fetch the plugin makes for the sign-in carries the sign-in's signal (`whileSigningIn`), and magpie's hook hands the signal to the plugin as a second argument, `callback(code, { signal })` and `authorize(inputs, { signal })` (OpenCode passes none), so a plugin that polls a file or its vendor for minutes (AStudio's waits on its desktop app's session file, plugins#658) can stop. Before, a session file written after Cancel still signed the account in. An `oauth` method's `authorize` that can't start says why as an `api` method's does, `{ type: "failed", error }`; `host.js` answers it, or a result with no `callback`, as the sign-in's failure (`plugin.Authorize` gives `ErrFailed` with the reason) instead of calling the callback it lacks, which reached the user as "s.a.callback is not a function". `TestCancelledSignInSavesNothing`, `TestCancelledSignInEndsThePluginsWait`, `TestCancelledSignInEndsItsFetch` and `TestSignInFailsWithThePluginsReason` in [`plugin_signinend_test.go`](../../internal/plugin/plugin_signinend_test.go).
Every other call but `init` is cancellable too (#4678): a models list, a usage read or a check magpie stops waiting for (its caller left, or `listWait` ran out) gets an `abort`, and `host.js` aborts the call's signal, which the usage hook gets as `usage(..., { signal })` and the models hook as `signal`. The call stays pending in the host until its handler ends, and nothing it answers after the abort is sent, so a hook still saving a refreshed sign-in finishes before the host may exit. `TestCancelledCallKeepsTheHostTillItsHookEnds` and the other tests in [`plugin_rpc_cancel_test.go`](../../internal/plugin/plugin_rpc_cancel_test.go).
The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSignIn`. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects.
## Verification
+9 -7
View File
@@ -120,7 +120,7 @@ type call struct {
// the body's reader takes them: the host's reader queues them without
// ever waiting on one request's consumer (see push).
stream bool
cancellable bool // a gateway request or sign-in step owns asynchronous I/O, without a stream slot
cancellable bool // asynchronous I/O of its own, without a stream slot: an aborted call is told to the host
mu sync.Mutex
queue []message
queued int // the queued chunks' decoded bytes
@@ -1751,11 +1751,6 @@ func (h *host) releaseSlot(c *call) {
}
}
// cancellable are the methods whose work the host ends when their caller
// gives up: a gateway request's I/O, and a sign-in's steps, so a sign-in
// cancelled or timed out saves nothing the plugin answers after (#5016).
var cancellable = map[string]bool{"gatewayRequest": true, "authorize": true, "callback": true, "apiKey": true}
// call asks the host method with params and reads its answer into out.
func (h *host) call(ctx context.Context, method string, params, out any) error {
id, c, err := h.begin(false)
@@ -1763,7 +1758,14 @@ func (h *host) call(ctx context.Context, method string, params, out any) error {
return err
}
c.mu.Lock()
c.cancellable = cancellable[method]
// An ordinary RPC is cancellable too: a caller whose context ends has
// the host told, so its plugin work is not left running unseen (#4678).
// A gateway request and a sign-in's steps were already; now every other
// call but init is as well, and a sign-in cancelled or timed out still
// saves nothing the plugin answers after (#5016). init is the exception:
// a start that overruns is stopped whole, and aborting it would only
// interrupt its own load.
c.cancellable = method != "init"
c.mu.Unlock()
if err := h.enqueueCall(ctx, map[string]any{"id": id, "method": method, "params": params}, nil, c); err != nil {
c.settle(err)
+56 -24
View File
@@ -355,12 +355,17 @@ let listWait = 20 * 1000
// late is what a step that took longer than ms gives instead of its own
// result: an error saying so. The step goes on by itself; what it gives
// later is dropped.
// later is dropped. A step handed a signal of its own (a model hook's) has
// its controller aborted here, so the I/O a deadline gives up on stops too
// rather than waiting for a caller that has moved on (#4678).
class Late extends Error {}
function inTime(step, ms, what) {
function inTime(step, ms, what, ctl) {
let timer
const late = new Promise((_, no) => {
timer = setTimeout(() => no(Object.assign(new Late(`${what} didn't finish in ${Math.round(ms / 1000)}s`), { plain: true })), ms)
timer = setTimeout(() => {
ctl?.abort()
no(Object.assign(new Late(`${what} didn't finish in ${Math.round(ms / 1000)}s`), { plain: true }))
}, ms)
})
return Promise.race([Promise.resolve().then(step), late]).finally(() => clearTimeout(timer))
}
@@ -1973,8 +1978,10 @@ function fromModelsDev(p, m) {
// lists them for account key (the first when none); strict fails where the
// plugin's list does, rather than keeping the list it was given.
// quiet asks no models hook (a provider switched off in magpie): the
// list is told as fallen back, which keeps the one magpie had.
async function info(id, key, strict, limit, quiet) {
// list is told as fallen back, which keeps the one magpie had. The
// listing's caller may give up (signal), which a hook is told through
// its own options' signal too (#4678).
async function info(id, key, strict, limit, quiet, signal) {
const md = mdev()[id]
const cfg = config.provider?.[id]
const out = {
@@ -2042,11 +2049,16 @@ async function info(id, key, strict, limit, quiet) {
const began = Date.now()
await fresh(id, k)
const all = readAuth()
// the hook's own signal: its listWait deadline aborts it, and so does
// the listing's caller going away, whichever comes first (#4678)
const ctl = new AbortController()
if (signal?.aborted) ctl.abort()
else signal?.addEventListener("abort", () => ctl.abort(), { once: true })
try {
const given = JSON.parse(JSON.stringify(out))
const l = { tried: false, lastOk: false }
const ask = () => listing.run(l, () => inScope(id, k, () => ph.models(given, { auth: authCopy(k) })))
const next = limit > 0 ? await inTime(ask, Math.max(limit - (Date.now() - began), 0), "the plugin's model list") : await ask()
const ask = () => listing.run(l, () => inScope(id, k, () => ph.models(given, { auth: authCopy(k), signal: ctl.signal })))
const next = limit > 0 ? await inTime(ask, Math.max(limit - (Date.now() - began), 0), "the plugin's model list", ctl) : await ask()
// a hook that asked its vendor, got no list and gave back the one it
// was given fell back: magpie keeps the list it had, as a built-in
// whose fetch failed keeps the one it fetched last; so does one that
@@ -2075,7 +2087,9 @@ async function info(id, key, strict, limit, quiet) {
// magpie keeps the one it had, as for one that gave its defaults back
out.fellBack = true
out.listError = e?.message ?? String(e)
send({ event: "log", level: "error", message: `${h.spec}: provider.models: ${e?.message ?? e}` })
// a listing the caller gave up on says its abort itself, not as if
// the vendor had failed
if (!ctl.signal.aborted) send({ event: "log", level: "error", message: `${h.spec}: provider.models: ${e?.message ?? e}` })
}
}
for (const [k, m] of Object.entries(cfg?.models ?? {})) if (m?.disabled) delete out.models[k]
@@ -2315,8 +2329,11 @@ function tiersOf(v) {
// providers lists each provider and its accounts' models, each asked
// through its proxy (proxies[provider][key], "" the provider's own), as a
// built-in fetches each account's list through the account's.
async function providers({ proxies, off } = {}) {
// built-in fetches each account's list through the account's. A caller
// that gave up (signal) has every hook it would still have asked told, so
// a timed-out listing stops its vendor reads instead of multiplying them
// (#4678).
async function providers({ proxies, off } = {}, signal) {
const stored = readAuth()
// a provider switched off in magpie is asked nothing: its models hook
// (and the sign-in renewal before it) would reach its vendor. It is
@@ -2337,12 +2354,12 @@ async function providers({ proxies, off } = {}) {
// listWaits back to back took one provider past refreshDeadline twice
// over (#4065)
const [p, own] = await Promise.all([
via.run(through(), () => info(id, undefined, false, listWait)).then((q) => (keepInfo(keys[0] ?? id, q, gen), q)),
via.run(through(), () => info(id, undefined, false, listWait, false, signal)).then((q) => (keepInfo(keys[0] ?? id, q, gen), q)),
// each account's own models, as the built-ins read each account's: a
// plan may serve fewer, or others, than the first account's. One that
// can't be read is taken to have them all, or the ones it was last
// told to have, as a built-in account whose fetch failed keeps its own.
Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true, listWait)).then((q) => (keepInfo(k, q, gen), q)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))),
Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true, listWait, false, signal)).then((q) => (keepInfo(k, q, gen), q)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))),
])
return rowOf(id, a, keys, stored, p, own)
}
@@ -2883,18 +2900,20 @@ async function load({ provider, account, proxy }) {
// a clean read clears it)
// }
// Run in the account's scope, a token it renews is saved to that account.
async function usage({ provider, account, proxy }) {
return via.run(proxy ?? "", () => usageOf(provider, account))
// A caller that gave up (signal) is what the hook is handed as its own
// options, so a vendor read that supports stopping stops (#4678).
async function usage({ provider, account, proxy }, signal) {
return via.run(proxy ?? "", () => usageOf(provider, account, signal))
}
async function usageOf(provider, account) {
async function usageOf(provider, account, signal) {
const a = auths().get(provider)?.auth
if (typeof a?.usage !== "function") throw new Error(`${provider}'s plugin doesn't tell its usage`)
const key = accountKey(provider, account)
if (!readAuth()[key]) throw new Error("not signed in")
await fresh(provider, key)
const p = await infoOf(provider, key)
const u = (await inScope(provider, key, () => a.usage(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {}
const u = (await inScope(provider, key, () => a.usage(async () => authCopy(key), JSON.parse(JSON.stringify(p)), signal === undefined ? undefined : { signal }))) ?? {}
const when = (v) => {
if (v === undefined || v === null || v === "") return ""
const d = new Date(typeof v === "number" && v < 1e11 ? v * 1000 : v)
@@ -3173,7 +3192,7 @@ const handlers = {
await loadPlugins(p.plugins ?? [])
return { plugins: loaded.map(withProviders) }
},
providers: (p) => providers(p ?? {}),
providers: (p, signal) => providers(p ?? {}, signal),
prompt: async (p) => ({ prompt: await nextPrompt(p.provider, p.method, p.inputs ?? {}) }),
validate: (p) => ({ error: validate(p.provider, p.method, p.key, p.value) }),
authorize,
@@ -3200,13 +3219,13 @@ const handlers = {
// vendor turned the sign-in away. A models hook may fall back to a list
// it keeps when the vendor can't be reached, so a check that reached
// none of the places it asked proves nothing, and fails.
async check(p) {
async check(p, signal) {
const key = accountKey(p.provider, p.account)
const r = { reached: false, failed: null, refused: null }
return via.run(p.proxy ?? "", () => reach.run(r, async () => {
await load({ provider: p.provider, account: key })
const pi = await info(p.provider, key, true)
const u = typeof auths().get(p.provider)?.auth?.usage === "function" ? await usageOf(p.provider, key) : null
const pi = await info(p.provider, key, true, undefined, false, signal)
const u = typeof auths().get(p.provider)?.auth?.usage === "function" ? await usageOf(p.provider, key, signal) : null
if (r.failed && !r.reached) throw new Error(`couldn't reach ${pi.name}: ${r.failed?.message ?? r.failed}`)
return { models: Object.keys(pi.models), usage: u, refused: r.refused ?? "" }
}))
@@ -3306,6 +3325,7 @@ const gatewayInflight = new Map() // RPC id -> AbortController
// plugin's wait ends or not (#5016).
const signInSteps = new Set(["authorize", "callback", "apiKey"])
const signInInflight = new Map() // RPC id -> AbortController
const rpcInflight = new Map() // an ordinary RPC's id -> its AbortController (#4678)
const rl = readline.createInterface({ input: process.stdin, terminal: false })
rl.on("line", (line) => {
if (!line.trim()) return
@@ -3321,6 +3341,7 @@ rl.on("line", (line) => {
if (record) transitionFetch(record, "cancelled")
gatewayInflight.get(id)?.abort()
signInInflight.get(id)?.abort()
rpcInflight.get(id)?.abort()
return
}
if (msg.method === "credit") {
@@ -3411,13 +3432,24 @@ rl.on("line", (line) => {
done()
return
}
// An ordinary RPC is told when magpie gives up on it, as a fetch and a
// gateway request are: the handler is handed the signal, so the work
// that supports stopping stops (#4678), and its answer, nobody's then,
// is not sent. It stays pending until the handler ends all the same: a
// handler that ignores the signal may still be renewing or saving a
// sign-in, and a host whose stdin closed must not exit under it.
const ctl = new AbortController()
rpcInflight.set(msg.id, ctl)
wait
.then(() => fn(msg.params ?? {}))
.then(() => fn(msg.params ?? {}, ctl.signal))
.then(
(result) => send({ id: msg.id, result: result ?? null }),
(e) => send({ id: msg.id, error: { message: String(e?.message ?? e) } }),
(result) => { if (!ctl.signal.aborted) send({ id: msg.id, result: result ?? null }) },
(e) => { if (!ctl.signal.aborted) send({ id: msg.id, error: { message: String(e?.message ?? e) } }) },
)
.finally(done)
.finally(() => {
rpcInflight.delete(msg.id)
done()
})
})
rl.on("close", () => {
closed = true
+171
View File
@@ -0,0 +1,171 @@
package plugin
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// TestOrdinaryCallCancelTellsTheHost: a caller whose context ends while an
// ordinary RPC is under way has the host told of it, as a fetch's or a
// gateway request's caller is. Before, only those two kinds were
// cancellable: the plugin's usage or model work went on unseen, and repeated
// reads left task after task alive past their callers (#4678).
func TestOrdinaryCallCancelTellsTheHost(t *testing.T) {
f := newFakeHost(t)
// the call count is read beside a caller goroutine still admitting, so
// it is read under the host's lock
liveCalls := func() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.host.calls)
}
ctx, cancel := context.WithCancel(context.Background())
waited := make(chan error, 1)
go func() {
waited <- f.host.call(ctx, "usage", map[string]any{"provider": "fakeco"}, nil)
}()
waitFor(t, "the usage call reached the host", func() bool { return liveCalls() == 1 })
cancel()
if err := <-waited; !errors.Is(err, context.Canceled) {
t.Fatalf("usage = %v, want canceled", err)
}
waitFor(t, "the host was told of the cancellation", func() bool {
for _, m := range f.methods() {
if m == "abort" {
return true
}
}
return false
})
waitFor(t, "the aborted call left the host", func() bool { return liveCalls() == 0 })
waitFor(t, "the call's slot came free", func() bool { return f.slotsFree() == cap(f.host.slots) })
}
// TestCancelledUsageReachesThePlugin: a usage read whose caller gave up has
// the plugin's own usage hook told as well, through the signal the host
// hands it, so a vendor read that supports stopping stops instead of waiting
// out its caller's successor (#4678). The hook traces what it was handed
// and whether the abort arrived, to a file the test reads.
func TestCancelledUsageReachesThePlugin(t *testing.T) {
sandbox(t)
trace := filepath.Join(t.TempDir(), "trace.jsonl")
t.Setenv("STUCK_USAGE", "1")
t.Setenv("STUCK_TRACE", trace)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
abs, err := filepath.Abs("testdata/stuck/index.js")
if err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := APIKey(ctx, "stuckco", 0, nil, "k-stuckco", NewAccount); err != nil {
t.Fatal(err)
}
uctx, ucancel := context.WithTimeout(context.Background(), time.Second)
defer ucancel()
if _, err := AccountUsage(uctx, "stuckco", ""); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("usage = %v, want deadline exceeded", err)
}
waitFor(t, "the plugin's usage hook was handed a signal", func() bool {
b, err := os.ReadFile(trace)
return err == nil && strings.Contains(string(b), `"signal":"live"`)
})
waitFor(t, "the plugin's usage hook saw the abort", func() bool {
b, err := os.ReadFile(trace)
return err == nil && strings.Contains(string(b), `"aborted":true`)
})
}
// TestModelListDeadlineTellsTheHook: a models hook whose listWait runs out
// is aborted, not merely raced past — what its vendor read still supports
// stopping stops, instead of one task waiting behind every timed-out read
// (#4678). The hook traces the signal it was handed to a file the test
// reads.
func TestModelListDeadlineTellsTheHook(t *testing.T) {
sandbox(t)
stuckWaits(t)
trace := filepath.Join(t.TempDir(), "trace.jsonl")
t.Setenv("STUCK_MODELS", "1")
t.Setenv("STUCK_MODELS_TRACE", "1")
t.Setenv("STUCK_TRACE", trace)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
abs, err := filepath.Abs("testdata/stuck/index.js")
if err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := APIKey(ctx, "stuckco", 0, nil, "k-stuckco", NewAccount); err != nil {
t.Fatal(err)
}
lctx, lcancel := context.WithTimeout(context.Background(), 20*time.Second)
defer lcancel()
ps, err := Providers(lctx)
if err != nil || len(ps) != 1 || ps[0].ID != "stuckco" {
t.Fatalf("Providers = %+v, %v", ps, err)
}
if !ps[0].FellBack {
t.Fatalf("stuckco listed fellBack=false, want the deadline's fallback")
}
waitFor(t, "the models hook was handed a signal", func() bool {
b, err := os.ReadFile(trace)
return err == nil && strings.Contains(string(b), `"signal":"live"`)
})
waitFor(t, "the deadline aborted the models hook", func() bool {
b, err := os.ReadFile(trace)
return err == nil && strings.Contains(string(b), `"aborted":true`)
})
}
// TestCancelledCallKeepsTheHostTillItsHookEnds: a call magpie gave up on
// still counts as the host's own until its handler ends. A hook that goes
// on after the abort (renewing or saving a sign-in) isn't cut off when the
// host is then stopped and its stdin closes: the host leaves when the hook
// has ended, not at once (#4678).
func TestCancelledCallKeepsTheHostTillItsHookEnds(t *testing.T) {
sandbox(t)
trace := filepath.Join(t.TempDir(), "trace.jsonl")
t.Setenv("STUCK_USAGE", "1")
t.Setenv("STUCK_USAGE_LINGER", "600")
t.Setenv("STUCK_TRACE", trace)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
abs, err := filepath.Abs("testdata/stuck/index.js")
if err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := APIKey(ctx, "stuckco", 0, nil, "k-stuckco", NewAccount); err != nil {
t.Fatal(err)
}
uctx, ucancel := context.WithTimeout(context.Background(), time.Second)
defer ucancel()
if _, err := AccountUsage(uctx, "stuckco", ""); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("usage = %v, want deadline exceeded", err)
}
waitFor(t, "the plugin's usage hook saw the abort", func() bool {
b, err := os.ReadFile(trace)
return err == nil && strings.Contains(string(b), `"aborted":true`)
})
// the host is stopped while the hook is still going: its stdin closes,
// and it has room to end its calls well past the hook's 600ms
was := stopWait
stopWait = 10 * time.Second
t.Cleanup(func() { stopWait = was })
Settle()
b, err := os.ReadFile(trace)
if err != nil || !strings.Contains(string(b), `"finished":true`) {
t.Fatalf("the host left before the hook ended; trace: %s (%v)", b, err)
}
}
+35 -3
View File
@@ -1,9 +1,24 @@
// A plugin whose vendor never lets it through, as one whose sign-in is
// answered 401 and tried again for ever: with $STUCK_LOAD set its plugin
// function never returns, and with $STUCK_MODELS set its models hook
// never does.
// function never returns, with $STUCK_MODELS set its models hook never
// does, and with $STUCK_USAGE set its usage hook doesn't either — but not
// before saying what its caller handed it, and whether an abort reaches it,
// to the file $STUCK_TRACE names (#4678).
const never = () => new Promise(() => {})
import fs from "node:fs"
// traceUsage says what the host handed the hook: a signal it can listen to,
// and, later, that the abort arrived, one JSON line each.
function traceUsage(options) {
const signal = options?.signal
const live = signal && typeof signal.addEventListener === "function"
fs.appendFileSync(process.env.STUCK_TRACE, JSON.stringify({ signal: live ? (signal.aborted ? "aborted" : "live") : "none" }) + "\n")
if (live && !signal.aborted) {
signal.addEventListener("abort", () => fs.appendFileSync(process.env.STUCK_TRACE, JSON.stringify({ aborted: true }) + "\n"), { once: true })
}
}
export const StuckPlugin = async () => {
if (process.env.STUCK_LOAD) await never()
return {
@@ -18,7 +33,8 @@ export const StuckPlugin = async () => {
},
provider: {
id: "stuckco",
async models(provider) {
async models(provider, options) {
if (process.env.STUCK_MODELS_TRACE) traceUsage(options)
if (process.env.STUCK_MODELS) await never()
return provider.models
},
@@ -27,6 +43,22 @@ export const StuckPlugin = async () => {
provider: "stuckco",
methods: [{ type: "api", label: "API key" }],
loader: async () => ({ baseURL: "https://stuck.invalid/v1" }),
usage: async (_getAuth, _provider, options) => {
if (process.env.STUCK_USAGE) {
traceUsage(options)
// with $STUCK_USAGE_LINGER set, an abort ends the hook that many
// ms later, as a hook still saving a renewed sign-in would, and it
// says so first
const linger = Number(process.env.STUCK_USAGE_LINGER)
if (linger > 0 && options?.signal) {
await new Promise((ok) => options.signal.addEventListener("abort", () => setTimeout(() => {
fs.appendFileSync(process.env.STUCK_TRACE, JSON.stringify({ finished: true }) + "\n")
ok()
}, linger), { once: true }))
} else await never()
}
return { windows: [] }
},
},
}
}