pi-pier 0.2.7 → 0.3.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.
Files changed (85) hide show
  1. package/README.md +26 -12
  2. package/package.json +8 -3
  3. package/schemas/efficiency-config.schema.json +77 -0
  4. package/schemas/role-manifest.schema.json +7 -1
  5. package/skills/pi-herdr-workflow/SKILL.md +11 -0
  6. package/src/ansi-text.ts +134 -0
  7. package/src/ask-dialog.ts +308 -0
  8. package/src/ask-user.ts +139 -88
  9. package/src/bootstrap.ts +13 -14
  10. package/src/compact-coordinator.ts +471 -0
  11. package/src/compact-economics-core.ts +328 -0
  12. package/src/config-catalog-core.ts +332 -0
  13. package/src/config-command.ts +388 -0
  14. package/src/dashboard-command.ts +108 -0
  15. package/src/efficiency-config-core.ts +464 -0
  16. package/src/efficiency-store.ts +299 -0
  17. package/src/focus-poller.ts +223 -0
  18. package/src/gc-core.ts +77 -18
  19. package/src/herdr-client.ts +284 -154
  20. package/src/history-store.ts +36 -23
  21. package/src/index-gates.ts +124 -0
  22. package/src/index-locks.ts +29 -16
  23. package/src/index-master.ts +29 -19
  24. package/src/index-notices.ts +35 -11
  25. package/src/index-pipe.ts +17 -7
  26. package/src/index-roles.ts +306 -0
  27. package/src/index-runtime.ts +2 -6
  28. package/src/index-worker.ts +7 -9
  29. package/src/index.ts +425 -388
  30. package/src/jev-client.ts +141 -0
  31. package/src/jev-core.ts +431 -0
  32. package/src/ledger.ts +13 -21
  33. package/src/lock-core.ts +98 -37
  34. package/src/manifest-compose.ts +35 -20
  35. package/src/observation-core.ts +200 -0
  36. package/src/pane-title.ts +19 -38
  37. package/src/pi-surface.ts +34 -22
  38. package/src/pier-options.ts +100 -0
  39. package/src/pipe-channel.ts +65 -52
  40. package/src/platform-paths.ts +19 -52
  41. package/src/{core → plugins}/grid-shape.ts +12 -12
  42. package/src/plugins/heat-plan.ts +158 -0
  43. package/src/plugins/observation.ts +475 -0
  44. package/src/plugins/subagent.ts +728 -0
  45. package/src/{core → plugins}/terminal.ts +237 -123
  46. package/src/{core → plugins}/todo.ts +75 -100
  47. package/src/progress-core.ts +16 -53
  48. package/src/reconcile-core.ts +24 -33
  49. package/src/reducer-core.ts +322 -0
  50. package/src/reducer-invoker.ts +419 -0
  51. package/src/renderers.ts +187 -0
  52. package/src/role-loader.ts +35 -29
  53. package/src/role-manifest.ts +23 -32
  54. package/src/role-state.ts +119 -0
  55. package/src/routing-telemetry.ts +136 -0
  56. package/src/runtime-policy.ts +25 -43
  57. package/src/session-tail.ts +102 -23
  58. package/src/settle-wake-core.ts +55 -22
  59. package/src/slim-frame.ts +29 -124
  60. package/src/stale-core.ts +17 -24
  61. package/src/storage-layout.ts +24 -30
  62. package/src/subagent-core.ts +256 -119
  63. package/src/subagent-gc.ts +131 -69
  64. package/src/subagent-poller.ts +401 -12
  65. package/src/subagent-session.ts +516 -0
  66. package/src/subagent-spawn.ts +651 -28
  67. package/src/swallow.ts +65 -0
  68. package/src/terminal-core.ts +160 -69
  69. package/src/todo-core.ts +62 -113
  70. package/src/todo-read-hook.ts +23 -39
  71. package/src/todo-reminder-core.ts +30 -48
  72. package/src/todo-window.ts +11 -12
  73. package/src/todos-service.ts +27 -35
  74. package/src/tool-error.ts +19 -0
  75. package/src/tool-gate.ts +38 -21
  76. package/src/vocab.ts +55 -25
  77. package/src/core/subagent.ts +0 -839
  78. package/src/git-adapter.ts +0 -104
  79. package/src/notice-buffer.ts +0 -23
  80. package/src/subagent-git-io.ts +0 -80
  81. package/src/subagent-launch.ts +0 -110
  82. package/src/subagent-poll-loop.ts +0 -285
  83. package/src/subagent-port.ts +0 -27
  84. package/src/subagent-scope.ts +0 -39
  85. package/src/subagent-session-io.ts +0 -147
@@ -1,10 +1,7 @@
1
1
  /**
2
- * Workspace history (v1.2, DESIGN.md §13.4).
3
- *
4
- * Task history is append-only JSONL partitioned by cwd, mirroring pi session partitioning:
5
- * <agentRoot>/herdr-pi/history/--<cwd>--/history.jsonl
6
- * Records are immutable so GC can remove panes without deleting history. Recovery keeps
7
- * both the sessionFile and launchCommand snapshots as fallbacks.
2
+ * Delegation ledger: append-only JSONL partitioned by cwd, mirroring pi's session partitioning
3
+ * (<agentRoot>/herdr-pi/history/--<cwd>--/history.jsonl). Rows are immutable, so GC can drop panes
4
+ * without losing history; recovery keeps both the sessionFile and launchCommand snapshots.
8
5
  */
9
6
  import * as fs from 'node:fs';
10
7
  import * as path from 'node:path';
@@ -12,13 +9,13 @@ import { historyFilePath, preferredHistoryFile } from './storage-layout.ts';
12
9
 
13
10
  export { historyFilePath, preferredHistoryFile };
14
11
 
15
- /** Legacy short/resident entries normalize to task; missing values do too, while role names pass through unchanged. */
12
+ /** Legacy short/resident entries normalize to task, as do missing values; role names pass through. */
16
13
  export function normalizeEntryKind(kind: string | null | undefined): string {
17
14
  if (!kind || kind === 'short' || kind === 'resident') return 'task';
18
15
  return kind;
19
16
  }
20
17
 
21
- /** O6: only a .jsonl path is accepted during settlement, so invalid reports cannot overwrite a valid path. */
18
+ /** Only a .jsonl path is accepted, so an invalid report cannot overwrite a valid one. */
22
19
  export function applyReportedSessionFile(
23
20
  current: string | null,
24
21
  reported: string | null | undefined,
@@ -29,11 +26,9 @@ export function applyReportedSessionFile(
29
26
 
30
27
  export interface HistoryEntry {
31
28
  taskId: string;
32
- /** 'task' or a role name; disk reads normalize short/resident to task for compatibility. */
33
29
  kind: string;
34
30
  paneId: string;
35
31
  tabId: string;
36
- /** v1.3: task tab name retained for history review and revival; omitted by older entries. */
37
32
  tabName?: string;
38
33
  workspaceId: string;
39
34
  cwd: string;
@@ -45,19 +40,17 @@ export interface HistoryEntry {
45
40
  status: 'running' | 'settled' | 'consumed' | 'closed';
46
41
  outcome?: string | null;
47
42
  createdAt: number;
48
- /** M13c: durable consumption time, which provides the GC TTL basis. */
49
43
  consumedAt?: number | null;
50
44
  closedAt?: number | null;
51
- /** Previous-generation pane ID, retained when work is redone or revived. */
52
45
  revivedFrom?: string | null;
53
- /** B5: writer marker (spawn / poll-settle / poll-timeout / gc / zombie-sweep …), so
54
- * multiple entries in one second remain auditable (ledger row#23/24 proves both writes). */
46
+ /** Writer marker (spawn / poll-settle / poll-timeout / gc / zombie-sweep …) for auditability. */
55
47
  via?: string;
56
48
  }
57
49
 
58
- /** B5: inherit outcome for a closed row—when patch omits it, use the latest non-empty value
59
- * for that taskId, preventing GC bookkeeping from erasing settlement results under the
60
- * “latest row is state” rule. */
50
+ /**
51
+ * When a patch omits `outcome`, inherit the latest non-empty value for the taskId: GC bookkeeping
52
+ * must not erase a settlement result under the "latest row is state" rule.
53
+ */
61
54
  export function inheritOutcome(lastOutcome: string | null | undefined, patchOutcome: string | null | undefined): string | null {
62
55
  if (patchOutcome !== undefined) return patchOutcome;
63
56
  return lastOutcome ?? null;
@@ -82,7 +75,6 @@ function coerceHistoryEntry(obj: unknown): HistoryEntry | null {
82
75
  return { ...raw, kind: normalizeEntryKind(raw.kind) };
83
76
  }
84
77
 
85
- /** Parse line by line; skip junk JSON and records missing taskId/status. */
86
78
  export function parseHistoryEntries(text: string): HistoryEntry[] {
87
79
  const entries: HistoryEntry[] = [];
88
80
  for (const line of (text ?? '').split(/\r?\n/)) {
@@ -107,7 +99,7 @@ export type HistoryReadResult =
107
99
  | { status: 'missing' }
108
100
  | { status: 'unreadable'; error: Error };
109
101
 
110
- /** Distinguish missing vs permission/IO failure. readHistory still returns [] for both. */
102
+ /** Distinguish missing vs permission/IO failure; readHistory still returns [] for both. */
111
103
  export function inspectHistory(file: string): HistoryReadResult {
112
104
  try {
113
105
  if (!fs.existsSync(file)) return { status: 'missing' };
@@ -118,15 +110,37 @@ export function inspectHistory(file: string): HistoryReadResult {
118
110
  }
119
111
  }
120
112
 
121
- /** Read a history file; missing or unreadable yields []. */
122
113
  export function readHistory(file: string): HistoryEntry[] {
123
114
  const r = inspectHistory(file);
124
115
  return r.status === 'ok' ? r.entries : [];
125
116
  }
126
117
 
118
+ /** Every ledger under `<agentRoot>/herdr-pi/history`. Resume must see tasks spawned into another checkout. */
119
+ export function readHistoryTree(agentRoot: string): HistoryEntry[] {
120
+ const root = path.join(agentRoot, 'herdr-pi', 'history');
121
+ let names: string[];
122
+ try {
123
+ names = fs.readdirSync(root);
124
+ } catch {
125
+ return [];
126
+ }
127
+ const all: HistoryEntry[] = [];
128
+ for (const name of names) {
129
+ let isDir = false;
130
+ try {
131
+ isDir = fs.statSync(path.join(root, name)).isDirectory();
132
+ } catch {
133
+ continue;
134
+ }
135
+ if (!isDir) continue;
136
+ all.push(...readHistory(path.join(root, name, 'history.jsonl')));
137
+ }
138
+ return all;
139
+ }
140
+
127
141
  export type HistoryWriteResult = { ok: true } | { ok: false; error: Error };
128
142
 
129
- /** Append one entry. Failures are logged and returned so the ledger is not silently lost. */
143
+ /** Failures are logged and returned so the ledger is not silently lost. */
130
144
  export function appendHistory(file: string, entry: HistoryEntry): HistoryWriteResult {
131
145
  try {
132
146
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -139,7 +153,6 @@ export function appendHistory(file: string, entry: HistoryEntry): HistoryWriteRe
139
153
  }
140
154
  }
141
155
 
142
- /** Group all generations of each taskId in ascending createdAt order for review. */
143
156
  export function generationsByTask(entries: readonly HistoryEntry[]): Map<string, HistoryEntry[]> {
144
157
  const map = new Map<string, HistoryEntry[]>();
145
158
  for (const e of entries) {
@@ -151,7 +164,7 @@ export function generationsByTask(entries: readonly HistoryEntry[]): Map<string,
151
164
  return map;
152
165
  }
153
166
 
154
- /** Return the newest generation for taskId, which is the one used for resume. */
167
+ /** Newest generation for taskId — the one used for resume. */
155
168
  export function latestGeneration(entries: readonly HistoryEntry[], taskId: string): HistoryEntry | null {
156
169
  const gens = generationsByTask(entries).get(taskId);
157
170
  if (!gens || gens.length === 0) return null;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Human-gate reporting: coalesces every blocking prompt (pier's ask tool, pi's own ctx.ui dialogs,
3
+ * external herdr:blocked producers) into ONE blocked edge.
4
+ *
5
+ * Depth semantics: only the 0→1 transition reports blocked (and marks the ask flag); only the 1→0
6
+ * transition restores working/idle. While the depth is positive, working/idle reports are dropped
7
+ * so the pane stays blocked for the whole dialog. */
8
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
9
+ import type { HerdrClientLike } from './herdr-client.ts';
10
+
11
+ /** pi surface pieces the gate runtime touches (ui_prompt events postdate the pinned devDependency). */
12
+ type GatePi = ExtensionAPI & {
13
+ on?: (name: 'ui_prompt_start' | 'ui_prompt_end', handler: (event: unknown) => void) => void;
14
+ };
15
+
16
+ /** Only inherently human-blocking kinds open the gate; `custom` covers resident overlays too (D97). */
17
+ const GATING_PROMPT_KINDS = new Set(['select', 'confirm', 'input', 'editor']);
18
+
19
+ export interface GateRuntimeDeps {
20
+ pi: ExtensionAPI;
21
+ client: HerdrClientLike;
22
+ /** Collapse the todo widget to one line while a gate is open; restore on release. */
23
+ rerenderWidget: () => void;
24
+ /** True while an agent turn is active (drives the state reported on release). */
25
+ isAgentActive: () => boolean;
26
+ /** Idle activity text (idle role badge / current todo) reported with the idle state. */
27
+ idleMessage: () => string | null;
28
+ /** Working activity text (current todo) reported when a gate releases mid-turn. */
29
+ workingMessage: () => string | null;
30
+ }
31
+
32
+ export interface GateRuntime {
33
+ depth(): number;
34
+ /** Gate-aware agent-state report (blocked depth swallows working/idle). */
35
+ report(state: 'working' | 'idle', activity: string | null): void;
36
+ /** Open one gate; true when this call opened the outer one. */
37
+ enter(label: string | null): boolean;
38
+ /** Close one gate; an unmatched release is ignored. True when the outer gate closed. */
39
+ exit(): boolean;
40
+ /** enter/exit + publish the herdr:blocked edge for pier's own gates. */
41
+ publish(active: boolean, label: string | null): void;
42
+ }
43
+
44
+ export function createGateRuntime(d: GateRuntimeDeps): GateRuntime {
45
+ const { client } = d;
46
+ let blockedDepth = 0;
47
+
48
+ function report(state: 'working' | 'idle', activity: string | null): void {
49
+ if (!client.available || blockedDepth > 0) return;
50
+ const message = activity ?? (state === 'idle' ? d.idleMessage() : null);
51
+ client.reportAgent(state, message).catch(() => {});
52
+ }
53
+
54
+ function enter(label: string | null): boolean {
55
+ blockedDepth += 1;
56
+ if (blockedDepth > 1) return false;
57
+ if (client.available) client.reportAgent('blocked', label).catch(() => {});
58
+ // D95: human-gate marker lets the workbench heatmap distinguish ask from block.
59
+ if (label) void client.reportAskFlag(label).catch(() => {});
60
+ d.rerenderWidget();
61
+ return true;
62
+ }
63
+
64
+ function exit(): boolean {
65
+ if (blockedDepth === 0) return false;
66
+ blockedDepth -= 1;
67
+ d.rerenderWidget();
68
+ if (blockedDepth > 0) return false;
69
+ report(d.isAgentActive() ? 'working' : 'idle', d.isAgentActive() ? d.workingMessage() : null);
70
+ void client.reportAskFlag(null).catch(() => {});
71
+ return true;
72
+ }
73
+
74
+ // emit() is synchronous; this flag stops our own listener from double-counting depth.
75
+ let publishing = false;
76
+ function emitHerdrBlocked(active: boolean, label: string | null): void {
77
+ publishing = true;
78
+ try {
79
+ d.pi.events.emit(
80
+ 'herdr:blocked',
81
+ active ? { active: true, ...(label ? { label } : {}) } : { active: false },
82
+ );
83
+ } finally {
84
+ publishing = false;
85
+ }
86
+ }
87
+
88
+ d.pi.events.on('herdr:blocked', (data) => {
89
+ if (publishing) return;
90
+ const active = typeof data === 'object' && data !== null && 'active' in data && data.active === true;
91
+ if (active) {
92
+ enter(typeof data === 'object' && 'label' in data && typeof data.label === 'string' ? data.label : null);
93
+ } else {
94
+ exit();
95
+ }
96
+ });
97
+
98
+ const gatePi = d.pi as GatePi;
99
+ gatePi.on?.('ui_prompt_start', (event) => {
100
+ const rec = (event ?? {}) as { kind?: unknown; title?: unknown };
101
+ const title = typeof rec.title === 'string' && rec.title.trim() ? rec.title.trim() : null;
102
+ const kind = typeof rec.kind === 'string' ? rec.kind : 'prompt';
103
+ if (!GATING_PROMPT_KINDS.has(kind)) return;
104
+ const label = title ?? kind;
105
+ // The ask tool opens its own gate first, so this is usually a nested no-op;
106
+ // prompts from other extensions or pi core open the gate here.
107
+ if (enter(label)) emitHerdrBlocked(true, label);
108
+ });
109
+ gatePi.on?.('ui_prompt_end', () => {
110
+ if (exit()) emitHerdrBlocked(false, null);
111
+ });
112
+
113
+ return {
114
+ depth: () => blockedDepth,
115
+ report,
116
+ enter,
117
+ exit,
118
+ publish(active: boolean, label: string | null): void {
119
+ if (active) enter(label);
120
+ else exit();
121
+ emitHerdrBlocked(active, label);
122
+ },
123
+ };
124
+ }
@@ -1,10 +1,5 @@
1
- /**
2
- * M18 file write-lock installer (soft veto / hard block).
3
- *
4
- * Why: lock acquire/release/command lived in the composition root next to
5
- * unrelated session wiring. The installer owns the three pi hooks and the
6
- * held-lock set; fail-open on agent.list remains the collaboration policy.
7
- */
1
+ /** M18 file write-lock installer (soft veto / hard block): owns the three pi hooks and the
2
+ * held-lock set; fail-open on agent.list is the collaboration policy. */
8
3
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
9
4
  import {
10
5
  acquireTokensFor,
@@ -16,6 +11,10 @@ import {
16
11
  } from './lock-core.ts';
17
12
  import type { HerdrClientLike, HerdrEnv } from './herdr-client.ts';
18
13
 
14
+ export interface WriteLocksHandle {
15
+ getHeldLocks: () => readonly string[];
16
+ }
17
+
19
18
  export function installWriteLocks(
20
19
  pi: ExtensionAPI,
21
20
  opts: {
@@ -23,11 +22,15 @@ export function installWriteLocks(
23
22
  env: HerdrEnv | null;
24
23
  hard: boolean;
25
24
  },
26
- ): void {
25
+ ): WriteLocksHandle {
27
26
  const { client, env, hard } = opts;
28
27
  const heldLocks = new Set<string>();
29
28
  const lockWarnByToolCall = new Map<string, string>();
30
29
 
30
+ if (!client.available || !env) {
31
+ return { getHeldLocks: () => [] };
32
+ }
33
+
31
34
  async function acquireLocks(paths: readonly string[]): Promise<void> {
32
35
  for (const p of paths) heldLocks.add(p);
33
36
  await client.reportLockTokens(acquireTokensFor(paths, env?.paneId ?? ''));
@@ -37,17 +40,24 @@ export function installWriteLocks(
37
40
  if (!client.available || !env) return;
38
41
  const cwd = ctx?.cwd ?? process.cwd();
39
42
  let agents: LockAgentView[];
43
+ let ownForegroundCwd: string | null = null;
40
44
  try {
41
- agents = (await client.listAgents()).map((a) => ({ paneId: a.paneId, tokens: a.tokens }));
45
+ const liveAgents = await client.listAgents();
46
+ agents = liveAgents.map((a) => ({ paneId: a.paneId, tokens: a.tokens }));
47
+ const me = liveAgents.find((a) => a.paneId === env.paneId);
48
+ if (me?.foregroundCwd) {
49
+ ownForegroundCwd = me.foregroundCwd;
50
+ }
42
51
  } catch {
43
52
  return;
44
53
  }
54
+ const effectiveCwd = ownForegroundCwd ?? cwd;
45
55
  const plan = planWriteGuard({
46
56
  toolName: event.toolName ?? '',
47
57
  input: event.input,
48
58
  agents,
49
59
  ownPaneId: env.paneId,
50
- cwd,
60
+ cwd: effectiveCwd,
51
61
  hard,
52
62
  });
53
63
  if (plan.kind === 'skip') return;
@@ -60,13 +70,14 @@ export function installWriteLocks(
60
70
  await acquireLocks(plan.paths);
61
71
  });
62
72
 
63
- pi.on('tool_result', async (event: { toolCallId?: string; content?: Array<{ type: string; text: string }> }) => {
64
- if (typeof event?.toolCallId !== 'string') return;
65
- const warning = lockWarnByToolCall.get(event.toolCallId);
73
+ pi.on('tool_result', async (event: unknown) => {
74
+ const rec = (event ?? {}) as { toolCallId?: unknown; content?: unknown };
75
+ if (typeof rec.toolCallId !== 'string') return;
76
+ const warning = lockWarnByToolCall.get(rec.toolCallId);
66
77
  if (!warning) return;
67
- lockWarnByToolCall.delete(event.toolCallId);
68
- const content = Array.isArray(event.content) ? event.content : [];
69
- return { content: [...content, { type: 'text', text: warning }] };
78
+ lockWarnByToolCall.delete(rec.toolCallId);
79
+ const content = Array.isArray(rec.content) ? rec.content as Array<{ type: 'text'; text: string }> : [];
80
+ return { content: [...content, { type: 'text' as const, text: warning }] };
70
81
  });
71
82
 
72
83
  pi.on('agent_settled', async () => {
@@ -102,4 +113,6 @@ export function installWriteLocks(
102
113
  ui?.notify?.(lines.join('\n'), 'info');
103
114
  },
104
115
  });
116
+
117
+ return { getHeldLocks: () => [...heldLocks] };
105
118
  }
@@ -1,22 +1,21 @@
1
- /**
2
- * Master-process plugin mount (cordis loader + terminal/todo/subagent).
3
- *
4
- * Why: worker must never load bootstrap/subagent-scope (C3). This module is
5
- * dynamically imported only from the master branch of index.ts.
6
- */
1
+ /** Master-process plugin mount (cordis loader + terminal/todo/subagent), dynamically imported from
2
+ * the master branch of index.ts only: a worker must never load bootstrap/subagent-poller (C3). */
7
3
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
8
4
  import type { Context } from '@deepseek-ai/cordis';
9
5
  import type { Server } from 'node:net';
10
6
  import { PiSurface } from './pi-surface.ts';
11
7
  import { createCordisApp } from './bootstrap.ts';
12
- import { disposeSessionRoot } from './subagent-scope.ts';
13
- import terminalPlugin from './core/terminal.ts';
14
- import todoPlugin from './core/todo.ts';
15
- import subagentPlugin from './core/subagent.ts';
8
+ import { disposeSessionRoot } from './subagent-poller.ts';
9
+ import terminalPlugin from './plugins/terminal.ts';
10
+ import todoPlugin from './plugins/todo.ts';
11
+ import subagentPlugin from './plugins/subagent.ts';
16
12
  import type { HerdrClientLike, HerdrEnv } from './herdr-client.ts';
13
+ import type { JevRuntime } from './jev-client.ts';
14
+ import type { RoutingTelemetryRecord } from './routing-telemetry.ts';
17
15
  import type { TodosService } from './todos-service.ts';
18
- import type { TodoUiSlot } from './core/todo.ts';
19
- import type { SubagentPortBox } from './subagent-port.ts';
16
+ import type { TodoUiSlot } from './plugins/todo.ts';
17
+ import type { SubagentPortBox } from './subagent-core.ts';
18
+ import type { SubagentDeps } from './plugins/subagent.ts';
20
19
 
21
20
  export interface MasterPluginMount {
22
21
  pi: ExtensionAPI;
@@ -35,6 +34,12 @@ export interface MasterPluginMount {
35
34
  reconcileOnSettlement: (description: string, outcome: 'settled' | 'failed') => string[];
36
35
  withReconcileNotes: (base: string, notes: readonly string[]) => string;
37
36
  claimSettleNotice: (key: string) => boolean;
37
+ isCompactionInFlight?: () => boolean;
38
+ isIntentionalAbort?: () => boolean;
39
+ /** Optional jev seam for subagent settle attribution (fail-open when absent). */
40
+ jev?: { ask: JevRuntime['ask']; getMinConfidence: () => number };
41
+ /** Phase 0 routing telemetry append (RFC rfc-jev-role-routing §8); absent in tests. */
42
+ appendRoutingLog?: (row: RoutingTelemetryRecord) => void;
38
43
  }
39
44
 
40
45
  async function loadEntry(
@@ -60,8 +65,7 @@ export async function mountMasterPlugins(m: MasterPluginMount): Promise<void> {
60
65
  // strip-types) and misses pi's typebox alias. HMR-only; production uses plugin().
61
66
  const useLoader = cordisApp.loaderReady && cordisApp.hmrActive;
62
67
 
63
- // Pipe server is created in the common segment; closing it from a core
64
- // plugin would kill it on hmr reload (d87).
68
+ // Pipe server is created in the common segment; closing it from a core plugin would kill it on hmr reload (d87).
65
69
  sessionRoot.effect(() => () => {
66
70
  if (m.pipeServerBox.current) {
67
71
  try { m.pipeServerBox.current.close(); } catch { /* already closed */ }
@@ -78,7 +82,7 @@ export async function mountMasterPlugins(m: MasterPluginMount): Promise<void> {
78
82
  };
79
83
  sessionRoot.provide('pi-herdr.terminal-deps', terminalDeps);
80
84
 
81
- await loadEntry(sessionRoot, useLoader, './core/terminal.ts', terminalPlugin);
85
+ await loadEntry(sessionRoot, useLoader, './plugins/terminal.ts', terminalPlugin);
82
86
 
83
87
  sessionRoot.provide('pi-herdr.todo-deps', {
84
88
  todos: m.todos,
@@ -86,17 +90,21 @@ export async function mountMasterPlugins(m: MasterPluginMount): Promise<void> {
86
90
  maxItems: 15,
87
91
  mirrorTodos: m.mirrorTodos,
88
92
  appendEntry: (customType: string, data: unknown) => {
89
- (m.pi as { appendEntry?: (t: string, d: unknown) => void }).appendEntry?.(customType, d);
93
+ (m.pi as { appendEntry?: (t: string, d: unknown) => void }).appendEntry?.(customType, data);
90
94
  },
91
95
  state: m.todoUi,
92
96
  getBlockedDepth: m.getBlockedDepth,
93
97
  stopReminder: {
94
98
  getBlockedDepth: m.getBlockedDepth,
95
99
  getRunningSubs: () => m.port.current?.listRunningSubs().length ?? 0,
100
+ isCompactionInFlight: m.isCompactionInFlight,
101
+ isIntentionalAbort: m.isIntentionalAbort,
96
102
  },
97
103
  });
98
- await loadEntry(sessionRoot, useLoader, './core/todo.ts', todoPlugin);
104
+ await loadEntry(sessionRoot, useLoader, './plugins/todo.ts', todoPlugin);
99
105
 
106
+ // D98 regression guard: `satisfies` makes tsc reject a missing/mistyped key here — the bag is
107
+ // consumed untyped by plugins/subagent.ts, and the fe99252 crash was exactly a dropped key.
100
108
  sessionRoot.provide('pi-herdr.subagent-deps', {
101
109
  client: m.client,
102
110
  env: m.env,
@@ -110,8 +118,10 @@ export async function mountMasterPlugins(m: MasterPluginMount): Promise<void> {
110
118
  withReconcileNotes: m.withReconcileNotes,
111
119
  claimSettleNotice: m.claimSettleNotice,
112
120
  terminalState: terminalDeps.state,
113
- });
114
- await loadEntry(sessionRoot, useLoader, './core/subagent.ts', subagentPlugin);
121
+ ...(m.jev ? { jev: m.jev } : {}),
122
+ ...(m.appendRoutingLog ? { logRouting: m.appendRoutingLog } : {}),
123
+ } satisfies SubagentDeps);
124
+ await loadEntry(sessionRoot, useLoader, './plugins/subagent.ts', subagentPlugin);
115
125
 
116
126
  m.pi.on('session_shutdown', () => {
117
127
  void disposeSessionRoot(sessionRoot);
@@ -1,14 +1,23 @@
1
1
  /**
2
- * D92 settlement-notice buffer (busy-run collapse).
3
- *
4
- * Why: `sendUserMessage(followUp)` only delivers when the agent has no more
5
- * tool calls — a long master run queues every settlement and floods at the
6
- * end. Buffer while busy; flush at turn_end (steer) / agent_settled (followUp).
7
- */
8
- import { collapseNotices } from './notice-buffer.ts';
2
+ * D92 settlement-notice buffer: `sendUserMessage(followUp)` only delivers when the agent has no
3
+ * more tool calls, so a long master run would queue every settlement and flood at the end. Buffer
4
+ * while busy; flush at turn_end (steer) / agent_settled (followUp), collapsing large batches. */
9
5
 
10
6
  export type NoticeSendMode = 'steer' | 'followUp';
11
7
 
8
+ export const NOTICE_MAX_SHOWN = 3;
9
+
10
+ /** Collapse a batch into one message body: empty → null; above the cap, the first max originals plus
11
+ * a tail pointing at history / subagent list. A single-item batch stays byte-identical to the
12
+ * direct-send format. */
13
+ export function collapseNotices(contents: readonly string[], max = NOTICE_MAX_SHOWN): string | null {
14
+ if (contents.length === 0) return null;
15
+ if (contents.length <= max) return contents.join('\n\n');
16
+ const hidden = contents.length - max;
17
+ const tail = `…另有 ${hidden} 条结算未逐条展示。全量结果看 history 台账(路径公式见 subagent resume 工具描述);在跑代理用 subagent list 查看。`;
18
+ return [...contents.slice(0, max), tail].join('\n\n');
19
+ }
20
+
12
21
  export interface NoticeBuffer {
13
22
  deliverNotice(content: string, paneId?: string): Promise<void>;
14
23
  noticePending(): ReadonlySet<string>;
@@ -19,14 +28,19 @@ export function createNoticeBuffer(opts: {
19
28
  /** True while the agent is in a turn, or after an abort that must not wake a new run. */
20
29
  isBusy: () => boolean;
21
30
  send: (content: string, mode: NoticeSendMode) => Promise<void>;
31
+ /**
32
+ * P0-2 (RFC docs/rfc-jev-integration.md §3): relevance reorder of a collapsed batch before truncation.
33
+ * Only consulted above the show cap; returning null (or omitting the hook) keeps arrival order.
34
+ * Implementations must not throw. */
35
+ rank?: (contents: readonly string[]) => Promise<readonly string[] | null>;
22
36
  }): NoticeBuffer {
23
- const pending: string[] = [];
37
+ const pending: Array<{ content: string; paneId?: string }> = [];
24
38
  const pendingPaneIds = new Set<string>();
25
39
  return {
26
40
  async deliverNotice(content, paneId) {
27
41
  if (content !== '' && paneId !== undefined) pendingPaneIds.add(paneId);
28
42
  if (opts.isBusy()) {
29
- pending.push(content);
43
+ pending.push({ content, paneId });
30
44
  return;
31
45
  }
32
46
  await opts.send(content, 'followUp');
@@ -35,8 +49,18 @@ export function createNoticeBuffer(opts: {
35
49
  noticePending: () => pendingPaneIds,
36
50
  async flush(mode) {
37
51
  if (pending.length === 0) return;
38
- const collapsed = collapseNotices(pending.splice(0));
39
- pendingPaneIds.clear();
52
+ const flushed = pending.splice(0);
53
+ const batch = flushed.map((n) => n.content);
54
+ let ordered: readonly string[] = batch;
55
+ if (opts.rank && batch.length > NOTICE_MAX_SHOWN) {
56
+ ordered = (await opts.rank(batch)) ?? batch;
57
+ }
58
+ // Release only this batch's panes: a notice buffered during the rank await is still undelivered,
59
+ // and GC must keep its pane until it is.
60
+ for (const { paneId } of flushed) {
61
+ if (paneId !== undefined && !pending.some((n) => n.paneId === paneId)) pendingPaneIds.delete(paneId);
62
+ }
63
+ const collapsed = collapseNotices(ordered);
40
64
  if (collapsed) await opts.send(collapsed, mode);
41
65
  },
42
66
  };
package/src/index-pipe.ts CHANGED
@@ -1,12 +1,7 @@
1
- /**
2
- * Common-segment pipe request handler (prompt / interrupt / reply).
3
- *
4
- * Why: index.ts owned the NDJSON switch next to session lifecycle. The
5
- * dispatch is a pure-ish adapter over the subagent port and notice buffer.
6
- */
1
+ /** Common-segment pipe request handler (prompt / interrupt / reply) over the subagent port and notice buffer. */
7
2
  import { formatSettlementNotice } from './vocab.ts';
8
3
  import type { PipeRequest, PipeResponse } from './pipe-channel.ts';
9
- import type { SubagentPortBox } from './subagent-port.ts';
4
+ import type { SubagentPortBox } from './subagent-core.ts';
10
5
 
11
6
  export interface MachineRequest {
12
7
  id: string;
@@ -24,6 +19,8 @@ export interface PipeHandlerSession {
24
19
  sendUserMessageAs: (content: string, mode: 'steer' | 'followUp') => Promise<void>;
25
20
  abort: () => void;
26
21
  setPendingMachineRequest: (req: MachineRequest | null) => void;
22
+ /** P0 (RFC §4.4): apply a role switch requested over the pipe (master → worker). */
23
+ applyRoleSwitch: (role: string, switchedBy: string) => Promise<{ ok: boolean; message: string }>;
27
24
  }
28
25
 
29
26
  export async function handlePipeRequest(
@@ -51,8 +48,21 @@ export async function handlePipeRequest(
51
48
  s.abort();
52
49
  s.setPendingMachineRequest(null);
53
50
  return { type: 'ok', id: req.id };
51
+ case 'role': {
52
+ const res = await s.applyRoleSwitch(req.role, s.paneId || 'pipe');
53
+ return res.ok
54
+ ? { type: 'ok', id: req.id, detail: res.message }
55
+ : { type: 'error', id: req.id, message: res.message };
56
+ }
54
57
  case 'reply': {
55
58
  s.port.current?.applyReplySession(req.paneId, req.sessionFile);
59
+ // Consume before the finish notice: otherwise listRunningSubs still reports the pane and the
60
+ // next master settle injects "still running" for an agent just announced finished.
61
+ s.port.current?.consumeReply(req.paneId, req.text);
62
+ // B8: the claim key `${paneId}:${requestId}` must match the poll loop's (subagent-poller.ts):
63
+ // a child echoes the id of the pipe request it answered (`id: req.id` in index.ts's settle
64
+ // push) and the parent hands that same id to startPoller (`prompt-<taskId>` / `fu-<ts>`).
65
+ // A mismatch surfaces as two "finished" notices for one settlement.
56
66
  if (s.claimSettleNotice(`${req.paneId}:${req.id}`)) {
57
67
  const notes = s.port.current?.reconcileOnReply(req.paneId) ?? [];
58
68
  const statLine = await s.port.current?.settleStatLine(req.paneId) ?? null;