@duct-sdk/sdk 0.5.13 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/action-confusion-format.d.ts +17 -0
  5. package/dist/cli/action-confusion-format.js +24 -0
  6. package/dist/cli/add.d.ts +7 -0
  7. package/dist/cli/add.js +152 -0
  8. package/dist/cli/agent-prompt.d.ts +3 -0
  9. package/dist/cli/agent-prompt.js +39 -0
  10. package/dist/cli/api-sources.d.ts +26 -0
  11. package/dist/cli/api-sources.js +222 -0
  12. package/dist/cli/cloud.d.ts +162 -0
  13. package/dist/cli/cloud.js +306 -0
  14. package/dist/cli/config-loader.d.ts +14 -0
  15. package/dist/cli/config-loader.js +56 -7
  16. package/dist/cli/device-login.d.ts +17 -0
  17. package/dist/cli/device-login.js +75 -0
  18. package/dist/cli/drift.js +6 -6
  19. package/dist/cli/generators/any-stack.d.ts +3 -0
  20. package/dist/cli/generators/any-stack.js +97 -0
  21. package/dist/cli/generators/config.js +3 -2
  22. package/dist/cli/generators/receiver.js +7 -7
  23. package/dist/cli/generators/shell.js +12 -12
  24. package/dist/cli/generators/token-route.js +245 -245
  25. package/dist/cli/generators/wiring-snippets.d.ts +0 -14
  26. package/dist/cli/generators/wiring-snippets.js +188 -305
  27. package/dist/cli/index.js +396 -611
  28. package/dist/cli/mcp-core.d.ts +42 -0
  29. package/dist/cli/mcp-core.js +161 -0
  30. package/dist/cli/mcp-setup.d.ts +4 -0
  31. package/dist/cli/mcp-setup.js +352 -0
  32. package/dist/cli/mcp.d.ts +2 -0
  33. package/dist/cli/mcp.js +457 -0
  34. package/dist/cli/migrate-intershell.js +5 -5
  35. package/dist/cli/policy-defaults.d.ts +37 -0
  36. package/dist/cli/policy-defaults.js +127 -0
  37. package/dist/cli/policy-replay-format.d.ts +9 -0
  38. package/dist/cli/policy-replay-format.js +46 -0
  39. package/dist/cli/processors/integration-audit.js +2 -2
  40. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  41. package/dist/cli/processors/openapi-parser.js +8 -3
  42. package/dist/cli/project-loader.d.ts +58 -0
  43. package/dist/cli/project-loader.js +198 -0
  44. package/dist/cli/project-writer.d.ts +23 -0
  45. package/dist/cli/project-writer.js +171 -0
  46. package/dist/cli/push.d.ts +43 -0
  47. package/dist/cli/push.js +308 -0
  48. package/dist/cli/safety-checks.d.ts +9 -0
  49. package/dist/cli/safety-checks.js +29 -0
  50. package/dist/cli/setup.d.ts +20 -0
  51. package/dist/cli/setup.js +349 -0
  52. package/dist/cli/shell-name.d.ts +8 -0
  53. package/dist/cli/shell-name.js +29 -0
  54. package/dist/cli/shells.d.ts +22 -0
  55. package/dist/cli/shells.js +122 -0
  56. package/dist/cli/split.d.ts +7 -0
  57. package/dist/cli/split.js +71 -0
  58. package/dist/cli/sync.d.ts +25 -0
  59. package/dist/cli/sync.js +120 -0
  60. package/dist/cli/test-runner.d.ts +21 -0
  61. package/dist/cli/test-runner.js +281 -0
  62. package/dist/core/compile.d.ts +43 -0
  63. package/dist/core/compile.js +512 -0
  64. package/dist/core/config.d.ts +538 -19
  65. package/dist/core/config.js +22 -14
  66. package/dist/core/login-handoff.d.ts +1 -1
  67. package/dist/core/login-handoff.js +1 -1
  68. package/dist/core/project.d.ts +1864 -0
  69. package/dist/core/project.js +291 -0
  70. package/dist/core/readiness-checks.js +2 -2
  71. package/dist/core/types.d.ts +10 -1
  72. package/dist/index.d.ts +2 -0
  73. package/dist/index.js +1 -0
  74. package/dist/project.d.ts +4 -0
  75. package/dist/project.js +8 -0
  76. package/dist/server.d.ts +2 -0
  77. package/dist/server.js +1 -0
  78. package/package.json +94 -95
  79. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  80. package/dist/adapters/react/page-context-guard.test.js +0 -15
  81. package/dist/cli/agents/api-agent.d.ts +0 -22
  82. package/dist/cli/agents/api-agent.js +0 -761
  83. package/dist/cli/agents/auth-agent.d.ts +0 -7
  84. package/dist/cli/agents/auth-agent.js +0 -212
  85. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  86. package/dist/cli/agents/deeplink-agent.js +0 -285
  87. package/dist/cli/agents/llm.d.ts +0 -33
  88. package/dist/cli/agents/llm.js +0 -309
  89. package/dist/cli/agents/pipeline.d.ts +0 -72
  90. package/dist/cli/agents/pipeline.js +0 -421
  91. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  92. package/dist/cli/agents/reviewer-agent.js +0 -450
  93. package/dist/cli/agents/route-agent.d.ts +0 -17
  94. package/dist/cli/agents/route-agent.js +0 -383
  95. package/dist/cli/config-loader.test.d.ts +0 -1
  96. package/dist/cli/config-loader.test.js +0 -63
  97. package/dist/cli/detectors/topology.d.ts +0 -46
  98. package/dist/cli/detectors/topology.js +0 -417
  99. package/dist/cli/generators/config.test.d.ts +0 -1
  100. package/dist/cli/generators/config.test.js +0 -222
  101. package/dist/cli/generators/shell.test.d.ts +0 -1
  102. package/dist/cli/generators/shell.test.js +0 -73
  103. package/dist/cli/generators/token-route.test.d.ts +0 -1
  104. package/dist/cli/generators/token-route.test.js +0 -53
  105. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  106. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  107. package/dist/cli/init.d.ts +0 -32
  108. package/dist/cli/init.js +0 -1336
  109. package/dist/cli/manifest-diff.test.d.ts +0 -1
  110. package/dist/cli/manifest-diff.test.js +0 -144
  111. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  112. package/dist/cli/processors/curl-parser.test.js +0 -24
  113. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  114. package/dist/cli/processors/integration-audit.test.js +0 -154
  115. package/dist/cli/processors/postprocess.d.ts +0 -22
  116. package/dist/cli/processors/postprocess.js +0 -107
  117. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  118. package/dist/cli/processors/prisma-parser.js +0 -117
  119. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  120. package/dist/cli/processors/verify-discovery.js +0 -193
  121. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  122. package/dist/cli/processors/verify-discovery.test.js +0 -153
  123. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  124. package/dist/cli/processors/zod-extractor.js +0 -153
  125. package/dist/cli/prompts/review.d.ts +0 -61
  126. package/dist/cli/prompts/review.js +0 -410
  127. package/dist/cli/selectors/express.d.ts +0 -12
  128. package/dist/cli/selectors/express.js +0 -117
  129. package/dist/cli/selectors/fastapi.d.ts +0 -12
  130. package/dist/cli/selectors/fastapi.js +0 -122
  131. package/dist/cli/selectors/generic.d.ts +0 -10
  132. package/dist/cli/selectors/generic.js +0 -74
  133. package/dist/cli/selectors/index.d.ts +0 -37
  134. package/dist/cli/selectors/index.js +0 -315
  135. package/dist/cli/selectors/next.d.ts +0 -12
  136. package/dist/cli/selectors/next.js +0 -130
  137. package/dist/core/config-policy.test.d.ts +0 -1
  138. package/dist/core/config-policy.test.js +0 -101
  139. package/dist/core/config-roundtrip.test.d.ts +0 -1
  140. package/dist/core/config-roundtrip.test.js +0 -180
  141. package/dist/core/endpoint-guard.test.d.ts +0 -1
  142. package/dist/core/endpoint-guard.test.js +0 -57
  143. package/dist/core/env-diagnostics.test.d.ts +0 -1
  144. package/dist/core/env-diagnostics.test.js +0 -31
  145. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  146. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  147. package/dist/core/evidence-bundle.test.d.ts +0 -1
  148. package/dist/core/evidence-bundle.test.js +0 -58
  149. package/dist/core/invariants.test.d.ts +0 -1
  150. package/dist/core/invariants.test.js +0 -217
  151. package/dist/core/login-handoff.test.d.ts +0 -1
  152. package/dist/core/login-handoff.test.js +0 -31
  153. package/dist/core/profile.test.d.ts +0 -1
  154. package/dist/core/profile.test.js +0 -95
  155. package/dist/core/readiness-checks.test.d.ts +0 -1
  156. package/dist/core/readiness-checks.test.js +0 -106
  157. package/dist/core/receipt.test.d.ts +0 -1
  158. package/dist/core/receipt.test.js +0 -75
  159. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  160. package/dist/core/sdk-entrypoint.test.js +0 -8
  161. package/dist/core/side-effects-review.test.d.ts +0 -1
  162. package/dist/core/side-effects-review.test.js +0 -28
  163. package/dist/core/token.conformance.test.d.ts +0 -1
  164. package/dist/core/token.conformance.test.js +0 -43
  165. package/dist/core/token.test.d.ts +0 -1
  166. package/dist/core/token.test.js +0 -66
@@ -0,0 +1,512 @@
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.consentHours ? { consentGrantHours: policy.agents.consentHours } : {}),
251
+ ...(policy.agents.validFrom ? { validFrom: policy.agents.validFrom } : {}),
252
+ ...(policy.agents.validUntil ? { validUntil: policy.agents.validUntil } : {}),
253
+ ...(project.network?.allowedCallers ? { allowedCallers: project.network.allowedCallers } : {}),
254
+ ...(project.network?.allowedCallees ? { allowedCallees: project.network.allowedCallees } : {}),
255
+ };
256
+ const approvers = policy.approvers;
257
+ const config = {
258
+ shellId: project.shellId,
259
+ product: project.product,
260
+ auth: project.auth ?? DEFAULT_PROJECT_AUTH,
261
+ routes: shell?.routes ?? [],
262
+ actions,
263
+ deeplinks: shell?.deeplinks ?? [],
264
+ agentPermissions,
265
+ ...(shell?.widget ? { widget: shell.widget } : {}),
266
+ ...(shell?.dataModel ? { dataModel: shell.dataModel } : {}),
267
+ ...(project.webhooks ? { webhooks: project.webhooks } : {}),
268
+ ...(project.network?.registry_visibility ? { registry_visibility: project.network.registry_visibility } : {}),
269
+ ...(project.network?.intershell_enabled !== undefined
270
+ ? { intershell_enabled: project.network.intershell_enabled }
271
+ : {}),
272
+ ...(approvers?.stepUp ? { approval: { stepUp: approvers.stepUp } } : {}),
273
+ ...(approvers?.emails || approvers?.reminderLeadMinutes !== undefined
274
+ ? {
275
+ operatorNotifications: {
276
+ ...(approvers.emails ? { approverEmails: approvers.emails } : {}),
277
+ ...(approvers.reminderLeadMinutes !== undefined
278
+ ? { confirmationReminderLeadMinutes: approvers.reminderLeadMinutes }
279
+ : {}),
280
+ },
281
+ }
282
+ : {}),
283
+ };
284
+ return { config, warnings };
285
+ }
286
+ // ----------------------------------------------------------------
287
+ // splitDuctConfig — legacy duct.config.ts → duct/ folder
288
+ // ----------------------------------------------------------------
289
+ const CAPABILITY_KEYS = [
290
+ "id",
291
+ "name",
292
+ "description",
293
+ "method",
294
+ "path",
295
+ "sideEffects",
296
+ "sideEffectsReviewAck",
297
+ "sensitivityLevel",
298
+ "requiresAuth",
299
+ "params",
300
+ "inputSchema",
301
+ "responseSchema",
302
+ "confidence",
303
+ "evidence",
304
+ "updatedAt",
305
+ ];
306
+ const HINT_KEYS = [
307
+ "searchHint",
308
+ "alwaysInclude",
309
+ "interruptBehavior",
310
+ "dependsOn",
311
+ "semanticType",
312
+ "outputSchema",
313
+ "paramMappings",
314
+ "navigatesTo",
315
+ ];
316
+ /**
317
+ * Every enforcement-relevant difference between two manifests, per action.
318
+ * Empty = the gateway makes the same decision for every caller on every action.
319
+ */
320
+ export function enforcementDiff(before, after) {
321
+ const diffs = [];
322
+ const level = (config, id) => {
323
+ const raw = config.agentPermissions.actionOverrides?.[id] ?? config.agentPermissions.defaultLevel;
324
+ return raw === "admin" ? "write" : raw;
325
+ };
326
+ const exposed = (config, action) => {
327
+ const allowed = config.agentPermissions.allowedActions;
328
+ return action.agentAccessible === true && (!allowed?.length || allowed.includes(action.id));
329
+ };
330
+ const keyed = (config) => new Map(config.actions.map((action) => [action.id, action]));
331
+ const a = keyed(before);
332
+ const b = keyed(after);
333
+ for (const id of new Set([...a.keys(), ...b.keys()])) {
334
+ const x = a.get(id);
335
+ const y = b.get(id);
336
+ if (!x || !y) {
337
+ diffs.push(`${id}: ${x ? "missing after" : "added"}`);
338
+ continue;
339
+ }
340
+ const checks = [
341
+ ["agent exposure", exposed(before, x), exposed(after, y)],
342
+ ["agent level", level(before, id), level(after, id)],
343
+ ["sideEffects", x.sideEffects, y.sideEffects],
344
+ ["sensitivityLevel", x.sensitivityLevel, y.sensitivityLevel],
345
+ ["requiresAuth", x.requiresAuth, y.requiresAuth],
346
+ ["method", x.method, y.method],
347
+ ["path", x.path, y.path],
348
+ ["approveIf", x.approveIf ?? null, y.approveIf ?? null],
349
+ ["rateLimit", x.rateLimit ?? null, y.rateLimit ?? null],
350
+ ["actionLimit", x.actionLimit ?? null, y.actionLimit ?? null],
351
+ ["validFrom", x.validFrom ?? null, y.validFrom ?? null],
352
+ ["validUntil", x.validUntil ?? null, y.validUntil ?? null],
353
+ ];
354
+ for (const [field, left, right] of checks) {
355
+ if (JSON.stringify(left) !== JSON.stringify(right)) {
356
+ diffs.push(`${id}: ${field} ${JSON.stringify(left)} → ${JSON.stringify(right)}`);
357
+ }
358
+ }
359
+ }
360
+ const pa = before.agentPermissions;
361
+ const pb = after.agentPermissions;
362
+ const shellChecks = [
363
+ ["requireUserConsent", pa.requireUserConsent, pb.requireUserConsent],
364
+ ["consentActionScope", pa.consentActionScope ?? null, pb.consentActionScope ?? null],
365
+ ["consentGrantHours", pa.consentGrantHours ?? null, pb.consentGrantHours ?? null],
366
+ ["validFrom", pa.validFrom ?? null, pb.validFrom ?? null],
367
+ ["validUntil", pa.validUntil ?? null, pb.validUntil ?? null],
368
+ ["allowedCallers", pa.allowedCallers ?? null, pb.allowedCallers ?? null],
369
+ ["allowedCallees", pa.allowedCallees ?? null, pb.allowedCallees ?? null],
370
+ ["intershell_enabled", Boolean(before.intershell_enabled), Boolean(after.intershell_enabled)],
371
+ ["registry_visibility", before.registry_visibility ?? "private", after.registry_visibility ?? "private"],
372
+ ];
373
+ for (const [field, left, right] of shellChecks) {
374
+ if (JSON.stringify(left) !== JSON.stringify(right)) {
375
+ diffs.push(`agentPermissions.${field}: ${JSON.stringify(left)} → ${JSON.stringify(right)}`);
376
+ }
377
+ }
378
+ return diffs;
379
+ }
380
+ /** Keep only the "what the API does" fields of an action (drop policy and chat hints). */
381
+ export function capabilityFromAction(action) {
382
+ return pick(action, CAPABILITY_KEYS);
383
+ }
384
+ function pick(source, keys) {
385
+ const out = {};
386
+ for (const key of keys) {
387
+ const value = source[key];
388
+ if (value !== undefined)
389
+ out[key] = value;
390
+ }
391
+ return out;
392
+ }
393
+ function normalizeAccess(level) {
394
+ if (level === "admin")
395
+ return "write";
396
+ return level;
397
+ }
398
+ /** Effective level the gateway applies to an action for agents (mirrors the shell-wide gate). */
399
+ function effectiveLevel(actionId, permissions) {
400
+ return permissions.actionOverrides?.[actionId] ?? permissions.defaultLevel;
401
+ }
402
+ export function splitDuctConfig(config) {
403
+ const warnings = [];
404
+ const permissions = config.agentPermissions;
405
+ const access = normalizeAccess(permissions.defaultLevel);
406
+ const allowedActions = permissions.allowedActions?.length ? new Set(permissions.allowedActions) : null;
407
+ const allow = [];
408
+ const levels = {};
409
+ const approveWhen = {};
410
+ const limits = {};
411
+ const windows = {};
412
+ const actionHints = {};
413
+ for (const action of config.actions) {
414
+ const exposed = action.agentAccessible === true && (!allowedActions || allowedActions.has(action.id));
415
+ if (exposed)
416
+ allow.push(action.id);
417
+ // Keep the exact effective level for exposed actions whenever compile would infer a different one.
418
+ const level = effectiveLevel(action.id, permissions);
419
+ const inferred = exposed
420
+ ? (access === "write" || (access === "read" && !action.sideEffects)
421
+ ? undefined
422
+ : action.sideEffects ? "write" : "read")
423
+ : undefined;
424
+ const original = permissions.actionOverrides?.[action.id];
425
+ if (original !== undefined) {
426
+ levels[action.id] = original;
427
+ }
428
+ else if (exposed && inferred !== undefined) {
429
+ // Compile would lift this action; pin the original shell-wide level so behaviour is unchanged.
430
+ levels[action.id] = level;
431
+ }
432
+ if (action.approveIf)
433
+ approveWhen[action.id] = decompilePredicate(action.approveIf);
434
+ const limit = fieldsToLimit(action);
435
+ if (limit)
436
+ limits[action.id] = limit;
437
+ if (action.validFrom || action.validUntil) {
438
+ windows[action.id] = {
439
+ ...(action.validFrom ? { from: action.validFrom } : {}),
440
+ ...(action.validUntil ? { until: action.validUntil } : {}),
441
+ };
442
+ }
443
+ const hints = pick(action, HINT_KEYS);
444
+ if (Object.keys(hints).length > 0)
445
+ actionHints[action.id] = hints;
446
+ }
447
+ const policy = {
448
+ agents: {
449
+ access,
450
+ allow,
451
+ ...(Object.keys(levels).length > 0 ? { levels } : {}),
452
+ userConsent: permissions.requireUserConsent,
453
+ ...(permissions.consentActionScope ? { consentScope: permissions.consentActionScope } : {}),
454
+ ...(permissions.validFrom ? { validFrom: permissions.validFrom } : {}),
455
+ ...(permissions.validUntil ? { validUntil: permissions.validUntil } : {}),
456
+ },
457
+ ...(Object.keys(approveWhen).length > 0 ? { approveWhen } : {}),
458
+ ...(Object.keys(limits).length > 0 ? { limits } : {}),
459
+ ...(Object.keys(windows).length > 0 ? { windows } : {}),
460
+ ...(config.approval?.stepUp || config.operatorNotifications
461
+ ? {
462
+ approvers: {
463
+ ...(config.operatorNotifications?.approverEmails?.length
464
+ ? { emails: config.operatorNotifications.approverEmails }
465
+ : {}),
466
+ ...(config.operatorNotifications?.confirmationReminderLeadMinutes !== undefined
467
+ ? { reminderLeadMinutes: config.operatorNotifications.confirmationReminderLeadMinutes }
468
+ : {}),
469
+ ...(config.approval?.stepUp ? { stepUp: config.approval.stepUp } : {}),
470
+ },
471
+ }
472
+ : {}),
473
+ };
474
+ const network = {
475
+ ...(config.registry_visibility && config.registry_visibility !== "private"
476
+ ? { registry_visibility: config.registry_visibility }
477
+ : {}),
478
+ ...(config.intershell_enabled ? { intershell_enabled: true } : {}),
479
+ ...(permissions.allowedCallers?.length ? { allowedCallers: permissions.allowedCallers } : {}),
480
+ ...(permissions.allowedCallees?.length ? { allowedCallees: permissions.allowedCallees } : {}),
481
+ };
482
+ const project = {
483
+ shellId: config.shellId,
484
+ product: config.product,
485
+ auth: config.auth,
486
+ ...(config.webhooks ? { webhooks: config.webhooks } : {}),
487
+ ...(Object.keys(network).length > 0 ? { network } : {}),
488
+ };
489
+ const capabilities = {
490
+ version: 1,
491
+ source: { kind: "imported", location: "duct.config.ts", syncedAt: new Date().toISOString() },
492
+ actions: config.actions.map((action) => pick(action, CAPABILITY_KEYS)),
493
+ };
494
+ const hasShell = (config.routes?.length ?? 0) > 0 ||
495
+ (config.deeplinks?.length ?? 0) > 0 ||
496
+ Boolean(config.widget) ||
497
+ Boolean(config.dataModel) ||
498
+ Object.keys(actionHints).length > 0;
499
+ const shell = hasShell
500
+ ? {
501
+ ...(config.widget ? { widget: config.widget } : {}),
502
+ routes: config.routes ?? [],
503
+ deeplinks: config.deeplinks ?? [],
504
+ ...(config.dataModel ? { dataModel: config.dataModel } : {}),
505
+ ...(Object.keys(actionHints).length > 0 ? { actionHints } : {}),
506
+ }
507
+ : null;
508
+ if (allowedActions) {
509
+ warnings.push("agentPermissions.allowedActions was folded into policy.agents.allow");
510
+ }
511
+ return { project, capabilities, policy, shell, warnings };
512
+ }