@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.
Files changed (160) hide show
  1. package/CHANGELOG.md +385 -344
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/add.d.ts +7 -0
  5. package/dist/cli/add.js +152 -0
  6. package/dist/cli/agent-prompt.d.ts +3 -0
  7. package/dist/cli/agent-prompt.js +39 -0
  8. package/dist/cli/api-sources.d.ts +26 -0
  9. package/dist/cli/api-sources.js +222 -0
  10. package/dist/cli/cloud.d.ts +133 -0
  11. package/dist/cli/cloud.js +298 -0
  12. package/dist/cli/config-loader.d.ts +14 -0
  13. package/dist/cli/config-loader.js +56 -7
  14. package/dist/cli/device-login.d.ts +17 -0
  15. package/dist/cli/device-login.js +75 -0
  16. package/dist/cli/drift.js +6 -6
  17. package/dist/cli/generators/any-stack.d.ts +3 -0
  18. package/dist/cli/generators/any-stack.js +97 -0
  19. package/dist/cli/generators/config.js +3 -2
  20. package/dist/cli/generators/receiver.js +7 -7
  21. package/dist/cli/generators/shell.js +12 -12
  22. package/dist/cli/generators/token-route.js +245 -245
  23. package/dist/cli/index.js +396 -611
  24. package/dist/cli/mcp-core.d.ts +42 -0
  25. package/dist/cli/mcp-core.js +161 -0
  26. package/dist/cli/mcp-setup.d.ts +4 -0
  27. package/dist/cli/mcp-setup.js +360 -0
  28. package/dist/cli/mcp.d.ts +2 -0
  29. package/dist/cli/mcp.js +457 -0
  30. package/dist/cli/migrate-intershell.js +5 -5
  31. package/dist/cli/policy-defaults.d.ts +37 -0
  32. package/dist/cli/policy-defaults.js +127 -0
  33. package/dist/cli/processors/integration-audit.js +2 -2
  34. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  35. package/dist/cli/processors/openapi-parser.js +8 -3
  36. package/dist/cli/project-loader.d.ts +58 -0
  37. package/dist/cli/project-loader.js +198 -0
  38. package/dist/cli/project-writer.d.ts +23 -0
  39. package/dist/cli/project-writer.js +171 -0
  40. package/dist/cli/push.d.ts +43 -0
  41. package/dist/cli/push.js +276 -0
  42. package/dist/cli/safety-checks.d.ts +9 -0
  43. package/dist/cli/safety-checks.js +29 -0
  44. package/dist/cli/setup.d.ts +20 -0
  45. package/dist/cli/setup.js +349 -0
  46. package/dist/cli/shell-name.d.ts +8 -0
  47. package/dist/cli/shell-name.js +29 -0
  48. package/dist/cli/shells.d.ts +22 -0
  49. package/dist/cli/shells.js +122 -0
  50. package/dist/cli/split.d.ts +7 -0
  51. package/dist/cli/split.js +71 -0
  52. package/dist/cli/sync.d.ts +25 -0
  53. package/dist/cli/sync.js +120 -0
  54. package/dist/cli/test-runner.d.ts +21 -0
  55. package/dist/cli/test-runner.js +281 -0
  56. package/dist/core/compile.d.ts +43 -0
  57. package/dist/core/compile.js +510 -0
  58. package/dist/core/config.d.ts +464 -1
  59. package/dist/core/config.js +14 -14
  60. package/dist/core/login-handoff.d.ts +1 -1
  61. package/dist/core/login-handoff.js +1 -1
  62. package/dist/core/project.d.ts +1798 -0
  63. package/dist/core/project.js +278 -0
  64. package/dist/core/readiness-checks.js +2 -2
  65. package/dist/core/types.d.ts +1 -1
  66. package/dist/index.d.ts +2 -0
  67. package/dist/index.js +1 -0
  68. package/dist/project.d.ts +4 -0
  69. package/dist/project.js +8 -0
  70. package/dist/server.d.ts +2 -0
  71. package/dist/server.js +1 -0
  72. package/package.json +94 -95
  73. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  74. package/dist/adapters/react/page-context-guard.test.js +0 -15
  75. package/dist/cli/agents/api-agent.d.ts +0 -22
  76. package/dist/cli/agents/api-agent.js +0 -761
  77. package/dist/cli/agents/auth-agent.d.ts +0 -7
  78. package/dist/cli/agents/auth-agent.js +0 -212
  79. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  80. package/dist/cli/agents/deeplink-agent.js +0 -285
  81. package/dist/cli/agents/llm.d.ts +0 -33
  82. package/dist/cli/agents/llm.js +0 -309
  83. package/dist/cli/agents/pipeline.d.ts +0 -72
  84. package/dist/cli/agents/pipeline.js +0 -421
  85. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  86. package/dist/cli/agents/reviewer-agent.js +0 -450
  87. package/dist/cli/agents/route-agent.d.ts +0 -17
  88. package/dist/cli/agents/route-agent.js +0 -383
  89. package/dist/cli/config-loader.test.d.ts +0 -1
  90. package/dist/cli/config-loader.test.js +0 -63
  91. package/dist/cli/detectors/topology.d.ts +0 -46
  92. package/dist/cli/detectors/topology.js +0 -417
  93. package/dist/cli/generators/config.test.d.ts +0 -1
  94. package/dist/cli/generators/config.test.js +0 -222
  95. package/dist/cli/generators/shell.test.d.ts +0 -1
  96. package/dist/cli/generators/shell.test.js +0 -73
  97. package/dist/cli/generators/token-route.test.d.ts +0 -1
  98. package/dist/cli/generators/token-route.test.js +0 -53
  99. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  100. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  101. package/dist/cli/init.d.ts +0 -32
  102. package/dist/cli/init.js +0 -1336
  103. package/dist/cli/manifest-diff.test.d.ts +0 -1
  104. package/dist/cli/manifest-diff.test.js +0 -144
  105. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  106. package/dist/cli/processors/curl-parser.test.js +0 -24
  107. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  108. package/dist/cli/processors/integration-audit.test.js +0 -154
  109. package/dist/cli/processors/postprocess.d.ts +0 -22
  110. package/dist/cli/processors/postprocess.js +0 -107
  111. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  112. package/dist/cli/processors/prisma-parser.js +0 -117
  113. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  114. package/dist/cli/processors/verify-discovery.js +0 -193
  115. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  116. package/dist/cli/processors/verify-discovery.test.js +0 -153
  117. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  118. package/dist/cli/processors/zod-extractor.js +0 -153
  119. package/dist/cli/prompts/review.d.ts +0 -61
  120. package/dist/cli/prompts/review.js +0 -410
  121. package/dist/cli/selectors/express.d.ts +0 -12
  122. package/dist/cli/selectors/express.js +0 -117
  123. package/dist/cli/selectors/fastapi.d.ts +0 -12
  124. package/dist/cli/selectors/fastapi.js +0 -122
  125. package/dist/cli/selectors/generic.d.ts +0 -10
  126. package/dist/cli/selectors/generic.js +0 -74
  127. package/dist/cli/selectors/index.d.ts +0 -37
  128. package/dist/cli/selectors/index.js +0 -315
  129. package/dist/cli/selectors/next.d.ts +0 -12
  130. package/dist/cli/selectors/next.js +0 -130
  131. package/dist/core/config-policy.test.d.ts +0 -1
  132. package/dist/core/config-policy.test.js +0 -101
  133. package/dist/core/config-roundtrip.test.d.ts +0 -1
  134. package/dist/core/config-roundtrip.test.js +0 -180
  135. package/dist/core/endpoint-guard.test.d.ts +0 -1
  136. package/dist/core/endpoint-guard.test.js +0 -57
  137. package/dist/core/env-diagnostics.test.d.ts +0 -1
  138. package/dist/core/env-diagnostics.test.js +0 -31
  139. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  140. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  141. package/dist/core/evidence-bundle.test.d.ts +0 -1
  142. package/dist/core/evidence-bundle.test.js +0 -58
  143. package/dist/core/invariants.test.d.ts +0 -1
  144. package/dist/core/invariants.test.js +0 -217
  145. package/dist/core/login-handoff.test.d.ts +0 -1
  146. package/dist/core/login-handoff.test.js +0 -31
  147. package/dist/core/profile.test.d.ts +0 -1
  148. package/dist/core/profile.test.js +0 -95
  149. package/dist/core/readiness-checks.test.d.ts +0 -1
  150. package/dist/core/readiness-checks.test.js +0 -106
  151. package/dist/core/receipt.test.d.ts +0 -1
  152. package/dist/core/receipt.test.js +0 -75
  153. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  154. package/dist/core/sdk-entrypoint.test.js +0 -8
  155. package/dist/core/side-effects-review.test.d.ts +0 -1
  156. package/dist/core/side-effects-review.test.js +0 -28
  157. package/dist/core/token.conformance.test.d.ts +0 -1
  158. package/dist/core/token.conformance.test.js +0 -43
  159. package/dist/core/token.test.d.ts +0 -1
  160. package/dist/core/token.test.js +0 -66
@@ -0,0 +1,510 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — Compile project files ⇄ manifest
3
+ //
4
+ // compileProject(): duct/ folder → the manifest the gateway enforces.
5
+ // splitDuctConfig(): legacy duct.config.ts → duct/ folder (lossless for
6
+ // enforcement: every action keeps the same agent decision).
7
+ // ============================================================
8
+ const SENSITIVITY_ORDER = ["none", "low", "medium", "high", "critical"];
9
+ const COMPARE_OPS = ["gt", "gte", "lt", "lte", "eq", "neq"];
10
+ /** Fallback when duct/project.ts omits `auth` (only identity + chat use it). */
11
+ export const DEFAULT_PROJECT_AUTH = {
12
+ strategy: "unknown",
13
+ sessionFields: [],
14
+ guestAllowed: false,
15
+ tokenExpirySeconds: 60,
16
+ };
17
+ // ----------------------------------------------------------------
18
+ // Patterns
19
+ // ----------------------------------------------------------------
20
+ export function patternToRegExp(pattern) {
21
+ const escaped = pattern
22
+ .split("*")
23
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
24
+ .join("[a-z0-9_]*");
25
+ return new RegExp(`^${escaped}$`);
26
+ }
27
+ export function matchesPattern(pattern, actionId) {
28
+ return patternToRegExp(pattern).test(actionId);
29
+ }
30
+ function matchesAny(patterns, actionId) {
31
+ return Boolean(patterns?.some((pattern) => matchesPattern(pattern, actionId)));
32
+ }
33
+ // ----------------------------------------------------------------
34
+ // Conditions → approveIf predicates
35
+ // ----------------------------------------------------------------
36
+ function compileComparison(param, comparison) {
37
+ if (typeof comparison !== "object" || comparison === null) {
38
+ return { op: "eq", param, value: comparison };
39
+ }
40
+ const [op, value] = Object.entries(comparison)[0];
41
+ if (op === "in") {
42
+ return { op: "in", param, values: value };
43
+ }
44
+ return {
45
+ op: op,
46
+ param,
47
+ value: value,
48
+ };
49
+ }
50
+ export function compileCondition(condition) {
51
+ if ("any" in condition && Array.isArray(condition.any)) {
52
+ const rules = condition.any.map(compileCondition);
53
+ return rules.length === 1 ? rules[0] : { op: "or", rules };
54
+ }
55
+ if ("all" in condition && Array.isArray(condition.all)) {
56
+ const rules = condition.all.map(compileCondition);
57
+ return rules.length === 1 ? rules[0] : { op: "and", rules };
58
+ }
59
+ const rules = Object.entries(condition).map(([param, comparison]) => compileComparison(param, comparison));
60
+ return rules.length === 1 ? rules[0] : { op: "and", rules };
61
+ }
62
+ export function decompilePredicate(predicate) {
63
+ if (predicate.op === "and" || predicate.op === "or") {
64
+ const parts = predicate.rules.map(decompilePredicate);
65
+ if (predicate.op === "and") {
66
+ // Flatten to a single param map when every part is a distinct single-param comparison.
67
+ const flat = {};
68
+ let flattenable = true;
69
+ for (const part of parts) {
70
+ const keys = Object.keys(part);
71
+ if (keys.length !== 1 || keys[0] === "any" || keys[0] === "all" || keys[0] in flat) {
72
+ flattenable = false;
73
+ break;
74
+ }
75
+ flat[keys[0]] = part[keys[0]];
76
+ }
77
+ return flattenable ? flat : { all: parts };
78
+ }
79
+ return { any: parts };
80
+ }
81
+ if (predicate.op === "in") {
82
+ return { [predicate.param]: { in: predicate.values } };
83
+ }
84
+ const compare = predicate;
85
+ if (compare.op === "eq") {
86
+ return { [compare.param]: compare.value };
87
+ }
88
+ return { [compare.param]: { [compare.op]: compare.value } };
89
+ }
90
+ function predicateParams(predicate, out) {
91
+ if (predicate.op === "and" || predicate.op === "or") {
92
+ for (const rule of predicate.rules)
93
+ predicateParams(rule, out);
94
+ return;
95
+ }
96
+ out.add(predicate.param.split(".")[0]);
97
+ }
98
+ // ----------------------------------------------------------------
99
+ // Limits
100
+ // ----------------------------------------------------------------
101
+ export function limitToFields(spec) {
102
+ const out = {};
103
+ if (spec.perMinute !== undefined)
104
+ out.rateLimit = spec.perMinute;
105
+ if (spec.perHour !== undefined)
106
+ out.actionLimit = { type: "rate", maxPerWindow: spec.perHour, windowSeconds: 3600 };
107
+ if (spec.perDay !== undefined)
108
+ out.actionLimit = { type: "rate", maxPerWindow: spec.perDay, windowSeconds: 86400 };
109
+ if (spec.window !== undefined) {
110
+ out.actionLimit = { type: "rate", maxPerWindow: spec.window.max, windowSeconds: spec.window.seconds };
111
+ }
112
+ if (spec.total !== undefined)
113
+ out.actionLimit = { type: "count", maxCount: spec.total };
114
+ return out;
115
+ }
116
+ export function fieldsToLimit(action) {
117
+ const spec = {};
118
+ if (action.rateLimit !== undefined)
119
+ spec.perMinute = action.rateLimit;
120
+ const limit = action.actionLimit;
121
+ if (limit?.type === "count")
122
+ spec.total = limit.maxCount;
123
+ if (limit?.type === "rate") {
124
+ if (limit.windowSeconds === 3600)
125
+ spec.perHour = limit.maxPerWindow;
126
+ else if (limit.windowSeconds === 86400)
127
+ spec.perDay = limit.maxPerWindow;
128
+ else
129
+ spec.window = { max: limit.maxPerWindow, seconds: limit.windowSeconds };
130
+ }
131
+ return Object.keys(spec).length > 0 ? spec : null;
132
+ }
133
+ // ----------------------------------------------------------------
134
+ // Agent exposure
135
+ // ----------------------------------------------------------------
136
+ function isHighSensitivity(level) {
137
+ return SENSITIVITY_ORDER.indexOf(level) >= SENSITIVITY_ORDER.indexOf("high");
138
+ }
139
+ function computeExposure(action, agents) {
140
+ const access = agents.access;
141
+ const explicitLevel = agents.levels?.[action.id];
142
+ if (matchesAny(agents.deny, action.id)) {
143
+ return { agentAccessible: false, level: "none" };
144
+ }
145
+ if (agents.allow) {
146
+ const allowed = matchesAny(agents.allow, action.id);
147
+ if (!allowed)
148
+ return { agentAccessible: false, level: explicitLevel };
149
+ if (explicitLevel)
150
+ return { agentAccessible: true, level: explicitLevel };
151
+ // Explicitly allowed: lift the shell-wide level just enough for this action to run.
152
+ const needed = action.sideEffects ? "write" : "read";
153
+ const shellLevelRuns = access === "write" || (access === "read" && !action.sideEffects);
154
+ return { agentAccessible: true, level: shellLevelRuns ? undefined : needed };
155
+ }
156
+ // No allow list: expose what the access level permits, never high/critical by default.
157
+ const byAccess = access === "write" || (access === "read" && !action.sideEffects);
158
+ return {
159
+ agentAccessible: byAccess && !isHighSensitivity(action.sensitivityLevel),
160
+ level: explicitLevel,
161
+ };
162
+ }
163
+ // ----------------------------------------------------------------
164
+ // compileProject
165
+ // ----------------------------------------------------------------
166
+ export function compileProject(input) {
167
+ const { project, capabilities, policy } = input;
168
+ const shell = input.shell ?? null;
169
+ const warnings = [];
170
+ const actionIds = capabilities.actions.map((action) => action.id);
171
+ const warnUnused = (section, patterns) => {
172
+ for (const pattern of patterns ?? []) {
173
+ if (!actionIds.some((id) => matchesPattern(pattern, id))) {
174
+ warnings.push(`policy.${section}: "${pattern}" matches no actions`);
175
+ }
176
+ }
177
+ };
178
+ warnUnused("agents.allow", policy.agents.allow);
179
+ warnUnused("agents.deny", policy.agents.deny);
180
+ warnUnused("approveWhen", Object.keys(policy.approveWhen ?? {}));
181
+ warnUnused("limits", Object.keys(policy.limits ?? {}));
182
+ warnUnused("sensitivity", Object.keys(policy.sensitivity ?? {}));
183
+ warnUnused("windows", Object.keys(policy.windows ?? {}));
184
+ for (const id of Object.keys(policy.agents.levels ?? {})) {
185
+ if (!actionIds.includes(id))
186
+ warnings.push(`policy.agents.levels: unknown action "${id}"`);
187
+ }
188
+ for (const id of Object.keys(shell?.actionHints ?? {})) {
189
+ if (!actionIds.includes(id))
190
+ warnings.push(`shell.actionHints: unknown action "${id}"`);
191
+ }
192
+ const actionOverrides = {};
193
+ const actions = capabilities.actions.map((capability) => {
194
+ let sensitivityLevel = capability.sensitivityLevel;
195
+ for (const [pattern, level] of Object.entries(policy.sensitivity ?? {})) {
196
+ if (matchesPattern(pattern, capability.id))
197
+ sensitivityLevel = level;
198
+ }
199
+ const exposure = computeExposure({ id: capability.id, sideEffects: capability.sideEffects, sensitivityLevel }, policy.agents);
200
+ if (exposure.level)
201
+ actionOverrides[capability.id] = exposure.level;
202
+ let approveIf;
203
+ for (const [pattern, condition] of Object.entries(policy.approveWhen ?? {})) {
204
+ if (matchesPattern(pattern, capability.id))
205
+ approveIf = compileCondition(condition);
206
+ }
207
+ if (approveIf) {
208
+ const known = new Set((capability.params ?? []).map((param) => param.name));
209
+ const used = new Set();
210
+ predicateParams(approveIf, used);
211
+ for (const param of used) {
212
+ if (!known.has(param)) {
213
+ warnings.push(`policy.approveWhen: "${capability.id}" has no param "${param}" — the condition can never match`);
214
+ }
215
+ }
216
+ }
217
+ let limitFields = {};
218
+ for (const [pattern, spec] of Object.entries(policy.limits ?? {})) {
219
+ if (matchesPattern(pattern, capability.id)) {
220
+ limitFields = { ...limitFields, ...limitToFields(spec) };
221
+ }
222
+ }
223
+ let validFrom;
224
+ let validUntil;
225
+ for (const [pattern, window] of Object.entries(policy.windows ?? {})) {
226
+ if (matchesPattern(pattern, capability.id)) {
227
+ validFrom = window.from ?? validFrom;
228
+ validUntil = window.until ?? validUntil;
229
+ }
230
+ }
231
+ const hints = shell?.actionHints?.[capability.id] ?? {};
232
+ const action = {
233
+ ...capability,
234
+ params: capability.params ?? [],
235
+ sensitivityLevel,
236
+ agentAccessible: exposure.agentAccessible,
237
+ ...(approveIf ? { approveIf } : {}),
238
+ ...limitFields,
239
+ ...(validFrom ? { validFrom } : {}),
240
+ ...(validUntil ? { validUntil } : {}),
241
+ ...hints,
242
+ };
243
+ return action;
244
+ });
245
+ const agentPermissions = {
246
+ defaultLevel: policy.agents.access,
247
+ requireUserConsent: policy.agents.userConsent,
248
+ ...(Object.keys(actionOverrides).length > 0 ? { actionOverrides } : {}),
249
+ ...(policy.agents.consentScope ? { consentActionScope: policy.agents.consentScope } : {}),
250
+ ...(policy.agents.validFrom ? { validFrom: policy.agents.validFrom } : {}),
251
+ ...(policy.agents.validUntil ? { validUntil: policy.agents.validUntil } : {}),
252
+ ...(project.network?.allowedCallers ? { allowedCallers: project.network.allowedCallers } : {}),
253
+ ...(project.network?.allowedCallees ? { allowedCallees: project.network.allowedCallees } : {}),
254
+ };
255
+ const approvers = policy.approvers;
256
+ const config = {
257
+ shellId: project.shellId,
258
+ product: project.product,
259
+ auth: project.auth ?? DEFAULT_PROJECT_AUTH,
260
+ routes: shell?.routes ?? [],
261
+ actions,
262
+ deeplinks: shell?.deeplinks ?? [],
263
+ agentPermissions,
264
+ ...(shell?.widget ? { widget: shell.widget } : {}),
265
+ ...(shell?.dataModel ? { dataModel: shell.dataModel } : {}),
266
+ ...(project.webhooks ? { webhooks: project.webhooks } : {}),
267
+ ...(project.network?.registry_visibility ? { registry_visibility: project.network.registry_visibility } : {}),
268
+ ...(project.network?.intershell_enabled !== undefined
269
+ ? { intershell_enabled: project.network.intershell_enabled }
270
+ : {}),
271
+ ...(approvers?.stepUp ? { approval: { stepUp: approvers.stepUp } } : {}),
272
+ ...(approvers?.emails || approvers?.reminderLeadMinutes !== undefined
273
+ ? {
274
+ operatorNotifications: {
275
+ ...(approvers.emails ? { approverEmails: approvers.emails } : {}),
276
+ ...(approvers.reminderLeadMinutes !== undefined
277
+ ? { confirmationReminderLeadMinutes: approvers.reminderLeadMinutes }
278
+ : {}),
279
+ },
280
+ }
281
+ : {}),
282
+ };
283
+ return { config, warnings };
284
+ }
285
+ // ----------------------------------------------------------------
286
+ // splitDuctConfig — legacy duct.config.ts → duct/ folder
287
+ // ----------------------------------------------------------------
288
+ const CAPABILITY_KEYS = [
289
+ "id",
290
+ "name",
291
+ "description",
292
+ "method",
293
+ "path",
294
+ "sideEffects",
295
+ "sideEffectsReviewAck",
296
+ "sensitivityLevel",
297
+ "requiresAuth",
298
+ "params",
299
+ "inputSchema",
300
+ "responseSchema",
301
+ "confidence",
302
+ "evidence",
303
+ "updatedAt",
304
+ ];
305
+ const HINT_KEYS = [
306
+ "searchHint",
307
+ "alwaysInclude",
308
+ "interruptBehavior",
309
+ "dependsOn",
310
+ "semanticType",
311
+ "outputSchema",
312
+ "paramMappings",
313
+ "navigatesTo",
314
+ ];
315
+ /**
316
+ * Every enforcement-relevant difference between two manifests, per action.
317
+ * Empty = the gateway makes the same decision for every caller on every action.
318
+ */
319
+ export function enforcementDiff(before, after) {
320
+ const diffs = [];
321
+ const level = (config, id) => {
322
+ const raw = config.agentPermissions.actionOverrides?.[id] ?? config.agentPermissions.defaultLevel;
323
+ return raw === "admin" ? "write" : raw;
324
+ };
325
+ const exposed = (config, action) => {
326
+ const allowed = config.agentPermissions.allowedActions;
327
+ return action.agentAccessible === true && (!allowed?.length || allowed.includes(action.id));
328
+ };
329
+ const keyed = (config) => new Map(config.actions.map((action) => [action.id, action]));
330
+ const a = keyed(before);
331
+ const b = keyed(after);
332
+ for (const id of new Set([...a.keys(), ...b.keys()])) {
333
+ const x = a.get(id);
334
+ const y = b.get(id);
335
+ if (!x || !y) {
336
+ diffs.push(`${id}: ${x ? "missing after" : "added"}`);
337
+ continue;
338
+ }
339
+ const checks = [
340
+ ["agent exposure", exposed(before, x), exposed(after, y)],
341
+ ["agent level", level(before, id), level(after, id)],
342
+ ["sideEffects", x.sideEffects, y.sideEffects],
343
+ ["sensitivityLevel", x.sensitivityLevel, y.sensitivityLevel],
344
+ ["requiresAuth", x.requiresAuth, y.requiresAuth],
345
+ ["method", x.method, y.method],
346
+ ["path", x.path, y.path],
347
+ ["approveIf", x.approveIf ?? null, y.approveIf ?? null],
348
+ ["rateLimit", x.rateLimit ?? null, y.rateLimit ?? null],
349
+ ["actionLimit", x.actionLimit ?? null, y.actionLimit ?? null],
350
+ ["validFrom", x.validFrom ?? null, y.validFrom ?? null],
351
+ ["validUntil", x.validUntil ?? null, y.validUntil ?? null],
352
+ ];
353
+ for (const [field, left, right] of checks) {
354
+ if (JSON.stringify(left) !== JSON.stringify(right)) {
355
+ diffs.push(`${id}: ${field} ${JSON.stringify(left)} → ${JSON.stringify(right)}`);
356
+ }
357
+ }
358
+ }
359
+ const pa = before.agentPermissions;
360
+ const pb = after.agentPermissions;
361
+ const shellChecks = [
362
+ ["requireUserConsent", pa.requireUserConsent, pb.requireUserConsent],
363
+ ["consentActionScope", pa.consentActionScope ?? null, pb.consentActionScope ?? null],
364
+ ["validFrom", pa.validFrom ?? null, pb.validFrom ?? null],
365
+ ["validUntil", pa.validUntil ?? null, pb.validUntil ?? null],
366
+ ["allowedCallers", pa.allowedCallers ?? null, pb.allowedCallers ?? null],
367
+ ["allowedCallees", pa.allowedCallees ?? null, pb.allowedCallees ?? null],
368
+ ["intershell_enabled", Boolean(before.intershell_enabled), Boolean(after.intershell_enabled)],
369
+ ["registry_visibility", before.registry_visibility ?? "private", after.registry_visibility ?? "private"],
370
+ ];
371
+ for (const [field, left, right] of shellChecks) {
372
+ if (JSON.stringify(left) !== JSON.stringify(right)) {
373
+ diffs.push(`agentPermissions.${field}: ${JSON.stringify(left)} → ${JSON.stringify(right)}`);
374
+ }
375
+ }
376
+ return diffs;
377
+ }
378
+ /** Keep only the "what the API does" fields of an action (drop policy and chat hints). */
379
+ export function capabilityFromAction(action) {
380
+ return pick(action, CAPABILITY_KEYS);
381
+ }
382
+ function pick(source, keys) {
383
+ const out = {};
384
+ for (const key of keys) {
385
+ const value = source[key];
386
+ if (value !== undefined)
387
+ out[key] = value;
388
+ }
389
+ return out;
390
+ }
391
+ function normalizeAccess(level) {
392
+ if (level === "admin")
393
+ return "write";
394
+ return level;
395
+ }
396
+ /** Effective level the gateway applies to an action for agents (mirrors the shell-wide gate). */
397
+ function effectiveLevel(actionId, permissions) {
398
+ return permissions.actionOverrides?.[actionId] ?? permissions.defaultLevel;
399
+ }
400
+ export function splitDuctConfig(config) {
401
+ const warnings = [];
402
+ const permissions = config.agentPermissions;
403
+ const access = normalizeAccess(permissions.defaultLevel);
404
+ const allowedActions = permissions.allowedActions?.length ? new Set(permissions.allowedActions) : null;
405
+ const allow = [];
406
+ const levels = {};
407
+ const approveWhen = {};
408
+ const limits = {};
409
+ const windows = {};
410
+ const actionHints = {};
411
+ for (const action of config.actions) {
412
+ const exposed = action.agentAccessible === true && (!allowedActions || allowedActions.has(action.id));
413
+ if (exposed)
414
+ allow.push(action.id);
415
+ // Keep the exact effective level for exposed actions whenever compile would infer a different one.
416
+ const level = effectiveLevel(action.id, permissions);
417
+ const inferred = exposed
418
+ ? (access === "write" || (access === "read" && !action.sideEffects)
419
+ ? undefined
420
+ : action.sideEffects ? "write" : "read")
421
+ : undefined;
422
+ const original = permissions.actionOverrides?.[action.id];
423
+ if (original !== undefined) {
424
+ levels[action.id] = original;
425
+ }
426
+ else if (exposed && inferred !== undefined) {
427
+ // Compile would lift this action; pin the original shell-wide level so behaviour is unchanged.
428
+ levels[action.id] = level;
429
+ }
430
+ if (action.approveIf)
431
+ approveWhen[action.id] = decompilePredicate(action.approveIf);
432
+ const limit = fieldsToLimit(action);
433
+ if (limit)
434
+ limits[action.id] = limit;
435
+ if (action.validFrom || action.validUntil) {
436
+ windows[action.id] = {
437
+ ...(action.validFrom ? { from: action.validFrom } : {}),
438
+ ...(action.validUntil ? { until: action.validUntil } : {}),
439
+ };
440
+ }
441
+ const hints = pick(action, HINT_KEYS);
442
+ if (Object.keys(hints).length > 0)
443
+ actionHints[action.id] = hints;
444
+ }
445
+ const policy = {
446
+ agents: {
447
+ access,
448
+ allow,
449
+ ...(Object.keys(levels).length > 0 ? { levels } : {}),
450
+ userConsent: permissions.requireUserConsent,
451
+ ...(permissions.consentActionScope ? { consentScope: permissions.consentActionScope } : {}),
452
+ ...(permissions.validFrom ? { validFrom: permissions.validFrom } : {}),
453
+ ...(permissions.validUntil ? { validUntil: permissions.validUntil } : {}),
454
+ },
455
+ ...(Object.keys(approveWhen).length > 0 ? { approveWhen } : {}),
456
+ ...(Object.keys(limits).length > 0 ? { limits } : {}),
457
+ ...(Object.keys(windows).length > 0 ? { windows } : {}),
458
+ ...(config.approval?.stepUp || config.operatorNotifications
459
+ ? {
460
+ approvers: {
461
+ ...(config.operatorNotifications?.approverEmails?.length
462
+ ? { emails: config.operatorNotifications.approverEmails }
463
+ : {}),
464
+ ...(config.operatorNotifications?.confirmationReminderLeadMinutes !== undefined
465
+ ? { reminderLeadMinutes: config.operatorNotifications.confirmationReminderLeadMinutes }
466
+ : {}),
467
+ ...(config.approval?.stepUp ? { stepUp: config.approval.stepUp } : {}),
468
+ },
469
+ }
470
+ : {}),
471
+ };
472
+ const network = {
473
+ ...(config.registry_visibility && config.registry_visibility !== "private"
474
+ ? { registry_visibility: config.registry_visibility }
475
+ : {}),
476
+ ...(config.intershell_enabled ? { intershell_enabled: true } : {}),
477
+ ...(permissions.allowedCallers?.length ? { allowedCallers: permissions.allowedCallers } : {}),
478
+ ...(permissions.allowedCallees?.length ? { allowedCallees: permissions.allowedCallees } : {}),
479
+ };
480
+ const project = {
481
+ shellId: config.shellId,
482
+ product: config.product,
483
+ auth: config.auth,
484
+ ...(config.webhooks ? { webhooks: config.webhooks } : {}),
485
+ ...(Object.keys(network).length > 0 ? { network } : {}),
486
+ };
487
+ const capabilities = {
488
+ version: 1,
489
+ source: { kind: "imported", location: "duct.config.ts", syncedAt: new Date().toISOString() },
490
+ actions: config.actions.map((action) => pick(action, CAPABILITY_KEYS)),
491
+ };
492
+ const hasShell = (config.routes?.length ?? 0) > 0 ||
493
+ (config.deeplinks?.length ?? 0) > 0 ||
494
+ Boolean(config.widget) ||
495
+ Boolean(config.dataModel) ||
496
+ Object.keys(actionHints).length > 0;
497
+ const shell = hasShell
498
+ ? {
499
+ ...(config.widget ? { widget: config.widget } : {}),
500
+ routes: config.routes ?? [],
501
+ deeplinks: config.deeplinks ?? [],
502
+ ...(config.dataModel ? { dataModel: config.dataModel } : {}),
503
+ ...(Object.keys(actionHints).length > 0 ? { actionHints } : {}),
504
+ }
505
+ : null;
506
+ if (allowedActions) {
507
+ warnings.push("agentPermissions.allowedActions was folded into policy.agents.allow");
508
+ }
509
+ return { project, capabilities, policy, shell, warnings };
510
+ }