@duct-sdk/sdk 0.1.7 → 0.1.13

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 (58) hide show
  1. package/README.md +3 -3
  2. package/dist/adapters/next/index.d.ts +1 -1
  3. package/dist/adapters/next/shell.d.ts +55 -1
  4. package/dist/adapters/next/shell.js +100 -17
  5. package/dist/adapters/react/index.d.ts +5 -1
  6. package/dist/adapters/react/index.js +2 -0
  7. package/dist/adapters/react/shell.d.ts +61 -1
  8. package/dist/adapters/react/shell.js +110 -16
  9. package/dist/adapters/react/use-page-context.d.ts +32 -0
  10. package/dist/adapters/react/use-page-context.js +99 -0
  11. package/dist/cli/agents/api-agent.d.ts +9 -3
  12. package/dist/cli/agents/api-agent.js +163 -69
  13. package/dist/cli/agents/auth-agent.d.ts +2 -1
  14. package/dist/cli/agents/auth-agent.js +38 -24
  15. package/dist/cli/agents/deeplink-agent.js +71 -49
  16. package/dist/cli/agents/llm.d.ts +1 -1
  17. package/dist/cli/agents/llm.js +48 -15
  18. package/dist/cli/agents/pipeline.d.ts +16 -0
  19. package/dist/cli/agents/pipeline.js +18 -5
  20. package/dist/cli/agents/reviewer-agent.js +46 -46
  21. package/dist/cli/agents/route-agent.d.ts +3 -1
  22. package/dist/cli/agents/route-agent.js +70 -44
  23. package/dist/cli/detectors/topology.d.ts +26 -0
  24. package/dist/cli/detectors/topology.js +310 -0
  25. package/dist/cli/drift.d.ts +11 -0
  26. package/dist/cli/drift.js +147 -2
  27. package/dist/cli/fs/sandbox.d.ts +2 -0
  28. package/dist/cli/fs/sandbox.js +22 -8
  29. package/dist/cli/generators/config.d.ts +13 -0
  30. package/dist/cli/generators/config.js +200 -50
  31. package/dist/cli/generators/receiver.js +728 -601
  32. package/dist/cli/generators/shell.js +532 -490
  33. package/dist/cli/index.js +502 -19
  34. package/dist/cli/init.d.ts +11 -1
  35. package/dist/cli/init.js +367 -31
  36. package/dist/cli/processors/postprocess.d.ts +22 -0
  37. package/dist/cli/processors/postprocess.js +107 -0
  38. package/dist/cli/processors/prisma-parser.d.ts +35 -0
  39. package/dist/cli/processors/prisma-parser.js +117 -0
  40. package/dist/cli/processors/zod-extractor.d.ts +27 -0
  41. package/dist/cli/processors/zod-extractor.js +153 -0
  42. package/dist/cli/prompts/review.d.ts +32 -0
  43. package/dist/cli/prompts/review.js +240 -0
  44. package/dist/cli/selectors/index.d.ts +22 -0
  45. package/dist/cli/selectors/index.js +274 -0
  46. package/dist/core/config.d.ts +18 -18
  47. package/dist/core/endpoints.d.ts +1 -0
  48. package/dist/core/endpoints.js +4 -0
  49. package/dist/core/introspect.d.ts +47 -0
  50. package/dist/core/introspect.js +94 -0
  51. package/dist/core/status.d.ts +39 -0
  52. package/dist/core/status.js +40 -0
  53. package/dist/core/token.d.ts +36 -1
  54. package/dist/core/token.js +43 -2
  55. package/dist/core/types.d.ts +114 -0
  56. package/dist/index.d.ts +9 -2
  57. package/dist/index.js +6 -1
  58. package/package.json +84 -84
@@ -0,0 +1,274 @@
1
+ // ============================================================
2
+ // @duct/sdk — Targeted File Selection
3
+ // Builds a bounded ReadList per agent from a TopoResult.
4
+ // No LLM. Max MAX_FILES_PER_LIST files per agent list.
5
+ // ============================================================
6
+ const MAX_FILES_PER_LIST = 30;
7
+ // ----------------------------------------------------------------
8
+ // Ranking helpers
9
+ // ----------------------------------------------------------------
10
+ async function rankFiles(paths, sandboxFs) {
11
+ const ranked = [];
12
+ for (const p of paths) {
13
+ try {
14
+ const content = await sandboxFs.readFile(p);
15
+ ranked.push({ path: p, sizeBytes: content?.length ?? 0 });
16
+ }
17
+ catch {
18
+ ranked.push({ path: p, sizeBytes: 0 });
19
+ }
20
+ }
21
+ // Smaller files first (more focused); stable for equal sizes
22
+ return ranked.sort((a, b) => a.sizeBytes - b.sizeBytes);
23
+ }
24
+ async function selectTop(paths, sandboxFs, limit = MAX_FILES_PER_LIST) {
25
+ if (paths.length <= limit)
26
+ return paths;
27
+ const ranked = await rankFiles(paths, sandboxFs);
28
+ const selected = ranked.slice(0, limit).map((r) => r.path);
29
+ console.error(`[duct/selectors] Trimmed ${paths.length} → ${selected.length} files (cap: ${limit})`);
30
+ return selected;
31
+ }
32
+ // ----------------------------------------------------------------
33
+ // Auth files — common across frameworks
34
+ // ----------------------------------------------------------------
35
+ const AUTH_CANDIDATES = [
36
+ "middleware.ts",
37
+ "middleware.js",
38
+ "src/middleware.ts",
39
+ "src/middleware.js",
40
+ "auth.ts",
41
+ "auth.js",
42
+ "auth.config.ts",
43
+ "auth.config.js",
44
+ // NextAuth
45
+ "pages/api/auth/[...nextauth].ts",
46
+ "pages/api/auth/[...nextauth].js",
47
+ "app/api/auth/[...nextauth]/route.ts",
48
+ "src/app/api/auth/[...nextauth]/route.ts",
49
+ // Env examples
50
+ ".env.example",
51
+ ".env.local.example",
52
+ ".env.sample",
53
+ ".env.template",
54
+ // Clerk
55
+ "clerk.config.ts",
56
+ "clerk.config.js",
57
+ "src/lib/clerk.ts",
58
+ "lib/clerk.ts",
59
+ ];
60
+ async function collectAuthFiles(sandboxFs) {
61
+ const found = [];
62
+ for (const candidate of AUTH_CANDIDATES) {
63
+ if (await sandboxFs.exists(candidate)) {
64
+ found.push(candidate);
65
+ }
66
+ }
67
+ return found;
68
+ }
69
+ // ----------------------------------------------------------------
70
+ // Next.js App Router strategy
71
+ // ----------------------------------------------------------------
72
+ async function selectNextApp(sandboxFs) {
73
+ const routeDir = (await sandboxFs.exists("src/app")) ? "src/app" : "app";
74
+ const pageFiles = await sandboxFs.findFiles(`${routeDir}/**/page.{ts,tsx,js,jsx}`);
75
+ const layoutFiles = await sandboxFs.findFiles(`${routeDir}/**/layout.{ts,tsx,js,jsx}`);
76
+ const apiDir = `${routeDir}/api`;
77
+ const apiRouteFiles = await sandboxFs.findFiles(`${apiDir}/**/route.{ts,tsx,js}`);
78
+ // Also grab root middleware
79
+ const authFiles = await collectAuthFiles(sandboxFs);
80
+ return {
81
+ routeFiles: await selectTop([...pageFiles, ...layoutFiles.slice(0, 5)], sandboxFs),
82
+ apiFiles: await selectTop(apiRouteFiles, sandboxFs),
83
+ authFiles: await selectTop(authFiles, sandboxFs),
84
+ };
85
+ }
86
+ // ----------------------------------------------------------------
87
+ // Next.js Pages Router strategy
88
+ // ----------------------------------------------------------------
89
+ async function selectNextPages(sandboxFs) {
90
+ const pagesDir = (await sandboxFs.exists("src/pages")) ? "src/pages" : "pages";
91
+ const allPageFiles = await sandboxFs.findFiles(`${pagesDir}/**/*.{ts,tsx,js,jsx}`);
92
+ const pageFiles = allPageFiles.filter((f) => !f.includes("/api/") &&
93
+ !f.includes("_app") &&
94
+ !f.includes("_document") &&
95
+ !f.includes("_error"));
96
+ const apiFiles = allPageFiles.filter((f) => f.includes("/api/"));
97
+ const authFiles = await collectAuthFiles(sandboxFs);
98
+ return {
99
+ routeFiles: await selectTop(pageFiles, sandboxFs),
100
+ apiFiles: await selectTop(apiFiles, sandboxFs),
101
+ authFiles: await selectTop(authFiles, sandboxFs),
102
+ };
103
+ }
104
+ // ----------------------------------------------------------------
105
+ // Remix strategy
106
+ // ----------------------------------------------------------------
107
+ async function selectRemix(sandboxFs) {
108
+ const routeFiles = await sandboxFs.findFiles("app/routes/**/*.{ts,tsx,js,jsx}");
109
+ const authFiles = await collectAuthFiles(sandboxFs);
110
+ // In Remix, routes double as API endpoints via loaders/actions
111
+ return {
112
+ routeFiles: await selectTop(routeFiles, sandboxFs),
113
+ apiFiles: await selectTop(routeFiles, sandboxFs), // same files serve as API
114
+ authFiles: await selectTop(authFiles, sandboxFs),
115
+ };
116
+ }
117
+ // ----------------------------------------------------------------
118
+ // SvelteKit strategy
119
+ // ----------------------------------------------------------------
120
+ async function selectSvelteKit(sandboxFs) {
121
+ const allRouteFiles = await sandboxFs.findFiles("src/routes/**/*.{ts,js,svelte}");
122
+ const serverFiles = allRouteFiles.filter((f) => f.includes("+server") || f.includes("+page.server"));
123
+ const pageFiles = allRouteFiles.filter((f) => f.includes("+page.svelte") || f.includes("+page.ts"));
124
+ const authFiles = await collectAuthFiles(sandboxFs);
125
+ return {
126
+ routeFiles: await selectTop(pageFiles, sandboxFs),
127
+ apiFiles: await selectTop(serverFiles, sandboxFs),
128
+ authFiles: await selectTop(authFiles, sandboxFs),
129
+ };
130
+ }
131
+ // ----------------------------------------------------------------
132
+ // Nuxt strategy
133
+ // ----------------------------------------------------------------
134
+ async function selectNuxt(sandboxFs) {
135
+ const pageFiles = await sandboxFs.findFiles("pages/**/*.{vue,ts,js}");
136
+ const serverApiFiles = await sandboxFs.findFiles("server/api/**/*.{ts,js}");
137
+ const serverRouteFiles = await sandboxFs.findFiles("server/routes/**/*.{ts,js}");
138
+ const authFiles = await collectAuthFiles(sandboxFs);
139
+ return {
140
+ routeFiles: await selectTop(pageFiles, sandboxFs),
141
+ apiFiles: await selectTop([...serverApiFiles, ...serverRouteFiles], sandboxFs),
142
+ authFiles: await selectTop(authFiles, sandboxFs),
143
+ };
144
+ }
145
+ // ----------------------------------------------------------------
146
+ // Express / Fastify strategy (JS/TS backend)
147
+ // ----------------------------------------------------------------
148
+ async function selectExpressLike(sandboxFs, apiRoot) {
149
+ const routeDirs = ["routes", "api", "controllers", "handlers", "endpoints", apiRoot];
150
+ const gathered = [];
151
+ for (const dir of [...new Set(routeDirs)]) {
152
+ if (!(await sandboxFs.exists(dir)))
153
+ continue;
154
+ const files = await sandboxFs.findFiles(`${dir}/**/*.{ts,js}`);
155
+ gathered.push(...files);
156
+ }
157
+ // Fallback: any file with URL patterns
158
+ if (gathered.length === 0) {
159
+ const allTs = await sandboxFs.findFiles("src/**/*.{ts,js}");
160
+ for (const f of allTs) {
161
+ const content = await sandboxFs.readFile(f);
162
+ if (!content)
163
+ continue;
164
+ if (/["'`]\/api\//.test(content) ||
165
+ /["'`]\/v\d\//.test(content) ||
166
+ /\(req,\s*res\)|request:\s*Request/.test(content) ||
167
+ /router\.(get|post|put|patch|delete)\(/.test(content)) {
168
+ gathered.push(f);
169
+ }
170
+ }
171
+ }
172
+ const authFiles = await collectAuthFiles(sandboxFs);
173
+ return {
174
+ routeFiles: [], // Express doesn't have separate route files
175
+ apiFiles: await selectTop([...new Set(gathered)], sandboxFs),
176
+ authFiles: await selectTop(authFiles, sandboxFs),
177
+ };
178
+ }
179
+ // ----------------------------------------------------------------
180
+ // FastAPI / Django strategy (Python)
181
+ // ----------------------------------------------------------------
182
+ async function selectPython(sandboxFs) {
183
+ const gathered = [];
184
+ // FastAPI: files with @router.{get,post,...} decorator
185
+ const pyFiles = await sandboxFs.findFiles("**/*.py");
186
+ for (const f of pyFiles) {
187
+ const content = await sandboxFs.readFile(f);
188
+ if (!content)
189
+ continue;
190
+ if (/@(router|app)\.(get|post|put|patch|delete)\(/.test(content) ||
191
+ f.includes("urls.py") // Django
192
+ ) {
193
+ gathered.push(f);
194
+ }
195
+ }
196
+ const authFiles = await collectAuthFiles(sandboxFs);
197
+ return {
198
+ routeFiles: [],
199
+ apiFiles: await selectTop([...new Set(gathered)], sandboxFs),
200
+ authFiles: await selectTop(authFiles, sandboxFs),
201
+ };
202
+ }
203
+ // ----------------------------------------------------------------
204
+ // Generic fallback strategy — unknown / messy codebases
205
+ // ----------------------------------------------------------------
206
+ async function selectGenericFallback(sandboxFs, apiRoot) {
207
+ const candidateDirs = ["routes", "api", "controllers", "handlers", "endpoints", apiRoot];
208
+ const gathered = [];
209
+ for (const dir of [...new Set(candidateDirs)]) {
210
+ if (!(await sandboxFs.exists(dir)))
211
+ continue;
212
+ const files = await sandboxFs.findFiles(`${dir}/**/*.{ts,tsx,js,jsx,py,rb}`);
213
+ gathered.push(...files);
214
+ }
215
+ // URL literal / handler signature fallback
216
+ if (gathered.length < MAX_FILES_PER_LIST) {
217
+ const srcFiles = await sandboxFs.findFiles("src/**/*.{ts,tsx,js,jsx}");
218
+ for (const f of srcFiles) {
219
+ if (gathered.includes(f))
220
+ continue;
221
+ const content = await sandboxFs.readFile(f);
222
+ if (!content)
223
+ continue;
224
+ if (/["'`]\/api\//.test(content) ||
225
+ /["'`]\/v\d\//.test(content) ||
226
+ /\(req,\s*res\)|request:\s*Request/.test(content)) {
227
+ gathered.push(f);
228
+ }
229
+ }
230
+ }
231
+ const authFiles = await collectAuthFiles(sandboxFs);
232
+ return {
233
+ routeFiles: [],
234
+ apiFiles: await selectTop([...new Set(gathered)], sandboxFs),
235
+ authFiles: await selectTop(authFiles, sandboxFs),
236
+ };
237
+ }
238
+ // ----------------------------------------------------------------
239
+ // buildReadList — main export
240
+ // ----------------------------------------------------------------
241
+ /**
242
+ * Build a bounded ReadList per agent from the project's topology.
243
+ *
244
+ * Given a TopoResult, builds a bounded ReadList for each agent.
245
+ * Each list is capped at MAX_FILES_PER_LIST entries, ranked by file size
246
+ * (smaller first — more focused files).
247
+ *
248
+ * Falls back to the generic strategy for unknown stacks. Generic fallback
249
+ * detections should get confidence < 0.6 automatically.
250
+ */
251
+ export async function buildReadList(topo, sandboxFs) {
252
+ switch (topo.framework) {
253
+ case "next-app":
254
+ return selectNextApp(sandboxFs);
255
+ case "next-pages":
256
+ return selectNextPages(sandboxFs);
257
+ case "remix":
258
+ return selectRemix(sandboxFs);
259
+ case "sveltekit":
260
+ return selectSvelteKit(sandboxFs);
261
+ case "nuxt":
262
+ return selectNuxt(sandboxFs);
263
+ case "vite-react":
264
+ case "vue3":
265
+ // Vite/Vue — treat like Express for API (no built-in routing), empty routes
266
+ return selectExpressLike(sandboxFs, topo.apiRoot);
267
+ default:
268
+ // Python / Ruby / Go / unknown
269
+ if (topo.language === "python") {
270
+ return selectPython(sandboxFs);
271
+ }
272
+ return selectGenericFallback(sandboxFs, topo.apiRoot);
273
+ }
274
+ }
@@ -56,13 +56,13 @@ export declare const DuctConfigSchema: z.ZodObject<{
56
56
  required: z.ZodBoolean;
57
57
  description: z.ZodOptional<z.ZodString>;
58
58
  }, "strip", z.ZodTypeAny, {
59
- name: string;
60
59
  type: "string" | "number" | "uuid" | "slug";
60
+ name: string;
61
61
  required: boolean;
62
62
  description?: string | undefined;
63
63
  }, {
64
- name: string;
65
64
  type: "string" | "number" | "uuid" | "slug";
65
+ name: string;
66
66
  required: boolean;
67
67
  description?: string | undefined;
68
68
  }>, "many">>;
@@ -73,14 +73,14 @@ export declare const DuctConfigSchema: z.ZodObject<{
73
73
  description: z.ZodOptional<z.ZodString>;
74
74
  defaultValue: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
75
75
  }, "strip", z.ZodTypeAny, {
76
- name: string;
77
76
  type: "string" | "number" | "boolean" | "string[]";
77
+ name: string;
78
78
  required: boolean;
79
79
  description?: string | undefined;
80
80
  defaultValue?: string | number | boolean | undefined;
81
81
  }, {
82
- name: string;
83
82
  type: "string" | "number" | "boolean" | "string[]";
83
+ name: string;
84
84
  required: boolean;
85
85
  description?: string | undefined;
86
86
  defaultValue?: string | number | boolean | undefined;
@@ -92,16 +92,16 @@ export declare const DuctConfigSchema: z.ZodObject<{
92
92
  }, "strip", z.ZodTypeAny, {
93
93
  name: string;
94
94
  params: {
95
- name: string;
96
95
  type: "string" | "number" | "uuid" | "slug";
96
+ name: string;
97
97
  required: boolean;
98
98
  description?: string | undefined;
99
99
  }[];
100
100
  path: string;
101
101
  description: string;
102
102
  queryParams: {
103
- name: string;
104
103
  type: "string" | "number" | "boolean" | "string[]";
104
+ name: string;
105
105
  required: boolean;
106
106
  description?: string | undefined;
107
107
  defaultValue?: string | number | boolean | undefined;
@@ -118,14 +118,14 @@ export declare const DuctConfigSchema: z.ZodObject<{
118
118
  requiresAuth: boolean;
119
119
  deeplinkable: boolean;
120
120
  params?: {
121
- name: string;
122
121
  type: "string" | "number" | "uuid" | "slug";
122
+ name: string;
123
123
  required: boolean;
124
124
  description?: string | undefined;
125
125
  }[] | undefined;
126
126
  queryParams?: {
127
- name: string;
128
127
  type: "string" | "number" | "boolean" | "string[]";
128
+ name: string;
129
129
  required: boolean;
130
130
  description?: string | undefined;
131
131
  defaultValue?: string | number | boolean | undefined;
@@ -148,14 +148,14 @@ export declare const DuctConfigSchema: z.ZodObject<{
148
148
  description: z.ZodOptional<z.ZodString>;
149
149
  schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
150
150
  }, "strip", z.ZodTypeAny, {
151
- name: string;
152
151
  type: "string" | "number" | "boolean" | "object" | "array";
152
+ name: string;
153
153
  required: boolean;
154
154
  description?: string | undefined;
155
155
  schema?: Record<string, unknown> | undefined;
156
156
  }, {
157
- name: string;
158
157
  type: "string" | "number" | "boolean" | "object" | "array";
158
+ name: string;
159
159
  required: boolean;
160
160
  description?: string | undefined;
161
161
  schema?: Record<string, unknown> | undefined;
@@ -167,8 +167,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
167
167
  id: string;
168
168
  name: string;
169
169
  params: {
170
- name: string;
171
170
  type: "string" | "number" | "boolean" | "object" | "array";
171
+ name: string;
172
172
  required: boolean;
173
173
  description?: string | undefined;
174
174
  schema?: Record<string, unknown> | undefined;
@@ -193,8 +193,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
193
193
  sideEffects: boolean;
194
194
  sensitivityLevel: "none" | "low" | "medium" | "high" | "critical";
195
195
  params?: {
196
- name: string;
197
196
  type: "string" | "number" | "boolean" | "object" | "array";
197
+ name: string;
198
198
  required: boolean;
199
199
  description?: string | undefined;
200
200
  schema?: Record<string, unknown> | undefined;
@@ -322,16 +322,16 @@ export declare const DuctConfigSchema: z.ZodObject<{
322
322
  routes: {
323
323
  name: string;
324
324
  params: {
325
- name: string;
326
325
  type: "string" | "number" | "uuid" | "slug";
326
+ name: string;
327
327
  required: boolean;
328
328
  description?: string | undefined;
329
329
  }[];
330
330
  path: string;
331
331
  description: string;
332
332
  queryParams: {
333
- name: string;
334
333
  type: "string" | "number" | "boolean" | "string[]";
334
+ name: string;
335
335
  required: boolean;
336
336
  description?: string | undefined;
337
337
  defaultValue?: string | number | boolean | undefined;
@@ -345,8 +345,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
345
345
  id: string;
346
346
  name: string;
347
347
  params: {
348
- name: string;
349
348
  type: "string" | "number" | "boolean" | "object" | "array";
349
+ name: string;
350
350
  required: boolean;
351
351
  description?: string | undefined;
352
352
  schema?: Record<string, unknown> | undefined;
@@ -425,14 +425,14 @@ export declare const DuctConfigSchema: z.ZodObject<{
425
425
  requiresAuth: boolean;
426
426
  deeplinkable: boolean;
427
427
  params?: {
428
- name: string;
429
428
  type: "string" | "number" | "uuid" | "slug";
429
+ name: string;
430
430
  required: boolean;
431
431
  description?: string | undefined;
432
432
  }[] | undefined;
433
433
  queryParams?: {
434
- name: string;
435
434
  type: "string" | "number" | "boolean" | "string[]";
435
+ name: string;
436
436
  required: boolean;
437
437
  description?: string | undefined;
438
438
  defaultValue?: string | number | boolean | undefined;
@@ -450,8 +450,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
450
450
  sideEffects: boolean;
451
451
  sensitivityLevel: "none" | "low" | "medium" | "high" | "critical";
452
452
  params?: {
453
- name: string;
454
453
  type: "string" | "number" | "boolean" | "object" | "array";
454
+ name: string;
455
455
  required: boolean;
456
456
  description?: string | undefined;
457
457
  schema?: Record<string, unknown> | undefined;
@@ -4,6 +4,7 @@ export interface EndpointProfile {
4
4
  }
5
5
  export declare function getAuthUrl(): string;
6
6
  export declare function getActiveApiBase(profile?: EndpointProfile | null): string;
7
+ export declare function getActiveAuthBase(profile?: EndpointProfile | null): string;
7
8
  export declare function getManifestApiBase(profile?: EndpointProfile | null): string;
8
9
  export declare function getShellRuntimeUrl(): string;
9
10
  export declare function getRegistryUrl(): string;
@@ -80,6 +80,10 @@ export function getActiveApiBase(profile) {
80
80
  const candidates = getManifestApiBases(profile);
81
81
  return candidates[0] ?? "http://localhost:3002";
82
82
  }
83
+ export function getActiveAuthBase(profile) {
84
+ const candidates = getCandidateAuthBases(profile);
85
+ return candidates[0] ?? "http://localhost:3001";
86
+ }
83
87
  export function getManifestApiBase(profile) {
84
88
  // Manifest lives in agent-proxy — same as the API base
85
89
  const bases = getManifestApiBases(profile);
@@ -0,0 +1,47 @@
1
+ export interface IntrospectEntity {
2
+ /** Entity type name (e.g. "Order", "User"). Must match DataModelEntity.id. */
3
+ name: string;
4
+ /** Total count of entities available for this user/session. */
5
+ count: number;
6
+ /** Optional sample values — used by shell to ground entity resolution. */
7
+ samples?: string[];
8
+ /** ISO 8601 timestamp of last data change. Used for cache invalidation. */
9
+ updatedAt?: string;
10
+ }
11
+ export interface IntrospectResult {
12
+ entities: IntrospectEntity[];
13
+ }
14
+ export interface IntrospectContext {
15
+ /** HTTP request headers (e.g. Authorization) — available in the resolver. */
16
+ headers: Record<string, string | string[] | undefined>;
17
+ /** URL search params from the request. */
18
+ searchParams: Record<string, string>;
19
+ }
20
+ /** Resolver function the company provides — returns entity availability for the current session. */
21
+ export type IntrospectResolver = (ctx: IntrospectContext) => Promise<IntrospectResult>;
22
+ export interface IntrospectHandlerOptions {
23
+ /** TTL for Cache-Control header in seconds. Default: 300 (5 minutes). */
24
+ cacheTtlSeconds?: number;
25
+ /** If true, sets Cache-Control: no-store (disables caching). Default: false. */
26
+ noCache?: boolean;
27
+ }
28
+ export declare function createIntrospectHandler(resolver: IntrospectResolver, options?: IntrospectHandlerOptions): (req: Request) => Promise<Response>;
29
+ export declare function createIntrospectPageHandler(resolver: IntrospectResolver, options?: IntrospectHandlerOptions): (req: {
30
+ headers: Record<string, string | string[]>;
31
+ query: Record<string, string | string[]>;
32
+ }, res: {
33
+ status: (code: number) => {
34
+ json: (body: unknown) => void;
35
+ };
36
+ setHeader: (name: string, value: string) => void;
37
+ }) => Promise<void>;
38
+ export declare function createIntrospectExpressHandler(resolver: IntrospectResolver, options?: IntrospectHandlerOptions): (req: {
39
+ headers: Record<string, string | string[] | undefined>;
40
+ query: Record<string, string | string[]>;
41
+ }, res: {
42
+ status: (code: number) => {
43
+ json: (body: unknown) => void;
44
+ };
45
+ setHeader: (name: string, value: string) => void;
46
+ json: (body: unknown) => void;
47
+ }) => Promise<void>;
@@ -0,0 +1,94 @@
1
+ // ============================================================
2
+ // @duct/sdk — /duct/introspect handler factory
3
+ // Provides framework-specific helpers for companies to implement
4
+ // the GET /duct/introspect endpoint.
5
+ //
6
+ // Contract:
7
+ // GET /duct/introspect
8
+ // → { entities: [{ name, count, samples?, updatedAt? }] }
9
+ //
10
+ // Companies pass a resolver function that returns entity counts/samples.
11
+ // The handler adds caching headers and formats the response.
12
+ // ============================================================
13
+ // ----------------------------------------------------------------
14
+ // Core handler — framework-agnostic logic
15
+ // ----------------------------------------------------------------
16
+ async function runResolver(resolver, ctx, options) {
17
+ const ttl = options.cacheTtlSeconds ?? 300;
18
+ const cacheControl = options.noCache
19
+ ? "no-store"
20
+ : `public, max-age=${ttl}, stale-while-revalidate=60`;
21
+ try {
22
+ const result = await resolver(ctx);
23
+ return {
24
+ body: result,
25
+ headers: { "Cache-Control": cacheControl, "Content-Type": "application/json" },
26
+ status: 200,
27
+ };
28
+ }
29
+ catch (err) {
30
+ const message = err instanceof Error ? err.message : "Internal resolver error";
31
+ return {
32
+ body: { entities: [] },
33
+ headers: { "Cache-Control": "no-store", "Content-Type": "application/json" },
34
+ status: 500,
35
+ };
36
+ void message;
37
+ }
38
+ }
39
+ function headersToRecord(headers) {
40
+ const out = {};
41
+ headers.forEach((value, key) => { out[key] = value; });
42
+ return out;
43
+ }
44
+ // ----------------------------------------------------------------
45
+ // Next.js App Router handler
46
+ // Usage: export const GET = createIntrospectHandler(resolver)
47
+ // ----------------------------------------------------------------
48
+ export function createIntrospectHandler(resolver, options = {}) {
49
+ return async (req) => {
50
+ const url = new URL(req.url);
51
+ const searchParams = {};
52
+ url.searchParams.forEach((v, k) => { searchParams[k] = v; });
53
+ const ctx = {
54
+ headers: headersToRecord(req.headers),
55
+ searchParams,
56
+ };
57
+ const { body, headers, status } = await runResolver(resolver, ctx, options);
58
+ return new Response(JSON.stringify(body), { status, headers });
59
+ };
60
+ }
61
+ // ----------------------------------------------------------------
62
+ // Next.js Pages Router handler
63
+ // Usage: export default createIntrospectPageHandler(resolver)
64
+ // ----------------------------------------------------------------
65
+ export function createIntrospectPageHandler(resolver, options = {}) {
66
+ return async (req, res) => {
67
+ const ctx = {
68
+ headers: req.headers,
69
+ searchParams: Object.fromEntries(Object.entries(req.query).map(([k, v]) => [k, Array.isArray(v) ? v[0] ?? "" : v])),
70
+ };
71
+ const { body, headers, status } = await runResolver(resolver, ctx, options);
72
+ for (const [key, value] of Object.entries(headers)) {
73
+ res.setHeader(key, value);
74
+ }
75
+ res.status(status).json(body);
76
+ };
77
+ }
78
+ // ----------------------------------------------------------------
79
+ // Express/Fastify handler factory
80
+ // Usage: app.get('/duct/introspect', createIntrospectExpressHandler(resolver))
81
+ // ----------------------------------------------------------------
82
+ export function createIntrospectExpressHandler(resolver, options = {}) {
83
+ return async (req, res) => {
84
+ const ctx = {
85
+ headers: req.headers,
86
+ searchParams: Object.fromEntries(Object.entries(req.query).map(([k, v]) => [k, Array.isArray(v) ? v[0] ?? "" : v])),
87
+ };
88
+ const { body, headers, status } = await runResolver(resolver, ctx, options);
89
+ for (const [key, value] of Object.entries(headers)) {
90
+ res.setHeader(key, value);
91
+ }
92
+ res.status(status).json(body);
93
+ };
94
+ }
@@ -0,0 +1,39 @@
1
+ export interface ShellStatusWidget {
2
+ welcomeMessage?: string;
3
+ placeholder?: string;
4
+ theme?: string;
5
+ primaryColor?: string;
6
+ width?: number | string;
7
+ height?: number | string;
8
+ }
9
+ export interface ShellStatus {
10
+ shellId: string;
11
+ /** "live" = active + manifest pushed. "not_ready" = active, no manifest yet. "suspended" = admin suspended. */
12
+ status: 'live' | 'not_ready' | 'suspended';
13
+ manifestReady: boolean;
14
+ widget?: ShellStatusWidget;
15
+ }
16
+ export interface CheckShellStatusOptions {
17
+ /**
18
+ * Override the agent proxy base URL.
19
+ * Defaults to DUCT_AGENT_PROXY_URL env var → https://api.duct.sh
20
+ */
21
+ agentProxyUrl?: string;
22
+ /** Fetch timeout in milliseconds. Defaults to 5000. */
23
+ timeoutMs?: number;
24
+ }
25
+ /**
26
+ * Server-side function to check whether a shell is live before rendering DuctShell.
27
+ *
28
+ * Use in RSC, middleware, or getServerSideProps — not in a browser context.
29
+ * Fails open: returns `status: 'live'` on network error so the shell is
30
+ * never silently hidden due to a transient proxy issue.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * // app/layout.tsx (RSC)
35
+ * const status = await checkShellStatus(process.env.DUCT_SHELL_ID!);
36
+ * if (status.status !== 'live') return null; // skip rendering shell
37
+ * ```
38
+ */
39
+ export declare function checkShellStatus(shellId: string, options?: CheckShellStatusOptions): Promise<ShellStatus>;
@@ -0,0 +1,40 @@
1
+ // ============================================================
2
+ // @duct/sdk — Shell Status Check (server-side)
3
+ // ============================================================
4
+ /**
5
+ * Server-side function to check whether a shell is live before rendering DuctShell.
6
+ *
7
+ * Use in RSC, middleware, or getServerSideProps — not in a browser context.
8
+ * Fails open: returns `status: 'live'` on network error so the shell is
9
+ * never silently hidden due to a transient proxy issue.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * // app/layout.tsx (RSC)
14
+ * const status = await checkShellStatus(process.env.DUCT_SHELL_ID!);
15
+ * if (status.status !== 'live') return null; // skip rendering shell
16
+ * ```
17
+ */
18
+ export async function checkShellStatus(shellId, options = {}) {
19
+ const base = options.agentProxyUrl ??
20
+ (typeof process !== 'undefined' ? process.env?.['DUCT_AGENT_PROXY_URL'] : undefined) ??
21
+ 'https://api.duct.sh';
22
+ const url = `${base.replace(/\/$/, '')}/v1/shells/${shellId}/status`;
23
+ const controller = new AbortController();
24
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 5000);
25
+ try {
26
+ const res = await fetch(url, { signal: controller.signal });
27
+ if (!res.ok) {
28
+ // Non-2xx — treat as not_ready rather than crashing
29
+ return { shellId, status: 'not_ready', manifestReady: false };
30
+ }
31
+ return (await res.json());
32
+ }
33
+ catch {
34
+ // Network / timeout — fail open so shell renders anyway
35
+ return { shellId, status: 'live', manifestReady: true };
36
+ }
37
+ finally {
38
+ clearTimeout(timer);
39
+ }
40
+ }