@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,75 @@
1
+ /**
2
+ * Redaction-aware logger (SEC-10).
3
+ *
4
+ * The ONLY logging path the remote/embedded code uses. Every line is scrubbed
5
+ * through {@link redactString} against the registered-secret set before it is
6
+ * written, so a token, model key, or downstream credential can never appear in
7
+ * a log — even if a caller accidentally interpolates one into a message.
8
+ *
9
+ * Logs go to **stderr** only. The stdio transport reserves stdout for the
10
+ * JSON-RPC protocol stream; the HTTP transport has no stdout protocol contract
11
+ * but keeping one sink keeps the contract uniform and avoids interleaving.
12
+ *
13
+ * The logger captures the secret set by reference; registering a secret after a
14
+ * sink is attached still scrubs it (the set is read at write time).
15
+ */
16
+ import { redactString, redactValue } from "./redact.js";
17
+ const LEVEL_ORDER = { debug: 10, info: 20, warn: 30, error: 40 };
18
+ /**
19
+ * A small structured logger. `fields` are JSON-serialized and scrubbed; the
20
+ * message string is scrubbed; the secret set is shared so a value registered
21
+ * anywhere is redacted everywhere.
22
+ */
23
+ export class RedactingLogger {
24
+ secrets = new Set();
25
+ level;
26
+ sink;
27
+ name;
28
+ constructor(options = {}) {
29
+ this.level = options.level ?? "info";
30
+ this.sink = options.sink ?? ((line) => process.stderr.write(`${line}\n`));
31
+ this.name = options.name ?? "hve-squad-mcp";
32
+ }
33
+ /**
34
+ * Register a secret value so every future (and concurrent) log line redacts
35
+ * it. Called at the trust boundary: the auth middleware registers the raw
36
+ * bearer token; the backend credential provider registers the model key.
37
+ */
38
+ registerSecret(value) {
39
+ if (typeof value === "string" && value.length >= 8) {
40
+ this.secrets.add(value);
41
+ }
42
+ }
43
+ /** The live secret set (read-only view) for ad-hoc scrubbing by callers. */
44
+ get secretSet() {
45
+ return this.secrets;
46
+ }
47
+ /** Scrub an arbitrary string with the current secret set. */
48
+ scrub(value) {
49
+ return redactString(value, this.secrets);
50
+ }
51
+ debug(message, fields) {
52
+ this.emit("debug", message, fields);
53
+ }
54
+ info(message, fields) {
55
+ this.emit("info", message, fields);
56
+ }
57
+ warn(message, fields) {
58
+ this.emit("warn", message, fields);
59
+ }
60
+ error(message, fields) {
61
+ this.emit("error", message, fields);
62
+ }
63
+ emit(level, message, fields) {
64
+ if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) {
65
+ return;
66
+ }
67
+ const scrubbedMessage = redactString(message, this.secrets);
68
+ let suffix = "";
69
+ if (fields && Object.keys(fields).length > 0) {
70
+ const scrubbedFields = redactValue(fields, this.secrets);
71
+ suffix = ` ${JSON.stringify(scrubbedFields)}`;
72
+ }
73
+ this.sink(`[${this.name}] ${level} ${scrubbedMessage}${suffix}`);
74
+ }
75
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Secret redaction (SEC-10).
3
+ *
4
+ * The single chokepoint that scrubs secret-shaped material out of any string
5
+ * before it can reach a log sink or a tool response. Two layers:
6
+ *
7
+ * 1. Registered secrets — exact values the server knows are sensitive (bearer
8
+ * tokens, model API keys, downstream tokens). Registered once at the trust
9
+ * boundary (auth middleware, backend credential provider) and never logged
10
+ * verbatim anywhere else.
11
+ * 2. Structural patterns — defense-in-depth for secret-shaped substrings that
12
+ * were never registered (JWTs, `Bearer` headers, `Authorization` headers,
13
+ * long high-entropy keys), so an un-registered leak is still caught.
14
+ *
15
+ * This module holds NO state of its own; the active secret set is owned by the
16
+ * logger so registration and scrubbing share one source of truth.
17
+ */
18
+ /** A redaction placeholder that never collides with real content. */
19
+ export const REDACTED = "[redacted]";
20
+ /**
21
+ * Structural patterns for secret-shaped substrings. Order matters: the broadest
22
+ * (whole `Authorization: Bearer ...` header) runs first so its inner token is
23
+ * already gone before the bare-JWT pass would have matched it.
24
+ */
25
+ const STRUCTURAL_PATTERNS = [
26
+ // `Authorization: Bearer <token>` (header form).
27
+ { label: "authorization-header", pattern: /\bauthorization\b\s*[:=]\s*bearer\s+[\w.\-+/=]+/gi },
28
+ // A bare `Bearer <token>`.
29
+ { label: "bearer", pattern: /\bbearer\s+[\w.\-+/=]+/gi },
30
+ // A JWT: three base64url segments separated by dots, starting `eyJ`.
31
+ { label: "jwt", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g },
32
+ // Azure OpenAI / Cognitive Services style 32+ char hex/base64 keys near a key hint.
33
+ { label: "api-key", pattern: /\b(api[_-]?key|ocp-apim-subscription-key)\b\s*[:=]\s*[\w.\-+/=]{16,}/gi },
34
+ ];
35
+ /** Escape a string for safe use inside a `RegExp`. */
36
+ function escapeRegExp(value) {
37
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
38
+ }
39
+ /**
40
+ * Scrub a single string: replace every registered secret value and every
41
+ * structural secret pattern with {@link REDACTED}. Short registered values
42
+ * (< 8 chars) are ignored to avoid pathological over-redaction of common words.
43
+ */
44
+ export function redactString(value, secrets) {
45
+ let out = value;
46
+ for (const secret of secrets) {
47
+ if (secret.length < 8) {
48
+ continue;
49
+ }
50
+ out = out.replace(new RegExp(escapeRegExp(secret), "g"), REDACTED);
51
+ }
52
+ for (const { pattern } of STRUCTURAL_PATTERNS) {
53
+ out = out.replace(pattern, REDACTED);
54
+ }
55
+ return out;
56
+ }
57
+ /**
58
+ * Deep-scrub an arbitrary value (string, array, or plain object) for logging.
59
+ * Non-string leaves are returned unchanged; strings are passed through
60
+ * {@link redactString}. Used so structured log fields are scrubbed too.
61
+ */
62
+ export function redactValue(value, secrets) {
63
+ if (typeof value === "string") {
64
+ return redactString(value, secrets);
65
+ }
66
+ if (Array.isArray(value)) {
67
+ return value.map((item) => redactValue(item, secrets));
68
+ }
69
+ if (value && typeof value === "object") {
70
+ const out = {};
71
+ for (const [key, item] of Object.entries(value)) {
72
+ out[key] = redactValue(item, secrets);
73
+ }
74
+ return out;
75
+ }
76
+ return value;
77
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Path resolution helpers for the squad-mcp server and generator.
3
+ *
4
+ * The server and generator must locate two roots at runtime:
5
+ * 1. the package root (where `tools.catalog.yml` and `generated/` live);
6
+ * 2. the squad `.github` root (where the read-only routing/roster
7
+ * instructions and the `*.agent.md` personas live).
8
+ *
9
+ * Both are resolved by walking the filesystem so the same code works whether it
10
+ * runs from TypeScript source (`tsx`) or compiled output (`dist/`), and whether
11
+ * the squad sources sit under `squad-src/.github` (this authoring repo) or
12
+ * `.github` (a deployed consumer).
13
+ */
14
+ import { existsSync } from "node:fs";
15
+ import { dirname, join, resolve } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ const CATALOG_FILE = "tools.catalog.yml";
18
+ /**
19
+ * Walk up from this module's directory until a directory containing
20
+ * `tools.catalog.yml` is found. That directory is the package root.
21
+ */
22
+ export function packageRoot() {
23
+ let dir = dirname(fileURLToPath(import.meta.url));
24
+ // Bound the walk so a misconfigured environment fails fast instead of looping.
25
+ for (let i = 0; i < 12; i += 1) {
26
+ if (existsSync(join(dir, CATALOG_FILE))) {
27
+ return dir;
28
+ }
29
+ const parent = dirname(dir);
30
+ if (parent === dir) {
31
+ break;
32
+ }
33
+ dir = parent;
34
+ }
35
+ throw new Error(`Could not locate ${CATALOG_FILE} by walking up from ${fileURLToPath(import.meta.url)}.`);
36
+ }
37
+ /** Absolute path to the authored tool catalog. */
38
+ export function catalogPath() {
39
+ return join(packageRoot(), CATALOG_FILE);
40
+ }
41
+ /** Absolute path to the generated runtime descriptor. */
42
+ export function generatedSchemaPath() {
43
+ return join(packageRoot(), "generated", "mcp-tools.schema.json");
44
+ }
45
+ /**
46
+ * Resolve the squad `.github` root holding the read-only routing/roster
47
+ * instructions and agent personas. Tries the authoring-repo layout
48
+ * (`<repo>/squad-src/.github`) first, then the deployed-consumer layout
49
+ * (`<repo>/.github`), where `<repo>` is the package root's parent.
50
+ *
51
+ * Returns `undefined` when neither candidate exists (the generator treats this
52
+ * as a hard error; the delegated engine treats it as "fall back to the
53
+ * embedded persona constants").
54
+ */
55
+ export function resolveSquadGithubRoot(fromPackageRoot = packageRoot()) {
56
+ const repoRoot = dirname(fromPackageRoot);
57
+ const probe = join("instructions", "squad", "squad-routing.instructions.md");
58
+ const candidates = [
59
+ // The committed cast snapshot FIRST: it is the artifact this server ships and
60
+ // the one `snapshot:cast --check` verifies. Anything installed into this repo
61
+ // later (an `apm install` for a headless squad run, say) must not shadow it,
62
+ // or tests and the generator would validate the install instead of the bundle.
63
+ // It is absent in the container, where the bundle is COPYed to /app/.github and
64
+ // the package-root candidate below resolves it.
65
+ join(fromPackageRoot, "host", "cast", ".github"),
66
+ join(repoRoot, "squad-src", ".github"),
67
+ join(repoRoot, ".github"),
68
+ // Also allow the package root itself to host a `.github` (the container layout).
69
+ join(fromPackageRoot, ".github"),
70
+ ];
71
+ for (const candidate of candidates) {
72
+ if (existsSync(join(candidate, probe))) {
73
+ return resolve(candidate);
74
+ }
75
+ }
76
+ return undefined;
77
+ }
78
+ /**
79
+ * Resolve the candidate `agents/` directories that may hold the `*.agent.md`
80
+ * personas, in priority order, filtered to those that exist.
81
+ *
82
+ * Unlike {@link resolveSquadGithubRoot} (which keys off the routing-probe file),
83
+ * this returns EVERY existing candidate because the layouts differ in what they
84
+ * contain. The persona loader scans them in order and takes the first `name:`
85
+ * match, so ORDER IS PRECEDENCE: the committed bundle comes first for the same
86
+ * reason as above — it is what ships, and nothing installed into this repo later
87
+ * should silently take its place.
88
+ */
89
+ export function resolveSquadAgentsRoots(fromPackageRoot = packageRoot()) {
90
+ const repoRoot = dirname(fromPackageRoot);
91
+ const candidates = [
92
+ join(fromPackageRoot, "host", "cast", ".github", "agents"),
93
+ join(repoRoot, "squad-src", ".github", "agents"),
94
+ join(repoRoot, ".github", "agents"),
95
+ // The container layout: the bundle is COPYed to /app/.github/agents.
96
+ join(fromPackageRoot, ".github", "agents"),
97
+ ];
98
+ const seen = new Set();
99
+ const roots = [];
100
+ for (const candidate of candidates) {
101
+ const abs = resolve(candidate);
102
+ if (!seen.has(abs) && existsSync(abs)) {
103
+ seen.add(abs);
104
+ roots.push(abs);
105
+ }
106
+ }
107
+ return roots;
108
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Tool + router layer.
3
+ *
4
+ * Exposes the coarse `squad_*` tools as MCP tool descriptors (advertising the
5
+ * raw JSON Schema authored in `tools.catalog.yml`), validates tool-call inputs
6
+ * against that schema with Ajv, and maps a validated call into a normalized
7
+ * `CoordinatorRequest`. This is the squad's routing boundary expressed as a tool
8
+ * surface; the routing decision itself lives in the catalog (one row per tool).
9
+ *
10
+ * The router is intentionally decoupled from the MCP SDK: it throws
11
+ * `ToolInputError` on bad input, and the server translates that into an MCP
12
+ * protocol error. This keeps the router unit-testable without a transport.
13
+ */
14
+ import { Ajv } from "ajv";
15
+ /** Thrown when a tool-call input fails JSON Schema validation. */
16
+ export class ToolInputError extends Error {
17
+ toolId;
18
+ details;
19
+ constructor(message, toolId, details) {
20
+ super(message);
21
+ this.toolId = toolId;
22
+ this.details = details;
23
+ this.name = "ToolInputError";
24
+ }
25
+ }
26
+ function optionalString(value) {
27
+ return typeof value === "string" && value.length > 0 ? value : undefined;
28
+ }
29
+ export class ToolRouter {
30
+ toolsById = new Map();
31
+ validators = new Map();
32
+ constructor(catalog) {
33
+ const ajv = new Ajv({ allErrors: true, strict: false });
34
+ for (const tool of catalog.tools) {
35
+ this.toolsById.set(tool.id, tool);
36
+ this.validators.set(tool.id, ajv.compile(tool.input));
37
+ }
38
+ }
39
+ /** The advertised tool ids, in catalog order. */
40
+ get toolIds() {
41
+ return [...this.toolsById.keys()];
42
+ }
43
+ /** Project the catalog into MCP `tools/list` descriptors. */
44
+ listToolDescriptors() {
45
+ return [...this.toolsById.values()].map((tool) => ({
46
+ name: tool.id,
47
+ title: tool.title,
48
+ description: tool.description,
49
+ inputSchema: tool.input,
50
+ }));
51
+ }
52
+ /** Look up a tool by id. */
53
+ getTool(id) {
54
+ return this.toolsById.get(id);
55
+ }
56
+ /**
57
+ * Validate a tool-call argument object against the tool's JSON Schema.
58
+ * Throws `ToolInputError` when the tool is unknown or the input is malformed.
59
+ */
60
+ validateInput(id, args) {
61
+ const validate = this.validators.get(id);
62
+ if (!validate) {
63
+ throw new ToolInputError(`Unknown tool: ${id}`, id, []);
64
+ }
65
+ const candidate = args ?? {};
66
+ if (!validate(candidate)) {
67
+ const details = (validate.errors ?? []).map((err) => `${err.instancePath || "(root)"} ${err.message ?? "is invalid"}`.trim());
68
+ throw new ToolInputError(`Invalid input for tool "${id}": ${details.join("; ")}`, id, details);
69
+ }
70
+ }
71
+ /** Map a validated argument object into a normalized CoordinatorRequest. */
72
+ toCoordinatorRequest(tool, args) {
73
+ const record = (args ?? {});
74
+ return {
75
+ toolId: tool.id,
76
+ request: String(record.request ?? ""),
77
+ profile: optionalString(record.profile),
78
+ tier: optionalString(record.tier),
79
+ owner: optionalString(record.owner),
80
+ mode: optionalString(record.mode),
81
+ discovery: optionalString(record.discovery),
82
+ context: optionalString(record.context),
83
+ squad: optionalString(record.squad),
84
+ init: record.init === true,
85
+ promote: record.promote === true,
86
+ };
87
+ }
88
+ }
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Live HTTP server bootstrap (deployed process only).
3
+ *
4
+ * Wires the production stack for the remote thin slice and is the ONLY module
5
+ * that pulls in the live-only dependencies — the `jose` JWKS verifier and the
6
+ * `@azure/identity` managed-identity token provider. Tests never import this file
7
+ * (they inject fakes), so the unit and conformance suites run without `jose`,
8
+ * without `@azure/identity`, and without a live Azure endpoint.
9
+ *
10
+ * Every trust-relevant value comes from operator config / environment (the model
11
+ * endpoint is allow-listed; the Origin list is strict; the audience is bound) —
12
+ * never from a caller. Secrets arrive via managed identity, never from code.
13
+ */
14
+ import { pathToFileURL } from "node:url";
15
+ import { loadCatalog } from "./catalog/catalog.js";
16
+ import { ToolRouter } from "./router/router.js";
17
+ import { loadOperatorConfig } from "./config/operator-config.js";
18
+ import { EntraAuthenticator } from "./auth/entra.js";
19
+ import { createJoseVerifier } from "./auth/jose-verifier.js";
20
+ import { EmbeddedCoordinator } from "./engine/embedded.js";
21
+ import { EphemeralWorkspaceManager } from "./engine/workspace.js";
22
+ import { GateKeeper, RunStoreApprovalChannel, TenantQuotaTracker } from "./engine/gates.js";
23
+ import { DurableRunStateStore } from "./engine/durable-run-state.js";
24
+ import { AzureTableRunStateStore } from "./engine/backends/azure-table-run-state.js";
25
+ import { AzureTableSquadMemoryStore } from "./engine/backends/azure-table-squad-memory.js";
26
+ import { FileSquadMemoryStore } from "./engine/backends/file-squad-memory.js";
27
+ import { GraphSquadMemoryStore } from "./engine/backends/graph-squad-memory.js";
28
+ import { TargetedSquadMemoryStore } from "./engine/targeted-squad-memory.js";
29
+ import { AutoMemory } from "./engine/auto-memory.js";
30
+ import { MemoryBackedArtifactStore } from "./engine/artifact-store.js";
31
+ import { SquadRunRecorder } from "./engine/squad-run-recorder.js";
32
+ import { OverflowSquadMemoryStore, } from "./engine/backends/overflow-squad-memory.js";
33
+ import { AesGcmFieldCipher, NullFieldCipher } from "./engine/field-cipher.js";
34
+ import { AzureOpenAIBackend } from "./engine/backends/azure-openai.js";
35
+ import { AzureBlobArtifactStore } from "./engine/backends/azure-blob-artifact-store.js";
36
+ import { PythonPptxRenderBackend } from "./engine/render/python-pptx-render-backend.js";
37
+ import { PptxRenderService } from "./engine/render/pptx-render-service.js";
38
+ import { createManagedIdentityTokenProvider } from "./engine/backends/managed-identity-credential.js";
39
+ import { RedactingLogger } from "./observability/logger.js";
40
+ import { SessionStore } from "./transports/session-store.js";
41
+ import { HttpMcpHandler } from "./transports/http-core.js";
42
+ import { createHttpServer } from "./transports/http.js";
43
+ /** The Azure Storage OAuth scope for the managed-identity Table token. */
44
+ const STORAGE_SCOPE = "https://storage.azure.com/.default";
45
+ /**
46
+ * The Microsoft Graph OAuth scope for the managed-identity token used by the
47
+ * SharePoint / OneDrive memory backend. The app identity needs an application
48
+ * permission on the target drive (`Sites.Selected` scoped to the site, or
49
+ * `Files.ReadWrite.All`) — least privilege is `Sites.Selected` plus a per-site
50
+ * write grant, so the server can reach ONLY the library the operator designated.
51
+ */
52
+ const GRAPH_SCOPE = "https://graph.microsoft.com/.default";
53
+ function readPricing(env) {
54
+ const input = Number(env.SQUAD_MCP_PRICE_INPUT_PER_MTOK);
55
+ const output = Number(env.SQUAD_MCP_PRICE_OUTPUT_PER_MTOK);
56
+ if (Number.isFinite(input) && Number.isFinite(output)) {
57
+ return { inputPerMTokUsd: input, outputPerMTokUsd: output };
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Build the durable run-state store + auditable approval channel from operator
63
+ * config (WI-06). Returns `undefined` when the gated pipeline is disabled (the
64
+ * safe hero-only default). Shared by the HTTP server and the worker so both bind
65
+ * to the SAME cross-replica store and approval record — an approval on the web
66
+ * tier is visible to the worker. Backends:
67
+ * * `file` — single-replica local directory (dev / single-instance).
68
+ * * `table` — Azure Table Storage with ETag CAS (multi-replica; production).
69
+ * When an encryption key is configured, `request`/`context` are AES-256-GCM
70
+ * encrypted at rest (MEDIUM-3).
71
+ */
72
+ export function buildRunStateStack(config, logger) {
73
+ if (!config.remotePipelineEnabled) {
74
+ return undefined;
75
+ }
76
+ const cipher = config.encryptionKeyBase64.length > 0
77
+ ? AesGcmFieldCipher.fromBase64Key(config.encryptionKeyBase64)
78
+ : new NullFieldCipher();
79
+ const runStateStore = config.runStateBackend === "table"
80
+ ? new AzureTableRunStateStore({
81
+ account: config.storageAccount,
82
+ tableName: config.runTableName,
83
+ getAccessToken: createManagedIdentityTokenProvider(STORAGE_SCOPE),
84
+ cipher,
85
+ logger,
86
+ })
87
+ : new DurableRunStateStore({ baseDir: config.runStateDir, cipher });
88
+ // Store-backed approval → cross-replica release (an approval on any replica is
89
+ // visible to all) with an auditable approver + timestamp.
90
+ const approvals = new RunStoreApprovalChannel(runStateStore, logger);
91
+ return { runStateStore, approvals };
92
+ }
93
+ /**
94
+ * Build the shared-state memory broker store from operator config. Returns
95
+ * `undefined` when the feature is disabled (the advisory-only default), so the
96
+ * bootstrap makes NO storage calls and the resource surface / memory tools are
97
+ * not served. Mirrors {@link buildRunStateStack}: it selects the backend and,
98
+ * when an encryption key is configured, encrypts `content` at rest with
99
+ * AES-256-GCM (MEDIUM-3) — otherwise the identity cipher. The SAME store instance
100
+ * serves both the resource read surface and the `squad_memory_write` CAS tool
101
+ * (wired in later phases). Backends:
102
+ * * `file` — single-replica local directory (dev / single-instance).
103
+ * * `table` — Azure Table Storage with ETag CAS (multi-replica; production).
104
+ */
105
+ export function buildSquadMemoryStack(config, logger) {
106
+ if (!config.enableMemory) {
107
+ return undefined;
108
+ }
109
+ const cipher = config.encryptionKeyBase64.length > 0
110
+ ? AesGcmFieldCipher.fromBase64Key(config.encryptionKeyBase64)
111
+ : new NullFieldCipher();
112
+ /** Build one destination from a (global or per-target) backend selection. */
113
+ const buildBackend = (spec) => {
114
+ if (spec.backend === "table") {
115
+ return new AzureTableSquadMemoryStore({
116
+ account: spec.storageAccount || config.storageAccount,
117
+ tableName: spec.tableName || config.memoryTableName,
118
+ getAccessToken: createManagedIdentityTokenProvider(STORAGE_SCOPE),
119
+ cipher,
120
+ logger,
121
+ });
122
+ }
123
+ if (spec.backend === "graph") {
124
+ return new GraphSquadMemoryStore({
125
+ driveId: spec.driveId ?? "",
126
+ rootPath: spec.rootPath,
127
+ endpoint: spec.endpoint && spec.endpoint.length > 0 ? spec.endpoint : undefined,
128
+ getAccessToken: createManagedIdentityTokenProvider(GRAPH_SCOPE),
129
+ // A SharePoint/OneDrive destination is human-readable BY DESIGN, so it
130
+ // stays plaintext unless the operator explicitly opts into ciphertext.
131
+ cipher: spec.encrypt ? cipher : new NullFieldCipher(),
132
+ logger,
133
+ });
134
+ }
135
+ return new FileSquadMemoryStore({ baseDir: spec.dir || config.memoryDir, cipher });
136
+ };
137
+ let memoryStore = buildBackend({
138
+ backend: config.memoryBackend,
139
+ dir: config.memoryDir,
140
+ storageAccount: config.storageAccount,
141
+ tableName: config.memoryTableName,
142
+ driveId: config.memoryGraphDriveId,
143
+ rootPath: config.memoryGraphRootPath,
144
+ endpoint: config.memoryGraphEndpoint,
145
+ encrypt: config.memoryGraphEncrypt,
146
+ });
147
+ // Named destinations: when the operator declared an allow-list, the caller may
148
+ // select among them by name (never by raw destination — SEC-3). A deployment
149
+ // that declares none keeps the single store above and ignores `target`.
150
+ if (config.memoryTargets.length > 0) {
151
+ const targets = new Map(config.memoryTargets.map((target) => [target.name, buildBackend(target)]));
152
+ memoryStore = new TargetedSquadMemoryStore({
153
+ targets,
154
+ defaultTarget: config.memoryDefaultTarget,
155
+ });
156
+ }
157
+ // WI-03 — when the operator enables the Blob overflow channel, wrap the store so
158
+ // over-threshold content spills to a tenant-scoped Blob (the same at-rest
159
+ // envelope; MEDIUM-3) with a tiny pointer entity left in the primary store. Off
160
+ // by default → the primary store's behavior is unchanged. The SAME `cipher` is
161
+ // passed so the blob payload is byte-identical to what the primary would persist.
162
+ if (config.memoryOverflowEnabled) {
163
+ const blobStore = new AzureBlobArtifactStore({
164
+ account: config.storageAccount,
165
+ container: config.memoryOverflowContainer,
166
+ getAccessToken: createManagedIdentityTokenProvider(STORAGE_SCOPE),
167
+ logger,
168
+ });
169
+ const blob = {
170
+ put: (blobPath, bytes) => blobStore.putObject(blobPath, bytes),
171
+ get: (blobPath) => blobStore.getObject(blobPath),
172
+ };
173
+ return {
174
+ memoryStore: new OverflowSquadMemoryStore({
175
+ primary: memoryStore,
176
+ blob,
177
+ cipher,
178
+ thresholdBytes: config.memoryOverflowThresholdBytes,
179
+ }),
180
+ };
181
+ }
182
+ return { memoryStore };
183
+ }
184
+ /**
185
+ * Assemble the {@link HttpMcpHandler} from operator config. Separated from
186
+ * `listen` so the wiring is exercisable; in production this loads the live
187
+ * verifier + managed-identity credential.
188
+ */
189
+ export function buildHttpHandler(config, env = process.env, logger = new RedactingLogger({ name: "hve-squad-mcp-http" })) {
190
+ const router = new ToolRouter(loadCatalog());
191
+ const jwksUri = (env.SQUAD_MCP_JWKS_URI ?? "").trim();
192
+ if (jwksUri.length === 0) {
193
+ throw new Error("SQUAD_MCP_JWKS_URI is required to validate Entra tokens (SEC-1).");
194
+ }
195
+ const authenticator = new EntraAuthenticator({
196
+ audience: config.audience,
197
+ allowedIssuers: config.allowedIssuers,
198
+ allowedTenants: config.allowedTenants,
199
+ verifier: createJoseVerifier({ jwksUri, issuer: config.allowedIssuers }),
200
+ logger,
201
+ });
202
+ const backend = new AzureOpenAIBackend({
203
+ endpoint: config.modelEndpoint,
204
+ deployment: config.modelDeployment,
205
+ apiVersion: config.modelApiVersion,
206
+ getAccessToken: createManagedIdentityTokenProvider(),
207
+ logger,
208
+ pricing: readPricing(env),
209
+ });
210
+ // HIGH-1 / WI-06: the gated async pipeline is exposed ONLY when the operator
211
+ // enabled it, with a durable run-state store and an auditable approval channel.
212
+ // Otherwise the surface stays hero-only (the council-gated default).
213
+ const stack = buildRunStateStack(config, logger);
214
+ // The shared-state memory broker is built only when the operator enabled it
215
+ // (off by default). The SAME store instance serves the resource read surface
216
+ // and the write-back tool (wired in later phases).
217
+ const memoryStack = buildSquadMemoryStack(config, logger);
218
+ // The deterministic render tool is built only when the operator enabled it. It
219
+ // reuses the Storage managed-identity token (storage.azure.com) for the Blob
220
+ // upload + user-delegation SAS; the interpreter/scripts/brand come from config.
221
+ const renderService = config.enableRenderPptx
222
+ ? new PptxRenderService({
223
+ backend: new PythonPptxRenderBackend({
224
+ pythonPath: config.renderPythonPath,
225
+ scriptsDir: config.renderScriptsDir,
226
+ }),
227
+ store: new AzureBlobArtifactStore({
228
+ account: config.storageAccount,
229
+ container: config.renderBlobContainer,
230
+ getAccessToken: createManagedIdentityTokenProvider(STORAGE_SCOPE),
231
+ logger,
232
+ }),
233
+ ttlMs: config.renderSasTtlMinutes * 60 * 1000,
234
+ templatePath: config.renderBrandTemplatePath.length > 0 ? config.renderBrandTemplatePath : undefined,
235
+ })
236
+ : undefined;
237
+ const embedded = new EmbeddedCoordinator({
238
+ backend,
239
+ workspaceManager: new EphemeralWorkspaceManager(),
240
+ quota: new TenantQuotaTracker({
241
+ concurrency: config.tenantConcurrency,
242
+ monthlyCeilingUsd: config.tenantMonthlyCostCeilingUsd,
243
+ }),
244
+ gates: new GateKeeper({ advisoryAutopilotEnabled: config.advisoryAutopilotEnabled }),
245
+ runStateStore: stack?.runStateStore,
246
+ approvals: stack?.approvals,
247
+ // WI-1b4-WORKER: when a worker is enabled, the poll is read-only and the ACA
248
+ // Job drives approved runs off the request path (runs may exceed 240s).
249
+ driveOnPoll: !config.workerEnabled,
250
+ // Deterministic server-side memory continuity. Built ONLY when the operator
251
+ // enabled both the memory broker and auto-memory; otherwise the engine keeps
252
+ // its previous behavior exactly (memory stays a manual tool).
253
+ autoMemory: config.memoryAutoEnabled && memoryStack
254
+ ? new AutoMemory({
255
+ store: memoryStack.memoryStore,
256
+ defaultProject: config.memoryDefaultProject,
257
+ logger,
258
+ })
259
+ : undefined,
260
+ // The squad ledger writes the `.copilot-tracking` tree through whichever
261
+ // store the memory backend already selected, so an operator picks the
262
+ // destination once. Requires auto-memory, which is what resolves the project
263
+ // partition the tree is written under.
264
+ runRecorder: config.enableArtifacts && config.memoryAutoEnabled && memoryStack
265
+ ? new SquadRunRecorder({
266
+ store: new MemoryBackedArtifactStore(memoryStack.memoryStore),
267
+ // Only when the operator enabled rendering; otherwise the presenter's
268
+ // markdown stands on its own rather than half-producing a deck.
269
+ renderer: renderService,
270
+ logger,
271
+ })
272
+ : undefined,
273
+ logger,
274
+ });
275
+ return new HttpMcpHandler({
276
+ router,
277
+ authenticator,
278
+ embedded,
279
+ sessions: new SessionStore({ idleMs: config.sessionIdleMs }),
280
+ allowedOrigins: config.allowedOrigins,
281
+ artifactsEnabled: config.enableArtifacts,
282
+ logger,
283
+ pipelineExposed: config.remotePipelineEnabled,
284
+ renderService,
285
+ memoryStore: memoryStack?.memoryStore,
286
+ businessToolsExposed: config.enableBusinessTools,
287
+ });
288
+ }
289
+ /** Start the live HTTP server. */
290
+ export async function mainHttp() {
291
+ const logger = new RedactingLogger({ name: "hve-squad-mcp-http" });
292
+ const config = loadOperatorConfig();
293
+ const handler = buildHttpHandler(config, process.env, logger);
294
+ const server = createHttpServer(handler);
295
+ const port = Number(process.env.PORT ?? 3000);
296
+ await new Promise((resolve) => server.listen(port, resolve));
297
+ logger.info("hve-squad MCP HTTP server listening", { port, mode: "embedded" });
298
+ }
299
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
300
+ mainHttp().catch((error) => {
301
+ process.stderr.write(`[hve-squad-mcp-http] fatal: ${String(error)}\n`);
302
+ process.exit(1);
303
+ });
304
+ }