@comput/pi-intercom 0.5.2 → 0.6.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/src/handoff.ts ADDED
@@ -0,0 +1,280 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { Agent, Config } from './config.js';
3
+
4
+ export interface WorkerPaneIdentity {
5
+ workspaceId: string; paneId: string; terminalId: string; sessionId: string;
6
+ sessionFile: string; pid: number; processStart: string;
7
+ }
8
+ export interface CloseProvider {
9
+ getIdentity(): Promise<WorkerPaneIdentity>;
10
+ inspect(identity: WorkerPaneIdentity, expectedSessionId: string, assertCurrent: () => void): Promise<void>;
11
+ close(identity: WorkerPaneIdentity, expectedSessionId: string, assertCurrent: () => void, beforeSubmit: () => Promise<void>): Promise<{ paneClosed: boolean; workerExited: boolean }>;
12
+ }
13
+ export type CloseReason = 'timeout' | 'interrupted' | 'delivery_failed' | 'identity_failed' | 'save_failed' | 'worker_changed' | 'worker_busy' | 'commit_rejected' | 'close_unverified' | 'close_failed';
14
+ export type CloseState = 'requested' | 'awaiting_handoff' | 'awaiting_settlement' | 'ready' | 'closing' | 'closed' | 'failed' | 'timed_out' | 'interrupted' | 'uncertain';
15
+ export interface Handoff { version: 1; summary: string; updatedAt: string; jobId: string }
16
+ export interface CloseJob { jobId: string; state: CloseState; createdAt: string; updatedAt: string; deadlineAt: string; reason?: CloseReason }
17
+ export type HandoffKind = 'close_prepare' | 'close_identity' | 'close_request' | 'handoff_report' | 'close_ready' | 'close_commit';
18
+ export const HANDOFF_KINDS: readonly string[] = ['close_prepare', 'close_identity', 'close_request', 'handoff_report', 'close_ready', 'close_commit'];
19
+ const states: CloseState[] = ['requested', 'awaiting_handoff', 'awaiting_settlement', 'ready', 'closing', 'closed', 'failed', 'timed_out', 'interrupted', 'uncertain'];
20
+ const reasons: CloseReason[] = ['timeout', 'interrupted', 'delivery_failed', 'identity_failed', 'save_failed', 'worker_changed', 'worker_busy', 'commit_rejected', 'close_unverified', 'close_failed'];
21
+ export const pendingClose = (job?: CloseJob) => !!job && ['requested', 'awaiting_handoff', 'awaiting_settlement', 'ready', 'closing'].includes(job.state);
22
+ export const fencedClose = (job?: CloseJob) => pendingClose(job) || job?.state === 'uncertain';
23
+ function requireValue(ok: unknown): asserts ok { if (!ok) throw new Error('PiIntercom: invalid handoff protocol/state'); }
24
+ const string = (value: unknown, max: number) => typeof value === 'string' && !!value.trim() && value.length <= max && !value.includes('\0');
25
+ const token = (value: unknown) => typeof value === 'string' && /^[a-zA-Z0-9-]{1,128}$/.test(value);
26
+ const timestamp = (value: unknown) => typeof value === 'string' && value.length <= 32 && Number.isFinite(Date.parse(value));
27
+ export function validateIdentity(value: unknown): asserts value is WorkerPaneIdentity {
28
+ const v = value as WorkerPaneIdentity;
29
+ requireValue(v && ['workspaceId', 'paneId', 'terminalId', 'sessionId', 'processStart'].every(k => string(v[k as keyof WorkerPaneIdentity], 256)) && string(v.sessionFile, 4096) && Number.isSafeInteger(v.pid) && v.pid > 0);
30
+ }
31
+ export function validateHandoff(value: unknown): asserts value is Handoff {
32
+ const v = value as Handoff;
33
+ requireValue(v && v.version === 1 && token(v.jobId) && string(v.summary, 4000) && timestamp(v.updatedAt));
34
+ requireValue(Object.keys(v).every(k => ['version', 'jobId', 'summary', 'updatedAt'].includes(k)));
35
+ }
36
+ export function validateCloseJob(value: unknown): asserts value is CloseJob {
37
+ const v = value as CloseJob;
38
+ requireValue(v && token(v.jobId) && states.includes(v.state) && timestamp(v.createdAt) && timestamp(v.updatedAt) && timestamp(v.deadlineAt) && (v.reason === undefined || reasons.includes(v.reason)));
39
+ requireValue(Object.keys(v).every(k => ['jobId', 'state', 'createdAt', 'updatedAt', 'deadlineAt', 'reason'].includes(k)));
40
+ }
41
+ export function validateHandoffPayload(kind: string, p: Record<string, unknown>): void {
42
+ requireValue(token(p.jobId));
43
+ const keys: Record<string, string[]> = {
44
+ close_prepare: ['jobId', 'deadlineAt'], close_identity: ['jobId', 'instanceId', 'identity'],
45
+ close_request: ['jobId', 'instanceId'], handoff_report: ['jobId', 'instanceId', 'summary'],
46
+ close_ready: ['jobId', 'instanceId', 'readyNonce'], close_commit: ['jobId', 'instanceId', 'readyNonce'],
47
+ };
48
+ requireValue(!!keys[kind] && Object.keys(p).every(k => keys[kind].includes(k)));
49
+ if (kind === 'close_prepare') requireValue(timestamp(p.deadlineAt));
50
+ else requireValue(token(p.instanceId));
51
+ if (kind === 'close_identity') validateIdentity(p.identity);
52
+ if (kind === 'handoff_report') requireValue(string(p.summary, 4000));
53
+ if (kind === 'close_ready' || kind === 'close_commit') requireValue(token(p.readyNonce));
54
+ }
55
+ interface Context {
56
+ state(): Promise<{ id: string; config: Config; me?: Agent }>;
57
+ assertCurrent(): void;
58
+ update(mutate: (config: Config) => void, guard?: () => void): Promise<void>;
59
+ send(sessionId: string, kind: HandoffKind, payload: Record<string, unknown>): Promise<void>;
60
+ deliver(message: string): void;
61
+ busy(): boolean;
62
+ provider?: CloseProvider;
63
+ timeoutMs?: number;
64
+ }
65
+ interface Pending {
66
+ target: Agent; job: CloseJob; timer: ReturnType<typeof setTimeout>;
67
+ identity?: WorkerPaneIdentity; instanceId?: string; initialized?: Promise<void>; processing: boolean; closing: boolean; ended: boolean;
68
+ }
69
+ interface WorkerPending {
70
+ jobId: string; coordinatorId: string; deadline: number; requested: boolean;
71
+ saved: boolean; reporting: boolean; invalidated: boolean; epoch: number;
72
+ readyNonce?: string; toolCallId?: string; committed: boolean; timer: ReturnType<typeof setTimeout>;
73
+ }
74
+ /** Extension-owned asynchronous protocol. No host abort, shutdown, automatic retries or guessed pane targets. */
75
+ export class HandoffWorkflow {
76
+ private readonly instanceId = randomUUID();
77
+ private jobs = new Map<string, Pending>();
78
+ private worker?: WorkerPending;
79
+ private epoch = 0;
80
+ private disposed = false;
81
+ private readonly timeout: number;
82
+ constructor(private readonly ctx: Context) {
83
+ this.timeout = Number.isFinite(ctx.timeoutMs) ? Math.max(1, Math.min(120000, ctx.timeoutMs!)) : 120000;
84
+ }
85
+ private valid() { requireValue(!this.disposed); this.ctx.assertCurrent(); }
86
+ private background(work: () => Promise<void>) { setImmediate(() => { if (!this.disposed) void work().catch(() => {}); }); }
87
+ dispose(): void {
88
+ this.disposed = true;
89
+ for (const p of this.jobs.values()) { p.ended = true; clearTimeout(p.timer); }
90
+ this.jobs.clear();
91
+ if (this.worker) clearTimeout(this.worker.timer);
92
+ this.worker = undefined;
93
+ }
94
+ async recover(): Promise<void> {
95
+ const { me, config } = await this.ctx.state();
96
+ if (!me?.coordinator || !config.agents.some(a => pendingClose(a.closeJob))) return;
97
+ await this.ctx.update(c => {
98
+ for (const a of c.agents) if (pendingClose(a.closeJob)) {
99
+ a.closeJob = { ...a.closeJob!, state: a.closeJob!.state === 'closing' ? 'uncertain' : 'interrupted', reason: 'interrupted', updatedAt: new Date().toISOString() };
100
+ }
101
+ });
102
+ }
103
+ private assertJob(p: Pending) {
104
+ this.valid();
105
+ requireValue(!p.ended && this.jobs.get(p.target.sessionId) === p && Date.now() < Date.parse(p.job.deadlineAt));
106
+ }
107
+ private target(c: Config, p: Pending): Agent {
108
+ this.assertJob(p);
109
+ const a = c.agents.find(a => a.sessionId === p.target.sessionId && !a.coordinator);
110
+ requireValue(a && a.closeJob?.jobId === p.job.jobId && pendingClose(a.closeJob) && a.port === p.target.port && a.projectDirectory === p.target.projectDirectory);
111
+ return a;
112
+ }
113
+ private async transition(p: Pending, state: CloseState, reason?: CloseReason): Promise<void> {
114
+ await this.ctx.update(c => {
115
+ const a = this.target(c, p);
116
+ a.closeJob = { ...a.closeJob!, state, updatedAt: new Date().toISOString(), ...(reason ? { reason } : {}) };
117
+ p.job = { ...a.closeJob };
118
+ }, () => this.assertJob(p));
119
+ }
120
+ private async finish(p: Pending, state: CloseState, reason?: CloseReason): Promise<void> {
121
+ if (p.ended) return;
122
+ p.ended = true; clearTimeout(p.timer);
123
+ // Keep the in-memory fence if persistence fails. Reload recovers durable intent.
124
+ try {
125
+ this.valid();
126
+ await this.ctx.update(c => {
127
+ const a = c.agents.find(a => a.sessionId === p.target.sessionId && !a.coordinator);
128
+ requireValue(a?.closeJob?.jobId === p.job.jobId);
129
+ a.closeJob = { ...a.closeJob, state, updatedAt: new Date().toISOString(), ...(reason ? { reason } : {}) };
130
+ });
131
+ this.jobs.delete(p.target.sessionId);
132
+ } catch { /* Failure never authorizes pane closure or replay. */ }
133
+ }
134
+ async request(target: Agent): Promise<CloseJob> {
135
+ this.valid(); requireValue(this.ctx.provider);
136
+ const existing = this.jobs.get(target.sessionId);
137
+ if (existing) { await existing.initialized; return { ...existing.job }; }
138
+ requireValue(!fencedClose(target.closeJob) && this.jobs.size < 16);
139
+ const now = Date.now();
140
+ const job: CloseJob = { jobId: randomUUID(), state: 'requested', createdAt: new Date(now).toISOString(), updatedAt: new Date(now).toISOString(), deadlineAt: new Date(now + this.timeout).toISOString() };
141
+ const p: Pending = { target: { ...target }, job, timer: undefined as unknown as ReturnType<typeof setTimeout>, processing: false, closing: false, ended: false };
142
+ // Install the fence synchronously, before the first asynchronous config write.
143
+ this.jobs.set(target.sessionId, p);
144
+ try {
145
+ p.initialized = this.ctx.update(c => {
146
+ const a = c.agents.find(a => a.sessionId === target.sessionId && !a.coordinator);
147
+ requireValue(a && !fencedClose(a.closeJob) && a.port === target.port && a.projectDirectory === target.projectDirectory && c.multiplexer === 'herdr');
148
+ a.closeJob = { ...job };
149
+ }, () => this.assertJob(p));
150
+ await p.initialized;
151
+ } catch (error) { this.jobs.delete(target.sessionId); throw error; }
152
+ p.timer = setTimeout(() => { void this.finish(p, p.closing ? 'uncertain' : 'timed_out', 'timeout'); }, Math.max(0, Date.parse(job.deadlineAt) - Date.now()));
153
+ this.background(async () => {
154
+ try { this.assertJob(p); await this.ctx.send(target.sessionId, 'close_prepare', { jobId: job.jobId, deadlineAt: job.deadlineAt }); }
155
+ catch { await this.finish(p, 'failed', 'delivery_failed'); }
156
+ });
157
+ return { ...job };
158
+ }
159
+ workerStarted(): void {
160
+ this.epoch++;
161
+ const w = this.worker;
162
+ if (w && (w.saved || w.reporting)) { w.invalidated = true; w.readyNonce = undefined; }
163
+ }
164
+ workerSettled(successfulToolCallIds: ReadonlySet<string>): void {
165
+ const w = this.worker;
166
+ if (!w || !w.saved || w.reporting || w.invalidated || w.readyNonce || w.committed || this.ctx.busy() || w.epoch !== this.epoch || !w.toolCallId || !successfulToolCallIds.has(w.toolCallId)) return;
167
+ w.readyNonce = randomUUID();
168
+ this.background(async () => {
169
+ this.assertWorker(w);
170
+ requireValue(!this.ctx.busy() && w.epoch === this.epoch && !w.invalidated);
171
+ await this.ctx.send(w.coordinatorId, 'close_ready', { jobId: w.jobId, instanceId: this.instanceId, readyNonce: w.readyNonce });
172
+ });
173
+ }
174
+ private assertWorker(w: WorkerPending) {
175
+ this.valid(); requireValue(this.worker === w && Date.now() < w.deadline);
176
+ }
177
+ get workerClosing(): boolean { return !!this.worker; }
178
+ isClosing(sessionId: string): boolean { return this.jobs.has(sessionId); }
179
+ async report(jobId: unknown, summary: unknown, toolCallId?: string): Promise<{ saved: true; closure: 'awaiting_turn_settlement' }> {
180
+ requireValue(string(summary, 4000) && string(toolCallId, 256));
181
+ const w = this.worker; requireValue(w && w.jobId === jobId && w.requested && !w.reporting && !w.saved && !w.invalidated);
182
+ this.assertWorker(w); w.reporting = true; w.toolCallId = toolCallId;
183
+ const reportEpoch = this.epoch;
184
+ try {
185
+ await this.ctx.send(w.coordinatorId, 'handoff_report', { jobId: w.jobId, instanceId: this.instanceId, summary });
186
+ this.assertWorker(w); requireValue(!w.invalidated && this.epoch === reportEpoch);
187
+ w.saved = true; w.epoch = reportEpoch;
188
+ return { saved: true, closure: 'awaiting_turn_settlement' };
189
+ } finally { w.reporting = false; }
190
+ }
191
+ async receive(kind: HandoffKind, from: string, payload: Record<string, unknown>): Promise<void> {
192
+ validateHandoffPayload(kind, payload);
193
+ const { config, me } = await this.ctx.state(); this.valid();
194
+ const sender = config.agents.find(a => a.sessionId === from);
195
+ const coordinatorMessage = ['close_prepare', 'close_request', 'close_commit'].includes(kind);
196
+ requireValue(me && sender && (coordinatorMessage ? sender.coordinator && !me.coordinator : me.coordinator && !sender.coordinator));
197
+ if (coordinatorMessage) {
198
+ requireValue(this.ctx.provider && me.closeJob?.jobId === payload.jobId && pendingClose(me.closeJob));
199
+ if (kind === 'close_prepare') {
200
+ requireValue(!this.worker);
201
+ const deadline = Date.parse(payload.deadlineAt as string);
202
+ requireValue(deadline > Date.now() && deadline <= Date.now() + 120000);
203
+ const w: WorkerPending = { jobId: payload.jobId as string, coordinatorId: from, deadline, requested: false, saved: false, reporting: false, invalidated: false, epoch: this.epoch, committed: false, timer: undefined as unknown as ReturnType<typeof setTimeout> };
204
+ this.worker = w;
205
+ w.timer = setTimeout(() => { if (this.worker === w) this.worker = undefined; }, deadline - Date.now());
206
+ this.background(async () => {
207
+ try {
208
+ const identity = await this.ctx.provider!.getIdentity(); validateIdentity(identity);
209
+ this.assertWorker(w); requireValue(identity.sessionId === me.sessionId);
210
+ await this.ctx.send(from, 'close_identity', { jobId: w.jobId, instanceId: this.instanceId, identity });
211
+ } catch { if (this.worker === w) { clearTimeout(w.timer); this.worker = undefined; } }
212
+ });
213
+ return;
214
+ }
215
+ const w = this.worker;
216
+ requireValue(w && w.jobId === payload.jobId && payload.instanceId === this.instanceId && from === w.coordinatorId);
217
+ this.assertWorker(w);
218
+ if (kind === 'close_request') {
219
+ requireValue(!w.requested); w.requested = true;
220
+ this.ctx.deliver(`Coordinator requests a handoff for owned-pane closure. Job ID: ${w.jobId}. Stop taking new assignments, summarize completed work, remaining work, validation and important files in intercom_report_handoff({jobId:"${w.jobId}",summary:...}) (public summary, max 4000 characters; no credentials or private reasoning), then finish this turn and wait. Do not exit, shut down, close a pane or start further work. Pane closure is asynchronous and is not proof all child processes terminated.`);
221
+ return;
222
+ }
223
+ requireValue(w.saved && !w.reporting && !w.invalidated && !w.committed && !this.ctx.busy() && w.epoch === this.epoch && w.readyNonce === payload.readyNonce);
224
+ w.committed = true; return;
225
+ }
226
+ const p = this.jobs.get(from); requireValue(p && p.job.jobId === payload.jobId);
227
+ this.assertJob(p);
228
+ if (kind === 'close_identity') {
229
+ requireValue(!p.identity && !p.processing && p.job.state === 'requested');
230
+ const identity = payload.identity as WorkerPaneIdentity;
231
+ requireValue(identity.sessionId === from);
232
+ p.identity = { ...identity }; p.instanceId = payload.instanceId as string; p.processing = true;
233
+ this.background(async () => {
234
+ try {
235
+ await this.ctx.provider!.inspect(p.identity!, from, () => this.assertJob(p));
236
+ this.assertJob(p);
237
+ await this.transition(p, 'awaiting_handoff');
238
+ await this.ctx.send(from, 'close_request', { jobId: p.job.jobId, instanceId: p.instanceId });
239
+ } catch { await this.finish(p, 'failed', 'identity_failed'); }
240
+ finally { p.processing = false; }
241
+ });
242
+ return;
243
+ }
244
+ requireValue(payload.instanceId === p.instanceId);
245
+ if (kind === 'handoff_report') {
246
+ requireValue(p.job.state === 'awaiting_handoff' || p.job.state === 'awaiting_settlement');
247
+ try {
248
+ await this.ctx.update(c => {
249
+ const a = this.target(c, p);
250
+ if (a.handoff?.jobId === p.job.jobId) requireValue(a.handoff.summary === payload.summary);
251
+ else a.handoff = { version: 1, jobId: p.job.jobId, summary: payload.summary as string, updatedAt: new Date().toISOString() };
252
+ a.closeJob = { ...a.closeJob!, state: 'awaiting_settlement', updatedAt: new Date().toISOString() };
253
+ }, () => this.assertJob(p));
254
+ this.assertJob(p); p.job = { ...p.job, state: 'awaiting_settlement' };
255
+ } catch (error) { await this.finish(p, 'failed', 'save_failed'); throw error; }
256
+ return;
257
+ }
258
+ requireValue(kind === 'close_ready' && p.job.state === 'awaiting_settlement' && !p.closing && !p.processing);
259
+ p.processing = true;
260
+ this.background(async () => {
261
+ let failure: CloseReason = 'identity_failed';
262
+ try {
263
+ await this.transition(p, 'ready');
264
+ await this.ctx.provider!.inspect(p.identity!, from, () => this.assertJob(p));
265
+ this.assertJob(p);
266
+ failure = 'save_failed'; await this.transition(p, 'closing');
267
+ this.assertJob(p); failure = 'close_failed';
268
+ let commitAttempted = false;
269
+ const result = await this.ctx.provider!.close(p.identity!, from, () => this.assertJob(p), async () => {
270
+ this.assertJob(p); requireValue(!commitAttempted); commitAttempted = true;
271
+ failure = 'commit_rejected';
272
+ await this.ctx.send(from, 'close_commit', { jobId: p.job.jobId, instanceId: p.instanceId, readyNonce: payload.readyNonce });
273
+ this.assertJob(p); p.closing = true; failure = 'close_failed';
274
+ });
275
+ this.assertJob(p); requireValue(p.closing);
276
+ await this.finish(p, result.paneClosed && result.workerExited ? 'closed' : 'uncertain', result.paneClosed && result.workerExited ? undefined : 'close_unverified');
277
+ } catch { await this.finish(p, p.closing ? 'uncertain' : 'failed', failure); }
278
+ });
279
+ }
280
+ }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { Intercom, UNSUPPORTED_CANCELLATION } from './runtime.js';
7
7
  import { launchers } from './launcher.js';
8
8
  import { ensureMonitorPane } from './monitor-launcher.js';
9
9
  import { createActivityTracker } from './activity.js';
10
+ import { createCloseProvider } from './pane-close.js';
10
11
 
11
12
  const to = Type.Object({ to: Type.String({ minLength: 1, maxLength: 128 }) });
12
13
  const tools: [string, string, TSchema][] = [
@@ -20,9 +21,10 @@ const tools: [string, string, TSchema][] = [
20
21
  ['report_work', 'Configured, responsibility-loaded workers only. Store one public report (blocked, needs_decision, ready_for_review) and notify the coordinator; clear retires it. Summary required except clear (omit or empty). Never include private reasoning, credentials, raw tool payloads, or secrets. Receipt is not approval, verified completion, or permission for follow-up work.', Type.Object({ status: Type.String({ enum: ['blocked', 'needs_decision', 'ready_for_review', 'clear'] }), summary: Type.Optional(Type.String({ maxLength: 2000 })) })],
21
22
  ['report_status', 'Worker only (including anonymous). Send runtime sessionId/port/busy report to coordinator. This is NOT registration and creates no config entry.', Type.Object({})],
22
23
  ['stop_worker', UNSUPPORTED_CANCELLATION, to],
23
- ['close_worker', UNSUPPORTED_CANCELLATION, to],
24
+ ['close_worker', 'Coordinator only. Begin a background save-handoff-and-close job for a configured worker in Linux Herdr. Requests a public summary, saves it in config, waits for successful tool persistence and final turn settlement, then attempts one verified pane close. Returns job acceptance, not completion. Registration/session history are retained. Check worker_status/list for closeJob; failure/timeout/uncertainty never authorizes retry. Not graceful abort or an all-descendants termination guarantee; Windows/non-Herdr unsupported.', to],
25
+ ['report_handoff', 'Configured worker only, in response to its pending close request. Submit the matching jobId and concise public resume handoff (current work, completed work, unfinished items, blockers, next step). Never include secrets, private reasoning or raw tool payloads. Saved receipt is not closure: finish the response and wait; the extension requires final turn settlement before pane closure.', Type.Object({ jobId: Type.String({ minLength: 1, maxLength: 128 }), summary: Type.String({ minLength: 1, maxLength: 4000 }) })],
24
26
  ['resume_worker', 'Coordinator only. Resume saved session/name/responsibility after the user explicitly confirms the old session was closed: set confirmClosed:true only for that confirmation, never infer it from disconnected status. A matching live health endpoint blocks launch. In-flight/uncertain attempts are fenced until worker status arrives; otherwise inspect process and reload coordinator before considering retry. No cross-process uniqueness guarantee, automatic assignment, replacement or removal.', Type.Object({ to: Type.String({ minLength: 1, maxLength: 128 }), confirmClosed: Type.Boolean() })],
25
- ['remove_worker', 'Coordinator only. Remove config entry only; never stop process or delete session files. A running worker must be explicitly closed before removal. Stop/close are disabled on current host: arrange explicit user closure first.', to],
27
+ ['remove_worker', 'Coordinator only. Remove config entry only; never stop process or delete session files. A running worker must be explicitly closed before removal. Retain registration to resume it later; remove only to forget it. Pending or uncertain close jobs block removal.', to],
26
28
  ['set_multiplexer', 'Coordinator only. Set herdr (default, Windows/Linux) or none (separate visible Windows terminals; unsupported on Linux) for future launches. Never move/restart existing workers or fall back.', Type.Object({ multiplexer: Type.String({ enum: ['herdr', 'none'] }) })],
27
29
  ];
28
30
 
@@ -55,6 +57,35 @@ export default function intercomExtension(pi: ExtensionAPI): void {
55
57
  extension: fileURLToPath(import.meta.url),
56
58
  sessionExists: async (cwd, id) => (await SessionManager.list(cwd, resumeSessionDirectory(cwd))).some(s => s.id === id),
57
59
  });
60
+ let monitorTask: { runtime: Intercom; generation: number; dirty: boolean; promise: Promise<void> } | undefined;
61
+ async function ensureCoordinatorMonitor(current: Intercom, ctx: ExtensionContext, started: number): Promise<void> {
62
+ const isCurrent = () => started === generation && runtime === current;
63
+ if (!isCurrent()) return;
64
+ if (monitorTask?.runtime === current && monitorTask.generation === started) {
65
+ monitorTask.dirty = true;
66
+ return monitorTask.promise;
67
+ }
68
+ const check = async () => {
69
+ try {
70
+ const { config, me, id } = await current.state();
71
+ if (!isCurrent() || !me?.coordinator || !config.agents.some(agent => !agent.coordinator)) return;
72
+ const monitor = await ensureMonitorPane({
73
+ root: current.store.root, sessionId: id,
74
+ script: fileURLToPath(new URL('../dist/monitor.js', import.meta.url)),
75
+ assertCurrent: () => { if (!isCurrent()) throw new Error('Coordinator session changed'); },
76
+ });
77
+ if (isCurrent()) ctx.ui.notify(`Intercom status monitor: ${monitor.outcome}${monitor.pane ? ` (${monitor.pane})` : ''}`, 'info');
78
+ } catch (error) {
79
+ if (isCurrent()) ctx.ui.notify(String(error), 'warning');
80
+ }
81
+ };
82
+ const task = { runtime: current, generation: started, dirty: false, promise: Promise.resolve() };
83
+ monitorTask = task;
84
+ task.promise = (async () => {
85
+ do { task.dirty = false; await check(); } while (task.dirty && isCurrent());
86
+ })();
87
+ try { await task.promise; } finally { if (monitorTask === task) monitorTask = undefined; }
88
+ }
58
89
  pi.on('session_start', async (_event, ctx) => {
59
90
  const started = ++generation;
60
91
  activity.reset();
@@ -74,7 +105,13 @@ export default function intercomExtension(pi: ExtensionAPI): void {
74
105
  deliver: content => pi.sendUserMessage(content, { deliverAs: 'steer' }),
75
106
  setName: async name => { if (pi.getSessionName() !== name) pi.setSessionName(name); await launcher.syncName(name); },
76
107
  notify: text => ctx.ui.notify(text, 'info'),
77
- }, { launch: launcher.launch, store: root => new PiConfigStore(root) });
108
+ }, {
109
+ launch: launcher.launch, store: root => new PiConfigStore(root),
110
+ closeProvider: createCloseProvider({
111
+ sessionId: () => context!.sessionManager.getSessionId(),
112
+ sessionFile: () => context!.sessionManager.getSessionFile(),
113
+ }),
114
+ });
78
115
  const current = runtime;
79
116
  try { await current.start(); }
80
117
  catch (e) { if (runtime === current) runtime = undefined; ctx.ui.notify(String(e), 'error'); return; }
@@ -87,13 +124,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
87
124
  ctx.ui.notify(`Legacy dashboard metadata cleanup failed; messaging remains available: ${String(error)}`, 'warning');
88
125
  }
89
126
  if (started !== generation) return;
90
- const monitor = await ensureMonitorPane({
91
- root: current.store.root, sessionId: ctx.sessionManager.getSessionId(),
92
- script: fileURLToPath(new URL('../dist/monitor.js', import.meta.url)),
93
- assertCurrent: () => { if (started !== generation || runtime !== current) throw new Error('Coordinator session changed'); },
94
- });
95
- if (started !== generation) return;
96
- ctx.ui.notify(`Intercom status monitor: ${monitor.outcome}${monitor.pane ? ` (${monitor.pane})` : ''}`, 'info');
127
+ await ensureCoordinatorMonitor(current, ctx, started);
97
128
  }
98
129
  } catch (error) {
99
130
  if (started !== generation) return;
@@ -107,8 +138,13 @@ export default function intercomExtension(pi: ExtensionAPI): void {
107
138
  runtime = undefined; context = undefined;
108
139
  await oldRuntime?.close();
109
140
  });
141
+ pi.on('input', (_event, ctx) => {
142
+ context = ctx;
143
+ runtime?.workerStarted(); // New owner input invalidates a pending close-readiness epoch.
144
+ });
110
145
  pi.on('agent_start', async (_event, ctx) => {
111
146
  context = ctx;
147
+ runtime?.workerStarted();
112
148
  activityOutcome = 'started';
113
149
  try { activity.start(); } finally { activityOutcome = 'snapshot'; }
114
150
  });
@@ -116,6 +152,15 @@ export default function intercomExtension(pi: ExtensionAPI): void {
116
152
  context = ctx;
117
153
  activityOutcome = 'settled';
118
154
  try { activity.settled(); } finally { activityOutcome = 'snapshot'; }
155
+ // Settlement is notification-only and follows tool-result persistence. Inspect
156
+ // only entry kinds and successful tool call IDs, never message/reasoning bodies.
157
+ const successful = new Set<string>();
158
+ for (const entry of ctx.sessionManager.getBranch()) {
159
+ if (entry.type === 'message' && entry.message.role === 'toolResult' && !entry.message.isError) {
160
+ successful.add(entry.message.toolCallId);
161
+ }
162
+ }
163
+ runtime?.workerSettled(successful);
119
164
  });
120
165
  pi.on('message_update', (event, ctx) => {
121
166
  context = ctx;
@@ -135,7 +180,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
135
180
  if (!runtime) return;
136
181
  const { me } = await runtime.state();
137
182
  const loaded = runtime.responsibility;
138
- return { systemPrompt: event.systemPrompt + '\n\nPiIntercom: communicates; Pi decides orchestration. Responsibility is not a work assignment. Do not implement unrelated work from findings. After assigned work, report as instructed and wait; do not autonomously exit. Progress questions require reporting and continuing unless explicitly redirected. stop_worker/close_worker are disabled due to host cancellation blocker.\n' + (me && loaded ? `Identity: ${loaded.name} (${me.sessionId}). Responsibility: ${loaded.description}.` : 'Anonymous/unloaded worker: wait for coordinator configuration and separate reload; do not treat registration as authorization to work.') };
183
+ return { systemPrompt: event.systemPrompt + '\n\nPiIntercom: communicates; Pi decides orchestration. Responsibility is not a work assignment. Do not implement unrelated work from findings. After assigned work, report as instructed and wait; do not autonomously exit. Progress questions require reporting and continuing unless explicitly redirected. stop_worker remains disabled due to the host cancellation blocker. close_worker is a separate Linux Herdr background handoff-and-pane-close workflow: do not self-exit, remove registration, force kill or infer completion from job acceptance.\n' + (me && loaded ? `Identity: ${loaded.name} (${me.sessionId}). Responsibility: ${loaded.description}.` : 'Anonymous/unloaded worker: wait for coordinator configuration and separate reload; do not treat registration as authorization to work.') };
139
184
  });
140
185
  for (const [operation, description, parameters] of tools) {
141
186
  pi.registerTool({
@@ -143,9 +188,11 @@ export default function intercomExtension(pi: ExtensionAPI): void {
143
188
  async execute(_id, args, signal, _update, ctx) {
144
189
  signal?.throwIfAborted(); context = ctx;
145
190
  if (!runtime) throw new Error('PiIntercom not initialized; inspect startup error.');
146
- const result = await runtime.tool(operation, args as Record<string, unknown>);
191
+ const current = runtime, started = generation;
192
+ const result = await current.tool(operation, args as Record<string, unknown>, _id);
193
+ if (operation === 'configure_worker') await ensureCoordinatorMonitor(current, ctx, started);
147
194
  const output = truncateHead(JSON.stringify(result, null, 2));
148
- return { content: [{ type: 'text', text: output.content + (output.truncated ? `\n[Truncated; full shared configuration: ${runtime.store.file}]` : '') }], details: {} };
195
+ return { content: [{ type: 'text', text: output.content + (output.truncated ? `\n[Truncated; full shared configuration: ${current.store.file}]` : '') }], details: {} };
149
196
  },
150
197
  });
151
198
  }
@@ -1,6 +1,6 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
2
  import { truncateToWidth, visibleWidth } from 'pi-intercom-tui';
3
- import type { ObservationSnapshot } from './snapshot.js';
3
+ import { publicCloseMetadata, type ObservationSnapshot } from './snapshot.js';
4
4
  import { workerObservation } from './worker-status.js';
5
5
  import { currentConnection, sortWorkersByConnection } from './connections.js';
6
6
  import { INTERCOM_VERSION } from './version.js';
@@ -74,7 +74,9 @@ export function renderMonitor(snapshot: ObservationSnapshot | undefined, width:
74
74
  const selectedIndex = Math.min(workers.length - 1, Math.max(-1, options.selectedIndex ?? -1));
75
75
  const showDetails = Boolean(options.details && selectedIndex >= 0 && height >= 8);
76
76
  const selectedReport = snapshot.reports?.find(report => report.sessionId === workers[selectedIndex]?.sessionId && reportLabels[report.status]);
77
- const detailBudget = showDetails ? Math.min(selectedReport ? 15 : 8, height - 5) : 0;
77
+ const selectedSaved = workers[selectedIndex] ? publicCloseMetadata(workers[selectedIndex]) : {};
78
+ const hasSaved = !!(selectedSaved.handoff || selectedSaved.closeJob);
79
+ const detailBudget = showDetails ? Math.min(hasSaved ? 22 : selectedReport ? 15 : 8, height - 5) : 0;
78
80
  const available = Math.max(0, height - lines.length - 2 - detailBudget);
79
81
  const needsOverflow = workers.length > available;
80
82
  const count = Math.min(workers.length, Math.max(0, available - (needsOverflow && available > 1 ? 1 : 0)));
@@ -94,7 +96,32 @@ export function renderMonitor(snapshot: ObservationSnapshot | undefined, width:
94
96
  const selected = start + offset === selectedIndex;
95
97
  const report = snapshot.reports?.find(report => report.sessionId === worker.sessionId && reportLabels[report.status]);
96
98
  lines.push(table(worker.name, connection.state, activity, age, evidence, report ? reportLabels[report.status] : '—', tone, selected));
97
- if (selected && showDetails && report) {
99
+ if (selected && showDetails && hasSaved) {
100
+ const savedAge = (timestamp: string) => {
101
+ const elapsed = now - Date.parse(timestamp);
102
+ return elapsed < 0 || !Number.isFinite(elapsed) ? 'clock uncertain' : ageLabel(elapsed) + (elapsed > snapshot.staleAfterMs ? ' (old)' : '');
103
+ };
104
+ const { handoff, closeJob } = selectedSaved;
105
+ const context = [
106
+ ...(closeJob ? [line(` Close workflow: ${closeJob.state}${closeJob.reason ? ` · ${closeJob.reason}` : ''} · ${savedAge(closeJob.updatedAt)}`)] : []),
107
+ line(handoff ? ` Saved handoff (public): ${savedAge(handoff.updatedAt)}` : ' Saved handoff: none'),
108
+ ];
109
+ selectedDetail = [
110
+ ...context,
111
+ ...(handoff ? wrapSummary(`Handoff: ${handoff.summary}`, Math.max(0, width - 2), Math.min(4, Math.max(0, detailBudget - context.length))).map(text => line(` ${text}`)) : []),
112
+ ...(handoff ? [line(` Handoff saved: ${handoff.updatedAt}`)] : []),
113
+ ...(report ? [
114
+ line(` Report: ${reportLabels[report.status]} · ${savedAge(report.updatedAt)}`),
115
+ line(' Self-reported, pending review'),
116
+ ...wrapSummary(`Summary: ${report.summary}`, Math.max(0, width - 2), 2).map(text => line(` ${text}`)),
117
+ ] : []),
118
+ ...connectionDetails,
119
+ line(` Responsibility: ${worker.description || 'Not specified'}`),
120
+ line(` Observed status: ${activity} · ${age}`),
121
+ line(` Last activity: ${evidence}`),
122
+ ...(closeJob ? [line(` Close updated: ${closeJob.updatedAt}`), line(' Workflow state is not proof all child processes terminated')] : []),
123
+ ];
124
+ } else if (selected && showDetails && report) {
98
125
  const elapsed = now - Date.parse(report.updatedAt);
99
126
  const reportAge = !Number.isFinite(elapsed) || elapsed < 0 ? 'clock uncertain' : ageLabel(elapsed) + (elapsed > snapshot.staleAfterMs ? ' (old)' : '');
100
127
  const contextRows = detailBudget >= 8 ? [
@@ -10,7 +10,7 @@ export const EVENT_TYPES = ['runtime.starting', 'runtime.ready', 'runtime.closed
10
10
  export type EventType = typeof EVENT_TYPES[number];
11
11
  const OUTCOMES = ['attempted', 'returned', 'failed', 'http_receipt', 'handler_failed', 'started', 'settled', 'snapshot', 'ended', 'written', 'removed', 'ready'] as const;
12
12
  const ERROR_CODES = ['operation_failed', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EADDRINUSE', 'EACCES', 'EPERM', 'ENOENT', 'ENOSPC'] as const;
13
- const KINDS = ['message', 'report', 'registration', 'status', 'request_status', 'reload', 'stop', 'close'] as const;
13
+ const KINDS = ['message', 'report', 'registration', 'status', 'request_status', 'reload', 'stop', 'close', 'close_prepare', 'close_identity', 'close_request', 'handoff_report', 'close_ready', 'close_commit'] as const;
14
14
  const OPERATIONS = ['configure_worker', 'set_multiplexer', 'remove_worker', 'create_worker', 'resume_worker', 'port_update', 'initialize'] as const;
15
15
  export interface EventMetadata {
16
16
  peerSessionId?: string;
@@ -0,0 +1,138 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { constants } from 'node:fs';
4
+ import { open, readFile, realpath } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import type { Run } from './launcher.js';
7
+ import type { CloseProvider, WorkerPaneIdentity } from './handoff.js';
8
+
9
+ interface ProcessIdentity { start: string; state: string }
10
+ export interface PaneCloseOptions {
11
+ sessionId(): string;
12
+ sessionFile(): string | undefined;
13
+ env?: NodeJS.ProcessEnv;
14
+ platform?: string;
15
+ pid?: number;
16
+ run?: Run;
17
+ processIdentity?: (pid: number) => Promise<ProcessIdentity | undefined>;
18
+ verifySession?: (file: string, id: string) => Promise<void>;
19
+ verificationMs?: number;
20
+ }
21
+ const rejected = () => new Error('PiIntercom: worker pane identity could not be verified; no close submitted.');
22
+ const exec: Run = async (file, args) => (await promisify(execFile)(file, args, {
23
+ windowsHide: true, timeout: 4000, maxBuffer: 1024 * 1024,
24
+ })).stdout;
25
+
26
+ /** Linux process start ticks distinguish a reused PID from the original worker. */
27
+ export async function linuxProcessIdentity(pid: number): Promise<ProcessIdentity | undefined> {
28
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw rejected();
29
+ let stat: string;
30
+ try { stat = await readFile(`/proc/${pid}/stat`, 'utf8'); }
31
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw rejected(); }
32
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
33
+ if (!/^[0-9]+$/.test(fields[19] ?? '') || !/^[A-Za-z]$/.test(fields[0] ?? '')) throw rejected();
34
+ return { start: fields[19], state: fields[0] };
35
+ }
36
+ async function verifySessionHeader(file: string, id: string): Promise<void> {
37
+ if (!path.isAbsolute(file) || file.length > 4096 || file.includes('\0')) throw rejected();
38
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
39
+ try {
40
+ if (!(await handle.stat()).isFile()) throw rejected();
41
+ // Inspect only the first session-header line, never transcript messages.
42
+ const buffer = Buffer.alloc(4096);
43
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
44
+ const end = buffer.subarray(0, bytesRead).indexOf(10);
45
+ if (end < 0) throw rejected();
46
+ const header = JSON.parse(buffer.subarray(0, end).toString('utf8'));
47
+ if (header?.type !== 'session' || header.id !== id) throw rejected();
48
+ } finally { await handle.close(); }
49
+ }
50
+ const alive = (identity: ProcessIdentity | undefined, start: string) =>
51
+ !!identity && identity.start === start && !['Z', 'X', 'x'].includes(identity.state);
52
+
53
+ /** Linux Herdr only. Identity-checked best effort; Herdr has no atomic compare-and-close API. */
54
+ export function createCloseProvider(options: PaneCloseOptions): CloseProvider | undefined {
55
+ const env = options.env ?? process.env;
56
+ if ((options.platform ?? process.platform) !== 'linux' || env.HERDR_ENV !== '1' || !env.HERDR_PANE_ID) return;
57
+ const run = options.run ?? exec;
58
+ const processIdentity = options.processIdentity ?? linuxProcessIdentity;
59
+ const verifySession = options.verifySession ?? verifySessionHeader;
60
+ const ownPid = options.pid ?? process.pid;
61
+ const verificationMs = Math.max(0, Math.min(2000, options.verificationMs ?? 1500));
62
+ async function query(args: string[]): Promise<any> {
63
+ const output = await run('herdr', args);
64
+ if (Buffer.byteLength(output) > 1024 * 1024) throw rejected();
65
+ return JSON.parse(output)?.result;
66
+ }
67
+ async function caller(): Promise<any> {
68
+ const pane = (await query(['pane', 'current', '--current']))?.pane;
69
+ if (!pane || typeof pane.pane_id !== 'string' || typeof pane.workspace_id !== 'string' || typeof pane.terminal_id !== 'string') throw rejected();
70
+ return pane;
71
+ }
72
+ async function verifyPane(pane: any, identity: WorkerPaneIdentity): Promise<void> {
73
+ if (!pane || pane.pane_id !== identity.paneId || pane.workspace_id !== identity.workspaceId ||
74
+ pane.terminal_id !== identity.terminalId || pane.agent !== 'pi' ||
75
+ pane.agent_session?.source !== 'herdr:pi' || pane.agent_session?.kind !== 'path' ||
76
+ typeof pane.agent_session.value !== 'string' || !path.isAbsolute(identity.sessionFile) ||
77
+ !Number.isSafeInteger(identity.pid) || identity.pid <= 0 || !/^[0-9]+$/.test(identity.processStart)) throw rejected();
78
+ if (await realpath(pane.agent_session.value) !== await realpath(identity.sessionFile)) throw rejected();
79
+ await verifySession(identity.sessionFile, identity.sessionId);
80
+ const info = (await query(['pane', 'process-info', '--pane', identity.paneId]))?.process_info;
81
+ if (info?.pane_id !== identity.paneId || !Array.isArray(info.foreground_processes) ||
82
+ !info.foreground_processes.some((p: { pid?: number }) => p.pid === identity.pid) ||
83
+ !alive(await processIdentity(identity.pid), identity.processStart)) throw rejected();
84
+ }
85
+ async function inspect(identity: WorkerPaneIdentity, expectedSessionId: string, assertCurrent: () => void): Promise<void> {
86
+ assertCurrent();
87
+ if (identity.sessionId !== expectedSessionId || expectedSessionId === options.sessionId() || identity.pid === ownPid) throw rejected();
88
+ const own = await caller();
89
+ assertCurrent();
90
+ if (own.pane_id === identity.paneId || own.workspace_id !== identity.workspaceId) throw rejected();
91
+ await verifyPane((await query(['pane', 'get', identity.paneId]))?.pane, identity);
92
+ assertCurrent();
93
+ }
94
+ return {
95
+ async getIdentity() {
96
+ try {
97
+ const sessionId = options.sessionId(), sessionFile = options.sessionFile();
98
+ if (!sessionFile) throw rejected();
99
+ const pane = await caller();
100
+ const process = await processIdentity(ownPid);
101
+ if (!process || !alive(process, process.start)) throw rejected();
102
+ const identity: WorkerPaneIdentity = { workspaceId: pane.workspace_id, paneId: pane.pane_id,
103
+ terminalId: pane.terminal_id, sessionId, sessionFile, pid: ownPid, processStart: process.start };
104
+ await verifyPane(pane, identity);
105
+ if (options.sessionId() !== sessionId || options.sessionFile() !== sessionFile) throw rejected();
106
+ return identity;
107
+ } catch { throw rejected(); }
108
+ },
109
+ async inspect(identity, expectedSessionId, assertCurrent) {
110
+ try { await inspect(identity, expectedSessionId, assertCurrent); } catch { throw rejected(); }
111
+ },
112
+ async close(identity, expectedSessionId, assertCurrent, beforeSubmit) {
113
+ try { await inspect(identity, expectedSessionId, assertCurrent); } catch { throw rejected(); }
114
+ assertCurrent();
115
+ // Revalidate worker settlement only AFTER potentially slow ownership reads.
116
+ // Herdr still has no atomic cross-process identity/idle compare-and-close.
117
+ await beforeSubmit();
118
+ assertCurrent();
119
+ // Exactly one explicit pane target. No tab/workspace close, retry, or force kill.
120
+ // A CLI timeout can mean the mutation happened: caller must persist uncertainty.
121
+ try { await run('herdr', ['pane', 'close', identity.paneId]); }
122
+ catch { throw new Error('PiIntercom: pane close outcome uncertain; inspect before any retry.'); }
123
+ let paneClosed = false, workerExited = false;
124
+ try {
125
+ const panes = (await query(['pane', 'list', '--workspace', identity.workspaceId]))?.panes;
126
+ paneClosed = Array.isArray(panes) && panes.every(p => typeof p?.pane_id === 'string') &&
127
+ !panes.some(p => p.pane_id === identity.paneId);
128
+ const deadline = Date.now() + verificationMs;
129
+ do {
130
+ workerExited = !alive(await processIdentity(identity.pid), identity.processStart);
131
+ if (workerExited || Date.now() >= deadline) break;
132
+ await new Promise(resolve => setTimeout(resolve, 50));
133
+ } while (true);
134
+ } catch { /* Verification failure is uncertainty, never an automatic retry. */ }
135
+ return { paneClosed, workerExited };
136
+ },
137
+ };
138
+ }