@duct-sdk/sdk 0.3.6 → 0.3.9
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 +19 -0
- package/dist/adapters/react/shell.js +90 -43
- package/dist/cli/agents/pipeline.d.ts +5 -0
- package/dist/cli/agents/pipeline.js +60 -2
- package/dist/cli/generators/config.js +13 -2
- package/dist/cli/index.js +22 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +14 -1
- package/dist/cli/migrate-intershell.d.ts +3 -0
- package/dist/cli/migrate-intershell.js +108 -0
- package/dist/cli/processors/curl-parser.d.ts +21 -0
- package/dist/cli/processors/curl-parser.js +186 -0
- package/dist/cli/processors/openapi-parser.js +58 -14
- package/dist/cli/prompts/review.d.ts +4 -0
- package/dist/cli/prompts/review.js +50 -0
- package/dist/core/auth-boundaries.d.ts +13 -0
- package/dist/core/auth-boundaries.js +51 -0
- package/dist/core/config.d.ts +6 -0
- package/dist/core/config.js +2 -0
- package/dist/core/intershell.d.ts +31 -0
- package/dist/core/intershell.js +69 -0
- package/dist/core/types.d.ts +28 -1
- package/dist/core/types.js +15 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Deterministic cURL / Postman collection parser
|
|
3
|
+
// ============================================================
|
|
4
|
+
function toSnakeCase(str) {
|
|
5
|
+
return str
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/[^a-z0-9]/g, "_")
|
|
8
|
+
.replace(/_+/g, "_")
|
|
9
|
+
.replace(/^_|_$/g, "");
|
|
10
|
+
}
|
|
11
|
+
function pathFromUrl(rawUrl) {
|
|
12
|
+
try {
|
|
13
|
+
const normalized = rawUrl.replace(/\\'/g, "'").replace(/\\"/g, '"');
|
|
14
|
+
const url = new URL(normalized.startsWith("http") ? normalized : `https://${normalized}`);
|
|
15
|
+
return { path: url.pathname || "/", host: url.host };
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function deriveActionId(method, path, name, used) {
|
|
22
|
+
const base = toSnakeCase(name?.trim() || `${method}_${path}`);
|
|
23
|
+
let id = base || "request";
|
|
24
|
+
let n = 2;
|
|
25
|
+
while (used.has(id)) {
|
|
26
|
+
id = `${base}_${n}`;
|
|
27
|
+
n += 1;
|
|
28
|
+
}
|
|
29
|
+
used.add(id);
|
|
30
|
+
return id;
|
|
31
|
+
}
|
|
32
|
+
/** Parse one curl command line (may span continuation with \\). */
|
|
33
|
+
export function parseCurlCommand(raw) {
|
|
34
|
+
const line = raw.replace(/\s\\\s*\n/g, " ").trim();
|
|
35
|
+
if (!/^curl\b/i.test(line))
|
|
36
|
+
return null;
|
|
37
|
+
const methodMatch = line.match(/(?:^|\s)-X\s+([A-Z]+)/i);
|
|
38
|
+
const method = (methodMatch?.[1] ?? "GET").toUpperCase();
|
|
39
|
+
const urlMatch = line.match(/(?:^|\s)(?:'([^']+)'|"([^"]+)"|(https?:\/\/[^\s'"]+))/i);
|
|
40
|
+
const url = urlMatch?.[1] ?? urlMatch?.[2] ?? urlMatch?.[3];
|
|
41
|
+
if (!url)
|
|
42
|
+
return null;
|
|
43
|
+
const parsed = pathFromUrl(url);
|
|
44
|
+
if (!parsed)
|
|
45
|
+
return null;
|
|
46
|
+
let body;
|
|
47
|
+
const dataMatch = line.match(/(?:^|\s)(?:-d|--data(?:-raw|-binary)?)\s+('([^']*)'|"([^"]*)"|(\S+))/i);
|
|
48
|
+
const dataRaw = dataMatch?.[2] ?? dataMatch?.[3] ?? dataMatch?.[4];
|
|
49
|
+
if (dataRaw) {
|
|
50
|
+
try {
|
|
51
|
+
const parsedBody = JSON.parse(dataRaw);
|
|
52
|
+
if (typeof parsedBody === "object" && parsedBody !== null && !Array.isArray(parsedBody)) {
|
|
53
|
+
body = parsedBody;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// non-JSON body — skip schema inference
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
method,
|
|
62
|
+
path: parsed.path,
|
|
63
|
+
url,
|
|
64
|
+
body,
|
|
65
|
+
name: `${method} ${parsed.path}`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function parseShellCurls(content) {
|
|
69
|
+
const chunks = content.split(/\n(?=curl\b)/i);
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const chunk of chunks) {
|
|
72
|
+
const req = parseCurlCommand(chunk.trim());
|
|
73
|
+
if (req)
|
|
74
|
+
out.push(req);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
function parsePostmanCollection(content) {
|
|
79
|
+
let json;
|
|
80
|
+
try {
|
|
81
|
+
json = JSON.parse(content);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
const out = [];
|
|
87
|
+
const walk = (items) => {
|
|
88
|
+
if (!Array.isArray(items))
|
|
89
|
+
return;
|
|
90
|
+
for (const item of items) {
|
|
91
|
+
if (typeof item !== "object" || item === null)
|
|
92
|
+
continue;
|
|
93
|
+
const obj = item;
|
|
94
|
+
if (Array.isArray(obj.item)) {
|
|
95
|
+
walk(obj.item);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const request = obj.request;
|
|
99
|
+
if (!request)
|
|
100
|
+
continue;
|
|
101
|
+
const method = String(request.method ?? "GET").toUpperCase();
|
|
102
|
+
const urlRaw = request.url;
|
|
103
|
+
let urlStr = "";
|
|
104
|
+
if (typeof urlRaw === "string")
|
|
105
|
+
urlStr = urlRaw;
|
|
106
|
+
else if (typeof urlRaw === "object" && urlRaw !== null) {
|
|
107
|
+
const u = urlRaw;
|
|
108
|
+
if (typeof u.raw === "string")
|
|
109
|
+
urlStr = u.raw;
|
|
110
|
+
else if (Array.isArray(u.path)) {
|
|
111
|
+
urlStr = `https://example.com/${u.path.join("/")}`;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const parsed = pathFromUrl(urlStr);
|
|
115
|
+
if (!parsed)
|
|
116
|
+
continue;
|
|
117
|
+
out.push({
|
|
118
|
+
method,
|
|
119
|
+
path: parsed.path,
|
|
120
|
+
url: urlStr,
|
|
121
|
+
name: typeof obj.name === "string" ? obj.name : `${method} ${parsed.path}`,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
walk(json.item);
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
function requestsToManifests(requests, sourceLabel) {
|
|
129
|
+
const used = new Set();
|
|
130
|
+
const actions = [];
|
|
131
|
+
const routes = [];
|
|
132
|
+
for (const req of requests) {
|
|
133
|
+
const id = deriveActionId(req.method, req.path, req.name, used);
|
|
134
|
+
const sideEffects = ["POST", "PUT", "PATCH", "DELETE"].includes(req.method);
|
|
135
|
+
actions.push({
|
|
136
|
+
id,
|
|
137
|
+
name: req.name ?? id,
|
|
138
|
+
description: `${req.method} ${req.path} (imported from ${sourceLabel})`,
|
|
139
|
+
method: req.method,
|
|
140
|
+
path: req.path,
|
|
141
|
+
agentAccessible: false,
|
|
142
|
+
sideEffects,
|
|
143
|
+
sensitivityLevel: "low",
|
|
144
|
+
params: [],
|
|
145
|
+
inputSchema: req.body ? { type: "object", properties: Object.fromEntries(Object.keys(req.body).map((k) => [k, { type: typeof req.body[k] }])) } : undefined,
|
|
146
|
+
requiresAuth: false,
|
|
147
|
+
confidence: 0.9,
|
|
148
|
+
evidence: [sourceLabel],
|
|
149
|
+
});
|
|
150
|
+
if (req.method === "GET") {
|
|
151
|
+
routes.push({
|
|
152
|
+
path: req.path,
|
|
153
|
+
name: req.name ?? id,
|
|
154
|
+
description: `${req.method} ${req.path}`,
|
|
155
|
+
params: [],
|
|
156
|
+
queryParams: [],
|
|
157
|
+
uiStateHint: "list",
|
|
158
|
+
requiresAuth: false,
|
|
159
|
+
deeplinkable: false,
|
|
160
|
+
confidence: 0.9,
|
|
161
|
+
evidence: [sourceLabel],
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { actions, routes, requestCount: requests.length, sourceLabel };
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Parse a `.sh` curl script, raw curl text, or Postman Collection v2.1 JSON.
|
|
169
|
+
*/
|
|
170
|
+
export async function parseCurlCollection(content, filePath = "curl-collection.sh") {
|
|
171
|
+
const trimmed = content.trim();
|
|
172
|
+
const lower = filePath.toLowerCase();
|
|
173
|
+
let requests = [];
|
|
174
|
+
if (lower.endsWith(".json") && trimmed.startsWith("{")) {
|
|
175
|
+
requests = parsePostmanCollection(trimmed);
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
requests = parseShellCurls(trimmed);
|
|
179
|
+
if (requests.length === 0 && trimmed.includes("curl")) {
|
|
180
|
+
const single = parseCurlCommand(trimmed);
|
|
181
|
+
if (single)
|
|
182
|
+
requests = [single];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return requestsToManifests(requests, filePath);
|
|
186
|
+
}
|
|
@@ -22,15 +22,56 @@ function toSnakeCase(str) {
|
|
|
22
22
|
.replace(/_+/g, "_")
|
|
23
23
|
.replace(/^_|_$/g, "");
|
|
24
24
|
}
|
|
25
|
-
function deriveActionId(operationId, method, path) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
25
|
+
function deriveActionId(operationId, method, path, tags, usedIds) {
|
|
26
|
+
let base;
|
|
27
|
+
if (operationId?.trim()) {
|
|
28
|
+
base = toSnakeCase(operationId.trim());
|
|
29
|
+
}
|
|
30
|
+
else if (tags?.length) {
|
|
31
|
+
const pathPart = path
|
|
32
|
+
.replace(/\{([^}]+)\}/g, (_, name) => name)
|
|
33
|
+
.replace(/[^a-zA-Z0-9]+/g, "_")
|
|
34
|
+
.replace(/^_|_$/g, "");
|
|
35
|
+
base = toSnakeCase(`${tags[0]}_${method}_${pathPart}`);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const pathPart = path
|
|
39
|
+
.replace(/\{([^}]+)\}/g, (_, name) => name)
|
|
40
|
+
.replace(/[^a-zA-Z0-9]+/g, "_")
|
|
41
|
+
.replace(/^_|_$/g, "");
|
|
42
|
+
base = toSnakeCase(`${method}_${pathPart}`);
|
|
43
|
+
}
|
|
44
|
+
if (!usedIds)
|
|
45
|
+
return base;
|
|
46
|
+
let id = base || "operation";
|
|
47
|
+
let n = 2;
|
|
48
|
+
while (usedIds.has(id)) {
|
|
49
|
+
id = `${base}_${n}`;
|
|
50
|
+
n += 1;
|
|
51
|
+
}
|
|
52
|
+
usedIds.add(id);
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
function resolveRef(ref, spec) {
|
|
56
|
+
if (!ref.startsWith("#/"))
|
|
57
|
+
return undefined;
|
|
58
|
+
const parts = ref.slice(2).split("/");
|
|
59
|
+
let node = spec;
|
|
60
|
+
for (const part of parts) {
|
|
61
|
+
if (typeof node !== "object" || node === null)
|
|
62
|
+
return undefined;
|
|
63
|
+
node = node[part];
|
|
64
|
+
}
|
|
65
|
+
return typeof node === "object" && node !== null ? node : undefined;
|
|
66
|
+
}
|
|
67
|
+
function dereferenceSchema(schema, spec, depth = 0) {
|
|
68
|
+
if (!schema || depth > 8)
|
|
69
|
+
return schema;
|
|
70
|
+
if (schema.$ref) {
|
|
71
|
+
const resolved = resolveRef(schema.$ref, spec);
|
|
72
|
+
return resolved ? dereferenceSchema(resolved, spec, depth + 1) : undefined;
|
|
73
|
+
}
|
|
74
|
+
return schema;
|
|
34
75
|
}
|
|
35
76
|
function inferSensitivityLevel(path, description, xDuctSensitivity) {
|
|
36
77
|
if (xDuctSensitivity && VALID_SENSITIVITY_LEVELS.has(xDuctSensitivity)) {
|
|
@@ -96,7 +137,7 @@ function operationHasSecurityRequirement(operation, spec) {
|
|
|
96
137
|
Object.keys(spec.securityDefinitions).length > 0);
|
|
97
138
|
return hasGlobalSchemes;
|
|
98
139
|
}
|
|
99
|
-
function extractParams(parameters, requestBody) {
|
|
140
|
+
function extractParams(parameters, requestBody, spec) {
|
|
100
141
|
const params = [];
|
|
101
142
|
let inputSchema;
|
|
102
143
|
for (const param of parameters) {
|
|
@@ -130,7 +171,9 @@ function extractParams(parameters, requestBody) {
|
|
|
130
171
|
// OpenAPI 3.x requestBody
|
|
131
172
|
if (requestBody?.content) {
|
|
132
173
|
const jsonContent = requestBody.content["application/json"];
|
|
133
|
-
const schema =
|
|
174
|
+
const schema = spec
|
|
175
|
+
? dereferenceSchema(jsonContent?.schema, spec)
|
|
176
|
+
: jsonContent?.schema;
|
|
134
177
|
if (schema) {
|
|
135
178
|
inputSchema = schema;
|
|
136
179
|
if (schema.properties) {
|
|
@@ -212,6 +255,7 @@ export async function parseOpenApiSpec(content, filePath = "openapi.json") {
|
|
|
212
255
|
const actions = [];
|
|
213
256
|
const routes = [];
|
|
214
257
|
const seen = new Set(); // deduplicate by METHOD:path
|
|
258
|
+
const usedActionIds = new Set();
|
|
215
259
|
let operationCount = 0;
|
|
216
260
|
const paths = (spec.paths ?? {});
|
|
217
261
|
for (const [rawPath, pathItem] of Object.entries(paths)) {
|
|
@@ -247,10 +291,10 @@ export async function parseOpenApiSpec(content, filePath = "openapi.json") {
|
|
|
247
291
|
const description = operation.summary ??
|
|
248
292
|
operation.description ??
|
|
249
293
|
`${upperMethod} ${normalizedPath}`;
|
|
250
|
-
const { params, inputSchema } = extractParams(mergedParams, operation.requestBody);
|
|
251
|
-
const id = deriveActionId(operation.operationId, method, normalizedPath);
|
|
294
|
+
const { params, inputSchema } = extractParams(mergedParams, operation.requestBody, spec);
|
|
295
|
+
const id = deriveActionId(operation.operationId, method, normalizedPath, operation.tags, usedActionIds);
|
|
252
296
|
const sideEffects = SIDE_EFFECT_METHODS.has(upperMethod);
|
|
253
|
-
const confidence = operation.operationId?.trim() ? 1.0 : 0.
|
|
297
|
+
const confidence = operation.operationId?.trim() ? 1.0 : 0.85;
|
|
254
298
|
const sensitivityLevel = inferSensitivityLevel(normalizedPath, description, operation["x-duct-sensitivity"]);
|
|
255
299
|
const requiresAuth = operationHasSecurityRequirement(operation, spec);
|
|
256
300
|
const dedupeKey = `${upperMethod}:${normalizedPath}`;
|
|
@@ -17,6 +17,10 @@ export interface ReviewedPipelineResult {
|
|
|
17
17
|
rejectedActions: ActionManifest[];
|
|
18
18
|
/** Decisions written to duct-review.json (noInteractive mode) */
|
|
19
19
|
reviewFilePath?: string;
|
|
20
|
+
/** Whether this shell should accept cross-shell calls (default false) */
|
|
21
|
+
intershell_enabled?: boolean;
|
|
22
|
+
/** Whether this shell should be discoverable in the Duct network (default 'private') */
|
|
23
|
+
registry_visibility?: 'public' | 'private';
|
|
20
24
|
}
|
|
21
25
|
/**
|
|
22
26
|
* Interactive Review CLI.
|
|
@@ -79,6 +79,19 @@ async function promptActionDecision(action, rl) {
|
|
|
79
79
|
});
|
|
80
80
|
});
|
|
81
81
|
}
|
|
82
|
+
async function promptYesNo(question, rl, defaultYes = false) {
|
|
83
|
+
const hint = defaultYes ? "[Y/n]" : "[y/N]";
|
|
84
|
+
process.stdout.write(`\n ${chalk.bold("[DUCT]")} ${question} ${chalk.gray(hint + ": ")}`);
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
rl.once("line", (answer) => {
|
|
87
|
+
const trimmed = answer.trim().toLowerCase();
|
|
88
|
+
if (trimmed === "")
|
|
89
|
+
resolve(defaultYes);
|
|
90
|
+
else
|
|
91
|
+
resolve(trimmed === "y" || trimmed === "yes");
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
}
|
|
82
95
|
async function handleExplain(action) {
|
|
83
96
|
process.stdout.write(chalk.gray(`\n What does "${action.id}" do?\n` +
|
|
84
97
|
` ${action.description}\n\n` +
|
|
@@ -121,6 +134,8 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
|
|
|
121
134
|
auth: pipelineResult.auth,
|
|
122
135
|
deeplinks: pipelineResult.deeplinks,
|
|
123
136
|
rejectedActions: [],
|
|
137
|
+
intershell_enabled: false,
|
|
138
|
+
registry_visibility: 'private',
|
|
124
139
|
};
|
|
125
140
|
}
|
|
126
141
|
// ---- --no-interactive mode: auto-approve where possible, collect rest ----
|
|
@@ -161,6 +176,8 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
|
|
|
161
176
|
deeplinks: pipelineResult.deeplinks,
|
|
162
177
|
rejectedActions,
|
|
163
178
|
reviewFilePath,
|
|
179
|
+
intershell_enabled: false,
|
|
180
|
+
registry_visibility: 'private',
|
|
164
181
|
};
|
|
165
182
|
}
|
|
166
183
|
// ---- Interactive mode ----
|
|
@@ -178,6 +195,8 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
|
|
|
178
195
|
auth: pipelineResult.auth,
|
|
179
196
|
deeplinks: pipelineResult.deeplinks,
|
|
180
197
|
rejectedActions: [],
|
|
198
|
+
intershell_enabled: false,
|
|
199
|
+
registry_visibility: 'private',
|
|
181
200
|
};
|
|
182
201
|
}
|
|
183
202
|
// Show auto-approved summary
|
|
@@ -229,6 +248,35 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
|
|
|
229
248
|
console.log(chalk.gray(` — ${action.id} — not marked agent-accessible`));
|
|
230
249
|
}
|
|
231
250
|
}
|
|
251
|
+
// ---- Intershell network exposure prompt ----
|
|
252
|
+
let intershell_enabled = false;
|
|
253
|
+
let registry_visibility = 'private';
|
|
254
|
+
const exposeToNetwork = await promptYesNo("Expose this shell to the Duct network (allow other shells to discover and call it)?", rl);
|
|
255
|
+
if (exposeToNetwork) {
|
|
256
|
+
intershell_enabled = true;
|
|
257
|
+
registry_visibility = 'public';
|
|
258
|
+
// Ask which already-approved actions should be discoverable cross-shell.
|
|
259
|
+
const agentActions = approvedActions.filter((a) => a.agentAccessible);
|
|
260
|
+
if (agentActions.length > 0) {
|
|
261
|
+
console.log(chalk.bold(`\n Which actions should be discoverable cross-shell?\n` +
|
|
262
|
+
chalk.gray(" This makes the action visible in the Duct capability network.\n" +
|
|
263
|
+
" Only agent-accessible actions are shown. y = include N = exclude\n")));
|
|
264
|
+
for (const action of agentActions) {
|
|
265
|
+
process.stdout.write(`\n ${chalk.bold("[DUCT]")} ${methodColor(action.method)} ${chalk.cyan(action.path)} — ${chalk.gray(action.description.slice(0, 80))}\n` +
|
|
266
|
+
` ${chalk.gray(`Include '${action.id}' in cross-shell capability network? [y/N]: `)}`);
|
|
267
|
+
const answer = await new Promise((resolve) => {
|
|
268
|
+
rl.once("line", (line) => resolve(line.trim().toLowerCase()));
|
|
269
|
+
});
|
|
270
|
+
if (answer !== "y" && answer !== "yes") {
|
|
271
|
+
// Mark as not agent-accessible in the final output
|
|
272
|
+
const idx = approvedActions.findIndex((a) => a.id === action.id);
|
|
273
|
+
if (idx !== -1) {
|
|
274
|
+
approvedActions[idx] = { ...approvedActions[idx], agentAccessible: false };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
232
280
|
rl.close();
|
|
233
281
|
const agentAccessibleCount = approvedActions.filter((a) => a.agentAccessible).length;
|
|
234
282
|
console.log(chalk.bold(`\n Review complete: ${agentAccessibleCount}/${pipelineResult.actions.length} actions marked agent-accessible\n`));
|
|
@@ -238,6 +286,8 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
|
|
|
238
286
|
auth: pipelineResult.auth,
|
|
239
287
|
deeplinks: pipelineResult.deeplinks,
|
|
240
288
|
rejectedActions,
|
|
289
|
+
intershell_enabled,
|
|
290
|
+
registry_visibility,
|
|
241
291
|
};
|
|
242
292
|
}
|
|
243
293
|
/**
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ActionManifest } from "./types.js";
|
|
2
|
+
export interface ActionDefinitionGrant {
|
|
3
|
+
actionId: string;
|
|
4
|
+
definitionHash: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function computeActionDefinitionFingerprint(action: Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel">): string;
|
|
7
|
+
export declare function buildActionDefinitionGrants(actionIds: string[], actionsById: Record<string, Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel">>): ActionDefinitionGrant[];
|
|
8
|
+
export type ActionRiskTier = "read" | "write" | "delete";
|
|
9
|
+
export declare function classifyActionRiskTier(action: Pick<ActionManifest, "method" | "sideEffects">): ActionRiskTier;
|
|
10
|
+
export declare function checkAgentScope(scopes: string[], action: Pick<ActionManifest, "id" | "method" | "path" | "sideEffects" | "sensitivityLevel">, params?: Record<string, unknown>): {
|
|
11
|
+
allowed: boolean;
|
|
12
|
+
error?: string;
|
|
13
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
export function computeActionDefinitionFingerprint(action) {
|
|
3
|
+
const canonical = JSON.stringify({
|
|
4
|
+
method: (action.method ?? "GET").toUpperCase(),
|
|
5
|
+
path: action.path ?? "",
|
|
6
|
+
sideEffects: Boolean(action.sideEffects),
|
|
7
|
+
sensitivityLevel: action.sensitivityLevel ?? "low",
|
|
8
|
+
});
|
|
9
|
+
return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
|
|
10
|
+
}
|
|
11
|
+
export function buildActionDefinitionGrants(actionIds, actionsById) {
|
|
12
|
+
return actionIds.map((actionId) => ({
|
|
13
|
+
actionId,
|
|
14
|
+
definitionHash: computeActionDefinitionFingerprint(actionsById[actionId] ?? { method: "GET", path: "/", sideEffects: false, sensitivityLevel: "low" }),
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
17
|
+
export function classifyActionRiskTier(action) {
|
|
18
|
+
const method = (action.method ?? "GET").toUpperCase();
|
|
19
|
+
if (method === "DELETE")
|
|
20
|
+
return "delete";
|
|
21
|
+
if (action.sideEffects || ["POST", "PUT", "PATCH"].includes(method))
|
|
22
|
+
return "write";
|
|
23
|
+
return "read";
|
|
24
|
+
}
|
|
25
|
+
export function checkAgentScope(scopes, action, params = {}) {
|
|
26
|
+
if (scopes.includes("*"))
|
|
27
|
+
return { allowed: true };
|
|
28
|
+
const tier = classifyActionRiskTier(action);
|
|
29
|
+
if (scopes.includes(action.id))
|
|
30
|
+
return { allowed: true };
|
|
31
|
+
if (tier === "read") {
|
|
32
|
+
if (scopes.includes("read:*") || scopes.includes(`read:${action.id}`)) {
|
|
33
|
+
return { allowed: true };
|
|
34
|
+
}
|
|
35
|
+
return { allowed: false, error: "read_not_in_agent_scope" };
|
|
36
|
+
}
|
|
37
|
+
if (tier === "write") {
|
|
38
|
+
if (scopes.includes(`write:${action.id}`))
|
|
39
|
+
return { allowed: true };
|
|
40
|
+
return { allowed: false, error: "write_not_in_agent_scope" };
|
|
41
|
+
}
|
|
42
|
+
for (const key of ["id", "recordId", "record_id"]) {
|
|
43
|
+
const val = params[key];
|
|
44
|
+
if (val != null && scopes.includes(`delete:${action.id}:${String(val)}`)) {
|
|
45
|
+
return { allowed: true };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (scopes.includes(`delete:${action.id}`))
|
|
49
|
+
return { allowed: true };
|
|
50
|
+
return { allowed: false, error: "delete_not_in_agent_scope" };
|
|
51
|
+
}
|
package/dist/core/config.d.ts
CHANGED
|
@@ -322,6 +322,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
|
|
|
322
322
|
logoUrl?: string | undefined;
|
|
323
323
|
customCSS?: string | undefined;
|
|
324
324
|
}>>;
|
|
325
|
+
registry_visibility: z.ZodDefault<z.ZodOptional<z.ZodEnum<["public", "private"]>>>;
|
|
326
|
+
intershell_enabled: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
325
327
|
}, "strip", z.ZodTypeAny, {
|
|
326
328
|
auth: {
|
|
327
329
|
strategy: "none" | "nextauth" | "clerk" | "auth0" | "custom-jwt" | "session-cookie" | "unknown";
|
|
@@ -405,6 +407,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
|
|
|
405
407
|
allowedCallers?: string[] | undefined;
|
|
406
408
|
allowedActions?: string[] | undefined;
|
|
407
409
|
};
|
|
410
|
+
registry_visibility: "public" | "private";
|
|
411
|
+
intershell_enabled: boolean;
|
|
408
412
|
widget?: {
|
|
409
413
|
primaryColor?: string | undefined;
|
|
410
414
|
position?: "bottom-right" | "bottom-left" | "top-right" | "top-left" | undefined;
|
|
@@ -518,6 +522,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
|
|
|
518
522
|
logoUrl?: string | undefined;
|
|
519
523
|
customCSS?: string | undefined;
|
|
520
524
|
} | undefined;
|
|
525
|
+
registry_visibility?: "public" | "private" | undefined;
|
|
526
|
+
intershell_enabled?: boolean | undefined;
|
|
521
527
|
}>;
|
|
522
528
|
export type ValidatedDuctConfig = z.infer<typeof DuctConfigSchema>;
|
|
523
529
|
/**
|
package/dist/core/config.js
CHANGED
|
@@ -162,6 +162,8 @@ export const DuctConfigSchema = z.object({
|
|
|
162
162
|
deeplinks: z.array(DeeplinkDefinitionSchema).default([]),
|
|
163
163
|
agentPermissions: AgentPermissionsSchema,
|
|
164
164
|
widget: WidgetConfigSchema.optional(),
|
|
165
|
+
registry_visibility: z.enum(['public', 'private']).optional().default('private'),
|
|
166
|
+
intershell_enabled: z.boolean().optional().default(false),
|
|
165
167
|
});
|
|
166
168
|
/**
|
|
167
169
|
* Define and validate a Duct configuration.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface IntershellMessage {
|
|
2
|
+
duct_version: '1';
|
|
3
|
+
message_id: string;
|
|
4
|
+
from_shell: string;
|
|
5
|
+
to_shell: string;
|
|
6
|
+
type: 'action_request' | 'query_request' | 'consent_request' | 'context_push';
|
|
7
|
+
payload: Record<string, unknown>;
|
|
8
|
+
auth: {
|
|
9
|
+
shell_token: string;
|
|
10
|
+
user_consent_token?: string;
|
|
11
|
+
};
|
|
12
|
+
timestamp: string;
|
|
13
|
+
}
|
|
14
|
+
export interface IntershellClientOptions {
|
|
15
|
+
agentProxyUrl: string;
|
|
16
|
+
shellToken: string;
|
|
17
|
+
fromShell: string;
|
|
18
|
+
}
|
|
19
|
+
export interface IntershellActionResult {
|
|
20
|
+
ok: boolean;
|
|
21
|
+
status: number;
|
|
22
|
+
data: unknown;
|
|
23
|
+
consent_required?: boolean;
|
|
24
|
+
approval_url?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Send a cross-shell action request. Handles consent_required responses.
|
|
28
|
+
*/
|
|
29
|
+
export declare function sendIntershellAction(opts: IntershellClientOptions, toShell: string, actionId: string, params?: Record<string, unknown>, userConsentToken?: string): Promise<IntershellActionResult>;
|
|
30
|
+
/** Send a natural-language query to another shell. */
|
|
31
|
+
export declare function sendIntershellQuery(opts: IntershellClientOptions, toShell: string, query: string): Promise<IntershellActionResult>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// IS-29: Thin client for cross-shell messaging via the Duct gateway API
|
|
2
|
+
/**
|
|
3
|
+
* Send a cross-shell action request. Handles consent_required responses.
|
|
4
|
+
*/
|
|
5
|
+
export async function sendIntershellAction(opts, toShell, actionId, params = {}, userConsentToken) {
|
|
6
|
+
const body = {
|
|
7
|
+
duct_version: '1',
|
|
8
|
+
message_id: `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
9
|
+
from_shell: opts.fromShell,
|
|
10
|
+
to_shell: toShell,
|
|
11
|
+
type: 'action_request',
|
|
12
|
+
payload: { action_id: actionId, params },
|
|
13
|
+
auth: {
|
|
14
|
+
shell_token: opts.shellToken,
|
|
15
|
+
...(userConsentToken ? { user_consent_token: userConsentToken } : {}),
|
|
16
|
+
},
|
|
17
|
+
timestamp: new Date().toISOString(),
|
|
18
|
+
};
|
|
19
|
+
const res = await fetch(`${opts.agentProxyUrl}/v1/intershell/message`, {
|
|
20
|
+
method: 'POST',
|
|
21
|
+
headers: { 'Content-Type': 'application/json' },
|
|
22
|
+
body: JSON.stringify(body),
|
|
23
|
+
});
|
|
24
|
+
const data = await res.json().catch(() => ({}));
|
|
25
|
+
const payload = data.payload;
|
|
26
|
+
if (res.status === 403 && payload?.error === 'user_consent_required') {
|
|
27
|
+
const consentRes = await fetch(`${opts.agentProxyUrl}/v1/intershell/message`, {
|
|
28
|
+
method: 'POST',
|
|
29
|
+
headers: { 'Content-Type': 'application/json' },
|
|
30
|
+
body: JSON.stringify({
|
|
31
|
+
...body,
|
|
32
|
+
message_id: `msg_${Date.now()}_consent`,
|
|
33
|
+
type: 'consent_request',
|
|
34
|
+
payload: { action_id: actionId, callback_url: 'http://localhost:3000/callback' },
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
const consentData = await consentRes.json().catch(() => ({}));
|
|
38
|
+
const consentPayload = consentData.payload;
|
|
39
|
+
return {
|
|
40
|
+
ok: false,
|
|
41
|
+
status: consentRes.status,
|
|
42
|
+
data: consentData,
|
|
43
|
+
consent_required: true,
|
|
44
|
+
approval_url: typeof consentPayload?.approval_url === 'string'
|
|
45
|
+
? consentPayload.approval_url
|
|
46
|
+
: undefined,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
return { ok: res.ok, status: res.status, data };
|
|
50
|
+
}
|
|
51
|
+
/** Send a natural-language query to another shell. */
|
|
52
|
+
export async function sendIntershellQuery(opts, toShell, query) {
|
|
53
|
+
const body = {
|
|
54
|
+
duct_version: '1',
|
|
55
|
+
message_id: `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
56
|
+
from_shell: opts.fromShell,
|
|
57
|
+
to_shell: toShell,
|
|
58
|
+
type: 'query_request',
|
|
59
|
+
payload: { query },
|
|
60
|
+
auth: { shell_token: opts.shellToken },
|
|
61
|
+
timestamp: new Date().toISOString(),
|
|
62
|
+
};
|
|
63
|
+
const res = await fetch(`${opts.agentProxyUrl}/v1/intershell/message`, {
|
|
64
|
+
method: 'POST',
|
|
65
|
+
headers: { 'Content-Type': 'application/json' },
|
|
66
|
+
body: JSON.stringify(body),
|
|
67
|
+
});
|
|
68
|
+
return { ok: res.ok, status: res.status, data: await res.json().catch(() => ({})) };
|
|
69
|
+
}
|
package/dist/core/types.d.ts
CHANGED
|
@@ -185,7 +185,13 @@ export interface AgentPermissions {
|
|
|
185
185
|
defaultLevel: AgentPermissionLevel;
|
|
186
186
|
/** Per-action overrides */
|
|
187
187
|
actionOverrides?: Record<string, AgentPermissionLevel>;
|
|
188
|
-
/**
|
|
188
|
+
/**
|
|
189
|
+
* Optional restriction: if set (non-empty), only the listed shell IDs can call this shell cross-shell.
|
|
190
|
+
* If absent or empty, any public Duct shell may call (subject to intershell_enabled + registry_visibility).
|
|
191
|
+
*
|
|
192
|
+
* NOTE: This field is an optional restriction, not a required allow-list.
|
|
193
|
+
* To close this shell to cross-shell calls entirely, set intershell_enabled: false.
|
|
194
|
+
*/
|
|
189
195
|
allowedCallers?: string[];
|
|
190
196
|
/** Whether to require explicit user consent for agent actions */
|
|
191
197
|
requireUserConsent: boolean;
|
|
@@ -205,6 +211,23 @@ export declare const SHELL_PRESET_DIMENSIONS: Record<ShellPreset, {
|
|
|
205
211
|
height: number;
|
|
206
212
|
}>;
|
|
207
213
|
export declare const DEFAULT_SHELL_PRESET: ShellPreset;
|
|
214
|
+
/** Viewport margins applied to the opened shell panel (matches DuctShell CSS). */
|
|
215
|
+
export declare const SHELL_PANEL_VIEWPORT_INSETS: {
|
|
216
|
+
readonly width: 32;
|
|
217
|
+
readonly height: 96;
|
|
218
|
+
};
|
|
219
|
+
export type ShellPanelViewportInsets = typeof SHELL_PANEL_VIEWPORT_INSETS;
|
|
220
|
+
/**
|
|
221
|
+
* Cap requested panel dimensions so tall/large presets fit inside a viewport
|
|
222
|
+
* (or bounded preview stage) without clipping below the fold.
|
|
223
|
+
*/
|
|
224
|
+
export declare function fitShellPanelDimensions(width: number, height: number, viewportWidth: number, viewportHeight: number, insets?: {
|
|
225
|
+
width: number;
|
|
226
|
+
height: number;
|
|
227
|
+
}): {
|
|
228
|
+
width: number;
|
|
229
|
+
height: number;
|
|
230
|
+
};
|
|
208
231
|
/**
|
|
209
232
|
* Resolve the effective panel dimensions from a preset and/or explicit
|
|
210
233
|
* width/height. Explicit width/height win only when no preset is provided.
|
|
@@ -368,6 +391,10 @@ export interface DuctConfig {
|
|
|
368
391
|
* Declare your entities now; runtime enforcement is in active development.
|
|
369
392
|
*/
|
|
370
393
|
dataModel?: DataModel;
|
|
394
|
+
/** Controls whether this shell is discoverable cross-shell. Default: 'private' */
|
|
395
|
+
registry_visibility?: 'public' | 'private';
|
|
396
|
+
/** Master switch: allow other shells to call this one. Default: false */
|
|
397
|
+
intershell_enabled?: boolean;
|
|
371
398
|
}
|
|
372
399
|
export interface ShellManifest {
|
|
373
400
|
shellId: string;
|
package/dist/core/types.js
CHANGED
|
@@ -9,6 +9,21 @@ export const SHELL_PRESET_DIMENSIONS = {
|
|
|
9
9
|
large: { width: 560, height: 720 },
|
|
10
10
|
};
|
|
11
11
|
export const DEFAULT_SHELL_PRESET = 'tall';
|
|
12
|
+
/** Viewport margins applied to the opened shell panel (matches DuctShell CSS). */
|
|
13
|
+
export const SHELL_PANEL_VIEWPORT_INSETS = {
|
|
14
|
+
width: 32,
|
|
15
|
+
height: 96,
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Cap requested panel dimensions so tall/large presets fit inside a viewport
|
|
19
|
+
* (or bounded preview stage) without clipping below the fold.
|
|
20
|
+
*/
|
|
21
|
+
export function fitShellPanelDimensions(width, height, viewportWidth, viewportHeight, insets = SHELL_PANEL_VIEWPORT_INSETS) {
|
|
22
|
+
return {
|
|
23
|
+
width: Math.min(width, Math.max(0, viewportWidth - insets.width)),
|
|
24
|
+
height: Math.min(height, Math.max(0, viewportHeight - insets.height)),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
12
27
|
/**
|
|
13
28
|
* Resolve the effective panel dimensions from a preset and/or explicit
|
|
14
29
|
* width/height. Explicit width/height win only when no preset is provided.
|