@comput/pi-intercom 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -150,7 +150,7 @@ export async function ensureCoreMonitorPane(options: CoreMonitorOptions): Promis
150
150
  // All identity reads and mutations share one verified connection. Repeated
151
151
  // coreCall invocations reconnect and cannot bind this multi-step operation.
152
152
  if (!options.call || options.call === coreCall) {
153
- return withCoreSession(call => ensureCoreMonitorPane({ ...options, call }), { endpoint: env.HC_SOCKET });
153
+ return withCoreSession(call => ensureCoreMonitorPane({ ...options, call }), { endpoint: env.HC_TERMINAL_SOCKET ?? env.HC_SOCKET });
154
154
  }
155
155
  const root = await realpath(options.root);
156
156
  const invoke = options.call;
@@ -323,7 +323,7 @@ export async function closeCoreMonitorPane(options: CoreMonitorOptions): Promise
323
323
  const check = () => options.assertCurrent?.();
324
324
  check();
325
325
  if (!options.call || options.call === coreCall) {
326
- return withCoreSession(call => closeCoreMonitorPane({ ...options, call }), { endpoint: env.HC_SOCKET });
326
+ return withCoreSession(call => closeCoreMonitorPane({ ...options, call }), { endpoint: env.HC_TERMINAL_SOCKET ?? env.HC_SOCKET });
327
327
  }
328
328
  const invoke = options.call;
329
329
  const call: CoreCall = async (method, params) => { check(); const result = await invoke(method, params); check(); return result; };
package/src/herdr-core.ts CHANGED
@@ -21,7 +21,7 @@ const sameCore = (a: any, b: any): boolean => a.id === b.id && a.name === b.name
21
21
  const READ_METHODS = new Set(['hello', 'server.status', 'terminal.get', 'terminal.list', 'doc.get']);
22
22
 
23
23
  export interface CoreSessionOptions {
24
- /** Explicit documented HC_SOCKET endpoint; no endpoint discovery or path guessing. */
24
+ /** Explicit core endpoint. Otherwise use the calling terminal's socket first. */
25
25
  endpoint?: string;
26
26
  /** Validate operation capabilities before permitting any mutation. */
27
27
  requiredMethods?: readonly string[];
@@ -35,9 +35,10 @@ export interface CoreSessionOptions {
35
35
  /** Resolve only documented Unix defaults. An existing config may override the
36
36
  * socket, so require explicit HC_SOCKET rather than silently ignoring that file. */
37
37
  export async function defaultCoreEndpoint(env: NodeJS.ProcessEnv = process.env, home = homedir(), uid = process.getuid?.()): Promise<string> {
38
- if (env.HC_SOCKET !== undefined) {
39
- if (!env.HC_SOCKET || !isAbsolute(env.HC_SOCKET) || env.HC_SOCKET.includes('\0')) throw failure('invalid explicit HC_SOCKET');
40
- return env.HC_SOCKET;
38
+ const inheritedSocket = env.HC_TERMINAL_SOCKET ?? env.HC_SOCKET;
39
+ if (inheritedSocket !== undefined) {
40
+ if (!inheritedSocket || !isAbsolute(inheritedSocket) || /[\x00-\x1f\x7f]/.test(inheritedSocket)) throw failure('invalid inherited core socket');
41
+ return inheritedSocket;
41
42
  }
42
43
  const session = env.HC_SESSION ?? 'default';
43
44
  if (!/^[a-zA-Z0-9_-]+$/.test(session) || session.trim() !== session || session.length > 64) throw failure('unsupported HC_SESSION; set explicit HC_SOCKET');
@@ -123,7 +124,7 @@ export async function withCoreSession<T>(operation: (call: CoreCall) => Promise<
123
124
  };
124
125
  const run = async () => {
125
126
  let before: any;
126
- const endpoint = options.endpoint ?? process.env.HC_SOCKET ?? (!options.startClient && process.platform !== 'win32' ? await defaultCoreEndpoint() : undefined);
127
+ const endpoint = options.endpoint ?? process.env.HC_TERMINAL_SOCKET ?? process.env.HC_SOCKET ?? (!options.startClient && process.platform !== 'win32' ? await defaultCoreEndpoint() : undefined);
127
128
  if (options.startClient || !endpoint) {
128
129
  if (options.startClient && !options.readStatus) throw failure('test client requires status preflight');
129
130
  if (!options.startClient && process.platform !== 'win32') throw failure('explicit HC_SOCKET required: Unix hc server status/connect may autostart; no client started');
@@ -169,7 +170,11 @@ export async function withCoreSession<T>(operation: (call: CoreCall) => Promise<
169
170
  const code = Number.isSafeInteger(message.error?.code) ? `; RPC code ${message.error.code}` : '';
170
171
  // Server messages/data may echo credentials or request payloads. Keep only
171
172
  // our method name and the numeric error code in public diagnostics.
172
- return fail(`API rejected request ${pending.method}${code}`);
173
+ const registryStopped = message.error?.message === 'cannot save terminals: registry writer stopped';
174
+ const detail = registryStopped
175
+ ? '; Herdr core registry writer stopped: core recovery is required; do not retry worker creation or delete Intercom config'
176
+ : '';
177
+ return fail(`API rejected request ${pending.method}${code}${detail}`);
173
178
  }
174
179
  const current = pending; pending = undefined;
175
180
  current.resolve(message.result);
package/src/index.ts CHANGED
@@ -20,8 +20,7 @@ const tools: [string, string, TSchema][] = [
20
20
  ['worker_status', 'Configured sessions only. Read paginated JSON worker observations and public reports from local files, optionally by worker name. Last-observed status is not live liveness or task completion; reports are self-reported, not approval. Local-only by default; probe:true performs bounded loopback identity checks for this page only, without worker prompts or Telegram dependency. Disconnected means endpoint unreachable, not process termination. Follow nextOffset for further pages; null report means no readable active report.', Type.Object({ name: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })), offset: Type.Optional(Type.Integer({ minimum: 0 })), limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 20 })), probe: Type.Optional(Type.Boolean()) })],
21
21
  ['list', 'Configured sessions only. Read current saved names, responsibilities, session IDs, roles and ports. No live probing. Output limited to 50 KiB/2000 lines; full data remains in config.json.', Type.Object({})],
22
22
  ['request_status', 'Coordinator only. Ask worker extension to send an independent sessionId/port/busy report without a model turn on worker. No synchronous status reply.', to],
23
- ['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 })) })],
24
- ['stop_reminders', 'Coordinator only. Disable the five-minute orchestration reminders until the next worker-directed call. Use when there is genuinely nothing to follow up on. Stops only reminders, not workers, close jobs or model work. Reminder state is session-local and clears on shutdown/reload.', Type.Object({})],
23
+ ['report_work', 'Configured, responsibility-loaded workers only. Store one public report (blocked, needs_decision, ready_for_review) and notify the coordinator; clear retires it silently. Put long details in a file and reference its path. 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 })) })],
25
24
  ['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({})],
26
25
  ['stop_worker', UNSUPPORTED_CANCELLATION, to],
27
26
  ['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],
@@ -235,7 +234,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
235
234
  successful.add(entry.message.toolCallId);
236
235
  }
237
236
  }
238
- runtime?.workerSettled(successful);
237
+ void runtime?.workerSettled(successful);
239
238
  });
240
239
  pi.on('message_update', (event, ctx) => {
241
240
  context = ctx;
@@ -255,7 +254,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
255
254
  if (!runtime) return;
256
255
  const { me } = await runtime.state();
257
256
  const loaded = runtime.responsibility;
258
- 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.') };
257
+ return { systemPrompt: event.systemPrompt + '\n\nPiIntercom: communicates; Pi decides orchestration. Responsibility is not a work assignment. Do not implement unrelated work from findings. After coordinator-assigned work, file intercom_report_work (or message the coordinator) before ending the turn, then wait; do not autonomously exit. Keep reports short: put long results in a file and reference its path. Worker reports are self-reported, not verified completion or approval. 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.') };
259
258
  });
260
259
  for (const [operation, description, parameters] of tools) {
261
260
  pi.registerTool({
@@ -274,7 +273,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
274
273
  if (!state.me?.coordinator) throw new Error('PiIntercom: coordinator permission required');
275
274
  monitorAutoEpoch++; // Fence prior automatic passes; lock refusal never schedules a retry.
276
275
  }
277
- const result = await current.tool(operation, args as Record<string, unknown>, _id, signal);
276
+ const result = await current.tool(operation, args as Record<string, unknown>, _id);
278
277
  if (operation === 'configure_worker') await ensureCoordinatorMonitor(current, ctx, started);
279
278
  const output = truncateHead(JSON.stringify(result, null, 2));
280
279
  return { content: [{ type: 'text', text: output.content + (output.truncated ? `\n[Truncated; full shared configuration: ${current.store.file}]` : '') }], details: {} };
package/src/launcher.ts CHANGED
@@ -67,7 +67,7 @@ export function launchers(options: LauncherOptions) {
67
67
  try {
68
68
  // Injection is a trusted test seam; production verifies hello/status
69
69
  // and the APIs needed for launch once, without reconnecting between steps.
70
- return await (options.coreCall ? operation(options.coreCall) : withCoreSession(operation, { endpoint: env.HC_SOCKET, requiredMethods: ['terminal.get', 'terminal.run', 'terminal.label', 'doc.get', 'doc.set'] }));
70
+ return await (options.coreCall ? operation(options.coreCall) : withCoreSession(operation, { endpoint: env.HC_TERMINAL_SOCKET ?? env.HC_SOCKET, requiredMethods: ['terminal.get', 'terminal.run', 'terminal.label', 'doc.get', 'doc.set'] }));
71
71
  } catch (e) {
72
72
  if (attempted) throw Object.assign(new Error('HC worker launch or placement failed; outcome unknown, terminal/process and app tab may remain; no automatic cleanup/retry/replacement or legacy fallback'), { outcomeUncertain: true });
73
73
  fail(`HC launch preflight failed: ${String(e)}; no fallback or launch attempted`);
@@ -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', 'close_prepare', 'close_identity', 'close_request', 'handoff_report', 'close_ready', 'close_commit'] as const;
13
+ const KINDS = ['message', 'report', 'registration', 'status', 'idle', '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;
package/src/runtime.ts CHANGED
@@ -9,7 +9,6 @@ import { readObservationSnapshot } from './snapshot.js';
9
9
  import { workerStatusPage } from './worker-status.js';
10
10
  import { probeWorker, probeWorkers } from './connections.js';
11
11
  import { HandoffWorkflow, HANDOFF_KINDS, fencedClose, type CloseProvider, type HandoffKind } from './handoff.js';
12
- import { CoordinatorReminders, type ReminderClock } from './reminders.js';
13
12
 
14
13
  export const UNSUPPORTED_CANCELLATION = 'Unsupported Pi host: stop_worker and legacy graceful-close control are disabled. Pi 0.84.4 extension abort does not cancel retry backoff/continuations; graceful shutdown cannot guarantee no queued work restarts. No cancellation or shutdown was performed. close_worker uses a separate supported-provider owned-pane closure contract, not graceful cancellation. See references/implementation-blocker.md. A verified supported host API is required for graceful cancellation (no version-only override).';
15
14
  export interface Host {
@@ -37,7 +36,6 @@ export interface RuntimeOptions {
37
36
  closeProvider?: CloseProvider;
38
37
  /** Test seam; production defaults to 120 seconds, values above that are capped. */
39
38
  closeTimeoutMs?: number;
40
- reminderClock?: ReminderClock;
41
39
  monitor?: MonitorOperations;
42
40
  /** Explicit launcher-provided root must equal canonical cwd; no parent-root exception. */
43
41
  workspaceRoot?: string;
@@ -60,11 +58,24 @@ export class Intercom {
60
58
  private probeController = new AbortController();
61
59
  private resumeFences = new Map<string, { inFlight: boolean; submitted: boolean; announced: boolean }>();
62
60
  private handoff?: HandoffWorkflow;
63
- private reminders?: CoordinatorReminders;
64
- private reminderRevision = 0;
65
- private reminderInvocation = 0;
61
+ /** Worker only: the coordinator sent work and has heard nothing back since. */
62
+ private owesCoordinator = false;
66
63
  workerStarted(): void { this.handoff?.workerStarted(); }
67
- workerSettled(successfulToolCallIds: ReadonlySet<string>): void { this.handoff?.workerSettled(successfulToolCallIds); }
64
+ /** Resolves once any idle notice has been attempted; callers need not await it. */
65
+ workerSettled(successfulToolCallIds: ReadonlySet<string>): Promise<void> {
66
+ this.handoff?.workerSettled(successfulToolCallIds);
67
+ if (!this.owesCoordinator || this.handoff?.workerClosing) return Promise.resolve();
68
+ // One event-driven notice, sent in code: no timer, no model turn here.
69
+ this.owesCoordinator = false;
70
+ return this.notifyIdle().catch(() => { /* Best effort; never retried. */ });
71
+ }
72
+ private async notifyIdle(): Promise<void> {
73
+ const assertValid = this.validity();
74
+ const { config, me } = await this.state();
75
+ assertValid();
76
+ if (!me || me.coordinator || !this.responsibility) return;
77
+ await this.transmit(coordinator(config).name, 'idle');
78
+ }
68
79
  private captureObserver(): (event: EventType, metadata?: EventMetadata) => void {
69
80
  const observer = this.observer;
70
81
  return (event, metadata = {}) => {
@@ -127,11 +138,6 @@ export class Intercom {
127
138
  const config = await this.store.read();
128
139
  assertValid();
129
140
  const me = config.agents.find(a => a.sessionId === this.id());
130
- this.reminders = new CoordinatorReminders({
131
- isCoordinator: async () => { const fresh = await this.state(); assertValid(); return fresh.me?.coordinator === true; },
132
- busy: () => this.host.busy(),
133
- deliver: message => { assertValid(); this.host.deliver(message, false); },
134
- }, this.options.reminderClock);
135
141
  this.handoff = new HandoffWorkflow({
136
142
  state: () => this.state(), assertCurrent: assertValid,
137
143
  update: async (mutate, guard) => {
@@ -189,8 +195,7 @@ export class Intercom {
189
195
  this.active = false; this.generation++;
190
196
  this.probeController.abort();
191
197
  this.handoff?.dispose(); this.handoff = undefined;
192
- this.reminderRevision = ++this.reminderInvocation;
193
- this.reminders?.dispose(); this.reminders = undefined;
198
+ this.owesCoordinator = false;
194
199
  const endpoint = this.endpoint; this.endpoint = undefined;
195
200
  this.responsibility = undefined;
196
201
  const closing = (async () => {
@@ -374,19 +379,27 @@ export class Intercom {
374
379
  if (!fresh.config.agents.some(agent => agent.sessionId === message.from && !agent.coordinator)) fail('reporting worker is no longer configured');
375
380
  await saveWorkerReport(this.store.root, { version: 1, sessionId: message.from, ...payload, updatedAt: new Date().toISOString() }, assertValid);
376
381
  assertValid();
377
- try {
378
- notify('worker report', `Report: ${payload.status}\n${payload.summary}\nThis is a worker-authored public report, not approval or verified completion. Evaluate it before deciding any next step. Clearing retires the report only; it does not resume or complete work.`);
379
- } catch { fail('Report stored, but coordinator notification failed or became uncertain; do not blindly resend'); }
382
+ // Retiring a report needs no decision: store it without waking the coordinator.
383
+ if (payload.status === 'clear') return;
384
+ try { notify('worker report', `${payload.status}: ${payload.summary}`); }
385
+ catch { fail('Report stored, but coordinator notification failed or became uncertain; do not blindly resend'); }
380
386
  });
381
387
  this.reportWrites = pending.catch(() => {}).finally(() => { this.pendingReports--; });
382
388
  await pending;
383
389
  return;
384
390
  }
391
+ if (message.kind === 'idle') {
392
+ requireCoordinator(config, id);
393
+ if (!sender || sender.coordinator) fail('idle notices require a configured worker sender');
394
+ notify('worker idle', 'Turn ended without a report or message to you.'); return;
395
+ }
385
396
  if (message.kind === 'message') {
386
397
  if (!sender || !me) fail('agent messaging requires configured sender and recipient; anonymous permissions TODO');
387
398
  if (!this.responsibility) fail('worker must load responsibility before receiving work');
388
399
  if (this.handoff?.workerClosing || fencedClose(me.closeJob)) fail('worker close is active or uncertain; new Intercom work is fenced');
389
- notify('agent message', message.payload.message as string); return;
400
+ notify('agent message', message.payload.message as string);
401
+ if (sender.coordinator && !me.coordinator) this.owesCoordinator = true;
402
+ return;
390
403
  }
391
404
  if (!sender?.coordinator) fail('control requires current coordinator sender session ID');
392
405
  if (me?.coordinator) fail('worker control cannot target coordinator');
@@ -408,17 +421,7 @@ export class Intercom {
408
421
  }
409
422
  fail('unsupported control');
410
423
  }
411
- async tool(operation: string, args: Record<string, unknown>, toolCallId?: string, reminderSignal?: AbortSignal): Promise<unknown> {
412
- // Reserve invocation order before state/directory awaits, but only VALID
413
- // reminder actions advance the accepted revision. Invalid/nonworker calls
414
- // must not supersede a pending stop or suppress an older valid preflight.
415
- const invocation = ++this.reminderInvocation;
416
- const armReminder = () => {
417
- if (invocation >= this.reminderRevision && !reminderSignal?.aborted) {
418
- this.reminderRevision = invocation;
419
- this.reminders?.arm(reminderSignal);
420
- }
421
- };
424
+ async tool(operation: string, args: Record<string, unknown>, toolCallId?: string): Promise<unknown> {
422
425
  const record = this.captureObserver();
423
426
  const assertValid = this.validity();
424
427
  const { id, config, me } = await this.state();
@@ -449,6 +452,7 @@ export class Intercom {
449
452
  if (!me || me.coordinator || !this.responsibility) fail('report_work requires a configured, responsibility-loaded worker');
450
453
  const payload = reportPayload(args);
451
454
  await this.transmit(coordinator(config).name, 'report', payload);
455
+ if (payload.status !== 'clear') this.owesCoordinator = false;
452
456
  return { accepted: true, coordinatorEvaluation: 'not awaited' };
453
457
  }
454
458
  if (operation === 'send') {
@@ -456,8 +460,9 @@ export class Intercom {
456
460
  const recipient = named(config, args.to as string);
457
461
  text(args.message, 'message', 48000);
458
462
  if (this.handoff?.workerClosing || fencedClose(me.closeJob) || this.handoff?.isClosing(recipient.sessionId) || fencedClose(recipient.closeJob)) fail('worker close is active or uncertain; new Intercom work is fenced');
459
- if (me.coordinator && !recipient.coordinator) armReminder();
460
- await this.transmit(args.to as string, 'message', { message: args.message }); return { accepted: true, completion: 'not awaited' };
463
+ await this.transmit(args.to as string, 'message', { message: args.message });
464
+ if (recipient.coordinator) this.owesCoordinator = false;
465
+ return { accepted: true, completion: 'not awaited' };
461
466
  }
462
467
  requireCoordinator(config, id);
463
468
  if (operation === 'configure_models') {
@@ -491,11 +496,6 @@ export class Intercom {
491
496
  if (operation === 'open_monitor' || operation === 'close_monitor') {
492
497
  return this.operateMonitor(operation, args);
493
498
  }
494
- if (operation === 'stop_reminders') {
495
- const current = invocation >= this.reminderRevision;
496
- if (current) { this.reminderRevision = invocation; this.reminders?.stop(); }
497
- return { stopped: current };
498
- }
499
499
  if (operation === 'stop_worker') fail(UNSUPPORTED_CANCELLATION);
500
500
  if (operation === 'configure_worker') {
501
501
  const assertConfigurable = () => {
@@ -503,8 +503,6 @@ export class Intercom {
503
503
  if (this.handoff?.isClosing(args.sessionId as string) || this.resumeFences.has(args.sessionId as string)) fail('worker lifecycle operation is in flight; configuration is fenced');
504
504
  };
505
505
  assertConfigurable();
506
- // Validate the candidate without writing, so invalid input never arms a
507
- // reminder; persistence failures after valid initiation still do.
508
506
  const relative = await directory(this.store.root, args.projectDirectory as string);
509
507
  assertConfigurable();
510
508
  const candidate: Agent = { sessionId: args.sessionId as string, name: args.name as string, description: args.description as string,
@@ -513,7 +511,6 @@ export class Intercom {
513
511
  const previous = config.agents.find(a => a.sessionId === candidate.sessionId);
514
512
  if (fencedClose(previous?.closeJob)) fail('worker close is active or uncertain; configuration is fenced');
515
513
  validateConfig({ ...config, agents: [...config.agents.filter(a => a.sessionId !== candidate.sessionId), candidate] });
516
- armReminder();
517
514
  await this.store.configure(id, args as unknown as Omit<Agent, 'coordinator'>, assertConfigurable);
518
515
  record('config.changed', { operation: 'configure_worker', peerSessionId: args.sessionId as string, peerName: args.name as string, outcome: 'written' });
519
516
  return { written: true, reloaded: false };
@@ -526,7 +523,6 @@ export class Intercom {
526
523
  const relative = await directory(this.store.root, (args.projectDirectory as string | undefined) ?? '.');
527
524
  assertValid();
528
525
  if (relative !== '.') fail('worker working directory must equal the config root; subdirectory launches would read a forbidden parent config');
529
- armReminder();
530
526
  return this.launchObserved({ multiplexer: config.multiplexer, cwd: path.resolve(this.store.root, relative), workspaceRoot: this.store.root });
531
527
  }
532
528
  const target = named(config, args.to as string);
@@ -535,12 +531,10 @@ export class Intercom {
535
531
  if (!this.options.closeProvider || !this.handoff || config.multiplexer !== 'herdr') fail('Owned-pane close requires supported Linux Herdr provider; no closure attempted');
536
532
  if (this.resumeFences.has(target.sessionId)) fail('resume is in flight; close is fenced');
537
533
  if (fencedClose(target.closeJob) && !this.handoff.isClosing(target.sessionId)) fail('worker close is active or uncertain; close is fenced');
538
- armReminder();
539
534
  return { job: await this.handoff.request(target), completion: 'not awaited', contract: 'best-effort owned-pane closure; not all-child-process termination' };
540
535
  }
541
536
  if (['reload_worker', 'resume_worker', 'remove_worker'].includes(operation) && (this.handoff?.isClosing(target.sessionId) || fencedClose(target.closeJob))) fail('worker close is active or uncertain; operation is fenced');
542
537
  if (operation === 'reload_worker' || operation === 'request_status') {
543
- armReminder();
544
538
  await this.transmit(target.name, operation === 'reload_worker' ? 'reload' : 'request_status');
545
539
  return { accepted: true, completion: 'not awaited' };
546
540
  }
@@ -556,7 +550,6 @@ export class Intercom {
556
550
  if (this.handoff?.isClosing(target.sessionId)) fail('worker close is active or uncertain; resume is fenced');
557
551
  const fence = { inFlight: true, submitted: false, announced: false };
558
552
  this.resumeFences.set(target.sessionId, fence);
559
- armReminder();
560
553
  let completed = false;
561
554
  try {
562
555
  const connection = await (this.options.probe ?? probeWorker)(target, { signal: this.probeController.signal });
package/src/transport.ts CHANGED
@@ -5,7 +5,7 @@ import { HANDOFF_KINDS, validateHandoffPayload, type HandoffKind } from './hando
5
5
 
6
6
  export const BODY_LIMIT = 64 * 1024;
7
7
  export const RECEIPT_TIMEOUT = 5000;
8
- export type Kind = 'message' | 'report' | 'registration' | 'status' | 'request_status' | 'reload' | 'stop' | 'close' | HandoffKind;
8
+ export type Kind = 'message' | 'report' | 'registration' | 'status' | 'idle' | 'request_status' | 'reload' | 'stop' | 'close' | HandoffKind;
9
9
  export interface Envelope {
10
10
  version: 1;
11
11
  kind: Kind;
@@ -24,7 +24,7 @@ export function reportPayload(payload: Record<string, unknown>): { status: Repor
24
24
  }
25
25
  export function envelope(value: unknown): Envelope {
26
26
  const m = value as Envelope;
27
- if (!m || m.version !== 1 || !['message', 'report', 'registration', 'status', 'request_status', 'reload', 'stop', 'close', ...HANDOFF_KINDS].includes(m.kind)) fail('invalid wire schema/version/kind');
27
+ if (!m || m.version !== 1 || !['message', 'report', 'registration', 'status', 'idle', 'request_status', 'reload', 'stop', 'close', ...HANDOFF_KINDS].includes(m.kind)) fail('invalid wire schema/version/kind');
28
28
  text(m.from, 'sender sessionId', 256); text(m.to, 'recipient sessionId', 256);
29
29
  if (m.correlationId !== undefined && (typeof m.correlationId !== 'string' || !/^[a-zA-Z0-9-]{1,128}$/.test(m.correlationId))) fail('invalid correlation ID');
30
30
  if (!m.payload || Array.isArray(m.payload) || typeof m.payload !== 'object') fail('invalid payload');
@@ -1,28 +0,0 @@
1
- export declare const REMINDER_INTERVAL_MS: number;
2
- export declare const REMINDER_TEXT = "Intercom reminder: Review outstanding delegated work and worker reports. If follow-up is needed, take the next appropriate action. Do not assume workers have finished or stopped.\n\nIf there is genuinely nothing to follow up on, call intercom_stop_reminders. Otherwise, reminders continue every five minutes; a new worker call resets the timer.\n\nThis reminder does not authorize new work, retries, worker closure, or publication.";
3
- export interface ReminderClock {
4
- schedule(callback: () => void, milliseconds: number): () => void;
5
- }
6
- interface ReminderHost {
7
- isCoordinator(): Promise<boolean>;
8
- busy(): boolean;
9
- deliver(text: string): void;
10
- }
11
- /** Ephemeral reminder only: never worker actions, network retries or a backlog. */
12
- export declare class CoordinatorReminders {
13
- private readonly host;
14
- private readonly timer;
15
- private generation;
16
- private tick;
17
- private checking;
18
- private disposed;
19
- private cancel?;
20
- private detachOwner?;
21
- constructor(host: ReminderHost, timer?: ReminderClock);
22
- arm(signal?: AbortSignal): void;
23
- stop(): void;
24
- dispose(): void;
25
- private current;
26
- private schedule;
27
- }
28
- export {};
package/dist/reminders.js DELETED
@@ -1,81 +0,0 @@
1
- export const REMINDER_INTERVAL_MS = 5 * 60 * 1000;
2
- export const REMINDER_TEXT = 'Intercom reminder: Review outstanding delegated work and worker reports. If follow-up is needed, take the next appropriate action. Do not assume workers have finished or stopped.\n\nIf there is genuinely nothing to follow up on, call intercom_stop_reminders. Otherwise, reminders continue every five minutes; a new worker call resets the timer.\n\nThis reminder does not authorize new work, retries, worker closure, or publication.';
3
- const clock = {
4
- schedule(callback, milliseconds) {
5
- const timer = setTimeout(callback, milliseconds);
6
- timer.unref();
7
- return () => clearTimeout(timer);
8
- },
9
- };
10
- /** Ephemeral reminder only: never worker actions, network retries or a backlog. */
11
- export class CoordinatorReminders {
12
- host;
13
- timer;
14
- generation = 0;
15
- tick = 0;
16
- checking = false;
17
- disposed = false;
18
- cancel;
19
- detachOwner;
20
- constructor(host, timer = clock) {
21
- this.host = host;
22
- this.timer = timer;
23
- }
24
- arm(signal) {
25
- if (this.disposed || signal?.aborted)
26
- return;
27
- this.stop();
28
- const generation = this.generation;
29
- if (signal) {
30
- const abort = () => { if (this.generation === generation)
31
- this.stop(); };
32
- signal.addEventListener('abort', abort, { once: true });
33
- this.detachOwner = () => signal.removeEventListener('abort', abort);
34
- }
35
- this.schedule(generation);
36
- }
37
- stop() {
38
- this.generation++;
39
- this.tick++;
40
- this.cancel?.();
41
- this.cancel = undefined;
42
- this.detachOwner?.();
43
- this.detachOwner = undefined;
44
- }
45
- dispose() { this.stop(); this.disposed = true; }
46
- current(generation, tick) {
47
- return !this.disposed && this.generation === generation && this.tick === tick;
48
- }
49
- schedule(generation) {
50
- this.cancel = this.timer.schedule(() => {
51
- if (this.disposed || generation !== this.generation)
52
- return;
53
- this.cancel = undefined;
54
- const tick = ++this.tick;
55
- this.schedule(generation);
56
- // A slow role read never creates concurrent reads or a queued reminder.
57
- // Advancing tick also invalidates any read from the preceding interval.
58
- if (this.checking)
59
- return;
60
- this.checking = true;
61
- void (async () => {
62
- try {
63
- const coordinator = await this.host.isCoordinator();
64
- if (!this.current(generation, tick))
65
- return;
66
- if (!coordinator) {
67
- this.stop();
68
- return;
69
- }
70
- if (!this.host.busy())
71
- this.host.deliver(REMINDER_TEXT);
72
- }
73
- catch { /* Unknown role/read/delivery outcome: no blind immediate replay. */ }
74
- finally {
75
- this.checking = false;
76
- }
77
- })();
78
- }, REMINDER_INTERVAL_MS);
79
- }
80
- }
81
- //# sourceMappingURL=reminders.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"reminders.js","sourceRoot":"","sources":["../src/reminders.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAClD,MAAM,CAAC,MAAM,aAAa,GAAG,ibAAib,CAAC;AAK/c,MAAM,KAAK,GAAkB;IAC3B,QAAQ,CAAC,QAAQ,EAAE,YAAY;QAC7B,MAAM,KAAK,GAAG,UAAU,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;QACjD,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;CACF,CAAC;AAMF,mFAAmF;AACnF,MAAM,OAAO,oBAAoB;IAOF;IAAqC;IAN1D,UAAU,GAAG,CAAC,CAAC;IACf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AC;IAC3B,CAAC;CACF"}
package/src/reminders.ts DELETED
@@ -1,69 +0,0 @@
1
- export const REMINDER_INTERVAL_MS = 5 * 60 * 1000;
2
- export const REMINDER_TEXT = 'Intercom reminder: Review outstanding delegated work and worker reports. If follow-up is needed, take the next appropriate action. Do not assume workers have finished or stopped.\n\nIf there is genuinely nothing to follow up on, call intercom_stop_reminders. Otherwise, reminders continue every five minutes; a new worker call resets the timer.\n\nThis reminder does not authorize new work, retries, worker closure, or publication.';
3
-
4
- export interface ReminderClock {
5
- schedule(callback: () => void, milliseconds: number): () => void;
6
- }
7
- const clock: ReminderClock = {
8
- schedule(callback, milliseconds) {
9
- const timer = setTimeout(callback, milliseconds);
10
- timer.unref();
11
- return () => clearTimeout(timer);
12
- },
13
- };
14
- interface ReminderHost {
15
- isCoordinator(): Promise<boolean>;
16
- busy(): boolean;
17
- deliver(text: string): void;
18
- }
19
- /** Ephemeral reminder only: never worker actions, network retries or a backlog. */
20
- export class CoordinatorReminders {
21
- private generation = 0;
22
- private tick = 0;
23
- private checking = false;
24
- private disposed = false;
25
- private cancel?: () => void;
26
- private detachOwner?: () => void;
27
- constructor(private readonly host: ReminderHost, private readonly timer: ReminderClock = clock) {}
28
- arm(signal?: AbortSignal): void {
29
- if (this.disposed || signal?.aborted) return;
30
- this.stop();
31
- const generation = this.generation;
32
- if (signal) {
33
- const abort = () => { if (this.generation === generation) this.stop(); };
34
- signal.addEventListener('abort', abort, { once: true });
35
- this.detachOwner = () => signal.removeEventListener('abort', abort);
36
- }
37
- this.schedule(generation);
38
- }
39
- stop(): void {
40
- this.generation++; this.tick++;
41
- this.cancel?.(); this.cancel = undefined;
42
- this.detachOwner?.(); this.detachOwner = undefined;
43
- }
44
- dispose(): void { this.stop(); this.disposed = true; }
45
- private current(generation: number, tick: number): boolean {
46
- return !this.disposed && this.generation === generation && this.tick === tick;
47
- }
48
- private schedule(generation: number): void {
49
- this.cancel = this.timer.schedule(() => {
50
- if (this.disposed || generation !== this.generation) return;
51
- this.cancel = undefined;
52
- const tick = ++this.tick;
53
- this.schedule(generation);
54
- // A slow role read never creates concurrent reads or a queued reminder.
55
- // Advancing tick also invalidates any read from the preceding interval.
56
- if (this.checking) return;
57
- this.checking = true;
58
- void (async () => {
59
- try {
60
- const coordinator = await this.host.isCoordinator();
61
- if (!this.current(generation, tick)) return;
62
- if (!coordinator) { this.stop(); return; }
63
- if (!this.host.busy()) this.host.deliver(REMINDER_TEXT);
64
- } catch { /* Unknown role/read/delivery outcome: no blind immediate replay. */ }
65
- finally { this.checking = false; }
66
- })();
67
- }, REMINDER_INTERVAL_MS);
68
- }
69
- }