@bakers-build/addon-pi 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-pi
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 pi coding CLI, with a real transcript footprint.
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 a pi JSONL transcript into an agent footprint (BB-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` (BB-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 '@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
+ /** 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 (BB-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` (BB-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,58 @@
1
+ import { type AgentFootprint, type AgentPlugin, type AgentRunIdentity, type BbAgent } from '@bakers-build/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>/.bakers/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 = ".bakers/pi-sessions";
11
+ /**
12
+ * The `--session-dir` value for a given run (BB-473): scoped to the run's
13
+ * own subdirectory when its identity is known, so `getRunLog` reads only that
14
+ * run's own transcripts — never a foreign one left behind by a resumed
15
+ * run/re-dispatch/reused worktree in the shared {@link PI_SESSION_DIR}. Falls
16
+ * back to the shared dir when no run identity is given (today's behaviour).
17
+ */
18
+ export declare function piSessionDir(run?: AgentRunIdentity): string;
19
+ /**
20
+ * Encode an absolute cwd the way pi names its per-cwd home-session directory
21
+ * under `~/.pi/agent/sessions/`: only `/` is replaced with `-`, and the slug is
22
+ * wrapped in leading + trailing `--` (a leading `/` yields the leading `--`).
23
+ * `.` and `-` are preserved — this is NOT claude's all-non-alnum scheme.
24
+ * Verified against pi v0.82.1: `/home/cw/projects/bakers` →
25
+ * `--home-cw-projects-bakers--`.
26
+ */
27
+ export declare function encodePiHomeSessionSlug(cwd: string): string;
28
+ export interface PiAgentOptions {
29
+ model?: string;
30
+ provider?: string;
31
+ thinking?: string;
32
+ effort?: string;
33
+ args?: string[];
34
+ /**
35
+ * Trust the worktree's project-local pi files (extensions/skills/themes) for
36
+ * the run — pi's `-a/--approve`. Opt-in (default off): pi has no
37
+ * tool-permission gate, and the bakers worktree ships no project-local pi files
38
+ * a run needs.
39
+ */
40
+ approve?: boolean;
41
+ }
42
+ export declare class PiAgent implements BbAgent {
43
+ private readonly home;
44
+ readonly id = "pi";
45
+ private readonly args;
46
+ private readonly model;
47
+ private readonly provider;
48
+ private readonly thinking;
49
+ private readonly approve;
50
+ private readonly overrides;
51
+ constructor(options?: PiAgentOptions, home?: string);
52
+ launchCommand(prompt: string, run?: AgentRunIdentity): string;
53
+ getRunLog(worktreePath: string, run?: AgentRunIdentity): Promise<string>;
54
+ parseFootprint(log: string): AgentFootprint;
55
+ }
56
+ /** Config-facing factory: `piAgent({ model: 'kimi-coding/k3' })`. */
57
+ export declare function piAgent(options?: PiAgentOptions): AgentPlugin;
58
+ export default piAgent;
@@ -0,0 +1,180 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { resolveAgentCliOptions, validateOptionalBoolean, validateOptionalString, } from '@bakers-build/conductor/contract';
5
+ import { shellQuote } from '@bakers-build/core';
6
+ import { parsePiTranscript } from './footprint.js';
7
+ export { parsePiTranscript } from './footprint.js';
8
+ /**
9
+ * The relative `--session-dir` pin — the single source of truth shared by
10
+ * `launchCommand` (which pins pi's transcript there at launch) and `getRunLog`
11
+ * (which reads it back). Relative → resolves against the run's cwd, i.e. the
12
+ * worktree (`<worktree>/.bakers/pi-sessions`). `launchCommand` gets no
13
+ * `worktreePath`, so a relative pin is the one path both sides can agree on.
14
+ */
15
+ export const PI_SESSION_DIR = '.bakers/pi-sessions';
16
+ /**
17
+ * The `--session-dir` value for a given run (BB-473): scoped to the run's
18
+ * own subdirectory when its identity is known, so `getRunLog` reads only that
19
+ * run's own transcripts — never a foreign one left behind by a resumed
20
+ * run/re-dispatch/reused worktree in the shared {@link PI_SESSION_DIR}. Falls
21
+ * back to the shared dir when no run identity is given (today's behaviour).
22
+ */
23
+ export function piSessionDir(run) {
24
+ return run?.sessionId ? `${PI_SESSION_DIR}/${run.sessionId}` : PI_SESSION_DIR;
25
+ }
26
+ /**
27
+ * Encode an absolute cwd the way pi names its per-cwd home-session directory
28
+ * under `~/.pi/agent/sessions/`: only `/` is replaced with `-`, and the slug is
29
+ * wrapped in leading + trailing `--` (a leading `/` yields the leading `--`).
30
+ * `.` and `-` are preserved — this is NOT claude's all-non-alnum scheme.
31
+ * Verified against pi v0.82.1: `/home/cw/projects/bakers` →
32
+ * `--home-cw-projects-bakers--`.
33
+ */
34
+ export function encodePiHomeSessionSlug(cwd) {
35
+ return `-${cwd.replaceAll('/', '-')}--`;
36
+ }
37
+ const PI_RESERVED = [
38
+ '--session-dir',
39
+ '--approve',
40
+ '-a',
41
+ '--no-approve',
42
+ '-na',
43
+ ];
44
+ const PI_KNOWN = [
45
+ { kind: 'model', flags: ['--model'] },
46
+ { kind: 'effort', flags: ['--thinking'] },
47
+ ];
48
+ /**
49
+ * Newest `*.jsonl` in `dir` by mtime, or `''`. Swallows every fs error.
50
+ * `minMtimeMs`, when given, excludes anything older — the fallback scan's
51
+ * defence against selecting a transcript from a PRIOR run left in the shared,
52
+ * cwd-keyed home session dir (BB-473 finding 2).
53
+ */
54
+ async function newestJsonl(dir, minMtimeMs) {
55
+ let entries;
56
+ try {
57
+ entries = await readdir(dir);
58
+ }
59
+ catch {
60
+ return '';
61
+ }
62
+ let latest = null;
63
+ for (const name of entries) {
64
+ if (!name.endsWith('.jsonl')) {
65
+ continue;
66
+ }
67
+ const full = join(dir, name);
68
+ try {
69
+ const s = await stat(full);
70
+ if (minMtimeMs !== undefined &&
71
+ Number.isFinite(minMtimeMs) &&
72
+ s.mtimeMs < minMtimeMs) {
73
+ continue;
74
+ }
75
+ if (!latest || s.mtimeMs > latest.mtimeMs) {
76
+ latest = { path: full, mtimeMs: s.mtimeMs };
77
+ }
78
+ }
79
+ catch {
80
+ // entry vanished between readdir and stat — skip.
81
+ }
82
+ }
83
+ if (!latest) {
84
+ return '';
85
+ }
86
+ try {
87
+ return await readFile(latest.path, 'utf8');
88
+ }
89
+ catch {
90
+ return '';
91
+ }
92
+ }
93
+ export class PiAgent {
94
+ home;
95
+ id = 'pi';
96
+ args;
97
+ model;
98
+ provider;
99
+ thinking;
100
+ approve;
101
+ overrides;
102
+ constructor(options = {}, home = homedir()) {
103
+ this.home = home;
104
+ const cli = resolveAgentCliOptions(options, PI_RESERVED, PI_KNOWN);
105
+ this.args = cli.args;
106
+ this.model = cli.model;
107
+ this.provider = validateOptionalString(options.provider, 'provider');
108
+ this.thinking =
109
+ cli.effort ?? validateOptionalString(options.thinking, 'thinking');
110
+ this.approve = validateOptionalBoolean(options.approve, 'approve') === true;
111
+ this.overrides = cli.overrides;
112
+ }
113
+ launchCommand(prompt, run) {
114
+ if (prompt === '') {
115
+ return 'pi';
116
+ }
117
+ // Positional prompt → an attachable interactive TUI (no `-p`/`--print`,
118
+ // which would leave the herdr pane without a session to attach to). Order:
119
+ // provider/model/thinking, then the transcript-pinning --session-dir, then
120
+ // the opt-in --approve.
121
+ const parts = ['pi', shellQuote(prompt)];
122
+ if (this.provider) {
123
+ parts.push('--provider', shellQuote(this.provider));
124
+ }
125
+ if (this.model !== undefined && !this.overrides.model) {
126
+ parts.push('--model', shellQuote(this.model));
127
+ }
128
+ if (this.thinking !== undefined && !this.overrides.effort) {
129
+ parts.push('--thinking', shellQuote(this.thinking));
130
+ }
131
+ // Scoped to this run's own subdirectory (BB-473) when a run identity is
132
+ // given, so getRunLog needs no ambiguity-prone scan of the shared
133
+ // session dir a resumed/re-dispatched/reused worktree could have left
134
+ // other transcripts in.
135
+ parts.push('--session-dir', piSessionDir(run));
136
+ if (this.approve) {
137
+ parts.push('--approve');
138
+ }
139
+ parts.push(...this.args.map(shellQuote));
140
+ return parts.join(' ');
141
+ }
142
+ async getRunLog(worktreePath, run) {
143
+ // Primary: the relative --session-dir pinned at launch (per-run scoped
144
+ // when `run` is given), joined onto the worktree — the deterministic
145
+ // location launchCommand wrote to.
146
+ const primary = await newestJsonl(join(worktreePath, piSessionDir(run)));
147
+ if (primary !== '') {
148
+ return primary;
149
+ }
150
+ // Fallback: pi's home session dir for the worktree cwd — covers a run
151
+ // launched without the pin (a human who ran bare `pi`, or a pre-addon
152
+ // run). BB-473 finding 2: that dir is shared/cwd-keyed like the other
153
+ // addons' scans, so it is bounded by `run.startedAt` where known — a
154
+ // transcript from a PRIOR run left in the same worktree can never be
155
+ // selected for this one even when it is the newest match.
156
+ const startedAtMs = run?.startedAt !== undefined ? new Date(run.startedAt).getTime() : null;
157
+ return newestJsonl(join(this.home, '.pi', 'agent', 'sessions', encodePiHomeSessionSlug(worktreePath)), startedAtMs !== null && Number.isFinite(startedAtMs)
158
+ ? startedAtMs
159
+ : undefined);
160
+ }
161
+ parseFootprint(log) {
162
+ return parsePiTranscript(log);
163
+ }
164
+ }
165
+ /** Config-facing factory: `piAgent({ model: 'kimi-coding/k3' })`. */
166
+ export function piAgent(options = {}) {
167
+ const agent = new PiAgent(options);
168
+ return {
169
+ kind: 'agent',
170
+ id: 'pi',
171
+ requiredModules: [],
172
+ async createAgent() {
173
+ return agent;
174
+ },
175
+ };
176
+ }
177
+ // Default export: this module also exports the `PiAgent` class, so the config
178
+ // resolver's auto-pick (no `export:`) would see multiple function exports and
179
+ // throw "specify export". The default export makes the factory win.
180
+ export default piAgent;
@@ -0,0 +1,4 @@
1
+ import type { Preset } from '@bakers-build/conductor/contract';
2
+ import { type PiAgentOptions } from './index.js';
3
+ export declare const agents: Preset<Partial<PiAgentOptions> | undefined>['agents'];
4
+ export declare const scopes: Preset['scopes'];
@@ -0,0 +1,15 @@
1
+ import piAgent from './index.js';
2
+ export const agents = (acc, opts) => {
3
+ const model = opts?.model;
4
+ return [
5
+ ...acc,
6
+ {
7
+ alias: 'pi',
8
+ description: 'General coding with the locally configured Pi model.',
9
+ ...(model !== undefined ? { model } : {}),
10
+ agent: piAgent(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-pi",
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 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/bakers-build/bakers-build.git",
20
+ "directory": "bakers-cli/addons/pi"
21
+ },
22
+ "peerDependencies": {
23
+ "@bakers-build/conductor": "^0.1.0-next.42",
24
+ "@bakers-build/core": "^0.1.0-next.42"
25
+ }
26
+ }