@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,96 @@
1
+ /**
2
+ * Federation framing for the EMBEDDED (remote / Copilot Studio) boundary.
3
+ *
4
+ * The delegated path already carries full federation semantics (`persona.ts` +
5
+ * `delegated.ts`): it hands the host the Federation Coordinator persona and lets
6
+ * the host resolve the registry and dispatch sub-squads. The embedded path had
7
+ * none — `squad_federate` was not even reachable over HTTP — so this module
8
+ * supplies the missing piece: the server-side, DETERMINISTIC federation directive
9
+ * that is prepended to the Federation Coordinator's charter for an embedded run.
10
+ *
11
+ * SEC-5 posture. The directive is AUTHORITY (it becomes part of the `system`
12
+ * charter), so it is composed EXCLUSIVELY from values the server has already
13
+ * validated:
14
+ * * `squad` — matched against {@link SUB_SQUAD_NAME} (lower-kebab-case) and
15
+ * dropped when it does not match, so no caller string is interpolated raw;
16
+ * * `init` / `promote` — booleans normalized by the router;
17
+ * * `mode` — matched against the closed autonomy set.
18
+ * The caller's free-text `request`/`context` are NEVER placed here; they remain
19
+ * delimited DATA composed by `composeEmbeddedPrompt`, exactly as for every other
20
+ * embedded stage.
21
+ *
22
+ * The directive also closes the turn to Watch Mode's unattended bootstrap. The
23
+ * bundled Federation Coordinator charter carries an auto-approved promotion /
24
+ * expansion path that a repository event may take; an MCP call is not that event,
25
+ * so every turn here is pinned CONFIRMATION-GATED (see `NO_WATCH_BOOTSTRAP_NOTE`).
26
+ */
27
+ import { FEDERATION_COORDINATOR_CHARTER } from "./embedded-roles.js";
28
+ import { NO_WATCH_BOOTSTRAP_NOTE } from "./persona.js";
29
+ /** The federation role name as it appears in the catalog and the deployed cast. */
30
+ export const FEDERATION_ROLE = "Squad Federation Coordinator";
31
+ /** Sub-squad naming rule from squad-federation.instructions.md (lower-kebab-case). */
32
+ const SUB_SQUAD_NAME = /^[a-z0-9][a-z0-9-]*$/;
33
+ /** The closed autonomy set the catalog allows. */
34
+ const AUTONOMY_MODES = new Set(["autonomous", "autopilot"]);
35
+ /**
36
+ * Validate the federation-relevant inputs of a coordinator request. Anything that
37
+ * fails its shape check is DROPPED (never passed through), so a hostile `squad`
38
+ * value can neither reach the charter nor a state path.
39
+ */
40
+ export function federationInputs(request) {
41
+ const squad = request.squad && SUB_SQUAD_NAME.test(request.squad) ? request.squad : undefined;
42
+ const mode = request.mode && AUTONOMY_MODES.has(request.mode) ? request.mode : undefined;
43
+ return { squad, init: request.init === true, promote: request.promote === true, mode };
44
+ }
45
+ /**
46
+ * Compose the server-side federation directive appended to the Federation
47
+ * Coordinator charter. Deterministic and fully derived from {@link federationInputs}.
48
+ *
49
+ * Precedence mirrors the delegated path and the squad's federation instructions:
50
+ * `promote` (adopt an existing single squad) is resolved BEFORE `init` (create /
51
+ * expand), because promotion is only meaningful on a repo that has a top-level
52
+ * squad and no registry yet; running init first would seed a second, empty
53
+ * federation root and strand the existing state. When both flags arrive together
54
+ * the directive states promotion first and init second, so the model never has to
55
+ * guess the order.
56
+ */
57
+ export function federationDirective(inputs) {
58
+ const lines = ["", "**Federation turn (server-resolved).**"];
59
+ if (inputs.promote) {
60
+ lines.push("- This turn runs **Federation Promotion Mode**: the repository has an existing", " single squad (a top-level `team.md`) and no `federation.md`. Adopt that squad", " into a federation as its FIRST sub-squad, relocating its state intact, and say", " explicitly what moves where before anything else in this turn. This is the", " CONFIRMATION-GATED promotion, not the unattended Watch Mode one: propose the", " move and wait for the user, never present it as already done.");
61
+ }
62
+ if (inputs.init) {
63
+ lines.push("- This turn runs **Federation Init / Expansion Mode**: propose the federation (or", " the new sub-squad), state the registry and meta-routing entries it needs, and", " make clear this is a proposal awaiting confirmation \u2014 do not present it as", " already created.");
64
+ }
65
+ if (inputs.squad) {
66
+ lines.push(`- The caller pinned an explicit sub-squad target: \`${inputs.squad}\`. Honor it and`, " do NOT re-route via meta-routing. Scope the whole turn to", ` \`.copilot-tracking/squad/members/${inputs.squad}/\`.`);
67
+ }
68
+ else {
69
+ lines.push("- No sub-squad was pinned. Resolve the target(s) from `meta-routing.md` and state", " the routing decision (which sub-squad, on what signal) before the work. If the", " target is ambiguous or unknown, escalate and ask \u2014 never invent a sub-squad.");
70
+ }
71
+ if (inputs.mode === "autopilot" && !inputs.squad) {
72
+ lines.push("- `mode=autopilot` with no pinned target means a FEDERATION-WIDE autopilot: plan", " ordered per-sub-squad runs, attribute every federation-level gate to the", " sub-squad that raised it, aggregate one cost ceiling, and close with a single", " consolidated final-outcome validation.");
73
+ }
74
+ else if (inputs.mode) {
75
+ lines.push(`- Autonomy mode \`${inputs.mode}\` is forwarded to the selected sub-squad's run.`);
76
+ }
77
+ lines.push("", NO_WATCH_BOOTSTRAP_NOTE, "", "You are advisory here: produce the federation decision and per-sub-squad plan as", "text. You do not create files, move state, or dispatch sub-squads yourself.");
78
+ return lines.join("\n");
79
+ }
80
+ /**
81
+ * Build the single-stage federation persona for an embedded run: the resolved
82
+ * Federation Coordinator charter (real on-disk `*.agent.md` bytes when the cast is
83
+ * present, else the embedded paraphrase) plus the server-composed directive.
84
+ */
85
+ export function federationPersona(request, resolved) {
86
+ const base = resolved ?? {
87
+ role: FEDERATION_ROLE,
88
+ charter: FEDERATION_COORDINATOR_CHARTER,
89
+ applyTo: [],
90
+ };
91
+ return {
92
+ ...base,
93
+ role: FEDERATION_ROLE,
94
+ charter: `${base.charter}\n${federationDirective(federationInputs(request))}`,
95
+ };
96
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Field-level encryption at rest (WI-06 / MEDIUM-3).
3
+ *
4
+ * The async run record persists the caller's `request`/`context` so a later
5
+ * status poll (or a worker) can drive the pipeline after approval. In the durable
6
+ * store that data is at rest — on the local disk (dev) or in Azure Table Storage
7
+ * (prod). Azure encrypts storage at rest with platform keys already, but the
8
+ * council flagged the caller's own prompt text as sensitive enough to warrant
9
+ * APPLICATION-level envelope encryption so it is opaque even to an operator with
10
+ * raw table access (defense in depth; MEDIUM-3, latent-HIGH once the durable
11
+ * store lands).
12
+ *
13
+ * This module is dependency-free: it uses Node's built-in `crypto` (AES-256-GCM),
14
+ * so it compiles and tests without any Azure SDK. The 32-byte data key is
15
+ * operator-provided (sourced from Key Vault as base64), never embedded in code or
16
+ * derived from caller input.
17
+ */
18
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
19
+ /**
20
+ * Identity cipher — stores fields verbatim. The default for the ephemeral store
21
+ * and local-file dev, where no key is configured. Production wires
22
+ * {@link AesGcmFieldCipher}.
23
+ */
24
+ export class NullFieldCipher {
25
+ encrypts = false;
26
+ encrypt(plaintext) {
27
+ return plaintext;
28
+ }
29
+ decrypt(ciphertext) {
30
+ return ciphertext;
31
+ }
32
+ }
33
+ /** Prefix marking an AES-GCM envelope so decrypt can distinguish it from plaintext. */
34
+ const ENVELOPE_PREFIX = "gcm1:";
35
+ /**
36
+ * AES-256-GCM field cipher. The envelope is `gcm1:<base64(iv|tag|ciphertext)>`;
37
+ * a fresh 12-byte IV is generated per field, and the 16-byte auth tag makes
38
+ * tampering detectable. `decrypt` returns non-enveloped input unchanged so a
39
+ * migration from plaintext records does not break reads.
40
+ */
41
+ export class AesGcmFieldCipher {
42
+ encrypts = true;
43
+ key;
44
+ /** @param key a 32-byte (256-bit) data key (operator-provided, from Key Vault). */
45
+ constructor(key) {
46
+ if (key.length !== 32) {
47
+ throw new Error("AesGcmFieldCipher requires a 32-byte key.");
48
+ }
49
+ this.key = key;
50
+ }
51
+ /** Build a cipher from a base64-encoded 32-byte key (the operator-config form). */
52
+ static fromBase64Key(base64Key) {
53
+ const key = Buffer.from(base64Key, "base64");
54
+ return new AesGcmFieldCipher(key);
55
+ }
56
+ encrypt(plaintext) {
57
+ const iv = randomBytes(12);
58
+ const cipher = createCipheriv("aes-256-gcm", this.key, iv);
59
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
60
+ const tag = cipher.getAuthTag();
61
+ return ENVELOPE_PREFIX + Buffer.concat([iv, tag, ciphertext]).toString("base64");
62
+ }
63
+ decrypt(value) {
64
+ if (!value.startsWith(ENVELOPE_PREFIX)) {
65
+ // Not an envelope (legacy plaintext / already-clear) — pass through.
66
+ return value;
67
+ }
68
+ const raw = Buffer.from(value.slice(ENVELOPE_PREFIX.length), "base64");
69
+ const iv = raw.subarray(0, 12);
70
+ const tag = raw.subarray(12, 28);
71
+ const ciphertext = raw.subarray(28);
72
+ const decipher = createDecipheriv("aes-256-gcm", this.key, iv);
73
+ decipher.setAuthTag(tag);
74
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
75
+ }
76
+ }
77
+ /** Encrypt an optional field (leaves `undefined` untouched). */
78
+ export function encryptField(cipher, value) {
79
+ return value === undefined ? undefined : cipher.encrypt(value);
80
+ }
81
+ /** Decrypt an optional field (leaves `undefined` untouched). */
82
+ export function decryptField(cipher, value) {
83
+ return value === undefined ? undefined : cipher.decrypt(value);
84
+ }
@@ -0,0 +1,241 @@
1
+ import { isRunApproved } from "./run-state.js";
2
+ /** Returns the `YYYY-MM` bucket a timestamp falls in (cost accounting window). */
3
+ function monthKey(epochMs) {
4
+ const date = new Date(epochMs);
5
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
6
+ }
7
+ /** Tracks per-tenant concurrency and monthly spend; refuses past either limit. */
8
+ export class TenantQuotaTracker {
9
+ concurrency;
10
+ monthlyCeilingUsd;
11
+ now;
12
+ usage = new Map();
13
+ constructor(options) {
14
+ this.concurrency = options.concurrency;
15
+ this.monthlyCeilingUsd = options.monthlyCeilingUsd;
16
+ this.now = options.now ?? Date.now;
17
+ }
18
+ usageFor(tenantId) {
19
+ const month = monthKey(this.now());
20
+ const existing = this.usage.get(tenantId);
21
+ if (!existing) {
22
+ const fresh = { active: 0, month, spentUsd: 0 };
23
+ this.usage.set(tenantId, fresh);
24
+ return fresh;
25
+ }
26
+ if (existing.month !== month) {
27
+ // Month rollover: reset the spend window, keep in-flight count.
28
+ existing.month = month;
29
+ existing.spentUsd = 0;
30
+ }
31
+ return existing;
32
+ }
33
+ /**
34
+ * Atomically check the cost ceiling and acquire a concurrency slot. Returns a
35
+ * `release` to free the slot (call once, in a `finally`). Refuses with a reason
36
+ * when at the cost ceiling (COST-2) or the concurrency cap (SEC-9 / COST-1).
37
+ */
38
+ acquire(tenantId) {
39
+ const usage = this.usageFor(tenantId);
40
+ if (usage.spentUsd >= this.monthlyCeilingUsd) {
41
+ return { ok: false, reason: "cost_ceiling" };
42
+ }
43
+ if (usage.active >= this.concurrency) {
44
+ return { ok: false, reason: "concurrency_cap" };
45
+ }
46
+ usage.active += 1;
47
+ let released = false;
48
+ return {
49
+ ok: true,
50
+ release: () => {
51
+ if (released) {
52
+ return;
53
+ }
54
+ released = true;
55
+ usage.active = Math.max(0, usage.active - 1);
56
+ },
57
+ };
58
+ }
59
+ /** Record realized inference cost so the ceiling reflects actual spend (COST-2). */
60
+ recordCostUsd(tenantId, usd) {
61
+ if (usd <= 0) {
62
+ return;
63
+ }
64
+ this.usageFor(tenantId).spentUsd += usd;
65
+ }
66
+ /** Current month's spend for a tenant. */
67
+ spentUsd(tenantId) {
68
+ return this.usageFor(tenantId).spentUsd;
69
+ }
70
+ /** Current in-flight dispatch count for a tenant. */
71
+ activeCount(tenantId) {
72
+ return this.usageFor(tenantId).active;
73
+ }
74
+ }
75
+ /**
76
+ * COST-2 (run scope) — a per-run cost ledger that accumulates realized stage cost
77
+ * across a single multi-stage advisory run and refuses the NEXT stage once the
78
+ * accumulated spend has reached the ceiling.
79
+ *
80
+ * This is the run-scoped sibling of {@link TenantQuotaTracker}'s monthly ceiling:
81
+ * it reuses the exact same COST-2 accumulate-then-refuse style (accumulate
82
+ * realized `estimatedCostUsd`; refuse when `spent >= ceiling`) rather than
83
+ * inventing a parallel accounting system, but at a per-run granularity so a
84
+ * single advisory pipeline cannot run away across its stages. The check is made
85
+ * BEFORE each stage's model call, so exceeding the ceiling halts the run with a
86
+ * clear reason and zero further model calls — the run's remaining stages are
87
+ * never dispatched.
88
+ */
89
+ export class RunCostLedger {
90
+ ceilingUsd;
91
+ spent = 0;
92
+ constructor(options) {
93
+ this.ceilingUsd = options.ceilingUsd;
94
+ }
95
+ /**
96
+ * Check BEFORE a stage: refuse (with the run-scoped reason) once accumulated
97
+ * spend has reached the ceiling. Mirrors {@link TenantQuotaTracker.acquire}'s
98
+ * `spentUsd >= ceiling` COST-2 test.
99
+ */
100
+ check() {
101
+ if (this.spent >= this.ceilingUsd) {
102
+ return { ok: false, reason: "run_cost_ceiling", spentUsd: this.spent, ceilingUsd: this.ceilingUsd };
103
+ }
104
+ return { ok: true, spentUsd: this.spent, ceilingUsd: this.ceilingUsd };
105
+ }
106
+ /** Record a stage's realized inference cost so the ceiling reflects actual spend. */
107
+ record(usd) {
108
+ if (typeof usd === "number" && usd > 0) {
109
+ this.spent += usd;
110
+ }
111
+ }
112
+ /** Accumulated spend across the run so far. */
113
+ spentUsd() {
114
+ return this.spent;
115
+ }
116
+ }
117
+ /**
118
+ * In-memory approval channel; the operator (or a test simulating one) calls
119
+ * `approve`. It records an audit entry (approver + timestamp) for every approval
120
+ * and, when an audit logger is supplied, emits a durable audit line — a security
121
+ * gate must be non-bypassable AND auditable. NOTE: the in-memory map is
122
+ * per-process; a multi-replica deployment needs the shared/durable approval
123
+ * backend (WI-06) so an approval on one replica is visible to all.
124
+ */
125
+ export class InMemoryApprovalChannel {
126
+ audit;
127
+ approved = new Map();
128
+ constructor(audit) {
129
+ this.audit = audit;
130
+ }
131
+ isApproved(runId) {
132
+ return Promise.resolve(this.approved.has(runId));
133
+ }
134
+ approve(runId, approver) {
135
+ const record = { approver, at: Date.now() };
136
+ this.approved.set(runId, record);
137
+ this.audit?.info("human gate approved", { runId, approver, at: record.at });
138
+ return Promise.resolve();
139
+ }
140
+ approvalRecord(runId) {
141
+ return Promise.resolve(this.approved.get(runId));
142
+ }
143
+ }
144
+ /**
145
+ * WI-06 — a store-backed approval channel that makes release CROSS-REPLICA.
146
+ *
147
+ * {@link InMemoryApprovalChannel} records an approval in a per-process map, so a
148
+ * release recorded on the replica that received the operator's `/admin/approve`
149
+ * is invisible to the OTHER replicas that may later poll the run — a held run
150
+ * would never resume on those replicas. This channel instead persists the
151
+ * approval ON the run record (`approvedBy`/`approvedAt`) through the shared
152
+ * {@link RunStateStore}, so any replica reading the record sees the release. It
153
+ * still records an auditable approver + timestamp and emits the audit line: a
154
+ * security gate must be non-bypassable AND auditable. Wire this with the Azure
155
+ * Table store for a true multi-replica deployment.
156
+ */
157
+ export class RunStoreApprovalChannel {
158
+ store;
159
+ audit;
160
+ constructor(store, audit) {
161
+ this.store = store;
162
+ this.audit = audit;
163
+ }
164
+ async isApproved(runId) {
165
+ const run = await this.store.get(runId);
166
+ return run !== undefined && isRunApproved(run);
167
+ }
168
+ async approve(runId, approver) {
169
+ const at = Date.now();
170
+ // Persist the approval on the shared record so every replica observes it.
171
+ await this.store.update(runId, { approvedBy: approver, approvedAt: at });
172
+ this.audit?.info("human gate approved", { runId, approver, at });
173
+ }
174
+ async approvalRecord(runId) {
175
+ const run = await this.store.get(runId);
176
+ if (!run || !isRunApproved(run)) {
177
+ return undefined;
178
+ }
179
+ return { approver: run.approvedBy, at: run.approvedAt ?? 0 };
180
+ }
181
+ }
182
+ /**
183
+ * Roles that reach OUTSIDE the tracking tree, so a plan containing one is never
184
+ * advisory regardless of the operator's setting.
185
+ *
186
+ * `backlog-executor` writes into a live Azure DevOps, GitHub, or Jira backlog, where
187
+ * a create is announced to a whole team by notifications and webhooks the moment it
188
+ * lands; `deployer` changes running infrastructure. No profile seeds
189
+ * `backlog-executor` at all, so this is belt-and-braces against a custom roster.
190
+ */
191
+ export const IMPACTFUL_ROLES = new Set([
192
+ "backlog-executor",
193
+ "deployer",
194
+ "iac-author",
195
+ "azure-diagnose",
196
+ ]);
197
+ /** True when every seeded role only produces text into the tracking tree. */
198
+ export function isAdvisoryOnly(seededRoles) {
199
+ return seededRoles.every((role) => !IMPACTFUL_ROLES.has(role.trim().toLowerCase()));
200
+ }
201
+ /**
202
+ * Classifies tool calls into proceed/hold. Holds are determined by tool metadata
203
+ * and the fail-safe destructive hint only; no input can turn a hold into a
204
+ * proceed.
205
+ */
206
+ export class GateKeeper {
207
+ advisoryAutopilotEnabled;
208
+ constructor(options = {}) {
209
+ this.advisoryAutopilotEnabled = options.advisoryAutopilotEnabled === true;
210
+ }
211
+ /**
212
+ * SEC-7 / PROD-5: a tool that carries gates, runs at a non-`auto` tier, drives
213
+ * the full pipeline, or is flagged destructive HOLDS for human approval. The
214
+ * `mode` is recorded but never downgrades a hold (autonomous/autopilot still
215
+ * stop at impactful actions).
216
+ */
217
+ classify(input) {
218
+ const { tool } = input;
219
+ const gated = tool.gates || tool.catchAll || tool.tier === "confirm" || tool.tier === "escalate";
220
+ if (gated || input.destructive === true) {
221
+ // A destructive run always holds: the advisory release is a narrowing of the
222
+ // gate, never an override of the fail-safe hint.
223
+ if (this.advisoryAutopilotEnabled &&
224
+ input.advisoryOnly === true &&
225
+ input.destructive !== true) {
226
+ return { kind: "proceed" };
227
+ }
228
+ const why = input.destructive
229
+ ? "destructive operation requires explicit human approval"
230
+ : `tool "${tool.id}" carries a Human Gate (tier=${tool.tier}${tool.gates ? ", gated" : ""})`;
231
+ return {
232
+ kind: "hold",
233
+ reason: why,
234
+ approvalRequest: "This action is paused for human approval and will not proceed until an " +
235
+ "operator approves it through the out-of-band approval channel. The squad " +
236
+ "never auto-releases a gate across the remote boundary.",
237
+ };
238
+ }
239
+ return { kind: "proceed" };
240
+ }
241
+ }
@@ -0,0 +1,43 @@
1
+ export function splitRow(line) {
2
+ return line
3
+ .trim()
4
+ .replace(/^\|/, "")
5
+ .replace(/\|$/, "")
6
+ .split("|")
7
+ .map((cell) => cell.trim());
8
+ }
9
+ export function isTableLine(line) {
10
+ return /^\s*\|.*\|\s*$/.test(line);
11
+ }
12
+ export function isSeparatorLine(line) {
13
+ return /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && line.includes("-");
14
+ }
15
+ export function parseTables(markdown) {
16
+ const lines = markdown.split(/\r?\n/);
17
+ const tables = [];
18
+ let inFence = false;
19
+ for (let i = 0; i < lines.length; i += 1) {
20
+ const line = lines[i];
21
+ if (/^\s*```/.test(line)) {
22
+ inFence = !inFence;
23
+ continue;
24
+ }
25
+ if (inFence) {
26
+ continue;
27
+ }
28
+ if (isTableLine(line) && i + 1 < lines.length && isSeparatorLine(lines[i + 1])) {
29
+ const headers = splitRow(line);
30
+ const rows = [];
31
+ let j = i + 2;
32
+ for (; j < lines.length; j += 1) {
33
+ if (/^\s*```/.test(lines[j]) || !isTableLine(lines[j])) {
34
+ break;
35
+ }
36
+ rows.push(splitRow(lines[j]));
37
+ }
38
+ tables.push({ headers, rows });
39
+ i = j - 1;
40
+ }
41
+ }
42
+ return tables;
43
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The `ModelBackend` seam.
3
+ *
4
+ * The embedded engine binds to this abstraction, never to a concrete model
5
+ * client, so:
6
+ * * the thin slice ships exactly ONE backend (Azure OpenAI), and
7
+ * * the GitHub Models / OpenAI-compatible backends (Phase 1b) and the optional
8
+ * Foundry backend (Phase 3) drop in without touching the engine — Foundry
9
+ * stays optional, never mandatory.
10
+ *
11
+ * The shape deliberately separates **authority** (the `system` prompt, composed
12
+ * from the persona only) from **data** (the `messages`, which carry the
13
+ * delimited, untrusted caller `request`/`context`). That separation is the
14
+ * SEC-5 charter-injection containment contract; see `embedded-prompt.ts`.
15
+ */
16
+ export {};
@@ -0,0 +1,132 @@
1
+ /**
2
+ * From-disk persona loader (single-source invariant).
3
+ *
4
+ * The embedded thin slice shipped PARAPHRASED role charters so the engine was
5
+ * deterministic without a deployed cast on disk. This loader is the follow-up
6
+ * named in `embedded-roles.ts`: it reads the REAL `*.agent.md` bytes (frontmatter
7
+ * plus body) so the embedded path and the delegated path can share the exact same
8
+ * persona source of truth in a deployed consumer.
9
+ *
10
+ * It is a pure read — no model, no network. It returns a {@link PersonaRecord}
11
+ * (charter body + parsed `applyTo`/`tools` frontmatter) or `undefined` when the
12
+ * cast is not present on disk (CI / minimal image), which callers treat as
13
+ * "fall back to the paraphrased constant".
14
+ *
15
+ * `applyTo` is parsed for completeness and future multi-instruction resolution,
16
+ * but agent personas normally carry no `applyTo` (that is an instructions-file
17
+ * concept); SEC-5 / untrusted-content-boundary is enforced unconditionally by
18
+ * `embedded-prompt.ts`, not by a per-role preamble.
19
+ */
20
+ import { readFileSync, readdirSync, statSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { parse as parseYaml } from "yaml";
23
+ import { resolveSquadAgentsRoots } from "../paths.js";
24
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
25
+ function normalizeList(value) {
26
+ if (Array.isArray(value)) {
27
+ return value.map((entry) => String(entry).trim()).filter((entry) => entry.length > 0);
28
+ }
29
+ if (typeof value === "string" && value.trim().length > 0) {
30
+ return [value.trim()];
31
+ }
32
+ return [];
33
+ }
34
+ function parseAgentPersona(text) {
35
+ const match = text.match(FRONTMATTER);
36
+ if (!match) {
37
+ return undefined;
38
+ }
39
+ let frontmatter;
40
+ try {
41
+ frontmatter = (parseYaml(match[1]) ?? {});
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ const name = typeof frontmatter.name === "string" ? frontmatter.name.trim() : undefined;
47
+ const tools = normalizeList(frontmatter.tools);
48
+ return {
49
+ name,
50
+ applyTo: normalizeList(frontmatter.applyTo),
51
+ tools: tools.length > 0 ? tools : undefined,
52
+ body: match[2].trim(),
53
+ };
54
+ }
55
+ function collectAgentFiles(dir, acc) {
56
+ let entries;
57
+ try {
58
+ entries = readdirSync(dir);
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ for (const entry of entries) {
64
+ const full = join(dir, entry);
65
+ let stats;
66
+ try {
67
+ stats = statSync(full);
68
+ }
69
+ catch {
70
+ continue;
71
+ }
72
+ if (stats.isDirectory()) {
73
+ collectAgentFiles(full, acc);
74
+ }
75
+ else if (entry.endsWith(".agent.md")) {
76
+ acc.push(full);
77
+ }
78
+ }
79
+ }
80
+ /**
81
+ * Load the {@link PersonaRecord} for a squad role by matching the agent `name:`
82
+ * frontmatter across the candidate agents roots. Returns `undefined` when no
83
+ * matching persona is found on disk.
84
+ */
85
+ export function loadPersonaForRole(role, roots = resolveSquadAgentsRoots()) {
86
+ for (const root of roots) {
87
+ const files = [];
88
+ collectAgentFiles(root, files);
89
+ for (const file of files) {
90
+ let text;
91
+ try {
92
+ text = readFileSync(file, "utf8");
93
+ }
94
+ catch {
95
+ continue;
96
+ }
97
+ const parsed = parseAgentPersona(text);
98
+ if (parsed && parsed.name === role && parsed.body.length > 0) {
99
+ return {
100
+ role,
101
+ charter: parsed.body,
102
+ applyTo: parsed.applyTo,
103
+ tools: parsed.tools,
104
+ };
105
+ }
106
+ }
107
+ }
108
+ return undefined;
109
+ }
110
+ /**
111
+ * Resolve the on-disk {@link PersonaRecord} for a squad ROLE KEY (e.g.
112
+ * `"architect"`) by first mapping the role key to the deployed agent `name:`
113
+ * via the injected `rosterMap`, then loading the real persona bytes for that
114
+ * agent name.
115
+ *
116
+ * Roster PARSING is intentionally NOT done here — this helper only consumes an
117
+ * already-parsed role -> agent-name map so the loader stays roster-map-injectable
118
+ * and free of instruction-file parsing (the routing engine owns roster parsing).
119
+ * This is a pure disk read with no paraphrase fallback; callers that want the
120
+ * hero paraphrase fallback use `resolvePersonaForRosterRole` in
121
+ * `embedded-roles.ts`.
122
+ *
123
+ * Returns `undefined` when the role key is absent from the map or the mapped
124
+ * agent persona is not present on disk (never a silent wrong persona).
125
+ */
126
+ export function loadPersonaForRosterRole(roleKey, rosterMap, roots = resolveSquadAgentsRoots()) {
127
+ const agentName = rosterMap.get(roleKey);
128
+ if (!agentName) {
129
+ return undefined;
130
+ }
131
+ return loadPersonaForRole(agentName, roots);
132
+ }