pi-workfeed 0.0.0-stage → 0.1.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/CHANGELOG.md +70 -0
- package/LICENSE +21 -0
- package/README.md +317 -2
- package/docs/README.md +15 -0
- package/docs/decisions//346/234/211/346/225/210/345/206/263/347/255/226/344/270/273/350/241/250.md +17 -0
- package/docs/schema.md +454 -0
- package/docs/verification.md +212 -0
- package/docs/versioning.md +91 -0
- package/extensions/journal/digest.ts +318 -0
- package/extensions/journal/index.ts +674 -0
- package/extensions/journal/replay.ts +359 -0
- package/extensions/todo/index.ts +332 -0
- package/package.json +54 -4
- package/schemas/workfeed-event-v1.schema.json +176 -0
- package/skills/workfeed-analysis/SKILL.md +142 -0
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-workfeed · journal — turns a pi session into a machine-readable event log.
|
|
3
|
+
*
|
|
4
|
+
* Two outputs, one truth, one derived:
|
|
5
|
+
* ~/.pi/agent/logs/<YYYY-MM-DD>/workfeed-<sid>.jsonl 真值层,一行一事件
|
|
6
|
+
* ~/.pi/agent/logs/<YYYY-MM-DD>/workfeed-<sid>.digest.md 派生层,聚合事实,可随时重算
|
|
7
|
+
*
|
|
8
|
+
* Every line carries the same four keys, so tasks / turns / tool calls / tokens
|
|
9
|
+
* can be joined without guessing:
|
|
10
|
+
* v schema version (1)
|
|
11
|
+
* sid session id
|
|
12
|
+
* task 1-based user-instruction index
|
|
13
|
+
* item work item id currently in_progress (source-neutral; absent when none)
|
|
14
|
+
*
|
|
15
|
+
* Environment:
|
|
16
|
+
* PI_WORKFEED_DIR log root (default ~/.pi/agent/logs)
|
|
17
|
+
* PI_WORKFEED_EXCERPT tool-output excerpt bytes kept in the log (default 2048, 0 = keep none)
|
|
18
|
+
* PI_WORKFEED_CONTENT set to 0 for metadata only: no prompt text, no tool output, no
|
|
19
|
+
* command text, no todo text, paths reduced to their basename
|
|
20
|
+
* PI_WORKFEED_ARGS tool arguments: full | redacted | shape | off
|
|
21
|
+
* (default: shape when PI_WORKFEED_CONTENT=0, else redacted)
|
|
22
|
+
* PI_WORKFEED_OFF=1 disable this extension
|
|
23
|
+
*
|
|
24
|
+
* The collection policy is explicit because the log is meant to be shared: a
|
|
25
|
+
* metadata-only log must stay safe to hand to a colleague or a bug report.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
29
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
|
|
30
|
+
import { homedir } from "node:os";
|
|
31
|
+
import { join } from "node:path";
|
|
32
|
+
import { fmtDur, type TodoItem, type TokenBuckets } from "./digest.ts";
|
|
33
|
+
import { rebuildDigest, resumeState } from "./replay.ts";
|
|
34
|
+
|
|
35
|
+
const SCHEMA_VERSION = 1;
|
|
36
|
+
/** logs are sensitive: owner-only, best effort (Windows honours this partially) */
|
|
37
|
+
const FILE_MODE = 0o600;
|
|
38
|
+
const DIR_MODE = 0o700;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Wrap footer status text in the same faint intensity pi applies to its own footer line.
|
|
42
|
+
*
|
|
43
|
+
* `ctx.ui.setStatus()` takes plain text and exposes no theme accessor, and pi does not dim
|
|
44
|
+
* extension statuses (footer.js dims only the truncation ellipsis), so we carry the exact
|
|
45
|
+
* sequence `theme.fg("dim", …)` emits — SGR 2 … 22;39 (theme.js). `sanitizeStatusText` strips
|
|
46
|
+
* only \r\n\t and pi-tui's visibleWidth/truncateToWidth ignore ANSI, so layout is unaffected.
|
|
47
|
+
*/
|
|
48
|
+
const faint = (text: string): string => `\x1b[2m${text}\x1b[22;39m`;
|
|
49
|
+
|
|
50
|
+
const EXCERPT = Math.max(0, Number(process.env.PI_WORKFEED_EXCERPT ?? 2048));
|
|
51
|
+
const CONTENT = process.env.PI_WORKFEED_CONTENT !== "0";
|
|
52
|
+
const ROOT = process.env.PI_WORKFEED_DIR || join(homedir(), ".pi", "agent", "logs");
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Argument policy — the one channel that used to leak regardless of CONTENT.
|
|
56
|
+
* full every argument value, clipped only (debugging)
|
|
57
|
+
* redacted per-tool summary: command text, paths, pattern, sizes (default with content)
|
|
58
|
+
* shape keys + string byte counts, no values at all (default in metadata-only)
|
|
59
|
+
* off no `args` field
|
|
60
|
+
*/
|
|
61
|
+
type ArgsMode = "full" | "redacted" | "shape" | "off";
|
|
62
|
+
const ARGS_MODE: ArgsMode = (() => {
|
|
63
|
+
const raw = (process.env.PI_WORKFEED_ARGS ?? "").toLowerCase();
|
|
64
|
+
if (raw === "full" || raw === "redacted" || raw === "shape" || raw === "off") return raw;
|
|
65
|
+
return CONTENT ? "redacted" : "shape";
|
|
66
|
+
})();
|
|
67
|
+
|
|
68
|
+
const zeroTokens = (): TokenBuckets => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 });
|
|
69
|
+
|
|
70
|
+
function dayStamp(d = new Date()): string {
|
|
71
|
+
const p = (n: number) => String(n).padStart(2, "0");
|
|
72
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Serialize anything to something that will not break one-line JSON. */
|
|
76
|
+
function safeJson(value: unknown, max = 4000): unknown {
|
|
77
|
+
let s: string;
|
|
78
|
+
try {
|
|
79
|
+
s = typeof value === "string" ? value : (JSON.stringify(value) ?? String(value));
|
|
80
|
+
} catch {
|
|
81
|
+
s = String(value);
|
|
82
|
+
}
|
|
83
|
+
return s.length <= max ? value : s.slice(0, max) + `…[${s.length - max} chars omitted]`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Keep the head and the tail of a long output; the middle is rarely the signal. */
|
|
87
|
+
function excerpt(text: string): { out: string; bytes: number } {
|
|
88
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
89
|
+
if (EXCERPT === 0 || bytes <= EXCERPT) return { out: EXCERPT === 0 ? "" : text, bytes };
|
|
90
|
+
const half = Math.floor(EXCERPT / 2);
|
|
91
|
+
return {
|
|
92
|
+
out: `${text.slice(0, half)}\n…[${bytes - EXCERPT} bytes omitted]…\n${text.slice(-half)}`,
|
|
93
|
+
bytes,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Credentials inside free text are redacted even in content mode. This is
|
|
99
|
+
* **best effort, not a guarantee**: patterns catch common shapes (flags, headers,
|
|
100
|
+
* DSNs, cloud keys, JWTs, env assignments), they cannot catch a secret that looks
|
|
101
|
+
* like an ordinary word. Treat the log as sensitive either way.
|
|
102
|
+
*/
|
|
103
|
+
function stripSecrets(text: string): string {
|
|
104
|
+
return text
|
|
105
|
+
// scheme://user:password@host — DSNs for postgres/mysql/redis/amqp…
|
|
106
|
+
.replace(/\b([a-z][a-z0-9+.-]{1,15}:\/\/)[^\s:@/]+:[^\s@/]+@/gi, "$1<redacted>:<redacted>@")
|
|
107
|
+
// --token value / API_KEY=value / DATABASE_URL=value …
|
|
108
|
+
.replace(/(--?[a-z0-9_-]*(?:token|secret|passw(?:or)?d|api[-_]?key|auth|credential)[a-z0-9_-]*\s*[= ]\s*)("[^"]*"|'[^']*'|[^\s;|&]+)/gi, "$1<redacted>")
|
|
109
|
+
.replace(/((?:[A-Za-z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|APIKEY|API_KEY|ACCESS_KEY|PRIVATE_KEY|DATABASE_URL|DB_URL|DSN)[A-Za-z0-9_]*)\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s;|&]+)/gi, "$1<redacted>")
|
|
110
|
+
// Authorization header, Bearer tokens
|
|
111
|
+
.replace(/((?:authorization|bearer)\s*[:=]?\s*)([A-Za-z0-9._~+/=-]{8,})/gi, "$1<redacted>")
|
|
112
|
+
.replace(/((?:api[_-]?key|secret|token|passw(?:or)?d)["']?\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s;|&]+)/gi, "$1<redacted>")
|
|
113
|
+
// curl -u user:password
|
|
114
|
+
.replace(/((?:^|\s)-u\s+)[^\s:]+:[^\s]+/g, "$1<redacted>:<redacted>")
|
|
115
|
+
// well-known token prefixes
|
|
116
|
+
.replace(/\b(?:sk|ghp|gho|ghs|xox[baprs])[-_]?[A-Za-z0-9_-]{16,}/g, "<redacted-token>")
|
|
117
|
+
.replace(/\bAKIA[0-9A-Z]{16}\b/g, "<redacted-token>")
|
|
118
|
+
// JWT: three base64url segments
|
|
119
|
+
.replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, "<redacted-token>")
|
|
120
|
+
// inline PEM private keys
|
|
121
|
+
.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "<redacted-private-key>");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Walk a value and redact every string inside it; used for tool arguments. */
|
|
125
|
+
function redactValue(value: unknown, depth = 0): unknown {
|
|
126
|
+
if (typeof value === "string") return stripSecrets(value);
|
|
127
|
+
if (typeof value !== "object" || value === null) return value;
|
|
128
|
+
if (depth > 6) return "<…>";
|
|
129
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1));
|
|
130
|
+
const out: Record<string, unknown> = {};
|
|
131
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = redactValue(v, depth + 1);
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A path in metadata-only mode keeps its last segment only: "which file" survives,
|
|
137
|
+
* "whose disk / which client folder" does not.
|
|
138
|
+
*/
|
|
139
|
+
function barePath(value: unknown): unknown {
|
|
140
|
+
if (typeof value !== "string") return value;
|
|
141
|
+
if (CONTENT) return value;
|
|
142
|
+
const parts = value.split(/[\\/]+/).filter(Boolean);
|
|
143
|
+
return parts.length ? `<…>/${parts[parts.length - 1]}` : value;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Structure without values: key names, plus string byte counts. */
|
|
147
|
+
function shapeArgs(input: unknown): unknown {
|
|
148
|
+
const a = input as Record<string, unknown> | undefined;
|
|
149
|
+
if (!a || typeof a !== "object") return undefined;
|
|
150
|
+
const keys = Object.keys(a).sort();
|
|
151
|
+
const stringBytes: Record<string, number> = {};
|
|
152
|
+
for (const k of keys) {
|
|
153
|
+
const v = a[k];
|
|
154
|
+
if (typeof v === "string") stringBytes[k] = Buffer.byteLength(v, "utf8");
|
|
155
|
+
}
|
|
156
|
+
return { keys, ...(Object.keys(stringBytes).length ? { stringBytes } : {}) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Shrink tool arguments: never put a whole file body into the log. */
|
|
160
|
+
function slimArgs(name: string, input: unknown): unknown {
|
|
161
|
+
if (ARGS_MODE === "off") return undefined;
|
|
162
|
+
if (ARGS_MODE === "shape") return shapeArgs(input);
|
|
163
|
+
const a = input as Record<string, unknown> | undefined;
|
|
164
|
+
if (!a) return undefined;
|
|
165
|
+
// `full` and the per-tool fallback (unknown / MCP tools) serialize arbitrary
|
|
166
|
+
// arguments, so redaction has to run on the value, not only on known fields.
|
|
167
|
+
if (ARGS_MODE === "full") return safeJson(redactValue(a), 1200);
|
|
168
|
+
const clip = (v: unknown, n = 2000) => (typeof v === "string" ? v.slice(0, n) : v);
|
|
169
|
+
switch (name) {
|
|
170
|
+
case "bash":
|
|
171
|
+
case "powershell":
|
|
172
|
+
return { command: stripSecrets(clip(a.command)), timeout: a.timeout };
|
|
173
|
+
case "write":
|
|
174
|
+
return {
|
|
175
|
+
path: barePath(a.path),
|
|
176
|
+
contentBytes: typeof a.content === "string" ? Buffer.byteLength(a.content) : undefined,
|
|
177
|
+
};
|
|
178
|
+
case "edit":
|
|
179
|
+
return {
|
|
180
|
+
path: barePath(a.path),
|
|
181
|
+
oldBytes: typeof a.old_string === "string" ? Buffer.byteLength(a.old_string) : undefined,
|
|
182
|
+
newBytes: typeof a.new_string === "string" ? Buffer.byteLength(a.new_string) : undefined,
|
|
183
|
+
replaceAll: a.replace_all,
|
|
184
|
+
};
|
|
185
|
+
case "read":
|
|
186
|
+
case "ls":
|
|
187
|
+
return { path: barePath(a.path), offset: a.offset, limit: a.limit };
|
|
188
|
+
case "grep":
|
|
189
|
+
return { pattern: stripSecrets(clip(a.pattern)), path: barePath(a.path), glob: a.glob, output_mode: a.output_mode };
|
|
190
|
+
default:
|
|
191
|
+
// Unknown tools (MCP servers, custom extensions) have no shape we understand,
|
|
192
|
+
// so this is the branch that used to leak: redact the values, then clip.
|
|
193
|
+
return safeJson(redactValue(a), 1200);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function textOf(result: unknown): string {
|
|
198
|
+
const r = result as { content?: Array<{ type?: string; text?: string }> } | undefined;
|
|
199
|
+
if (!r?.content) return "";
|
|
200
|
+
return r.content
|
|
201
|
+
.filter((c) => c?.type === "text" && typeof c.text === "string")
|
|
202
|
+
.map((c) => c.text as string)
|
|
203
|
+
.join("\n");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function toTodoItems(snapshot: unknown): TodoItem[] {
|
|
207
|
+
const s = snapshot as { todos?: Array<{ id?: number; text?: string; status?: string; elapsedMs?: number; startedAt?: number }> } | undefined;
|
|
208
|
+
if (!s?.todos) return [];
|
|
209
|
+
const now = Date.now();
|
|
210
|
+
return s.todos.map((t, i) => {
|
|
211
|
+
const base = t.elapsedMs ?? 0;
|
|
212
|
+
const running = t.status === "in_progress" && t.startedAt ? base + Math.max(0, now - t.startedAt) : base;
|
|
213
|
+
return { id: t.id ?? i + 1, text: String(t.text ?? ""), status: String(t.status ?? "pending"), elapsedMs: running };
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export default function (pi: ExtensionAPI) {
|
|
218
|
+
if (process.env.PI_WORKFEED_OFF === "1") return;
|
|
219
|
+
|
|
220
|
+
let sid = "unknown";
|
|
221
|
+
let cwd = "";
|
|
222
|
+
let dir: string | undefined;
|
|
223
|
+
let logPath: string | undefined;
|
|
224
|
+
let digestPath: string | undefined;
|
|
225
|
+
let warned = false;
|
|
226
|
+
|
|
227
|
+
let events = 0;
|
|
228
|
+
let task = 0;
|
|
229
|
+
let item: number | undefined;
|
|
230
|
+
|
|
231
|
+
let taskStartTs = 0;
|
|
232
|
+
/** true only between a user prompt and its settle: gates ghost settle rows */
|
|
233
|
+
let taskActive = false;
|
|
234
|
+
let turns = 0;
|
|
235
|
+
let tools = 0;
|
|
236
|
+
let tokens = zeroTokens();
|
|
237
|
+
|
|
238
|
+
let turnStartTs = 0;
|
|
239
|
+
let turnIndex = 0;
|
|
240
|
+
let toolStarts = new Map<string, { name: string; ts: number; task: number; item?: number }>();
|
|
241
|
+
let currentTool: string | undefined;
|
|
242
|
+
let lastTaskMs = 0;
|
|
243
|
+
let taskCount = 0;
|
|
244
|
+
|
|
245
|
+
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
246
|
+
let uiCtx: ExtensionContext | undefined;
|
|
247
|
+
|
|
248
|
+
const restrict = (path: string, mode: number) => {
|
|
249
|
+
try {
|
|
250
|
+
chmodSync(path, mode);
|
|
251
|
+
} catch {
|
|
252
|
+
/* Windows honours this partially; never let permissions break logging */
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const write = (event: Record<string, unknown>) => {
|
|
257
|
+
if (!logPath) return;
|
|
258
|
+
events += 1;
|
|
259
|
+
const line = JSON.stringify({ v: SCHEMA_VERSION, ts: Date.now(), sid, task, ...(item ? { item } : {}), ...event });
|
|
260
|
+
try {
|
|
261
|
+
appendFileSync(logPath, line + "\n", { encoding: "utf8", mode: FILE_MODE });
|
|
262
|
+
restrict(logPath, FILE_MODE);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
if (!warned) {
|
|
265
|
+
warned = true;
|
|
266
|
+
if (uiCtx?.hasUI) uiCtx.ui.notify(`workfeed: cannot write log: ${(err as Error).message}`, "error");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/** A session owns one log, wherever it was first written (date dirs are just filing). */
|
|
272
|
+
const findExistingLog = (sessionId: string): string | undefined => {
|
|
273
|
+
try {
|
|
274
|
+
const days = readdirSync(ROOT, { withFileTypes: true })
|
|
275
|
+
.filter((d) => d.isDirectory())
|
|
276
|
+
.map((d) => d.name)
|
|
277
|
+
.sort()
|
|
278
|
+
.reverse();
|
|
279
|
+
for (const day of days) {
|
|
280
|
+
const candidate = join(ROOT, day, `workfeed-${sessionId}.jsonl`);
|
|
281
|
+
if (existsSync(candidate)) return candidate;
|
|
282
|
+
}
|
|
283
|
+
} catch {
|
|
284
|
+
/* root may not exist yet */
|
|
285
|
+
}
|
|
286
|
+
return undefined;
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Say it once, at the moment the log actually starts existing. A privacy policy
|
|
291
|
+
* only in the README is read by nobody who is already working: from `/reload`
|
|
292
|
+
* onwards this extension writes prompts and tool output to disk, and the session
|
|
293
|
+
* that is being recorded is the only place where saying so is timely.
|
|
294
|
+
*/
|
|
295
|
+
const announced = new Set<string>();
|
|
296
|
+
const announceOnce = (ctx: ExtensionContext) => {
|
|
297
|
+
if (!ctx.hasUI || !logPath || announced.has(logPath)) return;
|
|
298
|
+
announced.add(logPath);
|
|
299
|
+
const where = String(barePath(logPath));
|
|
300
|
+
const how = CONTENT
|
|
301
|
+
? "prompt text and tool output are recorded; PI_WORKFEED_CONTENT=0 keeps timing only"
|
|
302
|
+
: "timing only (PI_WORKFEED_CONTENT=0) — no prompt text, no tool output";
|
|
303
|
+
ctx.ui.notify(`workfeed: writing this session to ${where} — ${how}. Logs are never rotated; delete old date folders to reclaim space.`, "info");
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Point the writer at the right files. Re-binds when the session id changes
|
|
308
|
+
* (`/new`, `/resume` inside a live process) and reuses an existing log across
|
|
309
|
+
* days, so one session never splits into two date directories.
|
|
310
|
+
*/
|
|
311
|
+
const ensureFiles = (ctx: ExtensionContext) => {
|
|
312
|
+
const sessionId = ctx.sessionManager.getSessionId?.() || "unknown";
|
|
313
|
+
if (logPath && sessionId === sid) return;
|
|
314
|
+
try {
|
|
315
|
+
sid = sessionId;
|
|
316
|
+
cwd = ctx.cwd;
|
|
317
|
+
const existing = findExistingLog(sid);
|
|
318
|
+
if (existing) {
|
|
319
|
+
logPath = existing;
|
|
320
|
+
digestPath = existing.replace(/\.jsonl$/, ".digest.md");
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
dir = join(ROOT, dayStamp());
|
|
324
|
+
mkdirSync(dir, { recursive: true, mode: DIR_MODE });
|
|
325
|
+
restrict(dir, DIR_MODE);
|
|
326
|
+
logPath = join(dir, `workfeed-${sid}.jsonl`);
|
|
327
|
+
digestPath = join(dir, `workfeed-${sid}.digest.md`);
|
|
328
|
+
// a brand-new session starts its own numbering: `/new` must not inherit
|
|
329
|
+
// the previous session's task counter
|
|
330
|
+
task = 0;
|
|
331
|
+
taskCount = 0;
|
|
332
|
+
lastTaskMs = 0;
|
|
333
|
+
item = undefined;
|
|
334
|
+
announceOnce(ctx);
|
|
335
|
+
} catch {
|
|
336
|
+
logPath = undefined;
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Rewrite the digest — by replaying the JSONL, never from the counters above.
|
|
342
|
+
*
|
|
343
|
+
* The log is the truth and this process only witnesses part of it: a session
|
|
344
|
+
* reopened after a restart, a `/fork`, or 2 000 tool calls later, still renders
|
|
345
|
+
* from every line on disk. See `replay.ts` for the constraint.
|
|
346
|
+
*/
|
|
347
|
+
const writeDigest = () => {
|
|
348
|
+
if (!digestPath || !logPath) return;
|
|
349
|
+
try {
|
|
350
|
+
if (!existsSync(logPath)) return;
|
|
351
|
+
const md = rebuildDigest(logPath, { cwd: String(barePath(cwd)), model: uiCtx?.model?.id, provider: uiCtx?.model?.provider });
|
|
352
|
+
writeFileSync(digestPath, md, { encoding: "utf8", mode: FILE_MODE });
|
|
353
|
+
restrict(digestPath, FILE_MODE);
|
|
354
|
+
} catch {
|
|
355
|
+
/* derived data: failing to write it must never break the session */
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
const status = (ctx: ExtensionContext | undefined, running: boolean) => {
|
|
360
|
+
if (!ctx?.hasUI) return;
|
|
361
|
+
if (!running) {
|
|
362
|
+
ctx.ui.setStatus("workfeed", lastTaskMs ? faint(`last ${fmtDur(lastTaskMs)}`) : "");
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const elapsed = taskStartTs ? Date.now() - taskStartTs : 0;
|
|
366
|
+
const tail = currentTool ? ` · ${currentTool}` : "";
|
|
367
|
+
const it = item ? ` · #${item}` : "";
|
|
368
|
+
ctx.ui.setStatus("workfeed", faint(`${fmtDur(elapsed)}${tail}${it} · t${turnIndex} · ${tools} calls`));
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
const startTicker = (ctx: ExtensionContext) => {
|
|
372
|
+
uiCtx = ctx;
|
|
373
|
+
if (ticker || !ctx.hasUI) return;
|
|
374
|
+
ticker = setInterval(() => {
|
|
375
|
+
if (taskStartTs && uiCtx) status(uiCtx, true);
|
|
376
|
+
}, 2000);
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
const stopTicker = () => {
|
|
380
|
+
if (ticker) clearInterval(ticker);
|
|
381
|
+
ticker = undefined;
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// ---- todo state arrives from the todo extension over the shared bus ----
|
|
385
|
+
// A `todo` line means "the list changed". Repeats are dropped here as well, so a
|
|
386
|
+
// noisy publisher (UI tick, duplicate extension instance) cannot inflate the log.
|
|
387
|
+
let lastTodoLine = "";
|
|
388
|
+
pi.events.on("workfeed:todo", (snapshot: unknown) => {
|
|
389
|
+
const snapshotItems = toTodoItems(snapshot);
|
|
390
|
+
item = snapshotItems.find((t) => t.status === "in_progress")?.id;
|
|
391
|
+
const items = snapshotItems.map((t) => ({
|
|
392
|
+
id: t.id,
|
|
393
|
+
status: t.status,
|
|
394
|
+
elapsedMs: t.elapsedMs,
|
|
395
|
+
...(CONTENT ? { text: stripSecrets(t.text).slice(0, 120) } : { textChars: t.text.length }),
|
|
396
|
+
}));
|
|
397
|
+
const line = JSON.stringify(items);
|
|
398
|
+
if (line === lastTodoLine) return;
|
|
399
|
+
lastTodoLine = line;
|
|
400
|
+
write({ t: "todo", rev: (snapshot as { rev?: number } | undefined)?.rev, items });
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
pi.on("session_start", async (event, ctx) => {
|
|
404
|
+
ensureFiles(ctx);
|
|
405
|
+
// A resumed session continues the log, so the task counter must continue too:
|
|
406
|
+
// otherwise the second process writes a second `task: 1` and the join key lie
|
|
407
|
+
// starts right there.
|
|
408
|
+
if (logPath && existsSync(logPath)) {
|
|
409
|
+
try {
|
|
410
|
+
const resumed = resumeState(logPath);
|
|
411
|
+
if (resumed.nextTask > task + 1) task = resumed.nextTask - 1;
|
|
412
|
+
taskCount = Math.max(taskCount, resumed.tasks);
|
|
413
|
+
if (resumed.lastTaskMs > 0) lastTaskMs = resumed.lastTaskMs;
|
|
414
|
+
} catch {
|
|
415
|
+
/* a broken tail must not stop the session from logging */
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
startTicker(ctx);
|
|
419
|
+
write({
|
|
420
|
+
t: "session",
|
|
421
|
+
reason: (event as { reason?: string })?.reason,
|
|
422
|
+
cwd: barePath(cwd),
|
|
423
|
+
sessionFile: barePath(ctx.sessionManager.getSessionFile?.()),
|
|
424
|
+
model: ctx.model?.id,
|
|
425
|
+
provider: ctx.model?.provider,
|
|
426
|
+
pid: process.pid,
|
|
427
|
+
});
|
|
428
|
+
writeDigest();
|
|
429
|
+
status(ctx, false);
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
pi.on("session_shutdown", async (event, ctx) => {
|
|
433
|
+
write({
|
|
434
|
+
t: "shutdown",
|
|
435
|
+
reason: (event as { reason?: string })?.reason,
|
|
436
|
+
turns,
|
|
437
|
+
tools,
|
|
438
|
+
tasks: taskCount,
|
|
439
|
+
lastTaskMs,
|
|
440
|
+
});
|
|
441
|
+
writeDigest();
|
|
442
|
+
stopTicker();
|
|
443
|
+
if (ctx.hasUI) ctx.ui.setStatus("workfeed", "");
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
447
|
+
ensureFiles(ctx);
|
|
448
|
+
const e = event as { messageType?: string; prompt?: string };
|
|
449
|
+
if (e.messageType && e.messageType !== "user") return;
|
|
450
|
+
task += 1;
|
|
451
|
+
taskActive = true;
|
|
452
|
+
taskStartTs = Date.now();
|
|
453
|
+
turns = 0;
|
|
454
|
+
tools = 0;
|
|
455
|
+
turnIndex = 0;
|
|
456
|
+
tokens = zeroTokens();
|
|
457
|
+
toolStarts = new Map();
|
|
458
|
+
write({
|
|
459
|
+
t: "prompt",
|
|
460
|
+
chars: (e.prompt ?? "").length,
|
|
461
|
+
...(CONTENT ? { text: stripSecrets(e.prompt ?? "").slice(0, 3000) } : {}),
|
|
462
|
+
model: ctx.model?.id,
|
|
463
|
+
thinking: ctx.thinkingLevel,
|
|
464
|
+
});
|
|
465
|
+
status(ctx, true);
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
pi.on("agent_start", async () => {
|
|
469
|
+
write({ t: "agent_start" });
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
pi.on("turn_start", async (event, ctx) => {
|
|
473
|
+
turnStartTs = Date.now();
|
|
474
|
+
turnIndex = (event as { turnIndex?: number })?.turnIndex ?? turnIndex + 1;
|
|
475
|
+
write({ t: "turn", phase: "start", turn: turnIndex, model: ctx.model?.id });
|
|
476
|
+
status(ctx, true);
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
pi.on("turn_end", async (event, ctx) => {
|
|
480
|
+
const e = event as {
|
|
481
|
+
turnIndex?: number;
|
|
482
|
+
outcome?: string;
|
|
483
|
+
message?: { usage?: Record<string, number>; stopReason?: string };
|
|
484
|
+
toolResults?: unknown[];
|
|
485
|
+
};
|
|
486
|
+
const dur = turnStartTs ? Date.now() - turnStartTs : undefined;
|
|
487
|
+
const usage = e.message?.usage;
|
|
488
|
+
if (usage) {
|
|
489
|
+
tokens.input += usage.input ?? 0;
|
|
490
|
+
tokens.output += usage.output ?? 0;
|
|
491
|
+
tokens.cacheRead += usage.cacheRead ?? 0;
|
|
492
|
+
tokens.cacheWrite += usage.cacheWrite ?? 0;
|
|
493
|
+
// self-hosted endpoints often send no total at all, some send 0:
|
|
494
|
+
// `??` cannot rescue a literal 0, so fall back on the parts we do have.
|
|
495
|
+
const reported = Math.max(usage.totalTokens ?? 0, usage.total ?? 0);
|
|
496
|
+
tokens.total +=
|
|
497
|
+
reported > 0
|
|
498
|
+
? reported
|
|
499
|
+
: (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
500
|
+
}
|
|
501
|
+
write({
|
|
502
|
+
t: "turn",
|
|
503
|
+
phase: "end",
|
|
504
|
+
turn: e.turnIndex ?? turnIndex,
|
|
505
|
+
durMs: dur,
|
|
506
|
+
outcome: e.outcome,
|
|
507
|
+
stopReason: e.message?.stopReason,
|
|
508
|
+
usage,
|
|
509
|
+
tools: e.toolResults?.length ?? 0,
|
|
510
|
+
});
|
|
511
|
+
turnStartTs = 0;
|
|
512
|
+
turns += 1;
|
|
513
|
+
status(ctx, true);
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
517
|
+
const e = event as { toolCallId?: string; toolName?: string; input?: unknown; parentToolCallId?: string };
|
|
518
|
+
const id = e.toolCallId || `${e.toolName}-${Date.now()}`;
|
|
519
|
+
// Ownership is frozen here: a long call must not be re-attributed if the
|
|
520
|
+
// todo list moves to another item while it runs.
|
|
521
|
+
toolStarts.set(id, { name: e.toolName ?? "?", ts: Date.now(), task, item });
|
|
522
|
+
currentTool = e.toolName;
|
|
523
|
+
tools += 1;
|
|
524
|
+
write({
|
|
525
|
+
t: "tool",
|
|
526
|
+
phase: "start",
|
|
527
|
+
id,
|
|
528
|
+
name: e.toolName,
|
|
529
|
+
parent: e.parentToolCallId,
|
|
530
|
+
args: slimArgs(e.toolName ?? "", e.input),
|
|
531
|
+
});
|
|
532
|
+
status(ctx, true);
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
pi.on("tool_execution_end", async (event, ctx) => {
|
|
536
|
+
const e = event as {
|
|
537
|
+
toolCallId?: string;
|
|
538
|
+
toolName?: string;
|
|
539
|
+
durationMs?: number;
|
|
540
|
+
isError?: boolean;
|
|
541
|
+
result?: { details?: Record<string, unknown> };
|
|
542
|
+
};
|
|
543
|
+
const id = e.toolCallId ?? "";
|
|
544
|
+
const start = toolStarts.get(id);
|
|
545
|
+
const out = textOf(e.result);
|
|
546
|
+
const outBytes = Buffer.byteLength(out, "utf8");
|
|
547
|
+
const ex = excerpt(stripSecrets(out));
|
|
548
|
+
const details = e.result?.details as Record<string, unknown> | undefined;
|
|
549
|
+
const exitCode = (details?.exitCode ?? details?.exit_code) as number | undefined;
|
|
550
|
+
const wallMs = start ? Date.now() - start.ts : undefined;
|
|
551
|
+
write({
|
|
552
|
+
t: "tool",
|
|
553
|
+
phase: "end",
|
|
554
|
+
id,
|
|
555
|
+
name: e.toolName,
|
|
556
|
+
parent: (e as { parentToolCallId?: string }).parentToolCallId,
|
|
557
|
+
durMs: e.durationMs,
|
|
558
|
+
wallMs,
|
|
559
|
+
isError: !!e.isError,
|
|
560
|
+
exitCode,
|
|
561
|
+
truncated: details?.truncated,
|
|
562
|
+
outBytes,
|
|
563
|
+
...(CONTENT ? { out: ex.out } : {}),
|
|
564
|
+
// Attribution stays where the call started, even if the todo list moved on.
|
|
565
|
+
// `item: undefined` deliberately overrides the line's current item (JSON drops it).
|
|
566
|
+
task: start ? start.task : task,
|
|
567
|
+
item: start ? start.item : item,
|
|
568
|
+
});
|
|
569
|
+
toolStarts.delete(id);
|
|
570
|
+
if (currentTool === e.toolName) currentTool = undefined;
|
|
571
|
+
status(ctx, true);
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
pi.on("user_bash", async (event) => {
|
|
575
|
+
const e = event as { command?: string };
|
|
576
|
+
write({
|
|
577
|
+
t: "user_bash",
|
|
578
|
+
chars: (e.command ?? "").length,
|
|
579
|
+
...(CONTENT ? { command: stripSecrets(e.command ?? "").slice(0, 4000) } : {}),
|
|
580
|
+
});
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
pi.on("after_provider_response", async (event) => {
|
|
584
|
+
const e = event as { status?: number; headers?: Record<string, string> };
|
|
585
|
+
if (typeof e.status === "number" && e.status >= 400) {
|
|
586
|
+
write({ t: "provider", status: e.status, requestId: e.headers?.["x-request-id"] });
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
// pi's contract (core/extensions/types.d.ts, SessionCompactEvent): { reason,
|
|
591
|
+
// compactionEntry, fromExtension, willRetry }. There is no messagesBefore/After — the
|
|
592
|
+
// only count pi hands over live is the token count on the entry. Reading fields that
|
|
593
|
+
// do not exist is how a stub-tested log ends up with an empty compaction row.
|
|
594
|
+
pi.on("session_compact", async (event) => {
|
|
595
|
+
const e = event as {
|
|
596
|
+
reason?: string;
|
|
597
|
+
compactionEntry?: { tokensBefore?: number };
|
|
598
|
+
willRetry?: boolean;
|
|
599
|
+
};
|
|
600
|
+
const before = e.compactionEntry?.tokensBefore;
|
|
601
|
+
write({
|
|
602
|
+
t: "compact",
|
|
603
|
+
reason: e.reason,
|
|
604
|
+
before: typeof before === "number" ? before : undefined,
|
|
605
|
+
willRetry: e.willRetry,
|
|
606
|
+
});
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
// Same problem here: the real failure text is `errorMessage`. A handler reading
|
|
610
|
+
// `error` logs every real failure as unexplained, and drops whether it was an abort.
|
|
611
|
+
pi.on("session_compact_failed", async (event) => {
|
|
612
|
+
const e = event as {
|
|
613
|
+
reason?: string;
|
|
614
|
+
errorMessage?: string;
|
|
615
|
+
aborted?: boolean;
|
|
616
|
+
willRetry?: boolean;
|
|
617
|
+
};
|
|
618
|
+
write({
|
|
619
|
+
t: "compact_failed",
|
|
620
|
+
reason: e.reason,
|
|
621
|
+
error: e.errorMessage,
|
|
622
|
+
aborted: e.aborted,
|
|
623
|
+
willRetry: e.willRetry,
|
|
624
|
+
});
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
pi.on("agent_settled", async (event) => {
|
|
628
|
+
const e = event as { aborted?: boolean };
|
|
629
|
+
// `before_agent_start` returns early for non-user messages (compaction, injected
|
|
630
|
+
// turns). Without this guard those settle with the *previous* task's counters
|
|
631
|
+
// and a duration of 0 — a ghost row that reads like a real task.
|
|
632
|
+
if (!taskActive) return;
|
|
633
|
+
const ms = taskStartTs ? Date.now() - taskStartTs : 0;
|
|
634
|
+
lastTaskMs = ms;
|
|
635
|
+
taskCount += 1;
|
|
636
|
+
taskStartTs = 0;
|
|
637
|
+
taskActive = false;
|
|
638
|
+
write({ t: "settle", taskMs: ms, aborted: !!e.aborted, turns, tools, tokens: { ...tokens } });
|
|
639
|
+
// Counters belong to the task that just closed: reset so nothing leaks into it.
|
|
640
|
+
turns = 0;
|
|
641
|
+
tools = 0;
|
|
642
|
+
turnIndex = 0;
|
|
643
|
+
tokens = zeroTokens();
|
|
644
|
+
toolStarts = new Map();
|
|
645
|
+
writeDigest();
|
|
646
|
+
status(uiCtx, false);
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
const summary = (): string => {
|
|
650
|
+
const lines = [
|
|
651
|
+
`log: ${logPath ?? "(not created)"}`,
|
|
652
|
+
`digest: ${digestPath ?? "(not created)"}`,
|
|
653
|
+
`session ${sid} · cwd ${cwd}`,
|
|
654
|
+
`tasks ${taskCount} · last ${fmtDur(lastTaskMs)} · current ${fmtDur(taskStartTs ? Date.now() - taskStartTs : 0)}`,
|
|
655
|
+
];
|
|
656
|
+
return lines.join("\n");
|
|
657
|
+
};
|
|
658
|
+
|
|
659
|
+
pi.registerCommand("workfeed", {
|
|
660
|
+
description: "Show the workfeed paths and this session's counters",
|
|
661
|
+
handler: async (_args, ctx) => {
|
|
662
|
+
ctx.ui.notify(summary(), "info");
|
|
663
|
+
},
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
// The digest is derived, so it can always be rebuilt from the log alone.
|
|
667
|
+
pi.registerCommand("workfeed-digest", {
|
|
668
|
+
description: "Rebuild the digest from the JSONL log (works after a restart)",
|
|
669
|
+
handler: async (_args, ctx) => {
|
|
670
|
+
writeDigest();
|
|
671
|
+
ctx.ui.notify(`digest rebuilt from ${logPath ?? "(no log yet)"}`, "info");
|
|
672
|
+
},
|
|
673
|
+
});
|
|
674
|
+
}
|