@zyro-sec/util 1.0.0 → 1.0.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/docs/layer-node.md +155 -0
- package/package.json +12 -19
- package/script/build.ts +9 -0
- package/script/pack.ts +5 -0
- package/src/abort.test.ts +16 -0
- package/src/abort.ts +9 -0
- package/src/activity-calendar.test.ts +136 -0
- package/src/activity-calendar.ts +50 -0
- package/src/artifact.test.ts +29 -0
- package/src/artifact.ts +95 -0
- package/src/base64.test.ts +12 -0
- package/src/base64.ts +29 -0
- package/src/binary.test.ts +19 -0
- package/src/binary.ts +30 -0
- package/src/bom.test.ts +21 -0
- package/src/bom.ts +46 -0
- package/src/cross-spawn-spawner.ts +694 -0
- package/src/duration.ts +22 -0
- package/src/effect/app-node-platform.ts +40 -0
- package/src/effect/app-node.ts +14 -0
- package/src/effect/layer-node.ts +360 -0
- package/src/effect-flock.ts +313 -0
- package/src/encode.test.ts +32 -0
- package/src/encode.ts +39 -0
- package/src/execute-output.test.ts +36 -0
- package/src/execute-output.ts +23 -0
- package/src/flock.ts +346 -0
- package/src/fs-util.ts +271 -0
- package/src/glob.ts +38 -0
- package/src/global-roots.ts +19 -0
- package/src/global-roots.workerd.ts +16 -0
- package/src/global.ts +88 -0
- package/src/hash.ts +11 -0
- package/src/heap-snapshot.ts +44 -0
- package/src/no-timeout-fetch.test.ts +33 -0
- package/src/no-timeout-fetch.ts +5 -0
- package/src/npm-config.ts +41 -0
- package/src/npm.ts +557 -0
- package/src/observability/logging.ts +179 -0
- package/src/observability/otlp.ts +109 -0
- package/src/observability/shared.ts +8 -0
- package/src/observability.ts +60 -0
- package/src/open.test.ts +16 -0
- package/src/open.ts +12 -0
- package/src/patch.ts +382 -0
- package/src/path.test.ts +89 -0
- package/src/path.ts +149 -0
- package/src/process-signal.test.ts +38 -0
- package/src/process-signal.ts +23 -0
- package/src/process.ts +270 -0
- package/src/qr.ts +323 -0
- package/src/record.ts +3 -0
- package/src/retry.test.ts +87 -0
- package/src/retry.ts +51 -0
- package/src/runtime/import.bun.ts +10 -0
- package/src/runtime/import.node.ts +61 -0
- package/src/runtime/import.workerd.ts +9 -0
- package/src/runtime-import.ts +1 -0
- package/src/session-mention.test.ts +19 -0
- package/src/session-mention.ts +24 -0
- package/src/session-title-fallback.ts +36 -0
- package/src/session-turn.test.ts +131 -0
- package/src/session-turn.ts +82 -0
- package/src/teardown.ts +19 -0
- package/src/text-boundary.test.ts +39 -0
- package/src/text-boundary.ts +36 -0
- package/src/uuid.test.ts +80 -0
- package/src/uuid.ts +15 -0
- package/test/fixtures/qr.json +625 -0
- package/test/glob.test.ts +11 -0
- package/test/global-roots.test.ts +62 -0
- package/test/global.test.ts +99 -0
- package/test/observability-otlp.test.ts +45 -0
- package/test/qr.test.ts +113 -0
- package/test/session-title-fallback.test.ts +49 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.dist.json +10 -0
- package/tsconfig.json +14 -0
package/src/retry.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export interface RetryOptions {
|
|
2
|
+
attempts?: number
|
|
3
|
+
delay?: number
|
|
4
|
+
factor?: number
|
|
5
|
+
maxDelay?: number
|
|
6
|
+
retryIf?: (error: unknown) => boolean
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const transientMessages = [
|
|
10
|
+
"load failed",
|
|
11
|
+
"network connection was lost",
|
|
12
|
+
"network request failed",
|
|
13
|
+
"failed to fetch",
|
|
14
|
+
"econnreset",
|
|
15
|
+
"econnrefused",
|
|
16
|
+
"epipe",
|
|
17
|
+
"etimedout",
|
|
18
|
+
"socket hang up",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
// Generated clients wrap fetch failures as ClientError("Transport", { cause }) and Bun/Node put the
|
|
22
|
+
// network detail in `code`, so the transient signal may sit anywhere along the cause chain.
|
|
23
|
+
function isTransientError(error: unknown, depth = 0): boolean {
|
|
24
|
+
if (!error) return false
|
|
25
|
+
const code = error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : ""
|
|
26
|
+
// oxlint-disable-next-line no-base-to-string -- Error input is intentionally normalized for message matching.
|
|
27
|
+
const message = `${String(error instanceof Error ? error.message : error)} ${code}`.toLowerCase()
|
|
28
|
+
if (transientMessages.some((item) => message.includes(item))) return true
|
|
29
|
+
if (!(error instanceof Error) || depth >= 5) return false
|
|
30
|
+
return isTransientError(error.cause, depth + 1)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function retry<T>(operation: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
|
|
34
|
+
const attempts = options.attempts ?? 3
|
|
35
|
+
const delay = options.delay ?? 500
|
|
36
|
+
const factor = options.factor ?? 2
|
|
37
|
+
const maxDelay = options.maxDelay ?? 10_000
|
|
38
|
+
const retryIf = options.retryIf ?? isTransientError
|
|
39
|
+
let lastError: unknown
|
|
40
|
+
|
|
41
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
42
|
+
try {
|
|
43
|
+
return await operation()
|
|
44
|
+
} catch (error) {
|
|
45
|
+
lastError = error
|
|
46
|
+
if (attempt === attempts - 1 || !retryIf(error)) throw error
|
|
47
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(delay * Math.pow(factor, attempt), maxDelay)))
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
throw lastError
|
|
51
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { pathToFileURL } from "node:url"
|
|
2
|
+
|
|
3
|
+
export function importModule(specifier: string) {
|
|
4
|
+
return import(specifier) as Promise<unknown>
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function resolveModule(specifier: string, directory: string) {
|
|
8
|
+
const resolved = Bun.resolveSync(specifier, directory)
|
|
9
|
+
return resolved.startsWith("node:") ? resolved : pathToFileURL(resolved).href
|
|
10
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Script, constants } from "node:vm"
|
|
2
|
+
import { registerHooks } from "node:module"
|
|
3
|
+
import { statSync } from "node:fs"
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
import { pathToFileURL } from "node:url"
|
|
6
|
+
|
|
7
|
+
export async function importModule(specifier: string) {
|
|
8
|
+
const imported = (await new Script(`import(${JSON.stringify(specifier)})`, {
|
|
9
|
+
importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
|
|
10
|
+
}).runInThisContext()) as unknown
|
|
11
|
+
if (typeof imported !== "object" || imported === null) return imported
|
|
12
|
+
|
|
13
|
+
const module = imported as Record<string, unknown>
|
|
14
|
+
const exports = module["module.exports"]
|
|
15
|
+
if (exports !== module.default || (typeof exports !== "object" && typeof exports !== "function") || exports === null)
|
|
16
|
+
return imported
|
|
17
|
+
return Object.assign({}, module, exports)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function resolveModule(specifier: string, directory: string) {
|
|
21
|
+
// Node only accepts import.meta.resolve's parent URL behind an experimental
|
|
22
|
+
// flag. Scope this synchronous resolution to the caller's package directory
|
|
23
|
+
// through the supported resolver hook instead.
|
|
24
|
+
const hook = registerHooks({
|
|
25
|
+
resolve(specifier, context, nextResolve) {
|
|
26
|
+
return nextResolve(specifier, { ...context, parentURL: pathToFileURL(path.join(directory, "package.json")).href })
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
try {
|
|
30
|
+
const resolve = (target: string) => {
|
|
31
|
+
const resolved = import.meta.resolve(path.isAbsolute(target) ? pathToFileURL(target).href : target)
|
|
32
|
+
if (resolved.startsWith("file:")) statSync(new URL(resolved))
|
|
33
|
+
return resolved
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
return resolve(specifier)
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (path.extname(specifier) || !missing(error)) throw error
|
|
39
|
+
// Node does not infer extensions for local files or legacy package
|
|
40
|
+
// subpaths. Resolve each candidate natively so package exports still apply.
|
|
41
|
+
for (const extension of [".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs", ".cts", ".cjs"]) {
|
|
42
|
+
try {
|
|
43
|
+
return resolve(specifier + extension)
|
|
44
|
+
} catch (cause) {
|
|
45
|
+
if (!missing(cause)) throw cause
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
throw error
|
|
49
|
+
}
|
|
50
|
+
} finally {
|
|
51
|
+
hook.deregister()
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function missing(error: unknown) {
|
|
56
|
+
return (
|
|
57
|
+
error instanceof Error &&
|
|
58
|
+
"code" in error &&
|
|
59
|
+
["ENOENT", "ENOTDIR", "ERR_MODULE_NOT_FOUND"].includes(String(error.code))
|
|
60
|
+
)
|
|
61
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const unavailable = () => new Error("Dynamic module loading is unavailable on workerd")
|
|
2
|
+
|
|
3
|
+
export function importModule(_specifier: string): Promise<unknown> {
|
|
4
|
+
return Promise.reject(unavailable())
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function resolveModule(_specifier: string, _directory: string): string {
|
|
8
|
+
throw unavailable()
|
|
9
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { importModule, resolveModule } from "#runtime-import"
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { parseSessionMention, serializeSessionMention, sessionMentions } from "./session-mention.js"
|
|
3
|
+
|
|
4
|
+
const id = "ses_0123456789abcdefghijklmnop"
|
|
5
|
+
|
|
6
|
+
test("session tokens round-trip independently of the title", () => {
|
|
7
|
+
expect(serializeSessionMention({ id })).toBe(`@session:${id}`)
|
|
8
|
+
expect(parseSessionMention(`@session:${id}`)).toEqual({ id })
|
|
9
|
+
expect(parseSessionMention(id)).toEqual({ id })
|
|
10
|
+
expect(sessionMentions(`See @session:${id}, then ${id}.`).map((match) => match.id)).toEqual([id, id])
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
test.each(["ses_123", `@session:${id}extra`, `x${id}`, `${id}/path`, `https://host/${id}`, `@other:${id}`, `${id}_x`])(
|
|
14
|
+
"does not parse malformed or embedded IDs: %s",
|
|
15
|
+
(text) => {
|
|
16
|
+
expect(parseSessionMention(text)).toBeUndefined()
|
|
17
|
+
expect(sessionMentions(text)).toEqual([])
|
|
18
|
+
},
|
|
19
|
+
)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type SessionMention = { id: `ses_${string}` }
|
|
2
|
+
|
|
3
|
+
// Match complete generated IDs only, including while an assistant is streaming one.
|
|
4
|
+
const pattern = /(?<![\w/:@-])(?:@session:)?(ses_[A-Za-z0-9]{26})(?![\w/-])/g
|
|
5
|
+
|
|
6
|
+
export function sessionMentions(text: string) {
|
|
7
|
+
return Array.from(text.matchAll(pattern), (match) => ({
|
|
8
|
+
// SAFETY: the capture above requires the session prefix and a complete generated suffix.
|
|
9
|
+
id: match[1] as SessionMention["id"],
|
|
10
|
+
text: match[0],
|
|
11
|
+
start: match.index,
|
|
12
|
+
end: match.index + match[0].length,
|
|
13
|
+
}))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseSessionMention(text: string): SessionMention | undefined {
|
|
17
|
+
const match = sessionMentions(text)[0]
|
|
18
|
+
|
|
19
|
+
return match?.text === text ? { id: match.id } : undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function serializeSessionMention(mention: SessionMention) {
|
|
23
|
+
return `@session:${mention.id}`
|
|
24
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export * as SessionTitleFallback from "./session-title-fallback.js"
|
|
2
|
+
|
|
3
|
+
const pattern = /^(New session|Child session) - \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
|
|
4
|
+
|
|
5
|
+
interface Info {
|
|
6
|
+
readonly title?: string
|
|
7
|
+
readonly parentID?: string
|
|
8
|
+
readonly time: {
|
|
9
|
+
readonly created: number
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Supplies the timestamped title required by compatibility surfaces. */
|
|
14
|
+
export function withTimestampedFallback(info: Info) {
|
|
15
|
+
return info.title ?? fallback(info)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Supplies a compact human label and collapses historical timestamped fallbacks. */
|
|
19
|
+
export function displayLabel(info: Pick<Info, "title" | "parentID">) {
|
|
20
|
+
if (!info.title) return info.parentID ? "Child session" : "New session"
|
|
21
|
+
return info.title.match(pattern)?.[1] ?? info.title
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Recognizes missing and historical root or child fallback titles. */
|
|
25
|
+
export function isFallbackTitle(title?: string) {
|
|
26
|
+
return title === undefined || pattern.test(title)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Recognizes a missing title or the exact root fallback for this session. */
|
|
30
|
+
export function isExactRootFallback(info: Pick<Info, "title" | "time">) {
|
|
31
|
+
return info.title === undefined || info.title === fallback({ time: info.time })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function fallback(info: Pick<Info, "parentID" | "time">) {
|
|
35
|
+
return `${info.parentID ? "Child" : "New"} session - ${new Date(info.time.created).toISOString()}`
|
|
36
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { SessionTurn } from "./session-turn.js"
|
|
3
|
+
|
|
4
|
+
type Message = {
|
|
5
|
+
id: string
|
|
6
|
+
type: string
|
|
7
|
+
time: { created: number; firstToken?: number; streamed?: number; completed?: number }
|
|
8
|
+
tokens?: { output: number; reasoning: number }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
test("measures turn duration from the user prompt across assistant steps", () => {
|
|
12
|
+
const final = step("assistant-2", { created: 27_000, completed: 30_000 })
|
|
13
|
+
const messages = [input("user-1", 1_000), step("assistant-1", { created: 8_000, completed: 11_000 }), final]
|
|
14
|
+
|
|
15
|
+
expect(SessionTurn.duration(messages, final)).toBe(29_000)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
test("measures decode throughput from the first streamed token", () => {
|
|
19
|
+
const first = step("assistant-1", { created: 6_000, firstToken: 8_000, streamed: 10_000, completed: 20_000 }, 20, 5)
|
|
20
|
+
const final = step("assistant-2", { created: 24_000, firstToken: 25_000, streamed: 28_000, completed: 31_000 }, 30, 10)
|
|
21
|
+
const messages = [input("user-1", 1_000), first, final]
|
|
22
|
+
|
|
23
|
+
// 65 tokens over the 5s the provider spent streaming them, not the 10s that include waiting for the first.
|
|
24
|
+
expect(SessionTurn.tokensPerSecond(messages, final)).toBe(13)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
test("falls back to the request window for steps recorded without a first token", () => {
|
|
28
|
+
const first = step("assistant-1", { created: 6_000, streamed: 10_000, completed: 20_000 }, 20, 5)
|
|
29
|
+
const final = step("assistant-2", { created: 24_000, firstToken: 25_000, streamed: 28_000, completed: 31_000 }, 30, 10)
|
|
30
|
+
const messages = [input("user-1", 1_000), first, final]
|
|
31
|
+
|
|
32
|
+
// The old step counts its 4s request window, the new one its 3s decode window.
|
|
33
|
+
expect(SessionTurn.tokensPerSecond(messages, final)).toBe(65 / 7)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test("measures request throughput including reasoning without tool time", () => {
|
|
37
|
+
const first = step("assistant-1", { created: 6_000, streamed: 10_000, completed: 20_000 }, 20, 5)
|
|
38
|
+
const final = step("assistant-2", { created: 24_000, streamed: 30_000, completed: 31_000 }, 30, 10)
|
|
39
|
+
const messages = [input("user-1", 1_000), first, final]
|
|
40
|
+
|
|
41
|
+
expect(SessionTurn.tokensPerSecond(messages, final)).toBe(6.5)
|
|
42
|
+
first.time.streamed = undefined
|
|
43
|
+
expect(SessionTurn.tokensPerSecond(messages, final)).toBeUndefined()
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
test("omits turn throughput when a stream boundary is unavailable", () => {
|
|
47
|
+
const final = step("assistant-1", { created: 1 }, 20)
|
|
48
|
+
expect(SessionTurn.tokensPerSecond([final], final)).toBeUndefined()
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
test.each([false, true])(
|
|
52
|
+
"measures historical footers without later inputs or incomplete steps (indexed: %s)",
|
|
53
|
+
(indexed) => {
|
|
54
|
+
const timed = (id: string, created: number, streamed: number, completed: number, output: number) =>
|
|
55
|
+
step(id, { created, streamed, completed }, output, 2)
|
|
56
|
+
const messages: Message[] = [
|
|
57
|
+
timed("before-input", 0, 1_000, 2_000, 5),
|
|
58
|
+
input("input", 3_000),
|
|
59
|
+
timed("first-step", 4_000, 5_000, 6_000, 10),
|
|
60
|
+
{ type: "system", id: "system", time: { created: 6_500 } },
|
|
61
|
+
timed("second-step", 7_000, 8_000, 9_000, 20),
|
|
62
|
+
{ type: "synthetic", id: "synthetic", time: { created: 10_000 } },
|
|
63
|
+
timed("after-synthetic", 11_000, 13_000, 14_000, 12),
|
|
64
|
+
input("later-input", 15_000),
|
|
65
|
+
step("incomplete", { created: 1 }),
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
expect(
|
|
69
|
+
messages.flatMap((message, index) => {
|
|
70
|
+
if (message.type !== "assistant") return []
|
|
71
|
+
const options = { index: indexed ? index : undefined }
|
|
72
|
+
return [
|
|
73
|
+
[SessionTurn.duration(messages, message, options), SessionTurn.tokensPerSecond(messages, message, options)],
|
|
74
|
+
]
|
|
75
|
+
}),
|
|
76
|
+
).toEqual([
|
|
77
|
+
[2_000, 7],
|
|
78
|
+
[3_000, 12],
|
|
79
|
+
[6_000, 17],
|
|
80
|
+
[4_000, 7],
|
|
81
|
+
[0, undefined],
|
|
82
|
+
])
|
|
83
|
+
},
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
test("preserves missing-anchor fallbacks without including the absent assistant's tokens", () => {
|
|
87
|
+
const absent = step("absent", { created: 8_000, streamed: 9_000, completed: 10_000 }, 900)
|
|
88
|
+
const stored = step("stored", { created: 6_000, streamed: 8_000, completed: 9_000 }, 20)
|
|
89
|
+
const prompt = input("input", 5_000)
|
|
90
|
+
|
|
91
|
+
expect(SessionTurn.duration([prompt, stored], absent)).toBe(5_000)
|
|
92
|
+
expect(SessionTurn.tokensPerSecond([prompt, stored], absent)).toBe(10)
|
|
93
|
+
expect(SessionTurn.duration([stored], absent)).toBe(2_000)
|
|
94
|
+
expect(SessionTurn.tokensPerSecond([stored], absent)).toBe(10)
|
|
95
|
+
expect(SessionTurn.duration([], absent)).toBe(2_000)
|
|
96
|
+
expect(SessionTurn.tokensPerSecond([], absent)).toBeUndefined()
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
test("measures a marker-era turn from its first prompt across steers", () => {
|
|
100
|
+
const timed = (id: string, created: number, streamed: number, completed: number, output: number) =>
|
|
101
|
+
step(id, { created, streamed, completed }, output)
|
|
102
|
+
const final = timed("second-step", 8_000, 9_000, 10_000, 20)
|
|
103
|
+
const messages: Message[] = [
|
|
104
|
+
input("old-input", 0),
|
|
105
|
+
timed("old-step", 1_000, 2_000, 3_000, 5),
|
|
106
|
+
{ type: "idle", id: "idle-1", time: { created: 3_500 } },
|
|
107
|
+
input("input", 4_000),
|
|
108
|
+
timed("first-step", 5_000, 6_000, 7_000, 10),
|
|
109
|
+
input("steer", 7_500),
|
|
110
|
+
final,
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
expect(SessionTurn.legacy(messages)).toBe(false)
|
|
114
|
+
expect(SessionTurn.duration(messages, final)).toBe(6_000)
|
|
115
|
+
expect(SessionTurn.tokensPerSecond(messages, final)).toBe(15)
|
|
116
|
+
expect(SessionTurn.duration(messages, final, { index: 6, legacy: true })).toBe(2_500)
|
|
117
|
+
expect(SessionTurn.tokensPerSecond(messages, final, { index: 6, legacy: true })).toBe(20)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
function input(id: string, created: number): Message {
|
|
121
|
+
return { type: "user", id, time: { created } }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function step(id: string, time: Message["time"], output?: number, reasoning = 0): Message {
|
|
125
|
+
return {
|
|
126
|
+
type: "assistant",
|
|
127
|
+
id,
|
|
128
|
+
time,
|
|
129
|
+
tokens: output === undefined ? undefined : { output, reasoning },
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export * as SessionTurn from "./session-turn.js"
|
|
2
|
+
|
|
3
|
+
/** The fields of a session message that turn measurements read. Client session messages satisfy it as they are. */
|
|
4
|
+
export interface Message {
|
|
5
|
+
readonly id: string
|
|
6
|
+
readonly type: string
|
|
7
|
+
readonly time: {
|
|
8
|
+
readonly created: number
|
|
9
|
+
/** When the provider streamed the first output token; steps recorded before this existed leave it unset. */
|
|
10
|
+
readonly firstToken?: number
|
|
11
|
+
readonly streamed?: number
|
|
12
|
+
readonly completed?: number
|
|
13
|
+
}
|
|
14
|
+
readonly tokens?: { readonly output: number; readonly reasoning: number }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface Options {
|
|
18
|
+
/** The position of `message` in `messages`. Reactive callers should pass it so the lookup does not read every message. */
|
|
19
|
+
readonly index?: number
|
|
20
|
+
/**
|
|
21
|
+
* Whether the session has no idle markers, so a turn ends at the next prompt. Reactive callers should pass it from a
|
|
22
|
+
* shared memo: the default scans every message, which subscribes the caller to the whole history.
|
|
23
|
+
*/
|
|
24
|
+
readonly legacy?: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Milliseconds from the prompt that started the turn until `message` completed, or 0 while it runs. */
|
|
28
|
+
export function duration(messages: readonly Message[], message: Message, options: Options = {}) {
|
|
29
|
+
if (message.time.completed === undefined) return 0
|
|
30
|
+
const index = options.index ?? messages.findIndex((item) => item.id === message.id)
|
|
31
|
+
const input =
|
|
32
|
+
messages[inputIndex(messages, index === -1 ? messages.length : index, options.legacy ?? legacy(messages))]
|
|
33
|
+
return Math.max(0, message.time.completed - (input?.time.created ?? message.time.created))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Output and reasoning tokens per second while the provider streamed them, or undefined until every step has streamed.
|
|
38
|
+
*
|
|
39
|
+
* Each step counts from its first streamed token to the end of the response body, so the wait for that first token
|
|
40
|
+
* (time to first token) is not divided into the output rate. Steps recorded before `time.firstToken` existed count
|
|
41
|
+
* from request dispatch instead, which is what this measured for them before the field existed.
|
|
42
|
+
*/
|
|
43
|
+
export function tokensPerSecond(messages: readonly Message[], message: Message, options: Options = {}) {
|
|
44
|
+
const steps = turnSteps(messages, message, options)
|
|
45
|
+
const durations = steps.flatMap((step) =>
|
|
46
|
+
step.time.streamed === undefined
|
|
47
|
+
? []
|
|
48
|
+
: [Math.max(0, step.time.streamed - (step.time.firstToken ?? step.time.created))],
|
|
49
|
+
)
|
|
50
|
+
if (steps.length === 0 || durations.length !== steps.length) return
|
|
51
|
+
const output = steps.reduce((total, step) => total + (step.tokens?.output ?? 0) + (step.tokens?.reasoning ?? 0), 0)
|
|
52
|
+
const total = durations.reduce((sum, value) => sum + value, 0)
|
|
53
|
+
if (output <= 0 || total <= 0) return
|
|
54
|
+
// Aggregate before dividing so each step is weighted by its provider-active duration.
|
|
55
|
+
return output / (total / 1_000)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function legacy(messages: readonly Message[]) {
|
|
59
|
+
return !messages.some((message) => message.type === "idle")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function turnSteps(messages: readonly Message[], message: Message, options: Options) {
|
|
63
|
+
const index = options.index ?? messages.findIndex((item) => item.id === message.id)
|
|
64
|
+
const end = index === -1 ? messages.length : index + 1
|
|
65
|
+
const start = inputIndex(messages, end, options.legacy ?? legacy(messages))
|
|
66
|
+
return messages.slice(start + 1, end).filter((item) => item.type === "assistant")
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function inputIndex(messages: readonly Message[], end: number, legacy: boolean) {
|
|
70
|
+
// Reading a sliced prefix subscribes every caller to unrelated historical messages, so walk
|
|
71
|
+
// back only as far as the turn boundary: the nearest input in legacy sessions, otherwise the
|
|
72
|
+
// first input after the previous idle marker.
|
|
73
|
+
let input = -1
|
|
74
|
+
for (let index = end - 1; index >= 0; index--) {
|
|
75
|
+
const message = messages[index]
|
|
76
|
+
if (message.type === "idle") return input
|
|
77
|
+
if (message.type !== "user" && message.type !== "synthetic") continue
|
|
78
|
+
if (legacy) return index
|
|
79
|
+
input = index
|
|
80
|
+
}
|
|
81
|
+
return input
|
|
82
|
+
}
|
package/src/teardown.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * as Teardown from "./teardown.js"
|
|
2
|
+
|
|
3
|
+
// Work that shutdown may be waiting on: layers releasing their resources and child processes that have not
|
|
4
|
+
// closed. Read when a shutdown deadline expires, to name what kept the process alive.
|
|
5
|
+
const entries = new Set<{ readonly label: string; readonly since: number }>()
|
|
6
|
+
|
|
7
|
+
/** Record pending work; call the returned function once it settles. */
|
|
8
|
+
export function track(label: string) {
|
|
9
|
+
const entry = { label, since: Date.now() }
|
|
10
|
+
entries.add(entry)
|
|
11
|
+
return () => {
|
|
12
|
+
entries.delete(entry)
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Pending work, oldest first, with how long each has been pending. */
|
|
17
|
+
export function pending(now = Date.now()) {
|
|
18
|
+
return Array.from(entries, (entry) => ({ label: entry.label, ms: now - entry.since }))
|
|
19
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { TextBoundary } from "./text-boundary.js"
|
|
3
|
+
|
|
4
|
+
const encoder = new TextEncoder()
|
|
5
|
+
const samples = ["", "ascii", "ab😀cd", "😀é€\uFFFD😀"]
|
|
6
|
+
|
|
7
|
+
describe("TextBoundary", () => {
|
|
8
|
+
test.each(samples)("every head and tail of %j keeps whole characters within the limit", (text) => {
|
|
9
|
+
for (let limit = 0; limit <= text.length + 1; limit++) {
|
|
10
|
+
const head = TextBoundary.head(text, limit)
|
|
11
|
+
const tail = TextBoundary.tail(text, limit)
|
|
12
|
+
expect(text.startsWith(head)).toBe(true)
|
|
13
|
+
expect(text.endsWith(tail)).toBe(true)
|
|
14
|
+
for (const part of [head, tail]) {
|
|
15
|
+
expect(part.isWellFormed()).toBe(true)
|
|
16
|
+
expect(part.length).toBeLessThanOrEqual(limit)
|
|
17
|
+
expect(part.length).toBeGreaterThanOrEqual(Math.min(limit, text.length) - 1)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
test.each(samples)("every UTF-8 tail of %j keeps whole characters within the limit", (text) => {
|
|
23
|
+
const bytes = encoder.encode(text)
|
|
24
|
+
for (let limit = 0; limit <= bytes.length + 1; limit++) {
|
|
25
|
+
const tail = TextBoundary.utf8Tail(bytes, limit)
|
|
26
|
+
expect(text.endsWith(tail)).toBe(true)
|
|
27
|
+
expect(encoder.encode(tail).length).toBeLessThanOrEqual(limit)
|
|
28
|
+
expect(encoder.encode(tail).length).toBeGreaterThanOrEqual(Math.min(limit, bytes.length) - 3)
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
test("keeps malformed input that is not at the cut", () => {
|
|
33
|
+
expect(TextBoundary.head("a\ud83d", 2)).toBe("a\ud83d")
|
|
34
|
+
expect(TextBoundary.head("a\ud83db", 2)).toBe("a")
|
|
35
|
+
expect(TextBoundary.tail("\ude00a", 2)).toBe("\ude00a")
|
|
36
|
+
expect(TextBoundary.tail("b\ude00a", 2)).toBe("a")
|
|
37
|
+
expect(TextBoundary.utf8Tail(Uint8Array.of(0x80, 0x41), 2)).toBe("\uFFFDA")
|
|
38
|
+
})
|
|
39
|
+
})
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export * as TextBoundary from "./text-boundary.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Clip text to a budget without ending or starting on half a character. `head` and `tail` count UTF-16 code units,
|
|
5
|
+
* like `.length`; `utf8Tail` counts bytes of UTF-8 output that has not been decoded yet. The result can be shorter
|
|
6
|
+
* than the budget by the part of the character at the cut, and `head("😀", 1)` is empty. Boundaries are code points,
|
|
7
|
+
* not graphemes, and malformed input is kept as it is everywhere except at the cut.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** The first `limit` code units of `text`, without a high surrogate whose pair the limit cut off. */
|
|
11
|
+
export function head(text: string, limit: number) {
|
|
12
|
+
if (text.length <= limit) return text
|
|
13
|
+
const code = text.charCodeAt(limit - 1)
|
|
14
|
+
return text.slice(0, code >= 0xd800 && code <= 0xdbff ? limit - 1 : limit)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The last `limit` code units of `text`, without a low surrogate whose pair the limit cut off. */
|
|
18
|
+
export function tail(text: string, limit: number) {
|
|
19
|
+
if (text.length <= limit) return text
|
|
20
|
+
const start = text.length - limit
|
|
21
|
+
const code = text.charCodeAt(start)
|
|
22
|
+
return text.slice(code >= 0xdc00 && code <= 0xdfff ? start + 1 : start)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The last `limit` bytes of `bytes`, decoded, after skipping up to 3 continuation bytes of a cut character. */
|
|
26
|
+
export function utf8Tail(bytes: Uint8Array, limit: number) {
|
|
27
|
+
if (bytes.length <= limit) return decoder.decode(bytes)
|
|
28
|
+
const start = bytes.length - limit
|
|
29
|
+
const end = Math.min(bytes.length, start + 3)
|
|
30
|
+
let index = start
|
|
31
|
+
while (index < end && (bytes[index] & 0xc0) === 0x80) index++
|
|
32
|
+
return decoder.decode(bytes.subarray(index))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Like Buffer#toString, keep a leading byte order mark.
|
|
36
|
+
const decoder = new TextDecoder("utf-8", { ignoreBOM: true })
|
package/src/uuid.test.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from "bun:test"
|
|
2
|
+
import { uuid } from "./uuid.js"
|
|
3
|
+
|
|
4
|
+
const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto")
|
|
5
|
+
|
|
6
|
+
const secureDescriptor = Object.getOwnPropertyDescriptor(globalThis, "isSecureContext")
|
|
7
|
+
|
|
8
|
+
const randomDescriptor = Object.getOwnPropertyDescriptor(Math, "random")
|
|
9
|
+
|
|
10
|
+
const setCrypto = (value: Partial<Crypto>) => {
|
|
11
|
+
Object.defineProperty(globalThis, "crypto", {
|
|
12
|
+
configurable: true,
|
|
13
|
+
value: value as Crypto,
|
|
14
|
+
})
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const setSecure = (value: boolean) => {
|
|
18
|
+
Object.defineProperty(globalThis, "isSecureContext", {
|
|
19
|
+
configurable: true,
|
|
20
|
+
value,
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const setRandom = (value: () => number) => {
|
|
25
|
+
Object.defineProperty(Math, "random", {
|
|
26
|
+
configurable: true,
|
|
27
|
+
value,
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
afterEach(() => {
|
|
32
|
+
if (cryptoDescriptor) {
|
|
33
|
+
Object.defineProperty(globalThis, "crypto", cryptoDescriptor)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (secureDescriptor) {
|
|
37
|
+
Object.defineProperty(globalThis, "isSecureContext", secureDescriptor)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (!secureDescriptor) {
|
|
41
|
+
delete (globalThis as { isSecureContext?: boolean }).isSecureContext
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (randomDescriptor) {
|
|
45
|
+
Object.defineProperty(Math, "random", randomDescriptor)
|
|
46
|
+
}
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
describe("uuid", () => {
|
|
50
|
+
test("uses randomUUID in secure contexts", () => {
|
|
51
|
+
setCrypto({ randomUUID: () => "00000000-0000-0000-0000-000000000000" })
|
|
52
|
+
setSecure(true)
|
|
53
|
+
expect(uuid()).toBe("00000000-0000-0000-0000-000000000000")
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const fallbacks: { name: string; secure: boolean; crypto: Partial<Crypto> }[] = [
|
|
57
|
+
{
|
|
58
|
+
name: "in insecure contexts",
|
|
59
|
+
secure: false,
|
|
60
|
+
crypto: { randomUUID: () => "00000000-0000-0000-0000-000000000000" },
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
name: "when randomUUID throws",
|
|
64
|
+
secure: true,
|
|
65
|
+
crypto: {
|
|
66
|
+
randomUUID: () => {
|
|
67
|
+
throw new DOMException("Failed", "OperationError")
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
{ name: "when randomUUID is unavailable", secure: true, crypto: {} },
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
test.each(fallbacks)("falls back $name", (row) => {
|
|
75
|
+
setCrypto(row.crypto)
|
|
76
|
+
setSecure(row.secure)
|
|
77
|
+
setRandom(() => 0.5)
|
|
78
|
+
expect(uuid()).toBe("8")
|
|
79
|
+
})
|
|
80
|
+
})
|
package/src/uuid.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const fallback = () => Math.random().toString(16).slice(2)
|
|
2
|
+
|
|
3
|
+
export function uuid() {
|
|
4
|
+
const c = globalThis.crypto
|
|
5
|
+
|
|
6
|
+
if (!c || typeof c.randomUUID !== "function") return fallback()
|
|
7
|
+
|
|
8
|
+
if (typeof globalThis.isSecureContext === "boolean" && !globalThis.isSecureContext) return fallback()
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
return c.randomUUID()
|
|
12
|
+
} catch {
|
|
13
|
+
return fallback()
|
|
14
|
+
}
|
|
15
|
+
}
|