pi-pier 0.3.1 → 0.4.2

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 (54) hide show
  1. package/README.md +7 -5
  2. package/package.json +3 -3
  3. package/schemas/efficiency-config.schema.json +6 -0
  4. package/src/ask-dialog.ts +9 -2
  5. package/src/ask-user.ts +142 -74
  6. package/src/bootstrap.ts +2 -1
  7. package/src/compact-coordinator.ts +207 -35
  8. package/src/compact-economics-core.ts +62 -29
  9. package/src/config-catalog-core.ts +1 -0
  10. package/src/cordis-services.ts +64 -0
  11. package/src/dashboard-command.ts +40 -15
  12. package/src/delegation-core.ts +115 -0
  13. package/src/efficiency-config-core.ts +17 -6
  14. package/src/efficiency-store.ts +43 -6
  15. package/src/guards.ts +6 -0
  16. package/src/herdr-client.ts +141 -36
  17. package/src/history-store.ts +2 -0
  18. package/src/index-gates.ts +6 -12
  19. package/src/index-master.ts +12 -16
  20. package/src/index-pipe.ts +6 -0
  21. package/src/index-runtime.ts +14 -0
  22. package/src/index-worker.ts +4 -10
  23. package/src/index.ts +310 -76
  24. package/src/jev-client.ts +32 -7
  25. package/src/jev-core.ts +71 -36
  26. package/src/observation-core.ts +13 -1
  27. package/src/panel-open.ts +47 -0
  28. package/src/pier-options.ts +1 -2
  29. package/src/pipe-channel.ts +9 -0
  30. package/src/plugins/heat-plan.ts +18 -3
  31. package/src/plugins/observation.ts +118 -46
  32. package/src/plugins/subagent.ts +119 -68
  33. package/src/plugins/terminal.ts +221 -57
  34. package/src/plugins/todo.ts +63 -63
  35. package/src/reducer-core.ts +3 -5
  36. package/src/reducer-invoker.ts +27 -13
  37. package/src/renderers.ts +25 -2
  38. package/src/role-manifest.ts +2 -3
  39. package/src/roles/worker-default.json +2 -2
  40. package/src/settle-wake-core.ts +17 -3
  41. package/src/subagent-core.ts +209 -3
  42. package/src/subagent-poller.ts +69 -19
  43. package/src/subagent-session.ts +67 -4
  44. package/src/subagent-spawn.ts +55 -7
  45. package/src/terminal-core.ts +178 -50
  46. package/src/todo-core.ts +47 -2
  47. package/src/todo-read-hook.ts +54 -17
  48. package/src/todo-reminder-core.ts +9 -5
  49. package/src/todo-window.ts +8 -4
  50. package/src/todos-service.ts +12 -0
  51. package/src/tree-view.ts +162 -0
  52. package/src/vocab.ts +7 -1
  53. package/src/worker-marker.ts +76 -0
  54. package/src/focus-poller.ts +0 -223
@@ -11,7 +11,7 @@ import type {
11
11
  } from '@earendil-works/pi-coding-agent';
12
12
  import { Type } from 'typebox';
13
13
  import { containsReducerReceipt, countLines, deriveObservationId, estimateTokens, formatObservationPlaceholder, isObservationId, sha256Hex, shouldPackForCache } from '../observation-core.ts';
14
- import { appendEfficiencyLog, efficiencyLogPath, observationObjectPath, readStoredObjectChunk, resolveSessionRoot, storeContentAddressedObject } from '../efficiency-store.ts';
14
+ import { appendEfficiencyLog, efficiencyLogPath, observationObjectExists, observationObjectPath, readStoredObjectChunk, resolveSessionRoot, storeContentAddressedObject } from '../efficiency-store.ts';
15
15
  import { resolveEfficiencyConfig, type EfficiencyConfig, type ObservationPackConfig } from '../efficiency-config-core.ts';
16
16
  import { resolveCacheRatioFromCost } from '../compact-economics-core.ts';
17
17
  import { planToolGate, type RuntimeRoleManifest } from '../tool-gate.ts';
@@ -51,14 +51,13 @@ function buildPlaceholder(
51
51
  toolCallId: string,
52
52
  text: string,
53
53
  textBytes: number,
54
+ contentHash: string,
54
55
  obsConfig: ObservationPackConfig,
55
56
  middle?: ExcerptMiddlePick,
56
- ): { id: string; placeholder: string; contentHash: string } {
57
- const contentHash = sha256Hex(text);
57
+ ): { id: string; placeholder: string } {
58
58
  const id = deriveObservationId(toolName, toolCallId, contentHash);
59
59
  return {
60
60
  id,
61
- contentHash,
62
61
  placeholder: formatObservationPlaceholder({
63
62
  id,
64
63
  toolName,
@@ -77,6 +76,20 @@ function memoKeyFor(sessionRoot: string, toolCallId: string, charLength: number)
77
76
  return `${sessionRoot}:${toolCallId}:${charLength}`;
78
77
  }
79
78
 
79
+ function rememberPlaceholder(
80
+ sessionRoot: string,
81
+ toolCallId: string,
82
+ charLength: number,
83
+ placeholder: string,
84
+ obsId: string,
85
+ ): void {
86
+ if (placeholderMemo.size >= MAX_MEMO_ENTRIES) {
87
+ const oldest = placeholderMemo.keys().next().value;
88
+ if (oldest) placeholderMemo.delete(oldest);
89
+ }
90
+ placeholderMemo.set(memoKeyFor(sessionRoot, toolCallId, charLength), { placeholder, obsId });
91
+ }
92
+
80
93
  /** Append one observation.jsonl record; telemetry is always best-effort. */
81
94
  async function logObservation(sessionRoot: string, fields: Record<string, unknown>): Promise<void> {
82
95
  try {
@@ -100,8 +113,12 @@ interface ExcerptMiddlePick {
100
113
  label: string;
101
114
  }
102
115
 
103
- /** P0-3 seam: async middle-window picker (jev-backed); null keeps the legacy head+tail halves. */
104
- export type PickMiddleExcerpt = (text: string, excerptBudgetBytes: number) => Promise<ExcerptMiddlePick | null>;
116
+ /** P0-3 seam: batched middle-window picker (jev-backed), one result per item in order; null keeps
117
+ * the legacy head+tail halves. A whole compaction batch is one call. */
118
+ export type PickMiddleExcerpts = (
119
+ items: ReadonlyArray<{ obsId: string; text: string }>,
120
+ excerptBudgetBytes: number,
121
+ ) => Promise<ReadonlyArray<ExcerptMiddlePick | null>>;
105
122
 
106
123
  /** Build the OCC `onBeforeCompact` hook: role-gated, config-gated batch packing of the branch's
107
124
  * large tool results before `ctx.compact()` rewrites the prefix. Exported so the gate behaviour is
@@ -110,7 +127,7 @@ export function createCompactionBatchPackHook(deps: {
110
127
  getObsConfig: () => ObservationPackConfig;
111
128
  getManifest?: () => RuntimeRoleManifest | null;
112
129
  getSessionId?: () => string | undefined;
113
- pickMiddleExcerpt?: PickMiddleExcerpt;
130
+ pickMiddleExcerpts?: PickMiddleExcerpts;
114
131
  }): (sessionRoot: string, ctx: unknown) => Promise<void> {
115
132
  return async (sessionRoot: string, ctx: unknown): Promise<void> => {
116
133
  const obsConfig = deps.getObsConfig();
@@ -133,7 +150,7 @@ export function createCompactionBatchPackHook(deps: {
133
150
  sessionId: deps.getSessionId?.(),
134
151
  messages,
135
152
  obsConfig,
136
- pickMiddleExcerpt: deps.pickMiddleExcerpt,
153
+ pickMiddleExcerpts: deps.pickMiddleExcerpts,
137
154
  });
138
155
  };
139
156
  }
@@ -147,20 +164,22 @@ async function packOneMessage(opts: {
147
164
  text: string;
148
165
  textBytes: number;
149
166
  charLength: number;
167
+ contentHash: string;
168
+ obsId: string;
150
169
  obsConfig: ObservationPackConfig;
151
170
  /** `extra` carries audit fields such as `source: 'compaction'`, `sendCount`, `tailTokensAfter`. */
152
171
  log?: { logEnabled: boolean; event: 'packed' | 'packed-batch'; sessionId?: string; extra?: Record<string, unknown> };
153
- pickMiddleExcerpt?: PickMiddleExcerpt;
154
- /** Prefetched middle excerpt (the batch path runs picks concurrently); null/undefined = none. */
172
+ pickMiddleExcerpts?: PickMiddleExcerpts;
173
+ /** Prefetched middle excerpt (the batch path picks for all items in one call); null/undefined = none. */
155
174
  middle?: ExcerptMiddlePick | null;
156
175
  }): Promise<string | null> {
157
- const { sessionRoot, toolName, toolCallId, text, textBytes, charLength, obsConfig, log, pickMiddleExcerpt } = opts;
176
+ const { sessionRoot, toolName, toolCallId, text, textBytes, charLength, contentHash, obsConfig, log, pickMiddleExcerpts } = opts;
158
177
  const middle = opts.middle !== undefined
159
178
  ? (opts.middle ?? undefined)
160
- : pickMiddleExcerpt
161
- ? (await pickMiddleExcerpt(text, obsConfig.excerptBytes)) ?? undefined
179
+ : pickMiddleExcerpts
180
+ ? (await pickMiddleExcerpts([{ obsId: opts.obsId, text }], obsConfig.excerptBytes))[0] ?? undefined
162
181
  : undefined;
163
- const { id: obsId, placeholder, contentHash } = buildPlaceholder(toolName, toolCallId, text, textBytes, obsConfig, middle);
182
+ const { id: obsId, placeholder } = buildPlaceholder(toolName, toolCallId, text, textBytes, contentHash, obsConfig, middle);
164
183
  const originalTokens = estimateTokens(text);
165
184
  const placeholderTokens = estimateTokens(placeholder);
166
185
 
@@ -174,11 +193,7 @@ async function packOneMessage(opts: {
174
193
  return null;
175
194
  }
176
195
 
177
- if (placeholderMemo.size >= MAX_MEMO_ENTRIES) {
178
- const oldest = placeholderMemo.keys().next().value;
179
- if (oldest) placeholderMemo.delete(oldest);
180
- }
181
- placeholderMemo.set(memoKeyFor(sessionRoot, toolCallId, charLength), { placeholder, obsId });
196
+ rememberPlaceholder(sessionRoot, toolCallId, charLength, placeholder, obsId);
182
197
 
183
198
  if (log?.logEnabled && !loggedPackedObsIds.has(obsId)) {
184
199
  loggedPackedObsIds.add(obsId);
@@ -198,20 +213,65 @@ async function packOneMessage(opts: {
198
213
  return placeholder;
199
214
  }
200
215
 
201
- /** One packable message: a non-error tool result with text-only content that is not yet packed. */
202
- interface PackCandidate { toolName: string; toolCallId: string; text: string; textBytes: number; charLength: number }
216
+ /** One packable message: a non-error, text-only tool result over the size threshold. */
217
+ interface PackCandidate {
218
+ toolName: string;
219
+ toolCallId: string;
220
+ text: string;
221
+ textBytes: number;
222
+ charLength: number;
223
+ contentHash: string;
224
+ obsId: string;
225
+ }
203
226
 
204
- function packCandidateAt(messages: readonly unknown[], index: number, sessionRoot: string): PackCandidate | null {
227
+ function packCandidateAt(
228
+ messages: readonly unknown[],
229
+ index: number,
230
+ sessionRoot: string,
231
+ minBytes: number,
232
+ ): PackCandidate | null {
205
233
  const msg = messages[index] as ContextMessage | undefined;
206
234
  const content = toolResultContent(msg);
207
235
  if (!content) return null;
208
236
  const { texts, charLength } = content;
209
237
  const text = texts.join('\n');
238
+ const textBytes = Buffer.byteLength(text, 'utf8');
239
+ if (textBytes < minBytes) return null;
210
240
  const toolName = typeof msg?.toolName === 'string' ? msg.toolName : 'tool';
211
241
  const toolCallId = typeof msg?.toolCallId === 'string' ? msg.toolCallId : `call_${index}`;
212
242
  if (placeholderMemo.has(memoKeyFor(sessionRoot, toolCallId, charLength))) return null;
213
243
  if (containsReducerReceipt(text)) return null;
214
- return { toolName, toolCallId, text, textBytes: Buffer.byteLength(text, 'utf8'), charLength };
244
+ const contentHash = sha256Hex(text);
245
+ return {
246
+ toolName,
247
+ toolCallId,
248
+ text,
249
+ textBytes,
250
+ charLength,
251
+ contentHash,
252
+ obsId: deriveObservationId(toolName, toolCallId, contentHash),
253
+ };
254
+ }
255
+
256
+ /** A resumed process starts with an empty memo, but the content-addressed object is still on disk.
257
+ * Rebuild the deterministic placeholder from it instead of asking jev again, rewriting the object,
258
+ * and logging the same saving twice. Returns null when the object is not (verifiably) there. */
259
+ async function reusePackedObservation(
260
+ candidate: PackCandidate,
261
+ sessionRoot: string,
262
+ obsConfig: ObservationPackConfig,
263
+ ): Promise<string | null> {
264
+ if (!(await observationObjectExists(sessionRoot, candidate.obsId, candidate.textBytes))) return null;
265
+ const { placeholder } = buildPlaceholder(
266
+ candidate.toolName,
267
+ candidate.toolCallId,
268
+ candidate.text,
269
+ candidate.textBytes,
270
+ candidate.contentHash,
271
+ obsConfig,
272
+ );
273
+ rememberPlaceholder(sessionRoot, candidate.toolCallId, candidate.charLength, placeholder, candidate.obsId);
274
+ return placeholder;
215
275
  }
216
276
 
217
277
  export async function batchPackObservations(opts: {
@@ -220,7 +280,7 @@ export async function batchPackObservations(opts: {
220
280
  messages: readonly unknown[];
221
281
  obsConfig: ObservationPackConfig;
222
282
  limits?: { maxItems?: number; maxBytes?: number };
223
- pickMiddleExcerpt?: PickMiddleExcerpt;
283
+ pickMiddleExcerpts?: PickMiddleExcerpts;
224
284
  }): Promise<number> {
225
285
  const { sessionRoot, sessionId, messages, obsConfig } = opts;
226
286
  if (!obsConfig.enabled || !sessionRoot || !Array.isArray(messages)) return 0;
@@ -228,24 +288,25 @@ export async function batchPackObservations(opts: {
228
288
  const maxItems = opts.limits?.maxItems ?? MAX_BATCH_PACK_ITEMS;
229
289
  const maxBytes = opts.limits?.maxBytes ?? MAX_BATCH_PACK_BYTES;
230
290
 
231
- // Pass 1 — select with the deterministic checks (memo, receipt, size, soft byte cap). Selection is
232
- // optimistic on bytes: a later store failure can only pack fewer items, never more than the caps.
291
+ // Pass 1 — select with the deterministic checks (memo, receipt, size, existing store object, soft
292
+ // byte cap). A reused object is memoized here, so no jev ask, write, or telemetry follows for it.
233
293
  const candidates: PackCandidate[] = [];
234
294
  let selectedBytes = 0;
235
295
  for (let i = 0; i < messages.length && candidates.length < maxItems; i++) {
236
- const candidate = packCandidateAt(messages, i, sessionRoot);
237
- if (!candidate || candidate.textBytes < obsConfig.thresholdBytes) continue;
296
+ const candidate = packCandidateAt(messages, i, sessionRoot, obsConfig.thresholdBytes);
297
+ if (!candidate) continue;
298
+ if (await reusePackedObservation(candidate, sessionRoot, obsConfig)) continue;
238
299
  if (selectedBytes + candidate.textBytes > maxBytes && candidates.length > 0) break;
239
300
  selectedBytes += candidate.textBytes;
240
301
  candidates.push(candidate);
241
302
  }
242
303
  if (candidates.length === 0) return 0;
243
304
 
244
- // Pass 2 — prefetch middle excerpts concurrently: every packed output asks jev, so a serial loop
245
- // would block onBeforeCompact for maxItems × (0.25–0.77s) per compaction.
246
- const picker = opts.pickMiddleExcerpt;
305
+ // Pass 2 — one batched pick for every selected output: per-item asks were a 6-20-way burst that
306
+ // all failed together when jev was down.
307
+ const picker = opts.pickMiddleExcerpts;
247
308
  const middles = picker
248
- ? await Promise.all(candidates.map((c) => picker(c.text, obsConfig.excerptBytes)))
309
+ ? await picker(candidates.map((c) => ({ obsId: c.obsId, text: c.text })), obsConfig.excerptBytes)
249
310
  : [];
250
311
 
251
312
  let packedCount = 0;
@@ -274,7 +335,11 @@ async function runRecall(
274
335
  return toolError(`invalid observation id format: "${String(rawId)}"`);
275
336
  }
276
337
  const id = rawId;
277
- const offset = typeof params?.offset === 'number' ? params.offset : 0;
338
+ const rawOffset = params?.offset;
339
+ if (rawOffset !== undefined && (typeof rawOffset !== 'number' || !Number.isInteger(rawOffset) || rawOffset < 0)) {
340
+ return toolError(`invalid observation offset: "${String(rawOffset)}"`);
341
+ }
342
+ const offset = rawOffset ?? 0;
278
343
 
279
344
  const sessionDir = ctx?.sessionManager?.getSessionDir?.();
280
345
  const sessionId = ctx?.sessionManager?.getSessionId?.();
@@ -288,9 +353,12 @@ async function runRecall(
288
353
  maxBytes: effConfig.observationPack.recallChunkBytes ?? RECALL_MAX_BYTES,
289
354
  maxLines: RECALL_MAX_LINES,
290
355
  });
356
+ // Mid-line offsets are advanced to the next line start by the reader; the header and telemetry
357
+ // report the offset the returned chunk actually starts at.
358
+ const alignedOffset = chunk.offset;
291
359
 
292
360
  const header = [
293
- `[obs_recall id=${id} offset=${offset} next_offset=${chunk.nextOffset} eof=${chunk.eof}]`,
361
+ `[obs_recall id=${id} offset=${alignedOffset} next_offset=${chunk.nextOffset} eof=${chunk.eof}]`,
294
362
  `[chunk_bytes=${chunk.bytes} chunk_lines=${chunk.lines}; use next_offset to continue]`,
295
363
  ].join('\n');
296
364
 
@@ -299,7 +367,7 @@ async function runRecall(
299
367
  event: 'recall',
300
368
  sessionId: sessionId ?? 'unknown',
301
369
  obsId: id,
302
- offset,
370
+ offset: alignedOffset,
303
371
  chunkBytes: chunk.bytes,
304
372
  lines: chunk.lines,
305
373
  nextOffset: chunk.nextOffset,
@@ -312,7 +380,7 @@ async function runRecall(
312
380
  content: [{ type: 'text', text: `${header}\n${chunk.text}` }],
313
381
  details: {
314
382
  id,
315
- offset,
383
+ offset: alignedOffset,
316
384
  bytes: chunk.bytes,
317
385
  lines: chunk.lines,
318
386
  nextOffset: chunk.nextOffset,
@@ -341,7 +409,7 @@ interface ObservationPackDeps {
341
409
  getConfig?: (ctx: ExtensionContext) => EfficiencyConfig;
342
410
  getRuntimeManifest?: () => RuntimeRoleManifest | null;
343
411
  getRemainingHorizon?: () => number;
344
- pickMiddleExcerpt?: PickMiddleExcerpt;
412
+ pickMiddleExcerpts?: PickMiddleExcerpts;
345
413
  }
346
414
 
347
415
  async function projectPlaceholders(
@@ -395,8 +463,16 @@ async function projectPlaceholders(
395
463
  const sendCount = priorAssistantCounts[i] ?? 0;
396
464
  if (sendCount < obsConfig.fullSends) continue;
397
465
 
398
- const candidate = packCandidateAt(projected, i, sessionRoot);
399
- if (!candidate || candidate.textBytes < obsConfig.thresholdBytes) continue;
466
+ const candidate = packCandidateAt(projected, i, sessionRoot, obsConfig.thresholdBytes);
467
+ if (!candidate) continue;
468
+
469
+ // Resume: the object survived the restart even though the memo did not. Project the same
470
+ // deterministic placeholder without re-asking jev or re-logging the saving.
471
+ const reused = await reusePackedObservation(candidate, sessionRoot, obsConfig);
472
+ if (reused) {
473
+ projected[i] = { ...msg, content: [{ type: 'text', text: reused }] };
474
+ continue;
475
+ }
400
476
 
401
477
  let tailTokensAfter = 0;
402
478
  for (let j = i + 1; j < len; j++) {
@@ -410,7 +486,7 @@ async function projectPlaceholders(
410
486
  // Projected saving of the legacy placeholder drives the economic decision; packOneMessage
411
487
  // recomputes the same placeholder when the answer is yes.
412
488
  const originalTokens = estimateTokens(candidate.text);
413
- const estimate = buildPlaceholder(candidate.toolName, candidate.toolCallId, candidate.text, candidate.textBytes, obsConfig);
489
+ const estimate = buildPlaceholder(candidate.toolName, candidate.toolCallId, candidate.text, candidate.textBytes, candidate.contentHash, obsConfig);
414
490
  const removedTokens = Math.max(0, originalTokens - estimateTokens(estimate.placeholder));
415
491
  // Same resolution as OCC (provider family / token-account fallback): passing a raw 'auto' would
416
492
  // let shouldPackForCache fall back on its own hardcoded ratio and diverge from compaction.
@@ -437,7 +513,7 @@ async function projectPlaceholders(
437
513
  sessionId,
438
514
  extra: { sendCount, tailTokensAfter },
439
515
  },
440
- pickMiddleExcerpt: deps.pickMiddleExcerpt,
516
+ pickMiddleExcerpts: deps.pickMiddleExcerpts,
441
517
  });
442
518
  if (!packed) continue;
443
519
  projected[i] = { ...msg, content: [{ type: 'text', text: packed }] };
@@ -454,11 +530,7 @@ export function registerObservationPack(deps: ObservationPackDeps & { pi: Extens
454
530
  name: RECALL_TOOL_NAME,
455
531
  label: 'Recall Observation',
456
532
  description:
457
- 'Recall a paged slice of a previously replaced large tool result by observation id and byte offset.',
458
- promptGuidelines: [
459
- 'Call obs_recall with id and offset to inspect specific parts of large tool outputs.',
460
- 'Check the returned next_offset and eof to page through long logs.',
461
- ],
533
+ 'Recall a paged slice of a previously replaced large tool result by observation id and byte offset; page on with the returned next_offset until eof.',
462
534
  parameters: Type.Object({
463
535
  id: Type.String({ description: 'Observation ID from placeholder (e.g. obs_...)' }),
464
536
  offset: Type.Optional(