@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.
Files changed (78) hide show
  1. package/docs/layer-node.md +155 -0
  2. package/package.json +12 -19
  3. package/script/build.ts +9 -0
  4. package/script/pack.ts +5 -0
  5. package/src/abort.test.ts +16 -0
  6. package/src/abort.ts +9 -0
  7. package/src/activity-calendar.test.ts +136 -0
  8. package/src/activity-calendar.ts +50 -0
  9. package/src/artifact.test.ts +29 -0
  10. package/src/artifact.ts +95 -0
  11. package/src/base64.test.ts +12 -0
  12. package/src/base64.ts +29 -0
  13. package/src/binary.test.ts +19 -0
  14. package/src/binary.ts +30 -0
  15. package/src/bom.test.ts +21 -0
  16. package/src/bom.ts +46 -0
  17. package/src/cross-spawn-spawner.ts +694 -0
  18. package/src/duration.ts +22 -0
  19. package/src/effect/app-node-platform.ts +40 -0
  20. package/src/effect/app-node.ts +14 -0
  21. package/src/effect/layer-node.ts +360 -0
  22. package/src/effect-flock.ts +313 -0
  23. package/src/encode.test.ts +32 -0
  24. package/src/encode.ts +39 -0
  25. package/src/execute-output.test.ts +36 -0
  26. package/src/execute-output.ts +23 -0
  27. package/src/flock.ts +346 -0
  28. package/src/fs-util.ts +271 -0
  29. package/src/glob.ts +38 -0
  30. package/src/global-roots.ts +19 -0
  31. package/src/global-roots.workerd.ts +16 -0
  32. package/src/global.ts +88 -0
  33. package/src/hash.ts +11 -0
  34. package/src/heap-snapshot.ts +44 -0
  35. package/src/no-timeout-fetch.test.ts +33 -0
  36. package/src/no-timeout-fetch.ts +5 -0
  37. package/src/npm-config.ts +41 -0
  38. package/src/npm.ts +557 -0
  39. package/src/observability/logging.ts +179 -0
  40. package/src/observability/otlp.ts +109 -0
  41. package/src/observability/shared.ts +8 -0
  42. package/src/observability.ts +60 -0
  43. package/src/open.test.ts +16 -0
  44. package/src/open.ts +12 -0
  45. package/src/patch.ts +382 -0
  46. package/src/path.test.ts +89 -0
  47. package/src/path.ts +149 -0
  48. package/src/process-signal.test.ts +38 -0
  49. package/src/process-signal.ts +23 -0
  50. package/src/process.ts +270 -0
  51. package/src/qr.ts +323 -0
  52. package/src/record.ts +3 -0
  53. package/src/retry.test.ts +87 -0
  54. package/src/retry.ts +51 -0
  55. package/src/runtime/import.bun.ts +10 -0
  56. package/src/runtime/import.node.ts +61 -0
  57. package/src/runtime/import.workerd.ts +9 -0
  58. package/src/runtime-import.ts +1 -0
  59. package/src/session-mention.test.ts +19 -0
  60. package/src/session-mention.ts +24 -0
  61. package/src/session-title-fallback.ts +36 -0
  62. package/src/session-turn.test.ts +131 -0
  63. package/src/session-turn.ts +82 -0
  64. package/src/teardown.ts +19 -0
  65. package/src/text-boundary.test.ts +39 -0
  66. package/src/text-boundary.ts +36 -0
  67. package/src/uuid.test.ts +80 -0
  68. package/src/uuid.ts +15 -0
  69. package/test/fixtures/qr.json +625 -0
  70. package/test/glob.test.ts +11 -0
  71. package/test/global-roots.test.ts +62 -0
  72. package/test/global.test.ts +99 -0
  73. package/test/observability-otlp.test.ts +45 -0
  74. package/test/qr.test.ts +113 -0
  75. package/test/session-title-fallback.test.ts +49 -0
  76. package/tsconfig.build.json +12 -0
  77. package/tsconfig.dist.json +10 -0
  78. package/tsconfig.json +14 -0
@@ -0,0 +1,179 @@
1
+ import { Effect, FileSystem, Formatter, Logger, Option, Schedule, Stream, type LogLevel } from "effect"
2
+ import path from "path"
3
+ import { Global } from "../global.js"
4
+ import { runID } from "./shared.js"
5
+
6
+ // One log file is shared by every opencode process on the machine and only ever appended to, so it
7
+ // is bounded by compacting in place instead of rotating: once it passes LOG_MAX_BYTES the head is
8
+ // dropped so roughly LOG_KEEP_BYTES remain, rounded forward to the next line boundary.
9
+ export const LOG_MAX_BYTES = 50 * 1024 * 1024
10
+ export const LOG_KEEP_BYTES = 25 * 1024 * 1024
11
+ export const LOG_TRIM_INTERVAL = "1 hour"
12
+ // A trim of a 1 GB log takes well under a second, so a lock older than this belongs to a dead process.
13
+ export const LOG_TRIM_LOCK_STALE_MS = 5 * 60 * 1000
14
+ const LOG_TRIM_CHUNK = 64 * 1024
15
+
16
+ function formatter(id: string = runID()) {
17
+ return Logger.map(Logger.formatStructured, (output) => {
18
+ const messages = Array.isArray(output.message) ? output.message : [output.message]
19
+ return [
20
+ ["timestamp", output.timestamp],
21
+ ["level", output.level],
22
+ ["run", id],
23
+ ...messages.flatMap((value) => (plain(value) ? flatten(value) : [["message", value] as const])),
24
+ ...(output.cause === undefined ? [] : [["cause", output.cause] as const]),
25
+ ...flatten(output.spans),
26
+ ...flatten(output.annotations),
27
+ ]
28
+ .map(([key, value]) => `${key}=${format(value)}`)
29
+ .join(" ")
30
+ })
31
+ }
32
+
33
+ function flatten(
34
+ input: Record<string, unknown>,
35
+ prefix = "",
36
+ seen = new WeakSet<object>(),
37
+ ): Array<readonly [string, unknown]> {
38
+ if (seen.has(input)) return [[prefix, "[Circular]"]]
39
+ seen.add(input)
40
+ const entries = Object.entries(input)
41
+ if (entries.length === 0 && prefix) return [[prefix, input]]
42
+ return entries.flatMap(([key, value]) => {
43
+ const path = prefix ? `${prefix}.${key}` : key
44
+ return plain(value) ? flatten(value, path, seen) : [[path, value] as const]
45
+ })
46
+ }
47
+
48
+ function plain(input: unknown): input is Record<string, unknown> {
49
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return false
50
+ const prototype = Object.getPrototypeOf(input)
51
+ return prototype === Object.prototype || prototype === null
52
+ }
53
+
54
+ function format(input: unknown) {
55
+ const value = typeof input === "string" ? input : Formatter.format(input)
56
+ return /^[^\s="\\]+$/.test(value) ? value : JSON.stringify(value)
57
+ }
58
+
59
+ export function file(local = true, channel = "local") {
60
+ if (!local) return path.join(Global.Path.log, "zyrosec.log")
61
+ return path.join(Global.Path.log, `zyrosec-${channel.replace(/[^a-zA-Z0-9._-]/g, "-")}.log`)
62
+ }
63
+
64
+ export function fileLogger(target = file(), id: string = runID()) {
65
+ // Do not set batchWindow to 0; it causes high idle CPU usage.
66
+ return Effect.gen(function* () {
67
+ const fs = yield* FileSystem.FileSystem
68
+ yield* fs.makeDirectory(path.dirname(target), { recursive: true })
69
+ const logger = yield* Logger.toFile(formatter(id), target, { flag: "a" })
70
+ yield* trim(target).pipe(
71
+ Effect.ignore,
72
+ Effect.repeat(Schedule.spaced(LOG_TRIM_INTERVAL)),
73
+ Effect.forkScoped({ startImmediately: true }),
74
+ )
75
+ return logger
76
+ })
77
+ }
78
+
79
+ // Compacts in place rather than writing a temp file and renaming over the log. Other processes hold
80
+ // the same file open with O_APPEND, so they keep appending to the compacted file, whereas a rename
81
+ // would strand them on the unlinked inode and lose their output.
82
+ //
83
+ // Appenders are not coordinated with the final truncate, so a batch flushed by another process
84
+ // between the last read and the truncate is lost. That window is a few milliseconds once per trim,
85
+ // which is an accepted trade for not wrapping every log write in a cross-process lock.
86
+ export const trim = Effect.fn("Logging.trim")(function* (
87
+ target: string,
88
+ options: { max?: number; keep?: number } = {},
89
+ ) {
90
+ const max = options.max ?? LOG_MAX_BYTES
91
+ const keep = options.keep ?? LOG_KEEP_BYTES
92
+ const fs = yield* FileSystem.FileSystem
93
+ // Every opencode process on the machine runs this against the same file. Two trimmers racing
94
+ // would have one compute its cut from a size the other already shrank, so only one may proceed
95
+ // and the rest skip until the next interval. mkdir is the atomic primitive on every platform.
96
+ // acquireRelease keeps the mkdir uninterruptible, so a scope closing mid-call cannot leave a lock
97
+ // on disk with no finalizer registered to remove it.
98
+ const lock = `${target}.trim`
99
+ const acquired = yield* Effect.acquireRelease(
100
+ fs.makeDirectory(lock).pipe(
101
+ Effect.as(true),
102
+ Effect.catchIf(
103
+ (error) => error.reason._tag === "AlreadyExists",
104
+ () => breakStaleLock(fs, lock),
105
+ ),
106
+ ),
107
+ (acquired) => (acquired ? fs.remove(lock, { recursive: true }).pipe(Effect.ignore) : Effect.void),
108
+ )
109
+ if (!acquired) return
110
+ const size = Number((yield* fs.stat(target)).size)
111
+ if (size <= max) return
112
+ const handle = yield* fs.open(target, { flag: "r+" })
113
+ const start = yield* lineStart(handle, size - keep)
114
+ yield* handle.seek(0n, "start")
115
+ // Reads run to the current EOF so lines appended since the stat survive; the write cursor always
116
+ // trails the read cursor so the forward copy never overwrites unread bytes.
117
+ const written = yield* fs.stream(target, { offset: start, chunkSize: LOG_TRIM_CHUNK }).pipe(
118
+ Stream.runFoldEffect(
119
+ () => 0,
120
+ (total, chunk) => handle.writeAll(chunk).pipe(Effect.as(total + chunk.length)),
121
+ ),
122
+ )
123
+ yield* handle.truncate(written)
124
+ }, Effect.scoped)
125
+
126
+ // Removes a lock left by a process that died mid-trim. Still yields this round: the next interval
127
+ // acquires cleanly, and a process that is legitimately trimming right now keeps its lock.
128
+ //
129
+ // Two processes that both observe the same stale lock can race here: one removes it, a third
130
+ // acquires fresh, and the other removes that fresh lock. That needs a crash inside a sub-second trim
131
+ // followed by three processes ticking within the same few milliseconds, and the consequence is the
132
+ // same bounded tail loss documented on `trim`. Not worth a breaker protocol; see EffectFlock if it is.
133
+ function breakStaleLock(fs: FileSystem.FileSystem, lock: string) {
134
+ return Effect.gen(function* () {
135
+ const info = yield* fs.stat(lock).pipe(Effect.option)
136
+ const modified = Option.flatMap(info, (value) => value.mtime)
137
+ if (Option.isNone(modified)) return false
138
+ if (Date.now() - modified.value.getTime() < LOG_TRIM_LOCK_STALE_MS) return false
139
+ yield* fs.remove(lock, { recursive: true }).pipe(Effect.ignore)
140
+ return false
141
+ })
142
+ }
143
+
144
+ // First byte after the first newline at or beyond `from`, or EOF when the tail has no newline.
145
+ function lineStart(handle: FileSystem.File, from: number) {
146
+ return Effect.gen(function* () {
147
+ let cursor = from
148
+ while (true) {
149
+ yield* handle.seek(BigInt(cursor), "start")
150
+ const chunk = yield* handle.readAlloc(LOG_TRIM_CHUNK)
151
+ if (Option.isNone(chunk)) return cursor
152
+ const newline = chunk.value.indexOf(10)
153
+ if (newline !== -1) return cursor + newline + 1
154
+ cursor += chunk.value.length
155
+ }
156
+ })
157
+ }
158
+
159
+ const stderrLogger = Logger.make((options) => {
160
+ if ((process.env.ZYROSEC_PRINT_LOGS ?? process.env.OPENCODE_PRINT_LOGS) !== "1") return
161
+ process.stderr.write(formatter().log(options) + "\n")
162
+ })
163
+
164
+ export function minimumLogLevel() {
165
+ const value = (process.env.ZYROSEC_LOG_LEVEL ?? process.env.OPENCODE_LOG_LEVEL)?.toUpperCase()
166
+ const levels = {
167
+ DEBUG: "Debug",
168
+ INFO: "Info",
169
+ WARN: "Warn",
170
+ ERROR: "Error",
171
+ } as const satisfies Record<string, LogLevel.LogLevel>
172
+ return value && value in levels ? levels[value as keyof typeof levels] : levels.INFO
173
+ }
174
+
175
+ export function loggers(local = true, channel = "local") {
176
+ return [fileLogger(file(local, channel)), stderrLogger]
177
+ }
178
+
179
+ export * as Logging from "./logging.js"
@@ -0,0 +1,109 @@
1
+ import { Effect, Layer, Scope } from "effect"
2
+ import { OtlpLogger } from "effect/observability"
3
+ import { runID } from "./shared.js"
4
+
5
+ export interface Options {
6
+ readonly endpoint?: string
7
+ readonly headers?: string
8
+ }
9
+
10
+ export interface App {
11
+ readonly client: string
12
+ readonly version: string
13
+ readonly channel: string
14
+ }
15
+
16
+ function parseHeaders(value?: string) {
17
+ return value
18
+ ? value.split(",").reduce(
19
+ (acc, entry) => {
20
+ const [key, ...value] = entry.split("=")
21
+ acc[key] = value.join("=")
22
+ return acc
23
+ },
24
+ {} as Record<string, string>,
25
+ )
26
+ : undefined
27
+ }
28
+
29
+ function resourceAttributes() {
30
+ const value = process.env.OTEL_RESOURCE_ATTRIBUTES
31
+ if (!value) return {}
32
+ try {
33
+ return Object.fromEntries(
34
+ value.split(",").map((entry) => {
35
+ const index = entry.indexOf("=")
36
+ if (index < 1) throw new Error("Invalid OTEL_RESOURCE_ATTRIBUTES entry")
37
+ return [decodeURIComponent(entry.slice(0, index)), decodeURIComponent(entry.slice(index + 1))]
38
+ }),
39
+ )
40
+ } catch {
41
+ return {}
42
+ }
43
+ }
44
+
45
+ export function resource(app: App = { client: "opencode", version: "unknown", channel: "local" }): {
46
+ serviceName: string
47
+ serviceVersion: string
48
+ attributes: Record<string, string>
49
+ } {
50
+ return {
51
+ serviceName: "opencode",
52
+ serviceVersion: app.version,
53
+ attributes: {
54
+ ...resourceAttributes(),
55
+ "deployment.environment.name": app.channel,
56
+ "opencode.client": app.client,
57
+ "opencode.run": runID(),
58
+ "service.instance.id": runID(),
59
+ },
60
+ }
61
+ }
62
+
63
+ export function loggers(options: Options | undefined, app: App) {
64
+ if (!options?.endpoint) return []
65
+ return [
66
+ OtlpLogger.make({
67
+ url: `${options.endpoint}/v1/logs`,
68
+ resource: resource(app),
69
+ headers: parseHeaders(options.headers),
70
+ }),
71
+ ]
72
+ }
73
+
74
+ export const tracingLayer = Effect.fnUntraced(function* (options: Options | undefined, app: App) {
75
+ if (!options?.endpoint) return Layer.empty
76
+ const [{ layer }, { OTLPTraceExporter }, { BatchSpanProcessor }, { AsyncLocalStorageContextManager }, { context }] =
77
+ yield* Effect.all(
78
+ [
79
+ Effect.promise(() => import("@effect/opentelemetry/NodeSdk")),
80
+ Effect.promise(() => import("@opentelemetry/exporter-trace-otlp-http")),
81
+ Effect.promise(() => import("@opentelemetry/sdk-trace-base")),
82
+ Effect.promise(() => import("@opentelemetry/context-async-hooks")),
83
+ Effect.promise(() => import("@opentelemetry/api")),
84
+ ],
85
+ { concurrency: "unbounded" },
86
+ )
87
+
88
+ // The Effect Node SDK does not register a global context manager, but the AI SDK uses it to parent spans.
89
+ const manager = new AsyncLocalStorageContextManager()
90
+ manager.enable()
91
+ context.setGlobalContextManager(manager)
92
+
93
+ const tracing = layer(() => ({
94
+ resource: resource(app),
95
+ spanProcessor: new BatchSpanProcessor(
96
+ new OTLPTraceExporter({
97
+ url: `${options.endpoint}/v1/traces`,
98
+ headers: parseHeaders(options.headers),
99
+ }),
100
+ ),
101
+ }))
102
+ return Layer.effectContext(
103
+ Effect.acquireRelease(Scope.make(), (scope, exit) => Scope.close(scope, exit).pipe(Effect.ignoreCause)).pipe(
104
+ Effect.flatMap((scope) => Layer.buildWithScope(tracing, scope)),
105
+ ),
106
+ )
107
+ })
108
+
109
+ export * as Otlp from "./otlp.js"
@@ -0,0 +1,8 @@
1
+ // Lazy: workerd forbids generating random values in global scope, so the id
2
+ // materializes on first call (inside a handler) and stays stable afterwards.
3
+ let generated: string | undefined
4
+
5
+ export function runID(): string {
6
+ generated ??= crypto.randomUUID().slice(0, 8)
7
+ return generated
8
+ }
@@ -0,0 +1,60 @@
1
+ export * as Observability from "./observability.js"
2
+
3
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"
4
+ import { LayerNode } from "./effect/layer-node.js"
5
+ import { Effect, Layer, Logger, References, Schema } from "effect"
6
+ import { FetchHttpClient } from "effect/http"
7
+ import { OtlpExporter, OtlpSerialization } from "effect/observability"
8
+ import { Logging } from "./observability/logging.js"
9
+ import { Otlp } from "./observability/otlp.js"
10
+
11
+ export const Options = Schema.Struct({
12
+ endpoint: Schema.optional(Schema.String),
13
+ headers: Schema.optional(Schema.String),
14
+ client: Schema.optional(Schema.String),
15
+ version: Schema.optional(Schema.String),
16
+ channel: Schema.optional(Schema.String),
17
+ })
18
+ export type Options = typeof Options.Type
19
+
20
+ export function layer(
21
+ options: Options = {
22
+ endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
23
+ headers: process.env.OTEL_EXPORTER_OTLP_HEADERS,
24
+ },
25
+ ) {
26
+ const app = {
27
+ client: options.client ?? "opencode",
28
+ version: options.version ?? "unknown",
29
+ channel: options.channel ?? "local",
30
+ }
31
+ const local = Logger.layer(Logging.loggers(app.channel === "local", app.channel), { mergeWithExisting: false }).pipe(
32
+ Layer.provide(NodeFileSystem.layer),
33
+ Layer.orDie,
34
+ Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())),
35
+ )
36
+ return Layer.unwrap(
37
+ Effect.gen(function* () {
38
+ const logs = Logger.layer(
39
+ [...Logging.loggers(app.channel === "local", app.channel), ...Otlp.loggers(options, app)],
40
+ { mergeWithExisting: false },
41
+ ).pipe(
42
+ Layer.provide(NodeFileSystem.layer),
43
+ Layer.provide(OtlpSerialization.layerJson),
44
+ Layer.provide(FetchHttpClient.layer),
45
+ Layer.provide(OtlpExporter.layerFlusher),
46
+ Layer.orDie,
47
+ Layer.merge(Layer.succeed(References.MinimumLogLevel, Logging.minimumLogLevel())),
48
+ )
49
+ return Layer.merge(logs, yield* Otlp.tracingLayer(options, app))
50
+ }),
51
+ ).pipe(Layer.catchCause(() => local))
52
+ }
53
+
54
+ // Layer.suspend: constructing the loggers eagerly at module scope performs
55
+ // I/O (file logger, run id) that workerd forbids in global scope.
56
+ export const node = LayerNode.make({
57
+ name: "observability",
58
+ layer: Layer.suspend(() => layer()),
59
+ deps: [],
60
+ })
@@ -0,0 +1,16 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { openUrl } from "./open.js"
3
+
4
+ describe("openUrl", () => {
5
+ test("rejects values that are not URLs", async () => {
6
+ await expect(openUrl("not a url")).rejects.toThrow("Only http and https links")
7
+ await expect(openUrl("")).rejects.toThrow("Only http and https links")
8
+ })
9
+
10
+ test("rejects non-http schemes", async () => {
11
+ await expect(openUrl("file:///etc/hosts")).rejects.toThrow("Only http and https links")
12
+ await expect(openUrl("javascript:alert(1)")).rejects.toThrow("Only http and https links")
13
+ await expect(openUrl("ms-msdt:/id PCWDiagnostic")).rejects.toThrow("Only http and https links")
14
+ await expect(openUrl("\\\\server\\share\\file.html")).rejects.toThrow("Only http and https links")
15
+ })
16
+ })
package/src/open.ts ADDED
@@ -0,0 +1,12 @@
1
+ import open from "open"
2
+
3
+ export function openUrl(input: string) {
4
+ const url = URL.canParse(input) ? new URL(input) : undefined
5
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
6
+ return Promise.reject(new Error(`Only http and https links can be opened in the browser: ${input}`))
7
+ return open(url.href)
8
+ }
9
+
10
+ export function openPath(path: string) {
11
+ return open(path)
12
+ }