@bridgebrew/harness-opencode 0.0.2 → 0.0.8

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 (3) hide show
  1. package/api.ts +9 -2
  2. package/package.json +6 -2
  3. package/server.ts +50 -12
package/api.ts CHANGED
@@ -92,11 +92,16 @@ export const connect = ({
92
92
  SILENT_MS,
93
93
  );
94
94
  };
95
+ // The server answers within `requestMs`, or the subscription fails (a stuck server would hang `open` forever).
96
+ const deadline = setTimeout(
97
+ () => abort.abort(new Error(`OpenCode did not answer its event stream in ${requestMs / 1000} s`)),
98
+ requestMs,
99
+ );
95
100
  const response = await fetch(`${base}/api/event`, {
96
101
  method: 'GET',
97
102
  headers: { authorization, accept: 'text/event-stream' },
98
103
  signal: abort.signal,
99
- });
104
+ }).finally(() => clearTimeout(deadline));
100
105
  if (!response.ok || !response.body) {
101
106
  abort.abort();
102
107
  throw new ApiError(
@@ -113,7 +118,9 @@ export const connect = ({
113
118
  // oxlint-disable-next-line bridge/no-new-unchecked-cast -- typing: Node's fetch body is an async iterable of bytes, which its DOM type does not say
114
119
  for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
115
120
  heard();
116
- buffer += decoder.decode(chunk, { stream: true }).replaceAll('\r\n', '\n');
121
+ // Line endings are normalised on the buffer: a `\r\n` can be split across two chunks. A `\r` at its end
122
+ // waits for the next chunk.
123
+ buffer = (buffer + decoder.decode(chunk, { stream: true })).replace(/\r\n|\r(?!$)/g, '\n');
117
124
  let cut: number;
118
125
  while ((cut = buffer.indexOf('\n\n')) >= 0) {
119
126
  const frame = buffer.slice(0, cut);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/harness-opencode",
3
- "version": "0.0.2",
3
+ "version": "0.0.8",
4
4
  "license": "MIT",
5
5
  "description": "Lets the harness run OpenCode 2, one server per session.",
6
6
  "keywords": [
@@ -52,7 +52,8 @@
52
52
  }
53
53
  }
54
54
  },
55
- "provenance": "official"
55
+ "provenance": "official",
56
+ "placement": "both"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "cordis": "4.0.0-rc.11"
@@ -61,5 +62,8 @@
61
62
  "scripts": {
62
63
  "test": "bridge plugin test .",
63
64
  "typecheck": "bridge plugin check ."
65
+ },
66
+ "engines": {
67
+ "bridge": ">=0.0.1-nightly.20261119.1"
64
68
  }
65
69
  }
package/server.ts CHANGED
@@ -37,6 +37,7 @@ import { randomBytes } from 'node:crypto';
37
37
  import { readFileSync } from 'node:fs';
38
38
  import { resolve } from 'node:path';
39
39
  import { pathToFileURL } from 'node:url';
40
+ import { stripVTControlCharacters } from 'node:util';
40
41
  import { isRecord, listOf } from './json.ts';
41
42
  import type { Context } from 'cordis';
42
43
  import { ApiError, connect, located, type Api, type Event, type Fetch } from './api.ts';
@@ -396,6 +397,14 @@ const outputOf = (content: unknown) => {
396
397
  return /^<subagent\b[^>]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text;
397
398
  };
398
399
 
400
+ /** How a call that ran ends: `failed` when it failed, or when it ran a command that exited non-zero (`metadata.exit`
401
+ * or `exitCode`: OpenCode reports a shell's exit code as a success). */
402
+ const endOf = (type: string, metadata: unknown) => {
403
+ const { exit, exitCode } = recordOf(metadata);
404
+ const exited = [exit, exitCode].some((code) => typeof code === 'number' && code !== 0);
405
+ return type === 'session.tool.success' && !exited ? 'completed' : 'failed';
406
+ };
407
+
399
408
  /** An ask's title: the command for a shell, the files for an edit, the folder for another directory, else the action
400
409
  * (an MCP tool's is `<server>_<tool>`) and what it names. */
401
410
  export const askTitle = (action: string, resources: string[]) => {
@@ -410,8 +419,7 @@ export const askTitle = (action: string, resources: string[]) => {
410
419
 
411
420
  /** The stderr tail an error message carries: its last lines. */
412
421
  const tailOf = (stderr: string) => {
413
- const lines = stderr
414
- .replace(/\x1b\[[0-9;]*m/g, '')
422
+ const lines = stripVTControlCharacters(stderr)
415
423
  .split('\n')
416
424
  .map((line) => line.trim())
417
425
  .filter(Boolean)
@@ -420,6 +428,22 @@ const tailOf = (stderr: string) => {
420
428
  return lines ? `: ${lines}` : '';
421
429
  };
422
430
 
431
+ /** The line of a failed command's error output that says why: the last error Node or the CLI printed (`Error: …`,
432
+ * `TypeError [ERR_…]: …`, `error: …`), else the last line that is neither a stack frame nor Node's `Node.js v…` line,
433
+ * else its last line. Node prints its version after the error, which alone tells nothing. */
434
+ const failureOf = (stderr: string) => {
435
+ const lines = stderr
436
+ .trim()
437
+ .split('\n')
438
+ .map((line) => line.trim());
439
+ return (
440
+ lines.findLast((line) => /^(?:Uncaught )?(?:\w*Error|error)(?: \[\w+\])?: /.test(line)) ??
441
+ lines.findLast((line) => line !== '' && !/^at /.test(line) && !/^Node\.js v\d/.test(line)) ??
442
+ lines.at(-1) ??
443
+ ''
444
+ );
445
+ };
446
+
423
447
  /** Runs `command args` through `spawn` to its end, or `ms` (then killed): its exit code (null when killed) and output. */
424
448
  const runToEnd = async (spawn: Spawn, options: Parameters<Spawn>[0], ms: number) => {
425
449
  const handle = await spawn(options);
@@ -520,13 +544,21 @@ export const opencodeDriver = ({
520
544
  };
521
545
  };
522
546
 
523
- /** Reads `path` (a catalog: models) until it lists something or `catalog.forMs` passed. */
547
+ /** Reads `path` (a catalog: models) until it lists something or `catalog.forMs` passed. A server still warming up
548
+ * answers 503: read again like an empty list, within the same deadline. */
524
549
  const catalogOf = async (api: Api, path: string) => {
525
550
  const until = Date.now() + catalog.forMs;
526
551
  for (;;) {
527
- const read = await api.get(path);
552
+ const read = await api.get(path).catch((error: unknown) => {
553
+ if (error instanceof ApiError && error.status === 503) return error;
554
+ throw error;
555
+ });
528
556
  const data = isRecord(read) ? listOf(read.data) : [];
529
- if (data.length || Date.now() >= until) return data;
557
+ if (data.length) return data;
558
+ if (Date.now() >= until) {
559
+ if (read instanceof ApiError) throw read; // still warming up past the deadline: not an empty catalog
560
+ return data;
561
+ }
530
562
  await new Promise((resolve) => setTimeout(resolve, catalog.everyMs));
531
563
  }
532
564
  };
@@ -535,7 +567,7 @@ export const opencodeDriver = ({
535
567
  name: 'opencode',
536
568
  capabilities: () => ({ resume: true, images: true, models: true, modes: true, steer: true }),
537
569
  // `GET /api/model` from a throwaway server (its default marked current), kept `MODELS_TTL_MS` per setup. A list that
538
- // cannot be read is empty (and not kept): the entry's custom models still show.
570
+ // cannot be read, or lists nothing (a cold server), is empty and not kept: the entry's custom models still show.
539
571
  async models({ harness, config, cwd }) {
540
572
  let setup: Setup;
541
573
  try {
@@ -578,7 +610,9 @@ export const opencodeDriver = ({
578
610
  })();
579
611
  listed.set(key, { at: Date.now(), models });
580
612
  try {
581
- return await models;
613
+ const found = await models;
614
+ if (!found.length) listed.delete(key);
615
+ return found;
582
616
  } catch (error) {
583
617
  listed.delete(key);
584
618
  log.error(`harness ${harness}: OpenCode's models could not be listed`, error);
@@ -607,7 +641,7 @@ export const opencodeDriver = ({
607
641
  const said = ran.stdout.trim().split('\n')[0]?.trim();
608
642
  const version = said ? versionOf(said) : undefined;
609
643
  if (ran.code !== 0 || !said || !version) {
610
- const why = ran.stderr.trim().split('\n').at(-1) ?? '';
644
+ const why = failureOf(ran.stderr);
611
645
  return {
612
646
  installed: false,
613
647
  message: `${command} --version ${ran.code === null ? 'did not answer' : 'failed'}${why ? `: ${why}` : ''}`,
@@ -978,7 +1012,8 @@ export const opencodeDriver = ({
978
1012
  );
979
1013
  };
980
1014
 
981
- /** The context window of the model a step runs, read once per model from the session's server. */
1015
+ /** The context window of the model a step runs, read once per model from the session's server (again after a
1016
+ * failed read). */
982
1017
  const windows = new Map<string, Promise<number | undefined>>();
983
1018
  const windowOf = (ref: unknown) => {
984
1019
  const mine = recordOf(ref);
@@ -997,7 +1032,10 @@ export const opencodeDriver = ({
997
1032
  const size = sizes.input ?? sizes.context;
998
1033
  return typeof size === 'number' && size > 0 ? size : undefined;
999
1034
  })
1000
- .catch(() => undefined),
1035
+ .catch(() => {
1036
+ windows.delete(key); // a failed read is not kept: the next step reads again
1037
+ return undefined;
1038
+ }),
1001
1039
  );
1002
1040
  return windows.get(key)!;
1003
1041
  };
@@ -1082,7 +1120,7 @@ export const opencodeDriver = ({
1082
1120
  if (!known) return;
1083
1121
  setTool({
1084
1122
  ...known,
1085
- status: type === 'session.tool.success' ? 'completed' : 'failed',
1123
+ status: endOf(type, body.metadata),
1086
1124
  output:
1087
1125
  type === 'session.tool.success'
1088
1126
  ? outputOf(body.content)
@@ -1220,7 +1258,7 @@ export const opencodeDriver = ({
1220
1258
  : (str(recordOf(body.error).message) ?? 'The tool failed.');
1221
1259
  setTool({
1222
1260
  ...known,
1223
- status: type === 'session.tool.success' ? 'completed' : 'failed',
1261
+ status: endOf(type, body.metadata),
1224
1262
  output,
1225
1263
  });
1226
1264
  return;