@caph42/pi-cursor-provider 0.7.1 → 0.8.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.8.1
6
+
7
+ - HTTP/1.1 fallback reports the real RunSSE status and headers. The first BidiAppend still goes out after RunSSE is issued and before those headers arrive.
8
+ - A RunSSE request that never returns headers, or a successful one that never sends a Run frame, now ends on its own 30 second deadline. BidiAppend keeps its own timeout. Cancelling the turn is still a cancellation.
9
+ - A stateless tool batch in a kept conversation no longer waits out a slow usage read before the tools are returned. The read continues in the background, and the deferred ledger still attributes it once.
10
+
11
+ ## 0.8.0
12
+
13
+ - Selecting another Cursor model while fast is on carries it to that model when the response is finished and the model supports fast at the current thinking level. The previous model stays on. A busy response, a model without support, or a model that is already on does not record another change. Turning it off does not turn off the model being left.
14
+ - `/cursor.fast` now remembers the models left on for the session's working directory. The record is `cursor-fast.json` beside `cursor.json`, separate from that hand-edited file. A new session in the same directory inherits it. The first change on a branch records the inherited models too, so a reload keeps them. A branch that already chose, including one that turned fast off, keeps its own choice. A different directory, and a directory change inside an existing session, do not move the switch. A failed write still changes the current session and says the directory preference was not saved.
15
+
5
16
  ## 0.7.1
6
17
 
7
18
  - Republished after npm staged 0.7.0 without making it installable.
package/README.md CHANGED
@@ -109,7 +109,7 @@ Select a Cursor model, then use:
109
109
 
110
110
  With no argument, `/cursor.fast` toggles the current model: off becomes on, and on becomes off. `/cursor.fast on` and `/cursor.fast off` set it explicitly. In the TUI, type `/cursor.fast ` and press Tab to choose `on` or `off`; a unique prefix such as `of` completes to `off` without executing the command. `/cursor.fast status` only reports the current state. In the TUI, enabled fast shows `Fast` on the second footer row beside the model/thinking information. Off shows nothing there. Other extension statuses retain their own row. The same text is also published through `ctx.ui.setStatus`, so a footer that renders extension statuses — Pi's own footer, or pi-ccline's — still shows it when another extension owns the footer slot; Cursor's footer filters that key out, so it never appears twice. RPC clients continue receiving the `cursor-fast` status text. Enabling fast preserves the selected model ID, context size, and thinking level. It requires an account-available fast variant at the same context and effective thinking parameters; unsupported combinations are rejected.
111
111
 
112
- The setting defaults to off and belongs to the current model in the current session. Other models keep their own settings. Reloading or resuming that session restores the setting from its current branch; a new session starts with fast off. Changes apply to the next request and require the current response to finish first.
112
+ The setting defaults to off and belongs to the current model. Selecting another Cursor model while fast is on carries that choice when the response is finished and the new model supports fast at the current thinking level; a busy response, a model without fast, or a model that is already on leaves the recorded choices unchanged. Turning it off does not turn off the model being left. Turning it on or off is recorded in the current session branch and in `cursor-fast.json` beside `cursor.json`, keyed by the session's working directory. The first change on a branch also records the models that branch inherited, so a later reload keeps every model, not only the one just changed. A branch that already chose — including one that turned fast off — wins over the file. A new session with no choice of its own inherits the models last left on in that directory, so the same project starts with fast on again; a different directory does not. Changing directory inside a session does not move the switch. If the directory file cannot be written, the change still applies to this session and Pi says it was not saved. Changes apply to the next request and require the current response to finish first.
113
113
 
114
114
  If fast is enabled and a later thinking change or catalogue update removes support, the footer shows `Fast unavailable` and requests report an error until you select a supported thinking level or run `/cursor.fast off`. The command does not add duplicate fast models to `/model`.
115
115
 
@@ -178,7 +178,7 @@ The stateless path still cancels the stream after tools. The native path does no
178
178
  ## Transport
179
179
 
180
180
  - Default: HTTP/2 `AgentService/Run` at the agent host from `ServerConfigService/GetServerConfig` (else the global agent URL).
181
- - When HTTP/2 cannot open (no response head in 15s, ALPN / "h2 is not supported" / HTTP/2 protocol errors), the Run goes as Cursor's clients do without HTTP/2: `AgentService/RunSSE` down and `BidiService/BidiAppend` up over HTTP/1.1 on `api2.cursor.sh`. Blocked HTTP/2 keeps later Runs on HTTP/1.1 for 10 minutes; a plain connection failure leaves the next Run to try HTTP/2 again.
181
+ - When HTTP/2 cannot open (no response head in 15s, ALPN / "h2 is not supported" / HTTP/2 protocol errors), the Run goes as Cursor's clients do without HTTP/2: `AgentService/RunSSE` down and `BidiService/BidiAppend` up over HTTP/1.1 on `api2.cursor.sh`. The first append follows the RunSSE request and does not wait for its headers. RunSSE itself gives up after 30 seconds without headers, and again after 30 seconds without a Run frame. Blocked HTTP/2 keeps later Runs on HTTP/1.1 for 10 minutes; a plain connection failure leaves the next Run to try HTTP/2 again.
182
182
  - A regional refusal refreshes GetServerConfig and retries once when the agent URL changed (or the failed attempt was already on HTTP/1.1). That refresh clears the HTTP/1.1 stickiness so the region's agent host can use HTTP/2 again.
183
183
  - "Max Mode Required" retries once with Max Mode and remembers that model id for the process.
184
184
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caph42/pi-cursor-provider",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
4
4
  "description": "Cursor provider for Pi: one HTTP/2 AgentService/Run per turn (magpie-aligned).",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/agent-run.ts CHANGED
@@ -9,7 +9,7 @@ import { clientVersion } from "./client.ts"
9
9
  import { canRead, ledger, owe, STEP_WAIT, usageKey } from "./ledger.ts"
10
10
  import { NATIVE_LIMITS, NativeSessionError, nativeSessions } from "./native-session.ts"
11
11
  import { buildRun, decode, exec, usageOf, type BlobStore, type ChatTool, type Conversation, type Frame, type ModelParam, type Payload, type RunError, type RunEvent } from "./protocol.ts"
12
- import { cancelledOpen, open, type Connect, type RunStream } from "./transport.ts"
12
+ import { cancelledOpen, open, type Connect, type EarlyWrite, type RunStream } from "./transport.ts"
13
13
  import { trace } from "./trace.ts"
14
14
 
15
15
  export type RunArgs = {
@@ -28,6 +28,7 @@ export type RunArgs = {
28
28
  onPayload?: (payload: Payload) => unknown
29
29
  headers?: Record<string, string | null | undefined>
30
30
  headerWaitMs?: number
31
+ firstFrameWaitMs?: number
31
32
  toolIdleMs?: number
32
33
  }
33
34
 
@@ -100,7 +101,7 @@ export function resumeRun(prepared: { owner: NativeOwner }, estimate: number, si
100
101
  return withDelivery(prepared.owner, resumed.events)
101
102
  }
102
103
 
103
- async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }: RunArgs): Promise<RunResult> {
104
+ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, firstFrameWaitMs, toolIdleMs }: RunArgs): Promise<RunResult> {
104
105
  const cid = convID || randomUUID()
105
106
  const since = Date.now()
106
107
  const book = ledger(tok, cid, since, signal, !!convID)
@@ -113,7 +114,11 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
113
114
  }
114
115
  const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
115
116
  const version = await clientVersion()
116
- const o = await open({ base, tok, headers, version, signal, connect, headerWaitMs })
117
+ // HTTP/1.1 sends this as BidiAppend after RunSSE is issued and before its
118
+ // headers, so a server that answers only after that append cannot deadlock
119
+ // open(). HTTP/2 writes it on its own stream once the response is open.
120
+ const pending: EarlyWrite[] = [{ chunk: frame(first), cb() {} }]
121
+ const o = await open({ base, tok, headers, version, signal, connect, headerWaitMs, firstFrameWaitMs, pending })
117
122
  if (o.error) return book.done(), { ...o, h1: !!o.h1 }
118
123
  if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
119
124
  const { session, req } = o
@@ -145,7 +150,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
145
150
  book.done()
146
151
  return cancelledOpen()
147
152
  }
148
- send(first)
153
+ if (!o.h1 && pending.length === 0) send(first)
149
154
  if (o.status < 200 || o.status > 299) {
150
155
  const chunks: Buffer[] = []
151
156
  let bodyCut = false
@@ -305,7 +310,7 @@ function nativeTransport(req: RunStream, close: () => void, fail: (e: unknown) =
305
310
  }
306
311
  }
307
312
 
308
- async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native, connect, onResponse, onPayload, headers, headerWaitMs }: RunArgs & { native: NativeOwner }): Promise<RunResult> {
313
+ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native, connect, onResponse, onPayload, headers, headerWaitMs, firstFrameWaitMs }: RunArgs & { native: NativeOwner }): Promise<RunResult> {
309
314
  const cid = convID || randomUUID()
310
315
  const since = Date.now()
311
316
  const accounting = new AbortController()
@@ -358,7 +363,8 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode,
358
363
  return { error: native.error }
359
364
  }
360
365
  const version = await clientVersion()
361
- const o = await open({ base, tok, headers, version, signal: native.ac.signal, connect, headerWaitMs })
366
+ const pending: EarlyWrite[] = [{ chunk: frame(first), cb() {} }]
367
+ const o = await open({ base, tok, headers, version, signal: native.ac.signal, connect, headerWaitMs, firstFrameWaitMs, pending })
362
368
  if (o.error) {
363
369
  native.fail(o.error)
364
370
  nativeSessions.forget(native)
@@ -381,7 +387,7 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode,
381
387
  nativeSessions.forget(native)
382
388
  return { error: native.error, h1: !!o.h1 }
383
389
  }
384
- native.send(first)
390
+ if (!o.h1 && pending.length === 0) native.send(first)
385
391
  native.accounting.started()
386
392
  if (o.status < 200 || o.status > 299) {
387
393
  const chunks: Buffer[] = []
package/src/codec.ts CHANGED
@@ -228,6 +228,7 @@ export function statusOf(status, code, msg) {
228
228
  return out(400, "input is too long for the model's context: " + msg)
229
229
  if (code === "invalid_argument") return out(400, msg)
230
230
  if (code === "unavailable") return out(503, msg)
231
+ if (code === "deadline_exceeded") return out(504, msg)
231
232
  if (code) return out(502, msg)
232
233
  return out(status, msg)
233
234
  }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Fast preferences remembered by the session's working directory.
3
+ *
4
+ * A session branch is still the source of truth once it has its own
5
+ * `cursor-fast` entries. A new session in a directory that was used before
6
+ * starts from the models last left on here, instead of the global default of
7
+ * off. The file sits beside `cursor.json` and is never merged into it:
8
+ * that file is hand-edited, and a bad write must not change what it hides.
9
+ *
10
+ * { "directories": { "/abs/project": ["grok-test@256k"] } }
11
+ *
12
+ * Keys are real paths. A missing, unreadable, or malformed file remembers
13
+ * nothing, and a failed write leaves the command's session entry in place.
14
+ */
15
+ import { readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs"
16
+ import { homedir } from "node:os"
17
+ import { join, normalize, resolve } from "node:path"
18
+
19
+ export const FAST_MEMORY_FILE = "cursor-fast.json"
20
+
21
+ /** `cursor-fast.json` beside the rest of Pi's config. */
22
+ export function fastMemoryPath(env: NodeJS.ProcessEnv = process.env): string {
23
+ const dir = (env.PI_CODING_AGENT_DIR ?? "").trim()
24
+ return join(dir || join(homedir(), ".pi", "agent"), FAST_MEMORY_FILE)
25
+ }
26
+
27
+ /** One spelling for a directory: the real path when it exists, otherwise the absolute path without `.` or `..`. */
28
+ export function canonicalCwd(cwd: string): string | undefined {
29
+ const trimmed = cwd.trim()
30
+ if (!trimmed) return undefined
31
+ const absolute = normalize(resolve(trimmed))
32
+ try {
33
+ return realpathSync(absolute)
34
+ } catch {
35
+ return absolute
36
+ }
37
+ }
38
+
39
+ function modelIds(value: unknown): string[] {
40
+ if (!Array.isArray(value)) return []
41
+ return [...new Set(value.flatMap((id) => (typeof id === "string" && id.trim() ? [id.trim()] : [])))]
42
+ }
43
+
44
+ /** Models last left on in each directory. Anything that is not that map is ignored. */
45
+ export function readFastMemory(path: string = fastMemoryPath()): Map<string, string[]> {
46
+ let json: unknown
47
+ try {
48
+ json = JSON.parse(readFileSync(path, "utf8"))
49
+ } catch {
50
+ return new Map()
51
+ }
52
+ const directories = (json as { directories?: unknown } | null)?.directories
53
+ if (!directories || typeof directories !== "object" || Array.isArray(directories)) return new Map()
54
+ const memory = new Map<string, string[]>()
55
+ for (const [cwd, models] of Object.entries(directories)) {
56
+ const key = canonicalCwd(cwd)
57
+ const ids = modelIds(models)
58
+ if (key && ids.length) memory.set(key, ids)
59
+ }
60
+ return memory
61
+ }
62
+
63
+ /** Replace one directory's remembered models. An empty list forgets the directory.
64
+ * A failed write returns false and leaves the previous file alone. */
65
+ export function writeFastDirectory(cwd: string, models: Iterable<string>, path: string = fastMemoryPath()): boolean {
66
+ const key = canonicalCwd(cwd)
67
+ if (!key) return false
68
+ const memory = readFastMemory(path)
69
+ const ids = modelIds([...models])
70
+ if (ids.length) memory.set(key, ids)
71
+ else memory.delete(key)
72
+ const directories = Object.fromEntries([...memory].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
73
+ const next = path + ".tmp"
74
+ try {
75
+ writeFileSync(next, JSON.stringify({ directories }) + "\n")
76
+ renameSync(next, path)
77
+ return true
78
+ } catch {
79
+ return false
80
+ }
81
+ }
package/src/fast.ts CHANGED
@@ -3,6 +3,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
3
3
  import { streamCursor } from "./pi-stream.ts"
4
4
  import { createFastFooter, supportsInlineFastFooter } from "./fast-footer.ts"
5
5
  import { cursorFastAutocomplete } from "./fast-autocomplete.ts"
6
+ import { canonicalCwd, readFastMemory, writeFastDirectory } from "./fast-memory.ts"
6
7
 
7
8
  const ENTRY = "cursor-fast"
8
9
  const STATUS = "cursor-fast"
@@ -11,6 +12,7 @@ type FastModel = Model<any> & { cursorFastLevels?: string[] }
11
12
 
12
13
  export function registerCursorFast(pi: ExtensionAPI) {
13
14
  const enabled = new Set<string>()
15
+ let activeModel: string | undefined
14
16
  let sessionId: string | undefined
15
17
  let currentContext: ExtensionContext | undefined
16
18
  let badge = ""
@@ -76,17 +78,65 @@ export function registerCursorFast(pi: ExtensionAPI) {
76
78
  display(ctx, supported(model, pi.getThinkingLevel()) ? "Fast" : "Fast unavailable")
77
79
  }
78
80
 
81
+ // A branch that already chose is left alone, including a branch that turned
82
+ // fast off. Only a session with no choice of its own inherits the directory.
83
+ function directoryOf(ctx: ExtensionContext): string | undefined {
84
+ const cwd = ctx.sessionManager.getCwd?.()
85
+ return typeof cwd === "string" ? canonicalCwd(cwd) : undefined
86
+ }
87
+
88
+ function chosen(ctx: ExtensionContext): Array<{ model: string; enabled: boolean }> {
89
+ return ctx.sessionManager.getBranch().flatMap((entry) => {
90
+ if (entry.type !== "custom" || entry.customType !== ENTRY) return []
91
+ const data = entry.data as { model?: unknown; enabled?: unknown } | undefined
92
+ return typeof data?.model === "string" && typeof data.enabled === "boolean" ? [{ model: data.model, enabled: data.enabled }] : []
93
+ })
94
+ }
95
+
96
+ function remember(ctx: ExtensionContext): boolean {
97
+ const cwd = directoryOf(ctx)
98
+ return cwd ? writeFastDirectory(cwd, enabled) : true
99
+ }
100
+
101
+ function record(ctx: ExtensionContext, model: string, on: boolean): boolean {
102
+ if (!chosen(ctx).length) {
103
+ for (const id of enabled) {
104
+ if (id !== model) pi.appendEntry(ENTRY, { model: id, enabled: true })
105
+ }
106
+ }
107
+ pi.appendEntry(ENTRY, { model, enabled: on })
108
+ if (on) enabled.add(model)
109
+ else enabled.delete(model)
110
+ return remember(ctx)
111
+ }
112
+
113
+ function carry(ctx: ExtensionContext) {
114
+ const next = modelOf(ctx)
115
+ const previous = activeModel
116
+ if (next) activeModel = next.id
117
+ if (!next || !previous || previous === next.id || !enabled.has(previous)) return
118
+ if (!ctx.isIdle()) return
119
+ if (enabled.has(next.id) || !supported(next, pi.getThinkingLevel())) return
120
+ if (!record(ctx, next.id, true)) {
121
+ ctx.ui.notify("Cursor fast followed the model, but the directory preference could not be saved.", "warning")
122
+ }
123
+ }
124
+
79
125
  function restore(ctx: ExtensionContext) {
80
126
  enabled.clear()
81
127
  sessionId = ctx.sessionManager.getSessionId()
82
- for (const entry of ctx.sessionManager.getBranch()) {
83
- if (entry.type !== "custom" || entry.customType !== ENTRY) continue
84
- const data = entry.data as { model?: unknown; enabled?: unknown } | undefined
85
- if (typeof data?.model !== "string" || typeof data.enabled !== "boolean") continue
86
- if (data.enabled) enabled.add(data.model)
87
- else enabled.delete(data.model)
128
+ const entries = chosen(ctx)
129
+ if (entries.length) {
130
+ for (const entry of entries) {
131
+ if (entry.enabled) enabled.add(entry.model)
132
+ else enabled.delete(entry.model)
133
+ }
134
+ } else {
135
+ const cwd = directoryOf(ctx)
136
+ for (const model of (cwd ? readFastMemory().get(cwd) : undefined) ?? []) enabled.add(model)
88
137
  }
89
138
  updateStatus(ctx)
139
+ activeModel = modelOf(ctx)?.id
90
140
  }
91
141
 
92
142
  pi.on("session_start", (_event, ctx) => {
@@ -105,7 +155,7 @@ export function registerCursorFast(pi: ExtensionAPI) {
105
155
  autocompleteInstalled = false
106
156
  enabled.clear()
107
157
  })
108
- pi.on("model_select", (_event, ctx) => updateStatus(ctx))
158
+ pi.on("model_select", (_event, ctx) => { carry(ctx); updateStatus(ctx) })
109
159
  pi.on("thinking_level_select", (_event, ctx) => updateStatus(ctx))
110
160
  pi.on("before_agent_start", (_event, ctx) => updateStatus(ctx))
111
161
 
@@ -136,9 +186,11 @@ export function registerCursorFast(pi: ExtensionAPI) {
136
186
  }
137
187
  if (action !== "status") {
138
188
  const on = action === "on"
139
- pi.appendEntry(ENTRY, { model: model.id, enabled: on })
140
- if (on) enabled.add(model.id)
141
- else enabled.delete(model.id)
189
+ // The first choice on a branch has to carry the models it inherited.
190
+ // Recording only the model just changed would drop the others on reload.
191
+ if (!record(ctx, model.id, on)) {
192
+ ctx.ui.notify("Cursor fast changed for this session, but the directory preference could not be saved.", "warning")
193
+ }
142
194
  }
143
195
  updateStatus(ctx)
144
196
  const on = enabled.has(model.id)
package/src/ledger.ts CHANGED
@@ -33,6 +33,8 @@ export const STEP_WAIT = {
33
33
  owedFor: 600_000,
34
34
  }
35
35
 
36
+ const HANDBACK_MS = 30
37
+
36
38
  // claimed are the usage events already counted, by account, conversation
37
39
  // and time, so that two steps of one conversation never count the same one.
38
40
  const claimed = new Map()
@@ -272,23 +274,35 @@ export function ledger(tok, conv, since, signal, kept, { before } = {}) {
272
274
  let mine = null
273
275
  let theirs = null
274
276
  let over = false
277
+ const assign = (usage, carry) => {
278
+ if (over) {
279
+ const left = addUsage(carry, usage)
280
+ if (left) owe(debtKey, { carry: left })
281
+ return
282
+ }
283
+ theirs = addUsage(theirs, carry)
284
+ mine = addUsage(mine, usage)
285
+ }
275
286
  const gather = (opts) =>
276
287
  collect(tok, conv, { ...opts, over: () => over, abortFetch: before !== undefined }).then((r) => {
277
- theirs = addUsage(theirs, r.carry)
288
+ let usage = null
289
+ let carry = r.carry && { ...r.carry }
278
290
  for (const e of r.events ?? []) {
279
- if (e.at >= since - 1000) mine = addUsage(mine, e.usage)
280
- else theirs = addUsage(theirs, e.usage)
291
+ if (e.at >= since - 1000) usage = addUsage(usage, e.usage)
292
+ else carry = addUsage(carry, e.usage)
281
293
  }
294
+ assign(usage, carry)
282
295
  return r
283
296
  })
284
297
  let collecting = null
298
+ let reading = null
285
299
  const debt = kept ? owed.get(debtKey) : undefined
286
300
  const timer = debt ? setTimeout(() => (collecting = gather()), Math.max(0, debt.ready - Date.now())) : null
287
301
  timer?.unref?.()
288
302
  const takeMine = () => {
289
303
  const u = mine
290
304
  mine = null
291
- return u
305
+ return u ?? false
292
306
  }
293
307
  const take = () => {
294
308
  const u = addUsage(theirs, mine)
@@ -302,7 +316,7 @@ export function ledger(tok, conv, since, signal, kept, { before } = {}) {
302
316
  const waits = stepsWait(m)
303
317
  if (!kept) {
304
318
  const r = waits
305
- ? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch((e) => {
319
+ ? await usageEvents(tok, conv, since, 1, { poll: true, first: 0, signal }).catch((e) => {
306
320
  trace?.note("usage", { error: e })
307
321
  return {}
308
322
  })
@@ -311,14 +325,39 @@ export function ledger(tok, conv, since, signal, kept, { before } = {}) {
311
325
  else if (!r.refused) misses.set(key, m + 1)
312
326
  return r.usage ?? null
313
327
  }
328
+ // A stateless Run of a kept conversation returns tools before Pi runs
329
+ // them. Record the debt and ask once in the background: a slow dashboard
330
+ // must not hold the tool batch. Later steps and the final settlement
331
+ // collect it, and claimed timestamps keep it from being counted twice.
314
332
  owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
315
333
  if (waits) {
316
- const r = await gather({ poll: true, signal })
317
- if (!canRead(tok)) return null
318
- if (r.short) misses.set(key, m + 1)
319
- else misses.delete(key)
334
+ let ready = false
335
+ reading = gather({ poll: false, signal }).then((r) => {
336
+ ready = true
337
+ if (!canRead(tok)) return null
338
+ if (r.short) misses.set(key, m + 1)
339
+ else misses.delete(key)
340
+ return true
341
+ })
342
+ const set = flights.get(debtKey) ?? new Set()
343
+ flights.set(debtKey, set.add(reading))
344
+ reading.finally(() => {
345
+ set.delete(reading)
346
+ if (!set.size && flights.get(debtKey) === set) flights.delete(debtKey)
347
+ })
348
+ if (HANDBACK_MS > 0) {
349
+ const won = await Promise.race([
350
+ reading.then(() => true),
351
+ sleep(HANDBACK_MS, signal, "resolve").then(() => false),
352
+ ])
353
+ if (won) return takeMine()
354
+ }
355
+ queueMicrotask(() => {
356
+ if (ready) takeMine()
357
+ })
358
+ return false
320
359
  } else misses.set(key, m + 1)
321
- return takeMine() ?? false
360
+ return false
322
361
  },
323
362
  async owed(final) {
324
363
  if (!kept) return null
package/src/protocol.ts CHANGED
@@ -395,6 +395,8 @@ export async function* decode(
395
395
  usage = u
396
396
  outputSource = "measured"
397
397
  }
398
+ // false: the dashboard was read and had nothing. null: the read is still
399
+ // running, so the estimate stands and the deferred ledger keeps the debt.
398
400
  counted = u === false || !!u
399
401
  } else if (calls > 0) {
400
402
  close?.()
package/src/run.ts CHANGED
@@ -54,6 +54,8 @@ export type RunAnswerOptions = {
54
54
  onPayload?: (payload: unknown) => unknown
55
55
  headers?: Record<string, string | null | undefined>
56
56
  headerWaitMs?: number
57
+ /** How long HTTP/1.1 RunSSE may take for headers and then its first frame. */
58
+ firstFrameWaitMs?: number
57
59
  toolIdleMs?: number
58
60
  }
59
61
 
@@ -101,6 +103,7 @@ async function answer({
101
103
  onPayload,
102
104
  headers,
103
105
  headerWaitMs,
106
+ firstFrameWaitMs,
104
107
  toolIdleMs,
105
108
  }: RunAnswerOptions): Promise<RunAnswerResult> {
106
109
  const chat = {
@@ -144,7 +147,7 @@ async function answer({
144
147
  const conv = conversation(chat, listed)
145
148
  let base = await resolveAgentURL(tok, false, signal)
146
149
  const once = () => {
147
- const args: RunArgs = { tok, base, id, tools: listed, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }
150
+ const args: RunArgs = { tok, base, id, tools: listed, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, firstFrameWaitMs, toolIdleMs }
148
151
  return startRun(prepared, args)
149
152
  }
150
153
  let ran = await once()
package/src/transport.ts CHANGED
@@ -23,6 +23,9 @@ export type Opened = {
23
23
  h1?: boolean
24
24
  }
25
25
 
26
+ /** What the caller wrote before the transport knew which stream would carry it. */
27
+ export type EarlyWrite = { chunk: Buffer; cb: (error?: Error | null) => void }
28
+
26
29
  /** A Run that never got its response headers. h2Failed: HTTP/2 itself failed. blocked: and it will keep failing here. */
27
30
  export type OpenFailed = {
28
31
  error: { status: number; message: string }
@@ -44,6 +47,10 @@ export type OpenRequest = {
44
47
  signal?: AbortSignal
45
48
  connect?: Connect
46
49
  headerWaitMs?: number
50
+ /** How long HTTP/1.1 RunSSE may take to send headers, then its first Run frame. */
51
+ firstFrameWaitMs?: number
52
+ /** Writes made while the transport was still opening. HTTP/1.1 sends them as BidiAppend. */
53
+ pending?: EarlyWrite[]
47
54
  version: string
48
55
  }
49
56
 
@@ -62,7 +69,15 @@ const H2 = {
62
69
  wait: 15_000,
63
70
  retryAfter: 10 * 60_000,
64
71
  }
65
- const H1 = { appendWait: 60_000 }
72
+ const H1 = {
73
+ appendWait: 60_000,
74
+ // RunSSE's own bound: response headers, then the first Run frame. Distinct
75
+ // from the HTTP/2 header timer, so a caller shortening that one to fall back
76
+ // faster does not also shorten a slow model's first byte. BidiAppend has its
77
+ // own deadline and does not cover either wait.
78
+ response: 30_000,
79
+ firstFrame: 30_000,
80
+ }
66
81
  const NET = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ECONNRESET", "ETIMEDOUT", "ECONNABORTED", "EPIPE"]
67
82
 
68
83
  export const cancelledOpen = (): OpenFailed => ({ error: { status: 410, message: "the request was cancelled" }, h2Failed: false })
@@ -155,14 +170,25 @@ function openH2(base: string, headers: Record<string, string>, signal: AbortSign
155
170
  })
156
171
  }
157
172
 
158
- function openH1(headers: Record<string, string>, signal: AbortSignal | undefined): Promise<Opened | OpenFailed> {
173
+ function headerRecord(res: Response): Record<string, string> {
174
+ const headers: Record<string, string> = {}
175
+ res.headers.forEach((value, key) => {
176
+ headers[key] = headers[key] ? `${headers[key]}, ${value}` : value
177
+ })
178
+ return headers
179
+ }
180
+
181
+ function openH1(headers: Record<string, string>, signal: AbortSignal | undefined, responseMs: number, firstFrameMs: number, pending: EarlyWrite[] = []): Promise<Opened | OpenFailed> {
159
182
  if (signal?.aborted) return Promise.resolve(cancelledOpen())
160
183
  const ac = new AbortController()
161
184
  const id = headers["x-request-id"]
162
185
  const h = { ...headers, "accept-encoding": "identity", "x-cursor-streaming": "true" }
163
186
  let ended = false
164
187
  let seq = 0
188
+ let opened = false
165
189
  let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
190
+ let responseTimer: ReturnType<typeof setTimeout> | undefined
191
+ let firstFrame: ReturnType<typeof setTimeout> | undefined
166
192
  const req = new Duplex({
167
193
  read() {},
168
194
  write(chunk, _enc, cb) {
@@ -171,7 +197,17 @@ function openH1(headers: Record<string, string>, signal: AbortSignal | undefined
171
197
  append(msg, n).then(() => cb(), (e) => cb(e))
172
198
  },
173
199
  })
200
+ const stopResponse = () => {
201
+ clearTimeout(responseTimer)
202
+ responseTimer = undefined
203
+ }
204
+ const stopFirstFrame = () => {
205
+ clearTimeout(firstFrame)
206
+ firstFrame = undefined
207
+ }
174
208
  const cleanup = () => {
209
+ stopResponse()
210
+ stopFirstFrame()
175
211
  signal?.removeEventListener("abort", close)
176
212
  ac.abort()
177
213
  reader?.cancel().catch(() => {})
@@ -218,55 +254,129 @@ function openH1(headers: Record<string, string>, signal: AbortSignal | undefined
218
254
  cleanup()
219
255
  req.destroy()
220
256
  }
257
+ let settle = (_result: Opened | OpenFailed) => {}
258
+ const miss = (which: "headers" | "frame", ms: number) => {
259
+ const message = which === "headers"
260
+ ? `RunSSE sent no response headers in ${Math.round(ms / 1000)}s`
261
+ : `RunSSE sent no frame in ${Math.round(ms / 1000)}s`
262
+ end(JSON.stringify({ error: { code: "deadline_exceeded", message } }))
263
+ settle({ error: { status: 504, message }, h2Failed: false })
264
+ }
265
+ const armResponse = () => {
266
+ responseTimer = setTimeout(() => miss("headers", responseMs), responseMs)
267
+ responseTimer.unref?.()
268
+ }
269
+ const armFirstFrame = () => {
270
+ firstFrame = setTimeout(() => miss("frame", firstFrameMs), firstFrameMs)
271
+ firstFrame.unref?.()
272
+ }
273
+ // A complete Connect frame is the first thing the Run produced. Heartbeats
274
+ // are those frames too. A partial frame leaves the deadline armed.
275
+ const sawFrame = (chunk: Uint8Array) => {
276
+ if (!firstFrame) return
277
+ const next = Buffer.from(chunk)
278
+ buf = buf.length ? Buffer.concat([buf, next]) : next
279
+ if (buf.length >= 5 && buf.length >= 5 + buf.readUInt32BE(1)) stopFirstFrame()
280
+ }
281
+ let buf: Buffer = Buffer.alloc(0)
282
+ const openedReq = Object.assign(req, {
283
+ close,
284
+ push(chunk: unknown, encoding?: BufferEncoding) {
285
+ if (Buffer.isBuffer(chunk)) sawFrame(chunk)
286
+ return Duplex.prototype.push.call(req, chunk, encoding)
287
+ },
288
+ })
221
289
  signal?.addEventListener("abort", close, { once: true })
222
290
  if (signal?.aborted) {
223
291
  close()
224
292
  return Promise.resolve(cancelledOpen())
225
293
  }
226
- ;(async () => {
227
- try {
228
- const res = await fetch(API + "/agent.v1.AgentService/RunSSE", {
229
- method: "POST",
230
- headers: { ...h, "content-type": "application/connect+proto", "connect-protocol-version": "1" },
231
- body: frame(pb().str(1, id).done()),
232
- signal: ac.signal,
233
- })
234
- if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
235
- if (!res.ok) return failed(res)
236
- reader = res.body!.getReader()
294
+ // RunSSE is issued first, then the buffered first message becomes BidiAppend
295
+ // before those headers come back. open() still resolves from the real headers.
296
+ const ready = new Promise<Opened | OpenFailed>((resolve) => {
297
+ settle = (result) => {
298
+ if (opened) return
299
+ opened = true
300
+ resolve(result)
301
+ }
302
+ armResponse()
303
+ ;(async () => {
237
304
  try {
238
- while (!ended && !req.destroyed) {
239
- const { value, done } = await reader.read()
240
- if (done) break
241
- if (!ended && !req.destroyed) req.push(Buffer.from(value))
305
+ const response = fetch(API + "/agent.v1.AgentService/RunSSE", {
306
+ method: "POST",
307
+ headers: { ...h, "content-type": "application/connect+proto", "connect-protocol-version": "1" },
308
+ body: frame(pb().str(1, id).done()),
309
+ signal: ac.signal,
310
+ })
311
+ for (const write of pending.splice(0)) req.write(write.chunk, write.cb)
312
+ const res = await response
313
+ stopResponse()
314
+ if (ended || ac.signal.aborted) {
315
+ await res.body?.cancel().catch(() => {})
316
+ settle(cancelledOpen())
317
+ return
318
+ }
319
+ settle({
320
+ session: { close, destroy: close },
321
+ req: openedReq,
322
+ status: res.status,
323
+ headers: headerRecord(res),
324
+ h1: true,
325
+ })
326
+ if (!res.ok) return failed(res)
327
+ armFirstFrame()
328
+ reader = res.body!.getReader()
329
+ try {
330
+ while (!ended && !req.destroyed) {
331
+ const { value, done } = await reader.read()
332
+ if (done) break
333
+ if (!ended && !req.destroyed) req.push(Buffer.from(value))
334
+ }
335
+ } finally {
336
+ reader.releaseLock()
337
+ reader = undefined
338
+ }
339
+ if (!ended && !req.destroyed) {
340
+ ended = true
341
+ req.push(null)
342
+ cleanup()
343
+ }
344
+ } catch (caught) {
345
+ const e = caught as Thrown
346
+ if (ac.signal.aborted) settle(cancelledOpen())
347
+ else {
348
+ end(JSON.stringify({ error: { code: "unavailable", message: `RunSSE: ${e?.message ?? e}` } }))
349
+ settle({ error: { status: 503, message: `RunSSE: ${e?.message ?? e}` }, h2Failed: false })
242
350
  }
243
- } finally {
244
- reader.releaseLock()
245
- reader = undefined
246
- }
247
- if (!ended && !req.destroyed) {
248
- ended = true
249
- req.push(null)
250
- cleanup()
251
351
  }
252
- } catch (caught) {
253
- const e = caught as Thrown
254
- if (!ac.signal.aborted) end(JSON.stringify({ error: { code: "unavailable", message: `RunSSE: ${e?.message ?? e}` } }))
255
- }
256
- })()
257
- return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true, headers: {} })
352
+ })()
353
+ })
354
+ return ready
355
+ }
356
+
357
+ function h1Wait(ms: number | undefined, fallback: number): number {
358
+ return Number.isFinite(Number(ms)) && Number(ms) > 0 ? Number(ms) : fallback
258
359
  }
259
360
 
260
- export async function open({ base, tok, headers: extra, signal, connect = defaultConnect, headerWaitMs = H2.wait, version }: OpenRequest): Promise<Opened | OpenFailed> {
361
+ export function open({ base, tok, headers: extra, signal, connect = defaultConnect, headerWaitMs = H2.wait, firstFrameWaitMs, pending = [], version }: OpenRequest): Promise<Opened | OpenFailed> {
261
362
  const headers = cursorHeaders(tok, version, extra)
262
- if (signal?.aborted) return cancelledOpen()
363
+ const responseMs = h1Wait(firstFrameWaitMs, H1.response)
364
+ const frameWait = h1Wait(firstFrameWaitMs, H1.firstFrame)
365
+ if (signal?.aborted) return Promise.resolve(cancelledOpen())
263
366
  if (connect !== defaultConnect) {
264
- const o = await openH2(base, headers, signal, connect, headerWaitMs)
265
- if (!o.error) trace?.note("transport", { url: base, h1: false })
266
- return o
367
+ return openH2(base, headers, signal, connect, headerWaitMs).then((o) => {
368
+ if (!o.error) pending.length = 0
369
+ if (!o.error) trace?.note("transport", { url: base, h1: false })
370
+ return o
371
+ })
267
372
  }
268
- if (Date.now() >= h1Until) {
269
- const o = await openH2(base, headers, signal, defaultConnect, headerWaitMs)
373
+ if (Date.now() < h1Until) {
374
+ trace?.note("transport", { url: API, h1: true, until: h1Until })
375
+ if (signal?.aborted) return Promise.resolve(cancelledOpen())
376
+ return openH1(headers, signal, responseMs, frameWait, pending)
377
+ }
378
+ return openH2(base, headers, signal, defaultConnect, headerWaitMs).then((o) => {
379
+ if (!o.error) pending.length = 0
270
380
  if (signal?.aborted) {
271
381
  try { o.req?.close?.(http2.constants.NGHTTP2_CANCEL) } catch {}
272
382
  try { o.session?.destroy?.() } catch {}
@@ -278,9 +388,9 @@ export async function open({ base, tok, headers: extra, signal, connect = defaul
278
388
  }
279
389
  if (o.blocked) h1Until = Date.now() + H2.retryAfter
280
390
  trace?.note("transport", { url: API, h1: true, h2: { url: base, error: o.error }, until: o.blocked ? h1Until : undefined })
281
- } else trace?.note("transport", { url: API, h1: true, until: h1Until })
282
- if (signal?.aborted) return cancelledOpen()
283
- return openH1(headers, signal)
391
+ if (signal?.aborted) return cancelledOpen()
392
+ return openH1(headers, signal, responseMs, frameWait, pending)
393
+ })
284
394
  }
285
395
 
286
396
  export function resetH1(): void { h1Until = 0 }