@zyro-sec/util 1.0.2 → 1.0.4

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.
Files changed (78) hide show
  1. package/docs/layer-node.md +155 -155
  2. package/package.json +1 -1
  3. package/script/build.ts +9 -9
  4. package/script/pack.ts +5 -5
  5. package/src/abort.ts +9 -9
  6. package/src/activity-calendar.ts +50 -50
  7. package/src/artifact.ts +95 -95
  8. package/src/base64.ts +29 -29
  9. package/src/binary.ts +30 -30
  10. package/src/bom.ts +46 -46
  11. package/src/cross-spawn-spawner.ts +694 -694
  12. package/src/duration.ts +22 -22
  13. package/src/effect/app-node-platform.ts +40 -40
  14. package/src/effect/app-node.ts +14 -14
  15. package/src/effect/layer-node.ts +360 -360
  16. package/src/effect-flock.ts +313 -313
  17. package/src/encode.ts +39 -39
  18. package/src/execute-output.ts +23 -23
  19. package/src/flock.ts +346 -346
  20. package/src/fs-util.ts +271 -271
  21. package/src/glob.ts +38 -38
  22. package/src/global-roots.ts +19 -19
  23. package/src/global-roots.workerd.ts +16 -16
  24. package/src/global.ts +88 -88
  25. package/src/hash.ts +11 -11
  26. package/src/heap-snapshot.ts +44 -44
  27. package/src/no-timeout-fetch.ts +5 -5
  28. package/src/npm-config.ts +41 -41
  29. package/src/npm.ts +557 -557
  30. package/src/observability/logging.ts +179 -179
  31. package/src/observability/otlp.ts +109 -109
  32. package/src/observability/shared.ts +8 -8
  33. package/src/observability.ts +60 -60
  34. package/src/open.ts +12 -12
  35. package/src/patch.ts +382 -382
  36. package/src/path.ts +149 -149
  37. package/src/process-signal.ts +23 -23
  38. package/src/process.ts +270 -270
  39. package/src/qr.ts +323 -323
  40. package/src/record.ts +3 -3
  41. package/src/retry.ts +51 -51
  42. package/src/runtime/import.bun.ts +10 -10
  43. package/src/runtime/import.node.ts +61 -61
  44. package/src/runtime/import.workerd.ts +9 -9
  45. package/src/runtime-import.ts +1 -1
  46. package/src/session-mention.ts +24 -24
  47. package/src/session-title-fallback.ts +36 -36
  48. package/src/session-turn.ts +82 -82
  49. package/src/teardown.ts +19 -19
  50. package/src/text-boundary.ts +36 -36
  51. package/src/uuid.ts +15 -15
  52. package/test/fixtures/qr.json +625 -625
  53. package/tsconfig.build.json +12 -12
  54. package/tsconfig.dist.json +10 -10
  55. package/tsconfig.json +14 -14
  56. package/src/abort.test.ts +0 -16
  57. package/src/activity-calendar.test.ts +0 -136
  58. package/src/artifact.test.ts +0 -29
  59. package/src/base64.test.ts +0 -12
  60. package/src/binary.test.ts +0 -19
  61. package/src/bom.test.ts +0 -21
  62. package/src/encode.test.ts +0 -32
  63. package/src/execute-output.test.ts +0 -36
  64. package/src/no-timeout-fetch.test.ts +0 -33
  65. package/src/open.test.ts +0 -16
  66. package/src/path.test.ts +0 -89
  67. package/src/process-signal.test.ts +0 -38
  68. package/src/retry.test.ts +0 -87
  69. package/src/session-mention.test.ts +0 -19
  70. package/src/session-turn.test.ts +0 -131
  71. package/src/text-boundary.test.ts +0 -39
  72. package/src/uuid.test.ts +0 -80
  73. package/test/glob.test.ts +0 -11
  74. package/test/global-roots.test.ts +0 -62
  75. package/test/global.test.ts +0 -99
  76. package/test/observability-otlp.test.ts +0 -45
  77. package/test/qr.test.ts +0 -113
  78. package/test/session-title-fallback.test.ts +0 -49
package/src/retry.ts CHANGED
@@ -1,51 +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
- }
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
+ }
@@ -1,10 +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
- }
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
+ }
@@ -1,61 +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
- }
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
+ }
@@ -1,9 +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
- }
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
+ }
@@ -1 +1 @@
1
- export { importModule, resolveModule } from "#runtime-import"
1
+ export { importModule, resolveModule } from "#runtime-import"
@@ -1,24 +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
- }
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
+ }
@@ -1,36 +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
- }
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
+ }
@@ -1,82 +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
- }
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 CHANGED
@@ -1,19 +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
- }
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
+ }