@caph42/pi-cursor-provider 0.0.0-stage → 0.3.0
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/LICENSE +23 -0
- package/README.md +133 -2
- package/package.json +43 -4
- package/src/auth.ts +272 -0
- package/src/client.ts +90 -0
- package/src/codec.ts +235 -0
- package/src/index.ts +93 -0
- package/src/ledger.ts +292 -0
- package/src/models.ts +336 -0
- package/src/native-session.ts +958 -0
- package/src/pi-stream.ts +330 -0
- package/src/run.ts +1268 -0
- package/src/usage.ts +257 -0
package/src/codec.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hand-written protobuf and Connect framing for Cursor AgentService/Run.
|
|
3
|
+
*
|
|
4
|
+
* Ported from magpie's Cursor provider (MIT):
|
|
5
|
+
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
6
|
+
* which itself was ported from magpie's Go client (internal/provider/cursor*.go).
|
|
7
|
+
*/
|
|
8
|
+
// @ts-nocheck
|
|
9
|
+
import { STATUS_CODES } from "node:http"
|
|
10
|
+
import { gunzipSync } from "node:zlib"
|
|
11
|
+
|
|
12
|
+
export const EMPTY = Buffer.alloc(0)
|
|
13
|
+
|
|
14
|
+
const statusText = (s) =>
|
|
15
|
+
({ 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" })[s] ?? STATUS_CODES[s] ?? ""
|
|
16
|
+
|
|
17
|
+
export class PB {
|
|
18
|
+
parts = []
|
|
19
|
+
push(b) {
|
|
20
|
+
this.parts.push(b)
|
|
21
|
+
return this
|
|
22
|
+
}
|
|
23
|
+
uv(v) {
|
|
24
|
+
const out = []
|
|
25
|
+
while (v >= 0x80) {
|
|
26
|
+
out.push((v % 128) | 0x80)
|
|
27
|
+
v = Math.floor(v / 128)
|
|
28
|
+
}
|
|
29
|
+
out.push(v)
|
|
30
|
+
return this.push(Uint8Array.from(out))
|
|
31
|
+
}
|
|
32
|
+
tag(num, wire) {
|
|
33
|
+
return this.uv(num * 8 + wire)
|
|
34
|
+
}
|
|
35
|
+
varint(num, v) {
|
|
36
|
+
return this.tag(num, 0).uv(v)
|
|
37
|
+
}
|
|
38
|
+
bytes(num, v) {
|
|
39
|
+
const b = v instanceof PB ? v.done() : v ?? EMPTY
|
|
40
|
+
return this.tag(num, 2).uv(b.length).push(b)
|
|
41
|
+
}
|
|
42
|
+
str(num, s) {
|
|
43
|
+
return this.bytes(num, Buffer.from(s, "utf8"))
|
|
44
|
+
}
|
|
45
|
+
double(num, v) {
|
|
46
|
+
const b = Buffer.alloc(8)
|
|
47
|
+
b.writeDoubleLE(v)
|
|
48
|
+
return this.tag(num, 1).push(b)
|
|
49
|
+
}
|
|
50
|
+
done() {
|
|
51
|
+
return Buffer.concat(this.parts)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export const pb = () => new PB()
|
|
55
|
+
|
|
56
|
+
// fields reads a message's fields; a malformed tail is dropped.
|
|
57
|
+
export function fields(b) {
|
|
58
|
+
b = Buffer.isBuffer(b) ? b : Buffer.from(b ?? EMPTY)
|
|
59
|
+
const out = []
|
|
60
|
+
let i = 0
|
|
61
|
+
const uv = () => {
|
|
62
|
+
let v = 0
|
|
63
|
+
let m = 1
|
|
64
|
+
while (i < b.length) {
|
|
65
|
+
const c = b[i++]
|
|
66
|
+
v += (c & 0x7f) * m
|
|
67
|
+
if (c < 0x80) return v
|
|
68
|
+
m *= 128
|
|
69
|
+
}
|
|
70
|
+
return -1
|
|
71
|
+
}
|
|
72
|
+
while (i < b.length) {
|
|
73
|
+
const key = uv()
|
|
74
|
+
if (key < 0) break
|
|
75
|
+
const f = { num: Math.floor(key / 8), wire: key % 8, n: 0, data: EMPTY }
|
|
76
|
+
switch (f.wire) {
|
|
77
|
+
case 0: {
|
|
78
|
+
const v = uv()
|
|
79
|
+
if (v < 0) return out
|
|
80
|
+
f.n = v
|
|
81
|
+
break
|
|
82
|
+
}
|
|
83
|
+
case 1:
|
|
84
|
+
if (i + 8 > b.length) return out
|
|
85
|
+
f.data = b.subarray(i, i + 8)
|
|
86
|
+
f.n = Number(b.readBigUInt64LE(i))
|
|
87
|
+
i += 8
|
|
88
|
+
break
|
|
89
|
+
case 2: {
|
|
90
|
+
const l = uv()
|
|
91
|
+
if (l < 0 || i + l > b.length) return out
|
|
92
|
+
f.data = b.subarray(i, i + l)
|
|
93
|
+
i += l
|
|
94
|
+
break
|
|
95
|
+
}
|
|
96
|
+
case 5:
|
|
97
|
+
if (i + 4 > b.length) return out
|
|
98
|
+
f.n = b.readUInt32LE(i)
|
|
99
|
+
i += 4
|
|
100
|
+
break
|
|
101
|
+
default:
|
|
102
|
+
return out
|
|
103
|
+
}
|
|
104
|
+
out.push(f)
|
|
105
|
+
}
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const field = (fs, num) => fs.find((f) => f.num === num)
|
|
110
|
+
export const pbStr = (fs, num) => field(fs, num)?.data.toString("utf8") ?? ""
|
|
111
|
+
export const pbNum = (fs, num) => field(fs, num)?.n ?? 0
|
|
112
|
+
|
|
113
|
+
// pbValue is a google.protobuf.Value.
|
|
114
|
+
export function pbValue(v) {
|
|
115
|
+
if (v === null || v === undefined) return pb().varint(1, 0)
|
|
116
|
+
if (typeof v === "number") return pb().double(2, v)
|
|
117
|
+
if (typeof v === "string") return pb().str(3, v)
|
|
118
|
+
if (typeof v === "boolean") return pb().varint(4, v ? 1 : 0)
|
|
119
|
+
if (Array.isArray(v)) {
|
|
120
|
+
const l = pb()
|
|
121
|
+
for (const e of v) l.bytes(1, pbValue(e))
|
|
122
|
+
return pb().bytes(6, l)
|
|
123
|
+
}
|
|
124
|
+
if (typeof v === "object") {
|
|
125
|
+
const st = pb()
|
|
126
|
+
for (const k of Object.keys(v).sort()) st.bytes(1, pb().str(1, k).bytes(2, pbValue(v[k])))
|
|
127
|
+
return pb().bytes(5, st)
|
|
128
|
+
}
|
|
129
|
+
return pb().varint(1, 0)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// pbAny reads a google.protobuf.Value.
|
|
133
|
+
export function pbAny(b) {
|
|
134
|
+
for (const f of fields(b)) {
|
|
135
|
+
switch (f.num) {
|
|
136
|
+
case 1:
|
|
137
|
+
return null
|
|
138
|
+
case 2:
|
|
139
|
+
return f.data.length === 8 ? f.data.readDoubleLE(0) : 0
|
|
140
|
+
case 3:
|
|
141
|
+
return f.data.toString("utf8")
|
|
142
|
+
case 4:
|
|
143
|
+
return f.n !== 0
|
|
144
|
+
case 5: {
|
|
145
|
+
const m = {}
|
|
146
|
+
for (const e of fields(f.data)) {
|
|
147
|
+
if (e.num !== 1) continue
|
|
148
|
+
const kv = fields(e.data)
|
|
149
|
+
const v = field(kv, 2)
|
|
150
|
+
m[pbStr(kv, 1)] = v ? pbAny(v.data) : null
|
|
151
|
+
}
|
|
152
|
+
return m
|
|
153
|
+
}
|
|
154
|
+
case 6:
|
|
155
|
+
return fields(f.data).filter((e) => e.num === 1).map((e) => pbAny(e.data))
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return null
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// frame wraps a message as one frame of a Connect stream.
|
|
162
|
+
export function frame(msg) {
|
|
163
|
+
const head = Buffer.alloc(5)
|
|
164
|
+
head.writeUInt32BE(msg.length, 1)
|
|
165
|
+
return Buffer.concat([head, msg])
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// frames reads a Connect stream's frames: a message, or the stream's end
|
|
169
|
+
// with its JSON.
|
|
170
|
+
export async function* frames(body) {
|
|
171
|
+
let buf = EMPTY
|
|
172
|
+
for await (const chunk of body) {
|
|
173
|
+
buf = buf.length ? Buffer.concat([buf, chunk]) : Buffer.from(chunk)
|
|
174
|
+
while (buf.length >= 5) {
|
|
175
|
+
const n = buf.readUInt32BE(1)
|
|
176
|
+
if (n > 64 << 20) throw new Error("a malformed stream")
|
|
177
|
+
if (buf.length < 5 + n) break
|
|
178
|
+
const flags = buf[0]
|
|
179
|
+
let data = buf.subarray(5, 5 + n)
|
|
180
|
+
buf = buf.subarray(5 + n)
|
|
181
|
+
if (flags & 1) data = gunzipSync(data)
|
|
182
|
+
yield { end: (flags & 2) !== 0, data }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (buf.length) throw new Error("unexpected EOF")
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ---- failures -----------------------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
export const regional = (msg) => msg.toLowerCase().includes("region")
|
|
191
|
+
|
|
192
|
+
// failure is the status and message for Cursor's Connect error, whose
|
|
193
|
+
// details say it best: {"code", "message", "details": [{"debug": {"error",
|
|
194
|
+
// "details": {"title", "detail"}}}]}, or the same under "error" at a
|
|
195
|
+
// stream's end.
|
|
196
|
+
export function failure(status, text) {
|
|
197
|
+
let e
|
|
198
|
+
try {
|
|
199
|
+
e = JSON.parse(typeof text === "string" ? text : Buffer.from(text).toString("utf8"))
|
|
200
|
+
} catch {
|
|
201
|
+
return statusOf(status, "", String(text ?? "").trim())
|
|
202
|
+
}
|
|
203
|
+
const f = e?.error && typeof e.error === "object" ? e.error : e ?? {}
|
|
204
|
+
let msg = f.message ?? ""
|
|
205
|
+
for (const d of f.details ?? []) {
|
|
206
|
+
const t = `${d?.debug?.details?.title ?? ""}: ${d?.debug?.details?.detail ?? ""}`.trim()
|
|
207
|
+
if (t !== ":") msg = t.replace(/^[:\s]+|[:\s]+$/g, "")
|
|
208
|
+
}
|
|
209
|
+
if (!msg || msg === "Error") msg = f.code ?? ""
|
|
210
|
+
if (!f.code && status >= 200 && status < 300) return { status, message: msg } // a stream that ended well
|
|
211
|
+
return statusOf(status, f.code ?? "", msg)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// statusOf is the status and words for Cursor's error of this code and
|
|
215
|
+
// message. A region the team isn't served in says so, not to sign in.
|
|
216
|
+
export function statusOf(status, code, msg) {
|
|
217
|
+
msg ||= statusText(status)
|
|
218
|
+
const low = msg.toLowerCase()
|
|
219
|
+
// magpie names the provider before the message itself
|
|
220
|
+
const out = (status, message) => ({ status, message })
|
|
221
|
+
if (regional(msg)) return out(403, msg + " — Cursor serves your team only in some regions and turned this request away; signing in again won't change that")
|
|
222
|
+
if (code === "permission_denied") return out(403, msg)
|
|
223
|
+
if (code === "unauthenticated" || status === 401 || low.includes("expired"))
|
|
224
|
+
return out(401, msg + " — sign in to Cursor again with /login cursor")
|
|
225
|
+
if (code === "resource_exhausted" || low.includes("quota") || low.includes("rate limit") || low.includes("usage limit"))
|
|
226
|
+
return out(429, "usage limit reached: " + msg)
|
|
227
|
+
if (low.includes("too long") || low.includes("context length") || low.includes("too many tokens"))
|
|
228
|
+
return out(400, "input is too long for the model's context: " + msg)
|
|
229
|
+
if (code === "invalid_argument") return out(400, msg)
|
|
230
|
+
if (code === "unavailable") return out(503, msg)
|
|
231
|
+
if (code) return out(502, msg)
|
|
232
|
+
return out(status, msg)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---- the conversation -------------------------------------------------------------
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi extension: provider id `cursor`.
|
|
3
|
+
*
|
|
4
|
+
* Login follows pi-cursor (MIT): https://github.com/Rahularya01/pi-cursor
|
|
5
|
+
* A stateless turn opens an HTTP/2 Run and tears it down after tools.
|
|
6
|
+
* A native Run in this process stays open and takes call_cursor_ results.
|
|
7
|
+
* This does not register a parked bridge, a checkpoint, or a run journal.
|
|
8
|
+
*/
|
|
9
|
+
import type { RefreshModelsContext } from "@earendil-works/pi-ai"
|
|
10
|
+
import type { ExtensionAPI, ProviderModelConfig } from "@earendil-works/pi-coding-agent"
|
|
11
|
+
import { login, refresh, resolveAccessToken } from "./auth.ts"
|
|
12
|
+
import { AGENT, clientVersion } from "./client.ts"
|
|
13
|
+
import { piModelConfigs, usable } from "./models.ts"
|
|
14
|
+
import { streamCursor } from "./pi-stream.ts"
|
|
15
|
+
import { fetchUsage, formatUsage } from "./usage.ts"
|
|
16
|
+
|
|
17
|
+
export { fetchUsage, formatUsage, onDemandOf } from "./usage.ts"
|
|
18
|
+
|
|
19
|
+
let models: ProviderModelConfig[] = []
|
|
20
|
+
|
|
21
|
+
async function refreshModels(ctx: RefreshModelsContext): Promise<ProviderModelConfig[]> {
|
|
22
|
+
if (ctx.signal.aborted || !ctx.allowNetwork) return models
|
|
23
|
+
const fromCred =
|
|
24
|
+
ctx.credential?.type === "oauth" ? ctx.credential.access : ctx.credential?.type === "api_key" ? ctx.credential.key : undefined
|
|
25
|
+
const auth = await resolveAccessToken({ apiKey: fromCred })
|
|
26
|
+
if (!auth) return models
|
|
27
|
+
try {
|
|
28
|
+
models = piModelConfigs(await usable(auth.token, ctx.force === true)) as ProviderModelConfig[]
|
|
29
|
+
return models
|
|
30
|
+
} catch {
|
|
31
|
+
return models
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default function (pi: ExtensionAPI) {
|
|
36
|
+
pi.registerProvider("cursor", {
|
|
37
|
+
name: "Cursor",
|
|
38
|
+
baseUrl: AGENT,
|
|
39
|
+
apiKey: "$CURSOR_ACCESS_TOKEN",
|
|
40
|
+
api: "cursor-run",
|
|
41
|
+
models,
|
|
42
|
+
oauth: {
|
|
43
|
+
name: "Cursor",
|
|
44
|
+
isSubscription: true,
|
|
45
|
+
login,
|
|
46
|
+
refreshToken: (credentials, signal) => refresh(credentials, signal),
|
|
47
|
+
getApiKey: (credentials) => credentials.access,
|
|
48
|
+
},
|
|
49
|
+
refreshModels,
|
|
50
|
+
streamSimple: streamCursor,
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
pi.registerCommand("cursor.doctor", {
|
|
54
|
+
description: "Show which Cursor credential would be used, without printing the token",
|
|
55
|
+
handler: async (args, ctx) => {
|
|
56
|
+
const extra = args.trim() ? " This command does not take arguments." : ""
|
|
57
|
+
const auth = await resolveAccessToken()
|
|
58
|
+
const version = await clientVersion()
|
|
59
|
+
if (!auth) {
|
|
60
|
+
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN.${extra}`, "warning")
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
ctx.ui.notify(`Cursor auth source: ${auth.source}. Client ${version}. Token not shown.${extra}`, "info")
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
pi.registerCommand("cursor.usage", {
|
|
68
|
+
description: "Show Cursor plan usage for this billing period",
|
|
69
|
+
handler: async (args, ctx) => {
|
|
70
|
+
const extra = args.trim() ? " This command does not take arguments." : ""
|
|
71
|
+
const auth = await resolveAccessToken()
|
|
72
|
+
if (!auth) {
|
|
73
|
+
const version = await clientVersion()
|
|
74
|
+
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN.${extra}`, "warning")
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
let ids = models.map((m) => m.id)
|
|
78
|
+
if (!ids.length) {
|
|
79
|
+
try {
|
|
80
|
+
ids = (await usable(auth.token)).map((m: { id: string }) => m.id)
|
|
81
|
+
} catch {
|
|
82
|
+
ids = []
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const report = await fetchUsage(auth.token, ids)
|
|
87
|
+
ctx.ui.notify(formatUsage(report) + extra, report.error ? "warning" : "info")
|
|
88
|
+
} catch (e) {
|
|
89
|
+
ctx.ui.notify(`Cursor usage could not be read. ${e instanceof Error ? e.message : String(e)}${extra}`, "warning")
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
}
|
package/src/ledger.ts
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deferred dashboard usage ledger for AgentService/Run steps.
|
|
3
|
+
*
|
|
4
|
+
* Ported from magpie's Cursor provider (MIT):
|
|
5
|
+
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
6
|
+
*
|
|
7
|
+
* A tool step has no TurnEndedUpdate. Usage is read from the dashboard's
|
|
8
|
+
* GetFilteredUsageEvents by conversation_id. Far from Cursor the event is
|
|
9
|
+
* late: the step says 0 and the conversation owes it; later steps collect
|
|
10
|
+
* it as magpie_deferred so prompt_tokens stay the step's own context size.
|
|
11
|
+
*/
|
|
12
|
+
// @ts-nocheck
|
|
13
|
+
import { createHash } from "node:crypto"
|
|
14
|
+
import { API, headersFor } from "./client.ts"
|
|
15
|
+
|
|
16
|
+
// STEP_WAIT is how long a step's event is looked for: first after that long,
|
|
17
|
+
// then every so often until the end (each ask given `ask` to answer).
|
|
18
|
+
// Far from Cursor none shows in that time (yetone/magpie#1053), and waiting
|
|
19
|
+
// longer would hold every tool step longer. So a tool step's Run is owed by
|
|
20
|
+
// its conversation: next steps collect it in the background from `owedAt`.
|
|
21
|
+
// After `skipAfter` misses in a row, steps stop waiting (but every
|
|
22
|
+
// `retryEvery`th). A debt not collected in `owedFor` is let go.
|
|
23
|
+
export const STEP_WAIT = {
|
|
24
|
+
first: 1500,
|
|
25
|
+
every: 500,
|
|
26
|
+
until: 6000,
|
|
27
|
+
ask: 5000,
|
|
28
|
+
skipAfter: 3,
|
|
29
|
+
retryEvery: 10,
|
|
30
|
+
owedAt: 5000,
|
|
31
|
+
owedFor: 600_000,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// claimed are the usage events already counted, by account, conversation
|
|
35
|
+
// and time, so that two steps of one conversation never count the same one.
|
|
36
|
+
const claimed = new Map()
|
|
37
|
+
|
|
38
|
+
// owed are what each account's conversation still owes, by credential
|
|
39
|
+
// fingerprint and conversation_id: n Runs whose events are to be counted,
|
|
40
|
+
// the earliest started at since, looked for from ready on; and carry, a
|
|
41
|
+
// count collected that no step gave out.
|
|
42
|
+
export const owed = new Map()
|
|
43
|
+
|
|
44
|
+
// flights are each account's conversation collections still going, which
|
|
45
|
+
// a step that ends the turn waits for.
|
|
46
|
+
export const flights = new Map()
|
|
47
|
+
|
|
48
|
+
// unreadable are the accounts (by token) whose usage events Cursor won't
|
|
49
|
+
// give (a 4xx), for owedFor: their steps are guessed, as before, and owe
|
|
50
|
+
// nothing. misses are how many steps in a row of an account's left
|
|
51
|
+
// something owed.
|
|
52
|
+
export const unreadable = new Map()
|
|
53
|
+
export const misses = new Map()
|
|
54
|
+
|
|
55
|
+
const tokKey = (tok) => createHash("sha256").update(tok).digest("hex")
|
|
56
|
+
export const usageKey = (tok, conv) => tokKey(tok) + "\0" + conv
|
|
57
|
+
|
|
58
|
+
export function canRead(tok) {
|
|
59
|
+
const at = unreadable.get(tokKey(tok))
|
|
60
|
+
if (at === undefined) return true
|
|
61
|
+
if (Date.now() - at < STEP_WAIT.owedFor) return false
|
|
62
|
+
unreadable.delete(tokKey(tok))
|
|
63
|
+
return true
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const ZERO = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 })
|
|
67
|
+
function addUsage(a, b) {
|
|
68
|
+
if (!b) return a
|
|
69
|
+
if (!a) return { ...b }
|
|
70
|
+
for (const k of Object.keys(a)) a[k] += b[k] ?? 0
|
|
71
|
+
return a
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// owe adds to the account/conversation's debt. A native Run bounds older
|
|
75
|
+
// event timestamps before its start: its authoritative final must never be
|
|
76
|
+
// collected as an earlier Run. Keep that bound when a later stateless Run
|
|
77
|
+
// adds unbounded debt. Ordinary stateless debt retains its original shape.
|
|
78
|
+
const DEBT_GROUP_LIMIT = 64
|
|
79
|
+
export function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null, before } = {}) {
|
|
80
|
+
for (const [k, d] of owed) {
|
|
81
|
+
if (d.groups) {
|
|
82
|
+
d.groups = d.groups.filter((g) => Date.now() - g.since <= STEP_WAIT.owedFor)
|
|
83
|
+
d.n = d.groups.reduce((sum, g) => sum + g.n, 0)
|
|
84
|
+
if (Date.now() - d.since > STEP_WAIT.owedFor) d.carry = null
|
|
85
|
+
if (!d.n && !d.carry) owed.delete(k)
|
|
86
|
+
else if (d.groups.length) d.since = Math.min(...d.groups.map((g) => g.since))
|
|
87
|
+
} else if (Date.now() - d.since > STEP_WAIT.owedFor) owed.delete(k)
|
|
88
|
+
}
|
|
89
|
+
if (n <= 0 && !carry) return
|
|
90
|
+
const d = owed.get(key)
|
|
91
|
+
if (!d) return void owed.set(key, { since, n, ready, carry: carry && { ...carry }, ...(before !== undefined ? { before } : {}) })
|
|
92
|
+
if (n > 0 && (d.groups || d.before !== undefined || before !== undefined)) {
|
|
93
|
+
const groups = d.groups ?? (d.n > 0 ? [{ since: d.since, n: d.n, ready: d.ready, before: d.before }] : [])
|
|
94
|
+
const same = groups.find((g) => g.before === before)
|
|
95
|
+
if (same) {
|
|
96
|
+
same.since = Math.min(same.since, since)
|
|
97
|
+
same.n += n
|
|
98
|
+
same.ready = Math.min(same.ready, ready)
|
|
99
|
+
} else groups.push({ since, n, ready, before })
|
|
100
|
+
// As with expired dashboard debt, overflow stays unknown, never estimated
|
|
101
|
+
// or merged across bounds into an authoritative native Run's event.
|
|
102
|
+
groups.sort((a, b) => a.since - b.since)
|
|
103
|
+
d.groups = groups.slice(-DEBT_GROUP_LIMIT)
|
|
104
|
+
delete d.before
|
|
105
|
+
d.n = d.groups.reduce((sum, g) => sum + g.n, 0)
|
|
106
|
+
d.since = Math.min(...d.groups.map((g) => g.since))
|
|
107
|
+
} else {
|
|
108
|
+
d.since = Math.min(d.since, since)
|
|
109
|
+
d.n += n
|
|
110
|
+
}
|
|
111
|
+
d.ready = Math.min(d.ready, ready)
|
|
112
|
+
d.carry = addUsage(d.carry, carry)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// usageEvents are the dashboard's events of conversation conv from since
|
|
116
|
+
// on, the `want` oldest not counted yet, summed.
|
|
117
|
+
export async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, signal, before = () => Infinity, groups, abortFetch = false } = {}) {
|
|
118
|
+
const key = usageKey(tok, conv)
|
|
119
|
+
const end = Date.now() + STEP_WAIT.until
|
|
120
|
+
const wait = (ms) => new Promise((r) => {
|
|
121
|
+
const t = setTimeout(r, ms)
|
|
122
|
+
signal?.addEventListener("abort", () => (clearTimeout(t), r()), { once: true })
|
|
123
|
+
})
|
|
124
|
+
for (const [k, at] of claimed) if (Date.now() - at > 2 * STEP_WAIT.owedFor) claimed.delete(k)
|
|
125
|
+
const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
|
|
126
|
+
let usage = null
|
|
127
|
+
let got = 0
|
|
128
|
+
const events = []
|
|
129
|
+
const counts = groups?.map(() => 0)
|
|
130
|
+
if (poll) await wait(first)
|
|
131
|
+
while (!signal?.aborted) {
|
|
132
|
+
try {
|
|
133
|
+
const res = await fetch(API + "/aiserver.v1.DashboardService/GetFilteredUsageEvents", {
|
|
134
|
+
method: "POST",
|
|
135
|
+
headers: await headersFor(tok),
|
|
136
|
+
body: JSON.stringify({ teamId: 0, startDate: String(since - 60_000), endDate: String(Date.now() + 60_000), page: 1, pageSize: 50 }),
|
|
137
|
+
signal: abortFetch && signal ? AbortSignal.any([signal, AbortSignal.timeout(STEP_WAIT.ask)]) : AbortSignal.timeout(STEP_WAIT.ask),
|
|
138
|
+
})
|
|
139
|
+
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
140
|
+
unreadable.set(tokKey(tok), Date.now())
|
|
141
|
+
return { usage, events, got, counts, refused: true }
|
|
142
|
+
}
|
|
143
|
+
const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : []
|
|
144
|
+
const found = evs
|
|
145
|
+
.filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp))
|
|
146
|
+
.sort((a, b) => num(a.timestamp) - num(b.timestamp))
|
|
147
|
+
for (const ev of found) {
|
|
148
|
+
if (got >= want) break
|
|
149
|
+
const at = num(ev.timestamp)
|
|
150
|
+
if (at >= before()) continue
|
|
151
|
+
const group = groups?.findIndex((g, i) => counts[i] < g.n && at >= g.since - 1000 && at < (g.before ?? Infinity))
|
|
152
|
+
if (groups && group === -1) continue
|
|
153
|
+
if (groups) counts[group]++
|
|
154
|
+
claimed.set(key + "\0" + ev.timestamp, Date.now())
|
|
155
|
+
const t = ev.tokenUsage
|
|
156
|
+
const u = { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens), reasoning: 0 }
|
|
157
|
+
usage = addUsage(usage ?? ZERO(), u)
|
|
158
|
+
events.push({ at: num(ev.timestamp), usage: u })
|
|
159
|
+
got++
|
|
160
|
+
}
|
|
161
|
+
if (got >= want) break
|
|
162
|
+
} catch {}
|
|
163
|
+
if (!poll || Date.now() + STEP_WAIT.every > end) break
|
|
164
|
+
await wait(STEP_WAIT.every)
|
|
165
|
+
}
|
|
166
|
+
return { usage, events, got, counts, refused: false }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The usage of one Run as the dashboard counts it; null when none shows in time. */
|
|
170
|
+
export async function stepUsage(tok, conv, since, signal) {
|
|
171
|
+
return (await usageEvents(tok, conv, since, 1, { poll: true, signal })).usage
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function collect(tok, conv, { poll = false, first, signal, over = () => false, abortFetch = false } = {}) {
|
|
175
|
+
const key = usageKey(tok, conv)
|
|
176
|
+
const d = owed.get(key)
|
|
177
|
+
if (!d) return Promise.resolve({ usage: null, carry: null, events: [], short: false })
|
|
178
|
+
owed.delete(key)
|
|
179
|
+
const p = (async () => {
|
|
180
|
+
const groups = (d.groups ?? [d]).filter((g) => (g.before === undefined && !d.groups) || Date.now() - g.since <= STEP_WAIT.owedFor)
|
|
181
|
+
const want = groups.reduce((sum, g) => sum + g.n, 0)
|
|
182
|
+
let r = { usage: null, events: [], got: 0 }
|
|
183
|
+
if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, {
|
|
184
|
+
poll, first, signal, abortFetch, before: () => d.before ?? Infinity, ...(d.groups ? { groups } : {}),
|
|
185
|
+
}).catch(() => r)
|
|
186
|
+
let short = false
|
|
187
|
+
for (const [i, g] of groups.entries()) {
|
|
188
|
+
const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got)
|
|
189
|
+
if (remaining > 0 && canRead(tok)) {
|
|
190
|
+
short = true
|
|
191
|
+
owe(key, { since: g.since, n: remaining, ready: g.ready, before: g.before })
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const carry = d.carry && { ...d.carry }
|
|
195
|
+
const usage = addUsage(d.carry, r.usage)
|
|
196
|
+
if (!over()) return { usage, carry, events: r.events ?? [], short }
|
|
197
|
+
owe(key, { carry: usage })
|
|
198
|
+
return { usage: null, carry: null, events: [], short }
|
|
199
|
+
})()
|
|
200
|
+
p.debt = d
|
|
201
|
+
const set = flights.get(key) ?? new Set()
|
|
202
|
+
flights.set(key, set.add(p))
|
|
203
|
+
p.finally(() => {
|
|
204
|
+
set.delete(p)
|
|
205
|
+
if (!set.size && flights.get(key) === set) flights.delete(key)
|
|
206
|
+
})
|
|
207
|
+
return p
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* How a Run of conversation conv, started at since, has its usage counted.
|
|
212
|
+
* kept when conversation_id names the session so a later Run can collect debt.
|
|
213
|
+
*/
|
|
214
|
+
export function ledger(tok, conv, since, signal, kept, { before } = {}) {
|
|
215
|
+
const key = tokKey(tok)
|
|
216
|
+
const debtKey = usageKey(tok, conv)
|
|
217
|
+
if (kept && before !== undefined) {
|
|
218
|
+
const debts = [owed.get(debtKey), ...[...(flights.get(debtKey) ?? [])].map((p) => p.debt)]
|
|
219
|
+
for (const d of debts) for (const g of d?.groups ?? (d ? [d] : [])) g.before = Math.min(g.before ?? Infinity, before)
|
|
220
|
+
}
|
|
221
|
+
let mine = null
|
|
222
|
+
let theirs = null
|
|
223
|
+
let over = false
|
|
224
|
+
const gather = (opts) =>
|
|
225
|
+
collect(tok, conv, { ...opts, over: () => over, abortFetch: before !== undefined }).then((r) => {
|
|
226
|
+
theirs = addUsage(theirs, r.carry)
|
|
227
|
+
for (const e of r.events ?? []) {
|
|
228
|
+
if (e.at >= since - 1000) mine = addUsage(mine, e.usage)
|
|
229
|
+
else theirs = addUsage(theirs, e.usage)
|
|
230
|
+
}
|
|
231
|
+
return r
|
|
232
|
+
})
|
|
233
|
+
let collecting = null
|
|
234
|
+
const debt = kept ? owed.get(debtKey) : undefined
|
|
235
|
+
const timer = debt ? setTimeout(() => (collecting = gather()), Math.max(0, debt.ready - Date.now())) : null
|
|
236
|
+
timer?.unref?.()
|
|
237
|
+
const takeMine = () => {
|
|
238
|
+
const u = mine
|
|
239
|
+
mine = null
|
|
240
|
+
return u
|
|
241
|
+
}
|
|
242
|
+
const take = () => {
|
|
243
|
+
const u = addUsage(theirs, mine)
|
|
244
|
+
mine = theirs = null
|
|
245
|
+
return u
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
async own() {
|
|
249
|
+
if (!canRead(tok)) return null
|
|
250
|
+
const m = misses.get(key) ?? 0
|
|
251
|
+
const waits = m < STEP_WAIT.skipAfter || m % STEP_WAIT.retryEvery === 0
|
|
252
|
+
if (!kept) {
|
|
253
|
+
const r = waits ? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch(() => ({})) : {}
|
|
254
|
+
if (r.usage) misses.delete(key)
|
|
255
|
+
else if (!r.refused) misses.set(key, m + 1)
|
|
256
|
+
return r.usage ?? null
|
|
257
|
+
}
|
|
258
|
+
owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
|
|
259
|
+
if (waits) {
|
|
260
|
+
const r = await gather({ poll: true, signal })
|
|
261
|
+
if (!canRead(tok)) return null
|
|
262
|
+
if (r.short) misses.set(key, m + 1)
|
|
263
|
+
else misses.delete(key)
|
|
264
|
+
} else misses.set(key, m + 1)
|
|
265
|
+
return takeMine() ?? false
|
|
266
|
+
},
|
|
267
|
+
async owed(final) {
|
|
268
|
+
if (!kept) return null
|
|
269
|
+
if (final) {
|
|
270
|
+
await collecting
|
|
271
|
+
await Promise.all([...(flights.get(debtKey) ?? [])])
|
|
272
|
+
if (owed.has(debtKey)) await gather({ poll: owed.get(debtKey).n > 0, first: 0, signal })
|
|
273
|
+
}
|
|
274
|
+
return take()
|
|
275
|
+
},
|
|
276
|
+
done() {
|
|
277
|
+
over = true
|
|
278
|
+
clearTimeout(timer)
|
|
279
|
+
const u = take()
|
|
280
|
+
if (u) owe(debtKey, { carry: u })
|
|
281
|
+
},
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Clear process-local ledger state (tests). */
|
|
286
|
+
export function clearLedger() {
|
|
287
|
+
claimed.clear()
|
|
288
|
+
owed.clear()
|
|
289
|
+
flights.clear()
|
|
290
|
+
unreadable.clear()
|
|
291
|
+
misses.clear()
|
|
292
|
+
}
|