@cydm/pie 4.11.0 → 4.12.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.
Files changed (37) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +2 -2
  2. package/dist/builtin/extensions/cron/index.js +1 -1
  3. package/dist/builtin/extensions/im-forward/index.js +8670 -7364
  4. package/dist/builtin/extensions/mcp-adapter/index.js +1 -1
  5. package/dist/builtin/extensions/memory/index.js +171 -66
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +533 -50
  8. package/dist/builtin/extensions/plan-mode/index.js +2 -2
  9. package/dist/builtin/extensions/subagent/README.md +1 -1
  10. package/dist/builtin/extensions/subagent/index.js +3 -3
  11. package/dist/builtin/extensions/todo/index.js +2 -2
  12. package/dist/chunks/{auth-storage-C3FZMT7J.js → auth-storage-IJEJ2TGE.js} +1 -1
  13. package/dist/chunks/chunk-26ILLZKQ.js +400 -0
  14. package/dist/chunks/{chunk-KWK7KTSZ.js → chunk-322WLBDY.js} +1 -1
  15. package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
  16. package/dist/chunks/{chunk-BB7ETSJK.js → chunk-6U6UGM4C.js} +119 -3
  17. package/dist/chunks/{chunk-ZPJ3BNQB.js → chunk-BSITHT43.js} +1 -0
  18. package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
  19. package/dist/chunks/{chunk-B5GKDXVG.js → chunk-IZ4DYCJ7.js} +246 -80
  20. package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
  21. package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
  22. package/dist/chunks/{chunk-EWPPGYBU.js → chunk-OGGL6LUN.js} +55 -16
  23. package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
  24. package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
  25. package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
  26. package/dist/chunks/chunk-WTBLV6F5.js +476 -0
  27. package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
  28. package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-B6GIYTI7.js} +35 -13
  29. package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-WHER3WTJ.js} +284 -109
  30. package/dist/chunks/memory-git-C3S276QJ.js +19 -0
  31. package/dist/chunks/{model-registry-MGZO2RBN.js → model-registry-QNEPISBJ.js} +11 -3
  32. package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
  33. package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
  34. package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
  35. package/dist/cli.js +740 -512
  36. package/package.json +2 -2
  37. package/dist/chunks/chunk-L7XXKNZW.js +0 -386
@@ -1,18 +1,25 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
- liveSessionHolder
4
- } from "../../../chunks/chunk-KWK7KTSZ.js";
3
+ redactText
4
+ } from "../../../chunks/chunk-KW46ND3S.js";
5
+ import {
6
+ isCompactSummaryMessage
7
+ } from "../../../chunks/chunk-SXBX2P5R.js";
8
+ import "../../../chunks/chunk-BQWHLYYZ.js";
5
9
  import {
6
10
  registerWorkerLifecycleBridge,
7
11
  syncInheritedWorkerModels
8
- } from "../../../chunks/chunk-EWPPGYBU.js";
12
+ } from "../../../chunks/chunk-OGGL6LUN.js";
9
13
  import {
10
14
  readProcessCommandLine
11
15
  } from "../../../chunks/chunk-7RJXKN7N.js";
12
- import "../../../chunks/chunk-ZPJ3BNQB.js";
16
+ import {
17
+ liveSessionHolder
18
+ } from "../../../chunks/chunk-322WLBDY.js";
19
+ import "../../../chunks/chunk-BSITHT43.js";
13
20
  import {
14
21
  loadResolvedModelsConfig
15
- } from "../../../chunks/chunk-B5GKDXVG.js";
22
+ } from "../../../chunks/chunk-IZ4DYCJ7.js";
16
23
  import "../../../chunks/chunk-CBDQJMUI.js";
17
24
  import "../../../chunks/chunk-G2K4GY6N.js";
18
25
  import {
@@ -25,17 +32,159 @@ import { execFileSync, spawn } from "node:child_process";
25
32
  import { createRequire } from "node:module";
26
33
  import { fileURLToPath } from "node:url";
27
34
  import * as fs4 from "node:fs";
28
- import * as os2 from "node:os";
35
+ import * as os3 from "node:os";
29
36
  import * as path4 from "node:path";
30
37
 
31
38
  // builtin/extensions/pie-proc/panel-bridge.ts
32
39
  import * as fs from "node:fs";
40
+ import * as os from "node:os";
33
41
  import * as path from "node:path";
34
42
  var VALID_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-_]{5,63}$/;
43
+ var HEADER_PAGE_SIZE = 64;
44
+ var INDEX_CACHE_TTL_MS = 5e3;
45
+ var MAX_HEADS_TO_SCAN = 200;
46
+ var MAX_ENTRY_BODY_BYTES = 512 * 1024;
47
+ var MAX_HEADER_PAGES_TO_WALK = 8;
48
+ var MAX_BRANCH_HOPS = 256;
49
+ var MAX_SAFE_COMMITTED_SEQ = 1e7;
50
+ var TOOL_ONLY_PREVIEW = /^\[[a-zA-Z0-9_.:-]+\](?:\s*\[[a-zA-Z0-9_.:-]+\])*$/;
51
+ function isSymlinkSafe(filePath) {
52
+ try {
53
+ return fs.lstatSync(filePath).isSymbolicLink();
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+ function isContainedRealFile(containerDir, filePath) {
59
+ if (isSymlinkSafe(filePath)) return false;
60
+ try {
61
+ const realContainer = fs.realpathSync(containerDir);
62
+ const realFile = fs.realpathSync(filePath);
63
+ return realFile.startsWith(`${realContainer}${path.sep}`);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ function parseSessionHead(headFile, fallbackId, fallbackMtimeMs = 0) {
69
+ if (isSymlinkSafe(headFile)) return void 0;
70
+ try {
71
+ const raw = JSON.parse(fs.readFileSync(headFile, "utf8"));
72
+ if (raw.format !== "pie-session" || raw.version !== 3 || !raw.metadata || typeof raw.metadata !== "object") {
73
+ return void 0;
74
+ }
75
+ const meta = raw.metadata;
76
+ const id = typeof raw.id === "string" && VALID_SESSION_ID.test(raw.id) ? raw.id : fallbackId;
77
+ const rawName = typeof meta.name === "string" && meta.name.trim() ? meta.name.trim() : id;
78
+ const name = redactText(rawName).text;
79
+ const nameSource = typeof meta.nameSource === "string" && meta.nameSource.trim() ? meta.nameSource.trim() : void 0;
80
+ const cwd = typeof meta.cwd === "string" && meta.cwd.trim() ? meta.cwd.trim() : void 0;
81
+ const provider = typeof meta.provider === "string" && meta.provider.trim() ? meta.provider.trim() : void 0;
82
+ const modelId = typeof meta.modelId === "string" && meta.modelId.trim() ? meta.modelId.trim() : void 0;
83
+ const model = provider && modelId ? `${provider}/${modelId}` : modelId ?? void 0;
84
+ const thinkingLevel = typeof meta.thinkingLevel === "string" && meta.thinkingLevel.trim() ? meta.thinkingLevel.trim() : void 0;
85
+ const updatedAt = typeof meta.updatedAt === "number" && Number.isFinite(meta.updatedAt) ? meta.updatedAt : fallbackMtimeMs;
86
+ const createdAt = typeof meta.createdAt === "number" && Number.isFinite(meta.createdAt) ? meta.createdAt : void 0;
87
+ const messageCount = typeof meta.messageCount === "number" && Number.isSafeInteger(meta.messageCount) && meta.messageCount >= 0 ? meta.messageCount : 0;
88
+ const committedSeq = typeof raw.committedSeq === "number" && Number.isSafeInteger(raw.committedSeq) && raw.committedSeq >= 0 && raw.committedSeq <= MAX_SAFE_COMMITTED_SEQ ? raw.committedSeq : 0;
89
+ const activeEntryExplicitNull = meta.activeEntryId === null;
90
+ const activeEntryId = typeof meta.activeEntryId === "string" && meta.activeEntryId.trim() ? meta.activeEntryId.trim() : void 0;
91
+ return {
92
+ sessionId: id,
93
+ name,
94
+ ...nameSource ? { nameSource } : {},
95
+ ...cwd ? { cwd } : {},
96
+ ...model ? { model } : {},
97
+ ...thinkingLevel ? { thinkingLevel } : {},
98
+ updatedAt,
99
+ ...createdAt !== void 0 ? { createdAt } : {},
100
+ messageCount,
101
+ committedSeq,
102
+ ...activeEntryId ? { activeEntryId } : {},
103
+ ...activeEntryExplicitNull ? { activeEntryExplicitNull: true } : {}
104
+ };
105
+ } catch {
106
+ return void 0;
107
+ }
108
+ }
35
109
  function readSessionHeadCwd(headFile) {
110
+ return parseSessionHead(headFile, "session")?.cwd;
111
+ }
112
+ function isSystemTempPath(cwd) {
113
+ const normalized = path.resolve(cwd);
114
+ const tmpDir = path.resolve(os.tmpdir());
115
+ const prefixes = [tmpDir, "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"];
116
+ return prefixes.some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}${path.sep}`));
117
+ }
118
+ function isManagerSessionHead(head) {
119
+ if (head.nameSource === "curated" && head.name.trim().toLowerCase() === "manager") return true;
120
+ if (!head.cwd) return false;
121
+ const norm = head.cwd.replace(/[\\/]+$/, "");
122
+ return norm.endsWith(`${path.sep}.pie${path.sep}manager`) || norm.endsWith(`${path.sep}.pie${path.sep}concierge`);
123
+ }
124
+ function cleanTurnText(raw, role) {
125
+ let s = raw.trim();
126
+ if (!s) return "";
127
+ if (role === "user") {
128
+ if (s.startsWith("[pie-ipc]")) {
129
+ const unwrapped = s.replace(/^\[pie-ipc\][^\n]*says:\s*(?:\r?\n)?/, "").trim();
130
+ if (unwrapped) s = unwrapped;
131
+ }
132
+ s = s.replace(/^\[(?:Feishu|Lark|Slack|Telegram|Discord|IM)\]\s*(?:\r?\n)?/, "").trim();
133
+ s = s.replace(/^(?:<at\b[^>]*>[^<]*<\/at>\s*)+/, "").trim();
134
+ }
135
+ return s;
136
+ }
137
+ function extractEntryMessageText(sessionDir, seq) {
138
+ const entriesDir = path.join(sessionDir, "entries");
139
+ if (isSymlinkSafe(entriesDir)) return void 0;
140
+ const entryPath = path.join(entriesDir, `${seq}.json`);
141
+ if (!isContainedRealFile(sessionDir, entryPath)) return void 0;
36
142
  try {
37
- const head = JSON.parse(fs.readFileSync(headFile, "utf8"));
38
- return typeof head.metadata?.cwd === "string" && head.metadata.cwd.trim() ? head.metadata.cwd.trim() : void 0;
143
+ const st = fs.statSync(entryPath);
144
+ if (!st.isFile() || st.size > MAX_ENTRY_BODY_BYTES) return void 0;
145
+ const parsed = JSON.parse(fs.readFileSync(entryPath, "utf8"));
146
+ const content = parsed.message?.content;
147
+ if (typeof content === "string") return content;
148
+ if (Array.isArray(content)) {
149
+ const parts = [];
150
+ for (const block of content) {
151
+ if (block && typeof block === "object" && block.type === "text" && typeof block.text === "string") {
152
+ const piece = block.text.trim();
153
+ if (piece) parts.push(piece);
154
+ }
155
+ }
156
+ return parts.join("\n").trim();
157
+ }
158
+ return "";
159
+ } catch {
160
+ return void 0;
161
+ }
162
+ }
163
+ function loadHeaderPage(sessionDir, pageIndex) {
164
+ if (pageIndex < 0) return void 0;
165
+ const headersDir = path.join(sessionDir, "headers");
166
+ if (isSymlinkSafe(headersDir)) return void 0;
167
+ const pagePath = path.join(headersDir, `page-${pageIndex}.json`);
168
+ if (!isContainedRealFile(sessionDir, pagePath)) return void 0;
169
+ try {
170
+ const parsed = JSON.parse(fs.readFileSync(pagePath, "utf8"));
171
+ if (!Array.isArray(parsed.headers)) return void 0;
172
+ const out = [];
173
+ for (const item of parsed.headers) {
174
+ if (!item || typeof item !== "object") continue;
175
+ const rec = item;
176
+ if (typeof rec.seq !== "number" || typeof rec.id !== "string" || typeof rec.type !== "string") continue;
177
+ out.push({
178
+ seq: rec.seq,
179
+ id: rec.id,
180
+ parentSeq: typeof rec.parentSeq === "number" ? rec.parentSeq : null,
181
+ type: rec.type,
182
+ timestamp: typeof rec.timestamp === "number" ? rec.timestamp : 0,
183
+ ...typeof rec.role === "string" ? { role: rec.role } : {},
184
+ ...typeof rec.preview === "string" ? { preview: rec.preview } : {}
185
+ });
186
+ }
187
+ return out;
39
188
  } catch {
40
189
  return void 0;
41
190
  }
@@ -76,6 +225,274 @@ function findSessionSource(sessionId, deps) {
76
225
  return void 0;
77
226
  }
78
227
  function registerPieProcPanelBridge(deps) {
228
+ let rankedCache;
229
+ const invalidateIndexCache = () => {
230
+ rankedCache = void 0;
231
+ };
232
+ const scanRankedCandidates = () => {
233
+ const now = Date.now();
234
+ if (rankedCache && now - rankedCache.at < INDEX_CACHE_TTL_MS) {
235
+ return rankedCache.items;
236
+ }
237
+ const byId = /* @__PURE__ */ new Map();
238
+ const record = (cand) => {
239
+ const prev = byId.get(cand.sessionId);
240
+ if (!prev || cand.mtimeMs > prev.mtimeMs) {
241
+ byId.set(cand.sessionId, {
242
+ ...cand,
243
+ ...cand.workerName ?? prev?.workerName ? { workerName: cand.workerName ?? prev?.workerName } : {}
244
+ });
245
+ } else if (!prev.workerName && cand.workerName) {
246
+ byId.set(cand.sessionId, { ...prev, workerName: cand.workerName });
247
+ }
248
+ };
249
+ const opDir = deps.operatorSessionsDir();
250
+ try {
251
+ for (const entry of fs.readdirSync(opDir, { withFileTypes: true })) {
252
+ if (entry.isSymbolicLink() || !entry.isDirectory()) continue;
253
+ if (!VALID_SESSION_ID.test(entry.name)) continue;
254
+ const dirPath = path.join(opDir, entry.name);
255
+ const headPath = path.join(dirPath, "head.json");
256
+ try {
257
+ if (isSymlinkSafe(headPath)) continue;
258
+ const st = fs.statSync(headPath);
259
+ if (!st.isFile()) continue;
260
+ record({ sessionId: entry.name, dirPath, headPath, mtimeMs: st.mtimeMs, source: "global" });
261
+ } catch {
262
+ }
263
+ }
264
+ } catch {
265
+ }
266
+ const agentsDir = path.join(deps.pieProcDir(), "agents");
267
+ if (!isSymlinkSafe(agentsDir)) {
268
+ try {
269
+ for (const agent of fs.readdirSync(agentsDir, { withFileTypes: true })) {
270
+ if (agent.isSymbolicLink() || !agent.isDirectory() || !deps.safeName(agent.name)) continue;
271
+ const sessionsDir = path.join(agentsDir, agent.name, "sessions");
272
+ if (isSymlinkSafe(sessionsDir)) continue;
273
+ try {
274
+ for (const s of fs.readdirSync(sessionsDir, { withFileTypes: true })) {
275
+ if (s.isSymbolicLink() || !s.isDirectory() || !VALID_SESSION_ID.test(s.name)) continue;
276
+ const dirPath = path.join(sessionsDir, s.name);
277
+ const headPath = path.join(dirPath, "head.json");
278
+ try {
279
+ if (!isContainedRealFile(dirPath, headPath)) continue;
280
+ const st = fs.statSync(headPath);
281
+ if (!st.isFile()) continue;
282
+ record({
283
+ sessionId: s.name,
284
+ dirPath,
285
+ headPath,
286
+ mtimeMs: st.mtimeMs,
287
+ source: "isolated",
288
+ workerName: agent.name
289
+ });
290
+ } catch {
291
+ }
292
+ }
293
+ } catch {
294
+ }
295
+ }
296
+ } catch {
297
+ }
298
+ }
299
+ const items = Array.from(byId.values()).sort(
300
+ (a, b) => b.mtimeMs - a.mtimeMs || a.sessionId.localeCompare(b.sessionId)
301
+ );
302
+ rankedCache = { at: now, items };
303
+ return items;
304
+ };
305
+ const buildSummary = (cand, head, registryNames, allowCwdRoots) => {
306
+ const workerName = registryNames.get(head.sessionId) ?? cand.workerName;
307
+ const holder = liveSessionHolder(head.sessionId);
308
+ let cwdAllowed = false;
309
+ let canonicalCwd = head.cwd;
310
+ let resumeReason;
311
+ if (!head.cwd) {
312
+ resumeReason = "session has no recorded working directory";
313
+ } else {
314
+ try {
315
+ canonicalCwd = deps.cwdAllowedOrThrow(head.cwd, allowCwdRoots);
316
+ cwdAllowed = true;
317
+ } catch (error) {
318
+ resumeReason = error instanceof Error ? error.message : String(error);
319
+ }
320
+ }
321
+ if (holder) {
322
+ resumeReason = `session is already owned by a live host (pid ${holder.pid})`;
323
+ }
324
+ return {
325
+ cwdAllowed,
326
+ summary: {
327
+ sessionId: head.sessionId,
328
+ name: head.name,
329
+ ...head.nameSource ? { nameSource: head.nameSource } : {},
330
+ ...workerName ? { workerName } : {},
331
+ ...canonicalCwd ? { cwd: canonicalCwd } : {},
332
+ ...head.model ? { model: head.model } : {},
333
+ ...head.thinkingLevel ? { thinkingLevel: head.thinkingLevel } : {},
334
+ updatedAt: Math.max(head.updatedAt, Math.floor(cand.mtimeMs)),
335
+ ...head.createdAt !== void 0 ? { createdAt: head.createdAt } : {},
336
+ messageCount: head.messageCount,
337
+ resumable: cwdAllowed && !holder,
338
+ ...resumeReason ? { resumeReason } : {},
339
+ ...holder ? { livePid: holder.pid } : {},
340
+ source: cand.source
341
+ }
342
+ };
343
+ };
344
+ const listRecentSessions = (opts) => {
345
+ const limit = Math.min(Math.max(1, Math.floor(opts?.limit ?? 10)), 50);
346
+ const offset = Math.max(0, Math.floor(opts?.offset ?? 0));
347
+ const includeEmpty = opts?.includeEmpty === true;
348
+ const excludeSet = new Set(opts?.excludeSessionIds ?? []);
349
+ const onlySet = opts?.onlySessionIds;
350
+ const allowCwdRoots = deps.allowCwd();
351
+ const registryNames = /* @__PURE__ */ new Map();
352
+ try {
353
+ for (const w of deps.readWorkers()) registryNames.set(w.sessionId, w.name);
354
+ } catch {
355
+ }
356
+ const ranked = scanRankedCandidates();
357
+ const matched = [];
358
+ let headsRead = 0;
359
+ let truncated = false;
360
+ for (const cand of ranked) {
361
+ if (excludeSet.has(cand.sessionId)) continue;
362
+ if (onlySet && !onlySet.has(cand.sessionId)) continue;
363
+ if (headsRead >= MAX_HEADS_TO_SCAN) {
364
+ truncated = true;
365
+ break;
366
+ }
367
+ headsRead += 1;
368
+ const head = parseSessionHead(cand.headPath, cand.sessionId, Math.floor(cand.mtimeMs));
369
+ if (!head) continue;
370
+ if (!includeEmpty) {
371
+ if (head.messageCount <= 0) continue;
372
+ if (isManagerSessionHead(head)) continue;
373
+ if (head.name.startsWith("[im-forward-dispatch]")) continue;
374
+ }
375
+ const { summary, cwdAllowed } = buildSummary(cand, head, registryNames, allowCwdRoots);
376
+ if (!includeEmpty && head.cwd && isSystemTempPath(head.cwd) && !cwdAllowed) continue;
377
+ matched.push(summary);
378
+ }
379
+ matched.sort((a, b) => b.updatedAt - a.updatedAt || a.sessionId.localeCompare(b.sessionId));
380
+ return {
381
+ sessions: matched.slice(offset, offset + limit),
382
+ total: matched.length,
383
+ ...truncated ? { truncated: true } : {}
384
+ };
385
+ };
386
+ const readSessionRecentTurns = (sessionId, opts) => {
387
+ if (!VALID_SESSION_ID.test(sessionId)) {
388
+ return { ok: false, turns: [], error: "invalid session id" };
389
+ }
390
+ const maxTurns = Math.min(Math.max(1, Math.floor(opts?.maxTurns ?? 6)), 12);
391
+ const maxChars = Math.min(Math.max(80, Math.floor(opts?.maxCharsPerTurn ?? 320)), 1200);
392
+ let cand = scanRankedCandidates().find((c) => c.sessionId === sessionId);
393
+ if (!cand) {
394
+ invalidateIndexCache();
395
+ cand = scanRankedCandidates().find((c) => c.sessionId === sessionId);
396
+ }
397
+ if (!cand) {
398
+ return { ok: false, turns: [], error: `session "${sessionId}" not found` };
399
+ }
400
+ const head = parseSessionHead(cand.headPath, cand.sessionId, Math.floor(cand.mtimeMs));
401
+ if (!head) {
402
+ return { ok: false, turns: [], error: `session "${sessionId}" head is unreadable` };
403
+ }
404
+ const registryNames = /* @__PURE__ */ new Map();
405
+ try {
406
+ for (const w of deps.readWorkers()) registryNames.set(w.sessionId, w.name);
407
+ } catch {
408
+ }
409
+ const { summary } = buildSummary(cand, head, registryNames, deps.allowCwd());
410
+ if (head.committedSeq <= 0 || head.activeEntryExplicitNull) {
411
+ return { ok: true, session: summary, turns: [] };
412
+ }
413
+ const pageCache = /* @__PURE__ */ new Map();
414
+ let pagesLoaded = 0;
415
+ const getPage = (pageIndex) => {
416
+ if (pageCache.has(pageIndex)) return pageCache.get(pageIndex);
417
+ if (pagesLoaded >= MAX_HEADER_PAGES_TO_WALK) return void 0;
418
+ pagesLoaded += 1;
419
+ const loaded = loadHeaderPage(cand.dirPath, pageIndex);
420
+ if (loaded) pageCache.set(pageIndex, loaded);
421
+ return loaded;
422
+ };
423
+ const findHeaderBySeq = (seq) => {
424
+ if (seq < 1 || seq > head.committedSeq) return void 0;
425
+ const page = getPage(Math.floor((seq - 1) / HEADER_PAGE_SIZE));
426
+ return page?.find((h) => h.seq === seq);
427
+ };
428
+ const headersToInspect = [];
429
+ const lastPageIdx = Math.floor((head.committedSeq - 1) / HEADER_PAGE_SIZE);
430
+ if (head.activeEntryId) {
431
+ let activeHeader;
432
+ const seqHintMatch = /^e(\d+)-/.exec(head.activeEntryId);
433
+ if (seqHintMatch) {
434
+ const hintSeq = Number(seqHintMatch[1]);
435
+ if (Number.isSafeInteger(hintSeq) && hintSeq >= 1 && hintSeq <= head.committedSeq) {
436
+ const hinted = getPage(Math.floor((hintSeq - 1) / HEADER_PAGE_SIZE));
437
+ const candidate = hinted?.find((h) => h.seq === hintSeq && h.id === head.activeEntryId);
438
+ if (candidate) activeHeader = candidate;
439
+ }
440
+ }
441
+ for (let p = lastPageIdx, checked = 0; !activeHeader && p >= 0 && checked < MAX_HEADER_PAGES_TO_WALK; p -= 1, checked += 1) {
442
+ const page = getPage(p);
443
+ if (!page) continue;
444
+ const found = page.find((h) => h.id === head.activeEntryId);
445
+ if (found) activeHeader = found;
446
+ }
447
+ if (activeHeader) {
448
+ let cur = activeHeader;
449
+ const seen = /* @__PURE__ */ new Set();
450
+ for (let hops = 0; cur && hops < MAX_BRANCH_HOPS; hops += 1) {
451
+ if (seen.has(cur.seq)) break;
452
+ seen.add(cur.seq);
453
+ headersToInspect.push(cur);
454
+ cur = cur.parentSeq !== null ? findHeaderBySeq(cur.parentSeq) : void 0;
455
+ }
456
+ }
457
+ } else {
458
+ for (let p = lastPageIdx, checked = 0; p >= 0 && checked < MAX_HEADER_PAGES_TO_WALK; p -= 1, checked += 1) {
459
+ const page = getPage(p);
460
+ if (!page) continue;
461
+ for (let i = page.length - 1; i >= 0; i -= 1) {
462
+ const h = page[i];
463
+ if (h.seq <= head.committedSeq) headersToInspect.push(h);
464
+ }
465
+ }
466
+ }
467
+ const collected = [];
468
+ for (const header of headersToInspect) {
469
+ if (collected.length >= maxTurns) break;
470
+ if (header.type !== "message") continue;
471
+ if (header.role !== "user" && header.role !== "assistant") continue;
472
+ const role = header.role;
473
+ let rawText = extractEntryMessageText(cand.dirPath, header.seq);
474
+ if (rawText === void 0) {
475
+ const preview = header.preview?.trim() ?? "";
476
+ if (!preview || role === "assistant" && TOOL_ONLY_PREVIEW.test(preview)) continue;
477
+ rawText = preview;
478
+ }
479
+ const cleaned = cleanTurnText(rawText, role);
480
+ if (!cleaned) continue;
481
+ if (role === "user" && isCompactSummaryMessage(cleaned)) continue;
482
+ const redacted = redactText(cleaned).text.replace(/\r\n/g, "\n");
483
+ const truncated = redacted.length > maxChars;
484
+ const text = truncated ? `${redacted.slice(0, maxChars - 1).trimEnd()}\u2026` : redacted;
485
+ collected.push({
486
+ seq: header.seq,
487
+ role,
488
+ timestamp: header.timestamp,
489
+ text,
490
+ ...truncated ? { truncated: true } : {}
491
+ });
492
+ }
493
+ collected.reverse();
494
+ return { ok: true, session: summary, turns: collected };
495
+ };
79
496
  const inspectResumable = (sessionId) => {
80
497
  const found = findSessionSource(sessionId, deps);
81
498
  if (!found) return void 0;
@@ -126,6 +543,7 @@ function registerPieProcPanelBridge(deps) {
126
543
  }
127
544
  }
128
545
  const res = await deps.killWorker(name, opts);
546
+ invalidateIndexCache();
129
547
  return { ok: res.isError !== true, detail: res.content[0]?.text ?? "done" };
130
548
  } catch (error) {
131
549
  return { ok: false, detail: error instanceof Error ? error.message : String(error) };
@@ -139,19 +557,22 @@ function registerPieProcPanelBridge(deps) {
139
557
  const hasWorkerIm = fs.existsSync(path.join(deps.pieProcDir(), "agents", info.name, "im-forward.json"));
140
558
  const inheritIm = !hasWorkerIm && deps.canInheritImForward();
141
559
  const res = await deps.spawnResumeWorker({ name: info.name, cwd: info.cwd, resumeSessionId: sessionId, inheritIm });
560
+ invalidateIndexCache();
142
561
  const detail = res.content[0]?.text ?? "spawned";
143
562
  const pidMatch = /\bpid (\d+)\b/.exec(detail);
144
563
  return { ok: res.isError !== true, detail, name: info.name, ...pidMatch ? { pid: Number(pidMatch[1]) } : {} };
145
564
  } catch (error) {
146
565
  return { ok: false, detail: error instanceof Error ? error.message : String(error) };
147
566
  }
148
- }
567
+ },
568
+ listRecentSessions,
569
+ readSessionRecentTurns
149
570
  });
150
571
  }
151
572
 
152
573
  // builtin/extensions/pie-proc/proc-config.ts
153
574
  import * as fs2 from "node:fs";
154
- import * as os from "node:os";
575
+ import * as os2 from "node:os";
155
576
  import * as path2 from "node:path";
156
577
  var DEFAULT_MAX_WORKERS = 50;
157
578
  var DEFAULT_CONFIG = {
@@ -161,11 +582,11 @@ var DEFAULT_CONFIG = {
161
582
  defaultTtlMs: 0
162
583
  };
163
584
  function expandTilde(p) {
164
- return p === "~" ? os.homedir() : p.startsWith("~/") ? path2.join(os.homedir(), p.slice(2)) : p;
585
+ return p === "~" ? os2.homedir() : p.startsWith("~/") ? path2.join(os2.homedir(), p.slice(2)) : p;
165
586
  }
166
587
  function configDirRoot() {
167
588
  const env = process.env.PIE_CODING_AGENT_DIR;
168
- if (!env) return path2.join(os.homedir(), ".pie");
589
+ if (!env) return path2.join(os2.homedir(), ".pie");
169
590
  return path2.resolve(expandTilde(env));
170
591
  }
171
592
  function configCandidates() {
@@ -174,8 +595,8 @@ function configCandidates() {
174
595
  if (pinnedRoot) {
175
596
  const pinDerived = path2.join(path2.dirname(path2.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
176
597
  if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
177
- } else if (configDirRoot() !== path2.join(os.homedir(), ".pie")) {
178
- candidates.push(path2.join(os.homedir(), ".pie", "pie-proc.json"));
598
+ } else if (configDirRoot() !== path2.join(os2.homedir(), ".pie")) {
599
+ candidates.push(path2.join(os2.homedir(), ".pie", "pie-proc.json"));
179
600
  }
180
601
  return candidates;
181
602
  }
@@ -436,7 +857,7 @@ async function waitForWorkerIpcReady(opts) {
436
857
  if (!isPidAlive(opts.pid)) return { exitedEarly: true };
437
858
  const remaining = deadline - Date.now();
438
859
  if (remaining <= 0) break;
439
- await new Promise((resolve4) => setTimeout(resolve4, Math.min(pollMs, remaining)));
860
+ await new Promise((resolve5) => setTimeout(resolve5, Math.min(pollMs, remaining)));
440
861
  }
441
862
  return { peer: readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid), exitedEarly: !isPidAlive(opts.pid) };
442
863
  }
@@ -498,14 +919,34 @@ function resolveOperatorSessionsDir() {
498
919
  } catch {
499
920
  const override = process.env.PIE_SESSIONS_DIR;
500
921
  if (override !== void 0 && override !== "") {
501
- if (override === "~") return path4.join(os2.homedir(), ".pie", "sessions");
502
- if (override.startsWith("~/")) return path4.join(os2.homedir(), override.slice(2));
922
+ if (override === "~") return path4.join(os3.homedir(), ".pie", "sessions");
923
+ if (override.startsWith("~/")) return path4.join(os3.homedir(), override.slice(2));
503
924
  if (path4.isAbsolute(override)) return override;
504
925
  }
505
- return path4.join(os2.homedir(), ".pie", "sessions");
926
+ return path4.join(os3.homedir(), ".pie", "sessions");
506
927
  }
507
928
  }
508
- var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
929
+ var IM_FORWARD_CONTROL_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "retryBackoffMs"]);
930
+ var IM_FORWARD_FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["providers", "__proto__", "constructor", "prototype", "toString", "valueOf"]);
931
+ var SAFE_PROVIDER_ID = /^[a-z][a-z0-9_-]{0,31}$/i;
932
+ var SAFE_IM_FIELD_KEY = /^[a-zA-Z][a-zA-Z0-9_-]{0,47}$/;
933
+ function isOperatorOnlyImKey(key) {
934
+ if (/(?:^|[_-])(?:cli|bin|env|args|cwd)$|(?:Cli|Bin|Env|Args|Cwd)$/.test(key)) return true;
935
+ if (/(?:^|[_-])(?:binary|cmd|command|exec|executable|path|script|shell|argv|launcher)(?:$|[_-])|(?:Binary|Cmd|Command|Exec|Executable|Path|Script|Shell|Argv|Launcher)(?:$|[A-Z0-9_-])/.test(key)) return true;
936
+ return false;
937
+ }
938
+ function isCredentialLikeImKey(key) {
939
+ return /(?:^|[_-])(?:token|secret|password|passwd|apikey|api_key|privatekey|cookie)$|(?:Token|Secret|Password|Passwd|ApiKey|PrivateKey|Cookie)$/.test(key);
940
+ }
941
+ function isSafeImIdentityValue(value) {
942
+ if (typeof value === "boolean") return true;
943
+ if (typeof value === "number") return Number.isFinite(value);
944
+ if (typeof value === "string") return value.length <= 512;
945
+ if (Array.isArray(value)) {
946
+ return value.length <= 256 && value.every((item) => typeof item === "string" && item.length <= 512);
947
+ }
948
+ return false;
949
+ }
509
950
  var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
510
951
  var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
511
952
  function pieProcDir() {
@@ -752,7 +1193,7 @@ function workerLiveness(record, opts = {}) {
752
1193
  if (groupProbe === "eperm") return "unknown";
753
1194
  const hasSpawnedAt = typeof record.spawnedAt === "number" && Number.isFinite(record.spawnedAt);
754
1195
  if (!hasSpawnedAt) return "unknown";
755
- const bootAtMs = Date.now() - os2.uptime() * 1e3;
1196
+ const bootAtMs = Date.now() - os3.uptime() * 1e3;
756
1197
  if (record.spawnedAt < bootAtMs - 5e3) return "dead";
757
1198
  const members = readProcessGroupMembers(record.pid);
758
1199
  if (members === void 0) return "unknown";
@@ -787,33 +1228,68 @@ function sanitizeImForward(raw) {
787
1228
  }
788
1229
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error('imForward must be an object, "inherit", or {inherit:true}');
789
1230
  const source = raw;
790
- const out = {};
1231
+ const out = /* @__PURE__ */ Object.create(null);
791
1232
  for (const [key, value] of Object.entries(source)) {
792
1233
  if (key === "inherit") continue;
793
- if (!IM_FORWARD_ALLOWED_KEYS.has(key)) {
794
- throw new Error(`imForward field "${key}" is not allowed (executable/path selection is operator-only config). Allowed: inherit, ${[...IM_FORWARD_ALLOWED_KEYS].join(", ")}`);
1234
+ if (IM_FORWARD_FORBIDDEN_KEYS.has(key) || !SAFE_IM_FIELD_KEY.test(key) || isOperatorOnlyImKey(key) || isCredentialLikeImKey(key)) {
1235
+ throw new Error(`imForward field "${key}" is not allowed (executable/path/credential selection is operator-only config). Use "inherit" or safe identity fields only.`);
1236
+ }
1237
+ if (key === "enabled") {
1238
+ if (typeof value !== "boolean") throw new Error('imForward field "enabled" must be a boolean');
1239
+ out.enabled = value;
1240
+ continue;
1241
+ }
1242
+ if (key === "provider") {
1243
+ if (typeof value !== "string" || !SAFE_PROVIDER_ID.test(value.trim())) {
1244
+ throw new Error('imForward field "provider" must be a valid provider id');
1245
+ }
1246
+ out.provider = value.trim();
1247
+ continue;
1248
+ }
1249
+ if (key === "retryBackoffMs") {
1250
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1251
+ throw new Error('imForward field "retryBackoffMs" must be a finite number');
1252
+ }
1253
+ out.retryBackoffMs = value;
1254
+ continue;
1255
+ }
1256
+ if (!isSafeImIdentityValue(value)) {
1257
+ throw new Error(`imForward field "${key}" must be a primitive or string array (nested objects are not allowed)`);
795
1258
  }
796
1259
  out[key] = value;
797
1260
  }
798
- return out;
1261
+ if (typeof out.provider !== "string" || !out.provider) {
1262
+ throw new Error('imForward requires a non-empty "provider" id (or use "inherit")');
1263
+ }
1264
+ return { ...out };
799
1265
  }
800
1266
  function readUserImForwardIdentity() {
801
1267
  try {
802
- const candidates = [path4.join(configDirRoot(), "im-forward.json")];
803
- for (const file of candidates) {
804
- try {
805
- const parsed = JSON.parse(fs4.readFileSync(file, "utf8"));
806
- const provider = typeof parsed.provider === "string" ? parsed.provider : "feishu";
807
- const settings = parsed.providers?.[provider];
808
- if (!settings) continue;
809
- const identity = { provider };
810
- for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
811
- if (settings[key] !== void 0) identity[key] = settings[key];
812
- }
813
- return identity;
814
- } catch {
815
- }
1268
+ const file = path4.join(configDirRoot(), "im-forward.json");
1269
+ const parsed = JSON.parse(fs4.readFileSync(file, "utf8"));
1270
+ const providersObj = parsed.providers && typeof parsed.providers === "object" && !Array.isArray(parsed.providers) ? parsed.providers : void 0;
1271
+ if (!providersObj) return void 0;
1272
+ let provider;
1273
+ if (typeof parsed.provider === "string" && SAFE_PROVIDER_ID.test(parsed.provider.trim())) {
1274
+ provider = parsed.provider.trim();
1275
+ } else if (!("provider" in parsed)) {
1276
+ const keys = Object.keys(providersObj).filter((k) => SAFE_PROVIDER_ID.test(k));
1277
+ if (keys.length === 1) provider = keys[0];
1278
+ }
1279
+ if (!provider) return void 0;
1280
+ const settings = providersObj[provider];
1281
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) return void 0;
1282
+ const identity = { provider };
1283
+ for (const [key, value] of Object.entries(settings)) {
1284
+ if (IM_FORWARD_CONTROL_KEYS.has(key) || IM_FORWARD_FORBIDDEN_KEYS.has(key)) continue;
1285
+ if (!SAFE_IM_FIELD_KEY.test(key) || isOperatorOnlyImKey(key)) continue;
1286
+ if (!isSafeImIdentityValue(value)) continue;
1287
+ identity[key] = value;
816
1288
  }
1289
+ if (typeof parsed.retryBackoffMs === "number" && Number.isFinite(parsed.retryBackoffMs)) {
1290
+ identity.retryBackoffMs = parsed.retryBackoffMs;
1291
+ }
1292
+ return identity;
817
1293
  } catch {
818
1294
  }
819
1295
  return void 0;
@@ -1141,18 +1617,25 @@ function pieProc(ctx) {
1141
1617
  if (imForward) {
1142
1618
  const imFile = path4.join(pieDir, "im-forward.json");
1143
1619
  if (!fs4.existsSync(imFile)) {
1144
- const provider = typeof imForward.provider === "string" && imForward.provider.trim() ? imForward.provider : "feishu";
1145
- const providerSettings = {};
1146
- for (const key of ["chatId", "openId", "allowUsers", "larkCliProfile"]) {
1147
- if (imForward[key] !== void 0) providerSettings[key] = imForward[key];
1620
+ const provider = typeof imForward.provider === "string" ? imForward.provider.trim() : "";
1621
+ if (provider && SAFE_PROVIDER_ID.test(provider)) {
1622
+ const providerSettings = {};
1623
+ for (const [key, value] of Object.entries(imForward)) {
1624
+ if (IM_FORWARD_CONTROL_KEYS.has(key) || IM_FORWARD_FORBIDDEN_KEYS.has(key)) continue;
1625
+ if (!SAFE_IM_FIELD_KEY.test(key) || isOperatorOnlyImKey(key)) continue;
1626
+ if (!isSafeImIdentityValue(value)) continue;
1627
+ providerSettings[key] = value;
1628
+ }
1629
+ const doc = {
1630
+ enabled: imForward.enabled === true,
1631
+ provider,
1632
+ providers: { [provider]: providerSettings }
1633
+ };
1634
+ if (typeof imForward.retryBackoffMs === "number" && Number.isFinite(imForward.retryBackoffMs)) {
1635
+ doc.retryBackoffMs = imForward.retryBackoffMs;
1636
+ }
1637
+ fs4.writeFileSync(imFile, JSON.stringify(doc, null, " "));
1148
1638
  }
1149
- const doc = {
1150
- enabled: imForward.enabled === true,
1151
- provider,
1152
- providers: { [provider]: providerSettings }
1153
- };
1154
- if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
1155
- fs4.writeFileSync(imFile, JSON.stringify(doc, null, " "));
1156
1639
  }
1157
1640
  }
1158
1641
  fs4.mkdirSync(logDir(), { recursive: true });
@@ -1364,7 +1847,7 @@ function pieProc(ctx) {
1364
1847
  thinkingLevel: Type.Optional(Type.String({ description: "spawn: optional thinking level override (off|minimal|low|medium|high|xhigh|max)" })),
1365
1848
  ttlMs: Type.Optional(Type.Number({ description: "spawn (resident only): idle TTL in ms (0 = never reap)", minimum: 0, maximum: 864e5 })),
1366
1849
  force: Type.Optional(Type.Boolean({ description: "kill: skip graceful SIGTERM" })),
1367
- imForward: Type.Optional(Type.Union([Type.Literal("inherit"), Type.Record(Type.String(), Type.Unknown())], { description: "spawn (resident only): IM identity binding \u2014 'inherit' copies the operator's user-layer IM identity verbatim (recommended: open_ids are per-app, hand copies break silently), or an object of identity fields only (enabled/provider/chatId/openId/allowUsers/larkCliProfile/inherit)" })),
1850
+ imForward: Type.Optional(Type.Union([Type.Literal("inherit"), Type.Record(Type.String(), Type.Unknown())], { description: "spawn (resident only): IM identity binding \u2014 'inherit' copies the operator's user-layer IM identity verbatim (recommended: user IDs are per-app, hand copies break silently), or an object of provider-neutral identity fields only (enabled/provider/allowUsers/inherit; executable/path/credential keys are rejected)" })),
1368
1851
  resumeSessionId: Type.Optional(Type.String({ description: "spawn (resident only): RESUME an existing business session instead of creating a new one. The session must exist in the global store (~/.pie/sessions), its recorded cwd must equal cwd, and no live host may own it. The worker keeps the session's context, IM topic anchors and model; its own config stays isolated. Use when the user wants an old session to CONTINUE its work (e.g. '\u8BA9 TBD \u7684\u90A3\u4E2A\u4F1A\u8BDD\u63A5\u7740\u67E5'), never for fresh tasks." }))
1369
1852
  }),
1370
1853
  risk: { riskClass: "process_lifecycle", requiresPermission: true, externalSideEffect: true, readsNetwork: false, writesNetwork: false, concurrencySafe: false },