@hve-squad/mcp 0.7.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/LICENSE +21 -0
- package/NOTICE +46 -0
- package/README.md +233 -0
- package/dist/src/auth/entra.js +164 -0
- package/dist/src/auth/jose-verifier.js +31 -0
- package/dist/src/auth/scopes.js +240 -0
- package/dist/src/catalog/catalog.js +80 -0
- package/dist/src/config/operator-config.js +281 -0
- package/dist/src/engine/advisory-pipeline.js +367 -0
- package/dist/src/engine/advisory-run-store.js +31 -0
- package/dist/src/engine/artifact-store.js +165 -0
- package/dist/src/engine/auto-memory.js +207 -0
- package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
- package/dist/src/engine/backends/azure-openai.js +69 -0
- package/dist/src/engine/backends/azure-table-run-state.js +319 -0
- package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
- package/dist/src/engine/backends/file-squad-memory.js +208 -0
- package/dist/src/engine/backends/graph-squad-memory.js +271 -0
- package/dist/src/engine/backends/managed-identity-credential.js +33 -0
- package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
- package/dist/src/engine/backlog-contract.js +200 -0
- package/dist/src/engine/business-tools.js +118 -0
- package/dist/src/engine/consumption.js +134 -0
- package/dist/src/engine/coordinator-engine.js +1 -0
- package/dist/src/engine/council.js +204 -0
- package/dist/src/engine/delegated.js +190 -0
- package/dist/src/engine/dispatch-loop.js +84 -0
- package/dist/src/engine/durable-run-state.js +251 -0
- package/dist/src/engine/embedded-prompt.js +35 -0
- package/dist/src/engine/embedded-roles.js +133 -0
- package/dist/src/engine/embedded.js +1023 -0
- package/dist/src/engine/federation.js +96 -0
- package/dist/src/engine/field-cipher.js +84 -0
- package/dist/src/engine/gates.js +241 -0
- package/dist/src/engine/markdown-table.js +43 -0
- package/dist/src/engine/model-backend.js +16 -0
- package/dist/src/engine/persona-loader.js +132 -0
- package/dist/src/engine/persona.js +287 -0
- package/dist/src/engine/profiles.js +237 -0
- package/dist/src/engine/render/pptx-render-service.js +60 -0
- package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
- package/dist/src/engine/render/render-backend.js +25 -0
- package/dist/src/engine/render-embedded.js +69 -0
- package/dist/src/engine/routing.js +275 -0
- package/dist/src/engine/run-params.js +70 -0
- package/dist/src/engine/run-state.js +132 -0
- package/dist/src/engine/run-worker.js +60 -0
- package/dist/src/engine/squad-history.js +136 -0
- package/dist/src/engine/squad-ledger.js +215 -0
- package/dist/src/engine/squad-memory-resources.js +218 -0
- package/dist/src/engine/squad-memory-state.js +57 -0
- package/dist/src/engine/squad-run-recorder.js +212 -0
- package/dist/src/engine/targeted-squad-memory.js +94 -0
- package/dist/src/engine/workspace.js +68 -0
- package/dist/src/observability/logger.js +75 -0
- package/dist/src/observability/redact.js +77 -0
- package/dist/src/paths.js +108 -0
- package/dist/src/router/router.js +88 -0
- package/dist/src/server-http.js +304 -0
- package/dist/src/server.js +237 -0
- package/dist/src/transports/http-core.js +1240 -0
- package/dist/src/transports/http.js +90 -0
- package/dist/src/transports/session-store.js +78 -0
- package/dist/src/transports/stdio.js +12 -0
- package/dist/src/worker-main.js +87 -0
- package/generated/copilot-studio-connector/README.md +44 -0
- package/generated/copilot-studio-connector/agent-instructions.md +90 -0
- package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
- package/generated/copilot-studio-connector/apiProperties.json +35 -0
- package/generated/copilot-studio-connector/connector.manifest.json +86 -0
- package/generated/mcp-tools.schema.json +462 -0
- package/package.json +61 -0
- package/tools.catalog.yml +397 -0
|
@@ -0,0 +1,1023 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EmbeddedCoordinator — Phase 1 server-side execution (thin slice).
|
|
3
|
+
*
|
|
4
|
+
* Runs a hero tool's squad stage server-side and returns a finished,
|
|
5
|
+
* squad-guided artifact. It reuses the SAME router/catalog and the SAME persona
|
|
6
|
+
* source of truth as the delegated path (no fork), and composes every council
|
|
7
|
+
* condition into one execution flow:
|
|
8
|
+
*
|
|
9
|
+
* * SEC-9 / COST-1 / COST-2 — admit under the per-tenant concurrency + cost
|
|
10
|
+
* ceiling BEFORE any work; refuse past either limit.
|
|
11
|
+
* * SEC-6 / SEC-7 / PROD-5 — a gated/destructive/confirm-tier tool HOLDS for
|
|
12
|
+
* out-of-band human approval and never auto-releases; no model call is made
|
|
13
|
+
* for a held run.
|
|
14
|
+
* * SEC-5 — caller `request`/`context` are composed as delimited DATA, never
|
|
15
|
+
* as authority (see `embedded-prompt.ts`). Routing, scope, and gate decisions
|
|
16
|
+
* are all made BEFORE the prompt is composed, so injection has nothing to flip.
|
|
17
|
+
* * SEC-4 — all file/memory work happens inside a server-allocated, per-tenant
|
|
18
|
+
* ephemeral workspace with GUARANTEED teardown (the `finally` below runs even
|
|
19
|
+
* on error/timeout).
|
|
20
|
+
* * SEC-3 — the caller's tenant identity is the single root; any future
|
|
21
|
+
* downstream call must authorize against it (the thin slice makes none).
|
|
22
|
+
* * ARCH-1 — run state flows through the `RunStateStore` seam so the durable
|
|
23
|
+
* resumable variant drops in later without changing this engine.
|
|
24
|
+
*
|
|
25
|
+
* SEC-7 is also structural: this module imports NO process/shell primitive
|
|
26
|
+
* (`child_process`, `node:child_process`, `exec`, `spawn`) and never will in the
|
|
27
|
+
* embedded path. The hero tool does inference plus contained file I/O only.
|
|
28
|
+
*/
|
|
29
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
30
|
+
import { charterForRole, resolvePersonaForRole } from "./embedded-roles.js";
|
|
31
|
+
import { composeEmbeddedPrompt } from "./embedded-prompt.js";
|
|
32
|
+
import { withMemoryContext } from "./auto-memory.js";
|
|
33
|
+
import { isAdvisoryOnly } from "./gates.js";
|
|
34
|
+
import { defaultProfileTables, resolveProfile } from "./profiles.js";
|
|
35
|
+
import { FEDERATION_ROLE, federationPersona } from "./federation.js";
|
|
36
|
+
import { coordinatorRequestFromRun, encodeRunParams } from "./run-params.js";
|
|
37
|
+
import { runPipeline } from "./dispatch-loop.js";
|
|
38
|
+
import { runAdvisoryPipeline } from "./advisory-pipeline.js";
|
|
39
|
+
import { StoreAdvisoryPersistence } from "./advisory-run-store.js";
|
|
40
|
+
import { EphemeralRunStateStore } from "./run-state.js";
|
|
41
|
+
import { GateKeeper, InMemoryApprovalChannel, } from "./gates.js";
|
|
42
|
+
function toMatchedRouting(tool) {
|
|
43
|
+
return {
|
|
44
|
+
routingIntent: tool.routingIntent,
|
|
45
|
+
role: tool.role,
|
|
46
|
+
tier: tool.tier,
|
|
47
|
+
parallelEligible: tool.parallelEligible,
|
|
48
|
+
council: tool.council,
|
|
49
|
+
catchAll: tool.catchAll,
|
|
50
|
+
gates: tool.gates,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** The spike catch-all pipeline: research then review, run server-side in order. */
|
|
54
|
+
const SPIKE_PIPELINE_ROLES = ["Squad Researcher", "Squad Reviewer"];
|
|
55
|
+
/** The federation meta tool id (catalog tool; gated + catch-all, like squad_run). */
|
|
56
|
+
const FEDERATION_TOOL_ID = "squad_federate";
|
|
57
|
+
/**
|
|
58
|
+
* Routing summary attached to a resolved FEDERATION run. Mirrors the catalog's
|
|
59
|
+
* `squad_federate` row so a `squad_status` poll reports the federation role rather
|
|
60
|
+
* than the plain Squad Coordinator (the durable record carries only the run).
|
|
61
|
+
*/
|
|
62
|
+
const FEDERATION_ROUTING = {
|
|
63
|
+
routingIntent: "federation meta layer",
|
|
64
|
+
role: FEDERATION_ROLE,
|
|
65
|
+
tier: "confirm",
|
|
66
|
+
parallelEligible: false,
|
|
67
|
+
council: [],
|
|
68
|
+
catchAll: true,
|
|
69
|
+
gates: true,
|
|
70
|
+
};
|
|
71
|
+
/** Default per-tenant cap on outstanding held runs (MEDIUM-2 resource-exhaustion guard). */
|
|
72
|
+
const DEFAULT_MAX_HELD_RUNS_PER_TENANT = 100;
|
|
73
|
+
/**
|
|
74
|
+
* Routing summary attached to an async pipeline result resolved by run id, when
|
|
75
|
+
* the original catalog tool is not in scope (the durable record carries only the
|
|
76
|
+
* run, not the tool). Mirrors the squad_run catch-all pipeline row.
|
|
77
|
+
*/
|
|
78
|
+
const EMPTY_ROUTING = {
|
|
79
|
+
routingIntent: "full classify-and-dispatch pipeline",
|
|
80
|
+
role: "Squad Coordinator",
|
|
81
|
+
tier: "confirm",
|
|
82
|
+
parallelEligible: false,
|
|
83
|
+
council: [],
|
|
84
|
+
catchAll: true,
|
|
85
|
+
gates: true,
|
|
86
|
+
};
|
|
87
|
+
/** Server-side embedded execution for the hero tool(s). Runs one model dispatch per call. */
|
|
88
|
+
export class EmbeddedCoordinator {
|
|
89
|
+
mode = "embedded";
|
|
90
|
+
backend;
|
|
91
|
+
workspaceManager;
|
|
92
|
+
quota;
|
|
93
|
+
gates;
|
|
94
|
+
runStateStore;
|
|
95
|
+
approvals;
|
|
96
|
+
maxHeldRunsPerTenant;
|
|
97
|
+
driveOnPoll;
|
|
98
|
+
runTtlMs;
|
|
99
|
+
leaseMs;
|
|
100
|
+
autoMemory;
|
|
101
|
+
runRecorder;
|
|
102
|
+
logger;
|
|
103
|
+
/** Outstanding held runs per tenant, started via startHttpRun (MEDIUM-2). */
|
|
104
|
+
heldCounts = new Map();
|
|
105
|
+
constructor(deps) {
|
|
106
|
+
this.backend = deps.backend;
|
|
107
|
+
this.workspaceManager = deps.workspaceManager;
|
|
108
|
+
this.quota = deps.quota;
|
|
109
|
+
this.gates = deps.gates ?? new GateKeeper();
|
|
110
|
+
this.runStateStore = deps.runStateStore ?? new EphemeralRunStateStore();
|
|
111
|
+
this.approvals = deps.approvals ?? new InMemoryApprovalChannel();
|
|
112
|
+
this.maxHeldRunsPerTenant = deps.maxHeldRunsPerTenant ?? DEFAULT_MAX_HELD_RUNS_PER_TENANT;
|
|
113
|
+
this.driveOnPoll = deps.driveOnPoll ?? true;
|
|
114
|
+
this.runTtlMs = deps.runTtlMs;
|
|
115
|
+
this.leaseMs = deps.leaseMs;
|
|
116
|
+
this.autoMemory = deps.autoMemory;
|
|
117
|
+
this.runRecorder = deps.runRecorder;
|
|
118
|
+
this.logger = deps.logger;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Auto-memory pre-read: resolve the project partition and merge prior `state` +
|
|
122
|
+
* `decisions` into the request's `context` as DATA. A no-op when auto-memory is
|
|
123
|
+
* not wired, so the default posture is byte-identical to before.
|
|
124
|
+
*/
|
|
125
|
+
async withMemory(tenantId, request) {
|
|
126
|
+
if (!this.autoMemory) {
|
|
127
|
+
return { request };
|
|
128
|
+
}
|
|
129
|
+
const project = this.autoMemory.resolveProject(request);
|
|
130
|
+
const memory = await this.autoMemory.loadContext(tenantId, project);
|
|
131
|
+
let carried = withMemoryContext(request, memory);
|
|
132
|
+
if (this.runRecorder) {
|
|
133
|
+
// Seeding the roster and reading the run index back are the artifact-shaped
|
|
134
|
+
// twin of the digest read above, so they share this one moment.
|
|
135
|
+
const opened = await this.runRecorder.open(tenantId, project, carried);
|
|
136
|
+
carried = withMemoryContext(carried, opened.historyBlock);
|
|
137
|
+
// The seeded roster wins over the caller's hint for the rest of the run.
|
|
138
|
+
carried = { ...carried, profile: opened.profile.name };
|
|
139
|
+
}
|
|
140
|
+
return { request: carried, project };
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Auto-memory post-write: persist a completed artifact to history and refresh the
|
|
144
|
+
* project's `state` digest. Never throws (the helper swallows store failures), so
|
|
145
|
+
* a memory outage can never fail an otherwise-successful run.
|
|
146
|
+
*/
|
|
147
|
+
async recordMemory(tenantId, project, entry) {
|
|
148
|
+
if (!this.autoMemory || !project) {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
await this.autoMemory.record(tenantId, project, entry);
|
|
152
|
+
await this.runRecorder?.closeRun(tenantId, project, entry.runId, []);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The ledger sink for one run, or `undefined` when the ledger is not wired.
|
|
156
|
+
*
|
|
157
|
+
* `project` is only defined when auto-memory resolved a partition, and there is
|
|
158
|
+
* no ledger destination without one — the project IS the partition the tree is
|
|
159
|
+
* written under.
|
|
160
|
+
*/
|
|
161
|
+
ledgerSink(tenantId, project, request, runId) {
|
|
162
|
+
if (!this.runRecorder || !project) {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
return this.runRecorder.sinkFor(tenantId, project, request, runId);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Whether this run's roster reaches only the tracking tree.
|
|
169
|
+
*
|
|
170
|
+
* Resolved from the roster the SERVER seeds for the requested profile, so the
|
|
171
|
+
* only caller influence is the profile NAME, which selects among rosters the
|
|
172
|
+
* operator's own deployed cast defines — a caller cannot name a roster into
|
|
173
|
+
* existence, and an unknown name falls back to `default`. A resolution failure
|
|
174
|
+
* returns `false`, which holds.
|
|
175
|
+
*/
|
|
176
|
+
resolveAdvisoryOnly(request) {
|
|
177
|
+
try {
|
|
178
|
+
return isAdvisoryOnly(resolveProfile(request.profile, defaultProfileTables()).roles);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
decrementHeld(tenantId) {
|
|
185
|
+
const current = this.heldCounts.get(tenantId) ?? 0;
|
|
186
|
+
if (current <= 1) {
|
|
187
|
+
this.heldCounts.delete(tenantId);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
this.heldCounts.set(tenantId, current - 1);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Execute one hero-tool call server-side. Routing/scope/gate decisions are made
|
|
195
|
+
* before any model call; on a hold or a quota denial NO backend call is made.
|
|
196
|
+
*
|
|
197
|
+
* `request.discovery` is deliberately not read here. The discovery gate
|
|
198
|
+
* interviews a human one question at a time, and this path has nobody to ask —
|
|
199
|
+
* so per `squad-discovery-gate.instructions.md` (*Unattended Runs*) no offer is
|
|
200
|
+
* made, an explicit depth is ignored rather than honored, and the caller's
|
|
201
|
+
* payload becomes the intake gate's input instead. An unattended run is gated by
|
|
202
|
+
* validation, not by ideation.
|
|
203
|
+
*/
|
|
204
|
+
async handle(tool, request, ctx) {
|
|
205
|
+
const matchedRouting = toMatchedRouting(tool);
|
|
206
|
+
const tenantId = ctx.auth.tenantId;
|
|
207
|
+
if (request.discovery) {
|
|
208
|
+
this.logger?.info("discovery_ignored_unattended", {
|
|
209
|
+
toolId: tool.id,
|
|
210
|
+
requested: request.discovery,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
// SEC-9 / COST-1 / COST-2 — admit under quota before any work.
|
|
214
|
+
const admit = this.quota.acquire(tenantId);
|
|
215
|
+
if (!admit.ok) {
|
|
216
|
+
return {
|
|
217
|
+
kind: "embedded",
|
|
218
|
+
outcome: "denied",
|
|
219
|
+
matchedRouting,
|
|
220
|
+
reason: admit.reason,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
// SEC-6 / SEC-7 / PROD-5 — a gated/destructive tool holds; never auto-releases.
|
|
225
|
+
const gate = this.gates.classify({
|
|
226
|
+
tool,
|
|
227
|
+
mode: request.mode,
|
|
228
|
+
advisoryOnly: this.resolveAdvisoryOnly(request),
|
|
229
|
+
});
|
|
230
|
+
if (gate.kind === "hold") {
|
|
231
|
+
const run = await this.runStateStore.create({ tenantId, toolId: tool.id });
|
|
232
|
+
await this.runStateStore.update(run.runId, { status: "held", holdReason: gate.reason });
|
|
233
|
+
return {
|
|
234
|
+
kind: "embedded",
|
|
235
|
+
outcome: "held",
|
|
236
|
+
matchedRouting,
|
|
237
|
+
approvalRequest: gate.approvalRequest,
|
|
238
|
+
reason: gate.reason,
|
|
239
|
+
runId: run.runId,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
// Thin slice: only the hero roles are embedded. Other roles stay delegated-only.
|
|
243
|
+
const charter = charterForRole(tool.role);
|
|
244
|
+
if (!charter) {
|
|
245
|
+
return {
|
|
246
|
+
kind: "embedded",
|
|
247
|
+
outcome: "denied",
|
|
248
|
+
matchedRouting,
|
|
249
|
+
reason: "role_not_embedded_in_thin_slice",
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const run = await this.runStateStore.create({ tenantId, toolId: tool.id });
|
|
253
|
+
// SEC-4 — server-allocated, per-tenant, isolated workspace with guaranteed teardown.
|
|
254
|
+
const workspace = await this.workspaceManager.allocate(tenantId);
|
|
255
|
+
try {
|
|
256
|
+
// Auto-memory: prior state/decisions join the caller's context as DATA.
|
|
257
|
+
const { request: framed, project } = await this.withMemory(tenantId, request);
|
|
258
|
+
// SEC-5 — caller text becomes delimited DATA; the charter is the only authority.
|
|
259
|
+
const prompt = composeEmbeddedPrompt({
|
|
260
|
+
systemAuthority: charter,
|
|
261
|
+
request: framed.request,
|
|
262
|
+
context: framed.context,
|
|
263
|
+
});
|
|
264
|
+
// Single server-side dispatch (SEC-7: inference + contained file I/O only).
|
|
265
|
+
const completion = await this.backend.complete({
|
|
266
|
+
system: prompt.system,
|
|
267
|
+
messages: prompt.messages,
|
|
268
|
+
});
|
|
269
|
+
// Write the artifact INSIDE the isolated workspace, then read it back.
|
|
270
|
+
const artifactPath = workspace.resolve("artifact.md");
|
|
271
|
+
await writeFile(artifactPath, completion.text, "utf8");
|
|
272
|
+
const artifact = await readFile(artifactPath, "utf8");
|
|
273
|
+
if (completion.usage?.estimatedCostUsd) {
|
|
274
|
+
this.quota.recordCostUsd(tenantId, completion.usage.estimatedCostUsd);
|
|
275
|
+
}
|
|
276
|
+
await this.runStateStore.update(run.runId, { status: "complete" });
|
|
277
|
+
await this.recordMemory(tenantId, project, { toolId: tool.id, runId: run.runId, artifact });
|
|
278
|
+
const result = {
|
|
279
|
+
kind: "embedded",
|
|
280
|
+
outcome: "completed",
|
|
281
|
+
matchedRouting,
|
|
282
|
+
artifact,
|
|
283
|
+
workspaceRoot: workspace.root,
|
|
284
|
+
runId: run.runId,
|
|
285
|
+
backendId: completion.backendId,
|
|
286
|
+
usage: completion.usage,
|
|
287
|
+
};
|
|
288
|
+
return result;
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
// SEC-4 — teardown runs even on error/timeout.
|
|
296
|
+
await workspace.dispose();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
finally {
|
|
300
|
+
// SEC-9 — always free the concurrency slot.
|
|
301
|
+
admit.release();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Execute one ADVISORY tool (`squad_plan` / `squad_architect`) server-side as a
|
|
306
|
+
* SINGLE-STAGE advisory dispatch through the advisory orchestrator (Phase 5).
|
|
307
|
+
*
|
|
308
|
+
* Unlike {@link handle} (which is bound to the two deterministic hero charters
|
|
309
|
+
* via `charterForRole`), this resolves the tool's role persona from the deployed
|
|
310
|
+
* cast (single-source invariant) and runs exactly one advisory stage via
|
|
311
|
+
* {@link runAdvisoryPipeline}. Advisory work lands NO impactful action, so — like
|
|
312
|
+
* the hero tools — it makes a single synchronous dispatch and never holds. All
|
|
313
|
+
* the same contained-execution guarantees apply: quota admission (SEC-9 / COST),
|
|
314
|
+
* a server-allocated per-tenant workspace with guaranteed teardown (SEC-4), and
|
|
315
|
+
* SEC-5 (the persona charter is the ONLY authority; caller input is DATA — the
|
|
316
|
+
* advisory orchestrator composes the prompt the same way `handle` does).
|
|
317
|
+
*
|
|
318
|
+
* `personaRoots` is an optional override used by tests for deterministic persona
|
|
319
|
+
* resolution; production passes none and uses the resolved cast.
|
|
320
|
+
*/
|
|
321
|
+
async handleAdvisory(tool, request, ctx, personaRoots) {
|
|
322
|
+
const matchedRouting = toMatchedRouting(tool);
|
|
323
|
+
const tenantId = ctx.auth.tenantId;
|
|
324
|
+
// SEC-9 / COST-1 / COST-2 — admit under quota before any work.
|
|
325
|
+
const admit = this.quota.acquire(tenantId);
|
|
326
|
+
if (!admit.ok) {
|
|
327
|
+
return { kind: "embedded", outcome: "denied", matchedRouting, reason: admit.reason };
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
// Resolve the tool's role persona from the deployed cast (real `*.agent.md`
|
|
331
|
+
// bytes; the hero paraphrase fallback covers only the 2 hero agents). An
|
|
332
|
+
// unresolvable role is denied — never a silent wrong persona.
|
|
333
|
+
const persona = resolvePersonaForRole(tool.role, personaRoots);
|
|
334
|
+
if (!persona) {
|
|
335
|
+
return { kind: "embedded", outcome: "denied", matchedRouting, reason: "role_not_resolvable" };
|
|
336
|
+
}
|
|
337
|
+
const run = await this.runStateStore.create({ tenantId, toolId: tool.id });
|
|
338
|
+
// SEC-4 — server-allocated, per-tenant, isolated workspace with guaranteed teardown.
|
|
339
|
+
const workspace = await this.workspaceManager.allocate(tenantId);
|
|
340
|
+
try {
|
|
341
|
+
// Single-stage advisory dispatch: one persona stage, no council/backlog.
|
|
342
|
+
const plan = [{ kind: "persona", role: persona.role, persona }];
|
|
343
|
+
const { request: framed, project } = await this.withMemory(tenantId, request);
|
|
344
|
+
const result = await runAdvisoryPipeline(framed, {
|
|
345
|
+
backend: this.backend,
|
|
346
|
+
ledger: this.ledgerSink(tenantId, project, framed, run.runId),
|
|
347
|
+
}, { plan });
|
|
348
|
+
// Write the artifact INSIDE the isolated workspace, then read it back.
|
|
349
|
+
const artifactPath = workspace.resolve("artifact.md");
|
|
350
|
+
await writeFile(artifactPath, result.artifact, "utf8");
|
|
351
|
+
const artifact = await readFile(artifactPath, "utf8");
|
|
352
|
+
for (const usage of result.usage) {
|
|
353
|
+
if (usage.estimatedCostUsd) {
|
|
354
|
+
this.quota.recordCostUsd(tenantId, usage.estimatedCostUsd);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
await this.runStateStore.update(run.runId, { status: "complete", artifact });
|
|
358
|
+
await this.recordMemory(tenantId, project, { toolId: tool.id, runId: run.runId, artifact });
|
|
359
|
+
return {
|
|
360
|
+
kind: "embedded",
|
|
361
|
+
outcome: "completed",
|
|
362
|
+
matchedRouting,
|
|
363
|
+
artifact,
|
|
364
|
+
workspaceRoot: workspace.root,
|
|
365
|
+
runId: run.runId,
|
|
366
|
+
backendId: result.stages.at(-1)?.backendId,
|
|
367
|
+
usage: result.usage.at(-1),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
372
|
+
throw error;
|
|
373
|
+
}
|
|
374
|
+
finally {
|
|
375
|
+
// SEC-4 — teardown runs even on error/timeout.
|
|
376
|
+
await workspace.dispose();
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
// SEC-9 — always free the concurrency slot.
|
|
381
|
+
admit.release();
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Execute one BUSINESS tool (`squad_business_plan` / `squad_backlog`) as a
|
|
386
|
+
* single-stage embedded advisory dispatch.
|
|
387
|
+
*
|
|
388
|
+
* Persona composition: the deployed cast persona (real `*.agent.md` bytes) is the
|
|
389
|
+
* DOMAIN authority and the tool spec's charter is appended as the OUTPUT
|
|
390
|
+
* contract. Appending rather than replacing keeps the single-source invariant
|
|
391
|
+
* (the cast still defines how the role thinks) while making the result shape
|
|
392
|
+
* deterministic enough for a Copilot Studio agent to consume — which is the whole
|
|
393
|
+
* point of the business surface. When the cast is absent, the spec charter alone
|
|
394
|
+
* is the fallback, exactly like the hero roles.
|
|
395
|
+
*
|
|
396
|
+
* Advisory posture is identical to {@link handleAdvisory}: quota admission
|
|
397
|
+
* (SEC-9 / COST), a per-tenant ephemeral workspace with guaranteed teardown
|
|
398
|
+
* (SEC-4), caller text as delimited DATA (SEC-5), no gate, and no impactful
|
|
399
|
+
* action. Auto-memory continuity applies here too when it is wired.
|
|
400
|
+
*/
|
|
401
|
+
async handleBusiness(spec, request, ctx, personaRoots) {
|
|
402
|
+
const matchedRouting = {
|
|
403
|
+
routingIntent: spec.toolId,
|
|
404
|
+
role: spec.role,
|
|
405
|
+
tier: "auto",
|
|
406
|
+
parallelEligible: false,
|
|
407
|
+
council: [],
|
|
408
|
+
catchAll: false,
|
|
409
|
+
gates: false,
|
|
410
|
+
};
|
|
411
|
+
const tenantId = ctx.auth.tenantId;
|
|
412
|
+
const admit = this.quota.acquire(tenantId);
|
|
413
|
+
if (!admit.ok) {
|
|
414
|
+
return { kind: "embedded", outcome: "denied", matchedRouting, reason: admit.reason };
|
|
415
|
+
}
|
|
416
|
+
try {
|
|
417
|
+
const deployed = resolvePersonaForRole(spec.role, personaRoots);
|
|
418
|
+
const persona = {
|
|
419
|
+
role: spec.role,
|
|
420
|
+
applyTo: deployed?.applyTo ?? [],
|
|
421
|
+
charter: deployed?.charter ? `${deployed.charter}\n\n${spec.charter}` : spec.charter,
|
|
422
|
+
};
|
|
423
|
+
const run = await this.runStateStore.create({ tenantId, toolId: spec.toolId });
|
|
424
|
+
const workspace = await this.workspaceManager.allocate(tenantId);
|
|
425
|
+
try {
|
|
426
|
+
const { request: framed, project } = await this.withMemory(tenantId, request);
|
|
427
|
+
const result = await runAdvisoryPipeline(framed, {
|
|
428
|
+
backend: this.backend,
|
|
429
|
+
ledger: this.ledgerSink(tenantId, project, framed, run.runId),
|
|
430
|
+
}, { plan: [{ kind: "persona", role: persona.role, persona }] });
|
|
431
|
+
const artifactPath = workspace.resolve("artifact.md");
|
|
432
|
+
await writeFile(artifactPath, result.artifact, "utf8");
|
|
433
|
+
const artifact = await readFile(artifactPath, "utf8");
|
|
434
|
+
for (const usage of result.usage) {
|
|
435
|
+
if (usage.estimatedCostUsd) {
|
|
436
|
+
this.quota.recordCostUsd(tenantId, usage.estimatedCostUsd);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
await this.runStateStore.update(run.runId, { status: "complete", artifact });
|
|
440
|
+
await this.recordMemory(tenantId, project, {
|
|
441
|
+
toolId: spec.toolId,
|
|
442
|
+
runId: run.runId,
|
|
443
|
+
artifact,
|
|
444
|
+
});
|
|
445
|
+
return {
|
|
446
|
+
kind: "embedded",
|
|
447
|
+
outcome: "completed",
|
|
448
|
+
matchedRouting,
|
|
449
|
+
artifact,
|
|
450
|
+
workspaceRoot: workspace.root,
|
|
451
|
+
runId: run.runId,
|
|
452
|
+
backendId: result.stages.at(-1)?.backendId,
|
|
453
|
+
usage: result.usage.at(-1),
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
catch (error) {
|
|
457
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
458
|
+
throw error;
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
await workspace.dispose();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
admit.release();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Execute the spike catch-all pipeline (Squad Researcher -> Squad Reviewer) as a
|
|
470
|
+
* sequential in-process dispatch loop, inside one server-allocated ephemeral
|
|
471
|
+
* workspace with guaranteed teardown (SEC-4). Personas are resolved from disk
|
|
472
|
+
* (single-source invariant) with the paraphrase fallback. This is the pipeline
|
|
473
|
+
* primitive the async run + gate-resume paths (Phases 3-4) drive; it does not
|
|
474
|
+
* itself acquire a quota slot (the caller owns admit/gate ordering).
|
|
475
|
+
*
|
|
476
|
+
* `personaRoots` is an optional override used by tests for deterministic
|
|
477
|
+
* persona resolution; production passes none and uses the resolved cast.
|
|
478
|
+
*/
|
|
479
|
+
async executePipeline(tool, request, ctx, personaRoots) {
|
|
480
|
+
const matchedRouting = toMatchedRouting(tool);
|
|
481
|
+
const tenantId = ctx.auth.tenantId;
|
|
482
|
+
const run = await this.runStateStore.create({ tenantId, toolId: tool.id });
|
|
483
|
+
const core = await this.runPipelineCore(tenantId, request, personaRoots);
|
|
484
|
+
if (core.outcome === "denied") {
|
|
485
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
486
|
+
return { kind: "embedded", outcome: "denied", matchedRouting, reason: core.reason };
|
|
487
|
+
}
|
|
488
|
+
await this.runStateStore.update(run.runId, { status: "complete", artifact: core.artifact });
|
|
489
|
+
return {
|
|
490
|
+
kind: "embedded",
|
|
491
|
+
outcome: "completed",
|
|
492
|
+
matchedRouting,
|
|
493
|
+
artifact: core.artifact,
|
|
494
|
+
workspaceRoot: core.workspaceRoot,
|
|
495
|
+
runId: run.runId,
|
|
496
|
+
backendId: core.backendId,
|
|
497
|
+
usage: core.usage,
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Async run start (KD-5 / KD-6): persist a durable "running" record and return
|
|
502
|
+
* the run id IMMEDIATELY, without awaiting the pipeline. The caller polls
|
|
503
|
+
* {@link getRunStatus} and drives the work via {@link runToCompletion}. Returning
|
|
504
|
+
* the id first is what lets a minutes-long run clear the 240s ingress ceiling.
|
|
505
|
+
*/
|
|
506
|
+
startRun(tool, ctx) {
|
|
507
|
+
return this.runStateStore
|
|
508
|
+
.create({ tenantId: ctx.auth.tenantId, toolId: tool.id })
|
|
509
|
+
.then((run) => ({ runId: run.runId }));
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Execute a previously-started run to completion and persist the artifact to the
|
|
513
|
+
* durable store. Enforces tenant ownership: a run id owned by another tenant is
|
|
514
|
+
* denied (no cross-tenant execution). Survives a cold start when the store is
|
|
515
|
+
* durable (the run is re-resolved by id).
|
|
516
|
+
*/
|
|
517
|
+
async runToCompletion(runId, request, ctx, personaRoots) {
|
|
518
|
+
const run = await this.runStateStore.get(runId);
|
|
519
|
+
if (!run || run.tenantId !== ctx.auth.tenantId) {
|
|
520
|
+
return {
|
|
521
|
+
kind: "embedded",
|
|
522
|
+
outcome: "denied",
|
|
523
|
+
matchedRouting: EMPTY_ROUTING,
|
|
524
|
+
reason: "run_not_found_or_cross_tenant",
|
|
525
|
+
runId,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
const core = await this.runPipelineCore(run.tenantId, request, personaRoots);
|
|
529
|
+
if (core.outcome === "denied") {
|
|
530
|
+
await this.runStateStore.update(runId, { status: "failed" });
|
|
531
|
+
return { kind: "embedded", outcome: "denied", matchedRouting: EMPTY_ROUTING, reason: core.reason, runId };
|
|
532
|
+
}
|
|
533
|
+
await this.runStateStore.update(runId, { status: "complete", artifact: core.artifact });
|
|
534
|
+
return {
|
|
535
|
+
kind: "embedded",
|
|
536
|
+
outcome: "completed",
|
|
537
|
+
matchedRouting: EMPTY_ROUTING,
|
|
538
|
+
artifact: core.artifact,
|
|
539
|
+
workspaceRoot: core.workspaceRoot,
|
|
540
|
+
runId,
|
|
541
|
+
backendId: core.backendId,
|
|
542
|
+
usage: core.usage,
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Poll a run's status and (when complete) its artifact, scoped to the caller's
|
|
547
|
+
* tenant. A run id owned by another tenant returns `undefined` (no leakage);
|
|
548
|
+
* combined with the unguessable, path-validated run id (durable store), this is
|
|
549
|
+
* the tenant-isolation boundary for the async poll.
|
|
550
|
+
*/
|
|
551
|
+
async getRunStatus(runId, ctx) {
|
|
552
|
+
const run = await this.runStateStore.get(runId);
|
|
553
|
+
if (!run || run.tenantId !== ctx.auth.tenantId) {
|
|
554
|
+
return undefined;
|
|
555
|
+
}
|
|
556
|
+
return { status: run.status, artifact: run.artifact };
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Gate carry-through across the async boundary (PROD-5 / SEC-6). A HELD run
|
|
560
|
+
* resumes ONLY when an operator has approved its run id out-of-band through the
|
|
561
|
+
* approval channel; there is no code path here that releases a hold from caller
|
|
562
|
+
* `request`/`context` or model output. When the run is not yet approved this
|
|
563
|
+
* returns the run STILL held and makes NO model call (no auto-release). The held
|
|
564
|
+
* record is durable, so a hold survives a scale-to-zero cold start; approval is
|
|
565
|
+
* checked again on the next resume call.
|
|
566
|
+
*/
|
|
567
|
+
async resumeRun(runId, request, ctx, personaRoots) {
|
|
568
|
+
const run = await this.runStateStore.get(runId);
|
|
569
|
+
if (!run || run.tenantId !== ctx.auth.tenantId) {
|
|
570
|
+
return {
|
|
571
|
+
kind: "embedded",
|
|
572
|
+
outcome: "denied",
|
|
573
|
+
matchedRouting: EMPTY_ROUTING,
|
|
574
|
+
reason: "run_not_found_or_cross_tenant",
|
|
575
|
+
runId,
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
// The ONLY release path: an explicit, out-of-band operator approval keyed on
|
|
579
|
+
// the run id. Never derived from caller input or model output (SEC-6).
|
|
580
|
+
if (!(await this.approvals.isApproved(runId))) {
|
|
581
|
+
return {
|
|
582
|
+
kind: "embedded",
|
|
583
|
+
outcome: "held",
|
|
584
|
+
matchedRouting: EMPTY_ROUTING,
|
|
585
|
+
reason: run.holdReason ?? "awaiting human approval",
|
|
586
|
+
approvalRequest: "This run is paused for human approval and will not proceed until an " +
|
|
587
|
+
"operator approves it out-of-band. The squad never auto-releases a gate.",
|
|
588
|
+
runId,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
// Approved: transition held -> running and execute the pipeline to completion.
|
|
592
|
+
await this.runStateStore.update(runId, { status: "running" });
|
|
593
|
+
const core = await this.runPipelineCore(run.tenantId, request, personaRoots);
|
|
594
|
+
if (core.outcome === "denied") {
|
|
595
|
+
await this.runStateStore.update(runId, { status: "failed" });
|
|
596
|
+
return { kind: "embedded", outcome: "denied", matchedRouting: EMPTY_ROUTING, reason: core.reason, runId };
|
|
597
|
+
}
|
|
598
|
+
await this.runStateStore.update(runId, { status: "complete", artifact: core.artifact });
|
|
599
|
+
return {
|
|
600
|
+
kind: "embedded",
|
|
601
|
+
outcome: "completed",
|
|
602
|
+
matchedRouting: EMPTY_ROUTING,
|
|
603
|
+
artifact: core.artifact,
|
|
604
|
+
workspaceRoot: core.workspaceRoot,
|
|
605
|
+
runId,
|
|
606
|
+
backendId: core.backendId,
|
|
607
|
+
usage: core.usage,
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Start an async run over the remote (HTTP) boundary. Admits under quota,
|
|
612
|
+
* classifies the gate, and persists a DURABLE run carrying the caller request so
|
|
613
|
+
* a later status poll can drive it to completion after approval. `squad_run` is
|
|
614
|
+
* gated, so this returns a HELD result with a run id: no pipeline runs and no
|
|
615
|
+
* model is called until an operator approves out-of-band (SEC-6 / PROD-5 carried
|
|
616
|
+
* across the remote boundary). A held run does not hold a concurrency slot.
|
|
617
|
+
*/
|
|
618
|
+
async startHttpRun(tool, request, ctx) {
|
|
619
|
+
const matchedRouting = toMatchedRouting(tool);
|
|
620
|
+
const tenantId = ctx.auth.tenantId;
|
|
621
|
+
const admit = this.quota.acquire(tenantId);
|
|
622
|
+
if (!admit.ok) {
|
|
623
|
+
return { kind: "embedded", outcome: "denied", matchedRouting, reason: admit.reason };
|
|
624
|
+
}
|
|
625
|
+
try {
|
|
626
|
+
const gate = this.gates.classify({
|
|
627
|
+
tool,
|
|
628
|
+
mode: request.mode,
|
|
629
|
+
advisoryOnly: this.resolveAdvisoryOnly(request),
|
|
630
|
+
});
|
|
631
|
+
if (gate.kind === "hold") {
|
|
632
|
+
// MEDIUM-2: cap outstanding held runs per tenant (held runs release the
|
|
633
|
+
// concurrency slot, so neither SEC-9 nor COST-2 throttles their creation).
|
|
634
|
+
const held = this.heldCounts.get(tenantId) ?? 0;
|
|
635
|
+
if (held >= this.maxHeldRunsPerTenant) {
|
|
636
|
+
return { kind: "embedded", outcome: "denied", matchedRouting, reason: "held_run_cap" };
|
|
637
|
+
}
|
|
638
|
+
const run = await this.runStateStore.create({ tenantId, toolId: tool.id, ttlMs: this.runTtlMs });
|
|
639
|
+
await this.runStateStore.update(run.runId, {
|
|
640
|
+
status: "held",
|
|
641
|
+
holdReason: gate.reason,
|
|
642
|
+
request: request.request,
|
|
643
|
+
context: request.context,
|
|
644
|
+
params: encodeRunParams(request),
|
|
645
|
+
});
|
|
646
|
+
this.heldCounts.set(tenantId, held + 1);
|
|
647
|
+
return {
|
|
648
|
+
kind: "embedded",
|
|
649
|
+
outcome: "held",
|
|
650
|
+
matchedRouting,
|
|
651
|
+
approvalRequest: gate.approvalRequest,
|
|
652
|
+
reason: gate.reason,
|
|
653
|
+
runId: run.runId,
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
// Non-gated remote tool: persist running; execution driven by the poll.
|
|
657
|
+
const run = await this.runStateStore.create({ tenantId, toolId: tool.id, ttlMs: this.runTtlMs });
|
|
658
|
+
await this.runStateStore.update(run.runId, {
|
|
659
|
+
status: "running",
|
|
660
|
+
request: request.request,
|
|
661
|
+
context: request.context,
|
|
662
|
+
params: encodeRunParams(request),
|
|
663
|
+
});
|
|
664
|
+
return {
|
|
665
|
+
kind: "embedded",
|
|
666
|
+
outcome: "held",
|
|
667
|
+
matchedRouting,
|
|
668
|
+
reason: "queued",
|
|
669
|
+
runId: run.runId,
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
finally {
|
|
673
|
+
// A held/queued run is not an in-flight dispatch; free the slot immediately.
|
|
674
|
+
admit.release();
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Poll a run over the remote boundary (tenant-scoped). A completed run returns
|
|
679
|
+
* its stored artifact; failed is denied; an unknown or cross-tenant run id is
|
|
680
|
+
* denied (no leakage). A held-but-unapproved run stays held (never auto-release).
|
|
681
|
+
*
|
|
682
|
+
* When the run is approved, behavior depends on `driveOnPoll`:
|
|
683
|
+
* * `driveOnPoll` true (single-replica default) — the poll DRIVES execution:
|
|
684
|
+
* it CAS-claims held/running(lease-expired) -> running (so exactly one poll
|
|
685
|
+
* or replica drives; MEDIUM-1 across replicas via WI-06 CAS), runs the
|
|
686
|
+
* pipeline under quota using the persisted request, and returns the artifact.
|
|
687
|
+
* * `driveOnPoll` false (worker deployment) — the poll is READ-ONLY: it reports
|
|
688
|
+
* the run as still running and a background ACA Job drives it off the request
|
|
689
|
+
* path, so a run may exceed the 240s ingress ceiling (WI-1b4-WORKER).
|
|
690
|
+
*/
|
|
691
|
+
async pollRun(runId, ctx) {
|
|
692
|
+
const run = await this.runStateStore.get(runId);
|
|
693
|
+
if (!run || run.tenantId !== ctx.auth.tenantId) {
|
|
694
|
+
return {
|
|
695
|
+
kind: "embedded",
|
|
696
|
+
outcome: "denied",
|
|
697
|
+
matchedRouting: EMPTY_ROUTING,
|
|
698
|
+
reason: "run_not_found_or_cross_tenant",
|
|
699
|
+
runId,
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
if (run.status === "complete") {
|
|
703
|
+
return { kind: "embedded", outcome: "completed", matchedRouting: EMPTY_ROUTING, artifact: run.artifact, runId };
|
|
704
|
+
}
|
|
705
|
+
if (run.status === "failed") {
|
|
706
|
+
return { kind: "embedded", outcome: "denied", matchedRouting: EMPTY_ROUTING, reason: "run_failed", runId };
|
|
707
|
+
}
|
|
708
|
+
// held / running: never auto-release; only an explicit approval proceeds.
|
|
709
|
+
if (!(await this.approvals.isApproved(runId))) {
|
|
710
|
+
return {
|
|
711
|
+
kind: "embedded",
|
|
712
|
+
outcome: "held",
|
|
713
|
+
matchedRouting: EMPTY_ROUTING,
|
|
714
|
+
reason: run.holdReason ?? "awaiting human approval",
|
|
715
|
+
approvalRequest: "This run is paused for human approval and will not proceed until an " +
|
|
716
|
+
"operator approves it out-of-band. The squad never auto-releases a gate.",
|
|
717
|
+
runId,
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
// Worker mode: the poll never executes; the ACA Job drives approved runs.
|
|
721
|
+
if (!this.driveOnPoll) {
|
|
722
|
+
return {
|
|
723
|
+
kind: "embedded",
|
|
724
|
+
outcome: "held",
|
|
725
|
+
matchedRouting: EMPTY_ROUTING,
|
|
726
|
+
reason: "queued_for_worker",
|
|
727
|
+
runId,
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
// Acquire a concurrency slot, then CAS-claim the run. The claim replaces the
|
|
731
|
+
// in-process in-flight guard with a cross-replica compare-and-swap: exactly one
|
|
732
|
+
// poll/replica wins held/running(lease-expired) -> running; a lost claim is
|
|
733
|
+
// deferred (another is already driving it).
|
|
734
|
+
const admit = this.quota.acquire(run.tenantId);
|
|
735
|
+
if (!admit.ok) {
|
|
736
|
+
return { kind: "embedded", outcome: "denied", matchedRouting: EMPTY_ROUTING, reason: admit.reason, runId };
|
|
737
|
+
}
|
|
738
|
+
const claimed = await this.runStateStore.claim(runId, ["held", "running"], "running", { leaseMs: this.leaseMs });
|
|
739
|
+
if (!claimed) {
|
|
740
|
+
admit.release();
|
|
741
|
+
return {
|
|
742
|
+
kind: "embedded",
|
|
743
|
+
outcome: "held",
|
|
744
|
+
matchedRouting: EMPTY_ROUTING,
|
|
745
|
+
reason: "run_already_in_flight",
|
|
746
|
+
runId,
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
try {
|
|
750
|
+
return await this.executeRunningRun(claimed);
|
|
751
|
+
}
|
|
752
|
+
finally {
|
|
753
|
+
admit.release();
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Drive a run that is ALREADY claimed (status `running`, lease held by the
|
|
758
|
+
* caller) to completion: run the pipeline under the persisted request, persist
|
|
759
|
+
* the artifact, and decrement the held-run count. Shared by the poll-drives path
|
|
760
|
+
* and the background worker so both produce identical results. Assumes the CAS
|
|
761
|
+
* claim already succeeded — it does not re-check approval (the claim path did).
|
|
762
|
+
*
|
|
763
|
+
* The catch-all `squad_run` runs the FULL advisory pipeline (Phase 5): routing
|
|
764
|
+
* -> research -> plan -> [council] -> review -> backlog-handoff, persisting each
|
|
765
|
+
* stage + the council verdict durably (so a status poll recompiles the finished
|
|
766
|
+
* artifact multi-replica / after a cold start). Any other tool id keeps the
|
|
767
|
+
* spike two-stage pipeline. Both persist the compiled artifact + `complete`.
|
|
768
|
+
*/
|
|
769
|
+
async executeRunningRun(run) {
|
|
770
|
+
if (run.toolId === "squad_run") {
|
|
771
|
+
return this.executeAdvisoryRun(run);
|
|
772
|
+
}
|
|
773
|
+
if (run.toolId === FEDERATION_TOOL_ID) {
|
|
774
|
+
return this.executeFederationRun(run);
|
|
775
|
+
}
|
|
776
|
+
const req = coordinatorRequestFromRun(run);
|
|
777
|
+
const core = await this.runPipelineCore(run.tenantId, req);
|
|
778
|
+
if (core.outcome === "denied") {
|
|
779
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
780
|
+
this.decrementHeld(run.tenantId);
|
|
781
|
+
return { kind: "embedded", outcome: "denied", matchedRouting: EMPTY_ROUTING, reason: core.reason, runId: run.runId };
|
|
782
|
+
}
|
|
783
|
+
await this.runStateStore.update(run.runId, { status: "complete", artifact: core.artifact });
|
|
784
|
+
this.decrementHeld(run.tenantId);
|
|
785
|
+
return {
|
|
786
|
+
kind: "embedded",
|
|
787
|
+
outcome: "completed",
|
|
788
|
+
matchedRouting: EMPTY_ROUTING,
|
|
789
|
+
artifact: core.artifact,
|
|
790
|
+
workspaceRoot: core.workspaceRoot,
|
|
791
|
+
runId: run.runId,
|
|
792
|
+
backendId: core.backendId,
|
|
793
|
+
usage: core.usage,
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Drive an approved/claimed `squad_run` through the FULL advisory pipeline
|
|
798
|
+
* (Phase 5). The advisory orchestrator routes the persisted request across the
|
|
799
|
+
* full cast (research -> plan -> [council] -> review -> backlog-handoff) as
|
|
800
|
+
* sequential model completions, threading each stage's artifact forward as DATA
|
|
801
|
+
* (SEC-5 preserved by the orchestrator). It runs in autopilot so the async drive
|
|
802
|
+
* yields ONE compiled artifact; the human gate is the EXISTING non-bypassable
|
|
803
|
+
* hold already applied at {@link startHttpRun} (released out-of-band via
|
|
804
|
+
* `/admin/approve`), so no additional final hold is injected here.
|
|
805
|
+
*
|
|
806
|
+
* Per-stage artifacts + the council verdict + a history list persist durably
|
|
807
|
+
* through {@link StoreAdvisoryPersistence} so a status poll recompiles the
|
|
808
|
+
* finished artifact multi-replica and after a cold start; the compiled artifact
|
|
809
|
+
* is also stored on the run so `squad_status` returns it directly. A council
|
|
810
|
+
* `Stop` verdict halts the pipeline and the run completes with the Stop artifact
|
|
811
|
+
* (there is no implement stage to gate in advisory scope). All work happens
|
|
812
|
+
* inside a server-allocated per-tenant workspace with guaranteed teardown (SEC-4).
|
|
813
|
+
*/
|
|
814
|
+
async executeAdvisoryRun(run) {
|
|
815
|
+
const req = coordinatorRequestFromRun(run);
|
|
816
|
+
const workspace = await this.workspaceManager.allocate(run.tenantId);
|
|
817
|
+
try {
|
|
818
|
+
const persistence = new StoreAdvisoryPersistence(this.runStateStore, run.runId);
|
|
819
|
+
const { request: framed, project } = await this.withMemory(run.tenantId, req);
|
|
820
|
+
// Autopilot: advance stage-to-stage to a single compiled artifact. The human
|
|
821
|
+
// gate already fired at startHttpRun; no additional finalHold is injected.
|
|
822
|
+
const result = await runAdvisoryPipeline(framed, {
|
|
823
|
+
backend: this.backend,
|
|
824
|
+
persistence,
|
|
825
|
+
ledger: this.ledgerSink(run.tenantId, project, framed, run.runId),
|
|
826
|
+
}, { mode: "autopilot" });
|
|
827
|
+
for (const usage of result.usage) {
|
|
828
|
+
if (usage.estimatedCostUsd) {
|
|
829
|
+
this.quota.recordCostUsd(run.tenantId, usage.estimatedCostUsd);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
// `completed` and a council `Stop` `halted` are both terminal-with-artifact;
|
|
833
|
+
// persist the compiled artifact so the status poll returns it directly.
|
|
834
|
+
await this.runStateStore.update(run.runId, { status: "complete", artifact: result.artifact });
|
|
835
|
+
await this.recordMemory(run.tenantId, project, {
|
|
836
|
+
toolId: run.toolId,
|
|
837
|
+
runId: run.runId,
|
|
838
|
+
artifact: result.artifact,
|
|
839
|
+
});
|
|
840
|
+
this.decrementHeld(run.tenantId);
|
|
841
|
+
return {
|
|
842
|
+
kind: "embedded",
|
|
843
|
+
outcome: "completed",
|
|
844
|
+
matchedRouting: EMPTY_ROUTING,
|
|
845
|
+
artifact: result.artifact,
|
|
846
|
+
workspaceRoot: workspace.root,
|
|
847
|
+
runId: run.runId,
|
|
848
|
+
backendId: result.stages.at(-1)?.backendId,
|
|
849
|
+
usage: result.usage.at(-1),
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
catch (error) {
|
|
853
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
854
|
+
this.decrementHeld(run.tenantId);
|
|
855
|
+
throw error;
|
|
856
|
+
}
|
|
857
|
+
finally {
|
|
858
|
+
// SEC-4 — teardown runs even on error/timeout.
|
|
859
|
+
await workspace.dispose();
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Drive an approved/claimed `squad_federate` run through the FEDERATION meta
|
|
864
|
+
* layer. This is the embedded counterpart of the delegated federation path: the
|
|
865
|
+
* run executes as a single Federation Coordinator advisory stage whose charter is
|
|
866
|
+
* the resolved federation persona PLUS a server-composed directive derived only
|
|
867
|
+
* from validated inputs (`squad` / `init` / `promote` / `mode`) — see
|
|
868
|
+
* `federation.ts`. The caller's free text stays delimited DATA (SEC-5).
|
|
869
|
+
*
|
|
870
|
+
* The federation inputs are recovered from the run's persisted `params`, so a
|
|
871
|
+
* pinned sub-squad or an init/promote turn survives the approve → poll cycle
|
|
872
|
+
* instead of degrading into a plain pipeline run.
|
|
873
|
+
*
|
|
874
|
+
* The Human Gate already fired at {@link startHttpRun} (`squad_federate` is
|
|
875
|
+
* `gates: true`), so no additional hold is injected here — identical to the
|
|
876
|
+
* `squad_run` path. All work happens inside a per-tenant ephemeral workspace with
|
|
877
|
+
* guaranteed teardown (SEC-4).
|
|
878
|
+
*/
|
|
879
|
+
async executeFederationRun(run) {
|
|
880
|
+
const req = coordinatorRequestFromRun(run);
|
|
881
|
+
const workspace = await this.workspaceManager.allocate(run.tenantId);
|
|
882
|
+
try {
|
|
883
|
+
// Real on-disk `*.agent.md` bytes when the cast is present; the embedded
|
|
884
|
+
// paraphrase otherwise (so a minimal image never fails role resolution).
|
|
885
|
+
const persona = federationPersona(req, resolvePersonaForRole(FEDERATION_ROLE));
|
|
886
|
+
const persistence = new StoreAdvisoryPersistence(this.runStateStore, run.runId);
|
|
887
|
+
const { request: framed, project } = await this.withMemory(run.tenantId, req);
|
|
888
|
+
const result = await runAdvisoryPipeline(framed, {
|
|
889
|
+
backend: this.backend,
|
|
890
|
+
persistence,
|
|
891
|
+
ledger: this.ledgerSink(run.tenantId, project, framed, run.runId),
|
|
892
|
+
}, { mode: "autopilot", plan: [{ kind: "persona", role: persona.role, persona }] });
|
|
893
|
+
for (const usage of result.usage) {
|
|
894
|
+
if (usage.estimatedCostUsd) {
|
|
895
|
+
this.quota.recordCostUsd(run.tenantId, usage.estimatedCostUsd);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
await this.runStateStore.update(run.runId, { status: "complete", artifact: result.artifact });
|
|
899
|
+
await this.recordMemory(run.tenantId, project, {
|
|
900
|
+
toolId: run.toolId,
|
|
901
|
+
runId: run.runId,
|
|
902
|
+
artifact: result.artifact,
|
|
903
|
+
});
|
|
904
|
+
this.decrementHeld(run.tenantId);
|
|
905
|
+
return {
|
|
906
|
+
kind: "embedded",
|
|
907
|
+
outcome: "completed",
|
|
908
|
+
matchedRouting: FEDERATION_ROUTING,
|
|
909
|
+
artifact: result.artifact,
|
|
910
|
+
workspaceRoot: workspace.root,
|
|
911
|
+
runId: run.runId,
|
|
912
|
+
backendId: result.stages.at(-1)?.backendId,
|
|
913
|
+
usage: result.usage.at(-1),
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
catch (error) {
|
|
917
|
+
await this.runStateStore.update(run.runId, { status: "failed" });
|
|
918
|
+
this.decrementHeld(run.tenantId);
|
|
919
|
+
throw error;
|
|
920
|
+
}
|
|
921
|
+
finally {
|
|
922
|
+
// SEC-4 — teardown runs even on error/timeout.
|
|
923
|
+
await workspace.dispose();
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* WI-1b4-WORKER — the background-worker entry point. CAS-claim a single
|
|
928
|
+
* claimable run (an approved held run, or a running run whose lease lapsed) and
|
|
929
|
+
* drive it to completion under quota. Returns the result, or `undefined` when the
|
|
930
|
+
* claim was lost to another worker/replica (no double-execution). The worker
|
|
931
|
+
* enumerates claimable runs via the store and calls this per run id.
|
|
932
|
+
*/
|
|
933
|
+
async driveClaimable(runId) {
|
|
934
|
+
const claimed = await this.runStateStore.claim(runId, ["held", "running"], "running", { leaseMs: this.leaseMs });
|
|
935
|
+
if (!claimed) {
|
|
936
|
+
return undefined;
|
|
937
|
+
}
|
|
938
|
+
const admit = this.quota.acquire(claimed.tenantId);
|
|
939
|
+
if (!admit.ok) {
|
|
940
|
+
// Leave the run running with its lease; it becomes reclaimable after the
|
|
941
|
+
// lease lapses, so a transient quota denial does not strand it.
|
|
942
|
+
return { kind: "embedded", outcome: "denied", matchedRouting: EMPTY_ROUTING, reason: admit.reason, runId };
|
|
943
|
+
}
|
|
944
|
+
try {
|
|
945
|
+
return await this.executeRunningRun(claimed);
|
|
946
|
+
}
|
|
947
|
+
finally {
|
|
948
|
+
admit.release();
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
/** List the runs a worker may claim right now (tenant-agnostic; server-internal). */
|
|
952
|
+
listClaimableRuns(now) {
|
|
953
|
+
return this.runStateStore.listClaimable(now);
|
|
954
|
+
}
|
|
955
|
+
/** Delete expired runs (TTL janitor); returns the count removed (worker/janitor). */
|
|
956
|
+
sweepExpiredRuns(now) {
|
|
957
|
+
return this.runStateStore.sweepExpired(now);
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Release a HELD run by recording an out-of-band OPERATOR approval (SEC-6). This
|
|
961
|
+
* is the ONLY production caller of the approval channel and the keystone that
|
|
962
|
+
* lets a deployed held `squad_run` proceed: the operator calls it through the
|
|
963
|
+
* `/admin/approve` route, never a `tools/call`, so caller `request`/`context` and
|
|
964
|
+
* model output have no path to a release. Tenant-scoped: an operator may release
|
|
965
|
+
* only runs owned by their own tenant/authority; an unknown or cross-tenant run
|
|
966
|
+
* id is denied with no leakage (mirrors {@link pollRun}). Records approver +
|
|
967
|
+
* timestamp via the auditable channel; `approver` is the operator's token subject.
|
|
968
|
+
* Idempotent — re-approving an already-approved run keeps the original record.
|
|
969
|
+
*/
|
|
970
|
+
approveRun(runId, ctx) {
|
|
971
|
+
return this.runStateStore.get(runId).then(async (run) => {
|
|
972
|
+
if (!run || run.tenantId !== ctx.auth.tenantId) {
|
|
973
|
+
return { ok: false, reason: "run_not_found_or_cross_tenant" };
|
|
974
|
+
}
|
|
975
|
+
await this.approvals.approve(runId, ctx.auth.subject);
|
|
976
|
+
// approvalRecord is present immediately after approve for this run id.
|
|
977
|
+
const record = (await this.approvals.approvalRecord(runId));
|
|
978
|
+
return { ok: true, record };
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Shared pipeline core: resolve the spike stages from disk (paraphrase
|
|
983
|
+
* fallback), run the sequential dispatch loop inside one server-allocated
|
|
984
|
+
* ephemeral workspace with guaranteed teardown (SEC-4), record cost, and return
|
|
985
|
+
* the combined artifact. Run-record lifecycle is the CALLER's concern so the
|
|
986
|
+
* sync (`executePipeline`) and async (`runToCompletion`) paths share this body.
|
|
987
|
+
*/
|
|
988
|
+
async runPipelineCore(tenantId, request, personaRoots) {
|
|
989
|
+
const stages = [];
|
|
990
|
+
for (const role of SPIKE_PIPELINE_ROLES) {
|
|
991
|
+
const persona = resolvePersonaForRole(role, personaRoots);
|
|
992
|
+
if (!persona) {
|
|
993
|
+
return { outcome: "denied", reason: "role_not_embedded_in_thin_slice" };
|
|
994
|
+
}
|
|
995
|
+
stages.push(persona);
|
|
996
|
+
}
|
|
997
|
+
// SEC-4 — server-allocated, per-tenant, isolated workspace with guaranteed teardown.
|
|
998
|
+
const workspace = await this.workspaceManager.allocate(tenantId);
|
|
999
|
+
try {
|
|
1000
|
+
const pipeline = await runPipeline(stages, request, { backend: this.backend });
|
|
1001
|
+
// Persist the combined artifact INSIDE the isolated workspace, then read it back.
|
|
1002
|
+
const artifactPath = workspace.resolve("artifact.md");
|
|
1003
|
+
await writeFile(artifactPath, pipeline.artifact, "utf8");
|
|
1004
|
+
const artifact = await readFile(artifactPath, "utf8");
|
|
1005
|
+
for (const usage of pipeline.usage) {
|
|
1006
|
+
if (usage.estimatedCostUsd) {
|
|
1007
|
+
this.quota.recordCostUsd(tenantId, usage.estimatedCostUsd);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
return {
|
|
1011
|
+
outcome: "completed",
|
|
1012
|
+
artifact,
|
|
1013
|
+
workspaceRoot: workspace.root,
|
|
1014
|
+
backendId: pipeline.stages.at(-1)?.backendId,
|
|
1015
|
+
usage: pipeline.usage.at(-1),
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
finally {
|
|
1019
|
+
// SEC-4 — teardown runs even on error/timeout.
|
|
1020
|
+
await workspace.dispose();
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|