@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.
- package/LICENSE +21 -0
- package/README.md +109 -0
- package/dist/browser/index.js +485 -0
- package/dist/extension/buffer.js +137 -0
- package/dist/extension/config.js +52 -0
- package/dist/extension/index.js +669 -0
- package/dist/extension/prompts.js +33 -0
- package/dist/extension/summarize.js +50 -0
- package/dist/shared/narration.js +69 -0
- package/docs/narration-subagents.png +0 -0
- package/docs/narration.png +0 -0
- package/package.json +62 -0
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { loadNarratorConfig, narrationConfigPath } from "./config.js";
|
|
4
|
+
import { NarrationBuffer } from "./buffer.js";
|
|
5
|
+
import { RETRO_SYSTEM_PROMPT, liveSystemPrompt, liveUserMessage, retrospectiveUserMessage } from "./prompts.js";
|
|
6
|
+
import { generateNarrationText } from "./summarize.js";
|
|
7
|
+
import { NARRATION_LIVE_MAX_WORDS, NARRATION_MAX_SUMMARY_LENGTH, NARRATION_METADATA_VERSION, NARRATION_NAMESPACE, NARRATOR_STYLES, SESSION_UI_METADATA_CUSTOM_TYPE, cleanNarrationText, clipWords, narratorConfigured, resolveNarratorConfig, } from "../shared/narration.js";
|
|
8
|
+
const TICK_MS = 1_000;
|
|
9
|
+
const REQUEST_TIMEOUT_MS = 20_000;
|
|
10
|
+
const BACKOFF_INITIAL_MS = 5_000;
|
|
11
|
+
const BACKOFF_MAX_MS = 60_000;
|
|
12
|
+
const MAX_RECORD_BYTES = 15_000;
|
|
13
|
+
const RECORD_RETRO_STEPS = [4_000, 2_000, 1_000, 0];
|
|
14
|
+
function isRecord(value) {
|
|
15
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
function getString(value, key) {
|
|
18
|
+
if (!isRecord(value))
|
|
19
|
+
return undefined;
|
|
20
|
+
const found = value[key];
|
|
21
|
+
return typeof found === "string" ? found : undefined;
|
|
22
|
+
}
|
|
23
|
+
function getBoolean(value, key) {
|
|
24
|
+
if (!isRecord(value))
|
|
25
|
+
return undefined;
|
|
26
|
+
const found = value[key];
|
|
27
|
+
return typeof found === "boolean" ? found : undefined;
|
|
28
|
+
}
|
|
29
|
+
/** Text from a message's string or content-block form, clipped for prompts. */
|
|
30
|
+
function messageText(message, limit = 1_200) {
|
|
31
|
+
if (!isRecord(message))
|
|
32
|
+
return "";
|
|
33
|
+
const content = message["content"];
|
|
34
|
+
if (typeof content === "string")
|
|
35
|
+
return content.slice(0, limit);
|
|
36
|
+
if (!Array.isArray(content))
|
|
37
|
+
return "";
|
|
38
|
+
const parts = [];
|
|
39
|
+
for (const part of content) {
|
|
40
|
+
if (getString(part, "type") === "text") {
|
|
41
|
+
const text = getString(part, "text");
|
|
42
|
+
if (text !== undefined)
|
|
43
|
+
parts.push(text);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return parts.join(" ").slice(0, limit);
|
|
47
|
+
}
|
|
48
|
+
function valueText(value, limit) {
|
|
49
|
+
if (value === undefined || value === null)
|
|
50
|
+
return "";
|
|
51
|
+
if (typeof value === "string")
|
|
52
|
+
return value.slice(0, limit);
|
|
53
|
+
try {
|
|
54
|
+
return JSON.stringify(value).slice(0, limit);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function toolResultText(result, limit) {
|
|
61
|
+
const content = isRecord(result) ? result["content"] : undefined;
|
|
62
|
+
if (Array.isArray(content)) {
|
|
63
|
+
const parts = [];
|
|
64
|
+
for (const part of content) {
|
|
65
|
+
if (getString(part, "type") === "text") {
|
|
66
|
+
const text = getString(part, "text");
|
|
67
|
+
if (text !== undefined)
|
|
68
|
+
parts.push(text);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (parts.length > 0)
|
|
72
|
+
return parts.join(" ").slice(0, limit);
|
|
73
|
+
}
|
|
74
|
+
return valueText(result, limit);
|
|
75
|
+
}
|
|
76
|
+
function normalize(value) {
|
|
77
|
+
return value.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/gu, " ").trim();
|
|
78
|
+
}
|
|
79
|
+
function tokens(value) {
|
|
80
|
+
const normalized = normalize(value);
|
|
81
|
+
return new Set(normalized === "" ? [] : normalized.split(" "));
|
|
82
|
+
}
|
|
83
|
+
function jaccard(left, right) {
|
|
84
|
+
const first = tokens(left);
|
|
85
|
+
const second = tokens(right);
|
|
86
|
+
if (first.size === 0 || second.size === 0)
|
|
87
|
+
return 0;
|
|
88
|
+
let shared = 0;
|
|
89
|
+
for (const token of first)
|
|
90
|
+
if (second.has(token))
|
|
91
|
+
shared += 1;
|
|
92
|
+
return shared / (first.size + second.size - shared);
|
|
93
|
+
}
|
|
94
|
+
function duplicate(previous, next) {
|
|
95
|
+
if (previous === undefined)
|
|
96
|
+
return false;
|
|
97
|
+
const left = normalize(previous);
|
|
98
|
+
const right = normalize(next);
|
|
99
|
+
if (left === "" || right === "")
|
|
100
|
+
return false;
|
|
101
|
+
return left === right || jaccard(left, right) >= 0.85;
|
|
102
|
+
}
|
|
103
|
+
function errorBody(message) {
|
|
104
|
+
const lines = message.split(/\r?\n/u);
|
|
105
|
+
// Provider failures sometimes prepend HTTP status/header lines; publish only body text.
|
|
106
|
+
const body = lines.filter((line) => !/^\s*(?:HTTP\/|authorization\s*:|proxy-authorization\s*:|www-authenticate\s*:|cookie\s*:|set-cookie\s*:|x-[a-z0-9-]+\s*:|api[-_]?key\s*:)/iu.test(line));
|
|
107
|
+
const joined = body.join(" ").trim();
|
|
108
|
+
return joined === "" ? message : joined;
|
|
109
|
+
}
|
|
110
|
+
function boundedError(error) {
|
|
111
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
112
|
+
const body = errorBody(message)
|
|
113
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/giu, "Bearer [redacted]")
|
|
114
|
+
.replace(/\b(?:sk|pk|rk|ghp|gho|ghs|xox[baprs])[-_][A-Za-z0-9_-]{8,}/gu, "[redacted]")
|
|
115
|
+
.replace(/\b(api[-_]?key|token|secret|password)\s*[=:]\s*\S+/giu, "$1=[redacted]");
|
|
116
|
+
return body.replace(/\s+/gu, " ").trim().slice(0, 300);
|
|
117
|
+
}
|
|
118
|
+
function fitsMetadata(bytes) {
|
|
119
|
+
return bytes <= MAX_RECORD_BYTES;
|
|
120
|
+
}
|
|
121
|
+
function byteLength(value) {
|
|
122
|
+
return new TextEncoder().encode(JSON.stringify(value)).length;
|
|
123
|
+
}
|
|
124
|
+
/** Keep the published entry under the host's 16 KiB public-metadata cap by trimming text. */
|
|
125
|
+
function fitRecord(record) {
|
|
126
|
+
if (fitsMetadata(byteLength(record)))
|
|
127
|
+
return record;
|
|
128
|
+
for (const retroLimit of RECORD_RETRO_STEPS) {
|
|
129
|
+
for (const summaryLimit of [400, 200, 0]) {
|
|
130
|
+
const agent = { ...record.agent };
|
|
131
|
+
if (agent.retrospective !== undefined) {
|
|
132
|
+
if (retroLimit === 0)
|
|
133
|
+
delete agent.retrospective;
|
|
134
|
+
else
|
|
135
|
+
agent.retrospective = agent.retrospective.slice(0, retroLimit);
|
|
136
|
+
}
|
|
137
|
+
if (agent.summary !== undefined) {
|
|
138
|
+
if (summaryLimit === 0)
|
|
139
|
+
delete agent.summary;
|
|
140
|
+
else
|
|
141
|
+
agent.summary = agent.summary.slice(0, summaryLimit);
|
|
142
|
+
}
|
|
143
|
+
const candidate = { ...record, agent };
|
|
144
|
+
if (fitsMetadata(byteLength(candidate)))
|
|
145
|
+
return candidate;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const { retrospective: _retro, summary: _summary, ...agent } = record.agent;
|
|
149
|
+
return { ...record, agent };
|
|
150
|
+
}
|
|
151
|
+
function saveConfig(path, config) {
|
|
152
|
+
return mkdir(dirname(path), { recursive: true })
|
|
153
|
+
.then(() => writeFile(path, `${JSON.stringify(config, null, 1)}\n`, "utf8"));
|
|
154
|
+
}
|
|
155
|
+
/** Narration for one Pi session, published only as browser-public session metadata. */
|
|
156
|
+
export default function narrationExtension(pi) {
|
|
157
|
+
let ctx;
|
|
158
|
+
let state;
|
|
159
|
+
let config = resolveNarratorConfig(undefined);
|
|
160
|
+
let ticker;
|
|
161
|
+
const metrics = { succeeded: 0, failed: 0, suppressedDuplicates: 0, skippedUnchanged: 0, lastLatencyMs: undefined, lastError: undefined };
|
|
162
|
+
const publish = () => {
|
|
163
|
+
if (ctx === undefined || state === undefined)
|
|
164
|
+
return;
|
|
165
|
+
const row = {
|
|
166
|
+
sessionId: state.sessionId,
|
|
167
|
+
name: state.name,
|
|
168
|
+
subagent: state.subagent,
|
|
169
|
+
status: state.status,
|
|
170
|
+
...(state.summary === undefined ? {} : { summary: state.summary }),
|
|
171
|
+
...(state.summaryAt === undefined ? {} : { summaryAt: state.summaryAt }),
|
|
172
|
+
startedAt: state.startedAt,
|
|
173
|
+
...(state.completedAt === undefined ? {} : { completedAt: state.completedAt }),
|
|
174
|
+
...(state.retrospective === undefined ? {} : { retrospective: state.retrospective }),
|
|
175
|
+
retrospectiveState: state.retrospectiveState,
|
|
176
|
+
};
|
|
177
|
+
const record = fitRecord({
|
|
178
|
+
v: NARRATION_METADATA_VERSION,
|
|
179
|
+
sessionId: state.sessionId,
|
|
180
|
+
executionId: state.executionId,
|
|
181
|
+
updatedAt: Date.now(),
|
|
182
|
+
agent: row,
|
|
183
|
+
metrics: {
|
|
184
|
+
succeeded: metrics.succeeded,
|
|
185
|
+
failed: metrics.failed,
|
|
186
|
+
suppressedDuplicates: metrics.suppressedDuplicates,
|
|
187
|
+
skippedUnchanged: metrics.skippedUnchanged,
|
|
188
|
+
...(metrics.lastLatencyMs === undefined ? {} : { lastLatencyMs: metrics.lastLatencyMs }),
|
|
189
|
+
...(metrics.lastError === undefined ? {} : { lastError: metrics.lastError }),
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
// Repeat snapshots are pure session-file growth: only publish when the row or metrics changed.
|
|
193
|
+
const signature = JSON.stringify({ executionId: record.executionId, agent: record.agent, metrics: record.metrics });
|
|
194
|
+
if (signature === state.lastPublishedSignature)
|
|
195
|
+
return;
|
|
196
|
+
state.lastPublishedSignature = signature;
|
|
197
|
+
// Plain custom entries are display/state data: they never enter LLM context.
|
|
198
|
+
pi.appendEntry(SESSION_UI_METADATA_CUSTOM_TYPE, {
|
|
199
|
+
version: 1,
|
|
200
|
+
metadata: { [NARRATION_NAMESPACE]: record },
|
|
201
|
+
});
|
|
202
|
+
state.lastPublishedAt = Date.now();
|
|
203
|
+
};
|
|
204
|
+
const resetExecution = (userRequest) => {
|
|
205
|
+
if (state === undefined)
|
|
206
|
+
return;
|
|
207
|
+
state.abort?.abort(new Error("Narration execution reset"));
|
|
208
|
+
state.turnSeq += 1;
|
|
209
|
+
state.executionId = `${state.sessionId}#${String(state.turnSeq)}`;
|
|
210
|
+
state.status = "active";
|
|
211
|
+
// Keep runActive: the run lifecycle owns it, and clearing it here makes the
|
|
212
|
+
// mid-run steering branch below unreachable.
|
|
213
|
+
state.awaitingTurnPrompt = false;
|
|
214
|
+
state.startedAt = Date.now();
|
|
215
|
+
state.completedAt = undefined;
|
|
216
|
+
state.summary = undefined;
|
|
217
|
+
state.summaryAt = undefined;
|
|
218
|
+
state.retrospective = undefined;
|
|
219
|
+
state.retrospectiveState = "none";
|
|
220
|
+
state.lastUserRequest = userRequest.slice(0, 1_200);
|
|
221
|
+
state.lastSummarizedHash = undefined;
|
|
222
|
+
state.consecutiveFailures = 0;
|
|
223
|
+
state.backoffUntil = 0;
|
|
224
|
+
state.dirty = false;
|
|
225
|
+
state.buffer.reset(state.startedAt, config.inputTokenBudget);
|
|
226
|
+
state.buffer.appendUser(userRequest, state.startedAt);
|
|
227
|
+
state.dirty = true;
|
|
228
|
+
publish();
|
|
229
|
+
};
|
|
230
|
+
const completeExecution = (status) => {
|
|
231
|
+
if (state === undefined)
|
|
232
|
+
return;
|
|
233
|
+
state.runActive = false;
|
|
234
|
+
if (status === "cancelled" || state.status === "active")
|
|
235
|
+
state.status = status;
|
|
236
|
+
state.completedAt = Date.now();
|
|
237
|
+
state.retrospectiveState = config.retrospectiveEnabled && state.buffer.hasContent() ? "pending" : "none";
|
|
238
|
+
publish();
|
|
239
|
+
};
|
|
240
|
+
const failExecution = (reason) => {
|
|
241
|
+
if (state === undefined)
|
|
242
|
+
return;
|
|
243
|
+
state.status = "failed";
|
|
244
|
+
state.completedAt = state.completedAt ?? Date.now();
|
|
245
|
+
state.buffer.appendStatus(`error: ${boundedError(reason)}`, Date.now());
|
|
246
|
+
state.dirty = true;
|
|
247
|
+
metrics.lastError = boundedError(reason);
|
|
248
|
+
publish();
|
|
249
|
+
};
|
|
250
|
+
const requestRef = () => {
|
|
251
|
+
if (config.provider === undefined || config.modelId === undefined)
|
|
252
|
+
return undefined;
|
|
253
|
+
return { provider: config.provider, modelId: config.modelId };
|
|
254
|
+
};
|
|
255
|
+
const dispatchLive = async (current) => {
|
|
256
|
+
const ref = requestRef();
|
|
257
|
+
if (ctx === undefined || ref === undefined || current.inFlight)
|
|
258
|
+
return;
|
|
259
|
+
current.inFlight = true;
|
|
260
|
+
current.dirty = false;
|
|
261
|
+
const controller = new AbortController();
|
|
262
|
+
current.abort = controller;
|
|
263
|
+
const executionId = current.executionId;
|
|
264
|
+
const hash = current.buffer.inputHash();
|
|
265
|
+
const started = Date.now();
|
|
266
|
+
try {
|
|
267
|
+
const outcome = await generateNarrationText(ctx.modelRegistry, ref, {
|
|
268
|
+
systemPrompt: liveSystemPrompt(config),
|
|
269
|
+
userMessage: liveUserMessage({
|
|
270
|
+
digest: current.buffer.digest(),
|
|
271
|
+
...(current.summary === undefined ? {} : { previousSummary: current.summary }),
|
|
272
|
+
...(current.lastUserRequest === undefined ? {} : { userRequest: current.lastUserRequest }),
|
|
273
|
+
}),
|
|
274
|
+
maxTokens: config.liveOutputTokens,
|
|
275
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
276
|
+
signal: controller.signal,
|
|
277
|
+
});
|
|
278
|
+
if (current.executionId !== executionId || state !== current)
|
|
279
|
+
return;
|
|
280
|
+
metrics.succeeded += 1;
|
|
281
|
+
metrics.lastLatencyMs = Date.now() - started;
|
|
282
|
+
metrics.lastError = undefined;
|
|
283
|
+
current.consecutiveFailures = 0;
|
|
284
|
+
current.backoffUntil = 0;
|
|
285
|
+
current.lastSummarizedHash = hash;
|
|
286
|
+
const summary = clipWords(cleanNarrationText(outcome.text, NARRATION_MAX_SUMMARY_LENGTH), NARRATION_LIVE_MAX_WORDS);
|
|
287
|
+
if (summary === undefined) {
|
|
288
|
+
metrics.failed += 1;
|
|
289
|
+
metrics.lastError = "Narration model returned no usable text";
|
|
290
|
+
publish();
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (duplicate(current.summary, summary) || current.buffer.breadcrumbsList().some((breadcrumb) => duplicate(breadcrumb, summary))) {
|
|
294
|
+
metrics.suppressedDuplicates += 1;
|
|
295
|
+
publish();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
current.summary = summary;
|
|
299
|
+
current.summaryAt = Date.now();
|
|
300
|
+
current.buffer.recordBreadcrumb(summary);
|
|
301
|
+
publish();
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (current.executionId !== executionId || state !== current)
|
|
305
|
+
return;
|
|
306
|
+
metrics.failed += 1;
|
|
307
|
+
metrics.lastError = boundedError(error);
|
|
308
|
+
current.consecutiveFailures += 1;
|
|
309
|
+
current.backoffUntil = Date.now() + Math.min(BACKOFF_INITIAL_MS * 2 ** (current.consecutiveFailures - 1), BACKOFF_MAX_MS);
|
|
310
|
+
current.buffer.appendStatus(`narration error: ${metrics.lastError}`, Date.now());
|
|
311
|
+
publish();
|
|
312
|
+
}
|
|
313
|
+
finally {
|
|
314
|
+
current.inFlight = false;
|
|
315
|
+
current.abort = undefined;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
const dispatchRetrospective = async (current) => {
|
|
319
|
+
const ref = requestRef();
|
|
320
|
+
if (ctx === undefined || ref === undefined || current.inFlight)
|
|
321
|
+
return;
|
|
322
|
+
current.inFlight = true;
|
|
323
|
+
const controller = new AbortController();
|
|
324
|
+
current.abort = controller;
|
|
325
|
+
const executionId = current.executionId;
|
|
326
|
+
try {
|
|
327
|
+
const outcome = await generateNarrationText(ctx.modelRegistry, ref, {
|
|
328
|
+
systemPrompt: RETRO_SYSTEM_PROMPT,
|
|
329
|
+
userMessage: retrospectiveUserMessage({
|
|
330
|
+
digest: current.buffer.digest(),
|
|
331
|
+
breadcrumbs: current.buffer.breadcrumbsList(),
|
|
332
|
+
...(current.lastUserRequest === undefined ? {} : { userRequest: current.lastUserRequest }),
|
|
333
|
+
}),
|
|
334
|
+
maxTokens: config.retrospectiveOutputTokens,
|
|
335
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
336
|
+
signal: controller.signal,
|
|
337
|
+
});
|
|
338
|
+
if (current.executionId !== executionId || state !== current)
|
|
339
|
+
return;
|
|
340
|
+
const text = cleanNarrationText(outcome.text, 4_000);
|
|
341
|
+
if (text === undefined) {
|
|
342
|
+
current.retrospectiveState = "failed";
|
|
343
|
+
publish();
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
current.retrospective = text;
|
|
347
|
+
current.retrospectiveState = "ready";
|
|
348
|
+
publish();
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
if (current.executionId !== executionId || state !== current)
|
|
352
|
+
return;
|
|
353
|
+
current.retrospectiveState = "failed";
|
|
354
|
+
metrics.lastError = boundedError(error);
|
|
355
|
+
publish();
|
|
356
|
+
}
|
|
357
|
+
finally {
|
|
358
|
+
current.inFlight = false;
|
|
359
|
+
current.abort = undefined;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const tick = async () => {
|
|
363
|
+
if (ctx === undefined || state === undefined)
|
|
364
|
+
return;
|
|
365
|
+
const current = state;
|
|
366
|
+
try {
|
|
367
|
+
config = resolveNarratorConfig(await loadNarratorConfig());
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
metrics.lastError = boundedError(error);
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
current.buffer.setBudget(config.inputTokenBudget);
|
|
374
|
+
if (!narratorConfigured(config)) {
|
|
375
|
+
if (!current.disabledPublished && current.summary !== undefined) {
|
|
376
|
+
current.disabledPublished = true;
|
|
377
|
+
publish();
|
|
378
|
+
}
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
current.disabledPublished = false;
|
|
382
|
+
const now = Date.now();
|
|
383
|
+
if (current.inFlight || now < current.backoffUntil)
|
|
384
|
+
return;
|
|
385
|
+
if (current.dirty) {
|
|
386
|
+
if (current.buffer.inputHash() === current.lastSummarizedHash) {
|
|
387
|
+
current.dirty = false;
|
|
388
|
+
metrics.skippedUnchanged += 1;
|
|
389
|
+
}
|
|
390
|
+
else if (now - current.lastPublishedAt >= config.minIntervalMs) {
|
|
391
|
+
await dispatchLive(current);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (current.retrospectiveState === "pending")
|
|
396
|
+
await dispatchRetrospective(current);
|
|
397
|
+
};
|
|
398
|
+
pi.on("session_start", (_event, context) => {
|
|
399
|
+
ctx = context;
|
|
400
|
+
const sessionId = context.sessionManager.getSessionId();
|
|
401
|
+
const header = context.sessionManager.getHeader();
|
|
402
|
+
const parent = getString(header, "parentSession");
|
|
403
|
+
state = {
|
|
404
|
+
sessionId,
|
|
405
|
+
sessionFile: context.sessionManager.getSessionFile(),
|
|
406
|
+
subagent: parent !== undefined && parent !== "",
|
|
407
|
+
name: context.sessionManager.getSessionName() ?? "Agent",
|
|
408
|
+
turnSeq: 0,
|
|
409
|
+
executionId: `${sessionId}#0`,
|
|
410
|
+
status: "active",
|
|
411
|
+
runActive: false,
|
|
412
|
+
awaitingTurnPrompt: true,
|
|
413
|
+
startedAt: Date.now(),
|
|
414
|
+
completedAt: undefined,
|
|
415
|
+
summary: undefined,
|
|
416
|
+
summaryAt: undefined,
|
|
417
|
+
retrospective: undefined,
|
|
418
|
+
retrospectiveState: "none",
|
|
419
|
+
lastUserRequest: undefined,
|
|
420
|
+
buffer: new NarrationBuffer({ startedAt: Date.now(), inputTokenBudget: config.inputTokenBudget }),
|
|
421
|
+
dirty: false,
|
|
422
|
+
lastPublishedAt: 0,
|
|
423
|
+
lastPublishedSignature: undefined,
|
|
424
|
+
lastSummarizedHash: undefined,
|
|
425
|
+
inFlight: false,
|
|
426
|
+
abort: undefined,
|
|
427
|
+
consecutiveFailures: 0,
|
|
428
|
+
backoffUntil: 0,
|
|
429
|
+
disabledPublished: false,
|
|
430
|
+
};
|
|
431
|
+
if (ticker === undefined) {
|
|
432
|
+
ticker = setInterval(() => { void tick(); }, TICK_MS);
|
|
433
|
+
ticker.unref?.();
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
pi.on("session_info_changed", (event) => {
|
|
437
|
+
if (state === undefined)
|
|
438
|
+
return;
|
|
439
|
+
const name = event.name?.trim();
|
|
440
|
+
if (name === undefined || name === "")
|
|
441
|
+
return;
|
|
442
|
+
state.name = name;
|
|
443
|
+
publish();
|
|
444
|
+
});
|
|
445
|
+
pi.on("agent_start", () => {
|
|
446
|
+
if (state === undefined)
|
|
447
|
+
return;
|
|
448
|
+
state.runActive = true;
|
|
449
|
+
state.awaitingTurnPrompt = true;
|
|
450
|
+
state.completedAt = undefined;
|
|
451
|
+
if (state.status !== "active")
|
|
452
|
+
state.status = "active";
|
|
453
|
+
publish();
|
|
454
|
+
});
|
|
455
|
+
pi.on("agent_end", () => {
|
|
456
|
+
if (state !== undefined)
|
|
457
|
+
state.runActive = false;
|
|
458
|
+
});
|
|
459
|
+
pi.on("agent_settled", (event) => {
|
|
460
|
+
completeExecution(event.aborted ? "cancelled" : "complete");
|
|
461
|
+
});
|
|
462
|
+
pi.on("message_start", (event) => {
|
|
463
|
+
if (state === undefined)
|
|
464
|
+
return;
|
|
465
|
+
const role = getString(event.message, "role");
|
|
466
|
+
if (role === "user") {
|
|
467
|
+
const text = messageText(event.message, 1_200);
|
|
468
|
+
if (state.runActive && !state.awaitingTurnPrompt) {
|
|
469
|
+
state.buffer.appendUser(text, Date.now(), true);
|
|
470
|
+
state.dirty = true;
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
resetExecution(text);
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
state.awaitingTurnPrompt = false;
|
|
477
|
+
state.buffer.noteActivity(Date.now());
|
|
478
|
+
});
|
|
479
|
+
pi.on("message_update", (event) => {
|
|
480
|
+
if (state === undefined)
|
|
481
|
+
return;
|
|
482
|
+
const update = event.assistantMessageEvent;
|
|
483
|
+
const kind = getString(update, "type");
|
|
484
|
+
const delta = getString(update, "delta");
|
|
485
|
+
state.awaitingTurnPrompt = false;
|
|
486
|
+
if (delta === undefined || delta === "")
|
|
487
|
+
return;
|
|
488
|
+
if (kind === "thinking_delta")
|
|
489
|
+
state.buffer.appendReasoning(delta, Date.now());
|
|
490
|
+
else if (kind === "text_delta")
|
|
491
|
+
state.buffer.appendText(delta, Date.now());
|
|
492
|
+
else
|
|
493
|
+
return;
|
|
494
|
+
state.dirty = true;
|
|
495
|
+
});
|
|
496
|
+
pi.on("tool_execution_start", (event) => {
|
|
497
|
+
if (state === undefined)
|
|
498
|
+
return;
|
|
499
|
+
state.awaitingTurnPrompt = false;
|
|
500
|
+
const args = valueText(event.args, 800);
|
|
501
|
+
if (event.toolName === "spawn_subsession" || event.toolName === "spawn_session") {
|
|
502
|
+
state.buffer.appendSubagent(args === "" ? `${event.toolName} started` : `${event.toolName}: ${args}`, Date.now());
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
state.buffer.appendToolStart(event.toolName, args, Date.now());
|
|
506
|
+
}
|
|
507
|
+
state.dirty = true;
|
|
508
|
+
});
|
|
509
|
+
pi.on("tool_execution_end", (event) => {
|
|
510
|
+
if (state === undefined)
|
|
511
|
+
return;
|
|
512
|
+
state.buffer.appendToolEnd(event.toolName, toolResultText(event.result, 1_500), event.isError ? "error" : "ok", Date.now());
|
|
513
|
+
state.dirty = true;
|
|
514
|
+
});
|
|
515
|
+
pi.on("message_end", (event) => {
|
|
516
|
+
if (state === undefined)
|
|
517
|
+
return;
|
|
518
|
+
const role = getString(event.message, "role");
|
|
519
|
+
if (role === "assistant" && getString(event.message, "stopReason") === "error") {
|
|
520
|
+
failExecution(getString(event.message, "errorMessage") ?? "assistant response failed");
|
|
521
|
+
}
|
|
522
|
+
else if (role === "toolResult" && getBoolean(event.message, "isError") === true) {
|
|
523
|
+
state.buffer.appendStatus(`${getString(event.message, "toolName") ?? "tool"} failed`, Date.now());
|
|
524
|
+
state.dirty = true;
|
|
525
|
+
}
|
|
526
|
+
});
|
|
527
|
+
pi.on("session_shutdown", () => {
|
|
528
|
+
// An interrupted run must not linger as "active" in saved session metadata.
|
|
529
|
+
if (state !== undefined && state.status === "active") {
|
|
530
|
+
state.status = "cancelled";
|
|
531
|
+
state.completedAt = Date.now();
|
|
532
|
+
state.retrospectiveState = "none";
|
|
533
|
+
publish();
|
|
534
|
+
}
|
|
535
|
+
if (ticker !== undefined)
|
|
536
|
+
clearInterval(ticker);
|
|
537
|
+
ticker = undefined;
|
|
538
|
+
state?.abort?.abort(new Error("Narration session shut down"));
|
|
539
|
+
ctx = undefined;
|
|
540
|
+
state = undefined;
|
|
541
|
+
});
|
|
542
|
+
pi.registerCommand("narrator", {
|
|
543
|
+
description: "Configure live activity narration (on|off|status|model|style|custom|interval)",
|
|
544
|
+
handler: async (args, commandCtx) => {
|
|
545
|
+
const path = narrationConfigPath();
|
|
546
|
+
let stored;
|
|
547
|
+
try {
|
|
548
|
+
stored = await loadNarratorConfig(path);
|
|
549
|
+
}
|
|
550
|
+
catch (error) {
|
|
551
|
+
await commandCtx.ui.select(`Narration config could not be read: ${boundedError(error)}`, ["Close"]);
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
const show = async (message) => {
|
|
555
|
+
await commandCtx.ui.select(message, ["Close"]);
|
|
556
|
+
};
|
|
557
|
+
const save = async (patch) => {
|
|
558
|
+
const next = { ...stored, ...patch };
|
|
559
|
+
await saveConfig(path, next);
|
|
560
|
+
// Only adopt the in-memory copy after the write succeeds.
|
|
561
|
+
stored = next;
|
|
562
|
+
};
|
|
563
|
+
const statusText = () => {
|
|
564
|
+
const resolved = resolveNarratorConfig(stored);
|
|
565
|
+
const model = resolved.provider === undefined ? "not configured" : `${resolved.provider}/${resolved.modelId ?? ""}`;
|
|
566
|
+
return [
|
|
567
|
+
`Narration ${resolved.enabled ? "enabled" : "disabled"}.`,
|
|
568
|
+
`Model: ${model}. Style: ${resolved.style}. Interval: ${String(resolved.minIntervalMs)} ms.`,
|
|
569
|
+
`Requests: ${String(metrics.succeeded)} ok, ${String(metrics.failed)} failed.`,
|
|
570
|
+
`Suppressed duplicates: ${String(metrics.suppressedDuplicates)}; unchanged skips: ${String(metrics.skippedUnchanged)}.`,
|
|
571
|
+
...(metrics.lastLatencyMs === undefined ? [] : [`Last latency: ${String(metrics.lastLatencyMs)} ms.`]),
|
|
572
|
+
...(metrics.lastError === undefined ? [] : [`Last error: ${metrics.lastError}`]),
|
|
573
|
+
].join("\n");
|
|
574
|
+
};
|
|
575
|
+
const pickModel = async () => {
|
|
576
|
+
const available = commandCtx.modelRegistry.getAvailable();
|
|
577
|
+
const options = available.slice(0, 100).map((model) => `${model.provider}/${model.id}${model.name === undefined ? "" : ` — ${model.name}`}`);
|
|
578
|
+
if (options.length === 0) {
|
|
579
|
+
await show("No models are available to select as the narration model.");
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const choice = await commandCtx.ui.select("Choose the narration model", options);
|
|
583
|
+
if (choice === undefined)
|
|
584
|
+
return;
|
|
585
|
+
const label = choice.split(" — ")[0] ?? choice;
|
|
586
|
+
const slash = label.indexOf("/");
|
|
587
|
+
if (slash <= 0 || slash === label.length - 1)
|
|
588
|
+
return;
|
|
589
|
+
const provider = label.slice(0, slash);
|
|
590
|
+
// Model ids may contain slashes (OpenRouter-style names): only the first separates the provider.
|
|
591
|
+
const modelId = label.slice(slash + 1);
|
|
592
|
+
await save({ model: { provider, modelId } });
|
|
593
|
+
await show(`Narration model set to ${provider}/${modelId}.`);
|
|
594
|
+
};
|
|
595
|
+
const editCustom = async () => {
|
|
596
|
+
const current = resolveNarratorConfig(stored).customInstructions;
|
|
597
|
+
const value = await commandCtx.ui.input("Custom narration instructions (empty keeps the default)", current, {});
|
|
598
|
+
if (value === undefined)
|
|
599
|
+
return;
|
|
600
|
+
const instructions = value.trim();
|
|
601
|
+
await save({ style: "custom", customInstructions: instructions });
|
|
602
|
+
await show(instructions === "" ? "Custom style selected; using the default prompt." : "Custom narration instructions saved.");
|
|
603
|
+
};
|
|
604
|
+
const trimmed = args.trim().toLowerCase();
|
|
605
|
+
if (trimmed === "on" || trimmed === "off") {
|
|
606
|
+
await save({ enabled: trimmed === "on" });
|
|
607
|
+
await show(`Narration ${trimmed === "on" ? "enabled" : "disabled"}.`);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (trimmed === "status") {
|
|
611
|
+
await show(statusText());
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
if (trimmed === "model") {
|
|
615
|
+
await pickModel();
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (trimmed === "style") {
|
|
619
|
+
const choice = await commandCtx.ui.select("Narration style", [...NARRATOR_STYLES]);
|
|
620
|
+
if (choice === "custom")
|
|
621
|
+
await editCustom();
|
|
622
|
+
else if (choice !== undefined)
|
|
623
|
+
await save({ style: choice });
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (trimmed === "custom") {
|
|
627
|
+
await editCustom();
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
if (trimmed === "interval") {
|
|
631
|
+
const value = await commandCtx.ui.input("Minimum seconds between summaries", "3", {});
|
|
632
|
+
const seconds = Number(value);
|
|
633
|
+
if (Number.isFinite(seconds) && seconds >= 1)
|
|
634
|
+
await save({ minIntervalMs: Math.round(seconds * 1_000) });
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
if (trimmed === "" || trimmed === "config" || trimmed === "settings") {
|
|
638
|
+
for (;;) {
|
|
639
|
+
const resolved = resolveNarratorConfig(stored);
|
|
640
|
+
const choice = await commandCtx.ui.select(`Narration is ${resolved.enabled ? "enabled" : "disabled"} (${resolved.provider ?? "no model"}/${resolved.modelId ?? ""}).`, ["Enable / disable", "Choose model", "Style", "Custom instructions", "Interval", "Status", "Close"]);
|
|
641
|
+
if (choice === undefined || choice === "Close")
|
|
642
|
+
return;
|
|
643
|
+
if (choice === "Enable / disable")
|
|
644
|
+
await save({ enabled: !resolveNarratorConfig(stored).enabled });
|
|
645
|
+
else if (choice === "Choose model")
|
|
646
|
+
await pickModel();
|
|
647
|
+
else if (choice === "Style") {
|
|
648
|
+
const style = await commandCtx.ui.select("Narration style", [...NARRATOR_STYLES]);
|
|
649
|
+
if (style === "custom")
|
|
650
|
+
await editCustom();
|
|
651
|
+
else if (style !== undefined)
|
|
652
|
+
await save({ style: style });
|
|
653
|
+
}
|
|
654
|
+
else if (choice === "Custom instructions")
|
|
655
|
+
await editCustom();
|
|
656
|
+
else if (choice === "Interval") {
|
|
657
|
+
const value = await commandCtx.ui.input("Minimum seconds between summaries", "3", {});
|
|
658
|
+
const seconds = Number(value);
|
|
659
|
+
if (Number.isFinite(seconds) && seconds >= 1)
|
|
660
|
+
await save({ minIntervalMs: Math.round(seconds * 1_000) });
|
|
661
|
+
}
|
|
662
|
+
else if (choice === "Status")
|
|
663
|
+
await show(statusText());
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
await show("Usage: /narrator [on|off|status|model|style|custom|interval]");
|
|
667
|
+
},
|
|
668
|
+
});
|
|
669
|
+
}
|