@opencode/util 2.1.4 → 2.2.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/dist/abort.d.ts +1 -0
- package/dist/abort.js +8 -0
- package/dist/cross-spawn-spawner.d.ts +2 -0
- package/dist/cross-spawn-spawner.js +35 -5
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +22 -0
- package/dist/effect/layer-node.js +18 -2
- package/dist/process-signal.d.ts +5 -0
- package/dist/process-signal.js +22 -0
- package/dist/qr.d.ts +15 -0
- package/dist/qr.js +295 -0
- package/dist/record.d.ts +2 -0
- package/dist/record.js +2 -0
- package/dist/session-mention.d.ts +11 -0
- package/dist/session-mention.js +18 -0
- package/dist/session-turn.d.ts +29 -0
- package/dist/session-turn.js +45 -0
- package/dist/teardown.d.ts +8 -0
- package/dist/teardown.js +16 -0
- package/package.json +4 -2
package/dist/abort.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function abort(controller: AbortController | undefined): void;
|
package/dist/abort.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// `controller.abort()` makes a new DOMException that records the caller's stack, and V8 keeps every frame's function
|
|
2
|
+
// and closure alive until something reads `.stack`. Aborting from a Solid cleanup or update then pins the whole batch
|
|
3
|
+
// it ran in, disposed computations and detached DOM included, for as long as the signal is reachable. This reason is
|
|
4
|
+
// made once, so its stack holds only this module's load.
|
|
5
|
+
const reason = new DOMException("signal is aborted without reason", "AbortError");
|
|
6
|
+
export function abort(controller) {
|
|
7
|
+
controller?.abort(reason);
|
|
8
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
|
|
2
|
+
/** Closing a child's scope escalates to SIGKILL after this, unless the command sets its own `forceKillAfter`. */
|
|
3
|
+
export declare const RELEASE_FORCE_KILL_AFTER = "3 seconds";
|
|
2
4
|
export declare class KilledBySignal extends Error {
|
|
3
5
|
readonly signal: NodeJS.Signals;
|
|
4
6
|
constructor(signal: NodeJS.Signals);
|
|
@@ -10,6 +10,21 @@ import { PassThrough } from "node:stream";
|
|
|
10
10
|
import launch from "cross-spawn";
|
|
11
11
|
import { makeGlobalNode } from "./effect/app-node.js";
|
|
12
12
|
import { filesystem, path } from "./effect/app-node-platform.js";
|
|
13
|
+
import { Teardown } from "./teardown.js";
|
|
14
|
+
/** Closing a child's scope escalates to SIGKILL after this, unless the command sets its own `forceKillAfter`. */
|
|
15
|
+
export const RELEASE_FORCE_KILL_AFTER = "3 seconds";
|
|
16
|
+
// Process groups of running children. Exiting without stopping them (a shutdown deadline, a second signal, a
|
|
17
|
+
// crash) would orphan them, so a synchronous exit hook kills whatever is left.
|
|
18
|
+
const groups = new Set();
|
|
19
|
+
let hooked = false;
|
|
20
|
+
const killGroups = () => groups.forEach((pid) => {
|
|
21
|
+
try {
|
|
22
|
+
globalThis.process.kill(-pid, "SIGKILL");
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// Already gone.
|
|
26
|
+
}
|
|
27
|
+
});
|
|
13
28
|
const toError = (err) => (err instanceof globalThis.Error ? err : new globalThis.Error(String(err)));
|
|
14
29
|
const toTag = (err) => {
|
|
15
30
|
switch (err.code) {
|
|
@@ -229,12 +244,14 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
|
229
244
|
const closed = Deferred.makeUnsafe();
|
|
230
245
|
const exited = Deferred.makeUnsafe();
|
|
231
246
|
const proc = launch(command.command, command.args, opts);
|
|
247
|
+
let settle = () => { };
|
|
232
248
|
let end = false;
|
|
233
249
|
let exit;
|
|
234
250
|
proc.on("error", (err) => {
|
|
235
251
|
resume(Effect.fail(toPlatformError("spawn", err, command)));
|
|
236
252
|
});
|
|
237
253
|
proc.on("exit", (...args) => {
|
|
254
|
+
groups.delete(proc.pid);
|
|
238
255
|
exit = args;
|
|
239
256
|
Deferred.doneUnsafe(exited, Exit.succeed(args));
|
|
240
257
|
});
|
|
@@ -242,11 +259,19 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
|
242
259
|
if (end)
|
|
243
260
|
return;
|
|
244
261
|
end = true;
|
|
262
|
+
settle();
|
|
245
263
|
Deferred.doneUnsafe(exited, Exit.succeed(exit ?? args));
|
|
246
264
|
Deferred.doneUnsafe(closed, Exit.succeed(exit ?? args));
|
|
247
265
|
});
|
|
248
266
|
proc.on("spawn", () => {
|
|
249
|
-
|
|
267
|
+
if (opts.detached && globalThis.process.platform !== "win32") {
|
|
268
|
+
if (!hooked)
|
|
269
|
+
globalThis.process.once("exit", killGroups);
|
|
270
|
+
hooked = true;
|
|
271
|
+
groups.add(proc.pid);
|
|
272
|
+
}
|
|
273
|
+
settle = Teardown.track(`child ${proc.pid} running: ${[command.command, ...command.args].join(" ").slice(0, 200)}`);
|
|
274
|
+
resume(Effect.succeed([proc, closed, exited, () => settle()]));
|
|
250
275
|
});
|
|
251
276
|
return Effect.sync(() => {
|
|
252
277
|
proc.kill("SIGTERM");
|
|
@@ -254,7 +279,7 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
|
254
279
|
});
|
|
255
280
|
const spawn = Effect.fnUntraced(function* (command, opts) {
|
|
256
281
|
yield* Effect.logInfo("spawning process", { command: command.command, args: command.args, cwd: opts.cwd });
|
|
257
|
-
const [proc, closed, exited] = yield* launchProcess(command, opts);
|
|
282
|
+
const [proc, closed, exited, settle] = yield* launchProcess(command, opts);
|
|
258
283
|
const stopOutput = yield* Deferred.make();
|
|
259
284
|
// Register before process release so the deadline remains active during termination.
|
|
260
285
|
yield* Effect.forkScoped(Effect.gen(function* () {
|
|
@@ -269,7 +294,7 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
|
269
294
|
discard(proc.stdout);
|
|
270
295
|
discard(proc.stderr);
|
|
271
296
|
}));
|
|
272
|
-
return [proc, closed, exited, stopOutput];
|
|
297
|
+
return [proc, closed, exited, stopOutput, settle];
|
|
273
298
|
});
|
|
274
299
|
const discard = (readable) => {
|
|
275
300
|
if (!readable || readable.destroyed)
|
|
@@ -360,8 +385,13 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
|
360
385
|
return yield* Effect.ignore(killGroup(command, proc, command.options.killSignal ?? "SIGTERM"));
|
|
361
386
|
}
|
|
362
387
|
}
|
|
363
|
-
yield* Effect.ignore(stop(command, proc, closed, stopOutput,
|
|
364
|
-
|
|
388
|
+
yield* Effect.ignore(stop(command, proc, closed, stopOutput, {
|
|
389
|
+
killSignal: command.options.killSignal,
|
|
390
|
+
forceKillAfter: command.options.forceKillAfter ?? RELEASE_FORCE_KILL_AFTER,
|
|
391
|
+
}));
|
|
392
|
+
}, (effect, [proc, , , stopOutput, settle]) => effect.pipe(Effect.ensuring(Effect.gen(function* () {
|
|
393
|
+
// A detached descendant holding the pipes can keep "close" from ever firing.
|
|
394
|
+
settle();
|
|
365
395
|
yield* Deferred.succeed(stopOutput, undefined);
|
|
366
396
|
proc.stdout?.destroy();
|
|
367
397
|
proc.stderr?.destroy();
|
package/dist/duration.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Compact elapsed time, e.g. `850ms`, `12.4s`, `3m 5s`, `2h 10m` or `1d 4h`. */
|
|
2
|
+
export function duration(input) {
|
|
3
|
+
if (input < 1000) {
|
|
4
|
+
return `${input}ms`;
|
|
5
|
+
}
|
|
6
|
+
if (input < 60000) {
|
|
7
|
+
return `${(input / 1000).toFixed(1)}s`;
|
|
8
|
+
}
|
|
9
|
+
if (input < 3600000) {
|
|
10
|
+
const minutes = Math.floor(input / 60000);
|
|
11
|
+
const seconds = Math.floor((input % 60000) / 1000);
|
|
12
|
+
return `${minutes}m ${seconds}s`;
|
|
13
|
+
}
|
|
14
|
+
if (input < 86400000) {
|
|
15
|
+
const hours = Math.floor(input / 3600000);
|
|
16
|
+
const minutes = Math.floor((input % 3600000) / 60000);
|
|
17
|
+
return `${hours}h ${minutes}m`;
|
|
18
|
+
}
|
|
19
|
+
const days = Math.floor(input / 86400000);
|
|
20
|
+
const hours = Math.floor((input % 86400000) / 3600000);
|
|
21
|
+
return `${days}d ${hours}h`;
|
|
22
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { Brand, Context, Effect, Layer } from "effect";
|
|
1
|
+
import { Brand, Context, Effect, Layer, Scope } from "effect";
|
|
2
|
+
import { Teardown } from "../teardown.js";
|
|
2
3
|
export * as LayerNode from "./layer-node.js";
|
|
3
4
|
const GraphTypeId = Symbol("LayerNode.Graph");
|
|
4
5
|
const VarianceTypeId = Symbol("LayerNode.Variance");
|
|
@@ -109,6 +110,7 @@ export function compile(root, options = {}) {
|
|
|
109
110
|
if (definition.kind === "unbound")
|
|
110
111
|
throw new Error(`Unbound layer node: ${definition.name}`);
|
|
111
112
|
const node = {
|
|
113
|
+
name: definition.name,
|
|
112
114
|
implementation: definition.implementation,
|
|
113
115
|
dependencies: definition.dependencies.flatMap((dependency) => resolve(dependency, isShared)),
|
|
114
116
|
shared: isShared,
|
|
@@ -141,13 +143,27 @@ export function compile(root, options = {}) {
|
|
|
141
143
|
const dependencies = node.dependencies.map(build);
|
|
142
144
|
// Acquisition uses the selected cache, while lazy LayerMaps inherit the enclosing shared cache.
|
|
143
145
|
const implementation = Layer.suspend(() => node.implementation.pipe(Layer.provide([ambient, ...dependencies])));
|
|
144
|
-
const layer = Layer.fromBuild((_, scope) => buildContext(implementation, node.shared ? memoMap : local, scope));
|
|
146
|
+
const layer = Layer.fromBuild((_, scope) => trackRelease(node.name, scope, () => buildContext(implementation, node.shared ? memoMap : local, scope)));
|
|
145
147
|
layers.set(node, layer);
|
|
146
148
|
return layer;
|
|
147
149
|
};
|
|
148
150
|
return buildContext(roots.map(build).reduce((result, layer) => layer.pipe(Layer.provideMerge(result)), Layer.empty), memoMap, scope);
|
|
149
151
|
});
|
|
150
152
|
}
|
|
153
|
+
// The node's scope releases sequentially in reverse order, so a finalizer added before the build runs last and one
|
|
154
|
+
// added after it runs first: together they bracket the release of everything this node acquired. The build must
|
|
155
|
+
// not start before the first finalizer is added; Layer builds fork their scopes as soon as they are called.
|
|
156
|
+
function trackRelease(name, scope, build) {
|
|
157
|
+
return Effect.gen(function* () {
|
|
158
|
+
let settle = () => { };
|
|
159
|
+
yield* Scope.addFinalizer(scope, Effect.sync(() => settle()));
|
|
160
|
+
const result = yield* build();
|
|
161
|
+
yield* Scope.addFinalizer(scope, Effect.sync(() => {
|
|
162
|
+
settle = Teardown.track(`layer ${name} releasing`);
|
|
163
|
+
}));
|
|
164
|
+
return result;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
151
167
|
class BuildResult extends Context.Service()("@opencode/LayerNode/BuildResult") {
|
|
152
168
|
}
|
|
153
169
|
function buildContext(layer, memoMap, scope) {
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export * as ProcessSignal from "./process-signal.js";
|
|
2
|
+
/** Install once at process startup. Removing subscribers never restores the signal's default action. */
|
|
3
|
+
export declare function install(signal: NodeJS.Signals, unavailable: () => void): void;
|
|
4
|
+
/** Subscribe only to an installed signal. The returned cleanup removes this subscriber, not the process handler. */
|
|
5
|
+
export declare function subscribe(signal: NodeJS.Signals, listener: () => void): () => void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export * as ProcessSignal from "./process-signal.js";
|
|
2
|
+
const handlers = new Map();
|
|
3
|
+
/** Install once at process startup. Removing subscribers never restores the signal's default action. */
|
|
4
|
+
export function install(signal, unavailable) {
|
|
5
|
+
if (handlers.has(signal))
|
|
6
|
+
return;
|
|
7
|
+
const listeners = new Set();
|
|
8
|
+
handlers.set(signal, listeners);
|
|
9
|
+
process.on(signal, () => {
|
|
10
|
+
if (!listeners.size)
|
|
11
|
+
return unavailable();
|
|
12
|
+
listeners.forEach((listener) => listener());
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
/** Subscribe only to an installed signal. The returned cleanup removes this subscriber, not the process handler. */
|
|
16
|
+
export function subscribe(signal, listener) {
|
|
17
|
+
const listeners = handlers.get(signal);
|
|
18
|
+
listeners?.add(listener);
|
|
19
|
+
return () => {
|
|
20
|
+
listeners?.delete(listener);
|
|
21
|
+
};
|
|
22
|
+
}
|
package/dist/qr.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Encodes text as UTF-8 into the smallest QR Code that fits. Rows of modules without a quiet zone; true is dark. */
|
|
2
|
+
export declare function encode(text: string): boolean[][];
|
|
3
|
+
/** Renders text as an SVG QR Code with 10-unit modules and a quiet zone of `border` modules. */
|
|
4
|
+
export declare function renderSVG(text: string, options?: {
|
|
5
|
+
border?: number;
|
|
6
|
+
blackColor?: string;
|
|
7
|
+
whiteColor?: string;
|
|
8
|
+
}): string;
|
|
9
|
+
/**
|
|
10
|
+
* Renders text as a QR Code for a terminal, two modules per character with half blocks. Light modules draw as blocks
|
|
11
|
+
* and dark modules as the terminal background, rows are joined with "\n", and the quiet zone is `border` modules.
|
|
12
|
+
*/
|
|
13
|
+
export declare function renderUnicodeCompact(text: string, options?: {
|
|
14
|
+
border?: number;
|
|
15
|
+
}): string;
|
package/dist/qr.js
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// QR Code encoder (ISO/IEC 18004) for byte-mode text at error correction level L, following the structure of
|
|
2
|
+
// Project Nayuki's QR Code generator (MIT): https://www.nayuki.io/page/qr-code-generator-library
|
|
3
|
+
// Error correction codewords per block and block count at level L, for versions 1 to 40.
|
|
4
|
+
const ECC_PER_BLOCK = [
|
|
5
|
+
7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30,
|
|
6
|
+
30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
|
|
7
|
+
];
|
|
8
|
+
const BLOCKS = [
|
|
9
|
+
1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19,
|
|
10
|
+
20, 21, 22, 24, 25,
|
|
11
|
+
];
|
|
12
|
+
const MASKS = [
|
|
13
|
+
(x, y) => (x + y) % 2 === 0,
|
|
14
|
+
(_, y) => y % 2 === 0,
|
|
15
|
+
(x) => x % 3 === 0,
|
|
16
|
+
(x, y) => (x + y) % 3 === 0,
|
|
17
|
+
(x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
|
|
18
|
+
(x, y) => ((x * y) % 2) + ((x * y) % 3) === 0,
|
|
19
|
+
(x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
|
|
20
|
+
(x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
|
|
21
|
+
];
|
|
22
|
+
/** Encodes text as UTF-8 into the smallest QR Code that fits. Rows of modules without a quiet zone; true is dark. */
|
|
23
|
+
export function encode(text) {
|
|
24
|
+
const bytes = new TextEncoder().encode(text);
|
|
25
|
+
const version = Array.from({ length: 40 }, (_, i) => i + 1).find((v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8 <= dataCapacity(v) * 8);
|
|
26
|
+
if (version === undefined)
|
|
27
|
+
throw new RangeError(`Text is too long for a QR Code: ${bytes.length} bytes`);
|
|
28
|
+
const size = version * 4 + 17;
|
|
29
|
+
const modules = Array.from({ length: size }, () => Array(size).fill(false));
|
|
30
|
+
const reserved = Array.from({ length: size }, () => Array(size).fill(false));
|
|
31
|
+
drawFunctionPatterns(version, size, (x, y, dark) => {
|
|
32
|
+
modules[y][x] = dark;
|
|
33
|
+
reserved[y][x] = true;
|
|
34
|
+
});
|
|
35
|
+
drawCodewords(modules, reserved, addErrorCorrection(dataCodewords(bytes, version), version));
|
|
36
|
+
const candidates = MASKS.map((mask, index) => {
|
|
37
|
+
const masked = modules.map((row, y) => row.map((dark, x) => dark !== (!reserved[y][x] && mask(x, y))));
|
|
38
|
+
drawFormat(index, size, (x, y, dark) => {
|
|
39
|
+
masked[y][x] = dark;
|
|
40
|
+
});
|
|
41
|
+
return masked;
|
|
42
|
+
});
|
|
43
|
+
const scores = candidates.map(penalty);
|
|
44
|
+
return candidates[scores.indexOf(Math.min(...scores))];
|
|
45
|
+
}
|
|
46
|
+
/** Renders text as an SVG QR Code with 10-unit modules and a quiet zone of `border` modules. */
|
|
47
|
+
export function renderSVG(text, options = {}) {
|
|
48
|
+
const modules = addBorder(encode(text), options.border ?? 1);
|
|
49
|
+
const width = modules.length * 10;
|
|
50
|
+
const path = modules
|
|
51
|
+
.flatMap((row, y) => row.flatMap((dark, x) => (dark ? [`M${x * 10},${y * 10}h10v10h-10z`] : [])))
|
|
52
|
+
.join("");
|
|
53
|
+
return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${width}">` +
|
|
54
|
+
`<rect fill="${escapeAttribute(options.whiteColor ?? "white")}" width="${width}" height="${width}"/>` +
|
|
55
|
+
`<path fill="${escapeAttribute(options.blackColor ?? "black")}" d="${path}"/></svg>`);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Renders text as a QR Code for a terminal, two modules per character with half blocks. Light modules draw as blocks
|
|
59
|
+
* and dark modules as the terminal background, rows are joined with "\n", and the quiet zone is `border` modules.
|
|
60
|
+
*/
|
|
61
|
+
export function renderUnicodeCompact(text, options = {}) {
|
|
62
|
+
const modules = addBorder(encode(text), options.border ?? 1);
|
|
63
|
+
return Array.from({ length: Math.ceil(modules.length / 2) }, (_, line) => modules[line * 2]
|
|
64
|
+
.map((top, x) => {
|
|
65
|
+
// The symbol has an odd number of rows, so the last line's missing bottom half shows the terminal background.
|
|
66
|
+
const bottom = modules[line * 2 + 1]?.[x] ?? true;
|
|
67
|
+
if (top)
|
|
68
|
+
return bottom ? " " : "\u2584";
|
|
69
|
+
return bottom ? "\u2580" : "\u2588";
|
|
70
|
+
})
|
|
71
|
+
.join("")).join("\n");
|
|
72
|
+
}
|
|
73
|
+
function drawFunctionPatterns(version, size, set) {
|
|
74
|
+
for (let i = 0; i < size; i++) {
|
|
75
|
+
set(6, i, i % 2 === 0);
|
|
76
|
+
set(i, 6, i % 2 === 0);
|
|
77
|
+
}
|
|
78
|
+
for (const [cx, cy] of [
|
|
79
|
+
[3, 3],
|
|
80
|
+
[size - 4, 3],
|
|
81
|
+
[3, size - 4],
|
|
82
|
+
])
|
|
83
|
+
for (let dy = -4; dy <= 4; dy++)
|
|
84
|
+
for (let dx = -4; dx <= 4; dx++) {
|
|
85
|
+
const x = cx + dx;
|
|
86
|
+
const y = cy + dy;
|
|
87
|
+
const distance = Math.max(Math.abs(dx), Math.abs(dy));
|
|
88
|
+
if (x >= 0 && x < size && y >= 0 && y < size)
|
|
89
|
+
set(x, y, distance !== 2 && distance !== 4);
|
|
90
|
+
}
|
|
91
|
+
const positions = alignmentPositions(version, size);
|
|
92
|
+
const last = positions.length - 1;
|
|
93
|
+
positions.forEach((cx, i) => positions.forEach((cy, j) => {
|
|
94
|
+
// Skip the three corners that hold finder patterns.
|
|
95
|
+
if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0))
|
|
96
|
+
return;
|
|
97
|
+
for (let dy = -2; dy <= 2; dy++)
|
|
98
|
+
for (let dx = -2; dx <= 2; dx++)
|
|
99
|
+
set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
|
|
100
|
+
}));
|
|
101
|
+
// Reserves the format areas; the real format bits are drawn once the mask is chosen.
|
|
102
|
+
drawFormat(0, size, set);
|
|
103
|
+
if (version < 7)
|
|
104
|
+
return;
|
|
105
|
+
const bits = bch(version, 12, 0x1f25);
|
|
106
|
+
for (let i = 0; i < 18; i++) {
|
|
107
|
+
const a = size - 11 + (i % 3);
|
|
108
|
+
const b = Math.floor(i / 3);
|
|
109
|
+
const dark = ((bits >>> i) & 1) === 1;
|
|
110
|
+
set(a, b, dark);
|
|
111
|
+
set(b, a, dark);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function alignmentPositions(version, size) {
|
|
115
|
+
if (version === 1)
|
|
116
|
+
return [];
|
|
117
|
+
const count = Math.floor(version / 7) + 2;
|
|
118
|
+
const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2;
|
|
119
|
+
return [6, ...Array.from({ length: count - 1 }, (_, i) => size - 7 - (count - 2 - i) * step)];
|
|
120
|
+
}
|
|
121
|
+
function drawFormat(mask, size, set) {
|
|
122
|
+
// Level L is 0b01 in the format information.
|
|
123
|
+
const bits = bch((1 << 3) | mask, 10, 0x537) ^ 0x5412;
|
|
124
|
+
const bit = (i) => ((bits >>> i) & 1) === 1;
|
|
125
|
+
for (let i = 0; i <= 5; i++)
|
|
126
|
+
set(8, i, bit(i));
|
|
127
|
+
set(8, 7, bit(6));
|
|
128
|
+
set(8, 8, bit(7));
|
|
129
|
+
set(7, 8, bit(8));
|
|
130
|
+
for (let i = 9; i < 15; i++)
|
|
131
|
+
set(14 - i, 8, bit(i));
|
|
132
|
+
for (let i = 0; i < 8; i++)
|
|
133
|
+
set(size - 1 - i, 8, bit(i));
|
|
134
|
+
for (let i = 8; i < 15; i++)
|
|
135
|
+
set(8, size - 15 + i, bit(i));
|
|
136
|
+
set(8, size - 8, true);
|
|
137
|
+
}
|
|
138
|
+
// Appends the BCH remainder of `data` for a generator polynomial of the given degree.
|
|
139
|
+
function bch(data, degree, generator) {
|
|
140
|
+
let remainder = data;
|
|
141
|
+
for (let i = 0; i < degree; i++)
|
|
142
|
+
remainder = (remainder << 1) ^ ((remainder >>> (degree - 1)) * generator);
|
|
143
|
+
return (data << degree) | remainder;
|
|
144
|
+
}
|
|
145
|
+
function dataCodewords(bytes, version) {
|
|
146
|
+
const capacity = dataCapacity(version);
|
|
147
|
+
const bits = [];
|
|
148
|
+
const append = (value, length) => {
|
|
149
|
+
for (let i = length - 1; i >= 0; i--)
|
|
150
|
+
bits.push((value >>> i) & 1);
|
|
151
|
+
};
|
|
152
|
+
append(0b0100, 4);
|
|
153
|
+
append(bytes.length, version < 10 ? 8 : 16);
|
|
154
|
+
bytes.forEach((byte) => append(byte, 8));
|
|
155
|
+
append(0, Math.min(4, capacity * 8 - bits.length));
|
|
156
|
+
append(0, (8 - (bits.length % 8)) % 8);
|
|
157
|
+
const data = Array.from({ length: bits.length / 8 }, (_, i) => bits.slice(i * 8, i * 8 + 8).reduce((byte, bit) => (byte << 1) | bit, 0));
|
|
158
|
+
return [...data, ...Array.from({ length: capacity - data.length }, (_, i) => (i % 2 === 0 ? 0xec : 0x11))];
|
|
159
|
+
}
|
|
160
|
+
function addErrorCorrection(data, version) {
|
|
161
|
+
const blocks = BLOCKS[version - 1];
|
|
162
|
+
const ecc = ECC_PER_BLOCK[version - 1];
|
|
163
|
+
const raw = Math.floor(rawModules(version) / 8);
|
|
164
|
+
// The first `short` blocks hold one data codeword fewer than the rest.
|
|
165
|
+
const short = blocks - (raw % blocks);
|
|
166
|
+
const shortLength = Math.floor(raw / blocks) - ecc;
|
|
167
|
+
const divisor = reedSolomonDivisor(ecc);
|
|
168
|
+
const split = Array.from({ length: blocks }, (_, i) => {
|
|
169
|
+
const start = i * shortLength + Math.max(0, i - short);
|
|
170
|
+
return data.slice(start, start + shortLength + (i < short ? 0 : 1));
|
|
171
|
+
});
|
|
172
|
+
const interleave = (rows, length) => Array.from({ length }, (_, i) => rows.flatMap((row) => (i < row.length ? [row[i]] : []))).flat();
|
|
173
|
+
return [
|
|
174
|
+
...interleave(split, shortLength + 1),
|
|
175
|
+
...interleave(split.map((block) => reedSolomonRemainder(block, divisor)), ecc),
|
|
176
|
+
];
|
|
177
|
+
}
|
|
178
|
+
function drawCodewords(modules, reserved, codewords) {
|
|
179
|
+
const size = modules.length;
|
|
180
|
+
let i = 0;
|
|
181
|
+
for (let right = size - 1; right >= 1; right -= 2) {
|
|
182
|
+
// The vertical timing pattern takes column 6, so the column pair shifts left past it.
|
|
183
|
+
if (right === 6)
|
|
184
|
+
right = 5;
|
|
185
|
+
for (let vertical = 0; vertical < size; vertical++)
|
|
186
|
+
for (let j = 0; j < 2; j++) {
|
|
187
|
+
const x = right - j;
|
|
188
|
+
const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical;
|
|
189
|
+
if (reserved[y][x] || i >= codewords.length * 8)
|
|
190
|
+
continue;
|
|
191
|
+
modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) === 1;
|
|
192
|
+
i++;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function penalty(modules) {
|
|
197
|
+
const size = modules.length;
|
|
198
|
+
const columns = modules.map((_, x) => modules.map((row) => row[x]));
|
|
199
|
+
const lines = [...modules, ...columns].reduce((sum, line) => sum + linePenalty(line), 0);
|
|
200
|
+
// Each 2x2 block of one colour, found from its bottom-right module.
|
|
201
|
+
const boxes = modules
|
|
202
|
+
.slice(1)
|
|
203
|
+
.flatMap((row, y) => row.slice(1).filter((dark, x) => dark === row[x] && dark === modules[y][x] && dark === modules[y][x + 1])).length;
|
|
204
|
+
const dark = modules.flat().filter(Boolean).length;
|
|
205
|
+
const total = size * size;
|
|
206
|
+
return lines + boxes * 3 + (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;
|
|
207
|
+
}
|
|
208
|
+
// Scores runs of five or more same-coloured modules, and 1:1:3:1:1 finder-like patterns with 4 light modules on a side.
|
|
209
|
+
function linePenalty(line) {
|
|
210
|
+
const size = line.length;
|
|
211
|
+
const history = [0, 0, 0, 0, 0, 0, 0];
|
|
212
|
+
const push = (length) => {
|
|
213
|
+
history.pop();
|
|
214
|
+
history.unshift(history[0] === 0 ? length + size : length);
|
|
215
|
+
};
|
|
216
|
+
const finders = () => {
|
|
217
|
+
const n = history[1];
|
|
218
|
+
const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n;
|
|
219
|
+
return ((core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) +
|
|
220
|
+
(core && history[6] >= n * 4 && history[0] >= n ? 1 : 0));
|
|
221
|
+
};
|
|
222
|
+
let result = 0;
|
|
223
|
+
let color = false;
|
|
224
|
+
let run = 0;
|
|
225
|
+
for (const dark of line) {
|
|
226
|
+
if (dark === color) {
|
|
227
|
+
run++;
|
|
228
|
+
if (run === 5)
|
|
229
|
+
result += 3;
|
|
230
|
+
if (run > 5)
|
|
231
|
+
result++;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
push(run);
|
|
235
|
+
if (!color)
|
|
236
|
+
result += finders() * 40;
|
|
237
|
+
color = dark;
|
|
238
|
+
run = 1;
|
|
239
|
+
}
|
|
240
|
+
if (color) {
|
|
241
|
+
push(run);
|
|
242
|
+
run = 0;
|
|
243
|
+
}
|
|
244
|
+
push(run + size);
|
|
245
|
+
return result + finders() * 40;
|
|
246
|
+
}
|
|
247
|
+
function reedSolomonDivisor(degree) {
|
|
248
|
+
const result = Array(degree).fill(0);
|
|
249
|
+
result[degree - 1] = 1;
|
|
250
|
+
let root = 1;
|
|
251
|
+
for (let i = 0; i < degree; i++) {
|
|
252
|
+
for (let j = 0; j < degree; j++) {
|
|
253
|
+
result[j] = multiply(result[j], root);
|
|
254
|
+
if (j + 1 < degree)
|
|
255
|
+
result[j] ^= result[j + 1];
|
|
256
|
+
}
|
|
257
|
+
root = multiply(root, 2);
|
|
258
|
+
}
|
|
259
|
+
return result;
|
|
260
|
+
}
|
|
261
|
+
function reedSolomonRemainder(data, divisor) {
|
|
262
|
+
return data.reduce((remainder, byte) => {
|
|
263
|
+
const factor = byte ^ remainder[0];
|
|
264
|
+
return [...remainder.slice(1), 0].map((value, i) => value ^ multiply(divisor[i], factor));
|
|
265
|
+
}, divisor.map(() => 0));
|
|
266
|
+
}
|
|
267
|
+
// Multiplies in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1.
|
|
268
|
+
function multiply(x, y) {
|
|
269
|
+
let z = 0;
|
|
270
|
+
for (let i = 7; i >= 0; i--) {
|
|
271
|
+
z = (z << 1) ^ ((z >>> 7) * 0x11d);
|
|
272
|
+
z ^= ((y >>> i) & 1) * x;
|
|
273
|
+
}
|
|
274
|
+
return z;
|
|
275
|
+
}
|
|
276
|
+
function rawModules(version) {
|
|
277
|
+
const base = (16 * version + 128) * version + 64;
|
|
278
|
+
if (version < 2)
|
|
279
|
+
return base;
|
|
280
|
+
const count = Math.floor(version / 7) + 2;
|
|
281
|
+
return base - ((25 * count - 10) * count - 55) - (version >= 7 ? 36 : 0);
|
|
282
|
+
}
|
|
283
|
+
function dataCapacity(version) {
|
|
284
|
+
return Math.floor(rawModules(version) / 8) - ECC_PER_BLOCK[version - 1] * BLOCKS[version - 1];
|
|
285
|
+
}
|
|
286
|
+
function addBorder(modules, border) {
|
|
287
|
+
const width = modules.length + border * 2;
|
|
288
|
+
const blank = () => Array(width).fill(false);
|
|
289
|
+
const edge = Array.from({ length: border }, blank);
|
|
290
|
+
const padding = Array(border).fill(false);
|
|
291
|
+
return [...edge, ...modules.map((row) => [...padding, ...row, ...padding]), ...Array.from({ length: border }, blank)];
|
|
292
|
+
}
|
|
293
|
+
function escapeAttribute(value) {
|
|
294
|
+
return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
|
295
|
+
}
|
package/dist/record.d.ts
ADDED
package/dist/record.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type SessionMention = {
|
|
2
|
+
id: `ses_${string}`;
|
|
3
|
+
};
|
|
4
|
+
export declare function sessionMentions(text: string): {
|
|
5
|
+
id: SessionMention["id"];
|
|
6
|
+
text: string;
|
|
7
|
+
start: number;
|
|
8
|
+
end: number;
|
|
9
|
+
}[];
|
|
10
|
+
export declare function parseSessionMention(text: string): SessionMention | undefined;
|
|
11
|
+
export declare function serializeSessionMention(mention: SessionMention): string;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Match complete generated IDs only, including while an assistant is streaming one.
|
|
2
|
+
const pattern = /(?<![\w/:@-])(?:@session:)?(ses_[A-Za-z0-9]{26})(?![\w/-])/g;
|
|
3
|
+
export function sessionMentions(text) {
|
|
4
|
+
return Array.from(text.matchAll(pattern), (match) => ({
|
|
5
|
+
// SAFETY: the capture above requires the session prefix and a complete generated suffix.
|
|
6
|
+
id: match[1],
|
|
7
|
+
text: match[0],
|
|
8
|
+
start: match.index,
|
|
9
|
+
end: match.index + match[0].length,
|
|
10
|
+
}));
|
|
11
|
+
}
|
|
12
|
+
export function parseSessionMention(text) {
|
|
13
|
+
const match = sessionMentions(text)[0];
|
|
14
|
+
return match?.text === text ? { id: match.id } : undefined;
|
|
15
|
+
}
|
|
16
|
+
export function serializeSessionMention(mention) {
|
|
17
|
+
return `@session:${mention.id}`;
|
|
18
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export * as SessionTurn from "./session-turn.js";
|
|
2
|
+
/** The fields of a session message that turn measurements read. Client session messages satisfy it as they are. */
|
|
3
|
+
export interface Message {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly type: string;
|
|
6
|
+
readonly time: {
|
|
7
|
+
readonly created: number;
|
|
8
|
+
readonly streamed?: number;
|
|
9
|
+
readonly completed?: number;
|
|
10
|
+
};
|
|
11
|
+
readonly tokens?: {
|
|
12
|
+
readonly output: number;
|
|
13
|
+
readonly reasoning: number;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export interface Options {
|
|
17
|
+
/** The position of `message` in `messages`. Reactive callers should pass it so the lookup does not read every message. */
|
|
18
|
+
readonly index?: number;
|
|
19
|
+
/**
|
|
20
|
+
* Whether the session has no idle markers, so a turn ends at the next prompt. Reactive callers should pass it from a
|
|
21
|
+
* shared memo: the default scans every message, which subscribes the caller to the whole history.
|
|
22
|
+
*/
|
|
23
|
+
readonly legacy?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** Milliseconds from the prompt that started the turn until `message` completed, or 0 while it runs. */
|
|
26
|
+
export declare function duration(messages: readonly Message[], message: Message, options?: Options): number;
|
|
27
|
+
/** Output and reasoning tokens per second across the turn's steps up to `message`, or undefined until every step has streamed. */
|
|
28
|
+
export declare function tokensPerSecond(messages: readonly Message[], message: Message, options?: Options): number | undefined;
|
|
29
|
+
export declare function legacy(messages: readonly Message[]): boolean;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export * as SessionTurn from "./session-turn.js";
|
|
2
|
+
/** Milliseconds from the prompt that started the turn until `message` completed, or 0 while it runs. */
|
|
3
|
+
export function duration(messages, message, options = {}) {
|
|
4
|
+
if (message.time.completed === undefined)
|
|
5
|
+
return 0;
|
|
6
|
+
const index = options.index ?? messages.findIndex((item) => item.id === message.id);
|
|
7
|
+
const input = messages[inputIndex(messages, index === -1 ? messages.length : index, options.legacy ?? legacy(messages))];
|
|
8
|
+
return Math.max(0, message.time.completed - (input?.time.created ?? message.time.created));
|
|
9
|
+
}
|
|
10
|
+
/** Output and reasoning tokens per second across the turn's steps up to `message`, or undefined until every step has streamed. */
|
|
11
|
+
export function tokensPerSecond(messages, message, options = {}) {
|
|
12
|
+
const index = options.index ?? messages.findIndex((item) => item.id === message.id);
|
|
13
|
+
const end = index === -1 ? messages.length : index + 1;
|
|
14
|
+
const start = inputIndex(messages, end, options.legacy ?? legacy(messages));
|
|
15
|
+
const steps = messages.slice(start + 1, end).filter((item) => item.type === "assistant");
|
|
16
|
+
const durations = steps.flatMap((step) => step.time.streamed === undefined ? [] : [Math.max(0, step.time.streamed - step.time.created)]);
|
|
17
|
+
if (steps.length === 0 || durations.length !== steps.length)
|
|
18
|
+
return;
|
|
19
|
+
const output = steps.reduce((total, step) => total + (step.tokens?.output ?? 0) + (step.tokens?.reasoning ?? 0), 0);
|
|
20
|
+
const total = durations.reduce((sum, value) => sum + value, 0);
|
|
21
|
+
if (output <= 0 || total <= 0)
|
|
22
|
+
return;
|
|
23
|
+
// Aggregate before dividing so each step is weighted by its provider-active duration.
|
|
24
|
+
return output / (total / 1_000);
|
|
25
|
+
}
|
|
26
|
+
export function legacy(messages) {
|
|
27
|
+
return !messages.some((message) => message.type === "idle");
|
|
28
|
+
}
|
|
29
|
+
function inputIndex(messages, end, legacy) {
|
|
30
|
+
// Reading a sliced prefix subscribes every caller to unrelated historical messages, so walk
|
|
31
|
+
// back only as far as the turn boundary: the nearest input in legacy sessions, otherwise the
|
|
32
|
+
// first input after the previous idle marker.
|
|
33
|
+
let input = -1;
|
|
34
|
+
for (let index = end - 1; index >= 0; index--) {
|
|
35
|
+
const message = messages[index];
|
|
36
|
+
if (message.type === "idle")
|
|
37
|
+
return input;
|
|
38
|
+
if (message.type !== "user" && message.type !== "synthetic")
|
|
39
|
+
continue;
|
|
40
|
+
if (legacy)
|
|
41
|
+
return index;
|
|
42
|
+
input = index;
|
|
43
|
+
}
|
|
44
|
+
return input;
|
|
45
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * as Teardown from "./teardown.js";
|
|
2
|
+
/** Record pending work; call the returned function once it settles. */
|
|
3
|
+
export declare function track(label: string): () => void;
|
|
4
|
+
/** Pending work, oldest first, with how long each has been pending. */
|
|
5
|
+
export declare function pending(now?: number): {
|
|
6
|
+
label: string;
|
|
7
|
+
ms: number;
|
|
8
|
+
}[];
|
package/dist/teardown.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export * as Teardown from "./teardown.js";
|
|
2
|
+
// Work that shutdown may be waiting on: layers releasing their resources and child processes that have not
|
|
3
|
+
// closed. Read when a shutdown deadline expires, to name what kept the process alive.
|
|
4
|
+
const entries = new Set();
|
|
5
|
+
/** Record pending work; call the returned function once it settles. */
|
|
6
|
+
export function track(label) {
|
|
7
|
+
const entry = { label, since: Date.now() };
|
|
8
|
+
entries.add(entry);
|
|
9
|
+
return () => {
|
|
10
|
+
entries.delete(entry);
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** Pending work, oldest first, with how long each has been pending. */
|
|
14
|
+
export function pending(now = Date.now()) {
|
|
15
|
+
return Array.from(entries, (entry) => ({ label: entry.label, ms: now - entry.since }));
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@opencode/util",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"build": "bun run script/build.ts",
|
|
42
|
+
"pack": "bun run script/pack.ts",
|
|
42
43
|
"test": "bun test --only-failures",
|
|
43
44
|
"typecheck": "bun check --no-script",
|
|
44
45
|
"typecheck:tsc": "tsc --noEmit",
|
|
@@ -76,6 +77,7 @@
|
|
|
76
77
|
"@types/npm-package-arg": "6.1.4",
|
|
77
78
|
"@types/npmcli__arborist": "6.3.3",
|
|
78
79
|
"@types/pacote": "11.1.8",
|
|
79
|
-
"@typescript/native": "npm:typescript@7.1.0-beta"
|
|
80
|
+
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
81
|
+
"jsqr": "1.4.0"
|
|
80
82
|
}
|
|
81
83
|
}
|