@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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +46 -0
  3. package/README.md +233 -0
  4. package/dist/src/auth/entra.js +164 -0
  5. package/dist/src/auth/jose-verifier.js +31 -0
  6. package/dist/src/auth/scopes.js +240 -0
  7. package/dist/src/catalog/catalog.js +80 -0
  8. package/dist/src/config/operator-config.js +281 -0
  9. package/dist/src/engine/advisory-pipeline.js +367 -0
  10. package/dist/src/engine/advisory-run-store.js +31 -0
  11. package/dist/src/engine/artifact-store.js +165 -0
  12. package/dist/src/engine/auto-memory.js +207 -0
  13. package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
  14. package/dist/src/engine/backends/azure-openai.js +69 -0
  15. package/dist/src/engine/backends/azure-table-run-state.js +319 -0
  16. package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
  17. package/dist/src/engine/backends/file-squad-memory.js +208 -0
  18. package/dist/src/engine/backends/graph-squad-memory.js +271 -0
  19. package/dist/src/engine/backends/managed-identity-credential.js +33 -0
  20. package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
  21. package/dist/src/engine/backlog-contract.js +200 -0
  22. package/dist/src/engine/business-tools.js +118 -0
  23. package/dist/src/engine/consumption.js +134 -0
  24. package/dist/src/engine/coordinator-engine.js +1 -0
  25. package/dist/src/engine/council.js +204 -0
  26. package/dist/src/engine/delegated.js +190 -0
  27. package/dist/src/engine/dispatch-loop.js +84 -0
  28. package/dist/src/engine/durable-run-state.js +251 -0
  29. package/dist/src/engine/embedded-prompt.js +35 -0
  30. package/dist/src/engine/embedded-roles.js +133 -0
  31. package/dist/src/engine/embedded.js +1023 -0
  32. package/dist/src/engine/federation.js +96 -0
  33. package/dist/src/engine/field-cipher.js +84 -0
  34. package/dist/src/engine/gates.js +241 -0
  35. package/dist/src/engine/markdown-table.js +43 -0
  36. package/dist/src/engine/model-backend.js +16 -0
  37. package/dist/src/engine/persona-loader.js +132 -0
  38. package/dist/src/engine/persona.js +287 -0
  39. package/dist/src/engine/profiles.js +237 -0
  40. package/dist/src/engine/render/pptx-render-service.js +60 -0
  41. package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
  42. package/dist/src/engine/render/render-backend.js +25 -0
  43. package/dist/src/engine/render-embedded.js +69 -0
  44. package/dist/src/engine/routing.js +275 -0
  45. package/dist/src/engine/run-params.js +70 -0
  46. package/dist/src/engine/run-state.js +132 -0
  47. package/dist/src/engine/run-worker.js +60 -0
  48. package/dist/src/engine/squad-history.js +136 -0
  49. package/dist/src/engine/squad-ledger.js +215 -0
  50. package/dist/src/engine/squad-memory-resources.js +218 -0
  51. package/dist/src/engine/squad-memory-state.js +57 -0
  52. package/dist/src/engine/squad-run-recorder.js +212 -0
  53. package/dist/src/engine/targeted-squad-memory.js +94 -0
  54. package/dist/src/engine/workspace.js +68 -0
  55. package/dist/src/observability/logger.js +75 -0
  56. package/dist/src/observability/redact.js +77 -0
  57. package/dist/src/paths.js +108 -0
  58. package/dist/src/router/router.js +88 -0
  59. package/dist/src/server-http.js +304 -0
  60. package/dist/src/server.js +237 -0
  61. package/dist/src/transports/http-core.js +1240 -0
  62. package/dist/src/transports/http.js +90 -0
  63. package/dist/src/transports/session-store.js +78 -0
  64. package/dist/src/transports/stdio.js +12 -0
  65. package/dist/src/worker-main.js +87 -0
  66. package/generated/copilot-studio-connector/README.md +44 -0
  67. package/generated/copilot-studio-connector/agent-instructions.md +90 -0
  68. package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
  69. package/generated/copilot-studio-connector/apiProperties.json +35 -0
  70. package/generated/copilot-studio-connector/connector.manifest.json +86 -0
  71. package/generated/mcp-tools.schema.json +462 -0
  72. package/package.json +61 -0
  73. package/tools.catalog.yml +397 -0
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Per-tool authorization scopes (SEC-2).
3
+ *
4
+ * Each coarse `squad_*` tool requires an explicit OAuth scope; absent the scope
5
+ * the call is denied (default-deny). The scope model is defined now — for ALL
6
+ * five tools — even though the thin slice only exposes the hero tools, so that
7
+ * `squad_run` is already gated the moment its embedded wiring lands in Phase 1b
8
+ * without revisiting the authorization model.
9
+ *
10
+ * Scopes are expressed as the short scope name a Copilot Studio / Entra app
11
+ * registration grants (the resource server's exposed API scopes). The audience
12
+ * binding (RFC 8707) is enforced separately in `entra.ts`; this map only answers
13
+ * "which scope does THIS tool require".
14
+ */
15
+ /** The OAuth scope a given tool requires to be invoked. */
16
+ export const TOOL_SCOPES = {
17
+ squad_research: "Squad.Research",
18
+ squad_review: "Squad.Review",
19
+ squad_plan: "Squad.Plan",
20
+ squad_architect: "Squad.Architect",
21
+ // squad_run carries the gated pipeline; its scope exists now so the gate is
22
+ // enforced as soon as the tool is wired (Phase 1b), never retrofitted.
23
+ squad_run: "Squad.Run",
24
+ // squad_federate is the federation meta layer (routes across named sub-squads).
25
+ // It is the SAME safety class as squad_run (catch-all + gates), so it carries a
26
+ // dedicated scope rather than reusing Squad.Run: a caller authorized to run one
27
+ // squad is not thereby authorized to drive a whole federation.
28
+ squad_federate: "Squad.Federate",
29
+ // squad_status polls a run the caller started; it reuses the Squad.Run scope
30
+ // (you may inspect runs you are authorized to start).
31
+ squad_status: "Squad.Run",
32
+ // squad_render_pptx is a deterministic file-output utility (content YAML -> a
33
+ // .pptx download link). It carries its own least-privilege scope so a render
34
+ // grant does not imply research/plan/run. Fail-closed like every other tool.
35
+ squad_render_pptx: "Squad.Render",
36
+ // squad_memory_read exposes the project's own `.copilot-tracking/squad/` memory
37
+ // + history over the MCP resource read surface. It carries a dedicated,
38
+ // least-privilege READ scope so a memory grant never implies research/plan/run
39
+ // (and never the write scope below). Fail-closed like every other tool.
40
+ squad_memory_read: "Squad.Memory",
41
+ // squad_memory_write is the compare-and-swap write-back tool for the same
42
+ // memory. Its scope is SEPARATE from the read scope so a caller that may read
43
+ // memory (Squad.Memory) still cannot mutate it without Squad.MemoryWrite.
44
+ squad_memory_write: "Squad.MemoryWrite",
45
+ // squad_memory_sync is the BATCH compare-and-swap write-back tool (WI-02): it
46
+ // flushes several memory entries in one call, each under its own CAS. It reuses
47
+ // the SAME Squad.MemoryWrite scope as squad_memory_write (a batch write is still
48
+ // a write — no new scope), so a caller that may write one entry may flush many.
49
+ squad_memory_sync: "Squad.MemoryWrite",
50
+ // squad_history browses the persisted `.copilot-tracking` tree a run produced
51
+ // — the artifact side of the same project the memory tools expose. Reading a
52
+ // run's own output is a READ of that project, so it reuses Squad.Memory rather
53
+ // than minting a scope an operator would have to grant twice for one capability.
54
+ squad_history: "Squad.Memory",
55
+ // squad_business_plan is the business-facing advisory tool (a single embedded
56
+ // dispatch producing a sectioned business plan). Least-privilege: a business
57
+ // grant never implies research/plan/run.
58
+ squad_business_plan: "Squad.Business",
59
+ // squad_backlog produces the STRUCTURED (JSON) backlog contract a Copilot Studio
60
+ // agent loops into the native ADO/Jira connector. Separate scope from
61
+ // Squad.Business so a backlog grant is independently revocable.
62
+ squad_backlog: "Squad.Backlog",
63
+ };
64
+ /**
65
+ * The distinct, high-privilege OPERATOR scope required to release a held run
66
+ * through the out-of-band approval endpoint (`POST /admin/approve`). It is
67
+ * deliberately NOT a member of {@link TOOL_SCOPES} — releasing a Human Gate is an
68
+ * operator action, not a squad tool a caller invokes — and it is separate from
69
+ * `Squad.Run` so a caller that may START or POLL a run (Squad.Run) still cannot
70
+ * APPROVE one. Grant it as an Entra app role (application permission) to the
71
+ * human/service principal that operates the deployment; the authenticator merges
72
+ * `roles[]` into the resolved scopes, so the same check covers a delegated scope
73
+ * or an app role. Never derivable from caller `request`/`context` or model output
74
+ * (SEC-6): the only code path that checks it is the admin route.
75
+ */
76
+ export const OPERATOR_APPROVAL_SCOPE = "Squad.Operate";
77
+ /**
78
+ * The two ORIGINAL hero tools from the thin slice. Kept as a named constant for
79
+ * legacy references; the authoritative remote-exposure set is
80
+ * {@link REMOTE_EXPOSED_TOOLS} / {@link isRemotelyExposed}, which (since Phase 5)
81
+ * also projects `squad_plan` and `squad_architect` into the Copilot Studio
82
+ * connector as advisory tools.
83
+ */
84
+ export const THIN_SLICE_HERO_TOOLS = ["squad_research", "squad_review"];
85
+ /**
86
+ * The ADVISORY tools exposed over the remote (HTTP) boundary in BOTH postures
87
+ * (Phase 5). The original hero tools (`squad_research`, `squad_review`) plus the
88
+ * advisory hero-style tools (`squad_plan`, `squad_architect`) that were formerly
89
+ * delegated-only. Each runs a SINGLE-STAGE embedded advisory dispatch and lands
90
+ * NO impactful action, so — like the hero tools — it is exposed even when the
91
+ * gated async pipeline is disabled, and follows the same audience/scope/origin/
92
+ * tenant rules. The gated async pipeline (`squad_run`/`squad_status`) is NOT here;
93
+ * it is gated separately behind {@link REMOTE_EXPOSED_TOOLS} + `pipelineExposed`.
94
+ */
95
+ export const ADVISORY_EXPOSED_TOOLS = [
96
+ "squad_research",
97
+ "squad_review",
98
+ "squad_plan",
99
+ "squad_architect",
100
+ ];
101
+ /**
102
+ * The tools reachable over the remote (HTTP) boundary when the operator has
103
+ * enabled the gated pipeline (Phase 5): the advisory surface
104
+ * ({@link ADVISORY_EXPOSED_TOOLS}) plus the gated async pipeline `squad_run` and
105
+ * the `squad_status` poll utility. `squad_run` is exposed but SAFE BY
106
+ * CONSTRUCTION — it holds at the Human Gate and never auto-releases, so exposure
107
+ * does not bypass a gate. The advisory tools carry no impactful action; `squad_run`
108
+ * carries the full advisory pipeline behind the existing non-bypassable hold.
109
+ */
110
+ export const REMOTE_EXPOSED_TOOLS = [
111
+ ...ADVISORY_EXPOSED_TOOLS,
112
+ "squad_run",
113
+ "squad_status",
114
+ // squad_federate is the federation meta layer. It is deliberately here (the
115
+ // pipeline-gated set) and NOT in ADVISORY_EXPOSED_TOOLS: like squad_run it is a
116
+ // catch-all with `gates: true`, so it must inherit the same non-bypassable Human
117
+ // Gate + durable run-state prerequisites rather than run as a synchronous
118
+ // advisory call. Exposing it in the advisory-only posture would create a gated
119
+ // tool with no durable approval channel behind it (HIGH-1).
120
+ "squad_federate",
121
+ ];
122
+ /** Resolve the required scope for a tool id, or `undefined` if unknown. */
123
+ export function requiredScopeFor(toolId) {
124
+ return TOOL_SCOPES[toolId];
125
+ }
126
+ /** True when the tool is exposed over the remote (HTTP) boundary in the thin slice. */
127
+ export function isHeroTool(toolId) {
128
+ return THIN_SLICE_HERO_TOOLS.includes(toolId);
129
+ }
130
+ /**
131
+ * True when the tool is an ADVISORY tool exposed over the remote boundary in
132
+ * BOTH postures (Phase 5): the hero tools plus `squad_plan` / `squad_architect`.
133
+ * These are exposed even when the gated async pipeline is disabled.
134
+ */
135
+ export function isAdvisoryExposed(toolId) {
136
+ return ADVISORY_EXPOSED_TOOLS.includes(toolId);
137
+ }
138
+ /** True when the tool is reachable over the remote (HTTP) boundary (Phase 1b.4). */
139
+ export function isRemotelyExposed(toolId) {
140
+ return REMOTE_EXPOSED_TOOLS.includes(toolId);
141
+ }
142
+ /** The synthetic status-poll utility tool id (not a squad routing intent). */
143
+ export const SQUAD_STATUS_TOOL = "squad_status";
144
+ /**
145
+ * The synthetic deterministic render tool id (not a squad routing intent, so it
146
+ * is not in `tools.catalog.yml` and does not participate in the generator drift
147
+ * check — the same posture as {@link SQUAD_STATUS_TOOL}). It is a transport-level
148
+ * utility that renders deck content YAML to a `.pptx` and returns a short-lived
149
+ * download link. Exposed only when the operator enables the render feature.
150
+ */
151
+ export const SQUAD_RENDER_PPTX_TOOL = "squad_render_pptx";
152
+ /**
153
+ * The synthetic memory READ tool id (not a squad routing intent, so it is not in
154
+ * `tools.catalog.yml` and does not participate in the generator drift check — the
155
+ * same posture as {@link SQUAD_STATUS_TOOL} / {@link SQUAD_RENDER_PPTX_TOOL}). It
156
+ * backs the shared-state broker's read surface; exposed only when the operator
157
+ * enables the memory feature (`SQUAD_MCP_ENABLE_MEMORY`).
158
+ */
159
+ export const SQUAD_MEMORY_READ_TOOL = "squad_memory_read";
160
+ /**
161
+ * The synthetic HISTORY tool id — list and read the `.copilot-tracking` tree a
162
+ * run wrote. Same synthetic posture as the memory tools above: it is not a squad
163
+ * routing intent, so it is not in the catalog and is exempt from the drift check.
164
+ */
165
+ export const SQUAD_HISTORY_TOOL = "squad_history";
166
+ /**
167
+ * The synthetic memory WRITE tool id — the compare-and-swap write-back tool for
168
+ * the shared-state broker. Same synthetic posture as the read tool above; exposed
169
+ * only when the operator enables the memory feature.
170
+ */
171
+ export const SQUAD_MEMORY_WRITE_TOOL = "squad_memory_write";
172
+ /**
173
+ * The synthetic memory SYNC tool id — the BATCH compare-and-swap write-back tool
174
+ * (WI-02). It flushes an array of `.copilot-tracking/squad/` entries in one call,
175
+ * each applied under its own CAS token, so a delegated host can persist a whole
176
+ * run's artifacts after the fact. Same synthetic posture and feature-gating as
177
+ * the read/write tools above, and it reuses the existing {@link SQUAD_MEMORY_WRITE_TOOL}
178
+ * scope (Squad.MemoryWrite) — a batch write is still a write, so no new scope.
179
+ */
180
+ export const SQUAD_MEMORY_SYNC_TOOL = "squad_memory_sync";
181
+ /**
182
+ * The memory broker tools exposed over the remote (HTTP) boundary WHEN the
183
+ * operator enables the memory feature. Unlike {@link ADVISORY_EXPOSED_TOOLS},
184
+ * membership here does NOT imply exposure by construction: the feature is
185
+ * off-by-default and gated at runtime by the `enableMemory` operator flag, so a
186
+ * caller reaches these tools only when the broker is explicitly turned on AND a
187
+ * backing store is configured. Kept out of the advisory/remote sets so the
188
+ * default posture (advisory-only) is unchanged.
189
+ */
190
+ export const MEMORY_EXPOSED_TOOLS = new Set([
191
+ SQUAD_MEMORY_READ_TOOL,
192
+ SQUAD_MEMORY_WRITE_TOOL,
193
+ SQUAD_MEMORY_SYNC_TOOL,
194
+ SQUAD_HISTORY_TOOL,
195
+ ]);
196
+ /**
197
+ * True when the tool is a memory broker tool. This is a CLASSIFICATION predicate
198
+ * only — it says the tool belongs to the memory feature, not that it is currently
199
+ * reachable. The caller gates actual exposure on the operator flag
200
+ * (`enableMemory`), mirroring how the render tool is gated on `enableRenderPptx`.
201
+ */
202
+ export function isMemoryExposed(toolId) {
203
+ return MEMORY_EXPOSED_TOOLS.has(toolId);
204
+ }
205
+ /** The federation meta tool id (a catalog tool, unlike the synthetic ids above). */
206
+ export const SQUAD_FEDERATE_TOOL = "squad_federate";
207
+ /**
208
+ * The synthetic BUSINESS-PLAN tool id. Like {@link SQUAD_RENDER_PPTX_TOOL} it is a
209
+ * transport-level tool rather than a squad routing intent, so it is NOT in
210
+ * `tools.catalog.yml` and does not participate in the generator drift check. It
211
+ * runs ONE embedded advisory dispatch against a real cast persona and returns a
212
+ * sectioned business plan — advisory text only, no impactful action.
213
+ */
214
+ export const SQUAD_BUSINESS_PLAN_TOOL = "squad_business_plan";
215
+ /**
216
+ * The synthetic STRUCTURED-BACKLOG tool id. Same synthetic posture as
217
+ * {@link SQUAD_BUSINESS_PLAN_TOOL}, but its result is a VALIDATED JSON backlog
218
+ * contract (epics → stories → tasks plus a flattened `workItems[]`) that a Copilot
219
+ * Studio agent loops one-per-item into the NATIVE Azure DevOps / Jira connector.
220
+ * This server still performs no ADO/Jira write of its own (ADR-0001 trust
221
+ * boundary); it only produces the plan the certified connector executes.
222
+ */
223
+ export const SQUAD_BACKLOG_TOOL = "squad_backlog";
224
+ /**
225
+ * The business-facing tools exposed over the remote boundary WHEN the operator
226
+ * enables the business feature. Like {@link MEMORY_EXPOSED_TOOLS}, membership is a
227
+ * CLASSIFICATION only — actual exposure is gated at runtime on the
228
+ * `enableBusinessTools` operator flag, so the default posture is unchanged.
229
+ */
230
+ export const BUSINESS_EXPOSED_TOOLS = new Set([
231
+ SQUAD_BUSINESS_PLAN_TOOL,
232
+ SQUAD_BACKLOG_TOOL,
233
+ ]);
234
+ /**
235
+ * True when the tool belongs to the business-user feature. CLASSIFICATION only —
236
+ * the caller gates reachability on the operator flag (`enableBusinessTools`).
237
+ */
238
+ export function isBusinessExposed(toolId) {
239
+ return BUSINESS_EXPOSED_TOOLS.has(toolId);
240
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Tool catalog loader and types.
3
+ *
4
+ * `tools.catalog.yml` is the single source of truth for the public tool
5
+ * surface. This module parses it into typed `CatalogTool` records and performs
6
+ * lightweight structural validation (the deeper catalog<->cast drift check
7
+ * lives in the generator, `generators/build-manifests.ts`).
8
+ */
9
+ import { readFileSync } from "node:fs";
10
+ import { parse as parseYaml } from "yaml";
11
+ import { catalogPath } from "../paths.js";
12
+ function asStringArray(value) {
13
+ if (value === undefined || value === null) {
14
+ return [];
15
+ }
16
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
17
+ throw new Error("Expected an array of strings.");
18
+ }
19
+ return value;
20
+ }
21
+ function normalizeTool(raw, index) {
22
+ if (typeof raw !== "object" || raw === null) {
23
+ throw new Error(`tools[${index}] is not an object.`);
24
+ }
25
+ const t = raw;
26
+ const id = t.id;
27
+ if (typeof id !== "string" || id.length === 0) {
28
+ throw new Error(`tools[${index}].id is required and must be a non-empty string.`);
29
+ }
30
+ if (typeof t.routingIntent !== "string" || t.routingIntent.length === 0) {
31
+ throw new Error(`tool "${id}": routingIntent is required.`);
32
+ }
33
+ if (typeof t.role !== "string" || t.role.length === 0) {
34
+ throw new Error(`tool "${id}": role is required.`);
35
+ }
36
+ if (typeof t.input !== "object" || t.input === null) {
37
+ throw new Error(`tool "${id}": input JSON Schema is required.`);
38
+ }
39
+ return {
40
+ id,
41
+ title: typeof t.title === "string" ? t.title : id,
42
+ description: typeof t.description === "string" ? t.description : "",
43
+ routingIntent: t.routingIntent,
44
+ role: t.role,
45
+ tier: typeof t.tier === "string" ? t.tier : "confirm",
46
+ parallelEligible: t.parallelEligible === true,
47
+ catchAll: t.catchAll === true,
48
+ gates: t.gates === true,
49
+ council: asStringArray(t.council),
50
+ councilIntent: typeof t.councilIntent === "string" ? t.councilIntent : undefined,
51
+ councilTier: typeof t.councilTier === "string" ? t.councilTier : undefined,
52
+ input: t.input,
53
+ };
54
+ }
55
+ /** Parse a catalog from a YAML string. */
56
+ export function parseCatalog(yamlText) {
57
+ const raw = parseYaml(yamlText);
58
+ if (typeof raw !== "object" || raw === null) {
59
+ throw new Error("tools.catalog.yml did not parse to an object.");
60
+ }
61
+ if (!Array.isArray(raw.tools) || raw.tools.length === 0) {
62
+ throw new Error("tools.catalog.yml must define a non-empty `tools` array.");
63
+ }
64
+ const tools = raw.tools.map((tool, index) => normalizeTool(tool, index));
65
+ const ids = new Set();
66
+ for (const tool of tools) {
67
+ if (ids.has(tool.id)) {
68
+ throw new Error(`Duplicate tool id "${tool.id}" in catalog.`);
69
+ }
70
+ ids.add(tool.id);
71
+ }
72
+ return {
73
+ schemaVersion: typeof raw.schemaVersion === "string" ? raw.schemaVersion : "0.0.0",
74
+ tools,
75
+ };
76
+ }
77
+ /** Load and parse the authored catalog from disk. */
78
+ export function loadCatalog(path = catalogPath()) {
79
+ return parseCatalog(readFileSync(path, "utf8"));
80
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Operator configuration (server-controlled; never caller-influenced).
3
+ *
4
+ * Every value here is set by the OPERATOR who deploys the server (environment
5
+ * variables sourced from the Container App config + Key Vault). None of it is
6
+ * ever taken from a tool input or request body. This separation is load-bearing
7
+ * for several council conditions:
8
+ *
9
+ * * SEC-3 — the Azure OpenAI endpoint is operator-configured and validated
10
+ * against an allow-list, so a caller can never redirect inference to an
11
+ * attacker-controlled endpoint.
12
+ * * SEC-8 — the Origin allow-list is operator-configured (never `*`).
13
+ * * SEC-1 — the expected token audience (RFC 8707 resource indicator) is
14
+ * operator-configured.
15
+ * * SEC-9 / COST-1 / COST-2 — per-tenant concurrency and the hard monthly
16
+ * cost ceiling default here.
17
+ *
18
+ * Secrets (model API key, if used instead of managed identity) are NOT part of
19
+ * this object; they are fetched on demand from Key Vault by the credential
20
+ * provider and registered with the logger for redaction.
21
+ */
22
+ /** The hard monthly cost ceiling per tenant (COST-2), default ~$500. */
23
+ export const DEFAULT_TENANT_MONTHLY_COST_CEILING_USD = 500;
24
+ /** Default per-tenant concurrency cap (SEC-9 / COST-1). */
25
+ export const DEFAULT_TENANT_CONCURRENCY = 4;
26
+ /** Default idle timeout (ms) after which a session id is forgotten (SEC-8). */
27
+ export const DEFAULT_SESSION_IDLE_MS = 5 * 60 * 1000;
28
+ function splitList(value) {
29
+ if (!value) {
30
+ return [];
31
+ }
32
+ return value
33
+ .split(",")
34
+ .map((item) => item.trim())
35
+ .filter((item) => item.length > 0);
36
+ }
37
+ function numberOr(value, fallback) {
38
+ if (value === undefined || value.trim().length === 0) {
39
+ return fallback;
40
+ }
41
+ const parsed = Number(value);
42
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
43
+ }
44
+ /** Parse the memory backend selector; anything unrecognized falls back to `file`. */
45
+ function parseMemoryBackend(value) {
46
+ const normalized = (value ?? "file").trim().toLowerCase();
47
+ return normalized === "table" || normalized === "graph" ? normalized : "file";
48
+ }
49
+ /** Target-name shape: the opaque selector a caller may pass. */
50
+ const MEMORY_TARGET_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
51
+ /**
52
+ * Parse `SQUAD_MCP_MEMORY_TARGETS` — a JSON array of operator-declared memory
53
+ * destinations. Empty / unset means "one destination", and the `target` input is
54
+ * ignored. Every entry is validated here so a malformed deployment fails at BOOT
55
+ * rather than on the first caller-selected write.
56
+ */
57
+ function parseMemoryTargets(value) {
58
+ const raw = (value ?? "").trim();
59
+ if (raw.length === 0) {
60
+ return [];
61
+ }
62
+ let parsed;
63
+ try {
64
+ parsed = JSON.parse(raw);
65
+ }
66
+ catch {
67
+ throw new Error("SQUAD_MCP_MEMORY_TARGETS must be a JSON array of memory destinations.");
68
+ }
69
+ if (!Array.isArray(parsed)) {
70
+ throw new Error("SQUAD_MCP_MEMORY_TARGETS must be a JSON array of memory destinations.");
71
+ }
72
+ const seen = new Set();
73
+ return parsed.map((entry, index) => {
74
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
75
+ throw new Error(`SQUAD_MCP_MEMORY_TARGETS[${index}] must be an object.`);
76
+ }
77
+ const record = entry;
78
+ const name = typeof record.name === "string" ? record.name.trim() : "";
79
+ if (!MEMORY_TARGET_NAME.test(name)) {
80
+ throw new Error(`SQUAD_MCP_MEMORY_TARGETS[${index}].name must be lower-kebab-case (it is the caller-facing selector).`);
81
+ }
82
+ if (seen.has(name)) {
83
+ throw new Error(`SQUAD_MCP_MEMORY_TARGETS has a duplicate target name "${name}".`);
84
+ }
85
+ seen.add(name);
86
+ const backend = parseMemoryBackend(typeof record.backend === "string" ? record.backend : undefined);
87
+ const target = { name, backend };
88
+ if (typeof record.dir === "string")
89
+ target.dir = record.dir.trim();
90
+ if (typeof record.storageAccount === "string")
91
+ target.storageAccount = record.storageAccount.trim();
92
+ if (typeof record.tableName === "string")
93
+ target.tableName = record.tableName.trim();
94
+ if (typeof record.driveId === "string")
95
+ target.driveId = record.driveId.trim();
96
+ if (typeof record.rootPath === "string")
97
+ target.rootPath = record.rootPath.trim();
98
+ if (typeof record.endpoint === "string")
99
+ target.endpoint = record.endpoint.trim();
100
+ target.encrypt = record.encrypt === true;
101
+ // Per-backend prerequisites, checked at boot (mirrors the HIGH-1 pattern).
102
+ if (backend === "file" && !target.dir) {
103
+ throw new Error(`SQUAD_MCP_MEMORY_TARGETS["${name}"] (file) requires "dir".`);
104
+ }
105
+ if (backend === "graph" && !target.driveId) {
106
+ throw new Error(`SQUAD_MCP_MEMORY_TARGETS["${name}"] (graph) requires "driveId".`);
107
+ }
108
+ return target;
109
+ });
110
+ }
111
+ /**
112
+ * Build the operator config from a (typically `process.env`) record. Throws when
113
+ * a hard-required value is missing or self-inconsistent so a misconfigured
114
+ * deployment fails fast at boot rather than at first call.
115
+ */
116
+ export function loadOperatorConfig(env = process.env) {
117
+ const audience = (env.SQUAD_MCP_AUDIENCE ?? "").trim();
118
+ if (audience.length === 0) {
119
+ throw new Error("SQUAD_MCP_AUDIENCE is required (the resource-server token audience; SEC-1).");
120
+ }
121
+ const allowedOrigins = splitList(env.SQUAD_MCP_ALLOWED_ORIGINS);
122
+ if (allowedOrigins.includes("*")) {
123
+ throw new Error("SQUAD_MCP_ALLOWED_ORIGINS must not contain '*' (SEC-8: strict Origin allow-list).");
124
+ }
125
+ const allowedModelEndpoints = splitList(env.SQUAD_MCP_ALLOWED_MODEL_ENDPOINTS);
126
+ const modelEndpoint = (env.SQUAD_MCP_MODEL_ENDPOINT ?? "").trim();
127
+ if (modelEndpoint.length > 0 && !allowedModelEndpoints.includes(modelEndpoint)) {
128
+ throw new Error("SQUAD_MCP_MODEL_ENDPOINT must be present in SQUAD_MCP_ALLOWED_MODEL_ENDPOINTS (SEC-3: endpoint allow-list).");
129
+ }
130
+ const remotePipelineEnabled = (env.SQUAD_MCP_REMOTE_PIPELINE_ENABLED ?? "").trim().toLowerCase() === "true";
131
+ const runStateBackend = (env.SQUAD_MCP_RUN_STATE_BACKEND ?? "file").trim().toLowerCase() === "table" ? "table" : "file";
132
+ const runStateDir = (env.SQUAD_MCP_RUN_STATE_DIR ?? "").trim();
133
+ const storageAccount = (env.SQUAD_MCP_STORAGE_ACCOUNT ?? "").trim();
134
+ const runTableName = (env.SQUAD_MCP_RUN_TABLE_NAME ?? "squadruns").trim();
135
+ const workerEnabled = (env.SQUAD_MCP_WORKER_ENABLED ?? "").trim().toLowerCase() === "true";
136
+ if (remotePipelineEnabled && runStateBackend === "file" && runStateDir.length === 0) {
137
+ throw new Error("SQUAD_MCP_RUN_STATE_DIR is required when SQUAD_MCP_REMOTE_PIPELINE_ENABLED=true " +
138
+ "with the file backend (the async pipeline's held-run approval control must be " +
139
+ "backed by durable state; HIGH-1).");
140
+ }
141
+ if (remotePipelineEnabled && runStateBackend === "table" && storageAccount.length === 0) {
142
+ throw new Error("SQUAD_MCP_STORAGE_ACCOUNT is required when SQUAD_MCP_RUN_STATE_BACKEND=table " +
143
+ "(the cross-replica run-state + approval store; WI-06).");
144
+ }
145
+ if (workerEnabled && !remotePipelineEnabled) {
146
+ throw new Error("SQUAD_MCP_WORKER_ENABLED=true requires SQUAD_MCP_REMOTE_PIPELINE_ENABLED=true.");
147
+ }
148
+ if (workerEnabled && runStateBackend !== "table") {
149
+ throw new Error("SQUAD_MCP_WORKER_ENABLED=true requires SQUAD_MCP_RUN_STATE_BACKEND=table " +
150
+ "(the worker and web replicas must share cross-replica run state; WI-06 / WI-1b4-WORKER).");
151
+ }
152
+ const enableRenderPptx = (env.SQUAD_MCP_ENABLE_RENDER_PPTX ?? "").trim().toLowerCase() === "true";
153
+ const renderPythonPath = (env.SQUAD_MCP_RENDER_PYTHON_PATH ?? "").trim();
154
+ const renderScriptsDir = (env.SQUAD_MCP_RENDER_SCRIPTS_DIR ?? "").trim();
155
+ if (enableRenderPptx && storageAccount.length === 0) {
156
+ throw new Error("SQUAD_MCP_STORAGE_ACCOUNT is required when SQUAD_MCP_ENABLE_RENDER_PPTX=true " +
157
+ "(the rendered deck is uploaded to a tenant-scoped Blob container).");
158
+ }
159
+ if (enableRenderPptx && (renderPythonPath.length === 0 || renderScriptsDir.length === 0)) {
160
+ throw new Error("SQUAD_MCP_RENDER_PYTHON_PATH and SQUAD_MCP_RENDER_SCRIPTS_DIR are required when " +
161
+ "SQUAD_MCP_ENABLE_RENDER_PPTX=true (the in-image python-pptx build step).");
162
+ }
163
+ const enableMemory = (env.SQUAD_MCP_ENABLE_MEMORY ?? "").trim().toLowerCase() === "true";
164
+ const memoryBackend = parseMemoryBackend(env.SQUAD_MCP_MEMORY_BACKEND);
165
+ const memoryTableName = (env.SQUAD_MCP_MEMORY_TABLE_NAME ?? "squadmemory").trim();
166
+ const memoryDir = (env.SQUAD_MCP_MEMORY_DIR ?? "").trim();
167
+ const memoryGraphDriveId = (env.SQUAD_MCP_MEMORY_GRAPH_DRIVE_ID ?? "").trim();
168
+ const memoryGraphRootPath = (env.SQUAD_MCP_MEMORY_GRAPH_ROOT_PATH ?? "").trim();
169
+ const memoryGraphEndpoint = (env.SQUAD_MCP_MEMORY_GRAPH_ENDPOINT ?? "").trim();
170
+ const memoryGraphEncrypt = (env.SQUAD_MCP_MEMORY_GRAPH_ENCRYPT ?? "").trim().toLowerCase() === "true";
171
+ if (enableMemory && memoryBackend === "table" && storageAccount.length === 0) {
172
+ throw new Error("SQUAD_MCP_STORAGE_ACCOUNT is required when SQUAD_MCP_ENABLE_MEMORY=true " +
173
+ "with the table backend (the cross-replica, tenant-isolated memory store).");
174
+ }
175
+ if (enableMemory && memoryBackend === "file" && memoryDir.length === 0) {
176
+ throw new Error("SQUAD_MCP_MEMORY_DIR is required when SQUAD_MCP_ENABLE_MEMORY=true " +
177
+ "with the file backend (the directory backing the local memory store).");
178
+ }
179
+ if (enableMemory && memoryBackend === "graph" && memoryGraphDriveId.length === 0) {
180
+ throw new Error("SQUAD_MCP_MEMORY_GRAPH_DRIVE_ID is required when SQUAD_MCP_MEMORY_BACKEND=graph " +
181
+ "(the SharePoint document library / OneDrive drive that holds squad memory).");
182
+ }
183
+ const memoryTargets = parseMemoryTargets(env.SQUAD_MCP_MEMORY_TARGETS);
184
+ const memoryDefaultTarget = (env.SQUAD_MCP_MEMORY_DEFAULT_TARGET ?? "").trim();
185
+ if (memoryTargets.length > 0) {
186
+ if (!enableMemory) {
187
+ throw new Error("SQUAD_MCP_MEMORY_TARGETS requires SQUAD_MCP_ENABLE_MEMORY=true " +
188
+ "(named destinations decorate the shared-state memory store).");
189
+ }
190
+ if (memoryDefaultTarget.length === 0) {
191
+ throw new Error("SQUAD_MCP_MEMORY_DEFAULT_TARGET is required when SQUAD_MCP_MEMORY_TARGETS is set " +
192
+ "(a call that names no target must resolve deterministically).");
193
+ }
194
+ if (!memoryTargets.some((target) => target.name === memoryDefaultTarget)) {
195
+ throw new Error("SQUAD_MCP_MEMORY_DEFAULT_TARGET must name one of SQUAD_MCP_MEMORY_TARGETS.");
196
+ }
197
+ }
198
+ const memoryAutoEnabled = (env.SQUAD_MCP_MEMORY_AUTO_ENABLED ?? "").trim().toLowerCase() === "true";
199
+ if (memoryAutoEnabled && !enableMemory) {
200
+ throw new Error("SQUAD_MCP_MEMORY_AUTO_ENABLED=true requires SQUAD_MCP_ENABLE_MEMORY=true " +
201
+ "(automatic continuity reads and writes through the shared-state memory store).");
202
+ }
203
+ const memoryDefaultProject = (env.SQUAD_MCP_MEMORY_DEFAULT_PROJECT ?? "default").trim();
204
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(memoryDefaultProject)) {
205
+ throw new Error("SQUAD_MCP_MEMORY_DEFAULT_PROJECT must be lower-kebab-case (it is a store partition segment).");
206
+ }
207
+ const enableArtifacts = (env.SQUAD_MCP_ENABLE_ARTIFACTS ?? "").trim().toLowerCase() === "true";
208
+ if (enableArtifacts && !enableMemory) {
209
+ throw new Error("SQUAD_MCP_ENABLE_ARTIFACTS=true requires SQUAD_MCP_ENABLE_MEMORY=true " +
210
+ "(the squad ledger is written through the configured memory store).");
211
+ }
212
+ const advisoryAutopilotEnabled = (env.SQUAD_MCP_ADVISORY_AUTOPILOT_ENABLED ?? "").trim().toLowerCase() === "true";
213
+ if (advisoryAutopilotEnabled && !remotePipelineEnabled) {
214
+ throw new Error("SQUAD_MCP_ADVISORY_AUTOPILOT_ENABLED=true requires SQUAD_MCP_REMOTE_PIPELINE_ENABLED=true " +
215
+ "(there is no gated pipeline to release otherwise).");
216
+ }
217
+ const enableBusinessTools = (env.SQUAD_MCP_ENABLE_BUSINESS_TOOLS ?? "").trim().toLowerCase() === "true";
218
+ if (enableBusinessTools && modelEndpoint.length === 0) {
219
+ throw new Error("SQUAD_MCP_MODEL_ENDPOINT is required when SQUAD_MCP_ENABLE_BUSINESS_TOOLS=true " +
220
+ "(the business tools run a server-side advisory dispatch).");
221
+ }
222
+ const memoryOverflowEnabled = (env.SQUAD_MCP_MEMORY_OVERFLOW_ENABLED ?? "").trim().toLowerCase() === "true";
223
+ const memoryOverflowContainer = (env.SQUAD_MCP_MEMORY_OVERFLOW_CONTAINER ?? "").trim();
224
+ const memoryOverflowThresholdBytes = numberOr(env.SQUAD_MCP_MEMORY_OVERFLOW_THRESHOLD_BYTES, 32768);
225
+ if (memoryOverflowEnabled && !enableMemory) {
226
+ throw new Error("SQUAD_MCP_MEMORY_OVERFLOW_ENABLED=true requires SQUAD_MCP_ENABLE_MEMORY=true " +
227
+ "(the overflow channel decorates the shared-state memory store; WI-03).");
228
+ }
229
+ if (memoryOverflowEnabled && storageAccount.length === 0) {
230
+ throw new Error("SQUAD_MCP_STORAGE_ACCOUNT is required when SQUAD_MCP_MEMORY_OVERFLOW_ENABLED=true " +
231
+ "(the over-threshold memory payload is uploaded to a tenant-scoped Blob container; WI-03).");
232
+ }
233
+ if (memoryOverflowEnabled && memoryOverflowContainer.length === 0) {
234
+ throw new Error("SQUAD_MCP_MEMORY_OVERFLOW_CONTAINER is required when SQUAD_MCP_MEMORY_OVERFLOW_ENABLED=true " +
235
+ "(the Blob container holding the overflow payloads; WI-03).");
236
+ }
237
+ return {
238
+ audience,
239
+ allowedIssuers: splitList(env.SQUAD_MCP_ALLOWED_ISSUERS),
240
+ allowedTenants: splitList(env.SQUAD_MCP_ALLOWED_TENANTS),
241
+ allowedOrigins,
242
+ allowedModelEndpoints,
243
+ modelEndpoint,
244
+ modelDeployment: (env.SQUAD_MCP_MODEL_DEPLOYMENT ?? "").trim(),
245
+ modelApiVersion: (env.SQUAD_MCP_MODEL_API_VERSION ?? "2024-10-21").trim(),
246
+ tenantConcurrency: numberOr(env.SQUAD_MCP_TENANT_CONCURRENCY, DEFAULT_TENANT_CONCURRENCY),
247
+ tenantMonthlyCostCeilingUsd: numberOr(env.SQUAD_MCP_TENANT_COST_CEILING_USD, DEFAULT_TENANT_MONTHLY_COST_CEILING_USD),
248
+ sessionIdleMs: numberOr(env.SQUAD_MCP_SESSION_IDLE_MS, DEFAULT_SESSION_IDLE_MS),
249
+ remotePipelineEnabled,
250
+ advisoryAutopilotEnabled,
251
+ runStateDir,
252
+ runStateBackend,
253
+ storageAccount,
254
+ runTableName,
255
+ encryptionKeyBase64: (env.SQUAD_MCP_RUN_ENCRYPTION_KEY_B64 ?? "").trim(),
256
+ workerEnabled,
257
+ enableRenderPptx,
258
+ renderBlobContainer: (env.SQUAD_MCP_RENDER_BLOB_CONTAINER ?? "renders").trim(),
259
+ renderPythonPath,
260
+ renderScriptsDir,
261
+ renderBrandTemplatePath: (env.SQUAD_MCP_RENDER_BRAND_TEMPLATE_PATH ?? "").trim(),
262
+ renderSasTtlMinutes: numberOr(env.SQUAD_MCP_RENDER_SAS_TTL_MINUTES, 60),
263
+ enableMemory,
264
+ memoryBackend,
265
+ memoryTableName,
266
+ memoryDir,
267
+ memoryOverflowEnabled,
268
+ memoryOverflowContainer,
269
+ memoryOverflowThresholdBytes,
270
+ memoryAutoEnabled,
271
+ memoryDefaultProject,
272
+ enableArtifacts,
273
+ memoryGraphDriveId,
274
+ memoryGraphRootPath,
275
+ memoryGraphEndpoint,
276
+ memoryGraphEncrypt,
277
+ memoryTargets,
278
+ memoryDefaultTarget,
279
+ enableBusinessTools,
280
+ };
281
+ }