@duct-sdk/sdk 0.3.6 → 0.3.8

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 CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.3.8] — 2026-06-11
6
+
7
+ ### Fixed
8
+ - **Smoother shell drag** — bubble and panel drags batch position updates to one React commit per animation frame, attach move listeners synchronously on pointer down, use pointer capture, and disable panel `transform` while dragging.
9
+
10
+ ## [0.3.7] — 2026-06-11
11
+
12
+ ### Added
13
+ - `@duct-sdk/sdk/server` exports `sendIntershellAction` and `sendIntershellQuery` — thin cross-shell client with consent retry (IS-29)
14
+
5
15
  ## [0.3.6] — 2026-06-10
6
16
 
7
17
  ### Fixed
@@ -121,6 +121,29 @@ function clampPanel(x, y, width, height) {
121
121
  y: Math.min(Math.max(margin, y), Math.max(margin, maxY)),
122
122
  };
123
123
  }
124
+ /** Coalesce high-frequency pointer moves to one React update per animation frame. */
125
+ function scheduleRafUpdate(rafRef, pendingRef, pos, commit) {
126
+ pendingRef.current = pos;
127
+ if (rafRef.current)
128
+ return;
129
+ rafRef.current = requestAnimationFrame(() => {
130
+ rafRef.current = 0;
131
+ const next = pendingRef.current;
132
+ if (next)
133
+ commit(next);
134
+ });
135
+ }
136
+ function cancelRafUpdate(rafRef, pendingRef, commit) {
137
+ if (rafRef.current) {
138
+ cancelAnimationFrame(rafRef.current);
139
+ rafRef.current = 0;
140
+ }
141
+ const next = pendingRef.current;
142
+ pendingRef.current = null;
143
+ if (next)
144
+ commit(next);
145
+ return next;
146
+ }
124
147
  /**
125
148
  * DuctShell — a self-contained floating launcher button + chat panel.
126
149
  *
@@ -162,6 +185,10 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
162
185
  const [panelPos, setPanelPos] = useState(null);
163
186
  const [isPanelDragging, setIsPanelDragging] = useState(false);
164
187
  const panelDragState = useRef(null);
188
+ const bubbleDragRaf = useRef(0);
189
+ const bubbleDragPending = useRef(null);
190
+ const panelDragRaf = useRef(0);
191
+ const panelDragPending = useRef(null);
165
192
  // Resolve theme for the launcher chrome (light/dark surface).
166
193
  const [isDarkChrome, setIsDarkChrome] = useState(theme === "dark");
167
194
  // Shell liveness — only checked when readyCheck=true
@@ -388,34 +415,16 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
388
415
  }
389
416
  catch { /* ignore corrupt storage */ }
390
417
  }, [shellId, draggable]);
391
- // Free-drag the open panel using a top handle. The handle sits outside the
392
- // iframe so dragging works without relying on iframe internals.
393
- useEffect(() => {
394
- if (!isPanelDragging)
395
- return;
396
- const onMove = (e) => {
397
- const st = panelDragState.current;
398
- if (!st)
399
- return;
400
- setPanelPos(clampPanel(e.clientX - st.dx, e.clientY - st.dy, st.width, st.height));
401
- };
402
- const onUp = () => {
403
- setIsPanelDragging(false);
404
- panelDragState.current = null;
405
- };
406
- window.addEventListener("pointermove", onMove);
407
- window.addEventListener("pointerup", onUp);
408
- return () => {
409
- window.removeEventListener("pointermove", onMove);
410
- window.removeEventListener("pointerup", onUp);
411
- };
412
- }, [isPanelDragging]);
413
418
  // Launcher bubble: pointer stays default until the user actually drags (4px threshold).
414
419
  // A tap opens; a drag repositions — no separate handle or grab cursor on hover.
415
420
  const onBubblePointerDown = useCallback((e) => {
416
421
  if (!draggable)
417
422
  return;
418
- const rect = e.currentTarget.getBoundingClientRect();
423
+ e.preventDefault();
424
+ const btn = e.currentTarget;
425
+ btn.setPointerCapture(e.pointerId);
426
+ btn.style.transform = "scale(1)";
427
+ const rect = btn.getBoundingClientRect();
419
428
  const st = {
420
429
  dx: e.clientX - rect.left,
421
430
  dy: e.clientY - rect.top,
@@ -424,7 +433,10 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
424
433
  moved: false,
425
434
  };
426
435
  dragState.current = st;
427
- setBubblePos((prev) => prev ?? clampBubble(rect.left, rect.top));
436
+ const initial = clampBubble(rect.left, rect.top);
437
+ setBubblePos((prev) => prev ?? initial);
438
+ bubbleDragPending.current = initial;
439
+ const commitBubblePos = (pos) => setBubblePos(pos);
428
440
  const onMove = (ev) => {
429
441
  if (!dragState.current)
430
442
  return;
@@ -433,25 +445,30 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
433
445
  && Math.abs(ev.clientY - st.startY) <= 4) {
434
446
  return;
435
447
  }
436
- st.moved = true;
437
- setIsDragging(true);
438
- setBubblePos(clampBubble(ev.clientX - st.dx, ev.clientY - st.dy));
448
+ if (!st.moved) {
449
+ st.moved = true;
450
+ setIsDragging(true);
451
+ }
452
+ scheduleRafUpdate(bubbleDragRaf, bubbleDragPending, clampBubble(ev.clientX - st.dx, ev.clientY - st.dy), commitBubblePos);
439
453
  };
440
- const onUp = () => {
454
+ const onUp = (ev) => {
455
+ if (btn.hasPointerCapture(ev.pointerId)) {
456
+ btn.releasePointerCapture(ev.pointerId);
457
+ }
441
458
  window.removeEventListener("pointermove", onMove);
442
459
  window.removeEventListener("pointerup", onUp);
443
460
  dragState.current = null;
444
461
  setIsDragging(false);
462
+ const finalPos = cancelRafUpdate(bubbleDragRaf, bubbleDragPending, commitBubblePos);
445
463
  if (st.moved) {
446
- setBubblePos((pos) => {
447
- if (pos) {
448
- try {
449
- window.localStorage.setItem(`duct-shell-pos:${shellId}`, JSON.stringify(pos));
450
- }
451
- catch { /* ignore */ }
464
+ const pos = finalPos ?? bubbleDragPending.current;
465
+ if (pos) {
466
+ setBubblePos(pos);
467
+ try {
468
+ window.localStorage.setItem(`duct-shell-pos:${shellId}`, JSON.stringify(pos));
452
469
  }
453
- return pos;
454
- });
470
+ catch { /* ignore */ }
471
+ }
455
472
  setPanelPos(null);
456
473
  }
457
474
  else {
@@ -461,18 +478,44 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
461
478
  window.addEventListener("pointermove", onMove);
462
479
  window.addEventListener("pointerup", onUp);
463
480
  }, [draggable, openPanel, shellId]);
481
+ // Free-drag the open panel using a top handle. Listeners attach synchronously on
482
+ // pointerdown so the first move event is not dropped behind a useEffect cycle.
464
483
  const onPanelPointerDown = useCallback((e) => {
465
484
  if (!draggable || !panelRef.current)
466
485
  return;
467
- const rect = panelRef.current.getBoundingClientRect();
468
- panelDragState.current = {
486
+ e.preventDefault();
487
+ const panel = panelRef.current;
488
+ panel.setPointerCapture(e.pointerId);
489
+ const rect = panel.getBoundingClientRect();
490
+ const st = {
469
491
  dx: e.clientX - rect.left,
470
492
  dy: e.clientY - rect.top,
471
493
  width: rect.width,
472
494
  height: rect.height,
473
495
  };
474
- setPanelPos(clampPanel(rect.left, rect.top, rect.width, rect.height));
496
+ panelDragState.current = st;
497
+ const initial = clampPanel(rect.left, rect.top, rect.width, rect.height);
498
+ setPanelPos(initial);
499
+ panelDragPending.current = initial;
475
500
  setIsPanelDragging(true);
501
+ const commitPanelPos = (pos) => setPanelPos(pos);
502
+ const onMove = (ev) => {
503
+ if (!panelDragState.current)
504
+ return;
505
+ scheduleRafUpdate(panelDragRaf, panelDragPending, clampPanel(ev.clientX - st.dx, ev.clientY - st.dy, st.width, st.height), commitPanelPos);
506
+ };
507
+ const onUp = (ev) => {
508
+ if (panel.hasPointerCapture(ev.pointerId)) {
509
+ panel.releasePointerCapture(ev.pointerId);
510
+ }
511
+ window.removeEventListener("pointermove", onMove);
512
+ window.removeEventListener("pointerup", onUp);
513
+ panelDragState.current = null;
514
+ setIsPanelDragging(false);
515
+ cancelRafUpdate(panelDragRaf, panelDragPending, commitPanelPos);
516
+ };
517
+ window.addEventListener("pointermove", onMove);
518
+ window.addEventListener("pointerup", onUp);
476
519
  }, [draggable]);
477
520
  if (!shellId) {
478
521
  console.error("[DuctShell] shellId prop is required");
@@ -526,8 +569,9 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
526
569
  overflow: "hidden",
527
570
  boxShadow: "0 24px 64px rgba(0,0,0,0.18), 0 8px 24px rgba(0,0,0,0.10)",
528
571
  opacity: panelOpen && !isAnimating ? 1 : 0,
529
- transform: panelOpen && !isAnimating ? "translateY(0)" : "translateY(12px)",
572
+ transform: isPanelDragging ? "none" : panelOpen && !isAnimating ? "translateY(0)" : "translateY(12px)",
530
573
  transition: isPanelDragging ? "none" : "opacity 220ms cubic-bezier(0.16,1,0.3,1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1)",
574
+ willChange: isPanelDragging ? "left, top" : undefined,
531
575
  pointerEvents: panelOpen ? "auto" : "none",
532
576
  visibility: panelVisible ? "visible" : "hidden",
533
577
  ...style,
@@ -563,6 +607,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
563
607
  height: `${BUBBLE_SIZE}px`,
564
608
  cursor: isDragging ? "grabbing" : "pointer",
565
609
  touchAction: draggable ? "none" : undefined,
610
+ willChange: isDragging ? "left, top" : undefined,
566
611
  }, onPointerDown: draggable ? onBubblePointerDown : undefined, onClick: draggable ? undefined : () => openPanel(), "aria-label": "Open Duct Shell", className: className, onMouseEnter: (e) => {
567
612
  if (isDragging)
568
613
  return;
@@ -102,7 +102,7 @@ ${pad} sideEffects: ${action.sideEffects},
102
102
  ${pad} // sensitivityLevel controls the minimum auth required for agent access.
103
103
  ${pad} // "low" — any authenticated shell
104
104
  ${pad} // "medium" — requires user consent token
105
- ${pad} // "high" — requires user consent token + explicit allowedCallers entry
105
+ ${pad} // "high" — requires user consent token; also respects allowedCallers restriction if set
106
106
  ${pad} sensitivityLevel: ${JSON.stringify(action.sensitivityLevel)},${params}
107
107
  ${pad} requiresAuth: ${action.requiresAuth},${action.rateLimit !== undefined ? `\n${pad} rateLimit: ${action.rateLimit},` : ""}
108
108
  ${pad} }`;
@@ -157,7 +157,7 @@ function generateAgentPermissions(perms, indentSpaces) {
157
157
  lines.push(`${pad} allowedActions: ${formatStringArray(perms.allowedActions, indentSpaces + 2)},`);
158
158
  }
159
159
  if (perms.allowedCallers && perms.allowedCallers.length > 0) {
160
- lines.push(`${pad} allowedCallers: ${formatStringArray(perms.allowedCallers, indentSpaces + 2)},`);
160
+ lines.push(`${pad} // Optional restriction: when non-empty, only these shell IDs may call this shell cross-shell.`, `${pad} // Absent or empty = any public Duct shell may call (subject to intershell_enabled + registry_visibility).`, `${pad} // To block all cross-shell calls, set intershell_enabled: false instead of maintaining this list.`, `${pad} allowedCallers: ${formatStringArray(perms.allowedCallers, indentSpaces + 2)},`);
161
161
  }
162
162
  if (perms.actionOverrides && Object.keys(perms.actionOverrides).length > 0) {
163
163
  lines.push(`${pad} actionOverrides: ${jsonValue(perms.actionOverrides, indentSpaces + 2)},`);
@@ -320,6 +320,11 @@ export default defineDuctConfig({
320
320
  requireUserConsent: true,
321
321
  },
322
322
 
323
+ // Intershell network settings (both default to isolated/private)
324
+ // Set intershell_enabled: true and registry_visibility: 'public' to join the Duct open network.
325
+ // intershell_enabled: false,
326
+ // registry_visibility: 'private',
327
+
323
328
  // Shell widget appearance
324
329
  widget: {
325
330
  position: "bottom-right",
@@ -375,6 +380,12 @@ export function generateConfigFile(config) {
375
380
  `${i}// Controls what AI agents/shells can do in your shell`,
376
381
  `${i}${generateAgentPermissions(config.agentPermissions, 2)}`,
377
382
  ];
383
+ // Intershell network settings — only emit when explicitly set (non-default)
384
+ const visibility = config.registry_visibility ?? 'private';
385
+ const intershellEnabled = config.intershell_enabled ?? false;
386
+ if (visibility !== 'private' || intershellEnabled !== false) {
387
+ sections.push("", `${i}// Intershell network settings`, `${i}// intershell_enabled: master switch — allows other Duct shells to invoke this shell cross-shell.`, `${i}// registry_visibility: 'public' makes this shell discoverable in the Duct capability network.`, `${i}// Set both to true/public to join the open network; leave as defaults (false/'private') to stay isolated.`, `${i}intershell_enabled: ${intershellEnabled},`, `${i}registry_visibility: ${JSON.stringify(visibility)},`);
388
+ }
378
389
  if (config.widget) {
379
390
  sections.push("", `${i}// Shell widget display configuration`, `${i}${generateWidget(config.widget, 2)}`);
380
391
  }
package/dist/cli/index.js CHANGED
@@ -1219,6 +1219,26 @@ program
1219
1219
  }
1220
1220
  });
1221
1221
  // ----------------------------------------------------------------
1222
+ // duct migrate — migration helpers for config schema changes
1223
+ // ----------------------------------------------------------------
1224
+ const migrateCmd = program
1225
+ .command("migrate")
1226
+ .description("Migration helpers for Duct config schema changes");
1227
+ migrateCmd
1228
+ .command("intershell")
1229
+ .description("Check for allowedCallers configs that need updating for the open-network model")
1230
+ .action(async () => {
1231
+ try {
1232
+ const { runMigrateIntershell } = await import("./migrate-intershell.js");
1233
+ await runMigrateIntershell({ cwd: process.cwd() });
1234
+ }
1235
+ catch (err) {
1236
+ const message = err instanceof Error ? err.message : String(err);
1237
+ console.error(chalk.red(`\nError: ${message}\n`));
1238
+ process.exit(1);
1239
+ }
1240
+ });
1241
+ // ----------------------------------------------------------------
1222
1242
  // Error handling
1223
1243
  // ----------------------------------------------------------------
1224
1244
  program.exitOverride();
@@ -0,0 +1,3 @@
1
+ export declare function runMigrateIntershell(opts?: {
2
+ cwd?: string;
3
+ }): Promise<void>;
@@ -0,0 +1,108 @@
1
+ // ============================================================
2
+ // @duct/sdk — duct migrate intershell
3
+ // Inspects duct.config.ts for allowedCallers without intershell_enabled
4
+ // and prints guidance on the open-network migration path.
5
+ // Does NOT modify any files — developer must update manually.
6
+ // ============================================================
7
+ import * as fs from "fs/promises";
8
+ import * as path from "path";
9
+ import chalk from "chalk";
10
+ async function findConfigFile(cwd) {
11
+ for (const name of ["duct.config.ts", "duct.config.js"]) {
12
+ const candidate = path.join(cwd, name);
13
+ try {
14
+ await fs.access(candidate);
15
+ return candidate;
16
+ }
17
+ catch {
18
+ // not found — try next
19
+ }
20
+ }
21
+ return null;
22
+ }
23
+ async function inspectConfig(configPath) {
24
+ const source = await fs.readFile(configPath, "utf-8");
25
+ // Simple text-level detection — avoids needing to evaluate the file.
26
+ // Look for non-commented occurrences of the relevant keys.
27
+ const withoutComments = source
28
+ .split("\n")
29
+ .filter((line) => !line.trim().startsWith("//"))
30
+ .join("\n");
31
+ const hasAllowedCallers = /allowedCallers\s*:/.test(withoutComments);
32
+ const hasIntershellEnabled = /intershell_enabled\s*:/.test(withoutComments);
33
+ return {
34
+ configPath,
35
+ hasAllowedCallers,
36
+ hasIntershellEnabled,
37
+ needsMigration: hasAllowedCallers && !hasIntershellEnabled,
38
+ };
39
+ }
40
+ // ----------------------------------------------------------------
41
+ // runMigrateIntershell — main entry point
42
+ // ----------------------------------------------------------------
43
+ export async function runMigrateIntershell(opts = {}) {
44
+ const cwd = opts.cwd ?? process.cwd();
45
+ console.log(chalk.bold("\n ◆ Duct · migrate intershell\n"));
46
+ const configPath = await findConfigFile(cwd);
47
+ if (!configPath) {
48
+ console.log(chalk.yellow(" No duct.config.ts or duct.config.js found in the current directory.\n" +
49
+ " Run `npx duct init` first to generate your config.\n"));
50
+ return;
51
+ }
52
+ console.log(chalk.gray(` Config: ${configPath}\n`));
53
+ let result;
54
+ try {
55
+ result = await inspectConfig(configPath);
56
+ }
57
+ catch (err) {
58
+ const message = err instanceof Error ? err.message : String(err);
59
+ console.error(chalk.red(` Could not read config: ${message}\n`));
60
+ process.exit(1);
61
+ }
62
+ if (!result.hasAllowedCallers) {
63
+ console.log(chalk.green(" ✓ No allowedCallers found — no migration needed.\n\n" +
64
+ " If you want this shell to participate in the Duct open network, add:\n\n" +
65
+ chalk.cyan(" intershell_enabled: true,\n" +
66
+ " registry_visibility: 'public',\n") +
67
+ "\n to your duct.config.ts, then run `npx duct push`.\n"));
68
+ return;
69
+ }
70
+ if (result.hasIntershellEnabled) {
71
+ console.log(chalk.green(" ✓ Config has both allowedCallers and intershell_enabled — already up to date.\n\n" +
72
+ " Reminder: allowedCallers is now an optional restriction (non-empty = restrict to list).\n" +
73
+ " To open the shell to any public Duct shell, remove allowedCallers or leave it empty.\n"));
74
+ return;
75
+ }
76
+ // Needs migration: allowedCallers set, intershell_enabled missing
77
+ console.log(chalk.yellow(" ⚠ Migration notice\n\n" +
78
+ " Your config has allowedCallers but intershell_enabled is not set.\n\n" +
79
+ " In the open-network model:\n" +
80
+ " • allowedCallers is an optional restriction.\n" +
81
+ " When non-empty, only the listed shell IDs can call this shell cross-shell.\n" +
82
+ " When absent or empty, any public Duct shell may call.\n" +
83
+ " • intershell_enabled (default false) is the master on/off switch for cross-shell calls.\n" +
84
+ " If not set, cross-shell calls are disabled regardless of allowedCallers.\n\n" +
85
+ " Action required — update your duct.config.ts manually:\n"));
86
+ console.log(chalk.cyan(" Option A — Enable cross-shell calls and keep the caller restriction:\n\n" +
87
+ " agentPermissions: {\n" +
88
+ " ...\n" +
89
+ " allowedCallers: [...], // keep your existing list\n" +
90
+ " },\n" +
91
+ " intershell_enabled: true,\n" +
92
+ " registry_visibility: 'public', // or 'private' if you don't want discovery\n"));
93
+ console.log(chalk.cyan(" Option B — Enable cross-shell calls and open to all public Duct shells:\n\n" +
94
+ " agentPermissions: {\n" +
95
+ " ...\n" +
96
+ " // remove allowedCallers, or leave empty\n" +
97
+ " },\n" +
98
+ " intershell_enabled: true,\n" +
99
+ " registry_visibility: 'public',\n"));
100
+ console.log(chalk.cyan(" Option C — Disable cross-shell calls entirely (default behaviour):\n\n" +
101
+ " agentPermissions: {\n" +
102
+ " ...\n" +
103
+ " // remove allowedCallers (has no effect when intershell_enabled is false)\n" +
104
+ " },\n" +
105
+ " intershell_enabled: false, // already the default; explicit for clarity\n"));
106
+ console.log(chalk.gray(" After updating, run `npx duct push` to sync changes with Duct cloud.\n" +
107
+ " This command does not modify any files.\n"));
108
+ }
@@ -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
  /**
@@ -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
  /**
@@ -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
+ }
@@ -185,7 +185,13 @@ export interface AgentPermissions {
185
185
  defaultLevel: AgentPermissionLevel;
186
186
  /** Per-action overrides */
187
187
  actionOverrides?: Record<string, AgentPermissionLevel>;
188
- /** List of allowed agent/shell IDs */
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;
@@ -368,6 +374,10 @@ export interface DuctConfig {
368
374
  * Declare your entities now; runtime enforcement is in active development.
369
375
  */
370
376
  dataModel?: DataModel;
377
+ /** Controls whether this shell is discoverable cross-shell. Default: 'private' */
378
+ registry_visibility?: 'public' | 'private';
379
+ /** Master switch: allow other shells to call this one. Default: false */
380
+ intershell_enabled?: boolean;
371
381
  }
372
382
  export interface ShellManifest {
373
383
  shellId: string;
package/dist/server.d.ts CHANGED
@@ -6,6 +6,8 @@ export { createIntrospectHandler, createIntrospectPageHandler, createIntrospectE
6
6
  export type { IntrospectEntity, IntrospectResult, IntrospectContext, IntrospectResolver, IntrospectHandlerOptions, } from "./core/introspect.js";
7
7
  export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDeferActions, } from "./core/action.js";
8
8
  export type { ActionSearchEntry } from "./core/action.js";
9
+ export { sendIntershellAction, sendIntershellQuery } from "./core/intershell.js";
10
+ export type { IntershellClientOptions, IntershellMessage, IntershellActionResult, } from "./core/intershell.js";
9
11
  export { checkShellStatus } from "./core/status.js";
10
12
  export type { ShellStatus, ShellStatusWidget, CheckShellStatusOptions } from "./core/status.js";
11
13
  export type { DuctConfig, DuctTokenPayload, DeeplinkTokenPayload, ActionManifest, ActionParam, RouteManifest, RouteParam, QueryParam, AuthSchema, AuthStrategy, DeeplinkDefinition, StateField, ShellManifest, ProductConfig, AgentPermissions, AgentPermissionLevel, WidgetConfig, SensitivityLevel, SessionContext, DuctAdapter, ReceiverOptions, } from "./core/types.js";
package/dist/server.js CHANGED
@@ -17,5 +17,7 @@ export { generateDuctToken, verifyDuctToken, generateDeeplinkToken, verifyDeepli
17
17
  export { createIntrospectHandler, createIntrospectPageHandler, createIntrospectExpressHandler, } from "./core/introspect.js";
18
18
  // Action utilities (permission checking, search index)
19
19
  export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDeferActions, } from "./core/action.js";
20
+ // Cross-shell client (IS-29)
21
+ export { sendIntershellAction, sendIntershellQuery } from "./core/intershell.js";
20
22
  // Shell status check (server-side polling)
21
23
  export { checkShellStatus } from "./core/status.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "type": "module",
5
5
  "description": "Duct SDK — A shell (like terminal) that knows when to talk, when to show, and when to hand off.",
6
6
  "main": "dist/index.js",