@luminascale/shepherd 0.0.0-stage → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/agents/README.md +12 -0
- package/.agents/agents/planner.md +38 -0
- package/.agents/agents/reviewer.md +38 -0
- package/.agents/agents/scout.md +43 -0
- package/.agents/agents/worker.md +33 -0
- package/.agents/skills/smoke-test/SKILL.md +155 -0
- package/.agents/skills/smoke-test/references/forensics.md +46 -0
- package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
- package/.github/workflows/publish.yml +77 -0
- package/.pi/prompts/release.md +21 -0
- package/.prettierrc +10 -0
- package/AGENTS.md +88 -0
- package/CONTRIBUTING.md +177 -0
- package/LICENSE +201 -0
- package/README.md +397 -2
- package/docs/README.md +26 -0
- package/docs/guides/agent-definitions.md +42 -0
- package/docs/guides/diagnostics.md +199 -0
- package/docs/guides/installation.md +61 -0
- package/docs/guides/tool-reference.md +55 -0
- package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
- package/docs/plans/agent-labels.md +257 -0
- package/docs/plans/architecture.md +110 -0
- package/docs/plans/settings-scope.md +163 -0
- package/docs/plans/tool-surface-split.md +278 -0
- package/docs/reference/dictionary +26 -0
- package/docs/releasing.md +47 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
- package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
- package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
- package/index.ts +602 -0
- package/package.json +112 -4
- package/scripts/capture-system-prompt.mjs +45 -0
- package/scripts/extract-pi-system-prompt.mjs +277 -0
- package/scripts/host-impact.mjs +74 -0
- package/scripts/resolve-agent.mjs +43 -0
- package/scripts/show-shepherd-orchestrator.mjs +58 -0
- package/scripts/show-shepherd-prompt.mjs +96 -0
- package/scripts/verify-suites.mjs +67 -0
- package/specs/001-artifacts/spec.md +436 -0
- package/specs/002-simplify-agent-orchestration/plan.md +287 -0
- package/specs/002-simplify-agent-orchestration/spec.md +323 -0
- package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
- package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
- package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
- package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
- package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
- package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
- package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
- package/specs/005-per-workspace-settings/plan.md +230 -0
- package/specs/005-per-workspace-settings/spec.md +368 -0
- package/specs/005-per-workspace-settings/tasks.md +178 -0
- package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
- package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
- package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
- package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
- package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
- package/specs/007-unwatched-completion-notice/journal.md +145 -0
- package/specs/007-unwatched-completion-notice/plan.md +186 -0
- package/specs/007-unwatched-completion-notice/spec.md +284 -0
- package/specs/007-unwatched-completion-notice/tasks.md +147 -0
- package/specs/008-remote-machine-sheep/intent.md +174 -0
- package/specs/008-remote-machine-sheep/journal.md +57 -0
- package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
- package/specs/009-hc-runtime/intent.md +44 -0
- package/specs/009-hc-runtime/plan.md +49 -0
- package/specs/009-hc-runtime/spec.md +118 -0
- package/specs/009-hc-runtime/tasks.md +62 -0
- package/specs/010-unseen-watch-parity/intent.md +57 -0
- package/specs/010-unseen-watch-parity/journal.md +172 -0
- package/specs/010-unseen-watch-parity/plan.md +74 -0
- package/specs/010-unseen-watch-parity/spec.md +191 -0
- package/specs/010-unseen-watch-parity/tasks.md +119 -0
- package/specs/011-hc-background-poll/intent.md +57 -0
- package/specs/011-hc-background-poll/journal.md +95 -0
- package/specs/011-hc-background-poll/plan.md +87 -0
- package/specs/011-hc-background-poll/spec.md +141 -0
- package/specs/011-hc-background-poll/tasks.md +83 -0
- package/specs/012-steer-default/intent.md +12 -0
- package/specs/012-steer-default/journal.md +40 -0
- package/specs/012-steer-default/plan.md +7 -0
- package/specs/012-steer-default/spec.md +42 -0
- package/specs/012-steer-default/tasks.md +6 -0
- package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
- package/specs/013-opencode-shepherd/intent.md +59 -0
- package/specs/013-opencode-shepherd/plan.md +204 -0
- package/specs/013-opencode-shepherd/spec.md +258 -0
- package/specs/013-opencode-shepherd/tasks.md +263 -0
- package/src/core/artifact-sessions.ts +835 -0
- package/src/core/config.ts +329 -0
- package/src/core/discovery.ts +342 -0
- package/src/core/herdr.ts +1 -0
- package/src/core/host.ts +77 -0
- package/src/core/ids.ts +78 -0
- package/src/core/lifecycle.ts +1 -0
- package/src/core/messaging.ts +1 -0
- package/src/core/migration.ts +55 -0
- package/src/core/orchestration.ts +1 -0
- package/src/core/types.ts +143 -0
- package/src/core/unseen-completions.ts +114 -0
- package/src/extension/cli.ts +417 -0
- package/src/extension/config.ts +1 -0
- package/src/extension/settings-ui.ts +296 -0
- package/src/extension/shepherd-done.ts +768 -0
- package/src/extension/shepherd.ts +2548 -0
- package/src/extension/system-prompt.ts +38 -0
- package/src/extension/unseen-completions.ts +237 -0
- package/src/opencode/actions.ts +794 -0
- package/src/opencode/bridge.ts +777 -0
- package/src/opencode/display.ts +36 -0
- package/src/opencode/fieldnotes.ts +60 -0
- package/src/opencode/host.ts +62 -0
- package/src/opencode/orphans.ts +162 -0
- package/src/opencode/server.ts +458 -0
- package/src/runtimes/backend.ts +119 -0
- package/src/runtimes/detect.ts +102 -0
- package/src/runtimes/hc/hc.ts +527 -0
- package/src/runtimes/hc/runtime.ts +1898 -0
- package/src/runtimes/herdr/herdr.ts +912 -0
- package/src/runtimes/herdr/lifecycle.ts +1712 -0
- package/src/runtimes/herdr/messaging.ts +703 -0
- package/src/runtimes/herdr/orchestration.ts +1583 -0
- package/src/runtimes/herdr/runtime.ts +224 -0
- package/src/runtimes/runtime.ts +133 -0
- package/src/runtimes/settle-observations.ts +114 -0
- package/test/fixtures/context-project/AGENTS.md +2 -0
- package/test/fixtures/home/.agents/agents/same.md +6 -0
- package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
- package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
- package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
- package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
- package/test/fixtures/proj/.pi/agents/same.md +6 -0
- package/test/helpers/fake-clock.mjs +39 -0
- package/test/helpers/feature-contracts.mjs +44 -0
- package/test/helpers/test-utils.mjs +44 -0
- package/test/verify-artifact-sessions.mjs +258 -0
- package/test/verify-backend.mjs +297 -0
- package/test/verify-child-mislabel.mjs +135 -0
- package/test/verify-child-surface.mjs +321 -0
- package/test/verify-cli.mjs +197 -0
- package/test/verify-command-ux.mjs +100 -0
- package/test/verify-compat.mjs +32 -0
- package/test/verify-cross-host-notes.mjs +128 -0
- package/test/verify-delegate.mjs +161 -0
- package/test/verify-detect.mjs +151 -0
- package/test/verify-discovery.mjs +239 -0
- package/test/verify-done-nudge.mjs +238 -0
- package/test/verify-effective-prompt.mjs +98 -0
- package/test/verify-hc-matrix.mjs +246 -0
- package/test/verify-hc-poll.mjs +260 -0
- package/test/verify-host-docs.mjs +66 -0
- package/test/verify-host-impact.mjs +49 -0
- package/test/verify-ids.mjs +141 -0
- package/test/verify-launch.mjs +183 -0
- package/test/verify-message-routing.mjs +560 -0
- package/test/verify-messaging.mjs +303 -0
- package/test/verify-migration-notice.mjs +74 -0
- package/test/verify-multi-wait.mjs +42 -0
- package/test/verify-opencode-display.mjs +47 -0
- package/test/verify-opencode-fieldnotes.mjs +121 -0
- package/test/verify-opencode-notice.mjs +77 -0
- package/test/verify-opencode-nudge.mjs +116 -0
- package/test/verify-opencode-orphans.mjs +160 -0
- package/test/verify-opencode-surface.mjs +107 -0
- package/test/verify-packaging.mjs +82 -0
- package/test/verify-parent-surface.mjs +118 -0
- package/test/verify-phase0.mjs +95 -0
- package/test/verify-registry.mjs +124 -0
- package/test/verify-rename-migration.mjs +111 -0
- package/test/verify-rendering.mjs +379 -0
- package/test/verify-session-boundary.mjs +146 -0
- package/test/verify-settings.mjs +260 -0
- package/test/verify-stale-wait.mjs +339 -0
- package/test/verify-status-widget.mjs +377 -0
- package/test/verify-status.mjs +172 -0
- package/test/verify-task-completion.mjs +156 -0
- package/test/verify-task-failures.mjs +201 -0
- package/test/verify-task-mislabel.mjs +143 -0
- package/test/verify-task-registry.mjs +194 -0
- package/test/verify-task-watchers.mjs +217 -0
- package/test/verify-tool-schemas.mjs +120 -0
- package/test/verify-unseen-completions.mjs +1211 -0
- package/test/verify-watchers.mjs +181 -0
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parent-owned filesystem mailbox for asynchronous Shepherd messages.
|
|
3
|
+
*
|
|
4
|
+
* This module is deliberately independent of Pi and Herdr. The parent creates
|
|
5
|
+
* a session broker, registers child identities, and passes each child a
|
|
6
|
+
* capability for its own inbox. Envelopes are published with an atomic
|
|
7
|
+
* temporary-file-plus-rename operation and consumed exactly once per broker
|
|
8
|
+
* session through acknowledgement markers.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
11
|
+
import * as fs from 'node:fs';
|
|
12
|
+
import * as os from 'node:os';
|
|
13
|
+
import * as path from 'node:path';
|
|
14
|
+
import { mintMessageId } from '../../core/ids.ts';
|
|
15
|
+
|
|
16
|
+
export type ShepherdEnvelopeKind = 'message' | 'task' | 'reply' | 'task_done' | 'runtime';
|
|
17
|
+
export type ShepherdDelivery = 'followUp' | 'steer';
|
|
18
|
+
export type ShepherdMessageStatus = 'completed' | 'blocked' | 'failed';
|
|
19
|
+
|
|
20
|
+
export interface ShepherdMessageEnvelope {
|
|
21
|
+
schemaVersion: 1;
|
|
22
|
+
sessionId: string;
|
|
23
|
+
brokerId: string;
|
|
24
|
+
kind: ShepherdEnvelopeKind;
|
|
25
|
+
messageId: string;
|
|
26
|
+
senderId: string;
|
|
27
|
+
targetId: string;
|
|
28
|
+
taskId?: string;
|
|
29
|
+
threadId?: string;
|
|
30
|
+
replyTo?: string;
|
|
31
|
+
expectsReply?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Set on a child `runtime` envelope that mirrors an `expectsReply` question
|
|
34
|
+
* the child just published. The parent uses it to open a pending request on
|
|
35
|
+
* the task (running -> waiting). It is the child's explicit, correlated
|
|
36
|
+
* declaration that a tracked reply is now outstanding.
|
|
37
|
+
*/
|
|
38
|
+
requestOpen?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Set on a child runtime envelope that mirrors a reply already delivered
|
|
41
|
+
* directly to a peer. The parent uses it to resolve the requester's task
|
|
42
|
+
* without relaying a second copy of the reply.
|
|
43
|
+
*/
|
|
44
|
+
replyReceived?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Companion to `requestOpen`: the opaque agent id the question was published
|
|
47
|
+
* to, so the parent can display who the task is waiting for and name the
|
|
48
|
+
* recipient in the reply-deadline outcome.
|
|
49
|
+
*/
|
|
50
|
+
requestTargetId?: string;
|
|
51
|
+
/**
|
|
52
|
+
* When the parent broker relays a child-authored reply, this carries the
|
|
53
|
+
* original author's agent id. The authenticated `senderId` stays the parent
|
|
54
|
+
* (the broker republishes under its own identity), so provenance about who
|
|
55
|
+
* actually wrote the reply is carried as structural metadata that cannot be
|
|
56
|
+
* forged through the transport layer.
|
|
57
|
+
*/
|
|
58
|
+
originSenderId?: string;
|
|
59
|
+
deadlineAt?: number;
|
|
60
|
+
delivery: ShepherdDelivery;
|
|
61
|
+
content?: string;
|
|
62
|
+
status?: ShepherdMessageStatus;
|
|
63
|
+
summary?: string;
|
|
64
|
+
error?: string;
|
|
65
|
+
createdAt: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type ShepherdEnvelopeInput = Omit<
|
|
69
|
+
ShepherdMessageEnvelope,
|
|
70
|
+
'schemaVersion' | 'sessionId' | 'brokerId' | 'messageId' | 'senderId' | 'createdAt'
|
|
71
|
+
> & {
|
|
72
|
+
messageId?: string;
|
|
73
|
+
createdAt?: number;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export interface BrokerOptions {
|
|
77
|
+
/** Use a deterministic test/runtime path instead of a generated temp path. */
|
|
78
|
+
rootDir?: string;
|
|
79
|
+
maxMessageBytes?: number;
|
|
80
|
+
maxContentLength?: number;
|
|
81
|
+
maxQueueDepth?: number;
|
|
82
|
+
parentId?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface ChildCapability {
|
|
86
|
+
sessionId: string;
|
|
87
|
+
brokerId: string;
|
|
88
|
+
agentId: string;
|
|
89
|
+
token: string;
|
|
90
|
+
inboxPath: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface PublishResult {
|
|
94
|
+
accepted: true;
|
|
95
|
+
messageId: string;
|
|
96
|
+
delivery: 'queued' | 'duplicate';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface ParentBroker {
|
|
100
|
+
readonly rootDir: string;
|
|
101
|
+
readonly sessionId: string;
|
|
102
|
+
readonly brokerId: string;
|
|
103
|
+
readonly parentId: string;
|
|
104
|
+
readonly parentInboxPath: string;
|
|
105
|
+
readonly maxMessageBytes: number;
|
|
106
|
+
readonly maxContentLength: number;
|
|
107
|
+
readonly maxQueueDepth: number;
|
|
108
|
+
readonly children: Map<string, ChildCapability>;
|
|
109
|
+
closed: boolean;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface ChildBroker {
|
|
113
|
+
readonly rootDir: string;
|
|
114
|
+
readonly sessionId: string;
|
|
115
|
+
readonly brokerId: string;
|
|
116
|
+
readonly parentId: string;
|
|
117
|
+
readonly agentId: string;
|
|
118
|
+
readonly capability: ChildCapability;
|
|
119
|
+
readonly maxMessageBytes: number;
|
|
120
|
+
readonly maxContentLength: number;
|
|
121
|
+
readonly maxQueueDepth: number;
|
|
122
|
+
closed: boolean;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export type MessagingErrorCode =
|
|
126
|
+
| 'broker_closed'
|
|
127
|
+
| 'invalid_envelope'
|
|
128
|
+
| 'foreign_session'
|
|
129
|
+
| 'invalid_sender'
|
|
130
|
+
| 'invalid_target'
|
|
131
|
+
| 'invalid_capability'
|
|
132
|
+
| 'queue_full'
|
|
133
|
+
| 'message_too_large'
|
|
134
|
+
| 'duplicate_conflict'
|
|
135
|
+
| 'children_alive';
|
|
136
|
+
|
|
137
|
+
export class MessagingError extends Error {
|
|
138
|
+
readonly code: MessagingErrorCode;
|
|
139
|
+
|
|
140
|
+
constructor(code: MessagingErrorCode, message: string) {
|
|
141
|
+
super(message);
|
|
142
|
+
this.name = 'MessagingError';
|
|
143
|
+
this.code = code;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const DEFAULT_MAX_MESSAGE_BYTES = 64 * 1024;
|
|
148
|
+
const DEFAULT_MAX_CONTENT_LENGTH = 50_000;
|
|
149
|
+
const DEFAULT_MAX_QUEUE_DEPTH = 1_000;
|
|
150
|
+
const ENVELOPE_KINDS = new Set<ShepherdEnvelopeKind>([
|
|
151
|
+
'message',
|
|
152
|
+
'task',
|
|
153
|
+
'reply',
|
|
154
|
+
'task_done',
|
|
155
|
+
'runtime',
|
|
156
|
+
]);
|
|
157
|
+
const DELIVERIES = new Set<ShepherdDelivery>(['followUp', 'steer']);
|
|
158
|
+
const STATUSES = new Set<ShepherdMessageStatus>(['completed', 'blocked', 'failed']);
|
|
159
|
+
|
|
160
|
+
function ensureDirectory(directory: string, mode = 0o700): void {
|
|
161
|
+
fs.mkdirSync(directory, { recursive: true, mode });
|
|
162
|
+
try {
|
|
163
|
+
fs.chmodSync(directory, mode);
|
|
164
|
+
} catch {
|
|
165
|
+
// Windows and some mounted filesystems do not support chmod reliably.
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function childDirectoryName(agentId: string): string {
|
|
170
|
+
return createHash('sha256').update(agentId).digest('hex').slice(0, 32);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function messageFileName(envelope: ShepherdMessageEnvelope): string {
|
|
174
|
+
const stamp = String(Math.max(0, Math.floor(envelope.createdAt))).padStart(16, '0');
|
|
175
|
+
return `${stamp}-${childDirectoryName(envelope.messageId)}.json`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function markerName(messageId: string): string {
|
|
179
|
+
return `${childDirectoryName(messageId)}.ack`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function assertNonEmptyString(value: unknown, field: string): asserts value is string {
|
|
183
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
184
|
+
throw new MessagingError('invalid_envelope', `${field} must be a non-empty string.`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function assertSafeLimit(value: number | undefined, fallback: number, field: string): number {
|
|
189
|
+
const result = value ?? fallback;
|
|
190
|
+
if (!Number.isInteger(result) || result <= 0) {
|
|
191
|
+
throw new MessagingError('invalid_envelope', `${field} must be a positive integer.`);
|
|
192
|
+
}
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Validate a decoded envelope before it reaches a routing handler. */
|
|
197
|
+
export function validateEnvelope(value: unknown): ShepherdMessageEnvelope {
|
|
198
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
199
|
+
throw new MessagingError('invalid_envelope', 'Message envelope must be a JSON object.');
|
|
200
|
+
}
|
|
201
|
+
const envelope = value as Record<string, unknown>;
|
|
202
|
+
if (envelope.schemaVersion !== 1) {
|
|
203
|
+
throw new MessagingError('invalid_envelope', 'Unsupported message envelope schema version.');
|
|
204
|
+
}
|
|
205
|
+
assertNonEmptyString(envelope.sessionId, 'sessionId');
|
|
206
|
+
assertNonEmptyString(envelope.brokerId, 'brokerId');
|
|
207
|
+
assertNonEmptyString(envelope.kind, 'kind');
|
|
208
|
+
if (!ENVELOPE_KINDS.has(envelope.kind as ShepherdEnvelopeKind)) {
|
|
209
|
+
throw new MessagingError('invalid_envelope', `Unsupported message kind "${envelope.kind}".`);
|
|
210
|
+
}
|
|
211
|
+
assertNonEmptyString(envelope.messageId, 'messageId');
|
|
212
|
+
assertNonEmptyString(envelope.senderId, 'senderId');
|
|
213
|
+
assertNonEmptyString(envelope.targetId, 'targetId');
|
|
214
|
+
if (!DELIVERIES.has(envelope.delivery as ShepherdDelivery)) {
|
|
215
|
+
throw new MessagingError('invalid_envelope', 'delivery must be followUp or steer.');
|
|
216
|
+
}
|
|
217
|
+
if (typeof envelope.createdAt !== 'number' || !Number.isFinite(envelope.createdAt)) {
|
|
218
|
+
throw new MessagingError('invalid_envelope', 'createdAt must be a finite number.');
|
|
219
|
+
}
|
|
220
|
+
if (
|
|
221
|
+
envelope.deadlineAt !== undefined &&
|
|
222
|
+
(typeof envelope.deadlineAt !== 'number' || !Number.isFinite(envelope.deadlineAt))
|
|
223
|
+
) {
|
|
224
|
+
throw new MessagingError(
|
|
225
|
+
'invalid_envelope',
|
|
226
|
+
'deadlineAt must be a finite number when present.'
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
for (const field of [
|
|
230
|
+
'taskId',
|
|
231
|
+
'threadId',
|
|
232
|
+
'replyTo',
|
|
233
|
+
'content',
|
|
234
|
+
'summary',
|
|
235
|
+
'error',
|
|
236
|
+
'requestTargetId',
|
|
237
|
+
'originSenderId',
|
|
238
|
+
]) {
|
|
239
|
+
if (envelope[field] !== undefined && typeof envelope[field] !== 'string') {
|
|
240
|
+
throw new MessagingError('invalid_envelope', `${field} must be a string when present.`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (envelope.expectsReply !== undefined && typeof envelope.expectsReply !== 'boolean') {
|
|
244
|
+
throw new MessagingError('invalid_envelope', 'expectsReply must be a boolean when present.');
|
|
245
|
+
}
|
|
246
|
+
if (envelope.requestOpen !== undefined && typeof envelope.requestOpen !== 'boolean') {
|
|
247
|
+
throw new MessagingError('invalid_envelope', 'requestOpen must be a boolean when present.');
|
|
248
|
+
}
|
|
249
|
+
if (envelope.replyReceived !== undefined && typeof envelope.replyReceived !== 'boolean') {
|
|
250
|
+
throw new MessagingError('invalid_envelope', 'replyReceived must be a boolean when present.');
|
|
251
|
+
}
|
|
252
|
+
if (envelope.status !== undefined && !STATUSES.has(envelope.status as ShepherdMessageStatus)) {
|
|
253
|
+
throw new MessagingError(
|
|
254
|
+
'invalid_envelope',
|
|
255
|
+
`Unsupported message status "${envelope.status}".`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
return { ...(value as ShepherdMessageEnvelope) };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Build a complete envelope for one broker participant. */
|
|
262
|
+
export function createEnvelope(
|
|
263
|
+
context: { sessionId: string; brokerId: string; senderId: string },
|
|
264
|
+
input: ShepherdEnvelopeInput
|
|
265
|
+
): ShepherdMessageEnvelope {
|
|
266
|
+
assertNonEmptyString(context.sessionId, 'sessionId');
|
|
267
|
+
assertNonEmptyString(context.brokerId, 'brokerId');
|
|
268
|
+
assertNonEmptyString(context.senderId, 'senderId');
|
|
269
|
+
const envelope = {
|
|
270
|
+
...input,
|
|
271
|
+
schemaVersion: 1 as const,
|
|
272
|
+
sessionId: context.sessionId,
|
|
273
|
+
brokerId: context.brokerId,
|
|
274
|
+
senderId: context.senderId,
|
|
275
|
+
messageId: input.messageId ?? mintMessageId(),
|
|
276
|
+
createdAt: input.createdAt ?? Date.now(),
|
|
277
|
+
};
|
|
278
|
+
return validateEnvelope(envelope);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function brokerManifest(broker: ParentBroker): Record<string, unknown> {
|
|
282
|
+
return {
|
|
283
|
+
schemaVersion: 1,
|
|
284
|
+
sessionId: broker.sessionId,
|
|
285
|
+
brokerId: broker.brokerId,
|
|
286
|
+
parentId: broker.parentId,
|
|
287
|
+
maxMessageBytes: broker.maxMessageBytes,
|
|
288
|
+
maxContentLength: broker.maxContentLength,
|
|
289
|
+
maxQueueDepth: broker.maxQueueDepth,
|
|
290
|
+
createdAt: Date.now(),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function writeJsonAtomic(target: string, value: unknown): void {
|
|
295
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
296
|
+
try {
|
|
297
|
+
fs.writeFileSync(temporary, JSON.stringify(value), { encoding: 'utf8', mode: 0o600 });
|
|
298
|
+
fs.renameSync(temporary, target);
|
|
299
|
+
} catch (error) {
|
|
300
|
+
try {
|
|
301
|
+
fs.rmSync(temporary, { force: true });
|
|
302
|
+
} catch {}
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function readJson(filePath: string): unknown {
|
|
308
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function inboxFiles(inboxPath: string): string[] {
|
|
312
|
+
try {
|
|
313
|
+
return fs
|
|
314
|
+
.readdirSync(inboxPath)
|
|
315
|
+
.filter(name => name.endsWith('.json'))
|
|
316
|
+
.sort()
|
|
317
|
+
.map(name => path.join(inboxPath, name));
|
|
318
|
+
} catch {
|
|
319
|
+
return [];
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function ackPath(broker: ParentBroker | ChildBroker, messageId: string): string {
|
|
324
|
+
return path.join(broker.rootDir, 'acks', markerName(messageId));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function isAcknowledged(broker: ParentBroker | ChildBroker, messageId: string): boolean {
|
|
328
|
+
return fs.existsSync(ackPath(broker, messageId));
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function acknowledgeEnvelope(
|
|
332
|
+
broker: ParentBroker | ChildBroker,
|
|
333
|
+
envelope: ShepherdMessageEnvelope
|
|
334
|
+
): void {
|
|
335
|
+
const target = ackPath(broker, envelope.messageId);
|
|
336
|
+
if (!fs.existsSync(target)) {
|
|
337
|
+
writeJsonAtomic(target, {
|
|
338
|
+
messageId: envelope.messageId,
|
|
339
|
+
targetId: envelope.targetId,
|
|
340
|
+
acknowledgedAt: Date.now(),
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function assertBrokerOpen(broker: ParentBroker | ChildBroker): void {
|
|
346
|
+
if (broker.closed) throw new MessagingError('broker_closed', 'Messaging broker is closed.');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function assertBrokerIdentity(
|
|
350
|
+
broker: ParentBroker | ChildBroker,
|
|
351
|
+
envelope: ShepherdMessageEnvelope
|
|
352
|
+
): void {
|
|
353
|
+
if (envelope.sessionId !== broker.sessionId || envelope.brokerId !== broker.brokerId) {
|
|
354
|
+
throw new MessagingError(
|
|
355
|
+
'foreign_session',
|
|
356
|
+
`Envelope "${envelope.messageId}" belongs to another Shepherd broker session.`
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function invalidChildTargetMessage(targetId: string): string {
|
|
362
|
+
return `Unknown child target "${targetId}". shepherd_message requires the exact opaque agent id returned by shepherd_spawn (for example "shepherd-agent-..."); do not use an agent name such as "planner", a display label, a Herdr pane id, or a placeholder such as "<planner agent ID>".`;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function queuePathForChild(broker: ParentBroker, targetId: string): string {
|
|
366
|
+
const child = broker.children.get(targetId);
|
|
367
|
+
if (!child) throw new MessagingError('invalid_target', invalidChildTargetMessage(targetId));
|
|
368
|
+
return child.inboxPath;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function queuePathForChildConnection(child: ChildBroker, targetId: string): string {
|
|
372
|
+
if (targetId === child.parentId || targetId === 'shepherd' || targetId === 'parent') {
|
|
373
|
+
return path.join(child.rootDir, 'parent', 'inbox');
|
|
374
|
+
}
|
|
375
|
+
const manifestPath = path.join(
|
|
376
|
+
child.rootDir,
|
|
377
|
+
'agents',
|
|
378
|
+
childDirectoryName(targetId),
|
|
379
|
+
'manifest.json'
|
|
380
|
+
);
|
|
381
|
+
if (!fs.existsSync(manifestPath)) {
|
|
382
|
+
throw new MessagingError('invalid_target', invalidChildTargetMessage(targetId));
|
|
383
|
+
}
|
|
384
|
+
return path.join(child.rootDir, 'agents', childDirectoryName(targetId), 'inbox');
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function publishToQueue(
|
|
388
|
+
broker: ParentBroker | ChildBroker,
|
|
389
|
+
inboxPath: string,
|
|
390
|
+
envelope: ShepherdMessageEnvelope
|
|
391
|
+
): PublishResult {
|
|
392
|
+
assertBrokerOpen(broker);
|
|
393
|
+
const encoded = Buffer.from(JSON.stringify(envelope), 'utf8');
|
|
394
|
+
const maxBytes = broker.maxMessageBytes;
|
|
395
|
+
const maxContentLength = broker.maxContentLength;
|
|
396
|
+
const maxQueueDepth = broker.maxQueueDepth;
|
|
397
|
+
if (typeof envelope.content === 'string' && envelope.content.length > maxContentLength) {
|
|
398
|
+
throw new MessagingError(
|
|
399
|
+
'message_too_large',
|
|
400
|
+
`Message "${envelope.messageId}" content exceeds the ${maxContentLength}-character limit.`
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
if (encoded.byteLength > maxBytes) {
|
|
404
|
+
throw new MessagingError(
|
|
405
|
+
'message_too_large',
|
|
406
|
+
`Message "${envelope.messageId}" is ${encoded.byteLength} bytes; maximum is ${maxBytes}.`
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
ensureDirectory(inboxPath);
|
|
410
|
+
if (isAcknowledged(broker, envelope.messageId)) {
|
|
411
|
+
return { accepted: true, messageId: envelope.messageId, delivery: 'duplicate' };
|
|
412
|
+
}
|
|
413
|
+
const files = inboxFiles(inboxPath);
|
|
414
|
+
const target = path.join(inboxPath, messageFileName(envelope));
|
|
415
|
+
if (files.length >= maxQueueDepth && !files.includes(target)) {
|
|
416
|
+
throw new MessagingError('queue_full', `Message queue for "${envelope.targetId}" is full.`);
|
|
417
|
+
}
|
|
418
|
+
if (fs.existsSync(target)) {
|
|
419
|
+
let existing: ShepherdMessageEnvelope | undefined;
|
|
420
|
+
try {
|
|
421
|
+
existing = validateEnvelope(readJson(target));
|
|
422
|
+
} catch {
|
|
423
|
+
throw new MessagingError(
|
|
424
|
+
'duplicate_conflict',
|
|
425
|
+
`Message file for "${envelope.messageId}" is invalid.`
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
if (JSON.stringify(existing) !== JSON.stringify(envelope)) {
|
|
429
|
+
throw new MessagingError(
|
|
430
|
+
'duplicate_conflict',
|
|
431
|
+
`Message id "${envelope.messageId}" is already in use.`
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
return { accepted: true, messageId: envelope.messageId, delivery: 'duplicate' };
|
|
435
|
+
}
|
|
436
|
+
const temporary = path.join(inboxPath, `.${messageFileName(envelope)}.${randomUUID()}.tmp`);
|
|
437
|
+
try {
|
|
438
|
+
fs.writeFileSync(temporary, encoded, { encoding: 'utf8', mode: 0o600 });
|
|
439
|
+
fs.renameSync(temporary, target);
|
|
440
|
+
} catch (error) {
|
|
441
|
+
try {
|
|
442
|
+
fs.rmSync(temporary, { force: true });
|
|
443
|
+
} catch {}
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
return { accepted: true, messageId: envelope.messageId, delivery: 'queued' };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function pollQueue(
|
|
450
|
+
broker: ParentBroker | ChildBroker,
|
|
451
|
+
inboxPath: string,
|
|
452
|
+
expectedTarget: string,
|
|
453
|
+
limit = Number.MAX_SAFE_INTEGER
|
|
454
|
+
): ShepherdMessageEnvelope[] {
|
|
455
|
+
assertBrokerOpen(broker);
|
|
456
|
+
const processedPath = path.join(broker.rootDir, 'processed');
|
|
457
|
+
const rejectedPath = path.join(broker.rootDir, 'rejected');
|
|
458
|
+
ensureDirectory(processedPath);
|
|
459
|
+
ensureDirectory(rejectedPath);
|
|
460
|
+
const messages: ShepherdMessageEnvelope[] = [];
|
|
461
|
+
for (const filePath of inboxFiles(inboxPath).slice(0, limit)) {
|
|
462
|
+
let envelope: ShepherdMessageEnvelope;
|
|
463
|
+
try {
|
|
464
|
+
envelope = validateEnvelope(readJson(filePath));
|
|
465
|
+
assertBrokerIdentity(broker, envelope);
|
|
466
|
+
if (
|
|
467
|
+
envelope.targetId !== expectedTarget &&
|
|
468
|
+
!(expectedTarget === broker.parentId && ['shepherd', 'parent'].includes(envelope.targetId))
|
|
469
|
+
) {
|
|
470
|
+
throw new MessagingError(
|
|
471
|
+
'invalid_target',
|
|
472
|
+
`Envelope target "${envelope.targetId}" does not match this inbox.`
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
} catch {
|
|
476
|
+
try {
|
|
477
|
+
fs.renameSync(
|
|
478
|
+
filePath,
|
|
479
|
+
path.join(rejectedPath, `${path.basename(filePath)}.${randomUUID()}`)
|
|
480
|
+
);
|
|
481
|
+
} catch {}
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
if (isAcknowledged(broker, envelope.messageId)) {
|
|
485
|
+
try {
|
|
486
|
+
fs.rmSync(filePath, { force: true });
|
|
487
|
+
} catch {}
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
try {
|
|
491
|
+
fs.renameSync(
|
|
492
|
+
filePath,
|
|
493
|
+
path.join(processedPath, `${path.basename(filePath)}.${randomUUID()}`)
|
|
494
|
+
);
|
|
495
|
+
acknowledgeEnvelope(broker, envelope);
|
|
496
|
+
messages.push(envelope);
|
|
497
|
+
} catch {
|
|
498
|
+
// Leave a failed file for a later poll where possible. A duplicate
|
|
499
|
+
// envelope is safe because handlers are required to be idempotent.
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return messages;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** Create the parent broker and its protected inbox structure. */
|
|
506
|
+
export function createParentBroker(
|
|
507
|
+
sessionOwner: string,
|
|
508
|
+
options: BrokerOptions = {}
|
|
509
|
+
): ParentBroker {
|
|
510
|
+
assertNonEmptyString(sessionOwner, 'sessionOwner');
|
|
511
|
+
const rootDir = options.rootDir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'pi-shepherd-broker-'));
|
|
512
|
+
ensureDirectory(rootDir);
|
|
513
|
+
const parentInboxPath = path.join(rootDir, 'parent', 'inbox');
|
|
514
|
+
ensureDirectory(parentInboxPath);
|
|
515
|
+
ensureDirectory(path.join(rootDir, 'agents'));
|
|
516
|
+
ensureDirectory(path.join(rootDir, 'acks'));
|
|
517
|
+
ensureDirectory(path.join(rootDir, 'processed'));
|
|
518
|
+
ensureDirectory(path.join(rootDir, 'rejected'));
|
|
519
|
+
const broker: ParentBroker = {
|
|
520
|
+
rootDir,
|
|
521
|
+
sessionId: sessionOwner,
|
|
522
|
+
brokerId: `shepherd-broker-${randomUUID()}`,
|
|
523
|
+
parentId: options.parentId ?? 'shepherd',
|
|
524
|
+
parentInboxPath,
|
|
525
|
+
maxMessageBytes: assertSafeLimit(
|
|
526
|
+
options.maxMessageBytes,
|
|
527
|
+
DEFAULT_MAX_MESSAGE_BYTES,
|
|
528
|
+
'maxMessageBytes'
|
|
529
|
+
),
|
|
530
|
+
maxContentLength: assertSafeLimit(
|
|
531
|
+
options.maxContentLength,
|
|
532
|
+
DEFAULT_MAX_CONTENT_LENGTH,
|
|
533
|
+
'maxContentLength'
|
|
534
|
+
),
|
|
535
|
+
maxQueueDepth: assertSafeLimit(options.maxQueueDepth, DEFAULT_MAX_QUEUE_DEPTH, 'maxQueueDepth'),
|
|
536
|
+
children: new Map(),
|
|
537
|
+
closed: false,
|
|
538
|
+
};
|
|
539
|
+
writeJsonAtomic(path.join(rootDir, 'broker.json'), brokerManifest(broker));
|
|
540
|
+
return broker;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Register one child and create its capability-protected inbox. */
|
|
544
|
+
export function registerChild(broker: ParentBroker, agentId: string): ChildCapability {
|
|
545
|
+
assertBrokerOpen(broker);
|
|
546
|
+
assertNonEmptyString(agentId, 'agentId');
|
|
547
|
+
if (agentId === broker.parentId || ['parent', 'shepherd'].includes(agentId)) {
|
|
548
|
+
throw new MessagingError('invalid_sender', `Child id "${agentId}" is reserved for the parent.`);
|
|
549
|
+
}
|
|
550
|
+
const existing = broker.children.get(agentId);
|
|
551
|
+
if (existing) return { ...existing };
|
|
552
|
+
const directory = path.join(broker.rootDir, 'agents', childDirectoryName(agentId));
|
|
553
|
+
const inboxPath = path.join(directory, 'inbox');
|
|
554
|
+
ensureDirectory(inboxPath);
|
|
555
|
+
const capability: ChildCapability = {
|
|
556
|
+
sessionId: broker.sessionId,
|
|
557
|
+
brokerId: broker.brokerId,
|
|
558
|
+
agentId,
|
|
559
|
+
token: randomUUID(),
|
|
560
|
+
inboxPath,
|
|
561
|
+
};
|
|
562
|
+
writeJsonAtomic(path.join(directory, 'manifest.json'), capability);
|
|
563
|
+
broker.children.set(agentId, capability);
|
|
564
|
+
return { ...capability };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Remove a child registration only after its process/pane is confirmed gone. */
|
|
568
|
+
export function unregisterChild(broker: ParentBroker, agentId: string): void {
|
|
569
|
+
assertBrokerOpen(broker);
|
|
570
|
+
const child = broker.children.get(agentId);
|
|
571
|
+
if (!child) return;
|
|
572
|
+
broker.children.delete(agentId);
|
|
573
|
+
const directory = path.join(broker.rootDir, 'agents', childDirectoryName(agentId));
|
|
574
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** Rehydrate a child-side broker from launch-time identity and capability data. */
|
|
578
|
+
export function createChildBroker(input: ChildCapability & { rootDir: string }): ChildBroker {
|
|
579
|
+
const brokerFile = path.join(input.rootDir, 'broker.json');
|
|
580
|
+
let manifest: any;
|
|
581
|
+
try {
|
|
582
|
+
manifest = readJson(brokerFile);
|
|
583
|
+
} catch {
|
|
584
|
+
throw new MessagingError('invalid_capability', 'Parent broker manifest is unavailable.');
|
|
585
|
+
}
|
|
586
|
+
if (manifest.sessionId !== input.sessionId || manifest.brokerId !== input.brokerId) {
|
|
587
|
+
throw new MessagingError(
|
|
588
|
+
'foreign_session',
|
|
589
|
+
'Child capability belongs to another broker session.'
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
const directory = path.join(input.rootDir, 'agents', childDirectoryName(input.agentId));
|
|
593
|
+
let stored: any;
|
|
594
|
+
try {
|
|
595
|
+
stored = readJson(path.join(directory, 'manifest.json'));
|
|
596
|
+
} catch {
|
|
597
|
+
throw new MessagingError('invalid_capability', 'Child capability manifest is unavailable.');
|
|
598
|
+
}
|
|
599
|
+
if (
|
|
600
|
+
stored.agentId !== input.agentId ||
|
|
601
|
+
stored.token !== input.token ||
|
|
602
|
+
stored.inboxPath !== input.inboxPath
|
|
603
|
+
) {
|
|
604
|
+
throw new MessagingError(
|
|
605
|
+
'invalid_capability',
|
|
606
|
+
'Child capability does not match its registered inbox.'
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
return {
|
|
610
|
+
rootDir: input.rootDir,
|
|
611
|
+
sessionId: input.sessionId,
|
|
612
|
+
brokerId: input.brokerId,
|
|
613
|
+
parentId: typeof manifest.parentId === 'string' ? manifest.parentId : 'shepherd',
|
|
614
|
+
agentId: input.agentId,
|
|
615
|
+
capability: { ...input },
|
|
616
|
+
maxMessageBytes: assertSafeLimit(
|
|
617
|
+
manifest.maxMessageBytes,
|
|
618
|
+
DEFAULT_MAX_MESSAGE_BYTES,
|
|
619
|
+
'maxMessageBytes'
|
|
620
|
+
),
|
|
621
|
+
maxContentLength: assertSafeLimit(
|
|
622
|
+
manifest.maxContentLength,
|
|
623
|
+
DEFAULT_MAX_CONTENT_LENGTH,
|
|
624
|
+
'maxContentLength'
|
|
625
|
+
),
|
|
626
|
+
maxQueueDepth: assertSafeLimit(
|
|
627
|
+
manifest.maxQueueDepth,
|
|
628
|
+
DEFAULT_MAX_QUEUE_DEPTH,
|
|
629
|
+
'maxQueueDepth'
|
|
630
|
+
),
|
|
631
|
+
closed: false,
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export function publishFromParent(
|
|
636
|
+
broker: ParentBroker,
|
|
637
|
+
envelope: ShepherdMessageEnvelope
|
|
638
|
+
): PublishResult {
|
|
639
|
+
assertBrokerOpen(broker);
|
|
640
|
+
const valid = validateEnvelope(envelope);
|
|
641
|
+
assertBrokerIdentity(broker, valid);
|
|
642
|
+
if (valid.senderId !== broker.parentId) {
|
|
643
|
+
throw new MessagingError(
|
|
644
|
+
'invalid_sender',
|
|
645
|
+
`Parent envelopes must be sent by "${broker.parentId}".`
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
if (valid.targetId === broker.parentId || ['parent', 'shepherd'].includes(valid.targetId)) {
|
|
649
|
+
throw new MessagingError('invalid_target', 'Parent messages cannot target the parent inbox.');
|
|
650
|
+
}
|
|
651
|
+
return publishToQueue(broker, queuePathForChild(broker, valid.targetId), valid);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export function publishFromChild(
|
|
655
|
+
child: ChildBroker,
|
|
656
|
+
envelope: ShepherdMessageEnvelope
|
|
657
|
+
): PublishResult {
|
|
658
|
+
assertBrokerOpen(child);
|
|
659
|
+
const valid = validateEnvelope(envelope);
|
|
660
|
+
assertBrokerIdentity(child, valid);
|
|
661
|
+
if (valid.senderId !== child.agentId) {
|
|
662
|
+
throw new MessagingError(
|
|
663
|
+
'invalid_sender',
|
|
664
|
+
`Child envelopes must be sent by "${child.agentId}".`
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
return publishToQueue(child, queuePathForChildConnection(child, valid.targetId), valid);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
export function pollParentInbox(broker: ParentBroker, limit?: number): ShepherdMessageEnvelope[] {
|
|
671
|
+
return pollQueue(broker, broker.parentInboxPath, broker.parentId, limit);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
export function pollChildInbox(child: ChildBroker, limit?: number): ShepherdMessageEnvelope[] {
|
|
675
|
+
return pollQueue(child, child.capability.inboxPath, child.agentId, limit);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Explicitly acknowledge an envelope; polling already performs this operation. */
|
|
679
|
+
export function acknowledge(
|
|
680
|
+
broker: ParentBroker | ChildBroker,
|
|
681
|
+
envelope: ShepherdMessageEnvelope
|
|
682
|
+
): void {
|
|
683
|
+
assertBrokerOpen(broker);
|
|
684
|
+
validateEnvelope(envelope);
|
|
685
|
+
assertBrokerIdentity(broker, envelope);
|
|
686
|
+
acknowledgeEnvelope(broker, envelope);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Remove a session mailbox only after the caller confirms all child panes are
|
|
691
|
+
* gone. The callback is intentionally supplied by the Herdr integration so
|
|
692
|
+
* this transport layer never guesses whether a child process still exists.
|
|
693
|
+
*/
|
|
694
|
+
export function closeBrokerWhenChildrenGone(
|
|
695
|
+
broker: ParentBroker,
|
|
696
|
+
childrenGone: () => boolean = () => broker.children.size === 0
|
|
697
|
+
): boolean {
|
|
698
|
+
if (broker.closed) return true;
|
|
699
|
+
if (!childrenGone()) return false;
|
|
700
|
+
broker.closed = true;
|
|
701
|
+
fs.rmSync(broker.rootDir, { recursive: true, force: true });
|
|
702
|
+
return true;
|
|
703
|
+
}
|