@bakers-build/addon-opencode 0.0.0-stage → 0.1.0-next.42

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 keytec GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @bakers-build/addon-opencode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ bakers.build agent plugin for the OpenCode CLI.
4
+
5
+ Part of the bakers.build CLI. Install the meta package `@bakers-build/bakers` to get the `bakers` CLI with all addons. Source: https://git.key-tec.de/bakers-build/bakers-build (bakers-cli/).
@@ -0,0 +1,19 @@
1
+ import { type AgentFootprint } from '@bakers-build/conductor/contract';
2
+ /**
3
+ * Parse an opencode session bundle into an agent footprint (BB-221).
4
+ *
5
+ * opencode persists a session as separate JSON records: one `session`, N
6
+ * `message`s (an assistant message carries `tokens: { input, output, reasoning,
7
+ * cache: { read, write } }` and `providerID`/`modelID` — there is **no**
8
+ * pre-summed total), and per-message `part`s (`type: 'tool'` → a tool call,
9
+ * `type: 'text'` on a user message → prompt words). `getRunLog` bundles them as
10
+ * `{ session, messages, parts }`; this derives the footprint from that bundle.
11
+ *
12
+ * `tokens` sums every bucket incl. cache across assistant turns. `duration_s` is
13
+ * the run's wall-clock length: the span between the earliest and latest epoch-ms
14
+ * timestamp found across the session and message records (BB-151); fewer than
15
+ * two timestamps → 0. `model` is the last assistant turn's `providerID/modelID`.
16
+ * A parse error, a non-object, or a bundle with no `session` → an empty
17
+ * footprint. Malformed records are skipped — never throws.
18
+ */
19
+ export declare function parseOpencodeTranscript(serialised: string): AgentFootprint;
@@ -0,0 +1,120 @@
1
+ import { emptyAgentFootprint, } from '@bakers-build/conductor/contract';
2
+ function num(value) {
3
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
4
+ }
5
+ function countWords(text) {
6
+ const trimmed = text.trim();
7
+ return trimmed === '' ? 0 : trimmed.split(/\s+/).length;
8
+ }
9
+ function isObject(value) {
10
+ return typeof value === 'object' && value !== null;
11
+ }
12
+ /** Every token bucket of an assistant turn, incl. cache read/write (BB-220 parity). */
13
+ function messageTokens(tokens) {
14
+ if (!tokens) {
15
+ return 0;
16
+ }
17
+ return (num(tokens.input) +
18
+ num(tokens.output) +
19
+ num(tokens.reasoning) +
20
+ num(tokens.cache?.read) +
21
+ num(tokens.cache?.write));
22
+ }
23
+ /**
24
+ * Parse an opencode session bundle into an agent footprint (BB-221).
25
+ *
26
+ * opencode persists a session as separate JSON records: one `session`, N
27
+ * `message`s (an assistant message carries `tokens: { input, output, reasoning,
28
+ * cache: { read, write } }` and `providerID`/`modelID` — there is **no**
29
+ * pre-summed total), and per-message `part`s (`type: 'tool'` → a tool call,
30
+ * `type: 'text'` on a user message → prompt words). `getRunLog` bundles them as
31
+ * `{ session, messages, parts }`; this derives the footprint from that bundle.
32
+ *
33
+ * `tokens` sums every bucket incl. cache across assistant turns. `duration_s` is
34
+ * the run's wall-clock length: the span between the earliest and latest epoch-ms
35
+ * timestamp found across the session and message records (BB-151); fewer than
36
+ * two timestamps → 0. `model` is the last assistant turn's `providerID/modelID`.
37
+ * A parse error, a non-object, or a bundle with no `session` → an empty
38
+ * footprint. Malformed records are skipped — never throws.
39
+ */
40
+ export function parseOpencodeTranscript(serialised) {
41
+ const footprint = emptyAgentFootprint();
42
+ let bundle;
43
+ try {
44
+ const parsed = JSON.parse(serialised);
45
+ if (!isObject(parsed) || !isObject(parsed.session)) {
46
+ return footprint;
47
+ }
48
+ bundle = parsed;
49
+ }
50
+ catch {
51
+ return footprint;
52
+ }
53
+ const messages = Array.isArray(bundle.messages) ? bundle.messages : [];
54
+ const parts = Array.isArray(bundle.parts) ? bundle.parts : [];
55
+ let minTs = Number.POSITIVE_INFINITY;
56
+ let maxTs = Number.NEGATIVE_INFINITY;
57
+ const track = (value) => {
58
+ if (typeof value === 'number' && Number.isFinite(value)) {
59
+ if (value < minTs)
60
+ minTs = value;
61
+ if (value > maxTs)
62
+ maxTs = value;
63
+ }
64
+ };
65
+ track(bundle.session?.time?.created);
66
+ track(bundle.session?.time?.updated);
67
+ // messageID → role, so a text part's words are attributed to user turns only.
68
+ const roleOf = new Map();
69
+ let lastAssistant;
70
+ for (const raw of messages) {
71
+ if (!isObject(raw)) {
72
+ continue;
73
+ }
74
+ const message = raw;
75
+ if (typeof message.id === 'string' && typeof message.role === 'string') {
76
+ roleOf.set(message.id, message.role);
77
+ }
78
+ track(message.time?.created);
79
+ track(message.time?.completed);
80
+ if (message.role === 'assistant') {
81
+ footprint.agent_turns += 1;
82
+ footprint.tokens += messageTokens(message.tokens);
83
+ if (typeof message.providerID === 'string' &&
84
+ typeof message.modelID === 'string') {
85
+ const created = num(message.time?.created);
86
+ if (!lastAssistant || created >= lastAssistant.created) {
87
+ lastAssistant = {
88
+ created,
89
+ model: `${message.providerID}/${message.modelID}`,
90
+ };
91
+ }
92
+ }
93
+ }
94
+ else if (message.role === 'user') {
95
+ footprint.user_prompts += 1;
96
+ }
97
+ }
98
+ for (const raw of parts) {
99
+ if (!isObject(raw)) {
100
+ continue;
101
+ }
102
+ const part = raw;
103
+ if (part.type === 'tool') {
104
+ footprint.tool_calls += 1;
105
+ }
106
+ else if (part.type === 'text' &&
107
+ typeof part.text === 'string' &&
108
+ typeof part.messageID === 'string' &&
109
+ roleOf.get(part.messageID) === 'user') {
110
+ footprint.user_prompt_words += countWords(part.text);
111
+ }
112
+ }
113
+ if (Number.isFinite(minTs) && Number.isFinite(maxTs) && maxTs > minTs) {
114
+ footprint.duration_s = Math.floor((maxTs - minTs) / 1000);
115
+ }
116
+ if (lastAssistant) {
117
+ footprint.model = lastAssistant.model;
118
+ }
119
+ return footprint;
120
+ }
@@ -0,0 +1,35 @@
1
+ import { type AgentFootprint, type AgentPlugin, type AgentRunIdentity, type BbAgent } from '@bakers-build/conductor/contract';
2
+ export { parseOpencodeTranscript } from './footprint.js';
3
+ export interface OpencodeAgentOptions {
4
+ model?: string;
5
+ effort?: string;
6
+ args?: string[];
7
+ }
8
+ /**
9
+ * opencode's local storage root: `${XDG_DATA_HOME:-~/.local/share}/opencode/storage`
10
+ * (AC-1). Injected into `OpencodeAgent` so unit tests can point at a fixture tree.
11
+ */
12
+ export declare function defaultOpencodeStorageRoot(): string;
13
+ export declare class OpencodeAgent implements BbAgent {
14
+ private readonly storageRoot;
15
+ readonly id = "opencode";
16
+ readonly launchWarnings?: readonly string[];
17
+ private readonly args;
18
+ private readonly model;
19
+ private readonly overrides;
20
+ constructor(options?: OpencodeAgentOptions, storageRoot?: string);
21
+ launchCommand(prompt: string, _run?: AgentRunIdentity): string;
22
+ /**
23
+ * Resolve the run's opencode session deterministically and return its raw
24
+ * records serialised (BB-221). opencode has no `--session-dir`-style pin, so
25
+ * the session is discovered by matching `session.directory` against the run's
26
+ * worktree path (the worktree is per-run-unique) and picking the newest by
27
+ * `time.created`. Returns a `{ session, messages, parts }` JSON bundle, or `''`
28
+ * when no session matches. Every fs/JSON step is guarded — never throws.
29
+ */
30
+ getRunLog(worktreePath: string, run?: AgentRunIdentity): Promise<string>;
31
+ parseFootprint(log: string): AgentFootprint;
32
+ }
33
+ /** Config-facing factory: `opencodeAgent({ model: 'provider/model' })`. */
34
+ export declare function opencodeAgent(options?: OpencodeAgentOptions): AgentPlugin;
35
+ export default opencodeAgent;
@@ -0,0 +1,162 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { resolveAgentCliOptions, } from '@bakers-build/conductor/contract';
5
+ import { shellQuote } from '@bakers-build/core';
6
+ import { parseOpencodeTranscript } from './footprint.js';
7
+ export { parseOpencodeTranscript } from './footprint.js';
8
+ const OPENCODE_RESERVED = ['--prompt', '--auto'];
9
+ const OPENCODE_KNOWN = [
10
+ { kind: 'model', flags: ['--model', '-m'] },
11
+ ];
12
+ /**
13
+ * opencode's local storage root: `${XDG_DATA_HOME:-~/.local/share}/opencode/storage`
14
+ * (AC-1). Injected into `OpencodeAgent` so unit tests can point at a fixture tree.
15
+ */
16
+ export function defaultOpencodeStorageRoot() {
17
+ const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
18
+ return join(dataHome, 'opencode', 'storage');
19
+ }
20
+ function isObject(value) {
21
+ return typeof value === 'object' && value !== null;
22
+ }
23
+ /** Read + JSON.parse a file, swallowing every error → `null`. */
24
+ async function readJson(path) {
25
+ try {
26
+ return JSON.parse(await readFile(path, 'utf8'));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /** Entries of `dir` starting with `prefix` and ending `.json`, or `[]`. */
33
+ async function listJson(dir, prefix) {
34
+ try {
35
+ return (await readdir(dir)).filter((name) => name.startsWith(prefix) && name.endsWith('.json'));
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ }
41
+ export class OpencodeAgent {
42
+ storageRoot;
43
+ id = 'opencode';
44
+ launchWarnings;
45
+ args;
46
+ model;
47
+ overrides;
48
+ constructor(options = {}, storageRoot = defaultOpencodeStorageRoot()) {
49
+ this.storageRoot = storageRoot;
50
+ const cli = resolveAgentCliOptions(options, OPENCODE_RESERVED, OPENCODE_KNOWN);
51
+ this.args = cli.args;
52
+ this.model = cli.model;
53
+ this.overrides = cli.overrides;
54
+ if (cli.effort !== undefined) {
55
+ this.launchWarnings = ['effort is unsupported and ignored'];
56
+ }
57
+ }
58
+ launchCommand(prompt, _run) {
59
+ if (prompt === '') {
60
+ return 'opencode';
61
+ }
62
+ // Interactive TUI with the initial prompt — mirrors the claude plugin
63
+ // (`claude '<prompt>' … --dangerously-skip-permissions`). `opencode run`
64
+ // would be the non-interactive print mode, which leaves the herdr pane
65
+ // without an attachable session.
66
+ const parts = ['opencode', '--prompt', shellQuote(prompt)];
67
+ if (this.model !== undefined && !this.overrides.model) {
68
+ parts.push('--model', shellQuote(this.model));
69
+ }
70
+ parts.push('--auto');
71
+ parts.push(...this.args.map(shellQuote));
72
+ return parts.join(' ');
73
+ }
74
+ /**
75
+ * Resolve the run's opencode session deterministically and return its raw
76
+ * records serialised (BB-221). opencode has no `--session-dir`-style pin, so
77
+ * the session is discovered by matching `session.directory` against the run's
78
+ * worktree path (the worktree is per-run-unique) and picking the newest by
79
+ * `time.created`. Returns a `{ session, messages, parts }` JSON bundle, or `''`
80
+ * when no session matches. Every fs/JSON step is guarded — never throws.
81
+ */
82
+ async getRunLog(worktreePath, run) {
83
+ const sessionRoot = join(this.storageRoot, 'session');
84
+ let projectDirs;
85
+ try {
86
+ projectDirs = await readdir(sessionRoot);
87
+ }
88
+ catch {
89
+ return '';
90
+ }
91
+ // opencode has no session-id pin (BB-473): the lower bound below is the
92
+ // only available defence, so a session from a PRIOR run left in the same
93
+ // (reused) worktree can never be selected for THIS run even when it is
94
+ // the only/newest directory-matching session around.
95
+ const startedAtMs = run?.startedAt !== undefined ? new Date(run.startedAt).getTime() : null;
96
+ let newest = null;
97
+ for (const projectDir of projectDirs) {
98
+ const dir = join(sessionRoot, projectDir);
99
+ for (const name of await listJson(dir, 'ses_')) {
100
+ const record = await readJson(join(dir, name));
101
+ if (!isObject(record) || record.directory !== worktreePath) {
102
+ continue;
103
+ }
104
+ const time = isObject(record.time) ? record.time : undefined;
105
+ const created = typeof time?.created === 'number'
106
+ ? time.created
107
+ : Number.NEGATIVE_INFINITY;
108
+ if (startedAtMs !== null &&
109
+ Number.isFinite(startedAtMs) &&
110
+ created < startedAtMs) {
111
+ continue;
112
+ }
113
+ if (!newest || created > newest.created) {
114
+ newest = { session: record, created };
115
+ }
116
+ }
117
+ }
118
+ if (!newest) {
119
+ return '';
120
+ }
121
+ const sessionId = newest.session.id;
122
+ const messages = [];
123
+ const parts = [];
124
+ if (typeof sessionId === 'string') {
125
+ const messageDir = join(this.storageRoot, 'message', sessionId);
126
+ for (const name of await listJson(messageDir, 'msg_')) {
127
+ const message = await readJson(join(messageDir, name));
128
+ if (message === null) {
129
+ continue;
130
+ }
131
+ messages.push(message);
132
+ const messageId = isObject(message) ? message.id : undefined;
133
+ if (typeof messageId === 'string') {
134
+ const partDir = join(this.storageRoot, 'part', messageId);
135
+ for (const partName of await listJson(partDir, 'prt_')) {
136
+ const part = await readJson(join(partDir, partName));
137
+ if (part !== null) {
138
+ parts.push(part);
139
+ }
140
+ }
141
+ }
142
+ }
143
+ }
144
+ return JSON.stringify({ session: newest.session, messages, parts });
145
+ }
146
+ parseFootprint(log) {
147
+ return parseOpencodeTranscript(log);
148
+ }
149
+ }
150
+ /** Config-facing factory: `opencodeAgent({ model: 'provider/model' })`. */
151
+ export function opencodeAgent(options = {}) {
152
+ const agent = new OpencodeAgent(options);
153
+ return {
154
+ kind: 'agent',
155
+ id: 'opencode',
156
+ requiredModules: [],
157
+ async createAgent() {
158
+ return agent;
159
+ },
160
+ };
161
+ }
162
+ export default opencodeAgent;
@@ -0,0 +1,4 @@
1
+ import type { Preset } from '@bakers-build/conductor/contract';
2
+ import { type OpencodeAgentOptions } from './index.js';
3
+ export declare const agents: Preset<Partial<OpencodeAgentOptions> | undefined>['agents'];
4
+ export declare const scopes: Preset['scopes'];
@@ -0,0 +1,15 @@
1
+ import opencodeAgent from './index.js';
2
+ export const agents = (acc, opts) => {
3
+ const model = opts?.model;
4
+ return [
5
+ ...acc,
6
+ {
7
+ alias: 'opencode',
8
+ description: 'General coding with the locally configured Opencode model.',
9
+ ...(model !== undefined ? { model } : {}),
10
+ agent: opencodeAgent(opts),
11
+ },
12
+ ];
13
+ };
14
+ // Agents are per machine: list this addon in ~/.bakers/machine.config.js addons[].
15
+ export const scopes = ['machine'];
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-opencode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-next.42",
4
+ "description": "bakers.build agent plugin for the OpenCode CLI.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./dist/src/index.js",
9
+ "./preset": "./dist/src/preset.js"
10
+ },
11
+ "files": [
12
+ "dist/src"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://git.key-tec.de/bakers-build/bakers-build.git",
20
+ "directory": "bakers-cli/addons/opencode"
21
+ },
22
+ "peerDependencies": {
23
+ "@bakers-build/conductor": "^0.1.0-next.42",
24
+ "@bakers-build/core": "^0.1.0-next.42"
25
+ }
26
+ }