@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,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run-state seam (ARCH-1 — resumable-ready).
|
|
3
|
+
*
|
|
4
|
+
* The thin slice runs a single-stage hero tool (`squad_research`) whose state is
|
|
5
|
+
* **ephemeral per request** — no resumability is needed. But the Gate B ADR
|
|
6
|
+
* (docs/planning/adrs/0001) commits to a tenant-isolated *resumable* run-state
|
|
7
|
+
* model for the long-running tools that land in Phase 1b / Phase 2. To avoid an
|
|
8
|
+
* ephemeral-only lock-in (architect condition 1), the engine writes and reads
|
|
9
|
+
* run state through THIS interface now, so a `DurableRunStateStore` can be
|
|
10
|
+
* dropped in later (persisting to Storage/Key Vault and rehydrating after a
|
|
11
|
+
* scale-to-zero cold start) without touching the embedded engine.
|
|
12
|
+
*
|
|
13
|
+
* No durable behavior is implemented here; only the seam plus the ephemeral
|
|
14
|
+
* realization the thin slice uses.
|
|
15
|
+
*/
|
|
16
|
+
import { randomUUID } from "node:crypto";
|
|
17
|
+
/** Default worker lease (ms): a `running` run past its lease is reclaimable. */
|
|
18
|
+
export const DEFAULT_LEASE_MS = 10 * 60 * 1000;
|
|
19
|
+
/** True when a run is approved for release (operator approval recorded on the record). */
|
|
20
|
+
export function isRunApproved(run) {
|
|
21
|
+
return typeof run.approvedBy === "string" && run.approvedBy.length > 0;
|
|
22
|
+
}
|
|
23
|
+
/** True when a run has passed its TTL. */
|
|
24
|
+
export function isRunExpired(run, now) {
|
|
25
|
+
return typeof run.expiresAt === "number" && run.expiresAt <= now;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Whether a run is claimable by a worker at `now`: an approved held run, or a
|
|
29
|
+
* `running` run whose lease has expired (never-started queue entry, or a crash).
|
|
30
|
+
* Shared by every store so `listClaimable` semantics are identical everywhere.
|
|
31
|
+
*/
|
|
32
|
+
export function isRunClaimable(run, now) {
|
|
33
|
+
if (run.status === "complete" || run.status === "failed" || isRunExpired(run, now)) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
if (run.status === "held") {
|
|
37
|
+
return isRunApproved(run);
|
|
38
|
+
}
|
|
39
|
+
// running: claimable only when its lease has lapsed.
|
|
40
|
+
return (run.leaseExpiresAt ?? 0) <= now;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* In-memory, per-process run-state store. Resets on restart (acceptable for the
|
|
44
|
+
* thin slice's stateless single-stage tools). A future durable store implements
|
|
45
|
+
* the same interface for the long-run/resumable path (ARCH-1 / ARCH-2).
|
|
46
|
+
*/
|
|
47
|
+
export class EphemeralRunStateStore {
|
|
48
|
+
kind = "ephemeral";
|
|
49
|
+
runs = new Map();
|
|
50
|
+
/** Sync, TTL-aware read used internally so `claim` stays atomic (no await gap). */
|
|
51
|
+
peek(runId) {
|
|
52
|
+
const run = this.runs.get(runId);
|
|
53
|
+
if (!run) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
if (isRunExpired(run, Date.now())) {
|
|
57
|
+
this.runs.delete(runId);
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
return run;
|
|
61
|
+
}
|
|
62
|
+
create(init) {
|
|
63
|
+
const now = Date.now();
|
|
64
|
+
const run = {
|
|
65
|
+
runId: randomUUID(),
|
|
66
|
+
tenantId: init.tenantId,
|
|
67
|
+
toolId: init.toolId,
|
|
68
|
+
status: "running",
|
|
69
|
+
createdAt: now,
|
|
70
|
+
updatedAt: now,
|
|
71
|
+
expiresAt: init.ttlMs !== undefined ? now + init.ttlMs : undefined,
|
|
72
|
+
};
|
|
73
|
+
this.runs.set(run.runId, run);
|
|
74
|
+
return Promise.resolve(run);
|
|
75
|
+
}
|
|
76
|
+
get(runId) {
|
|
77
|
+
return Promise.resolve(this.peek(runId));
|
|
78
|
+
}
|
|
79
|
+
update(runId, patch) {
|
|
80
|
+
const existing = this.peek(runId);
|
|
81
|
+
if (!existing) {
|
|
82
|
+
return Promise.resolve(undefined);
|
|
83
|
+
}
|
|
84
|
+
const next = { ...existing, ...patch, updatedAt: Date.now() };
|
|
85
|
+
this.runs.set(runId, next);
|
|
86
|
+
return Promise.resolve(next);
|
|
87
|
+
}
|
|
88
|
+
delete(runId) {
|
|
89
|
+
this.runs.delete(runId);
|
|
90
|
+
return Promise.resolve();
|
|
91
|
+
}
|
|
92
|
+
claim(runId, from, to, options = {}) {
|
|
93
|
+
const now = options.now ?? Date.now();
|
|
94
|
+
// Read+check+write with NO await between them: atomic within one process, so
|
|
95
|
+
// two concurrent claims cannot both win (in-process CAS; cross-replica CAS is
|
|
96
|
+
// the Azure Table store's ETag If-Match).
|
|
97
|
+
const existing = this.peek(runId);
|
|
98
|
+
if (!existing || !from.includes(existing.status)) {
|
|
99
|
+
return Promise.resolve(undefined);
|
|
100
|
+
}
|
|
101
|
+
if (existing.status === "running" && (existing.leaseExpiresAt ?? 0) > now) {
|
|
102
|
+
return Promise.resolve(undefined);
|
|
103
|
+
}
|
|
104
|
+
const next = {
|
|
105
|
+
...existing,
|
|
106
|
+
status: to,
|
|
107
|
+
leaseExpiresAt: now + (options.leaseMs ?? DEFAULT_LEASE_MS),
|
|
108
|
+
updatedAt: now,
|
|
109
|
+
};
|
|
110
|
+
this.runs.set(runId, next);
|
|
111
|
+
return Promise.resolve(next);
|
|
112
|
+
}
|
|
113
|
+
listClaimable(now = Date.now()) {
|
|
114
|
+
const claimable = [];
|
|
115
|
+
for (const run of this.runs.values()) {
|
|
116
|
+
if (!isRunExpired(run, now) && isRunClaimable(run, now)) {
|
|
117
|
+
claimable.push(run);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return Promise.resolve(claimable);
|
|
121
|
+
}
|
|
122
|
+
sweepExpired(now = Date.now()) {
|
|
123
|
+
let removed = 0;
|
|
124
|
+
for (const [runId, run] of this.runs) {
|
|
125
|
+
if (isRunExpired(run, now)) {
|
|
126
|
+
this.runs.delete(runId);
|
|
127
|
+
removed += 1;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return Promise.resolve(removed);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const DEFAULT_BATCH_SIZE = 10;
|
|
2
|
+
export class RunWorker {
|
|
3
|
+
coordinator;
|
|
4
|
+
logger;
|
|
5
|
+
batchSize;
|
|
6
|
+
constructor(deps) {
|
|
7
|
+
this.coordinator = deps.coordinator;
|
|
8
|
+
this.logger = deps.logger;
|
|
9
|
+
this.batchSize = deps.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Run ONE drain pass: sweep expired runs, then claim-and-drive up to
|
|
13
|
+
* `batchSize` claimable runs. Each drive CAS-claims first, so a run already
|
|
14
|
+
* being driven by another worker/poll is skipped (no double-execution). Returns
|
|
15
|
+
* per-tick counters; never throws for a single run's failure (it is logged and
|
|
16
|
+
* the run is marked failed by the coordinator).
|
|
17
|
+
*/
|
|
18
|
+
async tickOnce(now) {
|
|
19
|
+
const swept = await this.coordinator.sweepExpiredRuns(now);
|
|
20
|
+
const claimable = await this.coordinator.listClaimableRuns(now);
|
|
21
|
+
let driven = 0;
|
|
22
|
+
let skipped = 0;
|
|
23
|
+
for (const run of claimable.slice(0, this.batchSize)) {
|
|
24
|
+
try {
|
|
25
|
+
const result = await this.coordinator.driveClaimable(run.runId);
|
|
26
|
+
if (result === undefined) {
|
|
27
|
+
// Lost the CAS — another worker/poll is driving it.
|
|
28
|
+
skipped += 1;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
driven += 1;
|
|
32
|
+
this.logger?.info("worker drove a run", { runId: run.runId, outcome: result.outcome });
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
// A single run's failure must not stop the drain; the coordinator marks
|
|
36
|
+
// the run failed. Never log the error body (it could echo caller text).
|
|
37
|
+
skipped += 1;
|
|
38
|
+
this.logger?.error("worker run failed", { runId: run.runId, error: String(error) });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { driven, skipped, swept };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Poll the store on an interval until `signal` aborts. Between ticks it waits
|
|
45
|
+
* `intervalMs`. Intended for an ACA Job with `minReplicas: 1` (or an event-/
|
|
46
|
+
* schedule-triggered Job that runs `tickOnce` and exits).
|
|
47
|
+
*/
|
|
48
|
+
async runForever(intervalMs, signal) {
|
|
49
|
+
while (!signal?.aborted) {
|
|
50
|
+
await this.tickOnce();
|
|
51
|
+
await new Promise((resolve) => {
|
|
52
|
+
const timer = setTimeout(resolve, intervalMs);
|
|
53
|
+
signal?.addEventListener("abort", () => {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
resolve();
|
|
56
|
+
}, { once: true });
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a run's own history back.
|
|
3
|
+
*
|
|
4
|
+
* Auto-memory reads the tail of a rolling `state` digest — 8 000 characters of
|
|
5
|
+
* one-line summaries. That is continuity for the next dispatch and nothing an
|
|
6
|
+
* operator can audit: a Copilot Studio user who pushed a backlog out through a
|
|
7
|
+
* connector cannot open the plan, the council verdict, or the per-role history
|
|
8
|
+
* that produced it, because a flat digest has no structure to open.
|
|
9
|
+
*
|
|
10
|
+
* This module turns the persisted tree into two operations a host can actually
|
|
11
|
+
* use — browse and open — plus a run INDEX that is cheap enough to inject at the
|
|
12
|
+
* start of a run without spending the context window on artifact bodies.
|
|
13
|
+
*
|
|
14
|
+
* Everything here is READ-ONLY and tenant-scoped by construction: `tenantId`
|
|
15
|
+
* comes from the validated Entra token at the call site and is the store's first
|
|
16
|
+
* argument, exactly as it is on every write path.
|
|
17
|
+
*/
|
|
18
|
+
import { SQUAD_STATE_ROOT, TRACKING_ROOT, } from "./artifact-store.js";
|
|
19
|
+
import { DECISIONS_PATH, STATE_PATH } from "./squad-ledger.js";
|
|
20
|
+
/** Maximum artifacts returned by one listing, newest-path-last. */
|
|
21
|
+
export const HISTORY_LIST_LIMIT = 500;
|
|
22
|
+
/** Maximum characters returned for a single artifact read. */
|
|
23
|
+
export const HISTORY_READ_MAX_CHARS = 64_000;
|
|
24
|
+
/** Maximum characters of index injected into a prompt at run start. */
|
|
25
|
+
export const HISTORY_INDEX_MAX_CHARS = 4_000;
|
|
26
|
+
/** Read-only browsing over a persisted squad tree. */
|
|
27
|
+
export class SquadHistory {
|
|
28
|
+
store;
|
|
29
|
+
constructor(store) {
|
|
30
|
+
this.store = store;
|
|
31
|
+
}
|
|
32
|
+
/** List artifacts under a prefix (whole project when omitted). */
|
|
33
|
+
async list(tenantId, project, prefix) {
|
|
34
|
+
const entries = await this.store.list(tenantId, project, prefix);
|
|
35
|
+
return entries.slice(0, HISTORY_LIST_LIMIT);
|
|
36
|
+
}
|
|
37
|
+
/** Read one artifact, bounded so a single read cannot blow the context window. */
|
|
38
|
+
async read(tenantId, project, path) {
|
|
39
|
+
const artifact = await this.store.get(tenantId, project, path);
|
|
40
|
+
if (!artifact) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
const content = artifact.content.length <= HISTORY_READ_MAX_CHARS
|
|
44
|
+
? artifact.content
|
|
45
|
+
: `${artifact.content.slice(0, HISTORY_READ_MAX_CHARS)}\n…(truncated)…`;
|
|
46
|
+
return { path: artifact.path, content, updatedAt: artifact.updatedAt };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Build the compact index of what a project already holds.
|
|
50
|
+
*
|
|
51
|
+
* Deliberately metadata-only. The point of an index is to let the model decide
|
|
52
|
+
* WHICH artifact to open; inlining bodies would reintroduce the unbounded read
|
|
53
|
+
* that the 8 000-character digest cap existed to prevent.
|
|
54
|
+
*/
|
|
55
|
+
async index(tenantId, project) {
|
|
56
|
+
const entries = await this.store.list(tenantId, project);
|
|
57
|
+
const state = await this.readState(tenantId, project);
|
|
58
|
+
const byDirectory = new Map();
|
|
59
|
+
const agents = [];
|
|
60
|
+
for (const entry of entries) {
|
|
61
|
+
const historyMatch = entry.path.match(new RegExp(`^${escapeRegExp(SQUAD_STATE_ROOT)}/history/(.+)\\.md$`));
|
|
62
|
+
if (historyMatch) {
|
|
63
|
+
agents.push(historyMatch[1]);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (entry.path.startsWith(`${SQUAD_STATE_ROOT}/`)) {
|
|
67
|
+
continue; // Squad state is reported through `profile`/`turn`, not as a deliverable.
|
|
68
|
+
}
|
|
69
|
+
const directory = entry.path.split("/").slice(0, -1).join("/");
|
|
70
|
+
const bucket = byDirectory.get(directory) ?? [];
|
|
71
|
+
bucket.push(entry);
|
|
72
|
+
byDirectory.set(directory, bucket);
|
|
73
|
+
}
|
|
74
|
+
const deliverables = [...byDirectory.entries()]
|
|
75
|
+
.map(([directory, items]) => ({
|
|
76
|
+
directory,
|
|
77
|
+
count: items.length,
|
|
78
|
+
latest: items.reduce((a, b) => (a.updatedAt >= b.updatedAt ? a : b)).path,
|
|
79
|
+
}))
|
|
80
|
+
.sort((a, b) => a.directory.localeCompare(b.directory));
|
|
81
|
+
return {
|
|
82
|
+
profile: state?.profile,
|
|
83
|
+
turn: state?.turn,
|
|
84
|
+
deliverables,
|
|
85
|
+
agents: agents.sort(),
|
|
86
|
+
total: entries.length,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Render the index as the delimited DATA block injected at the start of a run.
|
|
91
|
+
*
|
|
92
|
+
* Returned as reference material, never as authority: it is model-produced text
|
|
93
|
+
* that has round-tripped through storage, so it is exactly as untrusted as
|
|
94
|
+
* caller `context` and is merged there rather than into the system prompt.
|
|
95
|
+
*/
|
|
96
|
+
async contextBlock(tenantId, project) {
|
|
97
|
+
const index = await this.index(tenantId, project);
|
|
98
|
+
if (index.total === 0) {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
const lines = [
|
|
102
|
+
`Squad profile: ${index.profile ?? "(not yet seeded)"}; turn ${index.turn ?? 0}; ${index.total} stored artifacts.`,
|
|
103
|
+
"",
|
|
104
|
+
"Prior deliverables (open with squad_history read):",
|
|
105
|
+
...index.deliverables.map((d) => `- ${d.directory}/ — ${d.count} file(s), most recent ${d.latest}`),
|
|
106
|
+
];
|
|
107
|
+
if (index.agents.length > 0) {
|
|
108
|
+
lines.push("", `Agents with recorded history: ${index.agents.join(", ")}.`);
|
|
109
|
+
}
|
|
110
|
+
const rendered = lines.join("\n");
|
|
111
|
+
return rendered.length <= HISTORY_INDEX_MAX_CHARS
|
|
112
|
+
? rendered
|
|
113
|
+
: `${rendered.slice(0, HISTORY_INDEX_MAX_CHARS)}\n…(truncated)…`;
|
|
114
|
+
}
|
|
115
|
+
/** The decision log, or `undefined` before the squad is seeded. */
|
|
116
|
+
async decisions(tenantId, project) {
|
|
117
|
+
return (await this.store.get(tenantId, project, DECISIONS_PATH))?.content;
|
|
118
|
+
}
|
|
119
|
+
async readState(tenantId, project) {
|
|
120
|
+
const entry = await this.store.get(tenantId, project, STATE_PATH);
|
|
121
|
+
if (!entry) {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
return JSON.parse(entry.content);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function escapeRegExp(value) {
|
|
133
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
134
|
+
}
|
|
135
|
+
/** The tracking prefixes a caller may browse, for input validation at the tool layer. */
|
|
136
|
+
export const BROWSABLE_PREFIXES = [TRACKING_ROOT, "docs", "outputs"];
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Squad Scribe, server-side.
|
|
3
|
+
*
|
|
4
|
+
* Under GitHub Copilot the Scribe is the single writer of squad state: it stamps
|
|
5
|
+
* the seeded roster into `team.md`, filters `routing.md` to that roster, keeps
|
|
6
|
+
* `state.json` current, and appends to the three append-only logs. The MCP server
|
|
7
|
+
* ran the same dispatches and wrote none of it, so a run left behind a rolling
|
|
8
|
+
* digest and nothing an operator could audit.
|
|
9
|
+
*
|
|
10
|
+
* This module writes that ledger through the {@link SquadArtifactStore} seam, so
|
|
11
|
+
* it lands in whichever backend the operator configured. It follows
|
|
12
|
+
* `squad-state.instructions.md` on the two points that actually matter:
|
|
13
|
+
*
|
|
14
|
+
* * `team.md`, `routing.md`, `state.json`, and the consumption files are
|
|
15
|
+
* REPLACED by the Scribe.
|
|
16
|
+
* * `decisions.md`, `notifications.md`, and `history/<agent>.md` are
|
|
17
|
+
* APPEND-ONLY — "new entries are added to the end; prior entries are never
|
|
18
|
+
* edited or removed" — so every write goes through the store's CAS append
|
|
19
|
+
* rather than a read-modify-write that could drop a concurrent role's entry.
|
|
20
|
+
*
|
|
21
|
+
* Seeding is idempotent and an existing `team.md` WINS over the `profile`
|
|
22
|
+
* argument. A project's roster is a decision the project already made; a later
|
|
23
|
+
* caller passing a different `profile` must not silently re-cast the squad.
|
|
24
|
+
*/
|
|
25
|
+
import { SQUAD_STATE_ROOT, } from "./artifact-store.js";
|
|
26
|
+
import { deliverableRootFor } from "./profiles.js";
|
|
27
|
+
/** The `state.json` schema this server writes (matches squad-state.instructions.md). */
|
|
28
|
+
export const STATE_SCHEMA_VERSION = "1.3";
|
|
29
|
+
export const TEAM_PATH = `${SQUAD_STATE_ROOT}/team.md`;
|
|
30
|
+
export const ROUTING_PATH = `${SQUAD_STATE_ROOT}/routing.md`;
|
|
31
|
+
export const STATE_PATH = `${SQUAD_STATE_ROOT}/state.json`;
|
|
32
|
+
export const DECISIONS_PATH = `${SQUAD_STATE_ROOT}/decisions.md`;
|
|
33
|
+
export const NOTIFICATIONS_PATH = `${SQUAD_STATE_ROOT}/notifications.md`;
|
|
34
|
+
export const CONSUMPTION_PATH = `${SQUAD_STATE_ROOT}/consumption.md`;
|
|
35
|
+
/** Per-agent dispatch history; one append-only file per agent. */
|
|
36
|
+
export function agentHistoryPath(agentName) {
|
|
37
|
+
return `${SQUAD_STATE_ROOT}/history/${slugForPath(agentName)}.md`;
|
|
38
|
+
}
|
|
39
|
+
/** Per-run pipeline summary. */
|
|
40
|
+
export function runHistoryPath(runId) {
|
|
41
|
+
return `${SQUAD_STATE_ROOT}/history/autopilot-run-${slugForPath(runId)}.md`;
|
|
42
|
+
}
|
|
43
|
+
/** Reduce a display name to a safe single path segment. */
|
|
44
|
+
export function slugForPath(value) {
|
|
45
|
+
const slug = value
|
|
46
|
+
.toLowerCase()
|
|
47
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
48
|
+
.replace(/^-|-$/g, "");
|
|
49
|
+
return slug.length > 0 ? slug : "unnamed";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Render `team.md` from the seeded roster.
|
|
53
|
+
*
|
|
54
|
+
* `Member Name` is left empty on every row. Naming is a question the coordinator
|
|
55
|
+
* puts to a user during Init Mode, and this server has no user in the loop — the
|
|
56
|
+
* roster's own unattended rule is to fall back to the empty-name behaviour rather
|
|
57
|
+
* than invent aliases ("Unattended runs never ask ... It never invents names").
|
|
58
|
+
*/
|
|
59
|
+
export function renderTeamMarkdown(profile, tables, opts = {}) {
|
|
60
|
+
const tier = opts.tier?.trim() || "default";
|
|
61
|
+
const header = [
|
|
62
|
+
"| Role | Member Name | Agent Name (Primary) | Alternate Agents | Invocation | Model Tier | Deliverable Root |",
|
|
63
|
+
"|------|-------------|----------------------|------------------|------------|------------|------------------|",
|
|
64
|
+
];
|
|
65
|
+
const rows = profile.roles.map((role) => {
|
|
66
|
+
const cast = tables.cast.get(role);
|
|
67
|
+
const root = role === "scribe"
|
|
68
|
+
? "(squad state)"
|
|
69
|
+
: (deliverableRootFor(role, tables, { squad: opts.squad, date: opts.date }) ??
|
|
70
|
+
"(returns findings to the coordinator)");
|
|
71
|
+
return `| ${role} | | ${cast?.primary ?? "(unresolved)"} | ${cast?.alternates.join(", ") ?? ""} | runSubagent / task | ${tier} | ${root} |`;
|
|
72
|
+
});
|
|
73
|
+
return [
|
|
74
|
+
"# Members",
|
|
75
|
+
"",
|
|
76
|
+
`Seeded from the \`${profile.name}\` profile.`,
|
|
77
|
+
"",
|
|
78
|
+
...header,
|
|
79
|
+
...rows,
|
|
80
|
+
"",
|
|
81
|
+
].join("\n");
|
|
82
|
+
}
|
|
83
|
+
/** Render `routing.md` filtered to the seeded roster. */
|
|
84
|
+
export function renderRoutingMarkdown(profile) {
|
|
85
|
+
return [
|
|
86
|
+
"# Routing",
|
|
87
|
+
"",
|
|
88
|
+
`Filtered to the \`${profile.name}\` profile's roster. A request that routes to a`,
|
|
89
|
+
"role this squad does not carry escalates to the user rather than being",
|
|
90
|
+
"reassigned to a role that cannot do the work.",
|
|
91
|
+
"",
|
|
92
|
+
"| Role | Seeded |",
|
|
93
|
+
"|------|--------|",
|
|
94
|
+
...profile.roles.map((role) => `| ${role} | yes |`),
|
|
95
|
+
"",
|
|
96
|
+
].join("\n");
|
|
97
|
+
}
|
|
98
|
+
/** Build the initial `state.json` for a freshly seeded squad. */
|
|
99
|
+
export function initialState(profile, opts = {}) {
|
|
100
|
+
return {
|
|
101
|
+
schemaVersion: STATE_SCHEMA_VERSION,
|
|
102
|
+
profile: profile.name,
|
|
103
|
+
updated: opts.date ?? new Date().toISOString().slice(0, 10),
|
|
104
|
+
turn: 0,
|
|
105
|
+
mode: opts.mode?.trim() || "interactive",
|
|
106
|
+
activeRoles: [],
|
|
107
|
+
openEscalations: [],
|
|
108
|
+
currentRun: { sessionModel: "", modelOverrides: {}, estCostUsd: 0, estCreditsTotal: 0 },
|
|
109
|
+
notify: {
|
|
110
|
+
approvalChannel: "in-chat",
|
|
111
|
+
enabled: false,
|
|
112
|
+
email: "",
|
|
113
|
+
github: { handle: "", repo: "" },
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** The Scribe, bound to one artifact store. */
|
|
118
|
+
export class SquadLedger {
|
|
119
|
+
store;
|
|
120
|
+
constructor(store) {
|
|
121
|
+
this.store = store;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Seed `team.md`, `routing.md`, and `state.json` for a project, once.
|
|
125
|
+
*
|
|
126
|
+
* An existing `team.md` short-circuits the whole call: re-casting a squad
|
|
127
|
+
* because a later request passed a different `profile` would silently discard
|
|
128
|
+
* the roster the project is already running under.
|
|
129
|
+
*/
|
|
130
|
+
async seed(tenantId, project, profile, tables, opts = {}) {
|
|
131
|
+
const existing = await this.store.get(tenantId, project, TEAM_PATH);
|
|
132
|
+
if (existing) {
|
|
133
|
+
return { created: false, profile: profileNameFrom(existing.content, profile.name), team: existing };
|
|
134
|
+
}
|
|
135
|
+
const team = await this.replace(tenantId, project, TEAM_PATH, renderTeamMarkdown(profile, tables, opts));
|
|
136
|
+
await this.replace(tenantId, project, ROUTING_PATH, renderRoutingMarkdown(profile));
|
|
137
|
+
await this.replace(tenantId, project, STATE_PATH, `${JSON.stringify(initialState(profile, opts), null, 2)}\n`);
|
|
138
|
+
// Pre-create the shared append-only logs. The store seam has no
|
|
139
|
+
// create-if-absent, so the FIRST write to a path cannot be arbitrated by
|
|
140
|
+
// compare-and-swap; creating them here means every later append across every
|
|
141
|
+
// replica holds a real CAS token.
|
|
142
|
+
await this.replace(tenantId, project, DECISIONS_PATH, "# Decisions\n");
|
|
143
|
+
await this.replace(tenantId, project, NOTIFICATIONS_PATH, "# Notifications\n");
|
|
144
|
+
return { created: true, profile: profile.name, team };
|
|
145
|
+
}
|
|
146
|
+
/** Read the current `state.json`, or `undefined` before the squad is seeded. */
|
|
147
|
+
async readState(tenantId, project) {
|
|
148
|
+
const entry = await this.store.get(tenantId, project, STATE_PATH);
|
|
149
|
+
if (!entry) {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
return JSON.parse(entry.content);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** Overwrite `state.json` with the supplied patch applied. */
|
|
160
|
+
async updateState(tenantId, project, patch) {
|
|
161
|
+
const current = await this.readState(tenantId, project);
|
|
162
|
+
if (!current) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const next = {
|
|
166
|
+
...current,
|
|
167
|
+
...patch,
|
|
168
|
+
currentRun: { ...current.currentRun, ...(patch.currentRun ?? {}) },
|
|
169
|
+
updated: patch.updated ?? new Date().toISOString().slice(0, 10),
|
|
170
|
+
};
|
|
171
|
+
await this.replace(tenantId, project, STATE_PATH, `${JSON.stringify(next, null, 2)}\n`);
|
|
172
|
+
}
|
|
173
|
+
/** Append a block to the chronological decision log. */
|
|
174
|
+
async appendDecision(tenantId, project, block) {
|
|
175
|
+
await this.store.append(tenantId, project, DECISIONS_PATH, block.trim());
|
|
176
|
+
}
|
|
177
|
+
/** Append a block to the notification log. */
|
|
178
|
+
async appendNotification(tenantId, project, block) {
|
|
179
|
+
await this.store.append(tenantId, project, NOTIFICATIONS_PATH, block.trim());
|
|
180
|
+
}
|
|
181
|
+
/** Append a dispatch record to an agent's own history file. */
|
|
182
|
+
async appendAgentHistory(tenantId, project, agentName, block) {
|
|
183
|
+
await this.store.append(tenantId, project, agentHistoryPath(agentName), block.trim());
|
|
184
|
+
}
|
|
185
|
+
/** Append a stage record to the per-run pipeline summary. */
|
|
186
|
+
async appendRunHistory(tenantId, project, runId, block) {
|
|
187
|
+
await this.store.append(tenantId, project, runHistoryPath(runId), block.trim());
|
|
188
|
+
}
|
|
189
|
+
/** Write a role's deliverable into that role's own root, returning the path. */
|
|
190
|
+
async writeDeliverable(tenantId, project, role, fileName, content, tables, opts = {}) {
|
|
191
|
+
const root = deliverableRootFor(role, tables, { squad: opts.squad, date: opts.date });
|
|
192
|
+
if (!root) {
|
|
193
|
+
return undefined; // The roster gives this role no standalone artifact.
|
|
194
|
+
}
|
|
195
|
+
const path = `${root}/${slugForPath(fileName)}.md`;
|
|
196
|
+
await this.replace(tenantId, project, path, content);
|
|
197
|
+
return path;
|
|
198
|
+
}
|
|
199
|
+
/** Replace an artifact, retrying once against the current revision. */
|
|
200
|
+
async replace(tenantId, project, path, content) {
|
|
201
|
+
const first = await this.store.put(tenantId, project, path, content);
|
|
202
|
+
if (first.ok) {
|
|
203
|
+
return first.artifact;
|
|
204
|
+
}
|
|
205
|
+
const retry = await this.store.put(tenantId, project, path, content, first.current?.etag);
|
|
206
|
+
if (!retry.ok) {
|
|
207
|
+
throw new Error(`Could not replace ${path}: lost the compare-and-swap twice.`);
|
|
208
|
+
}
|
|
209
|
+
return retry.artifact;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/** Recover the profile a seeded `team.md` was cast under. */
|
|
213
|
+
function profileNameFrom(teamMarkdown, fallback) {
|
|
214
|
+
return teamMarkdown.match(/Seeded from the `([a-z0-9-]+)` profile/)?.[1] ?? fallback;
|
|
215
|
+
}
|