@caph42/pi-cursor-provider 0.8.0 → 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 +6 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent-run.ts +13 -7
- package/src/codec.ts +1 -0
- package/src/ledger.ts +49 -10
- package/src/protocol.ts +2 -0
- package/src/run.ts +4 -1
- package/src/transport.ts +151 -41
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
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
|
+
|
|
5
11
|
## 0.8.0
|
|
6
12
|
|
|
7
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.
|
package/README.md
CHANGED
|
@@ -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
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
|
-
|
|
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
|
|
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
|
}
|
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
|
-
|
|
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)
|
|
280
|
-
else
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
|
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 = {
|
|
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
|
|
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
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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
|
-
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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()
|
|
269
|
-
|
|
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
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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 }
|