@caph42/pi-cursor-provider 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@
5
5
  * Ported from magpie's native-session.mjs (MIT):
6
6
  * https://github.com/magpie-community/plugins/tree/main/packages/cursor
7
7
  * Self-contained. The only import is node:crypto. Run wiring passes pb, exec,
8
- * usageOf, and failure in. This file does not import the rest of the package.
8
+ * usageOf, failure, and trace in. This file does not import the rest of the package.
9
9
  */
10
10
  import { createHash, randomBytes } from "node:crypto"
11
11
 
@@ -352,6 +352,27 @@ class Segment {
352
352
  }
353
353
  }
354
354
 
355
+ /** States an owner in entries can be in. fail() removes an owner as it sets failed, cancelled, or expired. */
356
+ export type OwnerPhase = "opening" | "running" | "submitting" | "awaiting-results" | "finalizing" | "complete"
357
+
358
+ export type OwnerView = {
359
+ phase: OwnerPhase
360
+ model: string
361
+ maxMode: boolean
362
+ /** Tool batches handed back to the caller. */
363
+ rounds: number
364
+ /** The Run's absolute lifetime deadline. */
365
+ lifetimeEnds: number
366
+ /** Whether the owner belongs to the account the reader asked about. */
367
+ current: boolean
368
+ }
369
+
370
+ /** The pool in a form the doctor may print. */
371
+ export type NativeState = {
372
+ owners: readonly OwnerView[]
373
+ limits: { perAccount: number; perProcess: number }
374
+ }
375
+
355
376
  export class NativeSessionPool {
356
377
  constructor(limits = NATIVE_LIMITS) {
357
378
  this.limits = limits
@@ -359,6 +380,21 @@ export class NativeSessionPool {
359
380
  this.handles = new Map()
360
381
  this.selectors = new Map()
361
382
  }
383
+ // Takes anything with Account's is(), so this file imports nothing. Unlike
384
+ // prepare, create, and response(), it changes no owner.
385
+ state(account?: { is(fingerprint: string): boolean }): NativeState {
386
+ return {
387
+ owners: [...this.entries].sort((a, b) => a.expiresAt - b.expiresAt).map((owner) => ({
388
+ phase: owner.state,
389
+ model: owner.resolution?.id ?? "",
390
+ maxMode: !!owner.resolution?.maxMode,
391
+ rounds: owner.segments,
392
+ lifetimeEnds: owner.expiresAt,
393
+ current: !!account?.is(owner.account),
394
+ })),
395
+ limits: { perAccount: this.limits.perAccount, perProcess: this.limits.perProcess },
396
+ }
397
+ }
362
398
  // selector is conversationID(chat, session): session/cache key AND first
363
399
  // user identity. Task subagents sharing a session must not own its parent.
364
400
  prepare(tok, chat, selector, tools) {
@@ -401,7 +437,7 @@ export class NativeSessionPool {
401
437
  return { owner, batch, results, encoded, digest, chat }
402
438
  } catch (e) {
403
439
  if (!(e instanceof NativeSessionError)) throw e
404
- return fallback("history incompatible with retained owner")
440
+ return { fallback: "history incompatible with retained owner", detail: e.message }
405
441
  }
406
442
  }
407
443
  // Pending ancestors, new input, and terminal old handles are ordinary
@@ -411,19 +447,20 @@ export class NativeSessionPool {
411
447
  return { account, selector, controls, selected: !!selector, chat }
412
448
  }
413
449
  create(prepared, resolution, wire) {
414
- if (prepared.fallback || prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return null
450
+ if (prepared.fallback) return prepared
451
+ if (prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return { fallback: "owner busy" }
415
452
  const crowded = () => this.entries.size >= this.limits.perProcess || [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
416
453
  while (crowded()) {
417
454
  const accountFull = [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
418
455
  const finished = [...this.entries].find((e) => ["complete", "failed", "cancelled", "expired"].includes(e.state) && (!accountFull || e.account === prepared.account))
419
- if (!finished) return null
456
+ if (!finished) return { fallback: accountFull ? "account owner limit" : "process owner limit" }
420
457
  this.forget(finished)
421
458
  }
422
459
  let owner
423
460
  try { owner = new NativeSession(this, prepared, resolution, wire) }
424
461
  catch (e) {
425
462
  if (!(e instanceof NativeSessionError)) throw e
426
- return null
463
+ return { fallback: "opening history not retainable", detail: e.message }
427
464
  }
428
465
  this.entries.add(owner)
429
466
  if (prepared.selected) this.selectors.set(owner.account + ":" + owner.selector, owner)
@@ -524,6 +561,7 @@ class NativeSession {
524
561
  if (this.error || this.state === "complete") return
525
562
  this.error = error
526
563
  this.state = state
564
+ this.wire.trace?.note("owner-ended", { state, model: this.resolution?.id, error })
527
565
  this.segment.fail(error)
528
566
  for (const segment of this.batches ?? []) segment.detach?.()
529
567
  this.segment.detach?.()
package/src/pi-stream.ts CHANGED
@@ -29,6 +29,11 @@ import type {
29
29
  } from "@earendil-works/pi-ai"
30
30
  import { resolveAccessToken } from "./auth.ts"
31
31
  import { runAnswer } from "./run.ts"
32
+ import { supportsFast, usable } from "./models.ts"
33
+
34
+ export interface CursorStreamOptions extends SimpleStreamOptions {
35
+ fast?: boolean
36
+ }
32
37
 
33
38
  /** Shown when no Cursor credential is available. */
34
39
  export const CURSOR_NOT_SIGNED_IN = "Cursor isn't signed in. Run /login cursor or set CURSOR_ACCESS_TOKEN."
@@ -269,7 +274,7 @@ export async function emitCursorEvents(
269
274
  export function streamCursor(
270
275
  model: Model<Api>,
271
276
  context: TranscriptContext,
272
- options?: SimpleStreamOptions,
277
+ options?: CursorStreamOptions,
273
278
  ): AssistantMessageEventStream {
274
279
  const stream = createAssistantMessageEventStream()
275
280
  void pump(stream, model, context, options)
@@ -280,7 +285,7 @@ async function pump(
280
285
  stream: AssistantMessageEventStream,
281
286
  model: Model<Api>,
282
287
  context: TranscriptContext,
283
- options?: SimpleStreamOptions,
288
+ options?: CursorStreamOptions,
284
289
  ) {
285
290
  const message = blank(model)
286
291
  const fail = (reason: Extract<StopReason, "error" | "aborted">, text: string) => {
@@ -298,12 +303,17 @@ async function pump(
298
303
  fail("error", CURSOR_NOT_SIGNED_IN)
299
304
  return
300
305
  }
306
+ if (options?.fast && !supportsFast(await usable(auth.token), model.id, options.reasoning ?? "off")) {
307
+ fail("error", `Cursor fast is enabled but unavailable for ${model.id} at thinking ${options.reasoning ?? "off"}. Use /cursor.fast off or choose a supported thinking level.`)
308
+ return
309
+ }
301
310
  const piTools = options?.toolChoice === "none" ? [] : getCurrentTools(context.messages)
302
311
  const system = getCurrentSystemPrompt(context.messages)
303
312
  const ran = await runAnswer({
304
313
  tok: auth.token,
305
314
  model: model.id,
306
315
  effort: options?.reasoning ?? "",
316
+ fast: options?.fast,
307
317
  messages: toChat(context.messages, system),
308
318
  tools: piTools.map((tool) => ({
309
319
  name: tool.name,
package/src/run.ts CHANGED
@@ -24,8 +24,10 @@ import { isDeepStrictEqual } from "node:util"
24
24
  import { EMPTY, failure, field, fields, frame, frames, pb, pbAny, pbNum, pbStr, pbValue, regional } from "./codec.ts"
25
25
  import { AGENT, API, CALL, GOOS, NAMESPACE, clientVersion, tempDir, unary } from "./client.ts"
26
26
  import { canRead, ledger, owe, STEP_WAIT, usageKey } from "./ledger.ts"
27
+ import { recall, store, tokenKey } from "./cache.ts"
27
28
  import { request as resolveModel, usable } from "./models.ts"
28
29
  import { NATIVE_LIMITS, NativeSessionError, nativeFields, nativeMcpArgs, nativeSessions } from "./native-session.ts"
30
+ import { hostOf, trace, type Account, type Host } from "./trace.ts"
29
31
 
30
32
  const NO_RESULT = "Tool use was interrupted and did not produce a result."
31
33
 
@@ -85,8 +87,12 @@ function toolsOf(chat) {
85
87
  // those calls went nowhere (#11).
86
88
  function catalog(tools) {
87
89
  if (!tools.length) return ""
90
+ const visible = (value) => String(value ?? "").replaceAll("<", "\\u003c")
88
91
  let s = `\n\n<dynamic_tool_catalog>\nThe MCP namespace "pi" has the tools below. They are reached only through \`${CALL}\`, never as tools of their own. Each entry is the exact call to make; its arguments must match the schema given. The schemas are complete, so there is no need to call \`GetDynamicTools\` first.\n`
89
- for (const t of tools) s += `<call>${CALL}({"namespace":"${NAMESPACE}","toolName":"${t.name}","arguments":{...}})\n${t.description}\narguments schema: ${t.schemaText}\n</call>\n`
92
+ for (const t of tools) {
93
+ const name = JSON.stringify(String(t.name ?? "")).replaceAll("<", "\\u003c")
94
+ s += `<call>${CALL}({"namespace":"${NAMESPACE}","toolName":${name},"arguments":{...}})\n${visible(t.description)}\narguments schema: ${visible(t.schemaText)}\n</call>\n`
95
+ }
90
96
  return s + "</dynamic_tool_catalog>"
91
97
  }
92
98
 
@@ -293,14 +299,20 @@ function buildRun(msgs, lastUser, tools, model, conv = "", { maxMode = false, pa
293
299
  // while it can't be had.
294
300
 
295
301
  const endpoints = new Map()
296
- export async function agentURL(tok, fresh) {
297
- const key = createHash("sha256").update(tok).digest("hex")
298
- const had = endpoints.get(key)
299
- if (!fresh && had && (had.listed || Date.now() - had.at < 60_000)) return had.url
302
+ const ENDPOINT_TTL = 10 * 60 * 1000
303
+ const ENDPOINT_MISS_TTL = 60_000
304
+ export function endpointCacheKeys() {
305
+ return [...endpoints.keys()]
306
+ }
307
+ export async function agentURL(tok, fresh, signal?: AbortSignal) {
308
+ const key = tokenKey(tok)
309
+ const had = recall(endpoints, key)
310
+ if (!fresh && had) return had.url
300
311
  let url = AGENT
301
312
  let listed = false
313
+ let error
302
314
  try {
303
- const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000)
315
+ const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000, signal)
304
316
  for (const raw of [cfg?.agentUrlConfig?.agentUrl, cfg?.agentUrlConfig?.agentnUrl]) {
305
317
  try {
306
318
  const u = new URL(raw)
@@ -311,10 +323,16 @@ export async function agentURL(tok, fresh) {
311
323
  }
312
324
  } catch {}
313
325
  }
314
- } catch {}
326
+ } catch (e) {
327
+ if (signal?.aborted) throw e
328
+ error = e
329
+ }
330
+ if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
315
331
  // A refresh that learns nothing must not replace a regional URL with the global one.
316
- if (!listed && fresh && had?.url) return had.url
317
- endpoints.set(key, { url, at: Date.now(), listed })
332
+ const kept = !listed && fresh && !!had?.url
333
+ trace?.note("endpoint", { url: kept ? had.url : url, listed, kept, error })
334
+ if (kept) return had.url
335
+ store(endpoints, key, { url, listed, expires: 0 }, listed ? ENDPOINT_TTL : ENDPOINT_MISS_TTL)
318
336
  return url
319
337
  }
320
338
 
@@ -330,9 +348,9 @@ export function clearAgentCache() {
330
348
  // connection that failed (refused, no network) or a stream the server
331
349
  // refused leaves the next Run to try HTTP/2 again.
332
350
  //
333
- // Tests may inject `connect`; that path stays HTTP/2-only with headerWaitMs.
351
+ // Tests may inject `connect`; that path stays HTTP/2-only. Both paths wait
352
+ // headerWaitMs for response headers. The default is H2.wait.
334
353
  let h1Until = 0
335
- const HEADER_WAIT_MS = 30_000
336
354
  const H2 = {
337
355
  wait: 15_000,
338
356
  retryAfter: 10 * 60_000,
@@ -508,28 +526,61 @@ function openH1(headers, signal) {
508
526
  return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true, headers: {} })
509
527
  }
510
528
 
511
- async function open(base, headers, signal, connect = defaultConnect, headerWaitMs = HEADER_WAIT_MS) {
529
+ async function open(base, headers, signal, connect = defaultConnect, headerWaitMs = H2.wait) {
512
530
  if (signal?.aborted) return cancelledOpen()
513
531
  // Injected connect (tests): HTTP/2 only, keep the caller's header wait.
514
532
  if (connect !== defaultConnect) {
515
- return openH2(base, headers, signal, connect, headerWaitMs)
533
+ const o = await openH2(base, headers, signal, connect, headerWaitMs)
534
+ if (!o.error) trace?.note("transport", { url: base, h1: false })
535
+ return o
516
536
  }
517
537
  if (Date.now() >= h1Until) {
518
- const o = await openH2(base, headers, signal, defaultConnect, H2.wait)
538
+ const o = await openH2(base, headers, signal, defaultConnect, headerWaitMs)
519
539
  if (signal?.aborted) {
520
540
  try { o.req?.close?.(http2.constants.NGHTTP2_CANCEL) } catch {}
521
541
  try { o.session?.destroy?.() } catch {}
522
542
  return cancelledOpen()
523
543
  }
524
- if (!o.h2Failed) return o
544
+ if (!o.h2Failed) {
545
+ trace?.note("transport", { url: base, h1: false })
546
+ return o
547
+ }
525
548
  if (o.blocked) h1Until = Date.now() + H2.retryAfter
526
- }
549
+ trace?.note("transport", { url: API, h1: true, h2: { url: base, error: o.error }, until: o.blocked ? h1Until : undefined })
550
+ } else trace?.note("transport", { url: API, h1: true, until: h1Until })
527
551
  if (signal?.aborted) return cancelledOpen()
528
552
  return openH1(headers, signal)
529
553
  }
530
554
 
531
555
  export function resetH1() { h1Until = 0 }
532
- export function onH1() { return Date.now() < h1Until }
556
+
557
+ /** What run.ts keeps between turns, in a form the doctor may print. */
558
+ export type RunState = {
559
+ transport: { via: "h2" } | { via: "h1"; until: number }
560
+ /** This account's agent host. null before a turn asked, after the entry expired, or without an account. */
561
+ agent: { host: Host; source: "server-config" | "global-fallback"; until: number } | null
562
+ /** Live agent hosts cached for other accounts. */
563
+ otherAgents: number
564
+ /** Models Cursor said need max mode. Later turns ask for it. */
565
+ maxModeForced: readonly string[]
566
+ }
567
+
568
+ // Walks endpoints without recall(), which deletes the expired entries this skips.
569
+ export function runState(account: Account | undefined, now = Date.now()): RunState {
570
+ let agent = null
571
+ let otherAgents = 0
572
+ for (const [key, entry] of endpoints) {
573
+ if (now >= entry.expires) continue
574
+ if (account?.is(key)) agent = { host: hostOf(entry.url), source: entry.listed ? "server-config" : "global-fallback", until: entry.expires }
575
+ else otherAgents++
576
+ }
577
+ return {
578
+ transport: now < h1Until ? { via: "h1", until: h1Until } : { via: "h2" },
579
+ agent,
580
+ otherAgents,
581
+ maxModeForced: [...maxOnly].sort(),
582
+ }
583
+ }
533
584
 
534
585
  // decode follows the server's messages into the answer's pieces until the
535
586
  // turn ends, or the model has made its tool calls. stepUsage / owedUsage are
@@ -866,12 +917,16 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
866
917
  send(first)
867
918
  if (o.status < 200 || o.status > 299) {
868
919
  const chunks = []
920
+ let bodyCut = false
869
921
  try {
870
922
  for await (const c of req) chunks.push(c)
871
- } catch {}
923
+ } catch {
924
+ bodyCut = true
925
+ }
872
926
  close()
873
927
  book.done()
874
- return { error: failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)), h1: !!o.h1 }
928
+ const error = failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20))
929
+ return { error: bodyCut ? { ...error, bodyCut } : error, h1: !!o.h1 }
875
930
  }
876
931
  const it = decode(frames(req), {
877
932
  send,
@@ -1150,25 +1205,7 @@ export function clearMaxOnly() {
1150
1205
  export { nativeSessions } from "./native-session.ts"
1151
1206
  export { STEP_WAIT, ledger, owed, misses, unreadable, clearLedger, usageKey } from "./ledger.ts"
1152
1207
 
1153
- /** One user-visible turn. A regional miss retries once, and only when the agent URL changed. */
1154
- export async function runAnswer({
1155
- tok,
1156
- model,
1157
- effort = "",
1158
- fast,
1159
- messages,
1160
- tools = [],
1161
- session = "",
1162
- signal,
1163
- connect,
1164
- resolveAgentURL = agentURL,
1165
- rawModels,
1166
- onResponse,
1167
- onPayload,
1168
- headers,
1169
- headerWaitMs = HEADER_WAIT_MS,
1170
- toolIdleMs = TOOL_IDLE_MS,
1171
- }: {
1208
+ export type RunAnswerOptions = {
1172
1209
  tok: string
1173
1210
  model?: string
1174
1211
  effort?: string
@@ -1178,14 +1215,16 @@ export async function runAnswer({
1178
1215
  session?: string
1179
1216
  signal?: AbortSignal
1180
1217
  connect?: (origin: string) => unknown
1181
- resolveAgentURL?: (tok: string, fresh: boolean) => Promise<string> | string
1218
+ resolveAgentURL?: (tok: string, fresh: boolean, signal?: AbortSignal) => Promise<string> | string
1182
1219
  rawModels?: unknown
1183
1220
  onResponse?: (response: { status: number; headers: Record<string, string> }) => unknown
1184
1221
  onPayload?: (payload: unknown) => unknown
1185
1222
  headers?: Record<string, string | null | undefined>
1186
1223
  headerWaitMs?: number
1187
1224
  toolIdleMs?: number
1188
- }): Promise<{
1225
+ }
1226
+
1227
+ export type RunAnswerResult = {
1189
1228
  error?: { status?: number; message?: string }
1190
1229
  conversationId?: string
1191
1230
  events?: AsyncIterable<{
@@ -1201,7 +1240,37 @@ export async function runAnswer({
1201
1240
  }
1202
1241
  error?: { status?: number; message?: string }
1203
1242
  }>
1204
- }> {
1243
+ }
1244
+
1245
+ /** One user-visible turn. A regional miss retries once, and only when the agent URL changed. */
1246
+ export async function runAnswer(opts: RunAnswerOptions): Promise<RunAnswerResult> {
1247
+ const t = trace
1248
+ if (!t) return answer(opts)
1249
+ return t.within({ token: opts.tok, model: opts.model }, async () => {
1250
+ const ran = await answer(opts)
1251
+ if (ran.error && !opts.signal?.aborted) t.note("failed", { error: ran.error })
1252
+ return ran.events ? { ...ran, events: t.carry(ran.events) } : ran
1253
+ })
1254
+ }
1255
+
1256
+ async function answer({
1257
+ tok,
1258
+ model,
1259
+ effort = "",
1260
+ fast,
1261
+ messages,
1262
+ tools = [],
1263
+ session = "",
1264
+ signal,
1265
+ connect,
1266
+ resolveAgentURL = agentURL,
1267
+ rawModels,
1268
+ onResponse,
1269
+ onPayload,
1270
+ headers,
1271
+ headerWaitMs = H2.wait,
1272
+ toolIdleMs = TOOL_IDLE_MS,
1273
+ }: RunAnswerOptions): Promise<RunAnswerResult> {
1205
1274
  const chat = {
1206
1275
  model,
1207
1276
  messages,
@@ -1223,6 +1292,7 @@ export async function runAnswer({
1223
1292
  try {
1224
1293
  const conv = conversation(chat, listed)
1225
1294
  const resumed = prepared.owner.resume({ ...prepared, estimate: conv.estimate }, signal)
1295
+ trace?.note("native", { path: "resumed" })
1226
1296
  return { conversationId: convID, events: withDelivery(prepared.owner, resumed.events) }
1227
1297
  } catch (e) {
1228
1298
  return { error: { status: e?.status ?? 502, message: e?.message ?? String(e) } }
@@ -1231,7 +1301,7 @@ export async function runAnswer({
1231
1301
  let raw = rawModels
1232
1302
  if (raw === undefined) {
1233
1303
  try {
1234
- raw = await usable(tok)
1304
+ raw = await usable(tok, false, signal)
1235
1305
  } catch {
1236
1306
  raw = []
1237
1307
  }
@@ -1241,25 +1311,35 @@ export async function runAnswer({
1241
1311
  let params = resolved.params
1242
1312
  let maxMode = resolved.maxMode || maxOnly.has(id)
1243
1313
  const conv = conversation(chat, listed)
1244
- let base = await resolveAgentURL(tok, false)
1314
+ let base = await resolveAgentURL(tok, false, signal)
1245
1315
  const once = async () => {
1246
- const native = prepared.fallback ? null : nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure })
1316
+ const made = nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure, trace })
1317
+ const native = made.fallback ? null : made
1318
+ trace?.note("native", native ? { path: "created" } : { path: "declined", fallback: made.fallback, detail: made.detail })
1247
1319
  const args = { tok, base, id, tools: listed, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }
1248
1320
  let response = native ? await runNative({ ...args, native }) : await runOnce(args)
1249
- if (response.error?.retentionIneligible && !signal?.aborted) response = await runOnce(args)
1321
+ if (response.error?.retentionIneligible && !signal?.aborted) {
1322
+ trace?.note("native", { path: "abandoned", error: response.error })
1323
+ response = await runOnce(args)
1324
+ }
1250
1325
  return response
1251
1326
  }
1252
1327
  let ran = await once()
1328
+ if (signal?.aborted) return ran
1253
1329
  if (ran.error && regional(ran.error.message)) {
1254
1330
  resetH1()
1255
- const fresh = await resolveAgentURL(tok, true)
1331
+ const fresh = await resolveAgentURL(tok, true, signal)
1256
1332
  const viaH1 = !!ran.h1
1257
- if (fresh !== base || viaH1) {
1333
+ const again = (fresh !== base || viaH1) && !signal?.aborted
1334
+ trace?.note("retry", { rule: "region", error: ran.error, to: again ? fresh : undefined, cancelled: !!signal?.aborted })
1335
+ if (again) {
1258
1336
  base = fresh
1259
1337
  ran = await once()
1260
1338
  }
1261
1339
  }
1340
+ if (signal?.aborted) return ran
1262
1341
  if (ran.error && !maxMode && maxRequired(ran.error.message)) {
1342
+ trace?.note("retry", { rule: "max-mode", error: ran.error, model: id })
1263
1343
  maxMode = true
1264
1344
  maxOnly.add(id)
1265
1345
  ran = await once()
package/src/sleep.ts ADDED
@@ -0,0 +1,29 @@
1
+ const CANCELLED = "Cursor sign-in cancelled"
2
+
3
+ export function sleep(
4
+ ms: number,
5
+ signal?: AbortSignal,
6
+ onAbort: "reject" | "resolve" = "reject",
7
+ ): Promise<void> {
8
+ return new Promise((resolve, reject) => {
9
+ const cancel = () => {
10
+ if (onAbort === "resolve") resolve()
11
+ else reject(new Error(CANCELLED))
12
+ }
13
+ if (signal?.aborted) {
14
+ cancel()
15
+ return
16
+ }
17
+ let settled = false
18
+ const finish = (fn: () => void) => {
19
+ if (settled) return
20
+ settled = true
21
+ clearTimeout(timer)
22
+ signal?.removeEventListener("abort", abort)
23
+ fn()
24
+ }
25
+ const abort = () => finish(cancel)
26
+ const timer = setTimeout(() => finish(resolve), ms)
27
+ signal?.addEventListener("abort", abort)
28
+ })
29
+ }