@hve-squad/mcp 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +46 -0
- package/README.md +233 -0
- package/dist/src/auth/entra.js +164 -0
- package/dist/src/auth/jose-verifier.js +31 -0
- package/dist/src/auth/scopes.js +240 -0
- package/dist/src/catalog/catalog.js +80 -0
- package/dist/src/config/operator-config.js +281 -0
- package/dist/src/engine/advisory-pipeline.js +367 -0
- package/dist/src/engine/advisory-run-store.js +31 -0
- package/dist/src/engine/artifact-store.js +165 -0
- package/dist/src/engine/auto-memory.js +207 -0
- package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
- package/dist/src/engine/backends/azure-openai.js +69 -0
- package/dist/src/engine/backends/azure-table-run-state.js +319 -0
- package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
- package/dist/src/engine/backends/file-squad-memory.js +208 -0
- package/dist/src/engine/backends/graph-squad-memory.js +271 -0
- package/dist/src/engine/backends/managed-identity-credential.js +33 -0
- package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
- package/dist/src/engine/backlog-contract.js +200 -0
- package/dist/src/engine/business-tools.js +118 -0
- package/dist/src/engine/consumption.js +134 -0
- package/dist/src/engine/coordinator-engine.js +1 -0
- package/dist/src/engine/council.js +204 -0
- package/dist/src/engine/delegated.js +190 -0
- package/dist/src/engine/dispatch-loop.js +84 -0
- package/dist/src/engine/durable-run-state.js +251 -0
- package/dist/src/engine/embedded-prompt.js +35 -0
- package/dist/src/engine/embedded-roles.js +133 -0
- package/dist/src/engine/embedded.js +1023 -0
- package/dist/src/engine/federation.js +96 -0
- package/dist/src/engine/field-cipher.js +84 -0
- package/dist/src/engine/gates.js +241 -0
- package/dist/src/engine/markdown-table.js +43 -0
- package/dist/src/engine/model-backend.js +16 -0
- package/dist/src/engine/persona-loader.js +132 -0
- package/dist/src/engine/persona.js +287 -0
- package/dist/src/engine/profiles.js +237 -0
- package/dist/src/engine/render/pptx-render-service.js +60 -0
- package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
- package/dist/src/engine/render/render-backend.js +25 -0
- package/dist/src/engine/render-embedded.js +69 -0
- package/dist/src/engine/routing.js +275 -0
- package/dist/src/engine/run-params.js +70 -0
- package/dist/src/engine/run-state.js +132 -0
- package/dist/src/engine/run-worker.js +60 -0
- package/dist/src/engine/squad-history.js +136 -0
- package/dist/src/engine/squad-ledger.js +215 -0
- package/dist/src/engine/squad-memory-resources.js +218 -0
- package/dist/src/engine/squad-memory-state.js +57 -0
- package/dist/src/engine/squad-run-recorder.js +212 -0
- package/dist/src/engine/targeted-squad-memory.js +94 -0
- package/dist/src/engine/workspace.js +68 -0
- package/dist/src/observability/logger.js +75 -0
- package/dist/src/observability/redact.js +77 -0
- package/dist/src/paths.js +108 -0
- package/dist/src/router/router.js +88 -0
- package/dist/src/server-http.js +304 -0
- package/dist/src/server.js +237 -0
- package/dist/src/transports/http-core.js +1240 -0
- package/dist/src/transports/http.js +90 -0
- package/dist/src/transports/session-store.js +78 -0
- package/dist/src/transports/stdio.js +12 -0
- package/dist/src/worker-main.js +87 -0
- package/generated/copilot-studio-connector/README.md +44 -0
- package/generated/copilot-studio-connector/agent-instructions.md +90 -0
- package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
- package/generated/copilot-studio-connector/apiProperties.json +35 -0
- package/generated/copilot-studio-connector/connector.manifest.json +86 -0
- package/generated/mcp-tools.schema.json +462 -0
- package/package.json +61 -0
- package/tools.catalog.yml +397 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared squad-memory MCP resource provider (shared-state broker — DR-01 / DR-10).
|
|
3
|
+
*
|
|
4
|
+
* Maps the `squad-memory://` URI scheme onto a {@link SquadMemoryStore} so the
|
|
5
|
+
* SAME read surface serves BOTH transports:
|
|
6
|
+
* * stdio (`src/server.ts`) — inside the local trust boundary, keyed on the
|
|
7
|
+
* {@link LOCAL_MEMORY_TENANT} sentinel.
|
|
8
|
+
* * HTTP (`src/transports/http-core.ts`) — keyed on the authenticated
|
|
9
|
+
* `tenantId` from the validated Entra token (never caller input; SEC-3).
|
|
10
|
+
*
|
|
11
|
+
* MCP resources are READ-ONLY (write-back is the `squad_memory_write` tool doing
|
|
12
|
+
* CAS — a later phase); the provider therefore exposes only `list` / `read` plus
|
|
13
|
+
* the RFC 6570 `templates` families and never mutates the store.
|
|
14
|
+
*
|
|
15
|
+
* URI scheme (tenant IMPLICIT — never encoded in the URI, so a caller can never
|
|
16
|
+
* name a foreign tenant):
|
|
17
|
+
* * `squad-memory://<project>/state`
|
|
18
|
+
* * `squad-memory://<project>/decisions`
|
|
19
|
+
* * `squad-memory://<project>/history/<agent>`
|
|
20
|
+
* * `squad-memory://<project>/repo-memory/<name>`
|
|
21
|
+
*
|
|
22
|
+
* SEC-4 — every `project` / `path` parsed out of a URI is re-validated with the
|
|
23
|
+
* Phase 1 {@link isSafeMemorySegment} / {@link isSafeMemoryPath} guards before it
|
|
24
|
+
* reaches the store, so a traversal payload can never escape its partition. An
|
|
25
|
+
* unknown/malformed URI AND a missing entry surface the SAME generic
|
|
26
|
+
* {@link McpError} (no detail that could enumerate another tenant's memory —
|
|
27
|
+
* DR-01 no-leakage).
|
|
28
|
+
*/
|
|
29
|
+
import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
30
|
+
import { isSafeMemoryPath, isSafeMemorySegment, } from "./squad-memory-state.js";
|
|
31
|
+
/** The custom URI scheme the broker publishes memory resources under. */
|
|
32
|
+
export const SQUAD_MEMORY_URI_SCHEME = "squad-memory";
|
|
33
|
+
/** The `squad-memory://` prefix every memory resource URI carries. */
|
|
34
|
+
const SCHEME_PREFIX = `${SQUAD_MEMORY_URI_SCHEME}://`;
|
|
35
|
+
/**
|
|
36
|
+
* The tenant sentinel used on the stdio transport. stdio is inside the local
|
|
37
|
+
* user's trust boundary (no Entra token to resolve a tenant from), so its memory
|
|
38
|
+
* is namespaced under this single local tenant rather than a real tenant id.
|
|
39
|
+
*/
|
|
40
|
+
export const LOCAL_MEMORY_TENANT = "local";
|
|
41
|
+
/** The MIME type reported for squad memory + history (markdown documents). */
|
|
42
|
+
export const SQUAD_MEMORY_MIME_TYPE = "text/markdown";
|
|
43
|
+
/**
|
|
44
|
+
* RFC 6570 template for the per-agent session-history family. Phase 3 + Phase 6
|
|
45
|
+
* wire against this constant; the `{project}` / `{agent}` variables expand to a
|
|
46
|
+
* concrete `squad-memory://<project>/history/<agent>` URI.
|
|
47
|
+
*/
|
|
48
|
+
export const SQUAD_MEMORY_HISTORY_URI_TEMPLATE = `${SCHEME_PREFIX}{project}/history/{agent}`;
|
|
49
|
+
/**
|
|
50
|
+
* RFC 6570 template for the repository-memory family (e.g. `repo-memory/squad-<agent>`).
|
|
51
|
+
* `{project}` / `{name}` expand to a concrete `squad-memory://<project>/repo-memory/<name>` URI.
|
|
52
|
+
*/
|
|
53
|
+
export const SQUAD_MEMORY_REPO_MEMORY_URI_TEMPLATE = `${SCHEME_PREFIX}{project}/repo-memory/{name}`;
|
|
54
|
+
/**
|
|
55
|
+
* The single generic message returned for an unknown/malformed URI OR a missing
|
|
56
|
+
* entry. Kept identical for both so a caller cannot distinguish "does not exist"
|
|
57
|
+
* from "not accessible" and enumerate memory (DR-01 no-leakage).
|
|
58
|
+
*/
|
|
59
|
+
const UNRESOLVED_URI_MESSAGE = "Unknown or inaccessible resource URI.";
|
|
60
|
+
/**
|
|
61
|
+
* Parse and re-validate a `squad-memory://` URI. Returns `undefined` for any URI
|
|
62
|
+
* that is not this scheme, is missing a project/path, or carries an unsafe
|
|
63
|
+
* segment (SEC-4) — the caller surfaces those as a single generic error.
|
|
64
|
+
*/
|
|
65
|
+
function parseMemoryUri(uri) {
|
|
66
|
+
if (!uri.startsWith(SCHEME_PREFIX)) {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
const rest = uri.slice(SCHEME_PREFIX.length);
|
|
70
|
+
const slash = rest.indexOf("/");
|
|
71
|
+
if (slash <= 0) {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
const project = rest.slice(0, slash);
|
|
75
|
+
const path = rest.slice(slash + 1);
|
|
76
|
+
if (path.length === 0 || !isSafeMemorySegment(project) || !isSafeMemoryPath(path)) {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
return { project, path };
|
|
80
|
+
}
|
|
81
|
+
/** A one-line description keyed on the memory path family. */
|
|
82
|
+
function describePath(project, path) {
|
|
83
|
+
if (path === "state") {
|
|
84
|
+
return `Current working state for project '${project}'.`;
|
|
85
|
+
}
|
|
86
|
+
if (path === "decisions") {
|
|
87
|
+
return `Recorded decisions for project '${project}'.`;
|
|
88
|
+
}
|
|
89
|
+
if (path.startsWith("history/")) {
|
|
90
|
+
return `Session history for agent '${path.slice("history/".length)}' in project '${project}'.`;
|
|
91
|
+
}
|
|
92
|
+
if (path.startsWith("repo-memory/")) {
|
|
93
|
+
return `Repository memory '${path.slice("repo-memory/".length)}' for project '${project}'.`;
|
|
94
|
+
}
|
|
95
|
+
return `Squad memory entry '${path}' for project '${project}'.`;
|
|
96
|
+
}
|
|
97
|
+
/** Build a `resources/list` descriptor for a concrete `project`/`path` entry. */
|
|
98
|
+
function toDescriptor(project, path) {
|
|
99
|
+
return {
|
|
100
|
+
uri: `${SCHEME_PREFIX}${project}/${path}`,
|
|
101
|
+
name: `${project}/${path}`,
|
|
102
|
+
description: describePath(project, path),
|
|
103
|
+
mimeType: SQUAD_MEMORY_MIME_TYPE,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The transport-agnostic memory read surface. Every method takes `tenantId`
|
|
108
|
+
* FIRST — the isolation key is supplied by the transport (a validated token on
|
|
109
|
+
* HTTP, the local sentinel on stdio) and is NEVER derived from the URI or any
|
|
110
|
+
* other caller input.
|
|
111
|
+
*/
|
|
112
|
+
export class SquadMemoryResourceProvider {
|
|
113
|
+
store;
|
|
114
|
+
constructor(store) {
|
|
115
|
+
this.store = store;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* List every stored memory resource for a tenant across all of its projects
|
|
119
|
+
* (`state`, `decisions`, `history/<agent>`, `repo-memory/<name>`). Only entries
|
|
120
|
+
* that actually exist are returned — the templates cover the open-ended families.
|
|
121
|
+
*/
|
|
122
|
+
async list(tenantId) {
|
|
123
|
+
const projects = await this.store.listProjects(tenantId);
|
|
124
|
+
const perProject = await Promise.all(projects.map((project) => this.store.list(tenantId, project)));
|
|
125
|
+
const descriptors = [];
|
|
126
|
+
projects.forEach((project, index) => {
|
|
127
|
+
for (const entry of perProject[index]) {
|
|
128
|
+
descriptors.push(toDescriptor(project, entry.path));
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return descriptors;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Read one memory resource by URI, scoped to `tenantId`. Throws a single
|
|
135
|
+
* generic {@link McpError} for an unknown/malformed URI OR a missing entry so a
|
|
136
|
+
* caller cannot distinguish the two (DR-01 no-leakage).
|
|
137
|
+
*/
|
|
138
|
+
async read(tenantId, uri) {
|
|
139
|
+
const parsed = parseMemoryUri(uri);
|
|
140
|
+
if (!parsed) {
|
|
141
|
+
throw new McpError(ErrorCode.InvalidParams, UNRESOLVED_URI_MESSAGE);
|
|
142
|
+
}
|
|
143
|
+
const entry = await this.store.read(tenantId, parsed.project, parsed.path);
|
|
144
|
+
if (!entry) {
|
|
145
|
+
throw new McpError(ErrorCode.InvalidParams, UNRESOLVED_URI_MESSAGE);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
contents: [{ uri, mimeType: SQUAD_MEMORY_MIME_TYPE, text: entry.content }],
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The RFC 6570 templates for the open-ended memory families. Static metadata
|
|
153
|
+
* (no store read, no tenant) describing how a caller composes a concrete
|
|
154
|
+
* `history/<agent>` or `repo-memory/<name>` URI.
|
|
155
|
+
*/
|
|
156
|
+
templates() {
|
|
157
|
+
return [
|
|
158
|
+
{
|
|
159
|
+
uriTemplate: SQUAD_MEMORY_HISTORY_URI_TEMPLATE,
|
|
160
|
+
name: "Squad agent history",
|
|
161
|
+
description: "Per-agent session history within a project.",
|
|
162
|
+
mimeType: SQUAD_MEMORY_MIME_TYPE,
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
uriTemplate: SQUAD_MEMORY_REPO_MEMORY_URI_TEMPLATE,
|
|
166
|
+
name: "Squad repository memory",
|
|
167
|
+
description: "Named repository-scoped memory within a project.",
|
|
168
|
+
mimeType: SQUAD_MEMORY_MIME_TYPE,
|
|
169
|
+
},
|
|
170
|
+
];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* A tiny in-process subscription registry for live resource push (WI-01, stdio
|
|
175
|
+
* ONLY — CON-1: the HTTP transport is POST-only, so `notifications/*` cannot be
|
|
176
|
+
* delivered to Copilot Studio; that path stays poll-on-read).
|
|
177
|
+
*
|
|
178
|
+
* It tracks the set of `squad-memory://` URIs a connected client asked to watch
|
|
179
|
+
* via `resources/subscribe` and exposes a single {@link onWrite} hook a mutation
|
|
180
|
+
* path calls. When the mutated URI is subscribed, it invokes the injected
|
|
181
|
+
* {@link MemoryResourceUpdateNotifier} EXACTLY ONCE (wired in `src/server.ts` to
|
|
182
|
+
* `Server.sendResourceUpdated`), so a subscriber is refreshed without re-polling.
|
|
183
|
+
*
|
|
184
|
+
* Transport-agnostic and reusable by design: the write path that calls
|
|
185
|
+
* {@link onWrite} is supplied by the caller, so a future stdio write tool and the
|
|
186
|
+
* Phase 4 `squad_memory_sync` batch CAS tool can both trigger the same hook
|
|
187
|
+
* without this module depending on either existing yet.
|
|
188
|
+
*/
|
|
189
|
+
export class SquadMemorySubscriptionRegistry {
|
|
190
|
+
subscribed = new Set();
|
|
191
|
+
notify;
|
|
192
|
+
constructor(notify) {
|
|
193
|
+
this.notify = notify;
|
|
194
|
+
}
|
|
195
|
+
/** Record interest in a URI (idempotent — a Set collapses duplicate subscribes). */
|
|
196
|
+
subscribe(uri) {
|
|
197
|
+
this.subscribed.add(uri);
|
|
198
|
+
}
|
|
199
|
+
/** Drop interest in a URI (idempotent — unsubscribing an unknown URI is a no-op). */
|
|
200
|
+
unsubscribe(uri) {
|
|
201
|
+
this.subscribed.delete(uri);
|
|
202
|
+
}
|
|
203
|
+
/** True when a client currently holds a subscription for `uri`. */
|
|
204
|
+
isSubscribed(uri) {
|
|
205
|
+
return this.subscribed.has(uri);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The hook a memory mutation path calls AFTER a write commits. Emits a single
|
|
209
|
+
* update notification for `uri` only when it is subscribed; an unwatched URI (or
|
|
210
|
+
* no subscriptions at all) is a silent no-op, so a write never notifies a client
|
|
211
|
+
* that did not ask for it.
|
|
212
|
+
*/
|
|
213
|
+
async onWrite(uri) {
|
|
214
|
+
if (this.subscribed.has(uri)) {
|
|
215
|
+
await this.notify(uri);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Squad memory-store seam (shared-state broker — DR-01 / DR-03).
|
|
3
|
+
*
|
|
4
|
+
* The Scenario B broker exposes the project's own `.copilot-tracking/squad/`
|
|
5
|
+
* memory + history as scope-guarded, tenant-isolated MCP resources plus a
|
|
6
|
+
* compare-and-swap (CAS) write-back tool. This module defines the persistence
|
|
7
|
+
* ENTITY and the store SEAM the broker reads/writes through, deliberately
|
|
8
|
+
* SEPARATE from the run-shaped {@link import("./run-state.js").RunState} (a memory
|
|
9
|
+
* entry is not a run — DR-03 forbids overloading `RunState`).
|
|
10
|
+
*
|
|
11
|
+
* Two realizations land beside this seam, mirroring the run-state stores:
|
|
12
|
+
* * `file` — {@link import("./backends/file-squad-memory.js").FileSquadMemoryStore}
|
|
13
|
+
* (single-replica, directory-backed; dev / single-instance).
|
|
14
|
+
* * `table` — {@link import("./backends/azure-table-squad-memory.js").AzureTableSquadMemoryStore}
|
|
15
|
+
* (Azure Table Storage with ETag CAS; multi-replica / production).
|
|
16
|
+
*
|
|
17
|
+
* Security posture (held by BOTH realizations):
|
|
18
|
+
* * Tenant isolation — the store key is ALWAYS prefixed with the authenticated
|
|
19
|
+
* `tenantId` (from the validated Entra token, never caller input). `project`
|
|
20
|
+
* is an explicit input (shape-checked at the protocol layer in later phases);
|
|
21
|
+
* the stores additionally reject unsafe segments so a traversal payload can
|
|
22
|
+
* never reach the filesystem / a foreign partition (SEC-4, defense in depth).
|
|
23
|
+
* * Encryption at rest — `content` is caller/model text, so both stores encrypt
|
|
24
|
+
* it with the injected {@link import("./field-cipher.js").FieldCipher} exactly
|
|
25
|
+
* as the run-state stores protect `request`/`context` (MEDIUM-3).
|
|
26
|
+
* * CAS — `write` takes an optional `expectedEtag`; a stale token loses the
|
|
27
|
+
* race (a 412 in the table store, an etag mismatch in the file store) so a
|
|
28
|
+
* concurrent writer never silently clobbers another's write.
|
|
29
|
+
*/
|
|
30
|
+
/** A single safe path segment: alphanumerics plus `.`, `_`, `-` (no traversal). */
|
|
31
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
|
|
32
|
+
/**
|
|
33
|
+
* True when a memory `path` is safe to use as a store key / filesystem location:
|
|
34
|
+
* one or more `/`-joined {@link SAFE_SEGMENT}s with no empty, `.`, or `..`
|
|
35
|
+
* segment. This is the SEC-4 traversal guard both stores apply before a caller
|
|
36
|
+
* `path` reaches the filesystem or a table RowKey (defense in depth; the protocol
|
|
37
|
+
* layer shape-checks inputs separately in later phases).
|
|
38
|
+
*/
|
|
39
|
+
export function isSafeMemoryPath(path) {
|
|
40
|
+
if (path.length === 0) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
const segments = path.split("/");
|
|
44
|
+
return segments.every((segment) => segment !== "." && segment !== ".." && SAFE_SEGMENT.test(segment));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* True when a tenant/project identifier is a single safe segment (no `/`, no
|
|
48
|
+
* traversal). `tenantId` is a validated Entra tenant id and `project` is
|
|
49
|
+
* shape-checked at the protocol layer, but the stores re-check so a bad value can
|
|
50
|
+
* never escape its partition / directory. Dot-segments (`.` / `..`) are rejected
|
|
51
|
+
* even though they match {@link SAFE_SEGMENT}'s character class: a bare `..`
|
|
52
|
+
* segment would otherwise collapse under `path.join` in the file backend and let
|
|
53
|
+
* a caller escape its tenant/project directory into a foreign partition (SEC-4).
|
|
54
|
+
*/
|
|
55
|
+
export function isSafeMemorySegment(segment) {
|
|
56
|
+
return segment !== "." && segment !== ".." && SAFE_SEGMENT.test(segment);
|
|
57
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { parseBacklog } from "./backlog-contract.js";
|
|
2
|
+
import { rebuildConsumption, renderConsumptionBlock } from "./consumption.js";
|
|
3
|
+
import { defaultProfileTables, deliverableRootFor, resolveProfile, } from "./profiles.js";
|
|
4
|
+
import { SquadHistory } from "./squad-history.js";
|
|
5
|
+
import { SquadLedger } from "./squad-ledger.js";
|
|
6
|
+
/**
|
|
7
|
+
* Pull the pptx skill's content YAML out of a presenter completion.
|
|
8
|
+
*
|
|
9
|
+
* Requires a fenced block carrying a top-level `slides:` key rather than
|
|
10
|
+
* accepting any YAML, because the presenter also emits YAML-ish fragments in
|
|
11
|
+
* prose and rendering the wrong one produces a confidently wrong deck.
|
|
12
|
+
*/
|
|
13
|
+
export function extractDeckYaml(text) {
|
|
14
|
+
const fences = text.matchAll(/```(?:ya?ml)?\s*\n([\s\S]*?)```/g);
|
|
15
|
+
for (const fence of fences) {
|
|
16
|
+
const body = fence[1];
|
|
17
|
+
if (/^slides\s*:/m.test(body)) {
|
|
18
|
+
return body.trim();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
export class SquadRunRecorder {
|
|
24
|
+
ledger;
|
|
25
|
+
history;
|
|
26
|
+
store;
|
|
27
|
+
tables;
|
|
28
|
+
renderer;
|
|
29
|
+
logger;
|
|
30
|
+
today;
|
|
31
|
+
constructor(deps) {
|
|
32
|
+
this.ledger = new SquadLedger(deps.store);
|
|
33
|
+
this.history = new SquadHistory(deps.store);
|
|
34
|
+
this.store = deps.store;
|
|
35
|
+
this.tables = deps.tables ?? defaultProfileTables();
|
|
36
|
+
this.renderer = deps.renderer;
|
|
37
|
+
this.logger = deps.logger;
|
|
38
|
+
this.today = deps.today ?? (() => new Date().toISOString().slice(0, 10));
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Seed the squad if this is the project's first run, and return the history
|
|
42
|
+
* index block to merge into the request `context` as DATA.
|
|
43
|
+
*
|
|
44
|
+
* The seeded profile is returned rather than the requested one: an existing
|
|
45
|
+
* `team.md` wins, so a later caller passing a different `profile` never
|
|
46
|
+
* silently re-casts a squad the project is already running under.
|
|
47
|
+
*/
|
|
48
|
+
async open(tenantId, project, request) {
|
|
49
|
+
const requested = resolveProfile(request.profile, this.tables);
|
|
50
|
+
const opts = this.optionsFor(request);
|
|
51
|
+
try {
|
|
52
|
+
const seeded = await this.ledger.seed(tenantId, project, requested, this.tables, opts);
|
|
53
|
+
const effective = seeded.profile === requested.name ? requested : resolveProfile(seeded.profile, this.tables);
|
|
54
|
+
const historyBlock = await this.history.contextBlock(tenantId, project);
|
|
55
|
+
return { profile: effective, historyBlock };
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
this.warn("squad ledger open failed; the run continues without a durable record", error);
|
|
59
|
+
return { profile: requested };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Persist a completed stage: its deliverable and its agent history entry. */
|
|
63
|
+
async recordStage(tenantId, project, request, runId, stage) {
|
|
64
|
+
const opts = this.optionsFor(request);
|
|
65
|
+
// A single-stage hero dispatch knows only the agent name, so recover the role
|
|
66
|
+
// from the roster — the Deliverable Root is looked up by role, not by agent.
|
|
67
|
+
const roleKey = stage.roleKey ?? this.roleKeyForAgent(stage.agentName);
|
|
68
|
+
try {
|
|
69
|
+
let deliverablePath;
|
|
70
|
+
if (roleKey) {
|
|
71
|
+
deliverablePath = await this.ledger.writeDeliverable(tenantId, project, roleKey, `${this.today()}-${runId}`, stage.artifact, this.tables, opts);
|
|
72
|
+
}
|
|
73
|
+
await this.ledger.appendAgentHistory(tenantId, project, stage.agentName, [
|
|
74
|
+
`### ${this.today()} — run ${runId}`,
|
|
75
|
+
"",
|
|
76
|
+
`* Role: ${roleKey ?? "(unmapped)"}`,
|
|
77
|
+
`* Deliverable: ${deliverablePath ?? "(returned findings to the coordinator)"}`,
|
|
78
|
+
...(stage.usage
|
|
79
|
+
? [
|
|
80
|
+
"",
|
|
81
|
+
renderConsumptionBlock({
|
|
82
|
+
role: roleKey ?? "unmapped",
|
|
83
|
+
agentName: stage.agentName,
|
|
84
|
+
model: stage.backendId ?? "unknown",
|
|
85
|
+
inputTokens: stage.usage.inputTokens ?? 0,
|
|
86
|
+
outputTokens: stage.usage.outputTokens ?? 0,
|
|
87
|
+
costUsd: stage.usage.estimatedCostUsd ?? 0,
|
|
88
|
+
}),
|
|
89
|
+
]
|
|
90
|
+
: []),
|
|
91
|
+
].join("\n"));
|
|
92
|
+
await this.ledger.appendRunHistory(tenantId, project, runId, `* ${stage.agentName} — ${deliverablePath ?? "findings only"}`);
|
|
93
|
+
await this.finishDeliverable(tenantId, project, roleKey, runId, stage, opts);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
this.warn("squad ledger stage record failed", error);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Turn a specialist's prose into the artifact the role actually owes.
|
|
101
|
+
*
|
|
102
|
+
* `presenter` owes a deck, not a description of one; `product-owner` owes work
|
|
103
|
+
* items a connector can create, not a bulleted list a human must retype. Both
|
|
104
|
+
* degrade to "the markdown is still there" rather than failing the run, because
|
|
105
|
+
* a model that did not follow the output contract is a quality problem, not an
|
|
106
|
+
* outage.
|
|
107
|
+
*/
|
|
108
|
+
async finishDeliverable(tenantId, project, roleKey, runId, stage, opts) {
|
|
109
|
+
if (roleKey === "presenter" && this.renderer) {
|
|
110
|
+
const contentYaml = extractDeckYaml(stage.artifact);
|
|
111
|
+
if (!contentYaml) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const rendered = await this.renderer.render({ contentYaml, styleYaml: "" }, { tenantId });
|
|
115
|
+
const note = rendered.content.map((part) => part.text ?? "").join("\n");
|
|
116
|
+
const root = deliverableRootFor("presenter", this.tables, {
|
|
117
|
+
squad: opts.squad,
|
|
118
|
+
date: opts.date,
|
|
119
|
+
});
|
|
120
|
+
if (!root) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
// The .pptx itself lives in the render container behind a short-lived SAS;
|
|
124
|
+
// the tracking tree carries the pointer and the source YAML so the deck is
|
|
125
|
+
// reproducible after the link expires.
|
|
126
|
+
await this.store.put(tenantId, project, `${root}/deck-${runId}.yaml`, contentYaml);
|
|
127
|
+
await this.store.put(tenantId, project, `${root}/deck-${runId}.md`, rendered.isError ? `# Deck render failed\n\n${note}` : `# Deck\n\n${note}`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (roleKey === "product-owner") {
|
|
131
|
+
const backlog = parseBacklog(stage.artifact);
|
|
132
|
+
if (backlog.workItems.length === 0) {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const root = deliverableRootFor("product-owner", this.tables, {
|
|
136
|
+
squad: opts.squad,
|
|
137
|
+
date: opts.date,
|
|
138
|
+
});
|
|
139
|
+
if (!root) {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
// The flat `workItems[]` is what a Copilot Studio agent loops one item per
|
|
143
|
+
// call into the native ADO or Jira connector; this server writes nothing
|
|
144
|
+
// to either (ADR-0001).
|
|
145
|
+
await this.store.put(tenantId, project, `${root}/backlog-${runId}.json`, `${JSON.stringify(backlog, null, 2)}\n`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Reverse the Cast Catalog: an agent's `name:` back to the role it fills. */
|
|
149
|
+
roleKeyForAgent(agentName) {
|
|
150
|
+
const wanted = agentName.trim().toLowerCase();
|
|
151
|
+
for (const [role, row] of this.tables.cast) {
|
|
152
|
+
if (row.primary.trim().toLowerCase() === wanted) {
|
|
153
|
+
return role;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
/** Append a verdict block (council or intake) to the decision log. */
|
|
159
|
+
async recordDecision(tenantId, project, block) {
|
|
160
|
+
try {
|
|
161
|
+
await this.ledger.appendDecision(tenantId, project, block);
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
this.warn("squad ledger decision record failed", error);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Advance the turn counter and record the run that produced it. */
|
|
168
|
+
async closeRun(tenantId, project, runId, activeRoles) {
|
|
169
|
+
try {
|
|
170
|
+
const state = await this.ledger.readState(tenantId, project);
|
|
171
|
+
await this.ledger.updateState(tenantId, project, {
|
|
172
|
+
turn: (state?.turn ?? 0) + 1,
|
|
173
|
+
activeRoles,
|
|
174
|
+
currentRun: { id: runId },
|
|
175
|
+
updated: this.today(),
|
|
176
|
+
});
|
|
177
|
+
// Rebuilt from the recorded history rather than this turn's dispatches, so
|
|
178
|
+
// the ledger cannot silently drop the roles that ran on earlier turns.
|
|
179
|
+
await rebuildConsumption(this.store, tenantId, project);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
this.warn("squad ledger state update failed", error);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
optionsFor(request) {
|
|
186
|
+
return {
|
|
187
|
+
mode: request.mode,
|
|
188
|
+
tier: request.tier,
|
|
189
|
+
squad: request.squad,
|
|
190
|
+
date: this.today(),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Bind this recorder to one run, producing the sink the advisory pipeline
|
|
195
|
+
* writes each finished stage through.
|
|
196
|
+
*
|
|
197
|
+
* The pipeline knows the stage; the recorder knows the tenant, the project and
|
|
198
|
+
* the run. Binding them here keeps the pipeline free of storage types, exactly
|
|
199
|
+
* as its existing persistence seam does.
|
|
200
|
+
*/
|
|
201
|
+
sinkFor(tenantId, project, request, runId) {
|
|
202
|
+
return {
|
|
203
|
+
recordStage: (stage) => this.recordStage(tenantId, project, request, runId, stage),
|
|
204
|
+
recordDecision: (block) => this.recordDecision(tenantId, project, block),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
warn(message, error) {
|
|
208
|
+
this.logger?.warn(message, {
|
|
209
|
+
error: error instanceof Error ? error.message : String(error),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** Thrown when a caller names a target the operator did not declare. */
|
|
2
|
+
export class UnknownMemoryTargetError extends Error {
|
|
3
|
+
requested;
|
|
4
|
+
constructor(requested) {
|
|
5
|
+
// Deliberately lists the ALLOWED names only — never the requested value
|
|
6
|
+
// (which is caller text) and never any destination detail.
|
|
7
|
+
super("Unknown memory target.");
|
|
8
|
+
this.requested = requested;
|
|
9
|
+
this.name = "UnknownMemoryTargetError";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Target-name shape: a short, opaque, lower-kebab-case label. */
|
|
13
|
+
const TARGET_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
14
|
+
/**
|
|
15
|
+
* A {@link SquadMemoryStore} that dispatches to one of several operator-declared
|
|
16
|
+
* stores. It implements the plain seam (so every existing caller keeps working,
|
|
17
|
+
* routed to the default target) and adds `*On(target, …)` variants for the call
|
|
18
|
+
* sites that accept a caller-selected target.
|
|
19
|
+
*/
|
|
20
|
+
export class TargetedSquadMemoryStore {
|
|
21
|
+
targets;
|
|
22
|
+
defaultTarget;
|
|
23
|
+
constructor(options) {
|
|
24
|
+
if (options.targets.size === 0) {
|
|
25
|
+
throw new Error("TargetedSquadMemoryStore requires at least one target.");
|
|
26
|
+
}
|
|
27
|
+
for (const name of options.targets.keys()) {
|
|
28
|
+
if (!TARGET_NAME.test(name)) {
|
|
29
|
+
throw new Error(`Memory target name "${name}" must be lower-kebab-case.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (!options.targets.has(options.defaultTarget)) {
|
|
33
|
+
throw new Error(`Default memory target "${options.defaultTarget}" is not a declared target.`);
|
|
34
|
+
}
|
|
35
|
+
this.targets = options.targets;
|
|
36
|
+
this.defaultTarget = options.defaultTarget;
|
|
37
|
+
}
|
|
38
|
+
/** The declared target names, for connector/tool-schema projection and docs. */
|
|
39
|
+
targetNames() {
|
|
40
|
+
return [...this.targets.keys()].sort();
|
|
41
|
+
}
|
|
42
|
+
/** The name used when a call selects none. */
|
|
43
|
+
get defaultTargetName() {
|
|
44
|
+
return this.defaultTarget;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Resolve a caller-supplied target name. `undefined` / empty selects the default.
|
|
48
|
+
* Any other unmatched value throws {@link UnknownMemoryTargetError} — fail-closed,
|
|
49
|
+
* never a silent fallback to the default, which would write a caller's memory
|
|
50
|
+
* somewhere it did not ask for.
|
|
51
|
+
*/
|
|
52
|
+
resolve(target) {
|
|
53
|
+
const name = (target ?? "").trim();
|
|
54
|
+
if (name.length === 0) {
|
|
55
|
+
return this.targets.get(this.defaultTarget);
|
|
56
|
+
}
|
|
57
|
+
const store = this.targets.get(name);
|
|
58
|
+
if (!store) {
|
|
59
|
+
throw new UnknownMemoryTargetError(name);
|
|
60
|
+
}
|
|
61
|
+
return store;
|
|
62
|
+
}
|
|
63
|
+
// --- plain seam (default target) -----------------------------------------
|
|
64
|
+
list(tenantId, project) {
|
|
65
|
+
return this.resolve().list(tenantId, project);
|
|
66
|
+
}
|
|
67
|
+
read(tenantId, project, path) {
|
|
68
|
+
return this.resolve().read(tenantId, project, path);
|
|
69
|
+
}
|
|
70
|
+
write(tenantId, project, path, content, expectedEtag) {
|
|
71
|
+
return this.resolve().write(tenantId, project, path, content, expectedEtag);
|
|
72
|
+
}
|
|
73
|
+
listProjects(tenantId) {
|
|
74
|
+
return this.resolve().listProjects(tenantId);
|
|
75
|
+
}
|
|
76
|
+
// --- target-selecting variants -------------------------------------------
|
|
77
|
+
listOn(target, tenantId, project) {
|
|
78
|
+
return this.resolve(target).list(tenantId, project);
|
|
79
|
+
}
|
|
80
|
+
readOn(target, tenantId, project, path) {
|
|
81
|
+
return this.resolve(target).read(tenantId, project, path);
|
|
82
|
+
}
|
|
83
|
+
writeOn(target, tenantId, project, path, content, expectedEtag) {
|
|
84
|
+
return this.resolve(target).write(tenantId, project, path, content, expectedEtag);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Narrow a store to the targeted decorator, for call sites that support a
|
|
89
|
+
* caller-selected target. Returns `undefined` for a plain single-destination
|
|
90
|
+
* store, so those deployments simply ignore the `target` input.
|
|
91
|
+
*/
|
|
92
|
+
export function asTargetedStore(store) {
|
|
93
|
+
return store instanceof TargetedSquadMemoryStore ? store : undefined;
|
|
94
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-allocated ephemeral per-request workspace (SEC-4).
|
|
3
|
+
*
|
|
4
|
+
* Tenant isolation is server-controlled and verifiable:
|
|
5
|
+
*
|
|
6
|
+
* * Workspace roots are **server-allocated** under the OS temp dir, namespaced
|
|
7
|
+
* by a hash of the tenant id plus a CSPRNG run id. A caller can neither name
|
|
8
|
+
* nor predict the path — `request`/`context` never contribute to it.
|
|
9
|
+
* * `resolve()` confines every path to the workspace root: any `..` traversal
|
|
10
|
+
* or absolute path that would escape the root throws, so an injected path in
|
|
11
|
+
* a tool input cannot reach another tenant's workspace or the host FS.
|
|
12
|
+
* * `dispose()` guarantees teardown (recursive remove, idempotent, error-safe)
|
|
13
|
+
* so it can run in a `finally` even after a failed or timed-out run.
|
|
14
|
+
* * Every `allocate()` returns a fresh unique directory — there is no shared
|
|
15
|
+
* mutable state across tenants or across calls.
|
|
16
|
+
*
|
|
17
|
+
* The thin slice's hero tool does inference plus file/memory work inside this
|
|
18
|
+
* directory ONLY; it never spawns a shell or process (SEC-7, enforced in the
|
|
19
|
+
* embedded engine).
|
|
20
|
+
*/
|
|
21
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
22
|
+
import { mkdir, rm } from "node:fs/promises";
|
|
23
|
+
import { tmpdir } from "node:os";
|
|
24
|
+
import { isAbsolute, join, resolve, sep } from "node:path";
|
|
25
|
+
/** Stable, non-reversible per-tenant directory namespace (keeps the raw tenant id off the path). */
|
|
26
|
+
function tenantNamespace(tenantId) {
|
|
27
|
+
return createHash("sha256").update(tenantId).digest("hex").slice(0, 16);
|
|
28
|
+
}
|
|
29
|
+
class EphemeralWorkspace {
|
|
30
|
+
id;
|
|
31
|
+
tenantId;
|
|
32
|
+
root;
|
|
33
|
+
constructor(id, tenantId, root) {
|
|
34
|
+
this.id = id;
|
|
35
|
+
this.tenantId = tenantId;
|
|
36
|
+
this.root = root;
|
|
37
|
+
}
|
|
38
|
+
resolve(relativePath) {
|
|
39
|
+
if (isAbsolute(relativePath)) {
|
|
40
|
+
throw new Error("Workspace paths must be relative (SEC-4: containment).");
|
|
41
|
+
}
|
|
42
|
+
const candidate = resolve(this.root, relativePath);
|
|
43
|
+
if (candidate !== this.root && !candidate.startsWith(this.root + sep)) {
|
|
44
|
+
throw new Error("Path escapes the workspace root (SEC-4: containment).");
|
|
45
|
+
}
|
|
46
|
+
return candidate;
|
|
47
|
+
}
|
|
48
|
+
async dispose() {
|
|
49
|
+
await rm(this.root, { recursive: true, force: true });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Allocates fresh, isolated, ephemeral workspaces under the OS temp dir. */
|
|
53
|
+
export class EphemeralWorkspaceManager {
|
|
54
|
+
kind = "ephemeral";
|
|
55
|
+
baseDir;
|
|
56
|
+
constructor(options = {}) {
|
|
57
|
+
this.baseDir = options.baseDir ?? join(tmpdir(), "squad-mcp-workspaces");
|
|
58
|
+
}
|
|
59
|
+
async allocate(tenantId) {
|
|
60
|
+
if (!tenantId || tenantId.length === 0) {
|
|
61
|
+
throw new Error("A tenant id is required to allocate a workspace (SEC-4).");
|
|
62
|
+
}
|
|
63
|
+
const id = randomUUID();
|
|
64
|
+
const root = join(this.baseDir, tenantNamespace(tenantId), id);
|
|
65
|
+
await mkdir(root, { recursive: true });
|
|
66
|
+
return new EphemeralWorkspace(id, tenantId, root);
|
|
67
|
+
}
|
|
68
|
+
}
|