macro-agent 0.1.12 → 0.2.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/dist/acp/macro-agent.d.ts.map +1 -1
- package/dist/acp/macro-agent.js +18 -40
- package/dist/acp/macro-agent.js.map +1 -1
- package/dist/agent/agent-manager-v2.d.ts.map +1 -1
- package/dist/agent/agent-manager-v2.js +241 -8
- package/dist/agent/agent-manager-v2.js.map +1 -1
- package/dist/agent/types.d.ts +47 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/boot-v2.d.ts +33 -0
- package/dist/boot-v2.d.ts.map +1 -1
- package/dist/boot-v2.js +144 -11
- package/dist/boot-v2.js.map +1 -1
- package/dist/cli/acp.js +0 -0
- package/dist/cli/inbox-mcp-proxy.d.ts +36 -0
- package/dist/cli/inbox-mcp-proxy.d.ts.map +1 -0
- package/dist/cli/inbox-mcp-proxy.js +51 -0
- package/dist/cli/inbox-mcp-proxy.js.map +1 -0
- package/dist/cli/index.js +0 -0
- package/dist/cli/mcp.js +0 -0
- package/dist/dispatch/loadout-translation.d.ts +100 -0
- package/dist/dispatch/loadout-translation.d.ts.map +1 -0
- package/dist/dispatch/loadout-translation.js +90 -0
- package/dist/dispatch/loadout-translation.js.map +1 -0
- package/dist/dispatch/mail-inbound-consumer.d.ts +136 -0
- package/dist/dispatch/mail-inbound-consumer.d.ts.map +1 -0
- package/dist/dispatch/mail-inbound-consumer.js +360 -0
- package/dist/dispatch/mail-inbound-consumer.js.map +1 -0
- package/dist/dispatch/mail-inbound-reuse-consumer.d.ts +75 -0
- package/dist/dispatch/mail-inbound-reuse-consumer.d.ts.map +1 -0
- package/dist/dispatch/mail-inbound-reuse-consumer.js +325 -0
- package/dist/dispatch/mail-inbound-reuse-consumer.js.map +1 -0
- package/dist/dispatch/permission-evaluator.d.ts +68 -0
- package/dist/dispatch/permission-evaluator.d.ts.map +1 -0
- package/dist/dispatch/permission-evaluator.js +159 -0
- package/dist/dispatch/permission-evaluator.js.map +1 -0
- package/dist/dispatch/permission-overlay.d.ts +64 -0
- package/dist/dispatch/permission-overlay.d.ts.map +1 -0
- package/dist/dispatch/permission-overlay.js +72 -0
- package/dist/dispatch/permission-overlay.js.map +1 -0
- package/dist/dispatch/permissions-handler.d.ts +71 -0
- package/dist/dispatch/permissions-handler.d.ts.map +1 -0
- package/dist/dispatch/permissions-handler.js +83 -0
- package/dist/dispatch/permissions-handler.js.map +1 -0
- package/dist/dispatch/spawn-agent-handler.d.ts +84 -0
- package/dist/dispatch/spawn-agent-handler.d.ts.map +1 -0
- package/dist/dispatch/spawn-agent-handler.js +85 -0
- package/dist/dispatch/spawn-agent-handler.js.map +1 -0
- package/dist/lifecycle/handlers-v2.d.ts +7 -0
- package/dist/lifecycle/handlers-v2.d.ts.map +1 -1
- package/dist/lifecycle/handlers-v2.js +27 -0
- package/dist/lifecycle/handlers-v2.js.map +1 -1
- package/dist/map/lifecycle-bridge.d.ts +18 -0
- package/dist/map/lifecycle-bridge.d.ts.map +1 -1
- package/dist/map/lifecycle-bridge.js +23 -1
- package/dist/map/lifecycle-bridge.js.map +1 -1
- package/dist/map/mail-bridge.d.ts +55 -0
- package/dist/map/mail-bridge.d.ts.map +1 -0
- package/dist/map/mail-bridge.js +115 -0
- package/dist/map/mail-bridge.js.map +1 -0
- package/dist/map/repo-workspace.d.ts +46 -0
- package/dist/map/repo-workspace.d.ts.map +1 -0
- package/dist/map/repo-workspace.js +39 -0
- package/dist/map/repo-workspace.js.map +1 -0
- package/dist/map/server.d.ts.map +1 -1
- package/dist/map/server.js +1 -0
- package/dist/map/server.js.map +1 -1
- package/dist/map/sidecar.d.ts.map +1 -1
- package/dist/map/sidecar.js +308 -1
- package/dist/map/sidecar.js.map +1 -1
- package/dist/map/types.d.ts +29 -0
- package/dist/map/types.d.ts.map +1 -1
- package/dist/mcp/tools/done-v2.d.ts.map +1 -1
- package/dist/mcp/tools/done-v2.js +1 -0
- package/dist/mcp/tools/done-v2.js.map +1 -1
- package/dist/teams/team-loader.d.ts.map +1 -1
- package/dist/teams/team-loader.js.map +1 -1
- package/dist/teams/team-runtime-v2.d.ts.map +1 -1
- package/dist/teams/team-runtime-v2.js +2 -0
- package/dist/teams/team-runtime-v2.js.map +1 -1
- package/package.json +7 -5
- package/src/acp/macro-agent.ts +20 -42
- package/src/agent/__tests__/agent-manager-v2.permission-interception.test.ts +296 -0
- package/src/agent/__tests__/agent-manager-v2.permissions.test.ts +233 -0
- package/src/agent/agent-manager-v2.ts +269 -8
- package/src/agent/types.ts +51 -0
- package/src/boot-v2.ts +192 -12
- package/src/cli/inbox-mcp-proxy.ts +56 -0
- package/src/dispatch/CLAUDE.md +129 -0
- package/src/dispatch/__tests__/loadout-translation.test.ts +141 -0
- package/src/dispatch/__tests__/mail-inbound-consumer.integration.test.ts +519 -0
- package/src/dispatch/__tests__/mail-inbound-consumer.test.ts +800 -0
- package/src/dispatch/__tests__/mail-inbound-reuse-consumer.test.ts +575 -0
- package/src/dispatch/__tests__/permission-evaluator.test.ts +196 -0
- package/src/dispatch/__tests__/permission-overlay.test.ts +56 -0
- package/src/dispatch/__tests__/permissions-handler.test.ts +168 -0
- package/src/dispatch/__tests__/spawn-agent-handler.test.ts +282 -0
- package/src/dispatch/loadout-translation.ts +138 -0
- package/src/dispatch/mail-inbound-consumer.ts +560 -0
- package/src/dispatch/mail-inbound-reuse-consumer.ts +479 -0
- package/src/dispatch/permission-evaluator.ts +191 -0
- package/src/dispatch/permission-overlay.ts +89 -0
- package/src/dispatch/permissions-handler.ts +112 -0
- package/src/dispatch/spawn-agent-handler.ts +160 -0
- package/src/lifecycle/handlers-v2.ts +34 -0
- package/src/map/__tests__/lifecycle-bridge.test.ts +64 -0
- package/src/map/__tests__/mail-bridge.test.ts +196 -0
- package/src/map/lifecycle-bridge.ts +48 -2
- package/src/map/mail-bridge.ts +203 -0
- package/src/map/repo-workspace.ts +82 -0
- package/src/map/server.ts +1 -0
- package/src/map/sidecar.ts +431 -1
- package/src/map/types.ts +34 -0
- package/src/mcp/tools/done-v2.ts +1 -0
- package/src/teams/team-loader.ts +3 -1
- package/src/teams/team-runtime-v2.ts +2 -0
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mail-Inbound Consumer
|
|
3
|
+
*
|
|
4
|
+
* Receives hub-driven `x-dispatch/work` envelopes from the local agent-inbox
|
|
5
|
+
* and spawns a worker agent to handle them — without requiring the optional
|
|
6
|
+
* outbound swarm-dispatch orchestrator (`config.dispatch.enabled`).
|
|
7
|
+
*
|
|
8
|
+
* This makes mail-inbound dispatch a **default capability** of macro-agent: as
|
|
9
|
+
* long as the MAP sidecar is connected and the inbox is running, any hub that
|
|
10
|
+
* delivers work via `mail/turn.received` will be served.
|
|
11
|
+
*
|
|
12
|
+
* ## Data flow
|
|
13
|
+
*
|
|
14
|
+
* hub sends `mail/turn.received`
|
|
15
|
+
* → mail-bridge translates {type,body} → {schema,data} + _conversationId
|
|
16
|
+
* → inboxAdapter delivers to local inbox (recipient = dispatcherAgentId)
|
|
17
|
+
* → inbox.events fires "inbox.message"
|
|
18
|
+
* → consumer classifies: schema === 'x-dispatch/work'?
|
|
19
|
+
* yes → spawn worker via agentManager.spawn()
|
|
20
|
+
* → record agentId → conversationId in side map
|
|
21
|
+
* → worker calls done(summary="…SENTINEL…")
|
|
22
|
+
* → handlers-v2 stores _lastSummary in agentStore metadata (parentId null branch)
|
|
23
|
+
* → agentManager.onLifecycleEvent fires "stopped"
|
|
24
|
+
* → consumer reads _lastSummary + conversationId
|
|
25
|
+
* → mapSidecar.postMailTurn(conversationId, agentId, summary) [fire-and-forget]
|
|
26
|
+
*
|
|
27
|
+
* @module dispatch/mail-inbound-consumer
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import type { AgentManager } from "../agent/agent-manager.js";
|
|
31
|
+
import type { AgentStore } from "../agent/agent-store.js";
|
|
32
|
+
import { loadoutToSpawnOptions, type WireLoadout } from "./loadout-translation.js";
|
|
33
|
+
|
|
34
|
+
// ─────────────────────────────────────────────────────────────────
|
|
35
|
+
// Dependency interfaces (narrow — keeps the module testable without
|
|
36
|
+
// dragging in the full InboxAdapter / MAPSidecar concrete types)
|
|
37
|
+
// ─────────────────────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
export interface InboxEvents {
|
|
40
|
+
on(event: "inbox.message", listener: (event: InboxMessageEvent) => void): void;
|
|
41
|
+
off?(event: "inbox.message", listener: (event: InboxMessageEvent) => void): void;
|
|
42
|
+
removeListener?(event: "inbox.message", listener: (event: InboxMessageEvent) => void): void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface InboxMessageEvent {
|
|
46
|
+
/** The inbox recipient agent ID. */
|
|
47
|
+
agentId: string;
|
|
48
|
+
message: {
|
|
49
|
+
id?: string;
|
|
50
|
+
content?: unknown;
|
|
51
|
+
sender_id?: string;
|
|
52
|
+
thread_tag?: string;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface MailInboundSidecar {
|
|
57
|
+
postMailTurn?(
|
|
58
|
+
conversationId: string,
|
|
59
|
+
participantId: string,
|
|
60
|
+
content: string,
|
|
61
|
+
): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Repo metadata surfaced by the hub's enrichWithRepo → mail port injection. */
|
|
65
|
+
export interface DispatchRepoMetadata {
|
|
66
|
+
repo_id?: string;
|
|
67
|
+
canonical_url?: string;
|
|
68
|
+
branch?: string;
|
|
69
|
+
commit_sha?: string;
|
|
70
|
+
clone_policy?: string;
|
|
71
|
+
clone_path?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Narrow interface for the sidecar's RepoManager — keeps the consumer
|
|
76
|
+
* testable without importing the full agent-workspace concrete type.
|
|
77
|
+
*/
|
|
78
|
+
export interface RepoManagerLike {
|
|
79
|
+
list(): Array<{ identity: { canonicalUrl: string }; localPath: string }>;
|
|
80
|
+
attach(config: {
|
|
81
|
+
remoteUrl: string;
|
|
82
|
+
localPath: string;
|
|
83
|
+
currentBranch?: string;
|
|
84
|
+
}): Promise<{ localPath: string }>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Narrow interface for the sidecar's RepoClient transport — used to
|
|
89
|
+
* declare newly-attached repos to the hub after clone.
|
|
90
|
+
*/
|
|
91
|
+
export interface RepoClientTransportLike {
|
|
92
|
+
notify(method: string, params: unknown): Promise<void>;
|
|
93
|
+
request(method: string, params: unknown): Promise<unknown>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface MailInboundConsumerOptions {
|
|
97
|
+
/**
|
|
98
|
+
* The inbox agent ID that mail-bridge delivers envelopes to.
|
|
99
|
+
* Typically `dispatcher:<claimantId>` when the outbound orchestrator
|
|
100
|
+
* is also running, or a dedicated ID when it is not.
|
|
101
|
+
*/
|
|
102
|
+
dispatcherAgentId: string;
|
|
103
|
+
|
|
104
|
+
/** Raw inbox event emitter (from inboxAdapter.getInbox().events). */
|
|
105
|
+
inboxEvents: InboxEvents;
|
|
106
|
+
|
|
107
|
+
/** Agent lifecycle manager — used to spawn workers. */
|
|
108
|
+
agentManager: AgentManager;
|
|
109
|
+
|
|
110
|
+
/** Agent store — used to read _lastSummary after the agent stops. */
|
|
111
|
+
agentStore: AgentStore;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Optional sidecar reference. Populated after step 13 in boot-v2 via
|
|
115
|
+
* the shared systemRef — the consumer accesses it lazily at reply time
|
|
116
|
+
* so it works even though the sidecar is created after the consumer.
|
|
117
|
+
*/
|
|
118
|
+
getSidecar: () => MailInboundSidecar | null | undefined;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Optional repo manager for pre-spawn mount. When provided, the consumer
|
|
122
|
+
* can clone/attach repos before spawning workers and set the worker's cwd
|
|
123
|
+
* to the repo path. Populated lazily from the sidecar's workspace manager.
|
|
124
|
+
*/
|
|
125
|
+
getRepoManager?: () => RepoManagerLike | null | undefined;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Optional repo client transport for declaring newly-cloned repos to the
|
|
129
|
+
* hub after a pre-spawn clone. Uses the sidecar's MAP connection transport.
|
|
130
|
+
*/
|
|
131
|
+
getRepoTransport?: () => RepoClientTransportLike | null | undefined;
|
|
132
|
+
|
|
133
|
+
/** Optional logger (default: console.log). */
|
|
134
|
+
log?: (msg: string) => void;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface MailInboundConsumerStats {
|
|
138
|
+
/** Count of envelopes dropped because they lacked a taskId. */
|
|
139
|
+
droppedMalformed: number;
|
|
140
|
+
/** Number of distinct taskIds currently tracked for dedup. */
|
|
141
|
+
seenTaskIds: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface MailInboundConsumer {
|
|
145
|
+
stop(): void;
|
|
146
|
+
/** Snapshot of consumer-level counters for observability. */
|
|
147
|
+
stats(): MailInboundConsumerStats;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ─────────────────────────────────────────────────────────────────
|
|
151
|
+
// Implementation
|
|
152
|
+
// ─────────────────────────────────────────────────────────────────
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Wire the mail-inbound consumer.
|
|
156
|
+
*
|
|
157
|
+
* Returns a `stop()` handle that detaches all listeners.
|
|
158
|
+
* Safe to call multiple times (idempotent cleanup).
|
|
159
|
+
*/
|
|
160
|
+
export function createMailInboundConsumer(
|
|
161
|
+
opts: MailInboundConsumerOptions,
|
|
162
|
+
): MailInboundConsumer {
|
|
163
|
+
const {
|
|
164
|
+
dispatcherAgentId,
|
|
165
|
+
inboxEvents,
|
|
166
|
+
agentManager,
|
|
167
|
+
agentStore,
|
|
168
|
+
getSidecar,
|
|
169
|
+
getRepoManager,
|
|
170
|
+
getRepoTransport,
|
|
171
|
+
log = (msg: string) => console.log(msg),
|
|
172
|
+
} = opts;
|
|
173
|
+
|
|
174
|
+
// ── Side-channel maps ────────────────────────────────────────
|
|
175
|
+
// agentId → conversationId: populated when a worker is spawned for a
|
|
176
|
+
// mail-inbound envelope; read when the agent's stopped event fires.
|
|
177
|
+
const agentConversationMap = new Map<string, string>();
|
|
178
|
+
|
|
179
|
+
// taskId → expiresAt: idempotency guard keyed on the dispatch envelope's
|
|
180
|
+
// task identifier. The local inbox can re-fire `inbox.message` for the
|
|
181
|
+
// same logical delivery — without this guard, a single bridged turn would
|
|
182
|
+
// trigger N concurrent spawn() calls, each producing a long-lived ACP
|
|
183
|
+
// subprocess.
|
|
184
|
+
//
|
|
185
|
+
// Bounded by TTL so the map cannot grow unbounded over a long-running
|
|
186
|
+
// deployment. SEEN_TASK_TTL_MS is generous (1 hour) — re-deliveries within
|
|
187
|
+
// that window are dropped, beyond it the dedup expires and a stale retry
|
|
188
|
+
// could legitimately re-spawn (preferable to permanent memory growth).
|
|
189
|
+
const SEEN_TASK_TTL_MS = 60 * 60 * 1000;
|
|
190
|
+
const seenTaskIds = new Map<string, number>();
|
|
191
|
+
function pruneSeenTaskIds(): void {
|
|
192
|
+
const now = Date.now();
|
|
193
|
+
for (const [id, expiresAt] of seenTaskIds) {
|
|
194
|
+
if (expiresAt <= now) seenTaskIds.delete(id);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Counter for envelopes dropped because they are malformed (no taskId).
|
|
199
|
+
// Surfaced via the consumer handle's stats() method so operators can
|
|
200
|
+
// distinguish "no work" from "work is broken".
|
|
201
|
+
let droppedMalformedCount = 0;
|
|
202
|
+
|
|
203
|
+
log(
|
|
204
|
+
`[mail-inbound] Consumer ready — listening for x-dispatch/work envelopes ` +
|
|
205
|
+
`(recipient=${dispatcherAgentId})`,
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
// ── Pre-spawn repo mount ─────────────────────────────────────
|
|
209
|
+
// Resolves the worker's cwd from the dispatch envelope's repo metadata.
|
|
210
|
+
// When clone_policy is 'allowed' and the repo isn't already attached,
|
|
211
|
+
// clones to clone_path (or a default under cwd) then attaches+declares.
|
|
212
|
+
// Best-effort: failures log a warning and return undefined (worker
|
|
213
|
+
// spawns without a repo-specific cwd).
|
|
214
|
+
async function resolveRepoCwd(
|
|
215
|
+
repoMeta: DispatchRepoMetadata,
|
|
216
|
+
taskId: string,
|
|
217
|
+
): Promise<string | undefined> {
|
|
218
|
+
const manager = getRepoManager?.();
|
|
219
|
+
if (!manager) return undefined;
|
|
220
|
+
|
|
221
|
+
const canonicalUrl = repoMeta.canonical_url;
|
|
222
|
+
if (!canonicalUrl) return undefined;
|
|
223
|
+
|
|
224
|
+
// Check if the repo is already attached (by canonical URL match).
|
|
225
|
+
const existing = manager.list().find(
|
|
226
|
+
(h) => h.identity.canonicalUrl === canonicalUrl,
|
|
227
|
+
);
|
|
228
|
+
if (existing) {
|
|
229
|
+
log(`[mail-inbound] Repo already attached at ${existing.localPath} for taskId=${taskId}`);
|
|
230
|
+
return existing.localPath;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Not attached — clone only if explicitly allowed.
|
|
234
|
+
if (repoMeta.clone_policy !== 'allowed') {
|
|
235
|
+
log(
|
|
236
|
+
`[mail-inbound] Repo ${canonicalUrl} not attached and clone_policy=${repoMeta.clone_policy ?? 'none'} — ` +
|
|
237
|
+
`skipping mount for taskId=${taskId}`,
|
|
238
|
+
);
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const clonePath = repoMeta.clone_path ?? `/tmp/openhive-repos/${repoMeta.repo_id}`;
|
|
243
|
+
try {
|
|
244
|
+
const { execSync } = await import("node:child_process");
|
|
245
|
+
|
|
246
|
+
// Clone if the directory doesn't exist yet.
|
|
247
|
+
const fs = await import("node:fs");
|
|
248
|
+
if (!fs.existsSync(clonePath)) {
|
|
249
|
+
log(`[mail-inbound] Cloning ${canonicalUrl} → ${clonePath} for taskId=${taskId}`);
|
|
250
|
+
execSync(`git clone --depth 1 ${canonicalUrl} ${clonePath}`, {
|
|
251
|
+
stdio: "pipe",
|
|
252
|
+
timeout: 120_000,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Checkout target branch if specified.
|
|
257
|
+
if (repoMeta.branch) {
|
|
258
|
+
try {
|
|
259
|
+
execSync(`git -C ${clonePath} fetch origin ${repoMeta.branch} --depth 1`, {
|
|
260
|
+
stdio: "pipe",
|
|
261
|
+
timeout: 60_000,
|
|
262
|
+
});
|
|
263
|
+
execSync(`git -C ${clonePath} checkout ${repoMeta.branch}`, {
|
|
264
|
+
stdio: "pipe",
|
|
265
|
+
timeout: 30_000,
|
|
266
|
+
});
|
|
267
|
+
} catch {
|
|
268
|
+
log(`[mail-inbound] Branch checkout failed for ${repoMeta.branch} — continuing on default branch`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Attach to the repo manager so future dispatches find it.
|
|
273
|
+
const handle = await manager.attach({
|
|
274
|
+
remoteUrl: canonicalUrl,
|
|
275
|
+
localPath: clonePath,
|
|
276
|
+
currentBranch: repoMeta.branch,
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
// Declare the new workspace to the hub (best-effort).
|
|
280
|
+
const transport = getRepoTransport?.();
|
|
281
|
+
if (transport) {
|
|
282
|
+
try {
|
|
283
|
+
const bindings = manager.list().map((h) => ({
|
|
284
|
+
canonical_url: h.identity.canonicalUrl,
|
|
285
|
+
local_path: h.localPath,
|
|
286
|
+
}));
|
|
287
|
+
await transport.notify("x-workspace/repo.declare", { bindings });
|
|
288
|
+
} catch {
|
|
289
|
+
// Non-fatal — the hub may not support workspace declarations.
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
log(`[mail-inbound] Mounted repo at ${handle.localPath} for taskId=${taskId}`);
|
|
294
|
+
return handle.localPath;
|
|
295
|
+
} catch (err) {
|
|
296
|
+
log(
|
|
297
|
+
`[mail-inbound] Pre-spawn repo mount failed for taskId=${taskId}: ` +
|
|
298
|
+
`${(err as Error).message ?? String(err)}`,
|
|
299
|
+
);
|
|
300
|
+
return undefined;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ── Inbox message listener ───────────────────────────────────
|
|
305
|
+
const onMessage = (event: InboxMessageEvent): void => {
|
|
306
|
+
// Only handle messages delivered to our dispatcher recipient.
|
|
307
|
+
if (event.agentId !== dispatcherAgentId) return;
|
|
308
|
+
|
|
309
|
+
const content = event.message?.content as {
|
|
310
|
+
schema?: string;
|
|
311
|
+
data?: {
|
|
312
|
+
taskId?: string;
|
|
313
|
+
prompt?: string;
|
|
314
|
+
content?: string;
|
|
315
|
+
title?: string;
|
|
316
|
+
role?: string;
|
|
317
|
+
tags?: string[];
|
|
318
|
+
loadout?: WireLoadout;
|
|
319
|
+
metadata?: Record<string, unknown>;
|
|
320
|
+
};
|
|
321
|
+
_conversationId?: string;
|
|
322
|
+
} | undefined;
|
|
323
|
+
|
|
324
|
+
if (content?.schema !== "x-dispatch/work") return;
|
|
325
|
+
|
|
326
|
+
const data = content.data;
|
|
327
|
+
if (!data?.taskId) {
|
|
328
|
+
droppedMalformedCount++;
|
|
329
|
+
log(
|
|
330
|
+
`[mail-inbound] Dropping malformed envelope (no taskId, total=${droppedMalformedCount}) — ` +
|
|
331
|
+
`keys=${Object.keys(data ?? {}).join(',')} from=${event.message?.sender_id ?? '?'}`,
|
|
332
|
+
);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const taskId = data.taskId;
|
|
337
|
+
pruneSeenTaskIds();
|
|
338
|
+
const seenExpiresAt = seenTaskIds.get(taskId);
|
|
339
|
+
if (seenExpiresAt !== undefined && seenExpiresAt > Date.now()) {
|
|
340
|
+
// Already spawned a worker for this dispatch within the dedup window
|
|
341
|
+
// — silently ignore the re-delivery. The hub treats dispatch as
|
|
342
|
+
// exactly-once on the worker side, so dropping is correct.
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
seenTaskIds.set(taskId, Date.now() + SEEN_TASK_TTL_MS);
|
|
346
|
+
|
|
347
|
+
const conversationId = content._conversationId;
|
|
348
|
+
const prompt = data.prompt ?? data.content ?? "";
|
|
349
|
+
|
|
350
|
+
// Validate the envelope's role against the local role registry. Unknown
|
|
351
|
+
// role names (e.g. team-role-ref roles like 'executor' surfaced by hubs
|
|
352
|
+
// that don't share macro-agent's role taxonomy) silently fall back to
|
|
353
|
+
// GenericRole inside `resolveRole`, which has `lifecycle.type='persistent'`
|
|
354
|
+
// and no system-prompt instruction to call `done()`. That breaks the
|
|
355
|
+
// mail-reply path because the worker stops without writing
|
|
356
|
+
// `_lastSummary`, so we end up logging "Worker stopped but _lastSummary
|
|
357
|
+
// is empty — no reply turn posted" and the hub never sees the answer.
|
|
358
|
+
//
|
|
359
|
+
// Use 'worker' as the fallback (ephemeral lifecycle + LIFECYCLE.DONE
|
|
360
|
+
// capability + system prompt that mandates `done()`) so unknown roles
|
|
361
|
+
// get a sensible default that completes the reply round-trip.
|
|
362
|
+
const requestedRole = data.role;
|
|
363
|
+
const roleRegistry = agentManager.getRoleRegistry?.();
|
|
364
|
+
const knownRole =
|
|
365
|
+
requestedRole && roleRegistry?.getRole(requestedRole) !== undefined;
|
|
366
|
+
const role = knownRole ? requestedRole! : "worker";
|
|
367
|
+
if (requestedRole && !knownRole) {
|
|
368
|
+
log(
|
|
369
|
+
`[mail-inbound] Unknown role '${requestedRole}' for taskId=${taskId} — falling back to 'worker'`,
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// Loadout-derived structured fields ride in the envelope. We prefer the
|
|
374
|
+
// canonical top-level `data.loadout` slot (Step 3 of the ACP+lifecycle
|
|
375
|
+
// plan) but fall back to the legacy `data.metadata.permissions` shape
|
|
376
|
+
// for one deprecation cycle so older hubs that haven't rolled the new
|
|
377
|
+
// wire shape continue to work.
|
|
378
|
+
//
|
|
379
|
+
// `loadoutToSpawnOptions` is shared with the new `dispatch/spawn-agent`
|
|
380
|
+
// MAP handler so both wire paths produce identical spawn options.
|
|
381
|
+
//
|
|
382
|
+
// `fullAutonomous: true` because mail-inbound workers have no human in
|
|
383
|
+
// the loop to answer `ask` rules — collapse them to `allow` (vs. the
|
|
384
|
+
// safer `deny` default for spawns where a human might still be reached).
|
|
385
|
+
let wireLoadout: WireLoadout | undefined = data.loadout;
|
|
386
|
+
if (!wireLoadout) {
|
|
387
|
+
const legacyPermissions = data.metadata?.permissions as
|
|
388
|
+
| { allow?: string[]; deny?: string[]; ask?: string[] }
|
|
389
|
+
| undefined;
|
|
390
|
+
const legacyMcpProviders = data.metadata?.mcpProviders as
|
|
391
|
+
| WireLoadout["mcpProviders"]
|
|
392
|
+
| undefined;
|
|
393
|
+
if (legacyPermissions || legacyMcpProviders) {
|
|
394
|
+
wireLoadout = {
|
|
395
|
+
...(legacyPermissions ? { permissions: legacyPermissions } : {}),
|
|
396
|
+
...(legacyMcpProviders ? { mcpProviders: legacyMcpProviders } : {}),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const spawnLoadoutOpts = loadoutToSpawnOptions(wireLoadout, {
|
|
401
|
+
fullAutonomous: true,
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
// Extract repo metadata from the envelope for pre-spawn mount.
|
|
405
|
+
const repoMeta: DispatchRepoMetadata = {
|
|
406
|
+
repo_id: data.metadata?.repo_id as string | undefined,
|
|
407
|
+
canonical_url: data.metadata?.canonical_url as string | undefined,
|
|
408
|
+
branch: data.metadata?.branch as string | undefined,
|
|
409
|
+
commit_sha: data.metadata?.commit_sha as string | undefined,
|
|
410
|
+
clone_policy: data.metadata?.clone_policy as string | undefined,
|
|
411
|
+
clone_path: data.metadata?.clone_path as string | undefined,
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
log(
|
|
415
|
+
`[mail-inbound] Received x-dispatch/work taskId=${taskId} ` +
|
|
416
|
+
`conv=${conversationId ?? "(none)"} role=${role}` +
|
|
417
|
+
(repoMeta.repo_id ? ` repo=${repoMeta.repo_id}` : "") +
|
|
418
|
+
(spawnLoadoutOpts.permissions
|
|
419
|
+
? ` permissions=${JSON.stringify(spawnLoadoutOpts.permissions)}`
|
|
420
|
+
: ""),
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
// Spawn is async — fire and forget. Errors are logged, not thrown.
|
|
424
|
+
// Pre-spawn mount resolves the worker's cwd from the repo metadata
|
|
425
|
+
// before spawning. Best-effort: mount failures proceed without a
|
|
426
|
+
// repo-specific cwd.
|
|
427
|
+
(async () => {
|
|
428
|
+
let repoCwd: string | undefined;
|
|
429
|
+
if (repoMeta.repo_id) {
|
|
430
|
+
repoCwd = await resolveRepoCwd(repoMeta, taskId);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const spawned = await agentManager.spawn({
|
|
434
|
+
task: prompt,
|
|
435
|
+
task_id: taskId,
|
|
436
|
+
role,
|
|
437
|
+
parent: null,
|
|
438
|
+
// Mail-inbound dispatch workers run sandboxed — strip the host's
|
|
439
|
+
// user-level Claude setting sources so installed plugin MCP servers
|
|
440
|
+
// (claude-code-swarm, oh-my-claudecode, …) don't auto-load and hang
|
|
441
|
+
// session/new on environments where the host services aren't reachable.
|
|
442
|
+
isolatedSettings: true,
|
|
443
|
+
...(repoCwd ? { cwd: repoCwd } : {}),
|
|
444
|
+
...spawnLoadoutOpts,
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
log(
|
|
448
|
+
`[mail-inbound] Spawned worker agentId=${spawned.id} for taskId=${taskId}` +
|
|
449
|
+
(repoCwd ? ` cwd=${repoCwd}` : ""),
|
|
450
|
+
);
|
|
451
|
+
if (conversationId) {
|
|
452
|
+
agentConversationMap.set(spawned.id, conversationId);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// Spawn only creates an idle ACP session — the task lives in the
|
|
456
|
+
// system prompt as instructions. To get the model to actually do
|
|
457
|
+
// the work, send the prompt as a user message via promptUntilDone.
|
|
458
|
+
// This drives the worker to completion (done() called) so the
|
|
459
|
+
// lifecycle stopped listener below fires and posts the reply
|
|
460
|
+
// back to the hub. Fire-and-forget; errors are logged.
|
|
461
|
+
try {
|
|
462
|
+
await agentManager.promptUntilDone(spawned.id, prompt, {
|
|
463
|
+
maxFollowUps: 0,
|
|
464
|
+
});
|
|
465
|
+
} catch (err) {
|
|
466
|
+
log(
|
|
467
|
+
`[mail-inbound] promptUntilDone failed for agentId=${spawned.id}: ` +
|
|
468
|
+
`${(err as Error).message ?? String(err)}`,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
})().catch((err: unknown) => {
|
|
472
|
+
log(
|
|
473
|
+
`[mail-inbound] Spawn failed for taskId=${taskId}: ${
|
|
474
|
+
(err as Error).message ?? String(err)
|
|
475
|
+
}`,
|
|
476
|
+
);
|
|
477
|
+
});
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
inboxEvents.on("inbox.message", onMessage);
|
|
481
|
+
|
|
482
|
+
// ── Lifecycle stopped listener ───────────────────────────────
|
|
483
|
+
const unsubscribeLifecycle = agentManager.onLifecycleEvent((event) => {
|
|
484
|
+
if (event.type !== "stopped") return;
|
|
485
|
+
|
|
486
|
+
const agentId = event.agent.id;
|
|
487
|
+
const conversationId = agentConversationMap.get(agentId);
|
|
488
|
+
if (!conversationId) return; // not a mail-inbound worker we spawned
|
|
489
|
+
|
|
490
|
+
agentConversationMap.delete(agentId);
|
|
491
|
+
|
|
492
|
+
// Read the summary stored by handlers-v2 for parentless workers.
|
|
493
|
+
const record = agentStore.getAgent(agentId);
|
|
494
|
+
const summary = record?.metadata?._lastSummary as string | undefined;
|
|
495
|
+
if (!summary) {
|
|
496
|
+
log(
|
|
497
|
+
`[mail-inbound] Worker agentId=${agentId} stopped but _lastSummary is empty — ` +
|
|
498
|
+
`no reply turn posted`,
|
|
499
|
+
);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
log(
|
|
504
|
+
`[mail-inbound] Worker agentId=${agentId} stopped — posting reply to ` +
|
|
505
|
+
`conv=${conversationId}`,
|
|
506
|
+
);
|
|
507
|
+
|
|
508
|
+
const sidecar = getSidecar();
|
|
509
|
+
if (!sidecar?.postMailTurn) {
|
|
510
|
+
log(`[mail-inbound] No sidecar/postMailTurn — reply turn dropped`);
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
sidecar.postMailTurn(conversationId, agentId, summary)
|
|
515
|
+
.then(() => {
|
|
516
|
+
// Clear the stored summary so it can't replay if the same agentId
|
|
517
|
+
// is ever reused for another dispatch (the AgentManager generally
|
|
518
|
+
// mints fresh ids, but this is cheap insurance against a future
|
|
519
|
+
// change).
|
|
520
|
+
try {
|
|
521
|
+
const existingMeta = agentStore.getAgent(agentId)?.metadata ?? {};
|
|
522
|
+
const { _lastSummary: _drop, ...rest } = existingMeta as Record<string, unknown>;
|
|
523
|
+
void _drop;
|
|
524
|
+
agentStore.updateAgent(agentId, { metadata: rest });
|
|
525
|
+
} catch {
|
|
526
|
+
// best-effort — store may be closing during shutdown
|
|
527
|
+
}
|
|
528
|
+
})
|
|
529
|
+
.catch(() => {
|
|
530
|
+
// best-effort — hub may be temporarily unreachable
|
|
531
|
+
});
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
// ── Cleanup ──────────────────────────────────────────────────
|
|
535
|
+
let stopped = false;
|
|
536
|
+
return {
|
|
537
|
+
stop() {
|
|
538
|
+
if (stopped) return;
|
|
539
|
+
stopped = true;
|
|
540
|
+
try {
|
|
541
|
+
if (inboxEvents.off) {
|
|
542
|
+
inboxEvents.off("inbox.message", onMessage);
|
|
543
|
+
} else if (inboxEvents.removeListener) {
|
|
544
|
+
inboxEvents.removeListener("inbox.message", onMessage);
|
|
545
|
+
}
|
|
546
|
+
} catch {
|
|
547
|
+
// best effort
|
|
548
|
+
}
|
|
549
|
+
unsubscribeLifecycle();
|
|
550
|
+
log(`[mail-inbound] Consumer stopped`);
|
|
551
|
+
},
|
|
552
|
+
stats() {
|
|
553
|
+
pruneSeenTaskIds();
|
|
554
|
+
return {
|
|
555
|
+
droppedMalformed: droppedMalformedCount,
|
|
556
|
+
seenTaskIds: seenTaskIds.size,
|
|
557
|
+
};
|
|
558
|
+
},
|
|
559
|
+
};
|
|
560
|
+
}
|