@gaia-ai/addon-pi 0.6.1

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 ADDED
@@ -0,0 +1,5 @@
1
+ # @gaia-ai/addon-pi
2
+
3
+ GAIA agent plugin for the pi coding CLI, with a real transcript footprint.
4
+
5
+ Part of the GAIA CLI. Install the meta package `@gaia-ai/gaia` to get the `gaia` CLI with all addons. Source: https://git.key-tec.de/keytec/gaia (gaia-cli/).
@@ -0,0 +1,19 @@
1
+ import { type AgentFootprint } from '@gaia-ai/conductor/contract';
2
+ /**
3
+ * Parse a pi JSONL transcript into an agent footprint (GAIA-132).
4
+ *
5
+ * pi's transcript is one JSON object per line. `message` entries carry
6
+ * `message.role`, and pi uses THREE roles: `user` (a genuine prompt),
7
+ * `assistant` (an agent turn, with a per-turn `message.usage.totalTokens` and a
8
+ * `content[]` array whose `toolCall` parts are the tool invocations), and a
9
+ * distinct `toolResult` role for tool output. Tool results are cleanly
10
+ * separable from prompts by role — no string-vs-array heuristic (unlike
11
+ * claude). Blank or malformed lines are skipped — never throws.
12
+ *
13
+ * `duration_s` is the run's wall-clock length: the span between the first and
14
+ * last entry that carries a parseable top-level `timestamp` (GAIA-151); fewer
15
+ * than two timestamps → 0. `tokens` uses pi's own per-turn `totalTokens`, so no
16
+ * usage-bucket sum is needed. `model` is the last assistant turn's
17
+ * `provider/model`, falling back to the last `model_change`'s `provider/modelId`.
18
+ */
19
+ export declare function parsePiTranscript(jsonl: string): AgentFootprint;
@@ -0,0 +1,113 @@
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
+ /** Words across the `text` parts of a pi `message.content[]` array. */
10
+ function promptWords(content) {
11
+ if (!Array.isArray(content)) {
12
+ return 0;
13
+ }
14
+ let words = 0;
15
+ for (const part of content) {
16
+ if (part &&
17
+ typeof part === 'object' &&
18
+ part.type === 'text' &&
19
+ typeof part.text === 'string') {
20
+ words += countWords(part.text);
21
+ }
22
+ }
23
+ return words;
24
+ }
25
+ /**
26
+ * Parse a pi JSONL transcript into an agent footprint (GAIA-132).
27
+ *
28
+ * pi's transcript is one JSON object per line. `message` entries carry
29
+ * `message.role`, and pi uses THREE roles: `user` (a genuine prompt),
30
+ * `assistant` (an agent turn, with a per-turn `message.usage.totalTokens` and a
31
+ * `content[]` array whose `toolCall` parts are the tool invocations), and a
32
+ * distinct `toolResult` role for tool output. Tool results are cleanly
33
+ * separable from prompts by role — no string-vs-array heuristic (unlike
34
+ * claude). Blank or malformed lines are skipped — never throws.
35
+ *
36
+ * `duration_s` is the run's wall-clock length: the span between the first and
37
+ * last entry that carries a parseable top-level `timestamp` (GAIA-151); fewer
38
+ * than two timestamps → 0. `tokens` uses pi's own per-turn `totalTokens`, so no
39
+ * usage-bucket sum is needed. `model` is the last assistant turn's
40
+ * `provider/model`, falling back to the last `model_change`'s `provider/modelId`.
41
+ */
42
+ export function parsePiTranscript(jsonl) {
43
+ const footprint = emptyAgentFootprint();
44
+ let minTs = Number.POSITIVE_INFINITY;
45
+ let maxTs = Number.NEGATIVE_INFINITY;
46
+ let lastModelChange;
47
+ for (const raw of jsonl.split('\n')) {
48
+ const trimmed = raw.trim();
49
+ if (trimmed === '') {
50
+ continue;
51
+ }
52
+ let entry;
53
+ try {
54
+ entry = JSON.parse(trimmed);
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ // Track the run span across ANY timestamped entry (session, message, …).
60
+ if (typeof entry.timestamp === 'string') {
61
+ const ts = Date.parse(entry.timestamp);
62
+ if (Number.isFinite(ts)) {
63
+ if (ts < minTs)
64
+ minTs = ts;
65
+ if (ts > maxTs)
66
+ maxTs = ts;
67
+ }
68
+ }
69
+ if (entry.type === 'model_change' &&
70
+ typeof entry.provider === 'string' &&
71
+ typeof entry.modelId === 'string') {
72
+ lastModelChange = `${entry.provider}/${entry.modelId}`;
73
+ continue;
74
+ }
75
+ if (entry.type !== 'message') {
76
+ continue;
77
+ }
78
+ const message = entry.message;
79
+ if (!message || typeof message !== 'object') {
80
+ continue;
81
+ }
82
+ if (message.role === 'assistant') {
83
+ footprint.agent_turns += 1;
84
+ footprint.tokens += num(message.usage?.totalTokens);
85
+ if (Array.isArray(message.content)) {
86
+ for (const part of message.content) {
87
+ if (part &&
88
+ typeof part === 'object' &&
89
+ part.type === 'toolCall') {
90
+ footprint.tool_calls += 1;
91
+ }
92
+ }
93
+ }
94
+ if (typeof message.provider === 'string' &&
95
+ typeof message.model === 'string') {
96
+ footprint.model = `${message.provider}/${message.model}`;
97
+ }
98
+ }
99
+ else if (message.role === 'user') {
100
+ footprint.user_prompts += 1;
101
+ footprint.user_prompt_words += promptWords(message.content);
102
+ }
103
+ // `toolResult` messages are tool output — neither a prompt nor a turn.
104
+ }
105
+ if (Number.isFinite(minTs) && Number.isFinite(maxTs) && maxTs > minTs) {
106
+ footprint.duration_s = Math.floor((maxTs - minTs) / 1000);
107
+ }
108
+ // Prefer the last assistant turn's model; fall back to the last model_change.
109
+ if (footprint.model === undefined && lastModelChange !== undefined) {
110
+ footprint.model = lastModelChange;
111
+ }
112
+ return footprint;
113
+ }
@@ -0,0 +1,43 @@
1
+ import type { AgentFootprint, AgentPlugin, GaiaAgent } from '@gaia-ai/conductor/contract';
2
+ export { parsePiTranscript } from './footprint.js';
3
+ /**
4
+ * The relative `--session-dir` pin — the single source of truth shared by
5
+ * `launchCommand` (which pins pi's transcript there at launch) and `getRunLog`
6
+ * (which reads it back). Relative → resolves against the run's cwd, i.e. the
7
+ * worktree (`<worktree>/.gaia/pi-sessions`). `launchCommand` gets no
8
+ * `worktreePath`, so a relative pin is the one path both sides can agree on.
9
+ */
10
+ export declare const PI_SESSION_DIR = ".gaia/pi-sessions";
11
+ /**
12
+ * Encode an absolute cwd the way pi names its per-cwd home-session directory
13
+ * under `~/.pi/agent/sessions/`: only `/` is replaced with `-`, and the slug is
14
+ * wrapped in leading + trailing `--` (a leading `/` yields the leading `--`).
15
+ * `.` and `-` are preserved — this is NOT claude's all-non-alnum scheme.
16
+ * Verified against pi v0.82.1: `/home/cw/projects/gaia` →
17
+ * `--home-cw-projects-gaia--`.
18
+ */
19
+ export declare function encodePiHomeSessionSlug(cwd: string): string;
20
+ export interface PiAgentOptions {
21
+ model?: string;
22
+ provider?: string;
23
+ thinking?: string;
24
+ /**
25
+ * Trust the worktree's project-local pi files (extensions/skills/themes) for
26
+ * the run — pi's `-a/--approve`. Opt-in (default off): pi has no
27
+ * tool-permission gate, and the gaia worktree ships no project-local pi files
28
+ * a run needs.
29
+ */
30
+ approve?: boolean;
31
+ }
32
+ export declare class PiAgent implements GaiaAgent {
33
+ private readonly options;
34
+ private readonly home;
35
+ readonly id = "pi";
36
+ constructor(options: PiAgentOptions, home?: string);
37
+ launchCommand(prompt: string): string;
38
+ getRunLog(worktreePath: string): Promise<string>;
39
+ parseFootprint(log: string): AgentFootprint;
40
+ }
41
+ /** Config-facing factory: `piAgent({ model: 'kimi-coding/k3' })`. */
42
+ export declare function piAgent(options?: PiAgentOptions): AgentPlugin;
43
+ export default piAgent;
@@ -0,0 +1,123 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { shellQuote } from '@gaia-ai/core';
5
+ import { parsePiTranscript } from './footprint.js';
6
+ export { parsePiTranscript } from './footprint.js';
7
+ /**
8
+ * The relative `--session-dir` pin — the single source of truth shared by
9
+ * `launchCommand` (which pins pi's transcript there at launch) and `getRunLog`
10
+ * (which reads it back). Relative → resolves against the run's cwd, i.e. the
11
+ * worktree (`<worktree>/.gaia/pi-sessions`). `launchCommand` gets no
12
+ * `worktreePath`, so a relative pin is the one path both sides can agree on.
13
+ */
14
+ export const PI_SESSION_DIR = '.gaia/pi-sessions';
15
+ /**
16
+ * Encode an absolute cwd the way pi names its per-cwd home-session directory
17
+ * under `~/.pi/agent/sessions/`: only `/` is replaced with `-`, and the slug is
18
+ * wrapped in leading + trailing `--` (a leading `/` yields the leading `--`).
19
+ * `.` and `-` are preserved — this is NOT claude's all-non-alnum scheme.
20
+ * Verified against pi v0.82.1: `/home/cw/projects/gaia` →
21
+ * `--home-cw-projects-gaia--`.
22
+ */
23
+ export function encodePiHomeSessionSlug(cwd) {
24
+ return `-${cwd.replaceAll('/', '-')}--`;
25
+ }
26
+ /** Newest `*.jsonl` in `dir` by mtime, or `''`. Swallows every fs error. */
27
+ async function newestJsonl(dir) {
28
+ let entries;
29
+ try {
30
+ entries = await readdir(dir);
31
+ }
32
+ catch {
33
+ return '';
34
+ }
35
+ let latest = null;
36
+ for (const name of entries) {
37
+ if (!name.endsWith('.jsonl')) {
38
+ continue;
39
+ }
40
+ const full = join(dir, name);
41
+ try {
42
+ const s = await stat(full);
43
+ if (!latest || s.mtimeMs > latest.mtimeMs) {
44
+ latest = { path: full, mtimeMs: s.mtimeMs };
45
+ }
46
+ }
47
+ catch {
48
+ // entry vanished between readdir and stat — skip.
49
+ }
50
+ }
51
+ if (!latest) {
52
+ return '';
53
+ }
54
+ try {
55
+ return await readFile(latest.path, 'utf8');
56
+ }
57
+ catch {
58
+ return '';
59
+ }
60
+ }
61
+ export class PiAgent {
62
+ options;
63
+ home;
64
+ id = 'pi';
65
+ constructor(options, home = homedir()) {
66
+ this.options = options;
67
+ this.home = home;
68
+ }
69
+ launchCommand(prompt) {
70
+ if (prompt === '') {
71
+ return 'pi';
72
+ }
73
+ // Positional prompt → an attachable interactive TUI (no `-p`/`--print`,
74
+ // which would leave the herdr pane without a session to attach to). Order:
75
+ // provider/model/thinking, then the transcript-pinning --session-dir, then
76
+ // the opt-in --approve.
77
+ const parts = ['pi', shellQuote(prompt)];
78
+ if (this.options.provider) {
79
+ parts.push('--provider', this.options.provider);
80
+ }
81
+ if (this.options.model) {
82
+ parts.push('--model', this.options.model);
83
+ }
84
+ if (this.options.thinking) {
85
+ parts.push('--thinking', this.options.thinking);
86
+ }
87
+ parts.push('--session-dir', PI_SESSION_DIR);
88
+ if (this.options.approve) {
89
+ parts.push('--approve');
90
+ }
91
+ return parts.join(' ');
92
+ }
93
+ async getRunLog(worktreePath) {
94
+ // Primary: the relative --session-dir pinned at launch, joined onto the
95
+ // worktree — the deterministic location launchCommand wrote to.
96
+ const primary = await newestJsonl(join(worktreePath, PI_SESSION_DIR));
97
+ if (primary !== '') {
98
+ return primary;
99
+ }
100
+ // Fallback: pi's home session dir for the worktree cwd — covers a run
101
+ // launched without the pin (a human who ran bare `pi`, or a pre-addon run).
102
+ return newestJsonl(join(this.home, '.pi', 'agent', 'sessions', encodePiHomeSessionSlug(worktreePath)));
103
+ }
104
+ parseFootprint(log) {
105
+ return parsePiTranscript(log);
106
+ }
107
+ }
108
+ /** Config-facing factory: `piAgent({ model: 'kimi-coding/k3' })`. */
109
+ export function piAgent(options = {}) {
110
+ const agent = new PiAgent(options);
111
+ return {
112
+ kind: 'agent',
113
+ id: 'pi',
114
+ requiredModules: [],
115
+ async createAgent() {
116
+ return agent;
117
+ },
118
+ };
119
+ }
120
+ // Default export: this module also exports the `PiAgent` class, so the config
121
+ // resolver's auto-pick (no `export:`) would see multiple function exports and
122
+ // throw "specify export". The default export makes the factory win.
123
+ export default piAgent;
@@ -0,0 +1,2 @@
1
+ import type { Preset } from '@gaia-ai/conductor/contract';
2
+ export declare const agents: Preset['agents'];
@@ -0,0 +1,5 @@
1
+ import piAgent from './index.js';
2
+ export const agents = (acc, opts) => [
3
+ ...acc,
4
+ { agent: piAgent(opts) },
5
+ ];
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@gaia-ai/addon-pi",
3
+ "version": "0.6.1",
4
+ "description": "GAIA agent plugin for the pi coding CLI, with a real transcript footprint.",
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/keytec/gaia.git",
20
+ "directory": "gaia-cli/addons/pi"
21
+ },
22
+ "peerDependencies": {
23
+ "@gaia-ai/conductor": "^0.6.1",
24
+ "@gaia-ai/core": "^0.6.1"
25
+ }
26
+ }