@opencode/util 2.1.3 → 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/npm.js CHANGED
@@ -7,8 +7,6 @@ import { Global } from "./global.js";
7
7
  import { EffectFlock } from "./effect-flock.js";
8
8
  import { makeGlobalNode } from "./effect/app-node.js";
9
9
  import { filesystem } from "./effect/app-node-platform.js";
10
- import { LayerNode } from "./effect/layer-node.js";
11
- import { makeRuntime } from "./effect/runtime.js";
12
10
  import { NpmConfig } from "./npm-config.js";
13
11
  export class InstallFailedError extends Schema.TaggedError()("NpmInstallFailedError", {
14
12
  add: Schema.Array(Schema.String).pipe(Schema.optional),
@@ -370,22 +368,6 @@ export const node = makeGlobalNode({
370
368
  layer: layer,
371
369
  deps: [FSUtil.node, Global.node, filesystem, EffectFlock.node],
372
370
  });
373
- const { runPromise } = makeRuntime(Service, LayerNode.compile(node));
374
- export async function add(...args) {
375
- return runPromise((svc) => svc.add(...args));
376
- }
377
- export async function resolve(...args) {
378
- return runPromise((svc) => svc.resolve(...args));
379
- }
380
- export async function check(...args) {
381
- return runPromise((svc) => svc.check(...args));
382
- }
383
- export async function update(...args) {
384
- return runPromise((svc) => svc.update(...args));
385
- }
386
- export async function which(...args) {
387
- return runPromise((svc) => svc.which(...args));
388
- }
389
371
  function gitRevision(resolved) {
390
372
  return resolved?.match(/#([a-f0-9]{40}|[a-f0-9]{64})(?=::|$)/i)?.[1];
391
373
  }
@@ -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("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
295
+ }
@@ -0,0 +1,2 @@
1
+ /** Plain-record narrowing. Excludes arrays so JSON object checks don't accept tuples as key/value bags. */
2
+ export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
package/dist/record.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Plain-record narrowing. Excludes arrays so JSON object checks don't accept tuples as key/value bags. */
2
+ export const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -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
+ }[];
@@ -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.1.3",
4
+ "version": "2.2.0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -39,8 +39,10 @@
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
- "typecheck": "tsc --noEmit",
44
+ "typecheck": "bun check --no-script",
45
+ "typecheck:tsc": "tsc --noEmit",
44
46
  "typecheck:dist": "bun run build && bun typecheck --project tsconfig.dist.json"
45
47
  },
46
48
  "dependencies": {
@@ -75,6 +77,7 @@
75
77
  "@types/npm-package-arg": "6.1.4",
76
78
  "@types/npmcli__arborist": "6.3.3",
77
79
  "@types/pacote": "11.1.8",
78
- "@typescript/native": "npm:typescript@7.0.2"
80
+ "@typescript/native": "npm:typescript@7.1.0-beta",
81
+ "jsqr": "1.4.0"
79
82
  }
80
83
  }
@@ -1,2 +0,0 @@
1
- import { Layer } from "effect";
2
- export declare const memoMap: Layer.MemoMap;
@@ -1,2 +0,0 @@
1
- import { Layer } from "effect";
2
- export const memoMap = Layer.makeMemoMapUnsafe();
@@ -1,8 +0,0 @@
1
- import { Layer, type Context, type Effect } from "effect";
2
- export declare function makeRuntime<I, S, E>(service: Context.Service<I, S>, layer: Layer.Layer<I, E>): {
3
- runSync: <A, Err>(fn: (svc: S) => Effect.Effect<A, Err, I>) => A;
4
- runPromiseExit: <A, Err>(fn: (svc: S) => Effect.Effect<A, Err, I>, options?: Effect.RunOptions) => Promise<import("effect/Exit").Exit<A, E | Err>>;
5
- runPromise: <A, Err>(fn: (svc: S) => Effect.Effect<A, Err, I>, options?: Effect.RunOptions) => Promise<A>;
6
- runFork: <A, Err>(fn: (svc: S) => Effect.Effect<A, Err, I>) => import("effect/Fiber").Fiber<A, E | Err>;
7
- runCallback: <A, Err>(fn: (svc: S) => Effect.Effect<A, Err, I>) => (interruptor?: number | undefined) => void;
8
- };
@@ -1,16 +0,0 @@
1
- import { Layer, ManagedRuntime } from "effect";
2
- import { memoMap } from "./memo-map.js";
3
- import { Observability } from "../observability.js";
4
- export function makeRuntime(service, layer) {
5
- let rt;
6
- const getRuntime = () => (rt ??= ManagedRuntime.make(Layer.provideMerge(layer, Observability.layer()), {
7
- memoMap,
8
- }));
9
- return {
10
- runSync: (fn) => getRuntime().runSync(service.use(fn)),
11
- runPromiseExit: (fn, options) => getRuntime().runPromiseExit(service.use(fn), options),
12
- runPromise: (fn, options) => getRuntime().runPromise(service.use(fn), options),
13
- runFork: (fn) => getRuntime().runFork(service.use(fn)),
14
- runCallback: (fn) => getRuntime().runCallback(service.use(fn)),
15
- };
16
- }
@@ -1,7 +0,0 @@
1
- import { Context, Effect } from "effect";
2
- type EffectMethod = (...args: ReadonlyArray<never>) => Effect.Effect<unknown, unknown, unknown>;
3
- type ServiceUse<Identifier, Shape> = {
4
- readonly [Key in keyof Shape as Shape[Key] extends EffectMethod ? Key : never]: Shape[Key] extends (...args: infer Args) => infer Return ? Args extends ReadonlyArray<unknown> ? Return extends Effect.Effect<infer A, infer E, infer R> ? (...args: Args) => Effect.Effect<A, E, R | Identifier> : never : never : never;
5
- };
6
- export declare const serviceUse: <Identifier, Shape>(tag: Context.Service<Identifier, Shape>) => ServiceUse<Identifier, Shape>;
7
- export {};
@@ -1,27 +0,0 @@
1
- import { Context, Effect } from "effect";
2
- export const serviceUse = (tag) => {
3
- const cache = new Map();
4
- // This is the only dynamic boundary: TypeScript knows the accessor shape,
5
- // but Proxy property names are runtime values.
6
- const access = new Proxy({}, {
7
- get: (_, key) => {
8
- if (typeof key !== "string")
9
- return undefined;
10
- const cached = cache.get(key);
11
- if (cached)
12
- return cached;
13
- const accessor = (...args) => tag.use((service) => {
14
- // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Proxy keys are checked at runtime.
15
- const method = service[key];
16
- if (typeof method !== "function")
17
- return Effect.die(new Error(`Service method not found: ${key}`));
18
- // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- ServiceUse exposes only Effect-returning methods.
19
- return method(...args);
20
- });
21
- cache.set(key, accessor);
22
- return accessor;
23
- },
24
- });
25
- // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Proxy implements the mapped accessor surface lazily.
26
- return access;
27
- };