@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.
Files changed (53) hide show
  1. package/README.md +55 -30
  2. package/dist/config.d.ts +9 -1
  3. package/dist/config.js +28 -2
  4. package/dist/config.js.map +1 -1
  5. package/dist/connections.d.ts +2 -0
  6. package/dist/connections.js +3 -3
  7. package/dist/connections.js.map +1 -1
  8. package/dist/core-monitor.js +2 -2
  9. package/dist/core-monitor.js.map +1 -1
  10. package/dist/herdr-core.d.ts +1 -1
  11. package/dist/herdr-core.js +11 -6
  12. package/dist/herdr-core.js.map +1 -1
  13. package/dist/index.js +23 -10
  14. package/dist/index.js.map +1 -1
  15. package/dist/launcher.js +1 -1
  16. package/dist/launcher.js.map +1 -1
  17. package/dist/monitor-view.js +9 -2
  18. package/dist/monitor-view.js.map +1 -1
  19. package/dist/observability.d.ts +1 -1
  20. package/dist/observability.js +1 -1
  21. package/dist/observability.js.map +1 -1
  22. package/dist/runtime.d.ts +15 -7
  23. package/dist/runtime.js +160 -67
  24. package/dist/runtime.js.map +1 -1
  25. package/dist/snapshot.js +2 -1
  26. package/dist/snapshot.js.map +1 -1
  27. package/dist/transport.d.ts +2 -1
  28. package/dist/transport.js +2 -2
  29. package/dist/transport.js.map +1 -1
  30. package/dist/worker-status.js +4 -1
  31. package/dist/worker-status.js.map +1 -1
  32. package/dist/workspace.d.ts +9 -0
  33. package/dist/workspace.js +61 -0
  34. package/dist/workspace.js.map +1 -0
  35. package/package.json +3 -2
  36. package/rules.md +30 -0
  37. package/src/config.ts +23 -2
  38. package/src/connections.ts +6 -4
  39. package/src/core-monitor.ts +2 -2
  40. package/src/herdr-core.ts +11 -6
  41. package/src/index.ts +17 -10
  42. package/src/launcher.ts +1 -1
  43. package/src/monitor-view.ts +9 -2
  44. package/src/observability.ts +1 -1
  45. package/src/runtime.ts +143 -64
  46. package/src/snapshot.ts +2 -1
  47. package/src/transport.ts +4 -4
  48. package/src/worker-status.ts +4 -1
  49. package/src/workspace.ts +51 -0
  50. package/dist/reminders.d.ts +0 -28
  51. package/dist/reminders.js +0 -81
  52. package/dist/reminders.js.map +0 -1
  53. package/src/reminders.ts +0 -69
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');
@@ -37,7 +37,7 @@ export function envelope(value: unknown): Envelope {
37
37
  return m;
38
38
  }
39
39
  export interface Endpoint { port: number; close(): Promise<void> }
40
- export async function listen(preferred: number | undefined, accept: (message: Envelope) => Promise<void>, health?: () => { version: 1; sessionId: string }): Promise<Endpoint> {
40
+ export async function listen(preferred: number | undefined, accept: (message: Envelope) => Promise<void>, health?: () => { version: 1; sessionId: string; busy?: boolean }): Promise<Endpoint> {
41
41
  const server = http.createServer(async (req, res) => {
42
42
  const reply = (status: number, data: unknown) => { if (!res.destroyed) { res.writeHead(status, { 'content-type': 'application/json', connection: 'close' }); res.end(JSON.stringify(data)); } };
43
43
  if (req.method === 'GET' && req.url === '/intercom/health') {
@@ -46,7 +46,7 @@ export async function listen(preferred: number | undefined, accept: (message: En
46
46
  else {
47
47
  const identity = health();
48
48
  if (identity.version !== 1 || typeof identity.sessionId !== 'string' || !identity.sessionId.trim() || identity.sessionId.length > 256) throw new Error('invalid health identity');
49
- reply(200, { version: 1, sessionId: identity.sessionId });
49
+ reply(200, { version: 1, sessionId: identity.sessionId, ...(typeof identity.busy === 'boolean' ? { busy: identity.busy } : {}) });
50
50
  }
51
51
  } catch { reply(503, { error: 'health unavailable' }); }
52
52
  req.resume(); return;
@@ -60,7 +60,10 @@ export function workerStatusPage(snapshot: ObservationSnapshot, options: { name?
60
60
  const age = now - Date.parse(timestamp);
61
61
  return Number.isFinite(age) && age >= 0 ? Math.floor(age / 1000) : null;
62
62
  };
63
- const entry = { sessionId: agent.sessionId, name: agent.name, ...workerObservation(snapshot, agent.sessionId, now),
63
+ const entry = { sessionId: agent.sessionId, name: agent.name, description: agent.description,
64
+ worktree: agent.worktree ?? null, branch: agent.branch ?? null,
65
+ configuration: agent.worktree && agent.branch ? 'configured (not proof of loaded configuration)' : 'reconfiguration_required',
66
+ ...workerObservation(snapshot, agent.sessionId, now),
64
67
  connection: currentConnection(agent.sessionId, snapshot.connections, now),
65
68
  handoff: saved.handoff ? { ...saved.handoff, ageSeconds: ageSeconds(saved.handoff.updatedAt), selfReported: true } : null,
66
69
  closeJob: saved.closeJob ? { ...saved.closeJob, ageSeconds: ageSeconds(saved.closeJob.updatedAt) } : null,
@@ -0,0 +1,51 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import { fail, requireWorkspace, type Agent } from './config.js';
6
+
7
+ const exec = promisify(execFile);
8
+ const CHECK_TIMEOUT_MS = 3000;
9
+ export interface WorkerWorkspace { worktree: string; branch: string }
10
+
11
+ /** Compare the loaded contract, not transport ports or optional workflow metadata. */
12
+ export function sameResponsibility(a: Agent, b: Agent): boolean {
13
+ return a.sessionId === b.sessionId && a.coordinator === b.coordinator && a.name === b.name &&
14
+ a.description === b.description && a.projectDirectory === b.projectDirectory &&
15
+ a.worktree === b.worktree && a.branch === b.branch;
16
+ }
17
+
18
+ /** Read-only Git inspection. No shell, hooks, writes, retries, or inherited Git routing. */
19
+ export async function validateWorkerWorkspace(root: string, agent: Pick<Agent, 'worktree' | 'branch'>): Promise<WorkerWorkspace> {
20
+ requireWorkspace(agent);
21
+ const deadline = Date.now() + CHECK_TIMEOUT_MS;
22
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
23
+ env.GIT_OPTIONAL_LOCKS = '0';
24
+ env.GIT_TERMINAL_PROMPT = '0';
25
+ const git = async (cwd: string, args: string[]): Promise<string> => {
26
+ const timeout = deadline - Date.now();
27
+ if (timeout <= 0) fail('worker workspace validation timed out');
28
+ try {
29
+ const result = await exec('git', ['-C', cwd, ...args], { env, timeout, maxBuffer: 16384, windowsHide: true, encoding: 'utf8' });
30
+ return result.stdout.trimEnd();
31
+ } catch { return fail('worker workspace Git check failed (Git unavailable, invalid repository, detached HEAD, or timeout)'); }
32
+ };
33
+ let base: string, worktree: string;
34
+ try {
35
+ [base, worktree] = await Promise.all([realpath(root), realpath(path.resolve(root, agent.worktree))]);
36
+ if (!(await stat(worktree)).isDirectory()) fail('worker worktree is not a directory');
37
+ } catch { return fail('worker worktree directory is missing or inaccessible'); }
38
+ if (path.relative(base, worktree) === '') fail('worker worktree must be separate from the project root');
39
+ const [rootCommon, metadata, ref] = await Promise.all([
40
+ git(base, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
41
+ git(worktree, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir']),
42
+ git(worktree, ['symbolic-ref', '--quiet', 'HEAD']),
43
+ ]);
44
+ const parts = metadata.split(/\r?\n/);
45
+ if (parts.length !== 2) fail('invalid worker worktree metadata');
46
+ const [top, common, projectCommon] = await Promise.all([realpath(parts[0]), realpath(parts[1]), realpath(rootCommon)]);
47
+ if (path.relative(top, worktree) !== '') fail('worker worktree must be the worktree root, not a subdirectory');
48
+ if (path.relative(common, projectCommon) !== '') fail('worker worktree belongs to a different repository');
49
+ if (ref !== `refs/heads/${agent.branch}`) fail('worker worktree is not on its configured branch');
50
+ return { worktree, branch: agent.branch };
51
+ }
@@ -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,IAAI,GAAG,CAAC,CAAC;IACT,QAAQ,GAAG,KAAK,CAAC;IACjB,QAAQ,GAAG,KAAK,CAAC;IACjB,MAAM,CAAc;IACpB,WAAW,CAAc;IACjC,YAA6B,IAAkB,EAAmB,QAAuB,KAAK;QAAjE,SAAI,GAAJ,IAAI,CAAc;QAAmB,UAAK,GAAL,KAAK,CAAuB;IAAG,CAAC;IAClG,GAAG,CAAC,MAAoB;QACtB,IAAI,IAAI,CAAC,QAAQ,IAAI,MAAM,EAAE,OAAO;YAAE,OAAO;QAC7C,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QACnC,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,KAAK,GAAG,GAAG,EAAE,GAAG,IAAI,IAAI,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AwE;YACxE,wEAAwE;YACxE,IAAI,IAAI,CAAC,QAAQ;gBAAE,OAAO;YAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;YACrB,KAAK,CAAC,KAAK,IAAI,EAAE;gBACf,IAAI,CAAC;oBACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;oBACpD,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC;wBAAE,OAAO;oBAC5C,IAAI,CAAC,WAAW,EAAE,CAAC;wBAAC,IAAI,CAAC,IAAI,EAAE,CAAC;wBAAC,OAAO;oBAAC,CAAC;oBAC1C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;wBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;gBAC1D,CAAC;gBAAC,MAAM,CAAC,CAAC,oEAAoE,CAAC,CAAC;wBACxE,CAAC;oBAAC,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;gBAAC,CAAC;YACpC,CAAC,CAAC,EAAE,CAAC;QACP,CAAC,EAAE,oBAAoB,CAAC,CAAC;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
- }