@duct-sdk/sdk 0.5.13 → 0.6.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/CHANGELOG.md +385 -344
- package/README.md +418 -264
- package/TOKEN_SPEC.md +243 -243
- package/dist/cli/add.d.ts +7 -0
- package/dist/cli/add.js +152 -0
- package/dist/cli/agent-prompt.d.ts +3 -0
- package/dist/cli/agent-prompt.js +39 -0
- package/dist/cli/api-sources.d.ts +26 -0
- package/dist/cli/api-sources.js +222 -0
- package/dist/cli/cloud.d.ts +133 -0
- package/dist/cli/cloud.js +298 -0
- package/dist/cli/config-loader.d.ts +14 -0
- package/dist/cli/config-loader.js +56 -7
- package/dist/cli/device-login.d.ts +17 -0
- package/dist/cli/device-login.js +75 -0
- package/dist/cli/drift.js +6 -6
- package/dist/cli/generators/any-stack.d.ts +3 -0
- package/dist/cli/generators/any-stack.js +97 -0
- package/dist/cli/generators/config.js +3 -2
- package/dist/cli/generators/receiver.js +7 -7
- package/dist/cli/generators/shell.js +12 -12
- package/dist/cli/generators/token-route.js +245 -245
- package/dist/cli/index.js +396 -611
- package/dist/cli/mcp-core.d.ts +42 -0
- package/dist/cli/mcp-core.js +161 -0
- package/dist/cli/mcp-setup.d.ts +4 -0
- package/dist/cli/mcp-setup.js +360 -0
- package/dist/cli/mcp.d.ts +2 -0
- package/dist/cli/mcp.js +457 -0
- package/dist/cli/migrate-intershell.js +5 -5
- package/dist/cli/policy-defaults.d.ts +37 -0
- package/dist/cli/policy-defaults.js +127 -0
- package/dist/cli/processors/integration-audit.js +2 -2
- package/dist/cli/processors/openapi-parser.d.ts +5 -0
- package/dist/cli/processors/openapi-parser.js +8 -3
- package/dist/cli/project-loader.d.ts +58 -0
- package/dist/cli/project-loader.js +198 -0
- package/dist/cli/project-writer.d.ts +23 -0
- package/dist/cli/project-writer.js +171 -0
- package/dist/cli/push.d.ts +43 -0
- package/dist/cli/push.js +276 -0
- package/dist/cli/safety-checks.d.ts +9 -0
- package/dist/cli/safety-checks.js +29 -0
- package/dist/cli/setup.d.ts +20 -0
- package/dist/cli/setup.js +349 -0
- package/dist/cli/shell-name.d.ts +8 -0
- package/dist/cli/shell-name.js +29 -0
- package/dist/cli/shells.d.ts +22 -0
- package/dist/cli/shells.js +122 -0
- package/dist/cli/split.d.ts +7 -0
- package/dist/cli/split.js +71 -0
- package/dist/cli/sync.d.ts +25 -0
- package/dist/cli/sync.js +120 -0
- package/dist/cli/test-runner.d.ts +21 -0
- package/dist/cli/test-runner.js +281 -0
- package/dist/core/compile.d.ts +43 -0
- package/dist/core/compile.js +510 -0
- package/dist/core/config.d.ts +464 -1
- package/dist/core/config.js +14 -14
- package/dist/core/login-handoff.d.ts +1 -1
- package/dist/core/login-handoff.js +1 -1
- package/dist/core/project.d.ts +1798 -0
- package/dist/core/project.js +278 -0
- package/dist/core/readiness-checks.js +2 -2
- package/dist/core/types.d.ts +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/project.d.ts +4 -0
- package/dist/project.js +8 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +1 -0
- package/package.json +94 -95
- package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
- package/dist/adapters/react/page-context-guard.test.js +0 -15
- package/dist/cli/agents/api-agent.d.ts +0 -22
- package/dist/cli/agents/api-agent.js +0 -761
- package/dist/cli/agents/auth-agent.d.ts +0 -7
- package/dist/cli/agents/auth-agent.js +0 -212
- package/dist/cli/agents/deeplink-agent.d.ts +0 -6
- package/dist/cli/agents/deeplink-agent.js +0 -285
- package/dist/cli/agents/llm.d.ts +0 -33
- package/dist/cli/agents/llm.js +0 -309
- package/dist/cli/agents/pipeline.d.ts +0 -72
- package/dist/cli/agents/pipeline.js +0 -421
- package/dist/cli/agents/reviewer-agent.d.ts +0 -13
- package/dist/cli/agents/reviewer-agent.js +0 -450
- package/dist/cli/agents/route-agent.d.ts +0 -17
- package/dist/cli/agents/route-agent.js +0 -383
- package/dist/cli/config-loader.test.d.ts +0 -1
- package/dist/cli/config-loader.test.js +0 -63
- package/dist/cli/detectors/topology.d.ts +0 -46
- package/dist/cli/detectors/topology.js +0 -417
- package/dist/cli/generators/config.test.d.ts +0 -1
- package/dist/cli/generators/config.test.js +0 -222
- package/dist/cli/generators/shell.test.d.ts +0 -1
- package/dist/cli/generators/shell.test.js +0 -73
- package/dist/cli/generators/token-route.test.d.ts +0 -1
- package/dist/cli/generators/token-route.test.js +0 -53
- package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
- package/dist/cli/generators/wiring-snippets.test.js +0 -80
- package/dist/cli/init.d.ts +0 -32
- package/dist/cli/init.js +0 -1336
- package/dist/cli/manifest-diff.test.d.ts +0 -1
- package/dist/cli/manifest-diff.test.js +0 -144
- package/dist/cli/processors/curl-parser.test.d.ts +0 -1
- package/dist/cli/processors/curl-parser.test.js +0 -24
- package/dist/cli/processors/integration-audit.test.d.ts +0 -1
- package/dist/cli/processors/integration-audit.test.js +0 -154
- package/dist/cli/processors/postprocess.d.ts +0 -22
- package/dist/cli/processors/postprocess.js +0 -107
- package/dist/cli/processors/prisma-parser.d.ts +0 -35
- package/dist/cli/processors/prisma-parser.js +0 -117
- package/dist/cli/processors/verify-discovery.d.ts +0 -33
- package/dist/cli/processors/verify-discovery.js +0 -193
- package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
- package/dist/cli/processors/verify-discovery.test.js +0 -153
- package/dist/cli/processors/zod-extractor.d.ts +0 -27
- package/dist/cli/processors/zod-extractor.js +0 -153
- package/dist/cli/prompts/review.d.ts +0 -61
- package/dist/cli/prompts/review.js +0 -410
- package/dist/cli/selectors/express.d.ts +0 -12
- package/dist/cli/selectors/express.js +0 -117
- package/dist/cli/selectors/fastapi.d.ts +0 -12
- package/dist/cli/selectors/fastapi.js +0 -122
- package/dist/cli/selectors/generic.d.ts +0 -10
- package/dist/cli/selectors/generic.js +0 -74
- package/dist/cli/selectors/index.d.ts +0 -37
- package/dist/cli/selectors/index.js +0 -315
- package/dist/cli/selectors/next.d.ts +0 -12
- package/dist/cli/selectors/next.js +0 -130
- package/dist/core/config-policy.test.d.ts +0 -1
- package/dist/core/config-policy.test.js +0 -101
- package/dist/core/config-roundtrip.test.d.ts +0 -1
- package/dist/core/config-roundtrip.test.js +0 -180
- package/dist/core/endpoint-guard.test.d.ts +0 -1
- package/dist/core/endpoint-guard.test.js +0 -57
- package/dist/core/env-diagnostics.test.d.ts +0 -1
- package/dist/core/env-diagnostics.test.js +0 -31
- package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
- package/dist/core/evidence-bundle.conformance.test.js +0 -110
- package/dist/core/evidence-bundle.test.d.ts +0 -1
- package/dist/core/evidence-bundle.test.js +0 -58
- package/dist/core/invariants.test.d.ts +0 -1
- package/dist/core/invariants.test.js +0 -217
- package/dist/core/login-handoff.test.d.ts +0 -1
- package/dist/core/login-handoff.test.js +0 -31
- package/dist/core/profile.test.d.ts +0 -1
- package/dist/core/profile.test.js +0 -95
- package/dist/core/readiness-checks.test.d.ts +0 -1
- package/dist/core/readiness-checks.test.js +0 -106
- package/dist/core/receipt.test.d.ts +0 -1
- package/dist/core/receipt.test.js +0 -75
- package/dist/core/sdk-entrypoint.test.d.ts +0 -1
- package/dist/core/sdk-entrypoint.test.js +0 -8
- package/dist/core/side-effects-review.test.d.ts +0 -1
- package/dist/core/side-effects-review.test.js +0 -28
- package/dist/core/token.conformance.test.d.ts +0 -1
- package/dist/core/token.conformance.test.js +0 -43
- package/dist/core/token.test.d.ts +0 -1
- package/dist/core/token.test.js +0 -66
package/dist/cli/mcp.js
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct-sdk/sdk — onboarding MCP server
|
|
3
|
+
//
|
|
4
|
+
// npx @duct-sdk/sdk mcp
|
|
5
|
+
//
|
|
6
|
+
// Lets a developer's coding assistant (Claude Code, Cursor, VS Code, Codex, …) connect a
|
|
7
|
+
// codebase to Duct: inspect the project, write duct/, run checks, and push once the
|
|
8
|
+
// developer approves. Every tool runs the same CLI command a developer would type, in a
|
|
9
|
+
// subprocess, so behaviour matches the CLI exactly and nothing it prints can corrupt the
|
|
10
|
+
// protocol stream. The API key never passes through the conversation: signing in is
|
|
11
|
+
// `npx @duct-sdk/sdk login` in the developer's own terminal (or DUCT_API_KEY).
|
|
12
|
+
//
|
|
13
|
+
// Transport: MCP over stdio (newline-delimited JSON-RPC 2.0). No extra dependencies.
|
|
14
|
+
// ============================================================
|
|
15
|
+
import { spawn } from "child_process";
|
|
16
|
+
import { createHash } from "crypto";
|
|
17
|
+
import { existsSync, readFileSync, statSync } from "fs";
|
|
18
|
+
import * as fs from "fs/promises";
|
|
19
|
+
import * as path from "path";
|
|
20
|
+
import { fileURLToPath } from "url";
|
|
21
|
+
import { buildAgentPrompt } from "./agent-prompt.js";
|
|
22
|
+
import { discoverLocalSources } from "./api-sources.js";
|
|
23
|
+
import { listAccountShells, readAuth, resolveApiKey } from "./cloud.js";
|
|
24
|
+
import { findProjectRoot } from "./project-loader.js";
|
|
25
|
+
import { normalizeShellName, shellNameError } from "./shell-name.js";
|
|
26
|
+
import { InvalidParams, looksLikeRepo, runStdioServer, text } from "./mcp-core.js";
|
|
27
|
+
export const SERVER_NAME = "duct-onboarding";
|
|
28
|
+
const CLI_ENTRY = fileURLToPath(new URL("./index.js", import.meta.url));
|
|
29
|
+
const VERSION = JSON.parse(readFileSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json"), "utf-8")).version;
|
|
30
|
+
/** Output returned to the assistant is capped so a noisy command cannot flood its context. */
|
|
31
|
+
const MAX_OUTPUT_CHARS = 8000;
|
|
32
|
+
const SIGN_IN_HINT = "Not signed in to Duct. Ask the developer to run `npx @duct-sdk/sdk login` in their own terminal; it opens the " +
|
|
33
|
+
"browser to approve this machine (no key is pasted anywhere). In CI, set DUCT_API_KEY. Then retry.";
|
|
34
|
+
const INSTRUCTIONS = `Connects this codebase to Duct, a gateway that lets AI agents call the product's API under a policy the team controls.
|
|
35
|
+
Workflow: duct_status → duct_create_shell if there is none → duct_setup (writes duct/) → describe endpoints in duct/capabilities.json if setup had no API spec → duct_check until it passes → duct_push (shows the change; push only after the developer approves).
|
|
36
|
+
Never change application code unless the developer asks, never edit duct/policy.ts beyond denying destructive actions, and never ask for the API key in chat.`;
|
|
37
|
+
// eslint-disable-next-line no-control-regex
|
|
38
|
+
const ANSI_RE = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
39
|
+
function clip(output) {
|
|
40
|
+
const clean = output.replace(ANSI_RE, "").replace(/\r/g, "").trim();
|
|
41
|
+
if (clean.length <= MAX_OUTPUT_CHARS)
|
|
42
|
+
return clean;
|
|
43
|
+
const head = clean.slice(0, MAX_OUTPUT_CHARS / 2);
|
|
44
|
+
const tail = clean.slice(-MAX_OUTPUT_CHARS / 2);
|
|
45
|
+
return `${head}\n… (${clean.length - MAX_OUTPUT_CHARS} characters omitted) …\n${tail}`;
|
|
46
|
+
}
|
|
47
|
+
function runCli(args, cwd, timeoutMs) {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
const child = spawn(process.execPath, [CLI_ENTRY, ...args], {
|
|
50
|
+
cwd,
|
|
51
|
+
// No TTY and CI=true: commands never wait for input.
|
|
52
|
+
env: { ...process.env, CI: "true", NO_COLOR: "1", FORCE_COLOR: "0" },
|
|
53
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
54
|
+
});
|
|
55
|
+
let output = "";
|
|
56
|
+
let timedOut = false;
|
|
57
|
+
child.stdout.on("data", (chunk) => (output += chunk));
|
|
58
|
+
child.stderr.on("data", (chunk) => (output += chunk));
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
timedOut = true;
|
|
61
|
+
child.kill();
|
|
62
|
+
}, timeoutMs);
|
|
63
|
+
child.on("error", (err) => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
resolve({ code: 1, output: `${output}\n${err.message}`, timedOut });
|
|
66
|
+
});
|
|
67
|
+
child.on("close", (code) => {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
resolve({ code, output, timedOut });
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function parseJsonOutput(output) {
|
|
74
|
+
const start = output.indexOf("{");
|
|
75
|
+
if (start < 0)
|
|
76
|
+
return null;
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(output.slice(start));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// ----------------------------------------------------------------
|
|
85
|
+
// Arguments
|
|
86
|
+
// ----------------------------------------------------------------
|
|
87
|
+
function projectDir(args) {
|
|
88
|
+
const raw = args.projectDir;
|
|
89
|
+
if (raw === undefined || raw === null || raw === "")
|
|
90
|
+
return process.cwd();
|
|
91
|
+
if (typeof raw !== "string" || !path.isAbsolute(raw))
|
|
92
|
+
throw new InvalidParams("projectDir must be an absolute path.");
|
|
93
|
+
if (!existsSync(raw) || !statSync(raw).isDirectory())
|
|
94
|
+
throw new InvalidParams(`projectDir ${raw} is not a directory.`);
|
|
95
|
+
return raw;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Directory for tools that write or publish. Some clients start stdio servers in the home or
|
|
99
|
+
* install directory, so without an explicit projectDir the server's own directory must look
|
|
100
|
+
* like a repository; otherwise the assistant is asked to say which repository it means.
|
|
101
|
+
*/
|
|
102
|
+
function writableProjectDir(args) {
|
|
103
|
+
const dir = projectDir(args);
|
|
104
|
+
const explicit = typeof args.projectDir === "string" && args.projectDir !== "";
|
|
105
|
+
if (!explicit && !looksLikeRepo(dir) && !findProjectRoot(dir)) {
|
|
106
|
+
throw new InvalidParams(`The server is running in ${dir}, which does not look like a repository. ` +
|
|
107
|
+
"Call again with projectDir set to the absolute path of the repository root.");
|
|
108
|
+
}
|
|
109
|
+
return dir;
|
|
110
|
+
}
|
|
111
|
+
/** Fingerprint of the files a push compiles, so a confirmed push is exactly what was previewed. */
|
|
112
|
+
async function projectFingerprint(dir) {
|
|
113
|
+
const found = findProjectRoot(dir);
|
|
114
|
+
if (!found)
|
|
115
|
+
return null;
|
|
116
|
+
const hash = createHash("sha256");
|
|
117
|
+
if (found.layout === "split") {
|
|
118
|
+
const base = path.join(found.root, "duct");
|
|
119
|
+
const files = [];
|
|
120
|
+
const walk = async (current) => {
|
|
121
|
+
for (const entry of await fs.readdir(current, { withFileTypes: true })) {
|
|
122
|
+
const full = path.join(current, entry.name);
|
|
123
|
+
if (entry.isDirectory())
|
|
124
|
+
await walk(full);
|
|
125
|
+
else if (entry.isFile())
|
|
126
|
+
files.push(full);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
await walk(base);
|
|
130
|
+
for (const file of files.sort()) {
|
|
131
|
+
hash.update(path.relative(base, file).split(path.sep).join("/"));
|
|
132
|
+
hash.update("\0");
|
|
133
|
+
hash.update(await fs.readFile(file));
|
|
134
|
+
hash.update("\0");
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
hash.update(await fs.readFile(path.join(found.root, "duct.config.ts")));
|
|
139
|
+
}
|
|
140
|
+
return hash.digest("hex").slice(0, 16);
|
|
141
|
+
}
|
|
142
|
+
function optionalString(args, key) {
|
|
143
|
+
const value = args[key];
|
|
144
|
+
if (value === undefined || value === null || value === "")
|
|
145
|
+
return undefined;
|
|
146
|
+
if (typeof value !== "string")
|
|
147
|
+
throw new InvalidParams(`${key} must be a string.`);
|
|
148
|
+
return value.trim();
|
|
149
|
+
}
|
|
150
|
+
const PROJECT_DIR_SCHEMA = {
|
|
151
|
+
type: "string",
|
|
152
|
+
description: "Absolute path to the repository root. Defaults to the directory the server was started in.",
|
|
153
|
+
};
|
|
154
|
+
// ----------------------------------------------------------------
|
|
155
|
+
// Tools
|
|
156
|
+
// ----------------------------------------------------------------
|
|
157
|
+
async function signedInShells() {
|
|
158
|
+
const auth = await readAuth();
|
|
159
|
+
const apiKey = resolveApiKey(auth);
|
|
160
|
+
if (!apiKey)
|
|
161
|
+
return { signedIn: false };
|
|
162
|
+
try {
|
|
163
|
+
return { signedIn: true, shells: await listAccountShells(auth, apiKey) };
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
return { signedIn: true, shells: null, error: err instanceof Error ? err.message : String(err) };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function countActions(root) {
|
|
170
|
+
try {
|
|
171
|
+
const parsed = JSON.parse(await fs.readFile(path.join(root, "duct", "capabilities.json"), "utf-8"));
|
|
172
|
+
return Array.isArray(parsed.actions) ? parsed.actions.length : null;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const statusTool = {
|
|
179
|
+
name: "duct_status",
|
|
180
|
+
title: "Duct status",
|
|
181
|
+
description: "Start here. Reports whether the developer is signed in to Duct, which shells (one per product and environment) they can use, whether this repo already has a duct/ project, and which API specs were found. Ends with the next step.",
|
|
182
|
+
inputSchema: { type: "object", properties: { projectDir: PROJECT_DIR_SCHEMA }, additionalProperties: false },
|
|
183
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
184
|
+
async run(args) {
|
|
185
|
+
const dir = projectDir(args);
|
|
186
|
+
const found = findProjectRoot(dir);
|
|
187
|
+
const root = found?.root ?? dir;
|
|
188
|
+
const [account, sources, actionCount] = await Promise.all([
|
|
189
|
+
signedInShells(),
|
|
190
|
+
discoverLocalSources(root),
|
|
191
|
+
found?.layout === "split" ? countActions(root) : Promise.resolve(null),
|
|
192
|
+
]);
|
|
193
|
+
const project = found
|
|
194
|
+
? { root, layout: found.layout === "split" ? "duct/ folder" : "legacy duct.config.ts", actionCount }
|
|
195
|
+
: null;
|
|
196
|
+
const shells = account.signedIn ? account.shells?.map((s) => ({ id: s.id, environment: s.environment, status: s.status })) ?? null : null;
|
|
197
|
+
let next;
|
|
198
|
+
if (!found && !looksLikeRepo(root))
|
|
199
|
+
next = `${root} does not look like a repository. Call the tools with projectDir set to the absolute path of the repository root.`;
|
|
200
|
+
else if (!account.signedIn)
|
|
201
|
+
next = SIGN_IN_HINT;
|
|
202
|
+
else if (account.shells && account.shells.length === 0)
|
|
203
|
+
next = "The workspace has no shells yet. Ask the developer for a name (prod, staging, dev, or a custom one) and where the product runs, then call duct_create_shell.";
|
|
204
|
+
else if (!project)
|
|
205
|
+
next =
|
|
206
|
+
sources.length > 0
|
|
207
|
+
? `Call duct_setup with source "${sources[0].location}".${shells && shells.length > 1 ? " Ask the developer which shell to use and pass it as shell." : ""}`
|
|
208
|
+
: `No API spec found. Call duct_setup with source "none" (or the URL of the spec the running API serves), then describe the endpoints in duct/capabilities.json.${shells && shells.length > 1 ? " Ask the developer which shell to use and pass it as shell." : ""}`;
|
|
209
|
+
else if (found?.layout !== "split")
|
|
210
|
+
next = "This repo uses a legacy duct.config.ts. Run `npx @duct-sdk/sdk split` to convert it, then call duct_check.";
|
|
211
|
+
else if (actionCount === 0)
|
|
212
|
+
next = "duct/capabilities.json has no actions yet. Describe the API's endpoints there (see the onboard prompt), then call duct_check.";
|
|
213
|
+
else
|
|
214
|
+
next = "Call duct_check. When it passes, call duct_push to show the developer what will change.";
|
|
215
|
+
const structured = {
|
|
216
|
+
directory: root,
|
|
217
|
+
looksLikeRepository: Boolean(found) || looksLikeRepo(root),
|
|
218
|
+
signedIn: account.signedIn,
|
|
219
|
+
shells,
|
|
220
|
+
...(account.signedIn && account.error ? { shellsError: account.error } : {}),
|
|
221
|
+
project,
|
|
222
|
+
apiSources: sources.map((s) => ({ kind: s.kind, location: s.location })),
|
|
223
|
+
next,
|
|
224
|
+
};
|
|
225
|
+
return text(JSON.stringify(structured, null, 2), structured);
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
const setupTool = {
|
|
229
|
+
name: "duct_setup",
|
|
230
|
+
title: "Create the duct/ project",
|
|
231
|
+
description: "Writes the duct/ project (capabilities, policy with safe defaults, tests) from an API spec, then runs checks. Never pushes. Agents get read-only access by default; anything with side effects needs approval.",
|
|
232
|
+
inputSchema: {
|
|
233
|
+
type: "object",
|
|
234
|
+
properties: {
|
|
235
|
+
projectDir: PROJECT_DIR_SCHEMA,
|
|
236
|
+
source: {
|
|
237
|
+
type: "string",
|
|
238
|
+
description: "OpenAPI spec, Postman collection, or curl script (repo path or URL), or \"none\" to start with an empty action list.",
|
|
239
|
+
},
|
|
240
|
+
shell: { type: "string", description: "Shell name (prod, checkout-prod) or ID. Required when the workspace has more than one shell." },
|
|
241
|
+
apiUrl: { type: "string", description: "Public URL where the API is served, if not the shell's registered domain." },
|
|
242
|
+
force: { type: "boolean", description: "Replace an existing duct/ folder. Only with the developer's explicit go-ahead." },
|
|
243
|
+
},
|
|
244
|
+
required: ["source"],
|
|
245
|
+
additionalProperties: false,
|
|
246
|
+
},
|
|
247
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
|
|
248
|
+
async run(args) {
|
|
249
|
+
const dir = writableProjectDir(args);
|
|
250
|
+
const source = optionalString(args, "source");
|
|
251
|
+
if (!source)
|
|
252
|
+
throw new InvalidParams("source is required (a path, a URL, or \"none\").");
|
|
253
|
+
const shell = optionalString(args, "shell");
|
|
254
|
+
const apiUrl = optionalString(args, "apiUrl");
|
|
255
|
+
const account = await signedInShells();
|
|
256
|
+
if (!account.signedIn)
|
|
257
|
+
return text(SIGN_IN_HINT, undefined, true);
|
|
258
|
+
if (!shell && account.shells && account.shells.length > 1) {
|
|
259
|
+
const list = account.shells.map((s) => `${s.id} (${s.environment}, ${s.status})`).join("\n");
|
|
260
|
+
return text(`This workspace has several shells. Ask the developer which one to use, then call again with shell:\n${list}`, undefined, true);
|
|
261
|
+
}
|
|
262
|
+
const cliArgs = ["setup", "--yes", "--no-push", "--source", source];
|
|
263
|
+
if (shell)
|
|
264
|
+
cliArgs.push("--shell", shell);
|
|
265
|
+
if (apiUrl)
|
|
266
|
+
cliArgs.push("--api-url", apiUrl);
|
|
267
|
+
if (args.force === true)
|
|
268
|
+
cliArgs.push("--force");
|
|
269
|
+
const run = await runCli(cliArgs, dir, 180_000);
|
|
270
|
+
const out = clip(run.output);
|
|
271
|
+
if (run.timedOut)
|
|
272
|
+
return text(`Setup timed out after 3 minutes.\n\n${out}`, undefined, true);
|
|
273
|
+
if (run.code !== 0)
|
|
274
|
+
return text(out, undefined, true);
|
|
275
|
+
return text(`${out}\n\nNext: review duct/policy.ts with the developer, then call duct_check.`);
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
const createShellTool = {
|
|
279
|
+
name: "duct_create_shell",
|
|
280
|
+
title: "Create a shell",
|
|
281
|
+
description: "Creates a shell (one per product and environment): prod, staging, dev, or a custom name such as checkout-prod. Without confirm it only shows what would be created. With confirm: true it creates the shell and saves its credentials to a git-ignored .env.duct.<name> file; the secret is never returned here.",
|
|
282
|
+
inputSchema: {
|
|
283
|
+
type: "object",
|
|
284
|
+
properties: {
|
|
285
|
+
projectDir: PROJECT_DIR_SCHEMA,
|
|
286
|
+
name: { type: "string", description: "prod, staging, dev, or a custom name (lowercase letters, digits, hyphens)." },
|
|
287
|
+
domains: {
|
|
288
|
+
type: "array",
|
|
289
|
+
items: { type: "string" },
|
|
290
|
+
description: "Where the product and its API run, e.g. https://app.example.com.",
|
|
291
|
+
},
|
|
292
|
+
confirm: { type: "boolean", description: "True only after the developer agreed to create this shell." },
|
|
293
|
+
},
|
|
294
|
+
required: ["name", "domains"],
|
|
295
|
+
additionalProperties: false,
|
|
296
|
+
},
|
|
297
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
298
|
+
async run(args) {
|
|
299
|
+
const dir = writableProjectDir(args);
|
|
300
|
+
const raw = optionalString(args, "name") ?? "";
|
|
301
|
+
const name = normalizeShellName(raw);
|
|
302
|
+
const problem = shellNameError(name);
|
|
303
|
+
if (problem)
|
|
304
|
+
return text(`"${raw}" is not a valid shell name. ${problem}`, undefined, true);
|
|
305
|
+
const domains = Array.isArray(args.domains) ? args.domains.filter((d) => typeof d === "string" && d.trim() !== "") : [];
|
|
306
|
+
if (domains.length === 0)
|
|
307
|
+
return text("Ask the developer where the product runs and pass it in domains (e.g. https://app.example.com).", undefined, true);
|
|
308
|
+
const account = await signedInShells();
|
|
309
|
+
if (!account.signedIn)
|
|
310
|
+
return text(SIGN_IN_HINT, undefined, true);
|
|
311
|
+
const existing = account.shells?.find((s) => s.environment === name);
|
|
312
|
+
if (existing) {
|
|
313
|
+
return text(`A shell named "${name}" already exists (${existing.id}). Use it with duct_setup (shell: "${name}"), or choose another name.`, { exists: true, shellId: existing.id }, true);
|
|
314
|
+
}
|
|
315
|
+
if (args.confirm !== true) {
|
|
316
|
+
return text(`Would create a shell named "${name}" for ${domains.join(", ")}. Its credentials (shell ID and a secret key shown only once) ` +
|
|
317
|
+
`will be saved to .env.duct.${name} in the repository, git-ignored; the secret is not shown in this conversation. ` +
|
|
318
|
+
"Ask the developer to confirm, then call again with confirm: true.", { name, domains, created: false });
|
|
319
|
+
}
|
|
320
|
+
const cliArgs = ["shells", "create", name, "--json"];
|
|
321
|
+
for (const domain of domains)
|
|
322
|
+
cliArgs.push("--domain", domain);
|
|
323
|
+
const run = await runCli(cliArgs, dir, 60_000);
|
|
324
|
+
const result = parseJsonOutput(run.output);
|
|
325
|
+
if (!result || run.code !== 0) {
|
|
326
|
+
const message = typeof result?.error === "string" ? `${result.error}${result.hint ? ` ${String(result.hint)}` : ""}` : clip(run.output);
|
|
327
|
+
return text(message || "The shell could not be created.", undefined, true);
|
|
328
|
+
}
|
|
329
|
+
return text(`Created ${String(result.shell_id)}. Credentials are in ${String(result.env_file)} (git-ignored). Ask the developer to copy them into the server's environment, then call duct_setup with shell: "${name}".`, { created: true, shellId: result.shell_id, envFile: result.env_file });
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
const checkTool = {
|
|
333
|
+
name: "duct_check",
|
|
334
|
+
title: "Check the project",
|
|
335
|
+
description: "Validates duct/ and asks Duct cloud whether it will work: API reachability, built-in guardrails, the project's policy tests, and whether the live shell matches. Returns a report; fix what fails and run it again.",
|
|
336
|
+
inputSchema: {
|
|
337
|
+
type: "object",
|
|
338
|
+
properties: {
|
|
339
|
+
projectDir: PROJECT_DIR_SCHEMA,
|
|
340
|
+
offline: { type: "boolean", description: "Only run local checks (no network)." },
|
|
341
|
+
},
|
|
342
|
+
additionalProperties: false,
|
|
343
|
+
},
|
|
344
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
345
|
+
async run(args) {
|
|
346
|
+
const dir = projectDir(args);
|
|
347
|
+
const run = await runCli(args.offline === true ? ["validate", "--json"] : ["test", "--json"], dir, 120_000);
|
|
348
|
+
const report = parseJsonOutput(run.output);
|
|
349
|
+
if (!report)
|
|
350
|
+
return text(clip(run.output) || "The check did not produce a report.", undefined, true);
|
|
351
|
+
return text(JSON.stringify(report, null, 2), report);
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
const pushTool = {
|
|
355
|
+
name: "duct_push",
|
|
356
|
+
title: "Push to Duct",
|
|
357
|
+
description: "Publishes duct/ so Duct enforces it. Without confirm it changes nothing: it runs every gate and returns what would change (actions, agent privileges, warnings) plus a previewToken. Show that to the developer; only after they approve, call again with confirm: true and the same previewToken.",
|
|
358
|
+
inputSchema: {
|
|
359
|
+
type: "object",
|
|
360
|
+
properties: {
|
|
361
|
+
projectDir: PROJECT_DIR_SCHEMA,
|
|
362
|
+
confirm: { type: "boolean", description: "True only after the developer approved the preview in this conversation." },
|
|
363
|
+
previewToken: { type: "string", description: "The previewToken from the preview the developer approved." },
|
|
364
|
+
},
|
|
365
|
+
additionalProperties: false,
|
|
366
|
+
},
|
|
367
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
368
|
+
async run(args) {
|
|
369
|
+
const dir = writableProjectDir(args);
|
|
370
|
+
const fingerprint = await projectFingerprint(dir);
|
|
371
|
+
if (!fingerprint)
|
|
372
|
+
return text("No duct/ project found. Call duct_setup first.", undefined, true);
|
|
373
|
+
if (args.confirm !== true) {
|
|
374
|
+
// --yes here only lets the dry run continue past gates that would otherwise stop it, so the
|
|
375
|
+
// developer sees every warning and the full privilege diff. Nothing is sent.
|
|
376
|
+
const run = await runCli(["push", "--dry-run", "--yes"], dir, 180_000);
|
|
377
|
+
const out = clip(run.output.split("\n").filter((line) => !line.includes("--yes")).join("\n"));
|
|
378
|
+
if (run.timedOut)
|
|
379
|
+
return text(`Preview timed out after 3 minutes.\n\n${out}`, undefined, true);
|
|
380
|
+
if (run.code !== 0) {
|
|
381
|
+
const hint = out.includes("sideEffectsReviewAck")
|
|
382
|
+
? "\n\nAsk the developer to confirm how each listed action is classified, record their reason as sideEffectsReviewAck in duct/capabilities.json, then preview again."
|
|
383
|
+
: "";
|
|
384
|
+
return text(`${out}${hint}`, undefined, true);
|
|
385
|
+
}
|
|
386
|
+
return text(`${out}\n\nNothing was pushed. Show the developer the changes and any warnings above and ask them to approve. ` +
|
|
387
|
+
`Then call duct_push with confirm: true and previewToken: "${fingerprint}".`, { pushed: false, previewToken: fingerprint });
|
|
388
|
+
}
|
|
389
|
+
if (optionalString(args, "previewToken") !== fingerprint) {
|
|
390
|
+
return text("duct/ changed since the preview the developer approved (or no preview token was given). " +
|
|
391
|
+
"Call duct_push without confirm, show the developer the new preview, and confirm with its previewToken.", undefined, true);
|
|
392
|
+
}
|
|
393
|
+
const run = await runCli(["push", "--yes"], dir, 180_000);
|
|
394
|
+
const out = clip(run.output);
|
|
395
|
+
if (run.timedOut)
|
|
396
|
+
return text(`Push timed out after 3 minutes.\n\n${out}`, undefined, true);
|
|
397
|
+
if (run.code !== 0)
|
|
398
|
+
return text(out, undefined, true);
|
|
399
|
+
return text(`${out}\n\nPushed. Run duct_check to confirm live enforcement matches the project.`, { pushed: true });
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
const addTool = {
|
|
403
|
+
name: "duct_add",
|
|
404
|
+
title: "Add an integration layer",
|
|
405
|
+
description: "Generates wiring for an optional layer. identity: lets agents act for the product's signed-in users (token route and receiver). shell: embeds the Duct chat UI in the product. Files are written for the detected framework, or as an HTTP contract for any other stack.",
|
|
406
|
+
inputSchema: {
|
|
407
|
+
type: "object",
|
|
408
|
+
properties: {
|
|
409
|
+
projectDir: PROJECT_DIR_SCHEMA,
|
|
410
|
+
layer: { type: "string", enum: ["identity", "shell"] },
|
|
411
|
+
force: { type: "boolean", description: "Overwrite generated files that already exist." },
|
|
412
|
+
},
|
|
413
|
+
required: ["layer"],
|
|
414
|
+
additionalProperties: false,
|
|
415
|
+
},
|
|
416
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
417
|
+
async run(args) {
|
|
418
|
+
const dir = writableProjectDir(args);
|
|
419
|
+
const layer = args.layer;
|
|
420
|
+
if (layer !== "identity" && layer !== "shell")
|
|
421
|
+
throw new InvalidParams('layer must be "identity" or "shell".');
|
|
422
|
+
const cliArgs = ["add", layer];
|
|
423
|
+
if (args.force === true)
|
|
424
|
+
cliArgs.push("--force");
|
|
425
|
+
const run = await runCli(cliArgs, dir, 60_000);
|
|
426
|
+
return text(clip(run.output), undefined, run.code !== 0);
|
|
427
|
+
},
|
|
428
|
+
};
|
|
429
|
+
const TOOLS = [statusTool, createShellTool, setupTool, checkTool, pushTool, addTool];
|
|
430
|
+
// ----------------------------------------------------------------
|
|
431
|
+
// Prompts
|
|
432
|
+
// ----------------------------------------------------------------
|
|
433
|
+
const ONBOARD_PROMPT = {
|
|
434
|
+
name: "onboard",
|
|
435
|
+
title: "Connect this codebase to Duct",
|
|
436
|
+
description: "Step-by-step onboarding: set up duct/, describe the API, check, and push with the developer's approval.",
|
|
437
|
+
};
|
|
438
|
+
function onboardPromptText() {
|
|
439
|
+
const found = findProjectRoot(process.cwd());
|
|
440
|
+
return `${INSTRUCTIONS}
|
|
441
|
+
|
|
442
|
+
Start by calling duct_status and follow its "next" step. When setup found no API spec, describe the endpoints yourself:
|
|
443
|
+
|
|
444
|
+
${buildAgentPrompt({ hasProject: found?.layout === "split" })}
|
|
445
|
+
|
|
446
|
+
Use duct_check instead of running validate/test in a terminal. Before duct_push with confirm: true, show the developer the preview and wait for their approval.`;
|
|
447
|
+
}
|
|
448
|
+
export async function runMcpServer() {
|
|
449
|
+
await runStdioServer({
|
|
450
|
+
name: SERVER_NAME,
|
|
451
|
+
title: "Duct onboarding",
|
|
452
|
+
version: VERSION,
|
|
453
|
+
instructions: INSTRUCTIONS,
|
|
454
|
+
tools: TOOLS,
|
|
455
|
+
prompts: [{ ...ONBOARD_PROMPT, text: onboardPromptText }],
|
|
456
|
+
});
|
|
457
|
+
}
|
|
@@ -42,11 +42,11 @@ async function inspectConfig(configPath) {
|
|
|
42
42
|
// ----------------------------------------------------------------
|
|
43
43
|
export async function runMigrateIntershell(opts = {}) {
|
|
44
44
|
const cwd = opts.cwd ?? process.cwd();
|
|
45
|
-
console.log(chalk.bold("\n
|
|
45
|
+
console.log(chalk.bold("\n Duct · migrate intershell\n"));
|
|
46
46
|
const configPath = await findConfigFile(cwd);
|
|
47
47
|
if (!configPath) {
|
|
48
48
|
console.log(chalk.yellow(" No duct.config.ts or duct.config.js found in the current directory.\n" +
|
|
49
|
-
" Run `npx duct
|
|
49
|
+
" Run `npx @duct-sdk/sdk` (setup) first to create your project.\n"));
|
|
50
50
|
return;
|
|
51
51
|
}
|
|
52
52
|
console.log(chalk.gray(` Config: ${configPath}\n`));
|
|
@@ -64,7 +64,7 @@ export async function runMigrateIntershell(opts = {}) {
|
|
|
64
64
|
" If you want this shell to participate in the Duct open network, add:\n\n" +
|
|
65
65
|
chalk.cyan(" intershell_enabled: true,\n" +
|
|
66
66
|
" registry_visibility: 'public',\n") +
|
|
67
|
-
"\n to your duct.config.ts, then run `npx duct push`.\n"));
|
|
67
|
+
"\n to your duct.config.ts, then run `npx @duct-sdk/sdk push`.\n"));
|
|
68
68
|
return;
|
|
69
69
|
}
|
|
70
70
|
if (result.hasIntershellEnabled) {
|
|
@@ -74,7 +74,7 @@ export async function runMigrateIntershell(opts = {}) {
|
|
|
74
74
|
return;
|
|
75
75
|
}
|
|
76
76
|
// Needs migration: allowedCallers set, intershell_enabled missing
|
|
77
|
-
console.log(chalk.yellow("
|
|
77
|
+
console.log(chalk.yellow(" ! Migration notice\n\n" +
|
|
78
78
|
" Your config has allowedCallers but intershell_enabled is not set.\n\n" +
|
|
79
79
|
" In the open-network model:\n" +
|
|
80
80
|
" • allowedCallers is an optional restriction.\n" +
|
|
@@ -103,6 +103,6 @@ export async function runMigrateIntershell(opts = {}) {
|
|
|
103
103
|
" // remove allowedCallers (has no effect when intershell_enabled is false)\n" +
|
|
104
104
|
" },\n" +
|
|
105
105
|
" intershell_enabled: false, // already the default; explicit for clarity\n"));
|
|
106
|
-
console.log(chalk.gray(" After updating, run `npx duct push` to sync changes with Duct cloud.\n" +
|
|
106
|
+
console.log(chalk.gray(" After updating, run `npx @duct-sdk/sdk push` to sync changes with Duct cloud.\n" +
|
|
107
107
|
" This command does not modify any files.\n"));
|
|
108
108
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { DuctConfig } from "../core/types.js";
|
|
2
|
+
import type { CapabilitiesFile, PolicyExpectation, PolicyFile, PolicyTestCase, TestsFile } from "../core/project.js";
|
|
3
|
+
type CapabilityLike = Pick<CapabilitiesFile["actions"][number], "id" | "method" | "sideEffects">;
|
|
4
|
+
/**
|
|
5
|
+
* Starting policy: agents may read (with the user's consent). Writes stay off for agents
|
|
6
|
+
* until the developer sets `access: "write"` or allows them, and even then each write
|
|
7
|
+
* waits for a human. Deletes are denied outright, and every action is rate limited.
|
|
8
|
+
*/
|
|
9
|
+
export declare function defaultPolicy(actions: CapabilityLike[]): PolicyFile;
|
|
10
|
+
/**
|
|
11
|
+
* Deny every DELETE action, however many there are. When every action whose id starts
|
|
12
|
+
* with `delete_` is a DELETE, they collapse into one `delete_*` pattern so policy.ts stays
|
|
13
|
+
* short for large APIs; any other DELETE action is listed by id.
|
|
14
|
+
*/
|
|
15
|
+
export declare function defaultDenyPatterns(actions: CapabilityLike[]): string[];
|
|
16
|
+
/** A few readable examples so tests.ts is not empty on day one. */
|
|
17
|
+
export declare function starterTests(actions: CapabilityLike[]): TestsFile;
|
|
18
|
+
export interface GuardrailCase extends PolicyTestCase {
|
|
19
|
+
builtin: true;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Invariants that must hold for any policy. `duct test` always runs these:
|
|
23
|
+
* - no agent write executes without a human (even with user consent)
|
|
24
|
+
* - high/critical actions never run for agents without consent
|
|
25
|
+
* - denied actions are denied
|
|
26
|
+
* - guests cannot trigger side effects
|
|
27
|
+
*/
|
|
28
|
+
export declare function builtinGuardrailCases(config: Pick<DuctConfig, "actions" | "agentPermissions">): GuardrailCase[];
|
|
29
|
+
export declare function expectationMet(expect: PolicyExpectation, decision: "allow" | "deny" | "approval" | "unknown_action"): boolean;
|
|
30
|
+
export interface AccessSummary {
|
|
31
|
+
agentsCanCall: string[];
|
|
32
|
+
needsHuman: string[];
|
|
33
|
+
blocked: string[];
|
|
34
|
+
}
|
|
35
|
+
/** Plain-language summary of what agents can do under a compiled config. */
|
|
36
|
+
export declare function summarizeAgentAccess(config: Pick<DuctConfig, "actions" | "agentPermissions">): AccessSummary;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct-sdk/sdk — Safe defaults for new projects + built-in guardrail checks
|
|
3
|
+
// ============================================================
|
|
4
|
+
const MAX_BUILTIN_CASES_PER_KIND = 25;
|
|
5
|
+
/**
|
|
6
|
+
* Starting policy: agents may read (with the user's consent). Writes stay off for agents
|
|
7
|
+
* until the developer sets `access: "write"` or allows them, and even then each write
|
|
8
|
+
* waits for a human. Deletes are denied outright, and every action is rate limited.
|
|
9
|
+
*/
|
|
10
|
+
export function defaultPolicy(actions) {
|
|
11
|
+
return {
|
|
12
|
+
agents: {
|
|
13
|
+
access: "read",
|
|
14
|
+
deny: defaultDenyPatterns(actions),
|
|
15
|
+
userConsent: true,
|
|
16
|
+
},
|
|
17
|
+
approveWhen: {},
|
|
18
|
+
limits: { "*": { perMinute: 60 } },
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Deny every DELETE action, however many there are. When every action whose id starts
|
|
23
|
+
* with `delete_` is a DELETE, they collapse into one `delete_*` pattern so policy.ts stays
|
|
24
|
+
* short for large APIs; any other DELETE action is listed by id.
|
|
25
|
+
*/
|
|
26
|
+
export function defaultDenyPatterns(actions) {
|
|
27
|
+
const deleteIds = actions.filter((action) => action.method === "DELETE").map((action) => action.id);
|
|
28
|
+
const prefixed = deleteIds.filter((id) => id.startsWith("delete_"));
|
|
29
|
+
const globIsExact = actions
|
|
30
|
+
.filter((action) => action.id.startsWith("delete_"))
|
|
31
|
+
.every((action) => action.method === "DELETE");
|
|
32
|
+
if (prefixed.length > 1 && globIsExact) {
|
|
33
|
+
return ["delete_*", ...deleteIds.filter((id) => !id.startsWith("delete_"))];
|
|
34
|
+
}
|
|
35
|
+
return deleteIds;
|
|
36
|
+
}
|
|
37
|
+
/** A few readable examples so tests.ts is not empty on day one. */
|
|
38
|
+
export function starterTests(actions) {
|
|
39
|
+
const policy = [];
|
|
40
|
+
const read = actions.find((action) => !action.sideEffects);
|
|
41
|
+
const write = actions.find((action) => action.sideEffects && action.method !== "DELETE");
|
|
42
|
+
const remove = actions.find((action) => action.method === "DELETE");
|
|
43
|
+
if (read) {
|
|
44
|
+
policy.push({
|
|
45
|
+
name: `agents can call ${read.id} with the user's consent`,
|
|
46
|
+
as: "agent",
|
|
47
|
+
action: read.id,
|
|
48
|
+
withUserConsent: true,
|
|
49
|
+
expect: "allow",
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
if (write) {
|
|
53
|
+
policy.push({
|
|
54
|
+
name: `agents never run ${write.id} without a human`,
|
|
55
|
+
as: "agent",
|
|
56
|
+
action: write.id,
|
|
57
|
+
withUserConsent: true,
|
|
58
|
+
expect: "blocked",
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (remove) {
|
|
62
|
+
policy.push({
|
|
63
|
+
name: `agents can never call ${remove.id}`,
|
|
64
|
+
as: "agent",
|
|
65
|
+
action: remove.id,
|
|
66
|
+
withUserConsent: true,
|
|
67
|
+
expect: "deny",
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return { policy };
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Invariants that must hold for any policy. `duct test` always runs these:
|
|
74
|
+
* - no agent write executes without a human (even with user consent)
|
|
75
|
+
* - high/critical actions never run for agents without consent
|
|
76
|
+
* - denied actions are denied
|
|
77
|
+
* - guests cannot trigger side effects
|
|
78
|
+
*/
|
|
79
|
+
export function builtinGuardrailCases(config) {
|
|
80
|
+
const cases = [];
|
|
81
|
+
const actions = config.actions ?? [];
|
|
82
|
+
const overrides = config.agentPermissions?.actionOverrides ?? {};
|
|
83
|
+
const add = (name, action, as, expect, withUserConsent) => cases.push({ builtin: true, name, action, as, expect, withUserConsent });
|
|
84
|
+
for (const action of actions.filter((a) => a.sideEffects).slice(0, MAX_BUILTIN_CASES_PER_KIND)) {
|
|
85
|
+
add(`agent writes need a human: ${action.id}`, action.id, "agent", "blocked", true);
|
|
86
|
+
}
|
|
87
|
+
for (const action of actions
|
|
88
|
+
.filter((a) => a.sensitivityLevel === "high" || a.sensitivityLevel === "critical")
|
|
89
|
+
.slice(0, MAX_BUILTIN_CASES_PER_KIND)) {
|
|
90
|
+
add(`sensitive actions need consent: ${action.id}`, action.id, "agent", "blocked", false);
|
|
91
|
+
}
|
|
92
|
+
for (const [actionId, level] of Object.entries(overrides).slice(0, MAX_BUILTIN_CASES_PER_KIND)) {
|
|
93
|
+
if (level === "none" && actions.some((a) => a.id === actionId)) {
|
|
94
|
+
add(`denied for agents: ${actionId}`, actionId, "agent", "deny", true);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const firstWrite = actions.find((a) => a.sideEffects);
|
|
98
|
+
if (firstWrite)
|
|
99
|
+
add(`guests cannot write: ${firstWrite.id}`, firstWrite.id, "guest", "deny", false);
|
|
100
|
+
return cases;
|
|
101
|
+
}
|
|
102
|
+
export function expectationMet(expect, decision) {
|
|
103
|
+
if (decision === "unknown_action")
|
|
104
|
+
return false;
|
|
105
|
+
if (expect === "blocked")
|
|
106
|
+
return decision === "deny" || decision === "approval";
|
|
107
|
+
return expect === decision;
|
|
108
|
+
}
|
|
109
|
+
/** Plain-language summary of what agents can do under a compiled config. */
|
|
110
|
+
export function summarizeAgentAccess(config) {
|
|
111
|
+
const summary = { agentsCanCall: [], needsHuman: [], blocked: [] };
|
|
112
|
+
const permissions = config.agentPermissions;
|
|
113
|
+
for (const action of config.actions ?? []) {
|
|
114
|
+
const level = permissions?.actionOverrides?.[action.id] ?? permissions?.defaultLevel ?? "none";
|
|
115
|
+
const levelAllows = level !== "none" && !(level === "read" && action.sideEffects);
|
|
116
|
+
if (!action.agentAccessible || !levelAllows) {
|
|
117
|
+
summary.blocked.push(action.id);
|
|
118
|
+
}
|
|
119
|
+
else if (action.sideEffects || action.approveIf) {
|
|
120
|
+
summary.needsHuman.push(action.id);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
summary.agentsCanCall.push(action.id);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return summary;
|
|
127
|
+
}
|