@comput/pi-intercom 0.11.1 → 0.13.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.
- package/README.md +55 -30
- package/dist/config.d.ts +9 -1
- package/dist/config.js +28 -2
- package/dist/config.js.map +1 -1
- package/dist/connections.d.ts +2 -0
- package/dist/connections.js +3 -3
- package/dist/connections.js.map +1 -1
- package/dist/core-monitor.js +2 -2
- package/dist/core-monitor.js.map +1 -1
- package/dist/herdr-core.d.ts +1 -1
- package/dist/herdr-core.js +11 -6
- package/dist/herdr-core.js.map +1 -1
- package/dist/index.js +23 -10
- package/dist/index.js.map +1 -1
- package/dist/launcher.js +1 -1
- package/dist/launcher.js.map +1 -1
- package/dist/monitor-view.js +9 -2
- package/dist/monitor-view.js.map +1 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +1 -1
- package/dist/observability.js.map +1 -1
- package/dist/runtime.d.ts +15 -7
- package/dist/runtime.js +160 -67
- package/dist/runtime.js.map +1 -1
- package/dist/snapshot.js +2 -1
- package/dist/snapshot.js.map +1 -1
- package/dist/transport.d.ts +2 -1
- package/dist/transport.js +2 -2
- package/dist/transport.js.map +1 -1
- package/dist/worker-status.js +4 -1
- package/dist/worker-status.js.map +1 -1
- package/dist/workspace.d.ts +9 -0
- package/dist/workspace.js +61 -0
- package/dist/workspace.js.map +1 -0
- package/package.json +3 -2
- package/rules.md +30 -0
- package/src/config.ts +23 -2
- package/src/connections.ts +6 -4
- package/src/core-monitor.ts +2 -2
- package/src/herdr-core.ts +11 -6
- package/src/index.ts +17 -10
- package/src/launcher.ts +1 -1
- package/src/monitor-view.ts +9 -2
- package/src/observability.ts +1 -1
- package/src/runtime.ts +143 -64
- package/src/snapshot.ts +2 -1
- package/src/transport.ts +4 -4
- package/src/worker-status.ts +4 -1
- package/src/workspace.ts +51 -0
- package/dist/reminders.d.ts +0 -28
- package/dist/reminders.js +0 -81
- package/dist/reminders.js.map +0 -1
- package/src/reminders.ts +0 -69
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
|
|
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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { Type, type TSchema } from 'typebox';
|
|
4
5
|
import { getAgentDir, SessionManager, SettingsManager, truncateHead, withFileMutationQueue, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
@@ -14,14 +15,13 @@ const modelSelection = Type.Union([Type.Null(), Type.Object({ provider: Type.Str
|
|
|
14
15
|
const tools: [string, string, TSchema][] = [
|
|
15
16
|
['configure_models', 'Coordinator only. Save coordinator and/or worker provider/model defaults in project config. Null removes a default. Applies on startup or idle responsibility reload, not immediately. Manual model changes remain allowed; unavailable models produce an error without fallback.', Type.Object({ coordinator: Type.Optional(modelSelection), worker: Type.Optional(modelSelection) }, { minProperties: 1, additionalProperties: false })],
|
|
16
17
|
['create_worker', 'Coordinator only. Launch one anonymous worker at the coordinator root. projectDirectory defaults to root and must resolve to that same directory; subfolder launches cannot use a parent config and are refused. No assignment, configuration, or registration wait.', Type.Object({ projectDirectory: Type.Optional(Type.String()) })],
|
|
17
|
-
['configure_worker', 'Coordinator only. Write
|
|
18
|
-
['reload_worker', 'Coordinator only. Ask worker to
|
|
18
|
+
['configure_worker', 'Coordinator only. Write reported connection details, responsibility, and required worktree/branch to config. All seven fields are required; blank/none worktree or branch refused. Worktree may be absolute or project-root-relative, including siblings. Changing an existing workspace requires a verified idle worker. Does not notify, reload, or start work. Use reload_worker separately.', Type.Object({ sessionId: Type.String(), port: Type.Integer({ minimum: 1, maximum: 65535 }), projectDirectory: Type.String(), name: Type.String({ minLength: 1, maxLength: 128 }), description: Type.String({ minLength: 1, maxLength: 4096 }), worktree: Type.String({ minLength: 1, maxLength: 4096 }), branch: Type.String({ minLength: 1, maxLength: 4096 }) })],
|
|
19
|
+
['reload_worker', 'Coordinator only. Ask idle worker to validate its worktree/branch, load its configuration and synchronize names. Missing legacy workspace fields require reconfiguration first. NOT Pi extension reload, cancellation, restart, or work assignment.', to],
|
|
19
20
|
['send', 'Configured sessions only. Send an explicit work/progress/findings message by recipient name. Idle delivery starts a turn; busy delivery steers at supported boundaries. Receipt is not an agent reply. Progress questions do not cancel assignments.', Type.Object({ to: Type.String(), message: Type.String({ minLength: 1, maxLength: 48000 }) })],
|
|
20
21
|
['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
|
-
['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
|
+
['list', 'Configured sessions only. Read current saved names, responsibilities, worktrees, branches, session IDs, roles and ports. No live probing. Output limited to 50 KiB/2000 lines; full data remains in config.json.', Type.Object({})],
|
|
22
23
|
['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({})],
|
|
24
|
+
['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
25
|
['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
26
|
['stop_worker', UNSUPPORTED_CANCELLATION, to],
|
|
27
27
|
['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 +235,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
|
|
|
235
235
|
successful.add(entry.message.toolCallId);
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
|
-
runtime?.workerSettled(successful);
|
|
238
|
+
void runtime?.workerSettled(successful);
|
|
239
239
|
});
|
|
240
240
|
pi.on('message_update', (event, ctx) => {
|
|
241
241
|
context = ctx;
|
|
@@ -253,9 +253,16 @@ export default function intercomExtension(pi: ExtensionAPI): void {
|
|
|
253
253
|
pi.on('before_agent_start', async (event, ctx) => {
|
|
254
254
|
context = ctx;
|
|
255
255
|
if (!runtime) return;
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
256
|
+
const current = runtime, started = generation;
|
|
257
|
+
// Package-owned rules, not a project file or a skill the model must discover.
|
|
258
|
+
// Pi keeps these instructions for the run; tools/messages do not repeat them.
|
|
259
|
+
let rules: string;
|
|
260
|
+
try { rules = await readFile(new URL('../rules.md', import.meta.url), 'utf8'); }
|
|
261
|
+
catch { return { systemPrompt: event.systemPrompt + '\n\nIntercom NOT READY: packaged rules.md is unavailable. Report the problem and do not continue assigned work until the installation is repaired.' }; }
|
|
262
|
+
if (runtime !== current || generation !== started) return;
|
|
263
|
+
const instructions = await current.beforeRunInstructions();
|
|
264
|
+
if (runtime !== current || generation !== started) return;
|
|
265
|
+
return { systemPrompt: event.systemPrompt + '\n\n' + rules + '\n' + instructions };
|
|
259
266
|
});
|
|
260
267
|
for (const [operation, description, parameters] of tools) {
|
|
261
268
|
pi.registerTool({
|
|
@@ -274,7 +281,7 @@ export default function intercomExtension(pi: ExtensionAPI): void {
|
|
|
274
281
|
if (!state.me?.coordinator) throw new Error('PiIntercom: coordinator permission required');
|
|
275
282
|
monitorAutoEpoch++; // Fence prior automatic passes; lock refusal never schedules a retry.
|
|
276
283
|
}
|
|
277
|
-
const result = await current.tool(operation, args as Record<string, unknown>, _id
|
|
284
|
+
const result = await current.tool(operation, args as Record<string, unknown>, _id);
|
|
278
285
|
if (operation === 'configure_worker') await ensureCoordinatorMonitor(current, ctx, started);
|
|
279
286
|
const output = truncateHead(JSON.stringify(result, null, 2));
|
|
280
287
|
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`);
|
package/src/monitor-view.ts
CHANGED
|
@@ -93,6 +93,10 @@ export function renderMonitor(snapshot: ObservationSnapshot | undefined, width:
|
|
|
93
93
|
line(` Connection: ${connection.state} · ${connection.reason}`),
|
|
94
94
|
line(` Checked: ${connection.checkedAt ?? 'never'} · ${Number.isFinite(checkedAge) && checkedAge >= 0 ? ageLabel(checkedAge) : 'age unknown'}`),
|
|
95
95
|
];
|
|
96
|
+
const workspaceDetails = [
|
|
97
|
+
line(` Worktree: ${worker.worktree || 'Missing — reconfigure worker'}`),
|
|
98
|
+
line(` Branch: ${worker.branch || 'Missing — reconfigure worker'}`),
|
|
99
|
+
];
|
|
96
100
|
const selected = start + offset === selectedIndex;
|
|
97
101
|
const report = snapshot.reports?.find(report => report.sessionId === worker.sessionId && reportLabels[report.status]);
|
|
98
102
|
lines.push(table(worker.name, connection.state, activity, age, evidence, report ? reportLabels[report.status] : '—', tone, selected));
|
|
@@ -117,6 +121,7 @@ export function renderMonitor(snapshot: ObservationSnapshot | undefined, width:
|
|
|
117
121
|
] : []),
|
|
118
122
|
...connectionDetails,
|
|
119
123
|
line(` Responsibility: ${worker.description || 'Not specified'}`),
|
|
124
|
+
...workspaceDetails,
|
|
120
125
|
line(` Observed status: ${activity} · ${age}`),
|
|
121
126
|
line(` Last activity: ${evidence}`),
|
|
122
127
|
...(closeJob ? [line(` Close updated: ${closeJob.updatedAt}`), line(' Workflow state is not proof all child processes terminated')] : []),
|
|
@@ -124,12 +129,13 @@ export function renderMonitor(snapshot: ObservationSnapshot | undefined, width:
|
|
|
124
129
|
} else if (selected && showDetails && report) {
|
|
125
130
|
const elapsed = now - Date.parse(report.updatedAt);
|
|
126
131
|
const reportAge = !Number.isFinite(elapsed) || elapsed < 0 ? 'clock uncertain' : ageLabel(elapsed) + (elapsed > snapshot.staleAfterMs ? ' (old)' : '');
|
|
127
|
-
const contextRows = detailBudget >=
|
|
132
|
+
const contextRows = detailBudget >= 11 ? [
|
|
128
133
|
paint('1', line(` ${worker.name}`)),
|
|
129
134
|
...connectionDetails,
|
|
130
135
|
line(` Responsibility: ${worker.description || 'Not specified'}`),
|
|
136
|
+
...workspaceDetails,
|
|
131
137
|
line(` Observed status: ${activity} · ${age}`),
|
|
132
|
-
...(detailBudget >=
|
|
138
|
+
...(detailBudget >= 12 ? [line(` Last activity: ${evidence}`)] : []),
|
|
133
139
|
] : [];
|
|
134
140
|
selectedDetail = [
|
|
135
141
|
...contextRows,
|
|
@@ -140,6 +146,7 @@ export function renderMonitor(snapshot: ObservationSnapshot | undefined, width:
|
|
|
140
146
|
} else if (selected && showDetails) selectedDetail = [
|
|
141
147
|
...connectionDetails,
|
|
142
148
|
line(` Responsibility: ${worker.description || 'Not specified'}`),
|
|
149
|
+
...workspaceDetails,
|
|
143
150
|
line(` Observed status: ${activity} · ${age}`),
|
|
144
151
|
line(` Last activity: ${evidence}`),
|
|
145
152
|
];
|
package/src/observability.ts
CHANGED
|
@@ -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
|
@@ -2,14 +2,15 @@ import path from 'node:path';
|
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { realpath } from 'node:fs/promises';
|
|
4
4
|
import { LocalObserver, LOG_LIMITS, observationError, type Observer, type EventType, type EventMetadata } from './observability.js';
|
|
5
|
-
import { ConfigStore, coordinator, directory, fail, named, port, requireCoordinator, text, validateConfig, monitorSettings, validateMonitorSettings, validateModels, type ModelSelection, type ModelSettings, type MonitorSettings, type Agent, type Config } from './config.js';
|
|
5
|
+
import { ConfigStore, coordinator, directory, fail, named, port, requireCoordinator, requireWorkspace, text, validateConfig, monitorSettings, validateMonitorSettings, validateModels, type ModelSelection, type ModelSettings, type MonitorSettings, type Agent, type Config } from './config.js';
|
|
6
6
|
import { listen, send, reportPayload, type Endpoint, type Envelope, type Kind } from './transport.js';
|
|
7
7
|
import { saveWorkerReport } from './reports.js';
|
|
8
8
|
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
|
-
|
|
12
|
+
|
|
13
|
+
import { sameResponsibility, validateWorkerWorkspace, type WorkerWorkspace } from './workspace.js';
|
|
13
14
|
|
|
14
15
|
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
16
|
export interface Host {
|
|
@@ -37,12 +38,13 @@ export interface RuntimeOptions {
|
|
|
37
38
|
closeProvider?: CloseProvider;
|
|
38
39
|
/** Test seam; production defaults to 120 seconds, values above that are capped. */
|
|
39
40
|
closeTimeoutMs?: number;
|
|
40
|
-
reminderClock?: ReminderClock;
|
|
41
41
|
monitor?: MonitorOperations;
|
|
42
42
|
/** Explicit launcher-provided root must equal canonical cwd; no parent-root exception. */
|
|
43
43
|
workspaceRoot?: string;
|
|
44
44
|
/** Adapter startup must not recreate a config removed after discovery. */
|
|
45
45
|
requireExistingConfig?: boolean;
|
|
46
|
+
/** Read-only validation seam for isolated runtime tests. */
|
|
47
|
+
validateWorkspace?: typeof validateWorkerWorkspace;
|
|
46
48
|
}
|
|
47
49
|
export class Intercom {
|
|
48
50
|
store!: ConfigStore;
|
|
@@ -53,6 +55,8 @@ export class Intercom {
|
|
|
53
55
|
private configuredRoot?: string;
|
|
54
56
|
private configuredFile?: string;
|
|
55
57
|
responsibility?: Agent;
|
|
58
|
+
private loadedWorkspace?: WorkerWorkspace;
|
|
59
|
+
private workspaceIssue?: string;
|
|
56
60
|
private observer?: Observer;
|
|
57
61
|
private closing?: Promise<void>;
|
|
58
62
|
private reportWrites: Promise<void> = Promise.resolve();
|
|
@@ -60,11 +64,24 @@ export class Intercom {
|
|
|
60
64
|
private probeController = new AbortController();
|
|
61
65
|
private resumeFences = new Map<string, { inFlight: boolean; submitted: boolean; announced: boolean }>();
|
|
62
66
|
private handoff?: HandoffWorkflow;
|
|
63
|
-
|
|
64
|
-
private
|
|
65
|
-
private reminderInvocation = 0;
|
|
67
|
+
/** Worker only: the coordinator sent work and has heard nothing back since. */
|
|
68
|
+
private owesCoordinator = false;
|
|
66
69
|
workerStarted(): void { this.handoff?.workerStarted(); }
|
|
67
|
-
|
|
70
|
+
/** Resolves once any idle notice has been attempted; callers need not await it. */
|
|
71
|
+
workerSettled(successfulToolCallIds: ReadonlySet<string>): Promise<void> {
|
|
72
|
+
this.handoff?.workerSettled(successfulToolCallIds);
|
|
73
|
+
if (!this.owesCoordinator || this.handoff?.workerClosing) return Promise.resolve();
|
|
74
|
+
// One event-driven notice, sent in code: no timer, no model turn here.
|
|
75
|
+
this.owesCoordinator = false;
|
|
76
|
+
return this.notifyIdle().catch(() => { /* Best effort; never retried. */ });
|
|
77
|
+
}
|
|
78
|
+
private async notifyIdle(): Promise<void> {
|
|
79
|
+
const assertValid = this.validity();
|
|
80
|
+
const { config, me } = await this.state();
|
|
81
|
+
assertValid();
|
|
82
|
+
if (!me || me.coordinator || !this.responsibility) return;
|
|
83
|
+
await this.transmit(coordinator(config).name, 'idle');
|
|
84
|
+
}
|
|
68
85
|
private captureObserver(): (event: EventType, metadata?: EventMetadata) => void {
|
|
69
86
|
const observer = this.observer;
|
|
70
87
|
return (event, metadata = {}) => {
|
|
@@ -116,7 +133,7 @@ export class Intercom {
|
|
|
116
133
|
const own = previous?.agents.find(a => a.sessionId === this.id());
|
|
117
134
|
const endpoint = await (this.options.listen ?? listen)(own?.port, m => { assertValid(); return this.receive(m); }, () => {
|
|
118
135
|
assertValid();
|
|
119
|
-
return { version: 1, sessionId: this.initialId };
|
|
136
|
+
return { version: 1, sessionId: this.initialId, busy: this.host.busy() };
|
|
120
137
|
});
|
|
121
138
|
try { assertValid(); } catch (error) { await endpoint.close(); throw error; }
|
|
122
139
|
this.endpoint = endpoint;
|
|
@@ -127,11 +144,6 @@ export class Intercom {
|
|
|
127
144
|
const config = await this.store.read();
|
|
128
145
|
assertValid();
|
|
129
146
|
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
147
|
this.handoff = new HandoffWorkflow({
|
|
136
148
|
state: () => this.state(), assertCurrent: assertValid,
|
|
137
149
|
update: async (mutate, guard) => {
|
|
@@ -171,7 +183,7 @@ export class Intercom {
|
|
|
171
183
|
}
|
|
172
184
|
} catch (e) { assertValid(); this.host.notify(`Coordinator unreachable/registration failed; worker remains reachable: ${String(e)}. No retry. Anonymous registration repeat is an unresolved contract; use explicit Pi /reload to restart this extension, not report_status.`); }
|
|
173
185
|
assertValid();
|
|
174
|
-
this.host.notify(`Intercom worker
|
|
186
|
+
this.host.notify(`Intercom worker listening at 127.0.0.1:${this.endpoint.port}; ${this.responsibility ? 'configuration loaded; waiting for explicit work' : 'not ready; configuration and successful reload required'}.`);
|
|
175
187
|
}
|
|
176
188
|
record('runtime.ready', { port: this.endpoint.port, role: me?.coordinator ? 'coordinator' : me ? 'worker' : 'anonymous', busy: this.host.busy(), outcome: 'ready' });
|
|
177
189
|
} catch (e) {
|
|
@@ -189,10 +201,11 @@ export class Intercom {
|
|
|
189
201
|
this.active = false; this.generation++;
|
|
190
202
|
this.probeController.abort();
|
|
191
203
|
this.handoff?.dispose(); this.handoff = undefined;
|
|
192
|
-
this.
|
|
193
|
-
this.reminders?.dispose(); this.reminders = undefined;
|
|
204
|
+
this.owesCoordinator = false;
|
|
194
205
|
const endpoint = this.endpoint; this.endpoint = undefined;
|
|
195
206
|
this.responsibility = undefined;
|
|
207
|
+
this.loadedWorkspace = undefined;
|
|
208
|
+
this.workspaceIssue = undefined;
|
|
196
209
|
const closing = (async () => {
|
|
197
210
|
try { if (endpoint) await endpoint.close(); }
|
|
198
211
|
finally {
|
|
@@ -258,21 +271,79 @@ export class Intercom {
|
|
|
258
271
|
if (!this.host.applyModel) fail('model selection unavailable in this host');
|
|
259
272
|
await this.host.applyModel(selection);
|
|
260
273
|
}
|
|
274
|
+
private invalidateWorkspace(reason: string): void {
|
|
275
|
+
this.responsibility = undefined;
|
|
276
|
+
this.loadedWorkspace = undefined;
|
|
277
|
+
this.workspaceIssue = reason;
|
|
278
|
+
}
|
|
279
|
+
private validateWorkspace(agent: Agent): Promise<WorkerWorkspace> {
|
|
280
|
+
requireWorkspace(agent);
|
|
281
|
+
return (this.options.validateWorkspace ?? validateWorkerWorkspace)(this.store.root, agent);
|
|
282
|
+
}
|
|
283
|
+
/** Supplies instructions once per agent run, never once per tool operation. */
|
|
284
|
+
async beforeRunInstructions(): Promise<string> {
|
|
285
|
+
const generation = this.generation;
|
|
286
|
+
try {
|
|
287
|
+
const assertValid = this.validity();
|
|
288
|
+
const { me, config } = await this.state();
|
|
289
|
+
assertValid();
|
|
290
|
+
if (!me) {
|
|
291
|
+
this.invalidateWorkspace('worker is not configured');
|
|
292
|
+
return 'Anonymous/unloaded worker: wait for coordinator configuration and separate reload; do not treat registration as authorization to work.';
|
|
293
|
+
}
|
|
294
|
+
if (me.coordinator) {
|
|
295
|
+
const missing = config.agents.filter(a => !a.coordinator && (!a.worktree || !a.branch)).map(a => a.name);
|
|
296
|
+
return `Identity: ${me.name} (${me.sessionId}). Responsibility: ${me.description}.\nProject/configuration root: ${this.store.root}.` +
|
|
297
|
+
(missing.length ? `\nWorkers with incomplete configuration: ${JSON.stringify(missing)}. Check their actual worktrees and branches, update each with intercom_configure_worker, then call intercom_reload_worker. Do not assign work until configuration is successfully loaded. Do not guess missing values; ask the user if they cannot be established.` : '');
|
|
298
|
+
}
|
|
299
|
+
requireWorkspace(me);
|
|
300
|
+
if (!this.responsibility) throw new Error(this.workspaceIssue ?? 'worker configuration is not loaded; successful reload required');
|
|
301
|
+
if (!sameResponsibility(me, this.responsibility)) fail('worker configuration changed; successful reload required');
|
|
302
|
+
const workspace = await this.validateWorkspace(me);
|
|
303
|
+
const fresh = await this.state();
|
|
304
|
+
assertValid();
|
|
305
|
+
if (!fresh.me || !sameResponsibility(me, fresh.me)) fail('worker configuration changed during validation; successful reload required');
|
|
306
|
+
this.loadedWorkspace = workspace;
|
|
307
|
+
this.workspaceIssue = undefined;
|
|
308
|
+
return `Identity: ${me.name} (${me.sessionId}). Responsibility: ${me.description}.\nProject/configuration root: ${this.store.root}.\nWorktree: ${workspace.worktree}. Branch: ${workspace.branch}.\nChange files only in that worktree, on that branch. Your tools still start in the project root; use explicit worktree paths.`;
|
|
309
|
+
} catch (error) {
|
|
310
|
+
// Hook exceptions are not an execution gate in Pi: always return explicit
|
|
311
|
+
// not-ready instructions instead of silently dropping the operating rules.
|
|
312
|
+
const reason = error instanceof Error ? error.message : 'worker configuration validation failed';
|
|
313
|
+
if (generation === this.generation) this.invalidateWorkspace(reason);
|
|
314
|
+
return `Intercom NOT READY: ${reason}\nDo not continue assigned work. Report the configuration problem to the coordinator and wait for correction and successful reload. Do not guess a workspace or fall back to the project root.`;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
261
317
|
async reload(): Promise<void> {
|
|
318
|
+
const generation = this.generation;
|
|
262
319
|
const record = this.captureObserver();
|
|
263
320
|
const assertValid = this.validity();
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
321
|
+
try {
|
|
322
|
+
const { me, config } = await this.state();
|
|
323
|
+
assertValid();
|
|
324
|
+
if (!me) fail('worker not configured; configure_worker must run before reload_worker');
|
|
325
|
+
if (!me.coordinator && this.host.busy()) fail('worker configuration reload requires an idle worker');
|
|
326
|
+
this.invalidateWorkspace('configuration reload has not completed');
|
|
327
|
+
const workspace = me.coordinator ? undefined : await this.validateWorkspace(me);
|
|
328
|
+
assertValid();
|
|
329
|
+
const selection = config.models?.[me.coordinator ? 'coordinator' : 'worker'];
|
|
330
|
+
await this.applyConfiguredModel(selection);
|
|
331
|
+
assertValid();
|
|
332
|
+
// Coordinator is a routing identity, not ownership of the user's Pi/tab title.
|
|
333
|
+
if (!me.coordinator) await this.host.setName(me.name);
|
|
334
|
+
const fresh = await this.state();
|
|
335
|
+
assertValid();
|
|
336
|
+
if (!fresh.me || !sameResponsibility(me, fresh.me)) fail('configuration changed during reload; reload again when idle');
|
|
337
|
+
if (!me.coordinator && this.host.busy()) fail('worker became busy during reload; reload again when idle');
|
|
338
|
+
this.responsibility = { ...me };
|
|
339
|
+
this.loadedWorkspace = workspace;
|
|
340
|
+
this.workspaceIssue = undefined;
|
|
341
|
+
record('config.reloaded', { role: me.coordinator ? 'coordinator' : 'worker' });
|
|
342
|
+
this.host.notify(`Intercom responsibility loaded for ${me.name}; no work turn started.`);
|
|
343
|
+
} catch (error) {
|
|
344
|
+
if (generation === this.generation) this.invalidateWorkspace(error instanceof Error ? error.message : 'configuration reload failed');
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
276
347
|
}
|
|
277
348
|
async transmit(to: string, kind: Kind, payload: Record<string, unknown> = {}): Promise<void> {
|
|
278
349
|
const record = this.captureObserver();
|
|
@@ -297,7 +368,9 @@ export class Intercom {
|
|
|
297
368
|
assertValid();
|
|
298
369
|
if (me?.coordinator) fail('report_status is worker-only');
|
|
299
370
|
if (!this.endpoint) fail('endpoint unavailable');
|
|
300
|
-
await this.transmit(coordinator(config).name, 'status', { port: this.endpoint.port, busy: this.host.busy()
|
|
371
|
+
await this.transmit(coordinator(config).name, 'status', { port: this.endpoint.port, busy: this.host.busy(),
|
|
372
|
+
worktree: me?.worktree, branch: me?.branch,
|
|
373
|
+
workspaceState: this.responsibility && this.loadedWorkspace && me && sameResponsibility(me, this.responsibility) ? 'loaded' : 'not_ready' });
|
|
301
374
|
}
|
|
302
375
|
async receive(message: Envelope): Promise<void> {
|
|
303
376
|
const record = this.captureObserver();
|
|
@@ -357,7 +430,10 @@ export class Intercom {
|
|
|
357
430
|
}
|
|
358
431
|
record('status.received', { ...metadata, busy: message.payload.busy as boolean, port: message.payload.port as number });
|
|
359
432
|
if (sender) record('config.changed', { operation: 'port_update', peerSessionId: message.from, port: message.payload.port as number, outcome: 'written' });
|
|
360
|
-
notify('status', JSON.stringify({ sessionId: message.from, port: message.payload.port, busy: message.payload.busy, configured: !!sender
|
|
433
|
+
notify('status', JSON.stringify({ sessionId: message.from, port: message.payload.port, busy: message.payload.busy, configured: !!sender,
|
|
434
|
+
worktree: sender?.worktree, branch: sender?.branch,
|
|
435
|
+
workspaceState: sender?.worktree && sender.branch && message.payload.workspaceState === 'loaded' &&
|
|
436
|
+
message.payload.worktree === sender.worktree && message.payload.branch === sender.branch ? 'loaded' : 'not_ready' }));
|
|
361
437
|
}
|
|
362
438
|
return;
|
|
363
439
|
}
|
|
@@ -374,19 +450,28 @@ export class Intercom {
|
|
|
374
450
|
if (!fresh.config.agents.some(agent => agent.sessionId === message.from && !agent.coordinator)) fail('reporting worker is no longer configured');
|
|
375
451
|
await saveWorkerReport(this.store.root, { version: 1, sessionId: message.from, ...payload, updatedAt: new Date().toISOString() }, assertValid);
|
|
376
452
|
assertValid();
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
453
|
+
// Retiring a report needs no decision: store it without waking the coordinator.
|
|
454
|
+
if (payload.status === 'clear') return;
|
|
455
|
+
try { notify('worker report', `${payload.status}: ${payload.summary}`); }
|
|
456
|
+
catch { fail('Report stored, but coordinator notification failed or became uncertain; do not blindly resend'); }
|
|
380
457
|
});
|
|
381
458
|
this.reportWrites = pending.catch(() => {}).finally(() => { this.pendingReports--; });
|
|
382
459
|
await pending;
|
|
383
460
|
return;
|
|
384
461
|
}
|
|
462
|
+
if (message.kind === 'idle') {
|
|
463
|
+
requireCoordinator(config, id);
|
|
464
|
+
if (!sender || sender.coordinator) fail('idle notices require a configured worker sender');
|
|
465
|
+
notify('worker idle', 'Turn ended without a report or message to you.'); return;
|
|
466
|
+
}
|
|
385
467
|
if (message.kind === 'message') {
|
|
386
468
|
if (!sender || !me) fail('agent messaging requires configured sender and recipient; anonymous permissions TODO');
|
|
387
469
|
if (!this.responsibility) fail('worker must load responsibility before receiving work');
|
|
470
|
+
if (!me.coordinator && !sameResponsibility(me, this.responsibility)) fail('worker configuration changed; successful reload required before receiving work');
|
|
388
471
|
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);
|
|
472
|
+
notify('agent message', message.payload.message as string);
|
|
473
|
+
if (sender.coordinator && !me.coordinator) this.owesCoordinator = true;
|
|
474
|
+
return;
|
|
390
475
|
}
|
|
391
476
|
if (!sender?.coordinator) fail('control requires current coordinator sender session ID');
|
|
392
477
|
if (me?.coordinator) fail('worker control cannot target coordinator');
|
|
@@ -408,17 +493,7 @@ export class Intercom {
|
|
|
408
493
|
}
|
|
409
494
|
fail('unsupported control');
|
|
410
495
|
}
|
|
411
|
-
async tool(operation: string, args: Record<string, unknown>, toolCallId?: string
|
|
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
|
-
};
|
|
496
|
+
async tool(operation: string, args: Record<string, unknown>, toolCallId?: string): Promise<unknown> {
|
|
422
497
|
const record = this.captureObserver();
|
|
423
498
|
const assertValid = this.validity();
|
|
424
499
|
const { id, config, me } = await this.state();
|
|
@@ -446,18 +521,21 @@ export class Intercom {
|
|
|
446
521
|
}
|
|
447
522
|
if (operation === 'report_status') { await this.report(); return { accepted: true }; }
|
|
448
523
|
if (operation === 'report_work') {
|
|
449
|
-
if (!me || me.coordinator || !this.responsibility) fail('report_work requires a configured, responsibility-loaded worker');
|
|
524
|
+
if (!me || me.coordinator || (!this.responsibility && !(this.workspaceIssue && args.status === 'blocked'))) fail('report_work requires a configured, responsibility-loaded worker (or blocked configuration report)');
|
|
450
525
|
const payload = reportPayload(args);
|
|
451
526
|
await this.transmit(coordinator(config).name, 'report', payload);
|
|
527
|
+
if (payload.status !== 'clear') this.owesCoordinator = false;
|
|
452
528
|
return { accepted: true, coordinatorEvaluation: 'not awaited' };
|
|
453
529
|
}
|
|
454
530
|
if (operation === 'send') {
|
|
455
|
-
if (!me
|
|
531
|
+
if (!me) fail('anonymous/unloaded worker cannot send agent messages (permissions TODO)');
|
|
456
532
|
const recipient = named(config, args.to as string);
|
|
533
|
+
if (!this.responsibility && !(this.workspaceIssue && recipient.coordinator)) fail('anonymous/unloaded worker cannot send agent messages (permissions TODO)');
|
|
457
534
|
text(args.message, 'message', 48000);
|
|
458
535
|
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
|
-
|
|
460
|
-
|
|
536
|
+
await this.transmit(args.to as string, 'message', { message: args.message });
|
|
537
|
+
if (recipient.coordinator) this.owesCoordinator = false;
|
|
538
|
+
return { accepted: true, completion: 'not awaited' };
|
|
461
539
|
}
|
|
462
540
|
requireCoordinator(config, id);
|
|
463
541
|
if (operation === 'configure_models') {
|
|
@@ -491,11 +569,6 @@ export class Intercom {
|
|
|
491
569
|
if (operation === 'open_monitor' || operation === 'close_monitor') {
|
|
492
570
|
return this.operateMonitor(operation, args);
|
|
493
571
|
}
|
|
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
572
|
if (operation === 'stop_worker') fail(UNSUPPORTED_CANCELLATION);
|
|
500
573
|
if (operation === 'configure_worker') {
|
|
501
574
|
const assertConfigurable = () => {
|
|
@@ -503,18 +576,25 @@ export class Intercom {
|
|
|
503
576
|
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
577
|
};
|
|
505
578
|
assertConfigurable();
|
|
506
|
-
// Validate the candidate without writing, so invalid input never arms a
|
|
507
|
-
// reminder; persistence failures after valid initiation still do.
|
|
508
579
|
const relative = await directory(this.store.root, args.projectDirectory as string);
|
|
509
580
|
assertConfigurable();
|
|
510
581
|
const candidate: Agent = { sessionId: args.sessionId as string, name: args.name as string, description: args.description as string,
|
|
511
|
-
port: args.port as number, projectDirectory: relative, coordinator: false };
|
|
582
|
+
port: args.port as number, projectDirectory: relative, worktree: args.worktree as string, branch: args.branch as string, coordinator: false };
|
|
512
583
|
if (candidate.sessionId === id) fail('cannot configure coordinator as worker');
|
|
513
584
|
const previous = config.agents.find(a => a.sessionId === candidate.sessionId);
|
|
514
585
|
if (fencedClose(previous?.closeJob)) fail('worker close is active or uncertain; configuration is fenced');
|
|
586
|
+
requireWorkspace(candidate);
|
|
515
587
|
validateConfig({ ...config, agents: [...config.agents.filter(a => a.sessionId !== candidate.sessionId), candidate] });
|
|
516
|
-
|
|
517
|
-
|
|
588
|
+
if (previous?.worktree && previous.branch && (previous.worktree !== candidate.worktree || previous.branch !== candidate.branch)) {
|
|
589
|
+
// A last-observed activity log is not a live idle check. Unknown or
|
|
590
|
+
// unreachable workers cannot authorize changing an existing workspace.
|
|
591
|
+
const connection = await (this.options.probe ?? probeWorker)(previous, { signal: this.probeController.signal });
|
|
592
|
+
assertConfigurable();
|
|
593
|
+
if (connection.state !== 'connected' || connection.busy !== false) fail('worktree/branch changes require a verified idle worker; busy or unknown worker refused');
|
|
594
|
+
}
|
|
595
|
+
await this.store.configure(id, args as unknown as Omit<Agent, 'coordinator'>, assertConfigurable, current => {
|
|
596
|
+
if (JSON.stringify(current ?? null) !== JSON.stringify(previous ?? null)) fail('worker configuration changed during configure check; no update written');
|
|
597
|
+
});
|
|
518
598
|
record('config.changed', { operation: 'configure_worker', peerSessionId: args.sessionId as string, peerName: args.name as string, outcome: 'written' });
|
|
519
599
|
return { written: true, reloaded: false };
|
|
520
600
|
}
|
|
@@ -526,7 +606,6 @@ export class Intercom {
|
|
|
526
606
|
const relative = await directory(this.store.root, (args.projectDirectory as string | undefined) ?? '.');
|
|
527
607
|
assertValid();
|
|
528
608
|
if (relative !== '.') fail('worker working directory must equal the config root; subdirectory launches would read a forbidden parent config');
|
|
529
|
-
armReminder();
|
|
530
609
|
return this.launchObserved({ multiplexer: config.multiplexer, cwd: path.resolve(this.store.root, relative), workspaceRoot: this.store.root });
|
|
531
610
|
}
|
|
532
611
|
const target = named(config, args.to as string);
|
|
@@ -535,16 +614,17 @@ export class Intercom {
|
|
|
535
614
|
if (!this.options.closeProvider || !this.handoff || config.multiplexer !== 'herdr') fail('Owned-pane close requires supported Linux Herdr provider; no closure attempted');
|
|
536
615
|
if (this.resumeFences.has(target.sessionId)) fail('resume is in flight; close is fenced');
|
|
537
616
|
if (fencedClose(target.closeJob) && !this.handoff.isClosing(target.sessionId)) fail('worker close is active or uncertain; close is fenced');
|
|
538
|
-
armReminder();
|
|
539
617
|
return { job: await this.handoff.request(target), completion: 'not awaited', contract: 'best-effort owned-pane closure; not all-child-process termination' };
|
|
540
618
|
}
|
|
541
619
|
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
620
|
if (operation === 'reload_worker' || operation === 'request_status') {
|
|
543
|
-
armReminder();
|
|
544
621
|
await this.transmit(target.name, operation === 'reload_worker' ? 'reload' : 'request_status');
|
|
545
622
|
return { accepted: true, completion: 'not awaited' };
|
|
546
623
|
}
|
|
547
624
|
if (operation === 'resume_worker') {
|
|
625
|
+
requireWorkspace(target);
|
|
626
|
+
await this.validateWorkspace(target);
|
|
627
|
+
assertValid();
|
|
548
628
|
if (args.confirmClosed !== true) fail('Resume requires explicit user confirmation that the previous worker session is closed (confirmClosed:true). Disconnected alone is not proof of closure.');
|
|
549
629
|
if (this.resumeFences.has(target.sessionId)) fail('Resume already in flight or awaiting worker status; outcome may be uncertain. Inspect the worker before any retry; no automatic relaunch.');
|
|
550
630
|
const relative = await directory(this.store.root, target.projectDirectory);
|
|
@@ -556,7 +636,6 @@ export class Intercom {
|
|
|
556
636
|
if (this.handoff?.isClosing(target.sessionId)) fail('worker close is active or uncertain; resume is fenced');
|
|
557
637
|
const fence = { inFlight: true, submitted: false, announced: false };
|
|
558
638
|
this.resumeFences.set(target.sessionId, fence);
|
|
559
|
-
armReminder();
|
|
560
639
|
let completed = false;
|
|
561
640
|
try {
|
|
562
641
|
const connection = await (this.options.probe ?? probeWorker)(target, { signal: this.probeController.signal });
|
|
@@ -566,7 +645,7 @@ export class Intercom {
|
|
|
566
645
|
assertValid();
|
|
567
646
|
requireCoordinator(fresh.config, id);
|
|
568
647
|
const current = fresh.config.agents.find(agent => agent.sessionId === target.sessionId && !agent.coordinator);
|
|
569
|
-
if (!current || current.port !== target.port || current
|
|
648
|
+
if (!current || current.port !== target.port || !sameResponsibility(current, target)) fail('Worker configuration changed during resume check; no launch submitted.');
|
|
570
649
|
if (this.handoff?.isClosing(target.sessionId) || fencedClose(current.closeJob)) fail('worker close is active or uncertain; resume is fenced');
|
|
571
650
|
fence.submitted = true;
|
|
572
651
|
const result = await this.launchObserved({ multiplexer: fresh.config.multiplexer, cwd, workspaceRoot: this.store.root, sessionId: current.sessionId });
|
package/src/snapshot.ts
CHANGED
|
@@ -86,7 +86,8 @@ export async function readObservationSnapshot(root: string): Promise<Observation
|
|
|
86
86
|
result.truncated ||= config.agents.length > MAX_AGENTS;
|
|
87
87
|
result.config = { multiplexer: config.multiplexer, agents: config.agents.slice(0, MAX_AGENTS).map(a => ({
|
|
88
88
|
sessionId: a.sessionId, name: a.name, coordinator: a.coordinator, description: a.description,
|
|
89
|
-
projectDirectory: a.projectDirectory, port: a.port,
|
|
89
|
+
projectDirectory: a.projectDirectory, port: a.port,
|
|
90
|
+
...(!a.coordinator ? { worktree: a.worktree, branch: a.branch } : {}), ...publicCloseMetadata(a),
|
|
90
91
|
})) };
|
|
91
92
|
} catch { result.errors.push('config_unavailable'); }
|
|
92
93
|
try {
|