@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,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-backed squad-memory store (shared-state broker — file backend).
|
|
3
|
+
*
|
|
4
|
+
* The dev / single-replica realization of
|
|
5
|
+
* {@link import("../squad-memory-state.js").SquadMemoryStore}, mirroring
|
|
6
|
+
* {@link import("../durable-run-state.js").DurableRunStateStore}: it persists each
|
|
7
|
+
* entry as a JSON envelope under `<memoryDir>/<tenantId>/<project>/<path>.json`
|
|
8
|
+
* and carries an in-file `etag` (a version + content hash) so its compare-and-swap
|
|
9
|
+
* behaves like the table store's ETag CAS. It survives process restarts but is
|
|
10
|
+
* SINGLE-REPLICA (no cross-process atomicity); a multi-replica deployment uses the
|
|
11
|
+
* {@link import("./azure-table-squad-memory.js").AzureTableSquadMemoryStore}.
|
|
12
|
+
*
|
|
13
|
+
* Security posture:
|
|
14
|
+
* * Tenant isolation — the on-disk layout is rooted at `<memoryDir>/<tenantId>`,
|
|
15
|
+
* so an entry is physically namespaced by the authenticated tenant.
|
|
16
|
+
* * SEC-4 — `tenantId` / `project` / `path` are validated as safe segments and
|
|
17
|
+
* the resolved file path is verified to stay within the project directory, so
|
|
18
|
+
* a traversal payload (`..`) can never reach outside the memory root.
|
|
19
|
+
* * MEDIUM-3 — `content` is encrypted at rest with the injected
|
|
20
|
+
* {@link FieldCipher} and decrypted on read, exactly as the durable run-state
|
|
21
|
+
* store protects `request`/`context`.
|
|
22
|
+
*/
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
26
|
+
import { isSafeMemoryPath, isSafeMemorySegment, } from "../squad-memory-state.js";
|
|
27
|
+
import { NullFieldCipher } from "../field-cipher.js";
|
|
28
|
+
/** The suffix every persisted memory envelope carries on disk. */
|
|
29
|
+
const ENVELOPE_SUFFIX = ".json";
|
|
30
|
+
export class FileSquadMemoryStore {
|
|
31
|
+
baseDir;
|
|
32
|
+
cipher;
|
|
33
|
+
constructor(options) {
|
|
34
|
+
this.baseDir = resolve(options.baseDir);
|
|
35
|
+
this.cipher = options.cipher ?? new NullFieldCipher();
|
|
36
|
+
mkdirSync(this.baseDir, { recursive: true });
|
|
37
|
+
}
|
|
38
|
+
/** The project directory, or `undefined` when a segment is unsafe. */
|
|
39
|
+
projectDir(tenantId, project) {
|
|
40
|
+
if (!isSafeMemorySegment(tenantId) || !isSafeMemorySegment(project)) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
return join(this.baseDir, tenantId, project);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The envelope file for an entry, or `undefined` when a segment/path is unsafe
|
|
47
|
+
* OR the resolved path escapes the project directory (SEC-4 traversal guard).
|
|
48
|
+
*/
|
|
49
|
+
pathFor(tenantId, project, path) {
|
|
50
|
+
const dir = this.projectDir(tenantId, project);
|
|
51
|
+
if (dir === undefined || !isSafeMemoryPath(path)) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
const file = resolve(join(dir, `${path}${ENVELOPE_SUFFIX}`));
|
|
55
|
+
// Belt-and-suspenders: even with segment validation, verify containment.
|
|
56
|
+
const dirPrefix = resolve(dir) + sep;
|
|
57
|
+
if (!file.startsWith(dirPrefix)) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
return file;
|
|
61
|
+
}
|
|
62
|
+
/** Compute the next CAS etag from the write counter + content. */
|
|
63
|
+
nextEtag(version, content) {
|
|
64
|
+
return createHash("sha256").update(`${version}:${content}`).digest("hex").slice(0, 32);
|
|
65
|
+
}
|
|
66
|
+
/** Read + decrypt the envelope at a file path (undefined when absent/corrupt). */
|
|
67
|
+
readEnvelope(file) {
|
|
68
|
+
if (!existsSync(file)) {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const envelope = JSON.parse(readFileSync(file, "utf8"));
|
|
73
|
+
return { ...envelope, content: this.cipher.decrypt(envelope.content ?? "") };
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
list(tenantId, project) {
|
|
80
|
+
const dir = this.projectDir(tenantId, project);
|
|
81
|
+
if (dir === undefined || !existsSync(dir)) {
|
|
82
|
+
return Promise.resolve([]);
|
|
83
|
+
}
|
|
84
|
+
const entries = [];
|
|
85
|
+
for (const file of this.walk(dir)) {
|
|
86
|
+
const envelope = this.readEnvelope(file);
|
|
87
|
+
if (envelope) {
|
|
88
|
+
entries.push({
|
|
89
|
+
tenantId,
|
|
90
|
+
project,
|
|
91
|
+
path: envelope.path,
|
|
92
|
+
content: envelope.content ?? "",
|
|
93
|
+
etag: envelope.etag,
|
|
94
|
+
updatedAt: envelope.updatedAt,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return Promise.resolve(entries);
|
|
99
|
+
}
|
|
100
|
+
read(tenantId, project, path) {
|
|
101
|
+
const file = this.pathFor(tenantId, project, path);
|
|
102
|
+
if (file === undefined) {
|
|
103
|
+
return Promise.resolve(undefined);
|
|
104
|
+
}
|
|
105
|
+
const envelope = this.readEnvelope(file);
|
|
106
|
+
if (!envelope) {
|
|
107
|
+
return Promise.resolve(undefined);
|
|
108
|
+
}
|
|
109
|
+
return Promise.resolve({
|
|
110
|
+
tenantId,
|
|
111
|
+
project,
|
|
112
|
+
path: envelope.path,
|
|
113
|
+
content: envelope.content ?? "",
|
|
114
|
+
etag: envelope.etag,
|
|
115
|
+
updatedAt: envelope.updatedAt,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
write(tenantId, project, path, content, expectedEtag) {
|
|
119
|
+
const file = this.pathFor(tenantId, project, path);
|
|
120
|
+
if (file === undefined) {
|
|
121
|
+
// A malformed key never touches disk; treat as a lost race (no leakage).
|
|
122
|
+
return Promise.resolve({ ok: false, conflict: true, current: undefined });
|
|
123
|
+
}
|
|
124
|
+
const existing = this.readEnvelope(file);
|
|
125
|
+
if (expectedEtag !== undefined && (existing === undefined || existing.etag !== expectedEtag)) {
|
|
126
|
+
// CAS lost: the caller's expected revision no longer matches (or is gone).
|
|
127
|
+
const current = existing === undefined
|
|
128
|
+
? undefined
|
|
129
|
+
: {
|
|
130
|
+
tenantId,
|
|
131
|
+
project,
|
|
132
|
+
path: existing.path,
|
|
133
|
+
content: existing.content ?? "",
|
|
134
|
+
etag: existing.etag,
|
|
135
|
+
updatedAt: existing.updatedAt,
|
|
136
|
+
};
|
|
137
|
+
return Promise.resolve({ ok: false, conflict: true, current });
|
|
138
|
+
}
|
|
139
|
+
const version = (existing?.version ?? 0) + 1;
|
|
140
|
+
const etag = this.nextEtag(version, content);
|
|
141
|
+
const updatedAt = Date.now();
|
|
142
|
+
const envelope = {
|
|
143
|
+
project,
|
|
144
|
+
path,
|
|
145
|
+
content: this.cipher.encrypt(content),
|
|
146
|
+
etag,
|
|
147
|
+
version,
|
|
148
|
+
updatedAt,
|
|
149
|
+
};
|
|
150
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
151
|
+
writeFileSync(file, JSON.stringify(envelope), "utf8");
|
|
152
|
+
return Promise.resolve({
|
|
153
|
+
ok: true,
|
|
154
|
+
etag,
|
|
155
|
+
entry: { tenantId, project, path, content, etag, updatedAt },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
listProjects(tenantId) {
|
|
159
|
+
if (!isSafeMemorySegment(tenantId)) {
|
|
160
|
+
return Promise.resolve([]);
|
|
161
|
+
}
|
|
162
|
+
const tenantDir = join(this.baseDir, tenantId);
|
|
163
|
+
if (!existsSync(tenantDir)) {
|
|
164
|
+
return Promise.resolve([]);
|
|
165
|
+
}
|
|
166
|
+
let projects;
|
|
167
|
+
try {
|
|
168
|
+
projects = readdirSync(tenantDir).filter((entry) => {
|
|
169
|
+
try {
|
|
170
|
+
return statSync(join(tenantDir, entry)).isDirectory();
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return Promise.resolve([]);
|
|
179
|
+
}
|
|
180
|
+
return Promise.resolve(projects);
|
|
181
|
+
}
|
|
182
|
+
/** Recursively yield every envelope file path under a project directory. */
|
|
183
|
+
*walk(dir) {
|
|
184
|
+
let entries;
|
|
185
|
+
try {
|
|
186
|
+
entries = readdirSync(dir);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
for (const entry of entries) {
|
|
192
|
+
const full = join(dir, entry);
|
|
193
|
+
let isDir = false;
|
|
194
|
+
try {
|
|
195
|
+
isDir = statSync(full).isDirectory();
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (isDir) {
|
|
201
|
+
yield* this.walk(full);
|
|
202
|
+
}
|
|
203
|
+
else if (entry.endsWith(ENVELOPE_SUFFIX)) {
|
|
204
|
+
yield full;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Microsoft Graph drive realization of the {@link SquadMemoryStore} seam —
|
|
3
|
+
* squad memory persisted to **SharePoint** (a document library) or **OneDrive**
|
|
4
|
+
* instead of Azure Table / local disk.
|
|
5
|
+
*
|
|
6
|
+
* Motivation: the shipped broker could only persist to Azure (a Table partition or
|
|
7
|
+
* a local directory). Teams that already govern their knowledge in SharePoint want
|
|
8
|
+
* the squad's state, decisions, and per-agent history to land there — reviewable,
|
|
9
|
+
* versioned, searchable, and subject to their existing retention and DLP policy.
|
|
10
|
+
* Because the store seam takes `tenantId` first and speaks list/read/write/CAS,
|
|
11
|
+
* a Graph drive slots in with no change to the resource surface or the memory
|
|
12
|
+
* tools.
|
|
13
|
+
*
|
|
14
|
+
* Layout — one markdown file per memory entry:
|
|
15
|
+
*
|
|
16
|
+
* <rootPath>/<tenantId>/<project>/<path>.md
|
|
17
|
+
*
|
|
18
|
+
* The `tenantId` prefix is the isolation key and is ALWAYS supplied by the caller
|
|
19
|
+
* from the validated Entra token, never from tool input (SEC-3). Every segment is
|
|
20
|
+
* re-validated with the Phase 1 traversal guards before it reaches a URL, so a
|
|
21
|
+
* `..` payload can never escape the configured root (SEC-4).
|
|
22
|
+
*
|
|
23
|
+
* Concurrency: Graph gives DriveItems a native `eTag`, and `PUT .../content`
|
|
24
|
+
* honours `If-Match`, which maps exactly onto the seam's compare-and-swap
|
|
25
|
+
* contract — a stale token yields HTTP 412 and is surfaced as a conflict rather
|
|
26
|
+
* than a silent clobber, identical to the Table backend's behavior.
|
|
27
|
+
*
|
|
28
|
+
* Encryption: the Table and file backends encrypt `content` at rest (MEDIUM-3).
|
|
29
|
+
* That is deliberately OPT-IN here and defaults to OFF, because the entire point
|
|
30
|
+
* of a SharePoint target is that a human can open the file. An operator that wants
|
|
31
|
+
* ciphertext in SharePoint passes a real {@link FieldCipher}; the trade-off is
|
|
32
|
+
* documented rather than silently chosen.
|
|
33
|
+
*
|
|
34
|
+
* Auth: an app-only Graph bearer token (`https://graph.microsoft.com/.default`)
|
|
35
|
+
* obtained from the same managed-identity credential the other backends use. The
|
|
36
|
+
* token is registered with the redacting logger so it can never surface in a log
|
|
37
|
+
* line (SEC-10).
|
|
38
|
+
*/
|
|
39
|
+
import { isSafeMemoryPath, isSafeMemorySegment, } from "../squad-memory-state.js";
|
|
40
|
+
import { NullFieldCipher } from "../field-cipher.js";
|
|
41
|
+
/** The default Graph endpoint (overridable for sovereign clouds / tests). */
|
|
42
|
+
export const DEFAULT_GRAPH_ENDPOINT = "https://graph.microsoft.com/v1.0";
|
|
43
|
+
/** The file extension every memory entry is stored under (human-readable). */
|
|
44
|
+
const ENTRY_EXTENSION = ".md";
|
|
45
|
+
/** Percent-encode one path segment for Graph's `root:/<path>:` addressing. */
|
|
46
|
+
function encodeSegment(segment) {
|
|
47
|
+
return encodeURIComponent(segment);
|
|
48
|
+
}
|
|
49
|
+
/** Epoch ms for a Graph ISO timestamp; 0 when absent/unparseable. */
|
|
50
|
+
function toEpoch(iso) {
|
|
51
|
+
if (!iso) {
|
|
52
|
+
return 0;
|
|
53
|
+
}
|
|
54
|
+
const parsed = Date.parse(iso);
|
|
55
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
56
|
+
}
|
|
57
|
+
export class GraphSquadMemoryStore {
|
|
58
|
+
driveId;
|
|
59
|
+
rootSegments;
|
|
60
|
+
getAccessToken;
|
|
61
|
+
cipher;
|
|
62
|
+
fetchImpl;
|
|
63
|
+
logger;
|
|
64
|
+
endpoint;
|
|
65
|
+
constructor(options) {
|
|
66
|
+
if (!options.driveId || options.driveId.trim().length === 0) {
|
|
67
|
+
throw new Error("GraphSquadMemoryStore requires a driveId (the SharePoint/OneDrive drive).");
|
|
68
|
+
}
|
|
69
|
+
this.driveId = options.driveId.trim();
|
|
70
|
+
this.rootSegments = (options.rootPath ?? "")
|
|
71
|
+
.split("/")
|
|
72
|
+
.map((segment) => segment.trim())
|
|
73
|
+
.filter((segment) => segment.length > 0);
|
|
74
|
+
// Fail fast on a misconfigured root rather than emitting a traversal URL.
|
|
75
|
+
for (const segment of this.rootSegments) {
|
|
76
|
+
if (!isSafeMemorySegment(segment)) {
|
|
77
|
+
throw new Error(`GraphSquadMemoryStore rootPath segment "${segment}" is not a safe path segment.`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
this.getAccessToken = options.getAccessToken;
|
|
81
|
+
this.cipher = options.cipher ?? new NullFieldCipher();
|
|
82
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
83
|
+
this.logger = options.logger;
|
|
84
|
+
this.endpoint = (options.endpoint ?? DEFAULT_GRAPH_ENDPOINT).replace(/\/$/, "");
|
|
85
|
+
}
|
|
86
|
+
async headers(extra = {}) {
|
|
87
|
+
const token = await this.getAccessToken();
|
|
88
|
+
this.logger?.registerSecret(token);
|
|
89
|
+
return { Authorization: `Bearer ${token}`, Accept: "application/json", ...extra };
|
|
90
|
+
}
|
|
91
|
+
/** `<endpoint>/drives/<driveId>/root:/<encoded path>` (or `/root` at the root). */
|
|
92
|
+
itemUrl(segments, suffix = "") {
|
|
93
|
+
const base = `${this.endpoint}/drives/${encodeURIComponent(this.driveId)}`;
|
|
94
|
+
if (segments.length === 0) {
|
|
95
|
+
return suffix ? `${base}/root/${suffix.replace(/^\//, "")}` : `${base}/root`;
|
|
96
|
+
}
|
|
97
|
+
const path = segments.map(encodeSegment).join("/");
|
|
98
|
+
return suffix ? `${base}/root:/${path}:/${suffix.replace(/^\//, "")}` : `${base}/root:/${path}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Resolve the drive-relative segments for one entry, or `undefined` when any
|
|
102
|
+
* component fails its shape check. Returning `undefined` (rather than throwing)
|
|
103
|
+
* keeps the SEC-4 guard indistinguishable from "not found" at the caller, so a
|
|
104
|
+
* traversal probe cannot be used to enumerate the drive.
|
|
105
|
+
*/
|
|
106
|
+
segmentsFor(tenantId, project, path) {
|
|
107
|
+
if (!isSafeMemorySegment(tenantId) || !isSafeMemorySegment(project) || !isSafeMemoryPath(path)) {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
const parts = path.split("/");
|
|
111
|
+
const last = `${parts[parts.length - 1]}${ENTRY_EXTENSION}`;
|
|
112
|
+
return [...this.rootSegments, tenantId, project, ...parts.slice(0, -1), last];
|
|
113
|
+
}
|
|
114
|
+
/** Folder segments for a tenant's project partition. */
|
|
115
|
+
projectSegments(tenantId, project) {
|
|
116
|
+
if (!isSafeMemorySegment(tenantId) || !isSafeMemorySegment(project)) {
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
return [...this.rootSegments, tenantId, project];
|
|
120
|
+
}
|
|
121
|
+
async read(tenantId, project, path) {
|
|
122
|
+
const segments = this.segmentsFor(tenantId, project, path);
|
|
123
|
+
if (!segments) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
const metaResponse = await this.fetchImpl(this.itemUrl(segments), {
|
|
127
|
+
method: "GET",
|
|
128
|
+
headers: await this.headers(),
|
|
129
|
+
});
|
|
130
|
+
if (metaResponse.status === 404) {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
if (!metaResponse.ok) {
|
|
134
|
+
throw new Error(`Graph item read failed with status ${metaResponse.status}.`);
|
|
135
|
+
}
|
|
136
|
+
const item = (await metaResponse.json());
|
|
137
|
+
const contentResponse = await this.fetchImpl(this.itemUrl(segments, "content"), {
|
|
138
|
+
method: "GET",
|
|
139
|
+
headers: await this.headers(),
|
|
140
|
+
});
|
|
141
|
+
if (contentResponse.status === 404) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
if (!contentResponse.ok) {
|
|
145
|
+
throw new Error(`Graph content read failed with status ${contentResponse.status}.`);
|
|
146
|
+
}
|
|
147
|
+
const stored = await contentResponse.text();
|
|
148
|
+
return {
|
|
149
|
+
tenantId,
|
|
150
|
+
project,
|
|
151
|
+
path,
|
|
152
|
+
content: this.cipher.decrypt(stored),
|
|
153
|
+
etag: item.eTag ?? "",
|
|
154
|
+
updatedAt: toEpoch(item.lastModifiedDateTime),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
async write(tenantId, project, path, content, expectedEtag) {
|
|
158
|
+
const segments = this.segmentsFor(tenantId, project, path);
|
|
159
|
+
if (!segments) {
|
|
160
|
+
// Treat an unsafe key as a lost race rather than a write to a wrong location.
|
|
161
|
+
return { ok: false, conflict: true, current: undefined };
|
|
162
|
+
}
|
|
163
|
+
// `If-Match` gives the CAS; omitting it is the unconditional first-write /
|
|
164
|
+
// overwrite the seam specifies. Graph creates missing parent folders for a
|
|
165
|
+
// `root:/path:/content` upload, so no explicit mkdir is needed.
|
|
166
|
+
const headers = await this.headers({
|
|
167
|
+
"Content-Type": "text/markdown",
|
|
168
|
+
...(expectedEtag ? { "If-Match": expectedEtag } : {}),
|
|
169
|
+
});
|
|
170
|
+
const response = await this.fetchImpl(this.itemUrl(segments, "content"), {
|
|
171
|
+
method: "PUT",
|
|
172
|
+
headers,
|
|
173
|
+
body: this.cipher.encrypt(content),
|
|
174
|
+
});
|
|
175
|
+
if (response.status === 412 || response.status === 409) {
|
|
176
|
+
// Lost the compare-and-swap: hand back the entry the caller lost to so it
|
|
177
|
+
// can re-read and retry (never a silent clobber).
|
|
178
|
+
const current = await this.read(tenantId, project, path).catch(() => undefined);
|
|
179
|
+
return { ok: false, conflict: true, current };
|
|
180
|
+
}
|
|
181
|
+
if (!response.ok) {
|
|
182
|
+
throw new Error(`Graph write failed with status ${response.status}.`);
|
|
183
|
+
}
|
|
184
|
+
const item = (await response.json());
|
|
185
|
+
const etag = item.eTag ?? "";
|
|
186
|
+
return {
|
|
187
|
+
ok: true,
|
|
188
|
+
etag,
|
|
189
|
+
entry: {
|
|
190
|
+
tenantId,
|
|
191
|
+
project,
|
|
192
|
+
path,
|
|
193
|
+
content,
|
|
194
|
+
etag,
|
|
195
|
+
updatedAt: toEpoch(item.lastModifiedDateTime) || Date.now(),
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
async list(tenantId, project) {
|
|
200
|
+
const root = this.projectSegments(tenantId, project);
|
|
201
|
+
if (!root) {
|
|
202
|
+
return [];
|
|
203
|
+
}
|
|
204
|
+
const entries = [];
|
|
205
|
+
// Depth-first walk so nested families (`history/<agent>`, `repo-memory/<name>`)
|
|
206
|
+
// are enumerated, not just the top level.
|
|
207
|
+
const stack = [{ segments: root, logical: [] }];
|
|
208
|
+
while (stack.length > 0) {
|
|
209
|
+
const current = stack.pop();
|
|
210
|
+
const children = await this.children(current.segments);
|
|
211
|
+
for (const child of children) {
|
|
212
|
+
const name = child.name ?? "";
|
|
213
|
+
if (name.length === 0) {
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (child.folder) {
|
|
217
|
+
stack.push({ segments: [...current.segments, name], logical: [...current.logical, name] });
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (!name.endsWith(ENTRY_EXTENSION)) {
|
|
221
|
+
// Ignore anything a human dropped into the library that is not ours.
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const logicalPath = [...current.logical, name.slice(0, -ENTRY_EXTENSION.length)].join("/");
|
|
225
|
+
entries.push({
|
|
226
|
+
tenantId,
|
|
227
|
+
project,
|
|
228
|
+
path: logicalPath,
|
|
229
|
+
// `list` is a metadata enumeration; content is fetched on demand by
|
|
230
|
+
// `read` (one extra round-trip per entry would be pathological here).
|
|
231
|
+
content: "",
|
|
232
|
+
etag: child.eTag ?? "",
|
|
233
|
+
updatedAt: toEpoch(child.lastModifiedDateTime),
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return entries;
|
|
238
|
+
}
|
|
239
|
+
async listProjects(tenantId) {
|
|
240
|
+
if (!isSafeMemorySegment(tenantId)) {
|
|
241
|
+
return [];
|
|
242
|
+
}
|
|
243
|
+
const children = await this.children([...this.rootSegments, tenantId]);
|
|
244
|
+
return children
|
|
245
|
+
.filter((child) => Boolean(child.folder) && typeof child.name === "string")
|
|
246
|
+
.map((child) => child.name)
|
|
247
|
+
.filter((name) => isSafeMemorySegment(name));
|
|
248
|
+
}
|
|
249
|
+
/** Enumerate a folder's children, following `@odata.nextLink` pagination. */
|
|
250
|
+
async children(segments) {
|
|
251
|
+
let url = this.itemUrl(segments, "children");
|
|
252
|
+
const items = [];
|
|
253
|
+
while (url) {
|
|
254
|
+
const response = await this.fetchImpl(url, {
|
|
255
|
+
method: "GET",
|
|
256
|
+
headers: await this.headers(),
|
|
257
|
+
});
|
|
258
|
+
if (response.status === 404) {
|
|
259
|
+
// A partition that has never been written simply has no folder yet.
|
|
260
|
+
return items;
|
|
261
|
+
}
|
|
262
|
+
if (!response.ok) {
|
|
263
|
+
throw new Error(`Graph children listing failed with status ${response.status}.`);
|
|
264
|
+
}
|
|
265
|
+
const page = (await response.json());
|
|
266
|
+
items.push(...(page.value ?? []));
|
|
267
|
+
url = page["@odata.nextLink"];
|
|
268
|
+
}
|
|
269
|
+
return items;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Managed-identity token provider for Azure OpenAI (live only).
|
|
3
|
+
*
|
|
4
|
+
* Isolated so `@azure/identity` loads ONLY in the deployed process — the AOAI
|
|
5
|
+
* backend, the embedded engine, and every test stay free of the Azure SDK and
|
|
6
|
+
* run without it. The live HTTP bootstrap (`server-http.ts`) wires this provider
|
|
7
|
+
* into the backend.
|
|
8
|
+
*
|
|
9
|
+
* SEC-10: no secret is embedded or configured here. `DefaultAzureCredential`
|
|
10
|
+
* resolves the Container App's user-assigned (or system-assigned) managed
|
|
11
|
+
* identity at runtime; the returned token is registered with the logger for
|
|
12
|
+
* redaction by the backend. If a Key-Vault-stored API key is preferred over
|
|
13
|
+
* managed identity, fetch it from Key Vault in the bootstrap and pass a provider
|
|
14
|
+
* that returns it instead — never read a key from plain environment or code.
|
|
15
|
+
*/
|
|
16
|
+
import { DefaultAzureCredential } from "@azure/identity";
|
|
17
|
+
/** The Cognitive Services scope Azure OpenAI tokens are minted for. */
|
|
18
|
+
export const COGNITIVE_SERVICES_SCOPE = "https://cognitiveservices.azure.com/.default";
|
|
19
|
+
/**
|
|
20
|
+
* Build a token provider that returns a fresh Azure OpenAI access token from the
|
|
21
|
+
* deployment's managed identity. The provider throws if no token can be acquired
|
|
22
|
+
* (fail-fast at first call rather than silently degrading).
|
|
23
|
+
*/
|
|
24
|
+
export function createManagedIdentityTokenProvider(scope = COGNITIVE_SERVICES_SCOPE) {
|
|
25
|
+
const credential = new DefaultAzureCredential();
|
|
26
|
+
return async () => {
|
|
27
|
+
const token = await credential.getToken(scope);
|
|
28
|
+
if (!token) {
|
|
29
|
+
throw new Error("Failed to acquire a managed-identity token for Azure OpenAI.");
|
|
30
|
+
}
|
|
31
|
+
return token.token;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Blob overflow channel for the squad-memory store (WI-03).
|
|
3
|
+
*
|
|
4
|
+
* Azure Table Storage caps a single string property at 32 KiB and an entity at
|
|
5
|
+
* ~1 MiB, so a large memory `content` (a long decision log, a fat repo-memory
|
|
6
|
+
* note) cannot land in the table verbatim. This DECORATOR keeps the primary
|
|
7
|
+
* {@link SquadMemoryStore} unchanged for small entries and, for over-threshold
|
|
8
|
+
* content, spills the (encrypted) payload to a tenant-scoped Blob while leaving a
|
|
9
|
+
* tiny POINTER entity in the primary store. Reads rehydrate the payload
|
|
10
|
+
* transparently, so callers see one seamless store regardless of size.
|
|
11
|
+
*
|
|
12
|
+
* The decorator is FEATURE-FLAGGED off by default (wired only when the operator
|
|
13
|
+
* sets `memoryOverflowEnabled`); when absent the primary store's behavior is
|
|
14
|
+
* byte-for-byte unchanged. Security posture, held here as well as in the primary:
|
|
15
|
+
*
|
|
16
|
+
* * At-rest parity (MEDIUM-3) — the blob payload is the SAME AES-256-GCM
|
|
17
|
+
* envelope the table store would have persisted (`cipher.encrypt(content)`),
|
|
18
|
+
* so the caller's text is opaque at rest in Blob exactly as it is in Table.
|
|
19
|
+
* The decorator is injected the SAME {@link FieldCipher} the primary uses.
|
|
20
|
+
* * No-plaintext pointer — the marker stored in the primary is only
|
|
21
|
+
* `blobref:v1:<sha256>:<blobPath>`; it never contains the caller's content, so
|
|
22
|
+
* an operator reading the table sees a reference and a digest, never the text.
|
|
23
|
+
* * Tenant isolation (SEC-4) — the blob path is
|
|
24
|
+
* `memory/<tenantId>/<encodedProject>/<encodedPath>` with every segment
|
|
25
|
+
* percent-encoded and the same safe-segment/path guard the primary applies, so
|
|
26
|
+
* a traversal payload can never escape the tenant's prefix.
|
|
27
|
+
* * Integrity — the marker carries a SHA-256 of the exact stored envelope bytes;
|
|
28
|
+
* a read verifies the digest before rehydrating, so a swapped/corrupted blob
|
|
29
|
+
* is detected rather than silently returned.
|
|
30
|
+
*
|
|
31
|
+
* CAS is unchanged: the pointer entity lives in the primary store, so its ETag IS
|
|
32
|
+
* the CAS token and a stale-etag write still loses the race at the primary — the
|
|
33
|
+
* blob is content-addressed spill, never the concurrency authority.
|
|
34
|
+
*/
|
|
35
|
+
import { createHash } from "node:crypto";
|
|
36
|
+
import { isSafeMemoryPath, isSafeMemorySegment, } from "../squad-memory-state.js";
|
|
37
|
+
import { NullFieldCipher } from "../field-cipher.js";
|
|
38
|
+
/** Marker prefix identifying a primary entity whose real content lives in Blob. */
|
|
39
|
+
const MARKER_PREFIX = "blobref:v1:";
|
|
40
|
+
/** SHA-256 hex is a fixed 64 characters — a stable split point in the marker. */
|
|
41
|
+
const SHA256_HEX_LENGTH = 64;
|
|
42
|
+
/** Build the pointer marker persisted in the primary store for an overflowed entry. */
|
|
43
|
+
function buildMarker(sha256Hex, blobPath) {
|
|
44
|
+
return `${MARKER_PREFIX}${sha256Hex}:${blobPath}`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Parse a pointer marker, or `undefined` when `content` is ordinary text. The
|
|
48
|
+
* SHA-256 is a fixed 64-char field, so the blob path (which may itself contain
|
|
49
|
+
* `:` or `/`) is the unambiguous remainder after the single separator.
|
|
50
|
+
*/
|
|
51
|
+
function parseMarker(content) {
|
|
52
|
+
if (!content.startsWith(MARKER_PREFIX)) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
const body = content.slice(MARKER_PREFIX.length);
|
|
56
|
+
const sha256Hex = body.slice(0, SHA256_HEX_LENGTH);
|
|
57
|
+
if (sha256Hex.length !== SHA256_HEX_LENGTH || body.charAt(SHA256_HEX_LENGTH) !== ":") {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
const blobPath = body.slice(SHA256_HEX_LENGTH + 1);
|
|
61
|
+
if (blobPath.length === 0) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
return { sha256Hex, blobPath };
|
|
65
|
+
}
|
|
66
|
+
/** The tenant-scoped, content-addressed blob path for an overflowed payload.
|
|
67
|
+
*
|
|
68
|
+
* Every segment is percent-encoded (SEC-4) and the payload's SHA-256 is the final
|
|
69
|
+
* segment, so each DISTINCT envelope lands at a DISTINCT path. That content
|
|
70
|
+
* addressing is load-bearing for CAS: the blob is PUT before the pointer's
|
|
71
|
+
* compare-and-swap, so a losing writer must never clobber the WINNER's payload —
|
|
72
|
+
* with a content-independent path it would, corrupting the winner's pointer. A
|
|
73
|
+
* losing write instead spills a harmless orphan blob the winner's pointer ignores.
|
|
74
|
+
*/
|
|
75
|
+
function blobPathFor(tenantId, project, path, sha256Hex) {
|
|
76
|
+
return `memory/${encodeURIComponent(tenantId)}/${encodeURIComponent(project)}/${encodeURIComponent(path)}/${sha256Hex}`;
|
|
77
|
+
}
|
|
78
|
+
export class OverflowSquadMemoryStore {
|
|
79
|
+
primary;
|
|
80
|
+
blob;
|
|
81
|
+
cipher;
|
|
82
|
+
thresholdBytes;
|
|
83
|
+
constructor(options) {
|
|
84
|
+
this.primary = options.primary;
|
|
85
|
+
this.blob = options.blob;
|
|
86
|
+
this.cipher = options.cipher ?? new NullFieldCipher();
|
|
87
|
+
this.thresholdBytes = options.thresholdBytes;
|
|
88
|
+
}
|
|
89
|
+
async list(tenantId, project) {
|
|
90
|
+
const entries = await this.primary.list(tenantId, project);
|
|
91
|
+
return Promise.all(entries.map((entry) => this.rehydrateEntry(entry)));
|
|
92
|
+
}
|
|
93
|
+
async read(tenantId, project, path) {
|
|
94
|
+
const entry = await this.primary.read(tenantId, project, path);
|
|
95
|
+
return entry ? this.rehydrateEntry(entry) : undefined;
|
|
96
|
+
}
|
|
97
|
+
async write(tenantId, project, path, content, expectedEtag) {
|
|
98
|
+
// Produce the encrypted envelope the primary store WOULD persist, and measure
|
|
99
|
+
// it: the overflow decision is on the at-rest byte length, not the plaintext.
|
|
100
|
+
const envelope = this.cipher.encrypt(content);
|
|
101
|
+
const envelopeBytes = Buffer.from(envelope, "utf8");
|
|
102
|
+
const safe = isSafeMemorySegment(tenantId) && isSafeMemorySegment(project) && isSafeMemoryPath(path);
|
|
103
|
+
// Small content (or an unsafe key the primary will reject anyway) delegates
|
|
104
|
+
// unchanged — no blob call, identical behavior to a store without overflow.
|
|
105
|
+
if (!safe || envelopeBytes.byteLength <= this.thresholdBytes) {
|
|
106
|
+
return this.primary.write(tenantId, project, path, content, expectedEtag);
|
|
107
|
+
}
|
|
108
|
+
// Over threshold: spill the encrypted envelope to Blob FIRST (so a reader can
|
|
109
|
+
// never observe a pointer to a not-yet-written blob), then write the tiny
|
|
110
|
+
// pointer entity to the primary under the same CAS token. The blob path is
|
|
111
|
+
// content-addressed (its own sha256), so a losing CAS writer cannot clobber
|
|
112
|
+
// the winner's payload — it only leaves a harmless orphan.
|
|
113
|
+
const sha256Hex = createHash("sha256").update(envelopeBytes).digest("hex");
|
|
114
|
+
const blobPath = blobPathFor(tenantId, project, path, sha256Hex);
|
|
115
|
+
await this.blob.put(blobPath, envelopeBytes);
|
|
116
|
+
const marker = buildMarker(sha256Hex, blobPath);
|
|
117
|
+
const result = await this.primary.write(tenantId, project, path, marker, expectedEtag);
|
|
118
|
+
if (!result.ok) {
|
|
119
|
+
// The CAS race was lost at the pointer entity; surface the current entry
|
|
120
|
+
// (rehydrated when it is itself an overflow pointer) so the caller can retry.
|
|
121
|
+
const current = result.current ? await this.rehydrateEntry(result.current) : undefined;
|
|
122
|
+
return { ok: false, conflict: true, current };
|
|
123
|
+
}
|
|
124
|
+
// Present the caller's real content (not the marker) with the primary's etag.
|
|
125
|
+
return { ok: true, etag: result.etag, entry: { ...result.entry, content } };
|
|
126
|
+
}
|
|
127
|
+
listProjects(tenantId) {
|
|
128
|
+
return this.primary.listProjects(tenantId);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Return `entry` unchanged when it is ordinary content, or rehydrate an overflow
|
|
132
|
+
* pointer by fetching + integrity-checking + decrypting the blob payload. The
|
|
133
|
+
* ETag is always the primary's (the CAS authority), never the blob's.
|
|
134
|
+
*/
|
|
135
|
+
async rehydrateEntry(entry) {
|
|
136
|
+
const marker = parseMarker(entry.content);
|
|
137
|
+
if (marker === undefined) {
|
|
138
|
+
return entry;
|
|
139
|
+
}
|
|
140
|
+
const bytes = await this.blob.get(marker.blobPath);
|
|
141
|
+
if (bytes === undefined) {
|
|
142
|
+
throw new Error("Overflow blob payload is missing for a pointer entry.");
|
|
143
|
+
}
|
|
144
|
+
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
145
|
+
if (digest !== marker.sha256Hex) {
|
|
146
|
+
throw new Error("Overflow blob payload failed its integrity check (sha256 mismatch).");
|
|
147
|
+
}
|
|
148
|
+
const content = this.cipher.decrypt(Buffer.from(bytes).toString("utf8"));
|
|
149
|
+
return { ...entry, content };
|
|
150
|
+
}
|
|
151
|
+
}
|