@gaia-ai/addon-opencode 0.6.2 → 0.6.4

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.
@@ -0,0 +1,19 @@
1
+ import { type AgentFootprint } from '@gaia-ai/conductor/contract';
2
+ /**
3
+ * Parse an opencode session bundle into an agent footprint (GAIA-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 (GAIA-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 '@gaia-ai/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 (GAIA-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 (GAIA-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 (GAIA-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
+ }
@@ -1,14 +1,29 @@
1
- import { type AgentFootprint, type AgentPlugin, type GaiaAgent } from '@gaia-ai/conductor/contract';
1
+ import type { AgentFootprint, AgentPlugin, GaiaAgent } from '@gaia-ai/conductor/contract';
2
+ export { parseOpencodeTranscript } from './footprint.js';
2
3
  export interface OpencodeAgentOptions {
3
4
  model?: string;
4
5
  }
6
+ /**
7
+ * opencode's local storage root: `${XDG_DATA_HOME:-~/.local/share}/opencode/storage`
8
+ * (AC-1). Injected into `OpencodeAgent` so unit tests can point at a fixture tree.
9
+ */
10
+ export declare function defaultOpencodeStorageRoot(): string;
5
11
  export declare class OpencodeAgent implements GaiaAgent {
6
12
  private readonly options;
13
+ private readonly storageRoot;
7
14
  readonly id = "opencode";
8
- constructor(options: OpencodeAgentOptions);
15
+ constructor(options: OpencodeAgentOptions, storageRoot?: string);
9
16
  launchCommand(prompt: string): string;
10
- getRunLog(): Promise<string>;
11
- parseFootprint(_log: string): AgentFootprint;
17
+ /**
18
+ * Resolve the run's opencode session deterministically and return its raw
19
+ * records serialised (GAIA-221). opencode has no `--session-dir`-style pin, so
20
+ * the session is discovered by matching `session.directory` against the run's
21
+ * worktree path (the worktree is per-run-unique) and picking the newest by
22
+ * `time.created`. Returns a `{ session, messages, parts }` JSON bundle, or `''`
23
+ * when no session matches. Every fs/JSON step is guarded — never throws.
24
+ */
25
+ getRunLog(worktreePath: string): Promise<string>;
26
+ parseFootprint(log: string): AgentFootprint;
12
27
  }
13
28
  /** Config-facing factory: `opencodeAgent({ model: 'provider/model' })`. */
14
29
  export declare function opencodeAgent(options?: OpencodeAgentOptions): AgentPlugin;
package/dist/src/index.js CHANGED
@@ -1,10 +1,45 @@
1
- import { emptyAgentFootprint, } from '@gaia-ai/conductor/contract';
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
2
4
  import { shellQuote } from '@gaia-ai/core';
5
+ import { parseOpencodeTranscript } from './footprint.js';
6
+ export { parseOpencodeTranscript } from './footprint.js';
7
+ /**
8
+ * opencode's local storage root: `${XDG_DATA_HOME:-~/.local/share}/opencode/storage`
9
+ * (AC-1). Injected into `OpencodeAgent` so unit tests can point at a fixture tree.
10
+ */
11
+ export function defaultOpencodeStorageRoot() {
12
+ const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
13
+ return join(dataHome, 'opencode', 'storage');
14
+ }
15
+ function isObject(value) {
16
+ return typeof value === 'object' && value !== null;
17
+ }
18
+ /** Read + JSON.parse a file, swallowing every error → `null`. */
19
+ async function readJson(path) {
20
+ try {
21
+ return JSON.parse(await readFile(path, 'utf8'));
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ /** Entries of `dir` starting with `prefix` and ending `.json`, or `[]`. */
28
+ async function listJson(dir, prefix) {
29
+ try {
30
+ return (await readdir(dir)).filter((name) => name.startsWith(prefix) && name.endsWith('.json'));
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ }
3
36
  export class OpencodeAgent {
4
37
  options;
38
+ storageRoot;
5
39
  id = 'opencode';
6
- constructor(options) {
40
+ constructor(options, storageRoot = defaultOpencodeStorageRoot()) {
7
41
  this.options = options;
42
+ this.storageRoot = storageRoot;
8
43
  }
9
44
  launchCommand(prompt) {
10
45
  if (prompt === '') {
@@ -21,11 +56,70 @@ export class OpencodeAgent {
21
56
  parts.push('--auto');
22
57
  return parts.join(' ');
23
58
  }
24
- async getRunLog() {
25
- return '';
59
+ /**
60
+ * Resolve the run's opencode session deterministically and return its raw
61
+ * records serialised (GAIA-221). opencode has no `--session-dir`-style pin, so
62
+ * the session is discovered by matching `session.directory` against the run's
63
+ * worktree path (the worktree is per-run-unique) and picking the newest by
64
+ * `time.created`. Returns a `{ session, messages, parts }` JSON bundle, or `''`
65
+ * when no session matches. Every fs/JSON step is guarded — never throws.
66
+ */
67
+ async getRunLog(worktreePath) {
68
+ const sessionRoot = join(this.storageRoot, 'session');
69
+ let projectDirs;
70
+ try {
71
+ projectDirs = await readdir(sessionRoot);
72
+ }
73
+ catch {
74
+ return '';
75
+ }
76
+ let newest = null;
77
+ for (const projectDir of projectDirs) {
78
+ const dir = join(sessionRoot, projectDir);
79
+ for (const name of await listJson(dir, 'ses_')) {
80
+ const record = await readJson(join(dir, name));
81
+ if (!isObject(record) || record.directory !== worktreePath) {
82
+ continue;
83
+ }
84
+ const time = isObject(record.time) ? record.time : undefined;
85
+ const created = typeof time?.created === 'number'
86
+ ? time.created
87
+ : Number.NEGATIVE_INFINITY;
88
+ if (!newest || created > newest.created) {
89
+ newest = { session: record, created };
90
+ }
91
+ }
92
+ }
93
+ if (!newest) {
94
+ return '';
95
+ }
96
+ const sessionId = newest.session.id;
97
+ const messages = [];
98
+ const parts = [];
99
+ if (typeof sessionId === 'string') {
100
+ const messageDir = join(this.storageRoot, 'message', sessionId);
101
+ for (const name of await listJson(messageDir, 'msg_')) {
102
+ const message = await readJson(join(messageDir, name));
103
+ if (message === null) {
104
+ continue;
105
+ }
106
+ messages.push(message);
107
+ const messageId = isObject(message) ? message.id : undefined;
108
+ if (typeof messageId === 'string') {
109
+ const partDir = join(this.storageRoot, 'part', messageId);
110
+ for (const partName of await listJson(partDir, 'prt_')) {
111
+ const part = await readJson(join(partDir, partName));
112
+ if (part !== null) {
113
+ parts.push(part);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
119
+ return JSON.stringify({ session: newest.session, messages, parts });
26
120
  }
27
- parseFootprint(_log) {
28
- return emptyAgentFootprint();
121
+ parseFootprint(log) {
122
+ return parseOpencodeTranscript(log);
29
123
  }
30
124
  }
31
125
  /** Config-facing factory: `opencodeAgent({ model: 'provider/model' })`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaia-ai/addon-opencode",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "GAIA agent plugin for the OpenCode CLI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,7 +20,7 @@
20
20
  "directory": "gaia-cli/addons/opencode"
21
21
  },
22
22
  "peerDependencies": {
23
- "@gaia-ai/conductor": "^0.6.2",
24
- "@gaia-ai/core": "^0.6.2"
23
+ "@gaia-ai/conductor": "^0.6.4",
24
+ "@gaia-ai/core": "^0.6.4"
25
25
  }
26
26
  }