@daguava/pi-narration 0.1.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.
@@ -0,0 +1,137 @@
1
+ const CHARS_PER_TOKEN = 3.5;
2
+ const MAX_BREADCRUMBS = 6;
3
+ const CLIPS = { reasoning: 1_200, text: 800, toolArgs: 800, toolResult: 1_500, user: 1_200, status: 400 };
4
+ function clip(value, limit) {
5
+ const normalized = value.replace(/\s+/gu, " ").trim();
6
+ return normalized.length <= limit ? normalized : `${normalized.slice(0, limit).replace(/[\s,;:.]+$/u, "")}…`;
7
+ }
8
+ const KIND_LABEL = {
9
+ user: "user request",
10
+ steering: "user steering",
11
+ reasoning: "reasoning",
12
+ text: "assistant",
13
+ toolStart: "tool started",
14
+ toolEnd: "tool finished",
15
+ subagent: "subagent",
16
+ status: "status",
17
+ };
18
+ /** Bounded rolling activity; relative stamps stay stable so provider prefix caching can hit. */
19
+ export class NarrationBuffer {
20
+ entries = [];
21
+ retained = 0;
22
+ startedAt = Date.now();
23
+ lastActivityAt = Date.now();
24
+ budgetTokens;
25
+ breadcrumbs = [];
26
+ constructor(options) {
27
+ this.startedAt = options.startedAt;
28
+ this.lastActivityAt = options.startedAt;
29
+ this.budgetTokens = options.inputTokenBudget;
30
+ }
31
+ get lastActivity() {
32
+ return this.lastActivityAt;
33
+ }
34
+ reset(startedAt, inputTokenBudget) {
35
+ this.entries = [];
36
+ this.retained = 0;
37
+ this.startedAt = startedAt;
38
+ this.lastActivityAt = startedAt;
39
+ this.budgetTokens = inputTokenBudget;
40
+ this.breadcrumbs.length = 0;
41
+ }
42
+ setBudget(inputTokenBudget) {
43
+ this.budgetTokens = inputTokenBudget;
44
+ this.trim();
45
+ }
46
+ hasContent() {
47
+ return this.entries.length > 0;
48
+ }
49
+ size() {
50
+ return this.retained;
51
+ }
52
+ digest() {
53
+ return this.entries.map((entry) => this.describe(entry)).join("\n");
54
+ }
55
+ inputHash() {
56
+ let hash = 0x811c9dc5;
57
+ const digest = this.digest();
58
+ for (let index = 0; index < digest.length; index += 1) {
59
+ hash ^= digest.charCodeAt(index);
60
+ hash = Math.imul(hash, 0x01000193);
61
+ }
62
+ return hash >>> 0;
63
+ }
64
+ breadcrumbsList() {
65
+ return this.breadcrumbs;
66
+ }
67
+ recordBreadcrumb(summary) {
68
+ this.breadcrumbs.push(summary);
69
+ if (this.breadcrumbs.length > MAX_BREADCRUMBS)
70
+ this.breadcrumbs.shift();
71
+ }
72
+ appendUser(text, at, steering = false) {
73
+ this.append({ kind: steering ? "steering" : "user", text: clip(text, CLIPS.user), at });
74
+ }
75
+ appendReasoning(delta, at) {
76
+ this.appendCoalesced("reasoning", undefined, delta, CLIPS.reasoning, at);
77
+ }
78
+ appendText(delta, at) {
79
+ this.appendCoalesced("text", undefined, delta, CLIPS.text, at);
80
+ }
81
+ appendToolStart(name, args, at) {
82
+ const detail = args === "" ? name : `${name}: ${args}`;
83
+ this.append({ kind: "toolStart", text: clip(detail, CLIPS.toolArgs), at });
84
+ }
85
+ appendToolEnd(name, result, status, at) {
86
+ const detail = result === "" ? `${name} (${status})` : `${name} (${status}): ${result}`;
87
+ this.append({ kind: "toolEnd", text: clip(detail, CLIPS.toolResult), at });
88
+ }
89
+ appendSubagent(text, at) {
90
+ this.append({ kind: "subagent", text: clip(text, CLIPS.user), at });
91
+ }
92
+ appendStatus(text, at) {
93
+ this.append({ kind: "status", text: clip(text, CLIPS.status), at });
94
+ }
95
+ noteActivity(at) {
96
+ this.lastActivityAt = Math.max(this.lastActivityAt, at);
97
+ }
98
+ append(entry) {
99
+ this.entries.push(entry);
100
+ this.retained += entry.text.length;
101
+ this.lastActivityAt = Math.max(this.lastActivityAt, entry.at);
102
+ this.trim();
103
+ }
104
+ appendCoalesced(kind, label, delta, limit, at) {
105
+ if (delta.trim() === "")
106
+ return;
107
+ const last = this.entries[this.entries.length - 1];
108
+ if (last?.kind === kind && last.label === label) {
109
+ const previous = last.text.length;
110
+ last.text = clip(`${last.text}${delta}`, limit);
111
+ last.at = at;
112
+ this.retained += last.text.length - previous;
113
+ this.lastActivityAt = Math.max(this.lastActivityAt, at);
114
+ this.trim();
115
+ return;
116
+ }
117
+ this.append({ kind, ...(label === undefined ? {} : { label }), text: clip(delta, limit), at });
118
+ }
119
+ describe(entry) {
120
+ const seconds = Math.max(0, Math.round((entry.at - this.startedAt) / 1_000));
121
+ const label = entry.label === undefined ? "" : ` ${entry.label}`;
122
+ return `[+${String(seconds)}s] ${KIND_LABEL[entry.kind]}${label}: ${entry.text}`;
123
+ }
124
+ trim() {
125
+ const maxChars = Math.max(1, Math.floor(this.budgetTokens * CHARS_PER_TOKEN));
126
+ while (this.entries.length > 1 && this.retained > maxChars) {
127
+ const removed = this.entries.shift();
128
+ if (removed === undefined)
129
+ return;
130
+ this.retained -= removed.text.length;
131
+ }
132
+ }
133
+ }
134
+ /** Keep configuration-driven budget authoritative for one execution. */
135
+ export function applyBufferBudget(buffer, config) {
136
+ buffer.setBudget(config.inputTokenBudget);
137
+ }
@@ -0,0 +1,52 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ /** Pi exposes its profile directory through the public env contract. */
5
+ export function narrationAgentDir(env = process.env, home = homedir()) {
6
+ const configured = env["PI_CODING_AGENT_DIR"];
7
+ if (configured === undefined || configured === "")
8
+ return join(home, ".pi", "agent");
9
+ if (configured === "~")
10
+ return home;
11
+ if (configured.startsWith("~/") || configured.startsWith("~\\"))
12
+ return join(home, configured.slice(2));
13
+ return configured;
14
+ }
15
+ export function narrationConfigPath(agentDir = narrationAgentDir()) {
16
+ return join(agentDir, "narration", "config.json");
17
+ }
18
+ function isRecord(value) {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+ export function parseNarratorConfig(value) {
22
+ if (!isRecord(value))
23
+ throw new Error("Narration config must be an object");
24
+ const model = isRecord(value["model"]) ? value["model"] : undefined;
25
+ const provider = model?.["provider"];
26
+ const modelId = model?.["modelId"];
27
+ return {
28
+ ...(typeof value["enabled"] === "boolean" ? { enabled: value["enabled"] } : {}),
29
+ ...(typeof provider === "string" && typeof modelId === "string"
30
+ ? { model: { provider, modelId } }
31
+ : {}),
32
+ ...(typeof value["minIntervalMs"] === "number" ? { minIntervalMs: value["minIntervalMs"] } : {}),
33
+ ...(typeof value["style"] === "string" ? { style: value["style"] } : {}),
34
+ ...(typeof value["customInstructions"] === "string" ? { customInstructions: value["customInstructions"] } : {}),
35
+ ...(typeof value["inputTokenBudget"] === "number" ? { inputTokenBudget: value["inputTokenBudget"] } : {}),
36
+ ...(typeof value["liveOutputTokens"] === "number" ? { liveOutputTokens: value["liveOutputTokens"] } : {}),
37
+ ...(typeof value["retrospectiveEnabled"] === "boolean" ? { retrospectiveEnabled: value["retrospectiveEnabled"] } : {}),
38
+ ...(typeof value["retrospectiveOutputTokens"] === "number" ? { retrospectiveOutputTokens: value["retrospectiveOutputTokens"] } : {}),
39
+ };
40
+ }
41
+ /** Read config fresh per request so edits apply without restarting the session. */
42
+ export async function loadNarratorConfig(path = narrationConfigPath()) {
43
+ try {
44
+ return parseNarratorConfig(JSON.parse(await readFile(path, "utf8")));
45
+ }
46
+ catch (error) {
47
+ const code = isRecord(error) ? error["code"] : undefined;
48
+ if (code === "ENOENT")
49
+ return {};
50
+ throw error;
51
+ }
52
+ }