Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/scoped-maps-connect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sapiom/harness": minor
---

Expose the shared Agent Map proposal through one capability-authenticated embedded HTTP MCP endpoint. Project planner, assigned-builder, and manual-builder sessions receive identical read, validate, and propose tools through private per-session Claude or Codex launch configuration, with rotation on resume and revocation on exit.
5 changes: 5 additions & 0 deletions .changeset/shared-proposals-persist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sapiom/harness": minor
---

Prepare crash-atomic, project-wide Agent Map proposal persistence for the SAP-3060 transport, with attributed operation history, bounded session-scoped idempotency receipts, and history-derived stale-write rebasing. Exact results are retained for a bounded retry window, while older same-session request IDs cannot apply twice. Agent Map workspace reads now return a coherent versioned workspace-and-proposal snapshot, and the named browser-safe contracts required by the accepted-delta bus payload are exported from the package entry point.
22 changes: 22 additions & 0 deletions packages/harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,28 @@ conversation history, but the losing local row can no longer resume or adopt
that fenced identity. Start a fresh session in the losing row's directory to
continue there.

### Agent Map MCP

Studio exposes a stateful Streamable HTTP MCP endpoint at `/mcp/agent-map` for
the coding-agent processes it launches. `POST` initializes and calls the
protocol; `GET` and `DELETE` support the protocol's live stream and session
shutdown. This route is separate from the browser-token-protected `/api`
surface. It requires a Studio-issued bearer capability scoped to one trusted
project/session identity; callers cannot supply or change that identity.

Studio injects the capability privately at process launch. Successful use
renews its inactivity lease, while session exit, resume rotation, signed-in
principal changes, and server shutdown revoke it. Consumers should not copy,
persist, log, or reuse the capability outside the launched session.

Every trusted Agent Map role receives the same three project-wide tools:

- `agent_map_read` reads the current confirmed workspace and shared proposal.
- `agent_map_validate` validates one complete operation batch without mutating
shared state or allocating permanent IDs.
- `agent_map_propose` atomically and idempotently applies one validated batch
to the shared Proposed map.

HTTP contracts that need more than a type to use are written up under `docs/`:

- [`docs/agent-canvas-graph.md`](docs/agent-canvas-graph.md) — the session-free
Expand Down
3 changes: 3 additions & 0 deletions packages/harness/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,14 @@
"@sapiom/agent-core": "workspace:^",
"@sapiom/analytics-core": "workspace:^",
"@sapiom/mcp": "workspace:^",
"@modelcontextprotocol/sdk": "^1.26.0",
"ajv": "^8.12.0",
"express": "^4.21.0",
"express-rate-limit": "^7.4.0",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"typescript": "~5.9.3",
"uuid": "^10.0.0",
"ws": "^8.18.0",
"zod": "^3.25.0"
},
Expand All @@ -84,6 +86,7 @@
"@types/node": "^20.11.30",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/uuid": "^10.0.0",
"@types/ws": "^8.5.10",
"@vitejs/plugin-react": "^4.3.4",
"@xterm/addon-fit": "^0.10.0",
Expand Down
23 changes: 23 additions & 0 deletions packages/harness/src/core/adapters/codex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,29 @@ describe("CodexAdapter", () => {
'sandbox_mode="workspace-write"',
]);
});

it("injects Agent Map MCP config per process while keeping the secret out of argv", () => {
const adapter = new CodexAdapter({ binary: "fake-codex" });
const agentMapMcp = {
url: "http://127.0.0.1:4312/mcp/agent-map",
bearerToken: "private-map-token",
};
for (const spec of [
adapter.launch({ harnessSessionId: "h1", cwd: "/tmp/proj", agentMapMcp }),
adapter.resume("rollout", { harnessSessionId: "h1", cwd: "/tmp/proj", agentMapMcp }),
]) {
expect(spec.args).toContain(
`mcp_servers.agent-map.url=${JSON.stringify(agentMapMcp.url)}`,
);
expect(spec.args).toContain(
'mcp_servers.agent-map.bearer_token_env_var="SAPIOM_AGENT_MAP_CAPABILITY"',
);
expect(spec.args.join(" ")).not.toContain(agentMapMcp.bearerToken);
expect(spec.env).toEqual({
SAPIOM_AGENT_MAP_CAPABILITY: agentMapMcp.bearerToken,
});
}
});
});

describe("detectBlockingPrompt", () => {
Expand Down
16 changes: 14 additions & 2 deletions packages/harness/src/core/adapters/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,9 @@ export class CodexAdapter implements HarnessAdapter {
args: buildConfigArgs(opts),
// Codex has no analog to Claude's CLAUDECODE nested-agent guard; no env
// overrides are needed for a fresh launch.
env: {},
env: opts.agentMapMcp
? { SAPIOM_AGENT_MAP_CAPABILITY: opts.agentMapMcp.bearerToken }
: {},
cwd: opts.cwd,
};
}
Expand All @@ -314,7 +316,9 @@ export class CodexAdapter implements HarnessAdapter {
return {
command: this.binary,
args: ["resume", agentSessionId, ...buildConfigArgs(opts)],
env: {},
env: opts.agentMapMcp
? { SAPIOM_AGENT_MAP_CAPABILITY: opts.agentMapMcp.bearerToken }
: {},
cwd: opts.cwd,
};
}
Expand Down Expand Up @@ -462,6 +466,14 @@ function buildConfigArgs(opts: LaunchOpts): string[] {
"-c",
'sandbox_mode="workspace-write"',
];
if (opts.agentMapMcp) {
args.push(
"-c",
`mcp_servers.agent-map.url=${JSON.stringify(opts.agentMapMcp.url)}`,
"-c",
'mcp_servers.agent-map.bearer_token_env_var="SAPIOM_AGENT_MAP_CAPABILITY"',
);
}
if (opts.systemPromptFile) {
try {
const prompt = readFileSync(opts.systemPromptFile, "utf8");
Expand Down
88 changes: 88 additions & 0 deletions packages/harness/src/core/agent-map-capability-registry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { describe, expect, it, vi } from "vitest";

import type { PlanningSessionIdentity } from "../shared/agent-map.js";
import {
AgentMapCapabilityError,
AgentMapCapabilityRegistry,
} from "./agent-map-capability-registry.js";

const identity = (sessionId = "session-1"): PlanningSessionIdentity => ({
projectId: "project-a",
sessionId,
userId: "user-a",
role: "agent-builder",
assignment: { kind: "unplanned" },
});

describe("AgentMapCapabilityRegistry", () => {
it("stores only a digest and rotates one generation per session", () => {
const tokens = ["a".repeat(43), "b".repeat(43)];
const registry = new AgentMapCapabilityRegistry({ randomToken: () => tokens.shift()! });
const first = registry.issue(identity());
expect(registry.resolve(first.token).identity).toEqual(identity());
const second = registry.rotate(identity());
expect(second.generation).toBe(first.generation + 1);
expect(() => registry.resolve(first.token)).toThrowError(
expect.objectContaining({ code: "revoked_capability" }),
);
});

it("fails closed for expired, revoked and unknown tokens without emitting material", () => {
let now = 10;
const onEvent = vi.fn();
const registry = new AgentMapCapabilityRegistry({
ttlMs: 5,
now: () => now,
randomToken: () => "secret-token",
onEvent,
});
const issued = registry.issue(identity());
now = 15;
expect(() => registry.resolve(issued.token)).toThrowError(AgentMapCapabilityError);
expect(() => registry.resolve("other")).toThrowError(
expect.objectContaining({ code: "invalid_capability" }),
);
expect(JSON.stringify(onEvent.mock.calls)).not.toContain("secret-token");
});

it("slides expiry on authenticated use but remains bounded by lifecycle revocation", () => {
let now = 100;
const registry = new AgentMapCapabilityRegistry({
ttlMs: 10,
now: () => now,
randomToken: () => "long-lived-session-token",
});
const issued = registry.issue(identity());
expect(issued.expiresAt).toBe(110);

now = 109;
expect(registry.resolve(issued.token).expiresAt).toBe(119);
now = 118;
expect(registry.resolve(issued.token).expiresAt).toBe(128);
expect(
registry.isGenerationLive(identity().sessionId, issued.generation),
).toBe(true);

registry.revokeSession(identity().sessionId);
expect(() => registry.resolve(issued.token)).toThrowError(
expect.objectContaining({ code: "revoked_capability" }),
);
});

it("expires a capability after a full inactivity window", () => {
let now = 100;
const registry = new AgentMapCapabilityRegistry({
ttlMs: 10,
now: () => now,
randomToken: () => "inactive-session-token",
});
const issued = registry.issue(identity());

now = 109;
registry.resolve(issued.token);
now = 119;
expect(() => registry.resolve(issued.token)).toThrowError(
expect.objectContaining({ code: "expired_capability" }),
);
});
});
170 changes: 170 additions & 0 deletions packages/harness/src/core/agent-map-capability-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { createHash, randomBytes } from "node:crypto";

import type { PlanningSessionIdentity } from "../shared/agent-map.js";

export type AgentMapCapabilityRejection =
| "invalid_capability"
| "expired_capability"
| "revoked_capability";

export class AgentMapCapabilityError extends Error {
constructor(readonly code: AgentMapCapabilityRejection) {
super("Agent Map capability is not valid");
this.name = "AgentMapCapabilityError";
}
}

export interface ResolvedAgentMapCapability {
identity: PlanningSessionIdentity;
generation: number;
expiresAt: number;
}

export interface IssuedAgentMapCapability extends ResolvedAgentMapCapability {
token: string;
}

export interface AgentMapCapabilityEvent {
name:
| "agent_map.capability.issued"
| "agent_map.capability.rotated"
| "agent_map.capability.revoked"
| "agent_map.capability.rejected";
role?: PlanningSessionIdentity["role"];
reason?: AgentMapCapabilityRejection;
}

export interface AgentMapCapabilityRegistryOptions {
ttlMs?: number;
now?: () => number;
randomToken?: () => string;
onEvent?: (event: AgentMapCapabilityEvent) => void;
}

interface Entry extends ResolvedAgentMapCapability {
digest: string;
}

const DEFAULT_TTL_MS = 12 * 60 * 60 * 1_000;
const MAX_REVOKED_DIGESTS = 4_096;

/** Process-local, digest-only authority for the embedded Agent Map MCP. */
export class AgentMapCapabilityRegistry {
private readonly active = new Map<string, Entry>();
private readonly currentBySession = new Map<string, string>();
private readonly revoked = new Set<string>();
private readonly generations = new Map<string, number>();
private readonly ttlMs: number;
private readonly now: () => number;
private readonly randomToken: () => string;

constructor(private readonly options: AgentMapCapabilityRegistryOptions = {}) {
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
this.now = options.now ?? Date.now;
this.randomToken =
options.randomToken ?? (() => randomBytes(32).toString("base64url"));
}

issue(identity: PlanningSessionIdentity): IssuedAgentMapCapability {
this.revokeSession(identity.sessionId);
const token = this.randomToken();
const digest = this.digest(token);
if (!token || this.active.has(digest) || this.revoked.has(digest)) {
throw new AgentMapCapabilityError("invalid_capability");
}
const generation = (this.generations.get(identity.sessionId) ?? 0) + 1;
this.generations.set(identity.sessionId, generation);
const entry: Entry = {
digest,
identity: structuredClone(identity),
generation,
expiresAt: this.now() + this.ttlMs,
};
this.active.set(digest, entry);
this.currentBySession.set(identity.sessionId, digest);
this.emit({ name: "agent_map.capability.issued", role: identity.role });
return { token, ...this.publicEntry(entry) };
}

rotate(identity: PlanningSessionIdentity): IssuedAgentMapCapability {
this.revokeSession(identity.sessionId);
const issued = this.issue(identity);
this.emit({ name: "agent_map.capability.rotated", role: identity.role });
return issued;
}

resolve(token: string): ResolvedAgentMapCapability {
const digest = this.digest(token);
const entry = this.active.get(digest);
if (!entry) {
const reason = this.revoked.has(digest)
? "revoked_capability"
: "invalid_capability";
this.reject(reason);
}
const resolvedAt = this.now();
if (entry.expiresAt <= resolvedAt) {
this.active.delete(digest);
this.currentBySession.delete(entry.identity.sessionId);
this.revoked.add(digest);
this.pruneRevoked();
this.reject("expired_capability");
}
// This is an inactivity lease, not a scheduled outage for a live agent.
// Successful authenticated use keeps the same private token viable while
// exit, principal change, resume rotation, and explicit revocation remain
// hard lifecycle boundaries.
entry.expiresAt = resolvedAt + this.ttlMs;
return this.publicEntry(entry);
}

revokeSession(sessionId: string): void {
const digest = this.currentBySession.get(sessionId);
if (!digest) return;
const entry = this.active.get(digest);
this.active.delete(digest);
this.currentBySession.delete(sessionId);
this.revoked.add(digest);
this.pruneRevoked();
this.emit({ name: "agent_map.capability.revoked", role: entry?.identity.role });
}

isGenerationLive(sessionId: string, generation: number): boolean {
const digest = this.currentBySession.get(sessionId);
const entry = digest ? this.active.get(digest) : undefined;
return !!entry && entry.generation === generation && entry.expiresAt > this.now();
}

private publicEntry(entry: Entry): ResolvedAgentMapCapability {
return {
identity: structuredClone(entry.identity),
generation: entry.generation,
expiresAt: entry.expiresAt,
};
}

private digest(token: string): string {
return createHash("sha256").update(token, "utf8").digest("hex");
}

private reject(reason: AgentMapCapabilityRejection): never {
this.emit({ name: "agent_map.capability.rejected", reason });
throw new AgentMapCapabilityError(reason);
}

private pruneRevoked(): void {
while (this.revoked.size > MAX_REVOKED_DIGESTS) {
const oldest = this.revoked.values().next().value as string | undefined;
if (!oldest) break;
this.revoked.delete(oldest);
}
}

private emit(event: AgentMapCapabilityEvent): void {
try {
this.options.onEvent?.(event);
} catch {
// Bounded observability must never change authorization semantics.
}
}
}
Loading
Loading