@bridgebrew/harness-opencode 0.0.5 → 0.0.10

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/README.md +1 -1
  2. package/package.json +10 -5
  3. package/server.ts +149 -18
package/README.md CHANGED
@@ -29,7 +29,7 @@ Requires `harness`.
29
29
  ## Limits
30
30
 
31
31
  Not handled yet: work OpenCode starts by itself (a background sub-agent's report), fork and rollback, compaction,
32
- slash commands, model variants, an external OpenCode server, reconnecting a lost event stream.
32
+ model variants, an external OpenCode server, reconnecting a lost event stream.
33
33
 
34
34
  ## Third-party code
35
35
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/harness-opencode",
3
- "version": "0.0.5",
3
+ "version": "0.0.10",
4
4
  "license": "MIT",
5
5
  "description": "Lets the harness run OpenCode 2, one server per session.",
6
6
  "keywords": [
@@ -20,8 +20,12 @@
20
20
  "icon": "plug",
21
21
  "domain": "agents",
22
22
  "server": "./server.ts",
23
- "requires": {
24
- "harness": {}
23
+ "contracts": {
24
+ "uses": {
25
+ "harness": {
26
+ "version": "1.0"
27
+ }
28
+ }
25
29
  },
26
30
  "driver": {
27
31
  "name": "opencode",
@@ -52,7 +56,8 @@
52
56
  }
53
57
  }
54
58
  },
55
- "provenance": "official"
59
+ "provenance": "official",
60
+ "placement": "both"
56
61
  },
57
62
  "peerDependencies": {
58
63
  "cordis": "4.0.0-rc.11"
@@ -63,6 +68,6 @@
63
68
  "typecheck": "bridge plugin check ."
64
69
  },
65
70
  "engines": {
66
- "bridge": ">=0.0.1-nightly.20261114.1"
71
+ "bridge": ">=0.0.1-nightly.20261120.1"
67
72
  }
68
73
  }
package/server.ts CHANGED
@@ -7,7 +7,8 @@
7
7
  // takes the password the driver put in `OPENCODE_PASSWORD`. The driver subscribes to `/api/event` first (the stream is
8
8
  // global and nothing is replayed), then loads the stored session (`GET /api/session/<resume>`; a session OpenCode no
9
9
  // longer has opens fresh, `resumed` false) or creates one in the folder with the model and the permission rules of the
10
- // mode, and registers the session's MCP servers on that server. Each turn is a `prompt`; it ends on the session's next
10
+ // mode, and registers the session's MCP servers on that server. Each turn is a `prompt` (a leading `/<name>` runs that
11
+ // command or skill instead, `commands` lists them); it ends on the session's next
11
12
  // `session.execution.succeeded|failed|interrupted`. Text and reasoning stream per delta, an `…ended` fills in what did
12
13
  // not stream; tool calls go from `tool.input.started` to `tool.success|failed`, a step's tokens are the usage. A level is
13
14
  // a set of session rules (`shell`, `edit`, `external_directory`: ask, allow or deny; God allows `*`), with the MCP
@@ -29,14 +30,14 @@
29
30
  // its id the one the prompt answered), or starts an execution with it once the running one ended; the turn ends at the
30
31
  // end of the execution that took the last one, so what the agent does about it streams to the same turn. Not handled
31
32
  // yet: executions OpenCode starts by itself (a background subagent's report: their events are dropped and their
32
- // asks rejected), fork and rollback, compaction and
33
- // slash commands, model variants, an external server, reconnecting. An entry may set `command` (default
34
- // `opencode2`, the name `@opencode/cli` installs beside `opencode`), `args` (flags for `serve`) and `environment` (an
33
+ // asks rejected), fork and rollback, compaction, model variants, an external server, reconnecting. An entry may set
34
+ // `command` (default `opencode2`, the name `@opencode/cli` installs beside `opencode`), `args` (flags for `serve`) and `environment` (an
35
35
  // isolated OpenCode's XDG folders, say). `status` checks `<command> --version` without a model call.
36
36
  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';
@@ -270,8 +271,9 @@ const exitedWithin = async (exited: Promise<unknown>, ms: number) => {
270
271
  const STATUS_MS = 15_000;
271
272
  /** How long a model list is kept, per entry setup. */
272
273
  const MODELS_TTL_MS = 5 * 60_000;
273
- /** A server started a moment ago lists no models yet: read again this often, this long. */
274
- const CATALOG_RETRY = { everyMs: 250, forMs: 5_000 };
274
+ /** A server started a moment ago lists no models yet: read again this often, this long; a prompt's `/<name>` is
275
+ * looked up for `lookupMs` at most (`listsOf`). */
276
+ const CATALOG_RETRY = { everyMs: 250, forMs: 5_000, lookupMs: 2_000 };
275
277
  /** The longest `setTimeout` delay (2^31 - 1 ms); a longer one fires at once. */
276
278
  const TIMEOUT_MAX = 2_147_483_647;
277
279
  /** What a declined ask tells the model (it reads it as `permission.rejected`). */
@@ -317,6 +319,80 @@ const str = (value: unknown) => (typeof value === 'string' && value !== '' ? val
317
319
  const recordOf = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {});
318
320
  /** An HTTP answer's `data` (its payload) as an object, or an empty one. */
319
321
  const dataOf = (answer: unknown) => recordOf(recordOf(answer).data);
322
+
323
+ type Command = NonNullable<Awaited<ReturnType<NonNullable<Driver['commands']>>>>[number];
324
+
325
+ /** OpenCode's two lists of what a `/<name>` runs, by kind, each as last read: its entries, or why it gave none. */
326
+ type Lists = Record<Command['kind'], { data?: unknown[]; error?: unknown }>;
327
+
328
+ /** OpenCode's commands (`GET /api/command`) and skills (`GET /api/skill`) in `directory`, each list read every `everyMs`
329
+ * until it reads the same twice or its read fails (503, warming up, is read again), `enough` says what was read
330
+ * suffices, or `forMs` passed, a stuck request included. OpenCode 2.0.29 loads a folder's lists on its first request
331
+ * there: a read then is empty or partial, the rest follow within ~250 ms (probe of 20 November 2026). ponytail: "the
332
+ * same twice" can stop on a list still loading slowly; the next read has it. */
333
+ const listsOf = (
334
+ api: Api,
335
+ directory: string,
336
+ { everyMs, forMs }: { everyMs: number; forMs: number },
337
+ enough: (lists: Lists) => boolean = () => false,
338
+ ) =>
339
+ new Promise<Lists>((done) => {
340
+ const lists: Lists = { command: {}, skill: {} };
341
+ const settled = new Set<Command['kind']>();
342
+ let over = false;
343
+ const end = () => {
344
+ if (over) return;
345
+ over = true;
346
+ clearTimeout(timer);
347
+ done(lists);
348
+ };
349
+ const timer = setTimeout(end, forMs);
350
+ const watch = async (kind: Command['kind']) => {
351
+ let was: string | undefined;
352
+ while (!over) {
353
+ const read: Lists[Command['kind']] = await api
354
+ .get(`/api/${kind}?${located(directory)}`)
355
+ .then(
356
+ (answer) => ({ data: isRecord(answer) ? listOf(answer.data) : [] }),
357
+ (error: unknown) => ({ error }),
358
+ );
359
+ if (over) return;
360
+ lists[kind] = read;
361
+ if (enough(lists)) return end();
362
+ const now = read.data && JSON.stringify(read.data);
363
+ const warming = read.error instanceof ApiError && read.error.status === 503;
364
+ if (!warming && (read.error !== undefined || now === was)) {
365
+ settled.add(kind);
366
+ if (settled.size === 2) end();
367
+ return;
368
+ }
369
+ was = now;
370
+ await new Promise((resolve) => setTimeout(resolve, everyMs));
371
+ }
372
+ };
373
+ void watch('command');
374
+ void watch('skill');
375
+ });
376
+
377
+ /** The commands then the skills (named by their `id`) of `lists`, each name once, a command before a skill of the
378
+ * same name. */
379
+ const commandsIn = (lists: Lists) => {
380
+ const seen = new Set<string>();
381
+ const listed = (kind: Command['kind'], name: unknown, description: unknown): Command[] => {
382
+ const named = str(name);
383
+ if (!named || seen.has(named)) return [];
384
+ seen.add(named);
385
+ return [{ name: named, description: str(description) ?? '', kind }];
386
+ };
387
+ return [
388
+ ...(lists.command.data ?? []).flatMap((each) =>
389
+ isRecord(each) ? listed('command', each.name, each.description) : [],
390
+ ),
391
+ ...(lists.skill.data ?? []).flatMap((each) =>
392
+ isRecord(each) ? listed('skill', each.id, each.description) : [],
393
+ ),
394
+ ];
395
+ };
320
396
  const pathIn = (input: unknown) => {
321
397
  const given = recordOf(input);
322
398
  return str(given.filePath) ?? str(given.path) ?? str(given.file);
@@ -418,8 +494,7 @@ export const askTitle = (action: string, resources: string[]) => {
418
494
 
419
495
  /** The stderr tail an error message carries: its last lines. */
420
496
  const tailOf = (stderr: string) => {
421
- const lines = stderr
422
- .replace(/\x1b\[[0-9;]*m/g, '')
497
+ const lines = stripVTControlCharacters(stderr)
423
498
  .split('\n')
424
499
  .map((line) => line.trim())
425
500
  .filter(Boolean)
@@ -478,7 +553,7 @@ export const opencodeDriver = ({
478
553
  fetch?: Fetch;
479
554
  disposing?: () => boolean;
480
555
  deadlines?: { requestMs: number; startMs: number; stopMs: number };
481
- catalog?: { everyMs: number; forMs: number };
556
+ catalog?: { everyMs: number; forMs: number; lookupMs: number };
482
557
  log?: { error: (...args: unknown[]) => void };
483
558
  }): Driver => {
484
559
  /** Configs whose `decisionTimeoutMs` was refused, said once each. */
@@ -567,7 +642,7 @@ export const opencodeDriver = ({
567
642
  name: 'opencode',
568
643
  capabilities: () => ({ resume: true, images: true, models: true, modes: true, steer: true }),
569
644
  // `GET /api/model` from a throwaway server (its default marked current), kept `MODELS_TTL_MS` per setup. A list that
570
- // cannot be read is empty (and not kept): the entry's custom models still show.
645
+ // cannot be read, or lists nothing (a cold server), is empty and not kept: the entry's custom models still show.
571
646
  async models({ harness, config, cwd }) {
572
647
  let setup: Setup;
573
648
  try {
@@ -610,13 +685,34 @@ export const opencodeDriver = ({
610
685
  })();
611
686
  listed.set(key, { at: Date.now(), models });
612
687
  try {
613
- return await models;
688
+ const found = await models;
689
+ if (!found.length) listed.delete(key);
690
+ return found;
614
691
  } catch (error) {
615
692
  listed.delete(key);
616
693
  log.error(`harness ${harness}: OpenCode's models could not be listed`, error);
617
694
  return [];
618
695
  }
619
696
  },
697
+ // A throwaway server's commands and skills in `cwd` (`listsOf`, `commandsIn`); a prompt starting with `/<name>`
698
+ // runs one. A list that cannot be read is logged and the other's entries listed; neither read is an error.
699
+ async commands({ harness, config, cwd }) {
700
+ const server = await start(setupOf(harness, config), cwd, {});
701
+ try {
702
+ const lists = await listsOf(server.api, cwd, catalog);
703
+ const missing = (['command', 'skill'] as const).filter((kind) => !lists[kind].data);
704
+ for (const kind of missing)
705
+ log.error(
706
+ `harness ${harness}: OpenCode's ${kind} list could not be read`,
707
+ lists[kind].error,
708
+ );
709
+ if (missing.length === 2)
710
+ throw new Error('OpenCode listed neither its commands nor its skills');
711
+ return commandsIn(lists);
712
+ } finally {
713
+ void server.handle.kill();
714
+ }
715
+ },
620
716
  modes: async () =>
621
717
  MODES.map(({ id, name, description, current, full, readOnly, options }) => ({
622
718
  id,
@@ -1473,17 +1569,52 @@ export const opencodeDriver = ({
1473
1569
  delivered: new Set(),
1474
1570
  };
1475
1571
  turn = mine;
1476
- api
1477
- .post(`/api/session/${id}/prompt`, {
1478
- text,
1479
- // Images as files OpenCode reads itself (probe p-image: a `file://` URI).
1480
- ...(images.length && {
1572
+ // Images as files OpenCode reads itself (probe p-image: a `file://` URI).
1573
+ const files = images.length
1574
+ ? {
1481
1575
  files: images.map((image) => ({
1482
1576
  uri: pathToFileURL(resolve(cwd, image.path)).href,
1483
1577
  name: image.name,
1484
1578
  })),
1485
- }),
1486
- })
1579
+ }
1580
+ : {};
1581
+ // A leading `/<name> rest` naming one of the server's commands runs it (`/command`, its arguments the
1582
+ // rest); one naming a skill sends the rest with that skill attached. Anything else, a path (`/a/b`)
1583
+ // included, is the prompt's text as typed. The lists are read for `catalog.lookupMs` at most, until the
1584
+ // name shows in one of them.
1585
+ const slash = /^\/([^\s/]+)(?:\s+([\s\S]*))?$/.exec(text);
1586
+ const post = async () => {
1587
+ const find = (lists: Lists) =>
1588
+ commandsIn(lists).find((each) => each.name === slash?.[1]);
1589
+ const named = slash
1590
+ ? find(
1591
+ await listsOf(
1592
+ api,
1593
+ cwd,
1594
+ { everyMs: catalog.everyMs, forMs: catalog.lookupMs },
1595
+ (lists) => find(lists) !== undefined,
1596
+ ),
1597
+ )
1598
+ : undefined;
1599
+ // Stopped or closed while the lists were read: nothing goes out, a stop ends the turn interrupted.
1600
+ if (turn !== mine || closed) return;
1601
+ if (mine.stopping) return finish({ reason: 'interrupted' });
1602
+ const rest = slash?.[2] ?? '';
1603
+ if (named?.kind === 'command')
1604
+ return api.post(`/api/session/${id}/command`, {
1605
+ name: named.name,
1606
+ text: rest,
1607
+ ...files,
1608
+ });
1609
+ if (named?.kind === 'skill')
1610
+ return api.post(`/api/session/${id}/prompt`, {
1611
+ text: rest,
1612
+ skills: [{ id: named.name }],
1613
+ ...files,
1614
+ });
1615
+ return api.post(`/api/session/${id}/prompt`, { text, ...files });
1616
+ };
1617
+ post()
1487
1618
  .catch((error: unknown) => {
1488
1619
  if (turn === mine && !closed)
1489
1620
  finish({