@bridgebrew/harness-opencode 0.0.8 → 0.0.13

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 -6
  3. package/server.ts +185 -23
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.8",
3
+ "version": "0.0.13",
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,10 +56,10 @@
52
56
  }
53
57
  }
54
58
  },
55
- "provenance": "official",
56
- "placement": "both"
59
+ "provenance": "official"
57
60
  },
58
61
  "peerDependencies": {
62
+ "@bridge/kernel": ">=0.0.1",
59
63
  "cordis": "4.0.0-rc.11"
60
64
  },
61
65
  "releaseStage": "dev",
@@ -64,6 +68,6 @@
64
68
  "typecheck": "bridge plugin check ."
65
69
  },
66
70
  "engines": {
67
- "bridge": ">=0.0.1-nightly.20261119.1"
71
+ "bridge": ">=0.0.1-nightly.20261123.1"
68
72
  }
69
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,15 +30,15 @@
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
40
  import { stripVTControlCharacters } from 'node:util';
41
+ import { tailText } from '@bridge/kernel/text';
41
42
  import { isRecord, listOf } from './json.ts';
42
43
  import type { Context } from 'cordis';
43
44
  import { ApiError, connect, located, type Api, type Event, type Fetch } from './api.ts';
@@ -271,8 +272,9 @@ const exitedWithin = async (exited: Promise<unknown>, ms: number) => {
271
272
  const STATUS_MS = 15_000;
272
273
  /** How long a model list is kept, per entry setup. */
273
274
  const MODELS_TTL_MS = 5 * 60_000;
274
- /** A server started a moment ago lists no models yet: read again this often, this long. */
275
- const CATALOG_RETRY = { everyMs: 250, forMs: 5_000 };
275
+ /** A server started a moment ago lists no models yet: read again this often, this long; a prompt's `/<name>` is
276
+ * looked up for `lookupMs` at most (`listsOf`). */
277
+ const CATALOG_RETRY = { everyMs: 250, forMs: 5_000, lookupMs: 2_000 };
276
278
  /** The longest `setTimeout` delay (2^31 - 1 ms); a longer one fires at once. */
277
279
  const TIMEOUT_MAX = 2_147_483_647;
278
280
  /** What a declined ask tells the model (it reads it as `permission.rejected`). */
@@ -318,6 +320,80 @@ const str = (value: unknown) => (typeof value === 'string' && value !== '' ? val
318
320
  const recordOf = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {});
319
321
  /** An HTTP answer's `data` (its payload) as an object, or an empty one. */
320
322
  const dataOf = (answer: unknown) => recordOf(recordOf(answer).data);
323
+
324
+ type Command = NonNullable<Awaited<ReturnType<NonNullable<Driver['commands']>>>>[number];
325
+
326
+ /** OpenCode's two lists of what a `/<name>` runs, by kind, each as last read: its entries, or why it gave none. */
327
+ type Lists = Record<Command['kind'], { data?: unknown[]; error?: unknown }>;
328
+
329
+ /** OpenCode's commands (`GET /api/command`) and skills (`GET /api/skill`) in `directory`, each list read every `everyMs`
330
+ * until it reads the same twice or its read fails (503, warming up, is read again), `enough` says what was read
331
+ * suffices, or `forMs` passed, a stuck request included. OpenCode 2.0.29 loads a folder's lists on its first request
332
+ * there: a read then is empty or partial, the rest follow within ~250 ms (probe of 20 November 2026). ponytail: "the
333
+ * same twice" can stop on a list still loading slowly; the next read has it. */
334
+ const listsOf = (
335
+ api: Api,
336
+ directory: string,
337
+ { everyMs, forMs }: { everyMs: number; forMs: number },
338
+ enough: (lists: Lists) => boolean = () => false,
339
+ ) =>
340
+ new Promise<Lists>((done) => {
341
+ const lists: Lists = { command: {}, skill: {} };
342
+ const settled = new Set<Command['kind']>();
343
+ let over = false;
344
+ const end = () => {
345
+ if (over) return;
346
+ over = true;
347
+ clearTimeout(timer);
348
+ done(lists);
349
+ };
350
+ const timer = setTimeout(end, forMs);
351
+ const watch = async (kind: Command['kind']) => {
352
+ let was: string | undefined;
353
+ while (!over) {
354
+ const read: Lists[Command['kind']] = await api
355
+ .get(`/api/${kind}?${located(directory)}`)
356
+ .then(
357
+ (answer) => ({ data: isRecord(answer) ? listOf(answer.data) : [] }),
358
+ (error: unknown) => ({ error }),
359
+ );
360
+ if (over) return;
361
+ lists[kind] = read;
362
+ if (enough(lists)) return end();
363
+ const now = read.data && JSON.stringify(read.data);
364
+ const warming = read.error instanceof ApiError && read.error.status === 503;
365
+ if (!warming && (read.error !== undefined || now === was)) {
366
+ settled.add(kind);
367
+ if (settled.size === 2) end();
368
+ return;
369
+ }
370
+ was = now;
371
+ await new Promise((resolve) => setTimeout(resolve, everyMs));
372
+ }
373
+ };
374
+ void watch('command');
375
+ void watch('skill');
376
+ });
377
+
378
+ /** The commands then the skills (named by their `id`) of `lists`, each name once, a command before a skill of the
379
+ * same name. */
380
+ const commandsIn = (lists: Lists) => {
381
+ const seen = new Set<string>();
382
+ const listed = (kind: Command['kind'], name: unknown, description: unknown): Command[] => {
383
+ const named = str(name);
384
+ if (!named || seen.has(named)) return [];
385
+ seen.add(named);
386
+ return [{ name: named, description: str(description) ?? '', kind }];
387
+ };
388
+ return [
389
+ ...(lists.command.data ?? []).flatMap((each) =>
390
+ isRecord(each) ? listed('command', each.name, each.description) : [],
391
+ ),
392
+ ...(lists.skill.data ?? []).flatMap((each) =>
393
+ isRecord(each) ? listed('skill', each.id, each.description) : [],
394
+ ),
395
+ ];
396
+ };
321
397
  const pathIn = (input: unknown) => {
322
398
  const given = recordOf(input);
323
399
  return str(given.filePath) ?? str(given.path) ?? str(given.file);
@@ -432,7 +508,7 @@ const tailOf = (stderr: string) => {
432
508
  * `TypeError [ERR_…]: …`, `error: …`), else the last line that is neither a stack frame nor Node's `Node.js v…` line,
433
509
  * else its last line. Node prints its version after the error, which alone tells nothing. */
434
510
  const failureOf = (stderr: string) => {
435
- const lines = stderr
511
+ const lines = stripVTControlCharacters(stderr)
436
512
  .trim()
437
513
  .split('\n')
438
514
  .map((line) => line.trim());
@@ -478,7 +554,7 @@ export const opencodeDriver = ({
478
554
  fetch?: Fetch;
479
555
  disposing?: () => boolean;
480
556
  deadlines?: { requestMs: number; startMs: number; stopMs: number };
481
- catalog?: { everyMs: number; forMs: number };
557
+ catalog?: { everyMs: number; forMs: number; lookupMs: number };
482
558
  log?: { error: (...args: unknown[]) => void };
483
559
  }): Driver => {
484
560
  /** Configs whose `decisionTimeoutMs` was refused, said once each. */
@@ -506,7 +582,7 @@ export const opencodeDriver = ({
506
582
  });
507
583
  handle.onOutput((stream, chunk) => {
508
584
  if (stream === 'stderr') {
509
- stderr = (stderr + chunk).slice(-4096);
585
+ stderr = tailText(stderr + chunk, 4096);
510
586
  return;
511
587
  }
512
588
  if (!first) return;
@@ -619,6 +695,25 @@ export const opencodeDriver = ({
619
695
  return [];
620
696
  }
621
697
  },
698
+ // A throwaway server's commands and skills in `cwd` (`listsOf`, `commandsIn`); a prompt starting with `/<name>`
699
+ // runs one. A list that cannot be read is logged and the other's entries listed; neither read is an error.
700
+ async commands({ harness, config, cwd }) {
701
+ const server = await start(setupOf(harness, config), cwd, {});
702
+ try {
703
+ const lists = await listsOf(server.api, cwd, catalog);
704
+ const missing = (['command', 'skill'] as const).filter((kind) => !lists[kind].data);
705
+ for (const kind of missing)
706
+ log.error(
707
+ `harness ${harness}: OpenCode's ${kind} list could not be read`,
708
+ lists[kind].error,
709
+ );
710
+ if (missing.length === 2)
711
+ throw new Error('OpenCode listed neither its commands nor its skills');
712
+ return commandsIn(lists);
713
+ } finally {
714
+ void server.handle.kill();
715
+ }
716
+ },
622
717
  modes: async () =>
623
718
  MODES.map(({ id, name, description, current, full, readOnly, options }) => ({
624
719
  id,
@@ -727,6 +822,8 @@ export const opencodeDriver = ({
727
822
  delivered: Set<string>;
728
823
  /** The execution ended while a steered message waited: the turn ends with the execution that takes it. */
729
824
  idle?: TurnEnd;
825
+ /** An execution started during it. */
826
+ executed?: true;
730
827
  }
731
828
  | undefined;
732
829
  let stopTimer: ReturnType<typeof setTimeout> | undefined;
@@ -1296,6 +1393,7 @@ export const opencodeDriver = ({
1296
1393
  }
1297
1394
  case 'session.execution.started':
1298
1395
  turn.idle = undefined;
1396
+ turn.executed = true;
1299
1397
  return;
1300
1398
  case 'session.execution.succeeded':
1301
1399
  if (turn.stopping) return finish({ reason: 'interrupted' });
@@ -1475,24 +1573,88 @@ export const opencodeDriver = ({
1475
1573
  delivered: new Set(),
1476
1574
  };
1477
1575
  turn = mine;
1478
- api
1479
- .post(`/api/session/${id}/prompt`, {
1480
- text,
1481
- // Images as files OpenCode reads itself (probe p-image: a `file://` URI).
1482
- ...(images.length && {
1576
+ // Images as files OpenCode reads itself (probe p-image: a `file://` URI).
1577
+ const files = images.length
1578
+ ? {
1483
1579
  files: images.map((image) => ({
1484
1580
  uri: pathToFileURL(resolve(cwd, image.path)).href,
1485
1581
  name: image.name,
1486
1582
  })),
1487
- }),
1488
- })
1489
- .catch((error: unknown) => {
1490
- if (turn === mine && !closed)
1491
- finish({
1492
- reason: 'failed',
1493
- message: `OpenCode refused the turn: ${error instanceof Error ? error.message : String(error)}`,
1494
- });
1495
- });
1583
+ }
1584
+ : {};
1585
+ // A leading `/<name> rest` naming one of the server's commands runs it (`/command`, its arguments the
1586
+ // rest); one naming a skill sends the rest with that skill attached. Anything else, a path (`/a/b`)
1587
+ // included, is the prompt's text as typed. The lists are read for `catalog.lookupMs` at most, until the
1588
+ // name shows in one of them.
1589
+ const slash = /^\/([^\s/]+)(?:\s+([\s\S]*))?$/.exec(text);
1590
+ const post = async () => {
1591
+ const find = (lists: Lists) =>
1592
+ commandsIn(lists).find((each) => each.name === slash?.[1]);
1593
+ const named = slash
1594
+ ? find(
1595
+ await listsOf(
1596
+ api,
1597
+ cwd,
1598
+ { everyMs: catalog.everyMs, forMs: catalog.lookupMs },
1599
+ (lists) => find(lists) !== undefined,
1600
+ ),
1601
+ )
1602
+ : undefined;
1603
+ // Stopped or closed while the lists were read: nothing goes out, a stop ends the turn interrupted.
1604
+ if (turn !== mine || closed) return;
1605
+ if (mine.stopping) return finish({ reason: 'interrupted' });
1606
+ const rest = slash?.[2] ?? '';
1607
+ if (named?.kind === 'command') {
1608
+ await api.post(`/api/session/${id}/command`, {
1609
+ name: named.name,
1610
+ text: rest,
1611
+ ...files,
1612
+ });
1613
+ // OpenCode answers once the command's callback returned; one that called no model started no
1614
+ // execution, so no end event comes: the turn ends once OpenCode says the session is not active. The
1615
+ // read is tried again (`catalog.everyMs`) for `requestMs` at most.
1616
+ const deadline = Date.now() + requestMs;
1617
+ for (;;) {
1618
+ if (turn !== mine || closed || mine.executed) return;
1619
+ const active = await api
1620
+ .get('/api/session/active')
1621
+ .catch((error: unknown) => error);
1622
+ if (isRecord(active) && isRecord(active.data)) {
1623
+ if (id in active.data) return; // running: its end event ends the turn
1624
+ break;
1625
+ }
1626
+ if (Date.now() >= deadline)
1627
+ return finish({
1628
+ reason: 'failed',
1629
+ message: `OpenCode did not say whether /${named.name} ran: ${active instanceof Error ? active.message : 'no session list'}`,
1630
+ });
1631
+ await new Promise((resolve) => setTimeout(resolve, catalog.everyMs));
1632
+ }
1633
+ // An execution that ran and ended before that read still has its events on the way: they end the turn
1634
+ // first, with its own outcome. ponytail: a fixed wait (`catalog.everyMs`), not a sync with the stream.
1635
+ await new Promise((resolve) => setTimeout(resolve, catalog.everyMs));
1636
+ if (turn !== mine || closed || mine.executed) return;
1637
+ // As an execution that ended: a steered message still posting or waiting ends it later (`steer`), or
1638
+ // starts an execution, which clears it.
1639
+ mine.idle = mine.stopping ? { reason: 'interrupted' } : { reason: 'completed' };
1640
+ if (!mine.steering.size && !mine.posting) finish(mine.idle);
1641
+ return;
1642
+ }
1643
+ if (named?.kind === 'skill')
1644
+ return api.post(`/api/session/${id}/prompt`, {
1645
+ text: rest,
1646
+ skills: [{ id: named.name }],
1647
+ ...files,
1648
+ });
1649
+ return api.post(`/api/session/${id}/prompt`, { text, ...files });
1650
+ };
1651
+ post().catch((error: unknown) => {
1652
+ if (turn === mine && !closed)
1653
+ finish({
1654
+ reason: 'failed',
1655
+ message: `OpenCode refused the turn: ${error instanceof Error ? error.message : String(error)}`,
1656
+ });
1657
+ });
1496
1658
  });
1497
1659
  },
1498
1660
  async steer(text, images = []) {