@opencode/util 2.2.6 → 2.3.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.
@@ -291,10 +291,19 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
291
291
  stderr = Stream.transduce(stderr, err.stream);
292
292
  return { stdout, stderr, all: Stream.merge(stdout, stderr) };
293
293
  };
294
- const launchProcess = (command, opts) => Effect.callback((resume) => {
294
+ // A Microsoft Store app execution alias, such as Store PowerShell 7 in %LOCALAPPDATA%\Microsoft\WindowsApps, is a
295
+ // reparse point that stat rejects with EACCES. cross-spawn then cannot find it and runs it through
296
+ // `cmd.exe /d /s /c`, which drops everything after the first newline of the command line. Launch the target of
297
+ // the link instead, read on every spawn because a Store update moves it.
298
+ const executable = (file) => {
299
+ if (globalThis.process.platform !== "win32" || !path.isAbsolute(file))
300
+ return Effect.succeed(file);
301
+ return fs.readLink(file).pipe(Effect.map((target) => path.resolve(path.dirname(file), target)), Effect.orElseSucceed(() => file));
302
+ };
303
+ const launchProcess = (command, file, opts) => Effect.callback((resume) => {
295
304
  const closed = Deferred.makeUnsafe();
296
305
  const exited = Deferred.makeUnsafe();
297
- const proc = launch(command.command, command.args.map(unwrap), opts);
306
+ const proc = launch(file, command.args.map(unwrap), opts);
298
307
  let settle = () => { };
299
308
  let end = false;
300
309
  let exit;
@@ -335,8 +344,8 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
335
344
  });
336
345
  });
337
346
  const spawn = Effect.fnUntraced(function* (command, opts) {
338
- yield* Effect.logInfo("spawning process", { command: command.command, args: command.args, cwd: opts.cwd });
339
- const [proc, closed, exited, settle] = yield* launchProcess(command, opts);
347
+ yield* Effect.logDebug("spawning process", { command: command.command, args: command.args, cwd: opts.cwd });
348
+ const [proc, closed, exited, settle] = yield* launchProcess(command, yield* executable(command.command), opts);
340
349
  const stopOutput = yield* Deferred.make();
341
350
  // Register before process release so the deadline remains active during termination.
342
351
  yield* Effect.forkScoped(Effect.gen(function* () {
@@ -4,7 +4,7 @@ export declare const tags: LayerNode.Tags<{
4
4
  readonly global: readonly [];
5
5
  }>;
6
6
  export type GlobalGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["global"]>;
7
- export type LocationGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["location"]>;
7
+ export type LocationGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["location" | "global"]>;
8
8
  export declare const makeGlobalNode: LayerNode.TagMaker<{
9
9
  readonly location: readonly ["global"];
10
10
  readonly global: readonly [];
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Code Mode's `execute` output for display. The tool returns its result (compact JSON for structured values) followed
3
+ * by optional "Warnings:" and "Logs:" sections. A JSON result comes back indented as `json`, the sections as `rest`,
4
+ * and `text` joins them.
5
+ */
6
+ export declare function formatExecuteOutput(output: string): {
7
+ json: string | undefined;
8
+ rest: string | undefined;
9
+ text: string;
10
+ };
@@ -0,0 +1,22 @@
1
+ import { Option, Schema } from "effect";
2
+ const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
3
+ /**
4
+ * Code Mode's `execute` output for display. The tool returns its result (compact JSON for structured values) followed
5
+ * by optional "Warnings:" and "Logs:" sections. A JSON result comes back indented as `json`, the sections as `rest`,
6
+ * and `text` joins them.
7
+ */
8
+ export function formatExecuteOutput(output) {
9
+ const end = output.search(/\n\n(Warnings|Logs):\n/);
10
+ const result = end === -1 ? output : output.slice(0, end);
11
+ const rest = end === -1 ? undefined : output.slice(end).trim();
12
+ const json = indentedJson(result);
13
+ return { json, rest, text: rest === undefined ? (json ?? result) : `${json ?? result}\n\n${rest}` };
14
+ }
15
+ function indentedJson(text) {
16
+ if (!text.startsWith("{") && !text.startsWith("["))
17
+ return;
18
+ const decoded = decodeJson(text);
19
+ if (Option.isNone(decoded))
20
+ return;
21
+ return JSON.stringify(decoded.value, null, 2);
22
+ }
package/dist/npm.d.ts CHANGED
@@ -7,6 +7,7 @@ declare const InstallFailedError_base: Schema.Class<InstallFailedError, Schema.T
7
7
  readonly cause: Schema.optional<Schema.Defect>;
8
8
  }>, import("effect/Cause").YieldableError>;
9
9
  export declare class InstallFailedError extends InstallFailedError_base {
10
+ get message(): string;
10
11
  }
11
12
  export interface Package {
12
13
  readonly directory: string;
package/dist/npm.js CHANGED
@@ -13,6 +13,16 @@ export class InstallFailedError extends Schema.TaggedError()("NpmInstallFailedEr
13
13
  dir: Schema.String,
14
14
  cause: Schema.optional(Schema.Defect()),
15
15
  }) {
16
+ get message() {
17
+ const summary = `Failed to install ${this.add?.join(", ") || this.dir}`;
18
+ if (!(this.cause instanceof Error))
19
+ return summary;
20
+ // @npmcli/git reports most failures as "An unknown git error occurred" and keeps git's output on `stderr`.
21
+ const stderr = "stderr" in this.cause && typeof this.cause.stderr === "string" ? this.cause.stderr.trim() : "";
22
+ if (!stderr)
23
+ return `${summary}: ${this.cause.message}`;
24
+ return `${summary}: ${this.cause.message}\n${stderr}`;
25
+ }
16
26
  }
17
27
  export class Service extends Context.Service()("@opencode/Npm") {
18
28
  }
@@ -5,6 +5,8 @@ export interface Message {
5
5
  readonly type: string;
6
6
  readonly time: {
7
7
  readonly created: number;
8
+ /** When the provider streamed the first output token; steps recorded before this existed leave it unset. */
9
+ readonly firstToken?: number;
8
10
  readonly streamed?: number;
9
11
  readonly completed?: number;
10
12
  };
@@ -24,6 +26,17 @@ export interface Options {
24
26
  }
25
27
  /** Milliseconds from the prompt that started the turn until `message` completed, or 0 while it runs. */
26
28
  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. */
29
+ /**
30
+ * Output and reasoning tokens per second while the provider streamed them, or undefined until every step has streamed.
31
+ *
32
+ * Each step counts from its first streamed token to the end of the response body, so the wait for that first token
33
+ * (time to first token) is not divided into the output rate. Steps recorded before `time.firstToken` existed count
34
+ * from request dispatch instead, which is what this measured for them before the field existed.
35
+ */
28
36
  export declare function tokensPerSecond(messages: readonly Message[], message: Message, options?: Options): number | undefined;
37
+ /**
38
+ * Milliseconds from the dispatch of the turn's first token-producing step to its first streamed token, or undefined
39
+ * until a step records one.
40
+ */
41
+ export declare function timeToFirstToken(messages: readonly Message[], message: Message, options?: Options): number | undefined;
29
42
  export declare function legacy(messages: readonly Message[]): boolean;
@@ -7,13 +7,18 @@ export function duration(messages, message, options = {}) {
7
7
  const input = messages[inputIndex(messages, index === -1 ? messages.length : index, options.legacy ?? legacy(messages))];
8
8
  return Math.max(0, message.time.completed - (input?.time.created ?? message.time.created));
9
9
  }
10
- /** Output and reasoning tokens per second across the turn's steps up to `message`, or undefined until every step has streamed. */
10
+ /**
11
+ * Output and reasoning tokens per second while the provider streamed them, or undefined until every step has streamed.
12
+ *
13
+ * Each step counts from its first streamed token to the end of the response body, so the wait for that first token
14
+ * (time to first token) is not divided into the output rate. Steps recorded before `time.firstToken` existed count
15
+ * from request dispatch instead, which is what this measured for them before the field existed.
16
+ */
11
17
  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)]);
18
+ const steps = turnSteps(messages, message, options);
19
+ const durations = steps.flatMap((step) => step.time.streamed === undefined
20
+ ? []
21
+ : [Math.max(0, step.time.streamed - (step.time.firstToken ?? step.time.created))]);
17
22
  if (steps.length === 0 || durations.length !== steps.length)
18
23
  return;
19
24
  const output = steps.reduce((total, step) => total + (step.tokens?.output ?? 0) + (step.tokens?.reasoning ?? 0), 0);
@@ -23,9 +28,25 @@ export function tokensPerSecond(messages, message, options = {}) {
23
28
  // Aggregate before dividing so each step is weighted by its provider-active duration.
24
29
  return output / (total / 1_000);
25
30
  }
31
+ /**
32
+ * Milliseconds from the dispatch of the turn's first token-producing step to its first streamed token, or undefined
33
+ * until a step records one.
34
+ */
35
+ export function timeToFirstToken(messages, message, options = {}) {
36
+ const step = turnSteps(messages, message, options).find((item) => item.time.firstToken !== undefined);
37
+ if (step?.time.firstToken === undefined)
38
+ return;
39
+ return Math.max(0, step.time.firstToken - step.time.created);
40
+ }
26
41
  export function legacy(messages) {
27
42
  return !messages.some((message) => message.type === "idle");
28
43
  }
44
+ function turnSteps(messages, message, options) {
45
+ const index = options.index ?? messages.findIndex((item) => item.id === message.id);
46
+ const end = index === -1 ? messages.length : index + 1;
47
+ const start = inputIndex(messages, end, options.legacy ?? legacy(messages));
48
+ return messages.slice(start + 1, end).filter((item) => item.type === "assistant");
49
+ }
29
50
  function inputIndex(messages, end, legacy) {
30
51
  // Reading a sliced prefix subscribes every caller to unrelated historical messages, so walk
31
52
  // back only as far as the turn boundary: the nearest input in legacy sessions, otherwise the
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.2.6",
4
+ "version": "2.3.0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -17,12 +17,12 @@
17
17
  ],
18
18
  "exports": {
19
19
  "./effect/layer-node": {
20
- "import": "./dist/effect/layer-node.js",
21
- "types": "./dist/effect/layer-node.d.ts"
20
+ "types": "./dist/effect/layer-node.d.ts",
21
+ "import": "./dist/effect/layer-node.js"
22
22
  },
23
23
  "./*": {
24
- "import": "./dist/*.js",
25
- "types": "./dist/*.d.ts"
24
+ "types": "./dist/*.d.ts",
25
+ "import": "./dist/*.js"
26
26
  }
27
27
  },
28
28
  "imports": {