@rob-c/pi-managed-tools 0.16.0 → 0.23.0

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/src/context.ts ADDED
@@ -0,0 +1,157 @@
1
+ /*
2
+ * pi-managed-tools — keep a set of developer binaries at their latest upstream release.
3
+ * Copyright (C) 2026 Robert Currie
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify it under
6
+ * the terms of the GNU General Public License as published by the Free Software
7
+ * Foundation; version 2 of the License only.
8
+ *
9
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY
10
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
11
+ * PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU General Public License along with this
14
+ * program; if not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.
15
+ */
16
+ /**
17
+ * What the model is sent of results it has already read: the `context` hook's two jobs.
18
+ *
19
+ * 1. **Old timelines lose their offsets, at compaction and only then.** Stamps were
20
+ * measured at a quarter of all bash-result bytes, and a result from forty turns ago is
21
+ * not read for its nanoseconds. But rewriting an old message changes the prompt's
22
+ * prefix, and with a caching provider one changed prefix costs more than every stamp
23
+ * in the session saves. Compaction is the one moment the prefix is rebuilt anyway — so
24
+ * the rule is stateless and free: a wrapped bash result older than the latest
25
+ * compaction summary is sent without its offsets, from that request on. The header,
26
+ * every stderr line's identity, the digest and the notes all stay; the session file is
27
+ * never touched.
28
+ *
29
+ * 2. **A `!` command reaches the model as a timeline.** The person sees the command's
30
+ * own bytes; what pi records, and would send, is that same plain text — both streams
31
+ * in one, no order, no timing. The capture took a timeline anyway, so the recorded
32
+ * message is swapped for it on the way out. The same swap every turn, so the prefix
33
+ * stays stable.
34
+ *
35
+ * Pure: the extension hands the messages in and keeps the views.
36
+ */
37
+
38
+ const FULL_OR_DITTO = /^\[(?:\s*\d+\.\d{1,9}|=) (out|err)\] /;
39
+
40
+ /** How an aged result's marker begins; it stands where `--- timeline ---` stood. */
41
+ export const AGED_MARKER = "--- output, offsets aged out";
42
+
43
+ /** The marker line, naming the command that still has the offsets while the capture lasts. */
44
+ export function agedMarker(runId?: string): string {
45
+ const where = runId ? `; \`busybox log ${runId} --stream timeline\` has the offsets while the capture lasts` : "";
46
+ return `${AGED_MARKER} (\`err|\` marks a stderr line${where}) ---`;
47
+ }
48
+
49
+ /**
50
+ * A wrapped result without its offsets, or undefined when the text is not a wrapped
51
+ * result or has been aged already.
52
+ *
53
+ * stdout lines become the command's own text and stderr lines keep an `err| ` mark, so
54
+ * the one thing the tags existed for — a warning is not program output — survives.
55
+ */
56
+ export function ageTimeline(text: string): string | undefined {
57
+ if (!/^run=R\d+ /m.test(text) || !/^--- timeline ---$/m.test(text)) return undefined;
58
+ const runId = /^run=(R\d+) /m.exec(text)?.[1];
59
+ let isChanged = false;
60
+ const lines = text.split("\n").map((line) => {
61
+ if (line === "--- timeline ---") {
62
+ isChanged = true;
63
+ return agedMarker(runId);
64
+ }
65
+ const match = FULL_OR_DITTO.exec(line);
66
+ if (!match) return line;
67
+ isChanged = true;
68
+ const own = line.slice(match[0].length);
69
+ return match[1] === "err" ? `err| ${own}` : own;
70
+ });
71
+ return isChanged ? lines.join("\n") : undefined;
72
+ }
73
+
74
+ interface TextPart {
75
+ type: string;
76
+ text?: string;
77
+ }
78
+
79
+ /** The fields of pi's messages this module reads; everything else is passed through. */
80
+ export interface ContextMessage {
81
+ role: string;
82
+ toolName?: string;
83
+ content?: unknown;
84
+ timestamp?: number;
85
+ command?: string;
86
+ output?: string;
87
+ }
88
+
89
+ /**
90
+ * Age every wrapped bash result older than the latest compaction summary.
91
+ *
92
+ * Returns the same array when nothing changed, so the caller can tell pi "unchanged" and
93
+ * keep mid-conversation system messages (and the cached prefix) where they are.
94
+ */
95
+ export function ageOutMessages<T extends ContextMessage>(messages: readonly T[]): T[] {
96
+ let cut = 0;
97
+ for (const message of messages) {
98
+ if (message.role === "compactionSummary" && typeof message.timestamp === "number") cut = Math.max(cut, message.timestamp);
99
+ }
100
+ if (cut === 0) return messages as T[];
101
+ let isChanged = false;
102
+ const out = messages.map((message) => {
103
+ if (message.role !== "toolResult" || message.toolName !== "bash") return message;
104
+ if (typeof message.timestamp !== "number" || message.timestamp >= cut) return message;
105
+ if (!Array.isArray(message.content)) return message;
106
+ let isAged = false;
107
+ const content = (message.content as TextPart[]).map((part) => {
108
+ if (part.type !== "text" || typeof part.text !== "string") return part;
109
+ const aged = ageTimeline(part.text);
110
+ if (aged === undefined) return part;
111
+ isAged = true;
112
+ return { ...part, text: aged };
113
+ });
114
+ if (!isAged) return message;
115
+ isChanged = true;
116
+ return { ...message, content };
117
+ });
118
+ return isChanged ? out : (messages as T[]);
119
+ }
120
+
121
+ /** One `!` command's timeline, kept for the model. */
122
+ export interface UserView {
123
+ /** The command pi was asked to run (its own prefix, if any, in front). */
124
+ command: string;
125
+ /** When the command ended, ms since the epoch: pi records its message at that moment. */
126
+ endedAt: number;
127
+ /** What the model should read instead of the plain bytes. */
128
+ view: string;
129
+ }
130
+
131
+ /** How far apart the end of the run and pi's record of it may be and still be the same command. */
132
+ const MATCH_WINDOW_MS = 5_000;
133
+
134
+ /**
135
+ * Swap each recorded `!` command's plain output for its timeline, where one was kept.
136
+ *
137
+ * Matched by the moment it ended and by the command text: pi records the message as the
138
+ * backend returns. Returns the same array when nothing matched.
139
+ */
140
+ export function swapUserBash<T extends ContextMessage>(messages: readonly T[], views: readonly UserView[]): T[] {
141
+ if (views.length === 0) return messages as T[];
142
+ let isChanged = false;
143
+ const out = messages.map((message) => {
144
+ if (message.role !== "bashExecution" || typeof message.timestamp !== "number" || typeof message.command !== "string") return message;
145
+ const stamp = message.timestamp;
146
+ const command = message.command;
147
+ let best: UserView | undefined;
148
+ for (const view of views) {
149
+ if (Math.abs(view.endedAt - stamp) > MATCH_WINDOW_MS || !view.command.endsWith(command)) continue;
150
+ if (!best || Math.abs(view.endedAt - stamp) < Math.abs(best.endedAt - stamp)) best = view;
151
+ }
152
+ if (!best || best.view === message.output) return message;
153
+ isChanged = true;
154
+ return { ...message, output: best.view };
155
+ });
156
+ return isChanged ? out : (messages as T[]);
157
+ }
package/src/display.ts ADDED
@@ -0,0 +1,79 @@
1
+ /*
2
+ * pi-managed-tools — keep a set of developer binaries at their latest upstream release.
3
+ * Copyright (C) 2026 Robert Currie
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify it under
6
+ * the terms of the GNU General Public License as published by the Free Software
7
+ * Foundation; version 2 of the License only.
8
+ *
9
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY
10
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
11
+ * PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU General Public License along with this
14
+ * program; if not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.
15
+ */
16
+ /**
17
+ * The timeline goes to the model; the human watching the screen gets the command's
18
+ * own output.
19
+ *
20
+ * One `bash` call now produces two texts from the same result:
21
+ *
22
+ * [ 0.011354 out] ok 1 <- model: ordering, timing, stream per line
23
+ * [ 0.066632 err] FAILED test_x
24
+ *
25
+ * ok 1 <- human: what the command said
26
+ * FAILED test_x
27
+ *
28
+ * The model needs the offsets; nobody reading a terminal needs `[ 0.011354 out]`
29
+ * repeated on every line. The split is done by the bash renderer (TUI and HTML
30
+ * export), while the tool result itself — the bytes the model reads and the session
31
+ * stores — keeps the timeline intact.
32
+ */
33
+
34
+ /** A line the wrapper itself printed, rather than the command. */
35
+ const WRAPPER_LINE = new RegExp(
36
+ [
37
+ "^run=R\\d+ ", // run=R12 exit_code=0 timed_out=false ...
38
+ "^timeline_lines=", // timeline_lines=3 shown=3 truncated=false
39
+ "^captured_bytes=", // captured_bytes=... capture_complete=...
40
+ "^(stdout|stderr)_artifact=", // artifact paths
41
+ "^pgid=", // only with --pgid
42
+ "^--- (timeline|stdout|stderr) ---$", // section markers
43
+ "^\\[brief\\] ", // brief's own reduction marker
44
+ "^pruned=\\d+ keep=\\d+$", // --prune's own report, from a capture made before it was dropped
45
+ "^timing: ", // the model-facing digest appended by tool_result
46
+ ].join("|"),
47
+ );
48
+
49
+ /**
50
+ * The per-line prefix in every shape it has had: padded (`[ 0.011354 out] `,
51
+ * `[00000.005868042 out] `), unpadded (`[0.005868042 out] `, `[1.225 out] `, 0.6.1 on),
52
+ * and `[= out] ` for a line at the same offset as the one above (compactStamps).
53
+ */
54
+ const TIMELINE_PREFIX = /^\[(?:\s*\d+\.\d{1,9}|=) (?:out|err)\] /;
55
+
56
+ /** Whether this text carries a timeline at all, so callers can skip the work. */
57
+ export function hasTimeline(text: string): boolean {
58
+ return TIMELINE_PREFIX.test(text) || /^timeline_lines=/m.test(text) || /^--- timeline ---$/m.test(text);
59
+ }
60
+
61
+ /**
62
+ * Remove the wrapper's own lines and the per-line prefix, keeping the command's bytes.
63
+ *
64
+ * Nothing else is touched: indentation, blank lines, ANSI the command printed itself and
65
+ * a truncated view's `... [N bytes] ...` marker all stay, because they are the command's
66
+ * output and not the wrapper's decoration.
67
+ */
68
+ export function stripTimeline(text: string): string {
69
+ const kept: string[] = [];
70
+ for (const line of text.split("\n")) {
71
+ if (WRAPPER_LINE.test(line)) continue;
72
+ kept.push(line.replace(TIMELINE_PREFIX, ""));
73
+ }
74
+ // A wrapper whose command printed nothing still has to read as "no output", not as
75
+ // a blank row that looks like a rendering bug.
76
+ while (kept.length > 0 && kept[0] === "") kept.shift();
77
+ while (kept.length > 0 && kept[kept.length - 1] === "") kept.pop();
78
+ return kept.length > 0 ? kept.join("\n") : "(no output)";
79
+ }