@stackwright-pro/mcp 0.2.0-alpha.2 → 0.2.0-alpha.21
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/README.md +236 -0
- package/dist/integrity.d.mts +32 -0
- package/dist/integrity.d.ts +32 -0
- package/dist/integrity.js +252 -0
- package/dist/integrity.js.map +1 -0
- package/dist/integrity.mjs +224 -0
- package/dist/integrity.mjs.map +1 -0
- package/dist/server.js +2671 -353
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +2658 -340
- package/dist/server.mjs.map +1 -1
- package/package.json +9 -4
package/dist/server.js
CHANGED
|
@@ -27,15 +27,44 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
|
27
27
|
var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
28
28
|
|
|
29
29
|
// src/tools/data-explorer.ts
|
|
30
|
-
var
|
|
30
|
+
var import_zod2 = require("zod");
|
|
31
31
|
var import_cli_data_explorer = require("@stackwright-pro/cli-data-explorer");
|
|
32
|
+
|
|
33
|
+
// src/coerce.ts
|
|
34
|
+
var import_zod = require("zod");
|
|
35
|
+
function jsonCoerce(schema) {
|
|
36
|
+
return import_zod.z.preprocess((v) => {
|
|
37
|
+
if (typeof v === "string") {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(v);
|
|
40
|
+
} catch {
|
|
41
|
+
return v;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return v;
|
|
45
|
+
}, schema);
|
|
46
|
+
}
|
|
47
|
+
function boolCoerce(schema) {
|
|
48
|
+
return import_zod.z.preprocess((v) => v === "true" ? true : v === "false" ? false : v, schema);
|
|
49
|
+
}
|
|
50
|
+
function numCoerce(schema) {
|
|
51
|
+
return import_zod.z.preprocess((v) => {
|
|
52
|
+
if (typeof v === "string" && v.trim() !== "") {
|
|
53
|
+
const n = Number(v);
|
|
54
|
+
if (!Number.isNaN(n)) return n;
|
|
55
|
+
}
|
|
56
|
+
return v;
|
|
57
|
+
}, schema);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/tools/data-explorer.ts
|
|
32
61
|
function registerDataExplorerTools(server2) {
|
|
33
62
|
server2.tool(
|
|
34
63
|
"stackwright_pro_list_entities",
|
|
35
64
|
"List all available API entities from OpenAPI specs or generated Zod schemas. Use this to discover what entities are available before generating endpoint filters. Returns entity names, endpoints, and field counts. Part of the Pro Otter Raft for building API-integrated Stackwright applications.",
|
|
36
65
|
{
|
|
37
|
-
specPath:
|
|
38
|
-
projectRoot:
|
|
66
|
+
specPath: import_zod2.z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
|
|
67
|
+
projectRoot: import_zod2.z.string().optional().describe("Project root directory (auto-detected if omitted)")
|
|
39
68
|
},
|
|
40
69
|
async ({ specPath, projectRoot }) => {
|
|
41
70
|
const result = (0, import_cli_data_explorer.listEntities)({
|
|
@@ -83,9 +112,13 @@ function registerDataExplorerTools(server2) {
|
|
|
83
112
|
"stackwright_pro_generate_filter",
|
|
84
113
|
"Generate endpoint filter configuration from selected entities. Creates include/exclude patterns for stackwright.yml OpenAPI integration. Use this after stackwright_pro_list_entities to select which API endpoints the application needs. Only selected endpoints will generate client code, reducing bundle size and improving security.",
|
|
85
114
|
{
|
|
86
|
-
selectedEntities:
|
|
87
|
-
|
|
88
|
-
|
|
115
|
+
selectedEntities: jsonCoerce(import_zod2.z.array(import_zod2.z.string())).describe(
|
|
116
|
+
'Entity slugs to include (e.g., ["equipment", "supplies"])'
|
|
117
|
+
),
|
|
118
|
+
excludePatterns: jsonCoerce(import_zod2.z.array(import_zod2.z.string()).optional()).describe(
|
|
119
|
+
'Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'
|
|
120
|
+
),
|
|
121
|
+
projectRoot: import_zod2.z.string().optional().describe("Project root directory")
|
|
89
122
|
},
|
|
90
123
|
async ({ selectedEntities, excludePatterns, projectRoot }) => {
|
|
91
124
|
const result = (0, import_cli_data_explorer.generateFilter)({
|
|
@@ -141,7 +174,7 @@ function registerDataExplorerTools(server2) {
|
|
|
141
174
|
}
|
|
142
175
|
|
|
143
176
|
// src/tools/security.ts
|
|
144
|
-
var
|
|
177
|
+
var import_zod3 = require("zod");
|
|
145
178
|
var import_crypto = require("crypto");
|
|
146
179
|
var import_fs = __toESM(require("fs"));
|
|
147
180
|
var import_path = __toESM(require("path"));
|
|
@@ -150,8 +183,8 @@ function registerSecurityTools(server2) {
|
|
|
150
183
|
"stackwright_pro_validate_spec",
|
|
151
184
|
"Validate an OpenAPI spec against the enterprise approved-specs configuration. Checks if the spec URL is on the allowlist and verifies SHA-256 hash integrity. Use this in enterprise environments where only pre-approved API specs are allowed. Fails build if spec is not approved or has been modified.",
|
|
152
185
|
{
|
|
153
|
-
specPath:
|
|
154
|
-
configPath:
|
|
186
|
+
specPath: import_zod3.z.string().describe("URL or file path to the OpenAPI spec to validate"),
|
|
187
|
+
configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml with prebuild.security config")
|
|
155
188
|
},
|
|
156
189
|
async ({ specPath, configPath }) => {
|
|
157
190
|
let securityEnabled = false;
|
|
@@ -259,9 +292,9 @@ Status: Valid (${allowlist.length} specs on allowlist)`
|
|
|
259
292
|
"stackwright_pro_add_approved_spec",
|
|
260
293
|
"Add an OpenAPI spec to the approved-specs allowlist in stackwright.yml. Computes the SHA-256 hash of the spec and adds it to the security configuration. Use this when onboarding a new API in enterprise environments.",
|
|
261
294
|
{
|
|
262
|
-
name:
|
|
263
|
-
url:
|
|
264
|
-
configPath:
|
|
295
|
+
name: import_zod3.z.string().describe("Human-readable name for the spec"),
|
|
296
|
+
url: import_zod3.z.string().describe("URL or file path to the OpenAPI spec"),
|
|
297
|
+
configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
|
|
265
298
|
},
|
|
266
299
|
async ({ name, url, configPath }) => {
|
|
267
300
|
const configFile = configPath || import_path.default.join(process.cwd(), "stackwright.yml");
|
|
@@ -315,7 +348,7 @@ SHA-256 computed: ${sha256}`
|
|
|
315
348
|
"stackwright_pro_list_approved_specs",
|
|
316
349
|
"List all specs currently on the approved-specs allowlist. Shows spec names, URLs, and hash prefixes. Use this to audit what APIs are approved in the project.",
|
|
317
350
|
{
|
|
318
|
-
configPath:
|
|
351
|
+
configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
|
|
319
352
|
},
|
|
320
353
|
async ({ configPath }) => {
|
|
321
354
|
const configFile = configPath || import_path.default.join(process.cwd(), "stackwright.yml");
|
|
@@ -384,16 +417,18 @@ SHA-256 computed: ${sha256}`
|
|
|
384
417
|
}
|
|
385
418
|
|
|
386
419
|
// src/tools/isr.ts
|
|
387
|
-
var
|
|
420
|
+
var import_zod4 = require("zod");
|
|
388
421
|
function registerIsrTools(server2) {
|
|
389
422
|
server2.tool(
|
|
390
423
|
"stackwright_pro_configure_isr",
|
|
391
424
|
"Configure Incremental Static Regeneration (ISR) for an API-backed collection. ISR allows API data to be cached and refreshed on a schedule, providing real-time data with the performance of static generation. Use this after stackwright_pro_generate_filter to set revalidation intervals.",
|
|
392
425
|
{
|
|
393
|
-
collection:
|
|
394
|
-
revalidateSeconds:
|
|
395
|
-
|
|
396
|
-
|
|
426
|
+
collection: import_zod4.z.string().describe('Collection name (e.g., "equipment", "supplies")'),
|
|
427
|
+
revalidateSeconds: numCoerce(import_zod4.z.number().optional()).describe(
|
|
428
|
+
"Revalidation interval in seconds (default: 60)"
|
|
429
|
+
),
|
|
430
|
+
fallback: import_zod4.z.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
|
|
431
|
+
configPath: import_zod4.z.string().optional().describe("Path to stackwright.yml")
|
|
397
432
|
},
|
|
398
433
|
async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
|
|
399
434
|
const revalidate = revalidateSeconds;
|
|
@@ -436,14 +471,16 @@ ${yamlSnippet}
|
|
|
436
471
|
"stackwright_pro_configure_isr_batch",
|
|
437
472
|
"Configure ISR for multiple collections at once. More efficient than calling stackwright_pro_configure_isr multiple times. Provide different revalidation intervals based on data freshness requirements.",
|
|
438
473
|
{
|
|
439
|
-
collections:
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
474
|
+
collections: jsonCoerce(
|
|
475
|
+
import_zod4.z.array(
|
|
476
|
+
import_zod4.z.object({
|
|
477
|
+
name: import_zod4.z.string().describe("Collection name"),
|
|
478
|
+
revalidateSeconds: numCoerce(import_zod4.z.number().optional()).describe("Revalidation interval")
|
|
479
|
+
})
|
|
480
|
+
)
|
|
444
481
|
).describe("Array of collection configurations"),
|
|
445
|
-
defaultFallback:
|
|
446
|
-
configPath:
|
|
482
|
+
defaultFallback: import_zod4.z.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
|
|
483
|
+
configPath: import_zod4.z.string().optional().describe("Path to stackwright.yml")
|
|
447
484
|
},
|
|
448
485
|
async ({ collections, defaultFallback = "blocking", configPath }) => {
|
|
449
486
|
const lines = [`\u2699\uFE0F Batch ISR Configuration:
|
|
@@ -471,17 +508,17 @@ Fallback: ${defaultFallback}`);
|
|
|
471
508
|
}
|
|
472
509
|
|
|
473
510
|
// src/tools/dashboard.ts
|
|
474
|
-
var
|
|
511
|
+
var import_zod5 = require("zod");
|
|
475
512
|
var import_cli_data_explorer2 = require("@stackwright-pro/cli-data-explorer");
|
|
476
513
|
function registerDashboardTools(server2) {
|
|
477
514
|
server2.tool(
|
|
478
515
|
"stackwright_pro_generate_dashboard",
|
|
479
516
|
"Generate a dashboard page configuration for displaying API data. Creates YAML content for a Stackwright page with grid, metric_card, data_table, and collection_list content types. Use this after stackwright_pro_generate_filter to create pages for your API collections.",
|
|
480
517
|
{
|
|
481
|
-
entities:
|
|
482
|
-
layout:
|
|
483
|
-
pageTitle:
|
|
484
|
-
specPath:
|
|
518
|
+
entities: jsonCoerce(import_zod5.z.array(import_zod5.z.string())).describe("Entity slugs to include in dashboard"),
|
|
519
|
+
layout: import_zod5.z.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
|
|
520
|
+
pageTitle: import_zod5.z.string().optional().describe("Page title"),
|
|
521
|
+
specPath: import_zod5.z.string().optional().describe("Path to OpenAPI spec for entity details")
|
|
485
522
|
},
|
|
486
523
|
async ({ entities, layout = "mixed", pageTitle, specPath }) => {
|
|
487
524
|
let entityDetails = [];
|
|
@@ -567,9 +604,9 @@ ${yaml}
|
|
|
567
604
|
"stackwright_pro_generate_detail_page",
|
|
568
605
|
"Generate a detail view page for a single API entity. Creates YAML content for displaying all fields of an individual record. Use this to create detail pages that complement collection listing pages.",
|
|
569
606
|
{
|
|
570
|
-
entity:
|
|
571
|
-
slugField:
|
|
572
|
-
specPath:
|
|
607
|
+
entity: import_zod5.z.string().describe('Entity slug (e.g., "equipment")'),
|
|
608
|
+
slugField: import_zod5.z.string().optional().describe('Field to use as URL slug (default: "id")'),
|
|
609
|
+
specPath: import_zod5.z.string().optional().describe("Path to OpenAPI spec for field details")
|
|
573
610
|
},
|
|
574
611
|
async ({ entity, slugField = "id", specPath }) => {
|
|
575
612
|
let fields = [];
|
|
@@ -645,298 +682,170 @@ ${yaml}
|
|
|
645
682
|
}
|
|
646
683
|
|
|
647
684
|
// src/tools/clarification.ts
|
|
648
|
-
var
|
|
649
|
-
var
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
if (!startupOutput.includes("Starting")) {
|
|
684
|
-
console.error("[Python Clarification]", data.toString().trim());
|
|
685
|
-
}
|
|
686
|
-
});
|
|
687
|
-
proc.on("error", (err) => {
|
|
688
|
-
if (!started) {
|
|
689
|
-
activeServers.delete(sessionId);
|
|
690
|
-
reject(new Error(`Failed to start Python server: ${err.message}`));
|
|
691
|
-
}
|
|
692
|
-
});
|
|
693
|
-
proc.on("exit", (code) => {
|
|
694
|
-
activeServers.delete(sessionId);
|
|
695
|
-
if ((0, import_fs2.existsSync)(socketPath)) {
|
|
696
|
-
try {
|
|
697
|
-
(0, import_fs2.unlinkSync)(socketPath);
|
|
698
|
-
} catch {
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
});
|
|
702
|
-
setTimeout(() => {
|
|
703
|
-
if (!started) {
|
|
704
|
-
proc.kill();
|
|
705
|
-
activeServers.delete(sessionId);
|
|
706
|
-
reject(new Error("Python server startup timeout"));
|
|
707
|
-
}
|
|
708
|
-
}, 1e4);
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
async function stopPythonServer(sessionId) {
|
|
712
|
-
const proc = activeServers.get(sessionId);
|
|
713
|
-
if (proc) {
|
|
714
|
-
proc.kill("SIGTERM");
|
|
715
|
-
activeServers.delete(sessionId);
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
async function httpRequest(host, port, path3, body) {
|
|
719
|
-
const http = await import("http");
|
|
720
|
-
return new Promise((resolve, reject) => {
|
|
721
|
-
const url = new URL(path3, `http://${host}:${port}`);
|
|
722
|
-
const reqOptions = {
|
|
723
|
-
hostname: host,
|
|
724
|
-
port,
|
|
725
|
-
path: url.pathname,
|
|
726
|
-
method: body ? "POST" : "GET",
|
|
727
|
-
headers: {
|
|
728
|
-
"Content-Type": "application/json"
|
|
729
|
-
}
|
|
685
|
+
var import_zod6 = require("zod");
|
|
686
|
+
var CONTRADICTION_PATTERNS = [
|
|
687
|
+
{
|
|
688
|
+
keywords: ["minimal", "clean", "simple"],
|
|
689
|
+
conflicts: ["vibrant", "rich", "content-heavy", "playful"]
|
|
690
|
+
},
|
|
691
|
+
{
|
|
692
|
+
keywords: ["dark", "dark mode"],
|
|
693
|
+
conflicts: ["light mode only", "light"]
|
|
694
|
+
},
|
|
695
|
+
{
|
|
696
|
+
keywords: ["enterprise", "professional", "corporate"],
|
|
697
|
+
conflicts: ["playful", "casual", "fun"]
|
|
698
|
+
},
|
|
699
|
+
{
|
|
700
|
+
keywords: ["accessible", "wcag", "section 508"],
|
|
701
|
+
conflicts: ["compact", "dense", "small text"]
|
|
702
|
+
},
|
|
703
|
+
{
|
|
704
|
+
keywords: ["government", "defense", "federal"],
|
|
705
|
+
conflicts: ["public", "no auth", "consumer"]
|
|
706
|
+
}
|
|
707
|
+
];
|
|
708
|
+
function handleClarify(input) {
|
|
709
|
+
const { question_type, question, choices, priority, target_field, context } = input;
|
|
710
|
+
const base = {
|
|
711
|
+
action: "ask_user",
|
|
712
|
+
targetField: target_field
|
|
713
|
+
};
|
|
714
|
+
if (question_type === "closed_choice" && choices && choices.length > 0) {
|
|
715
|
+
const header = truncateHeader(question);
|
|
716
|
+
base.adaptedQuestion = {
|
|
717
|
+
question,
|
|
718
|
+
header,
|
|
719
|
+
options: choices.map((c) => ({ label: c }))
|
|
730
720
|
};
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
} else {
|
|
742
|
-
resolve(parsed);
|
|
743
|
-
}
|
|
744
|
-
} catch (e) {
|
|
745
|
-
reject(new Error(`Failed to parse response: ${data}`));
|
|
746
|
-
}
|
|
747
|
-
});
|
|
748
|
-
});
|
|
749
|
-
req.on("error", reject);
|
|
750
|
-
if (body) {
|
|
751
|
-
req.write(JSON.stringify(body));
|
|
752
|
-
}
|
|
753
|
-
req.end();
|
|
754
|
-
});
|
|
721
|
+
} else {
|
|
722
|
+
const contextPrefix = context ? `Context: ${context}
|
|
723
|
+
|
|
724
|
+
` : "";
|
|
725
|
+
base.prompt = `${contextPrefix}${question}`;
|
|
726
|
+
}
|
|
727
|
+
if (priority === "optional") {
|
|
728
|
+
base.suggestedDefault = inferDefault(question_type, choices);
|
|
729
|
+
}
|
|
730
|
+
return base;
|
|
755
731
|
}
|
|
756
|
-
function
|
|
757
|
-
const
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
732
|
+
function handleDetectConflict(input) {
|
|
733
|
+
const preferenceLower = input.stated_preference.toLowerCase();
|
|
734
|
+
const valuesLower = Object.values(input.selected_values).map((v) => v.toLowerCase());
|
|
735
|
+
for (const pattern of CONTRADICTION_PATTERNS) {
|
|
736
|
+
const preferenceMatch = pattern.keywords.some((kw) => preferenceLower.includes(kw));
|
|
737
|
+
if (!preferenceMatch) continue;
|
|
738
|
+
const conflictingValues = valuesLower.filter(
|
|
739
|
+
(val) => pattern.conflicts.some((c) => val.includes(c))
|
|
740
|
+
);
|
|
741
|
+
if (conflictingValues.length > 0) {
|
|
742
|
+
const matchedKeywords = pattern.keywords.filter((kw) => preferenceLower.includes(kw));
|
|
743
|
+
const primaryKeyword = matchedKeywords[0] ?? "preference";
|
|
744
|
+
return {
|
|
745
|
+
conflict: true,
|
|
746
|
+
description: `Stated preference includes "${matchedKeywords.join(", ")}" but selections contain "${conflictingValues.join(", ")}" \u2014 these are contradictory.`,
|
|
747
|
+
resolution_options: [
|
|
748
|
+
`Align selections with the "${primaryKeyword}" preference`,
|
|
749
|
+
`Revise stated preference to match current selections`,
|
|
750
|
+
"Ask user which direction they actually want"
|
|
751
|
+
]
|
|
752
|
+
};
|
|
765
753
|
}
|
|
766
754
|
}
|
|
767
|
-
return
|
|
755
|
+
return { conflict: false };
|
|
756
|
+
}
|
|
757
|
+
function truncateHeader(text) {
|
|
758
|
+
const MAX = 50;
|
|
759
|
+
if (text.length <= MAX) return text;
|
|
760
|
+
return text.slice(0, MAX - 1) + "\u2026";
|
|
761
|
+
}
|
|
762
|
+
function inferDefault(questionType, choices) {
|
|
763
|
+
if (questionType === "closed_choice" && choices && choices.length > 0) {
|
|
764
|
+
return choices[0] ?? "(first choice)";
|
|
765
|
+
}
|
|
766
|
+
return "(use sensible project default)";
|
|
768
767
|
}
|
|
769
768
|
function registerClarificationTools(server2) {
|
|
770
769
|
server2.tool(
|
|
771
770
|
"stackwright_pro_clarify",
|
|
772
|
-
"Ask the user for clarification when
|
|
771
|
+
"Ask the user for clarification when a specialist otter encounters ambiguity. This is for MID-EXECUTION questions, NOT upfront question collection (use the Question Manifest Protocol for that). Returns a structured response for the foreman to present to the user via ask_user_question (closed_choice) or directly (open_text).",
|
|
773
772
|
{
|
|
774
|
-
context:
|
|
775
|
-
question_type:
|
|
776
|
-
question:
|
|
777
|
-
choices:
|
|
778
|
-
|
|
779
|
-
|
|
773
|
+
context: import_zod6.z.string().optional().describe("Context about what the otter is trying to do"),
|
|
774
|
+
question_type: import_zod6.z.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
|
|
775
|
+
question: import_zod6.z.string().describe("The clarification question to ask the user"),
|
|
776
|
+
choices: jsonCoerce(import_zod6.z.array(import_zod6.z.string()).optional()).describe(
|
|
777
|
+
"Options for closed_choice questions"
|
|
778
|
+
),
|
|
779
|
+
priority: import_zod6.z.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
|
|
780
|
+
target_field: import_zod6.z.string().optional().describe("What field/config does this clarify?")
|
|
780
781
|
},
|
|
781
|
-
async ({ context, question_type, question, choices, priority
|
|
782
|
-
const
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
const response = await httpRequest(
|
|
803
|
-
port === 8765 ? "127.0.0.1" : "127.0.0.1",
|
|
804
|
-
port,
|
|
805
|
-
"/clarify",
|
|
806
|
-
{ request }
|
|
807
|
-
);
|
|
808
|
-
await stopPythonServer(sessionId);
|
|
809
|
-
const decision = response.decision;
|
|
810
|
-
const value = decision.value;
|
|
811
|
-
const source = decision.source;
|
|
812
|
-
const explicit = decision.explicit ? "explicitly" : "via fallback";
|
|
813
|
-
if (response.fallback_used) {
|
|
814
|
-
return {
|
|
815
|
-
content: [
|
|
816
|
-
{
|
|
817
|
-
type: "text",
|
|
818
|
-
text: `\u26A0\uFE0F Clarification fallback used: ${response.fallback_reason || "No user input available"}
|
|
819
|
-
|
|
820
|
-
Default value used: ${JSON.stringify(value)}
|
|
821
|
-
|
|
822
|
-
\u{1F4A1} Consider following up with the user later if this default isn't appropriate.`
|
|
823
|
-
}
|
|
824
|
-
]
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
return {
|
|
828
|
-
content: [
|
|
829
|
-
{
|
|
830
|
-
type: "text",
|
|
831
|
-
text: `\u2705 User clarified (${source}): ${JSON.stringify(value)}
|
|
832
|
-
|
|
833
|
-
Use this value to continue execution.`
|
|
834
|
-
}
|
|
835
|
-
]
|
|
836
|
-
};
|
|
837
|
-
} catch (error) {
|
|
838
|
-
await stopPythonServer(sessionId);
|
|
839
|
-
return {
|
|
840
|
-
content: [
|
|
841
|
-
{
|
|
842
|
-
type: "text",
|
|
843
|
-
text: `\u274C Clarification failed: ${error instanceof Error ? error.message : "Unknown error"}
|
|
844
|
-
|
|
845
|
-
Cannot proceed without user input. Consider:
|
|
846
|
-
1. Using a reasonable default
|
|
847
|
-
2. Asking the user directly in your response
|
|
848
|
-
3. Skipping this step if optional`
|
|
849
|
-
}
|
|
850
|
-
],
|
|
851
|
-
isError: true
|
|
852
|
-
};
|
|
853
|
-
}
|
|
782
|
+
async ({ context, question_type, question, choices, priority, target_field }) => {
|
|
783
|
+
const result = handleClarify({
|
|
784
|
+
context: context ?? void 0,
|
|
785
|
+
question_type,
|
|
786
|
+
question,
|
|
787
|
+
choices: choices ?? void 0,
|
|
788
|
+
priority: priority ?? "preferred",
|
|
789
|
+
target_field: target_field ?? void 0
|
|
790
|
+
});
|
|
791
|
+
return {
|
|
792
|
+
content: [
|
|
793
|
+
{
|
|
794
|
+
type: "text",
|
|
795
|
+
text: `\u{1F9A6} Clarification needed${target_field ? ` for "${target_field}"` : ""}. Present the following to the user. ` + (result.adaptedQuestion ? "Pass the adaptedQuestion to ask_user_question directly." : "Ask the user the prompt below.")
|
|
796
|
+
},
|
|
797
|
+
{
|
|
798
|
+
type: "text",
|
|
799
|
+
text: JSON.stringify(result)
|
|
800
|
+
}
|
|
801
|
+
]
|
|
802
|
+
};
|
|
854
803
|
}
|
|
855
804
|
);
|
|
856
805
|
server2.tool(
|
|
857
806
|
"stackwright_pro_detect_conflict",
|
|
858
|
-
"Detect when a user's stated preference conflicts with their selected choices.
|
|
807
|
+
"Detect when a user's stated preference conflicts with their selected choices. Uses keyword heuristics against known contradiction patterns (minimal vs vibrant, dark vs light, etc). Returns conflict details and resolution options.",
|
|
859
808
|
{
|
|
860
|
-
stated_preference:
|
|
861
|
-
selected_values:
|
|
809
|
+
stated_preference: import_zod6.z.string().describe("What the user said they wanted"),
|
|
810
|
+
selected_values: jsonCoerce(import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string())).describe(
|
|
811
|
+
"What the user actually selected (field \u2192 value)"
|
|
812
|
+
)
|
|
862
813
|
},
|
|
863
814
|
async ({ stated_preference, selected_values }) => {
|
|
864
|
-
const
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
{ stated_preference, selected_values }
|
|
872
|
-
);
|
|
873
|
-
await stopPythonServer(sessionId);
|
|
874
|
-
if (response.conflict) {
|
|
875
|
-
const data = response.data;
|
|
876
|
-
return {
|
|
877
|
-
content: [
|
|
878
|
-
{
|
|
879
|
-
type: "text",
|
|
880
|
-
text: `\u26A0\uFE0F CONFLICT DETECTED
|
|
815
|
+
const result = handleDetectConflict({ stated_preference, selected_values });
|
|
816
|
+
if (result.conflict) {
|
|
817
|
+
return {
|
|
818
|
+
content: [
|
|
819
|
+
{
|
|
820
|
+
type: "text",
|
|
821
|
+
text: `\u26A0\uFE0F CONFLICT DETECTED
|
|
881
822
|
|
|
882
823
|
User stated: "${stated_preference}"
|
|
883
824
|
But selected: ${JSON.stringify(selected_values)}
|
|
884
825
|
|
|
885
|
-
|
|
826
|
+
${result.description}
|
|
886
827
|
|
|
887
|
-
Resolution options:
|
|
828
|
+
Resolution options:
|
|
829
|
+
${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
|
|
888
830
|
|
|
889
831
|
\u{1F4A1} Consider asking the user to reconcile this conflict.`
|
|
890
|
-
|
|
891
|
-
]
|
|
892
|
-
};
|
|
893
|
-
}
|
|
894
|
-
return {
|
|
895
|
-
content: [
|
|
832
|
+
},
|
|
896
833
|
{
|
|
897
834
|
type: "text",
|
|
898
|
-
text:
|
|
835
|
+
text: JSON.stringify(result)
|
|
899
836
|
}
|
|
900
837
|
]
|
|
901
838
|
};
|
|
902
|
-
} catch (error) {
|
|
903
|
-
await stopPythonServer(sessionId);
|
|
904
|
-
return {
|
|
905
|
-
content: [
|
|
906
|
-
{
|
|
907
|
-
type: "text",
|
|
908
|
-
text: `\u274C Conflict detection failed: ${error instanceof Error ? error.message : "Unknown error"}`
|
|
909
|
-
}
|
|
910
|
-
],
|
|
911
|
-
isError: true
|
|
912
|
-
};
|
|
913
839
|
}
|
|
914
|
-
}
|
|
915
|
-
);
|
|
916
|
-
server2.tool(
|
|
917
|
-
"stackwright_pro_get_defaults",
|
|
918
|
-
"Get the current clarification defaults from config. Use this to understand what fallback values will be used if user doesn't provide input.",
|
|
919
|
-
{
|
|
920
|
-
config_path: import_zod5.z.string().optional().describe("Path to config file. Default: .stackwright/clarification.yaml")
|
|
921
|
-
},
|
|
922
|
-
async ({ config_path }) => {
|
|
923
840
|
return {
|
|
924
841
|
content: [
|
|
925
842
|
{
|
|
926
843
|
type: "text",
|
|
927
|
-
text:
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
- CLI args: --clarify-* flags
|
|
933
|
-
|
|
934
|
-
Default behaviors:
|
|
935
|
-
- allow_dont_know: true (users can skip)
|
|
936
|
-
- default_timeout: 120 seconds
|
|
937
|
-
- channel_priority: [tui, cli_args, config, defaults]
|
|
938
|
-
|
|
939
|
-
\u{1F4A1} Set CLARIFICATION_DEFAULT_<FIELD>=value to change defaults.`
|
|
844
|
+
text: "\u2705 No conflict detected between stated preference and selections."
|
|
845
|
+
},
|
|
846
|
+
{
|
|
847
|
+
type: "text",
|
|
848
|
+
text: JSON.stringify(result)
|
|
940
849
|
}
|
|
941
850
|
]
|
|
942
851
|
};
|
|
@@ -945,31 +854,53 @@ Default behaviors:
|
|
|
945
854
|
}
|
|
946
855
|
|
|
947
856
|
// src/tools/packages.ts
|
|
948
|
-
var
|
|
949
|
-
var
|
|
950
|
-
var
|
|
951
|
-
var
|
|
857
|
+
var import_zod7 = require("zod");
|
|
858
|
+
var import_fs2 = require("fs");
|
|
859
|
+
var import_child_process = require("child_process");
|
|
860
|
+
var import_path2 = __toESM(require("path"));
|
|
861
|
+
var BASELINE_DEPS = {
|
|
862
|
+
"@stackwright-pro/mcp": "latest",
|
|
863
|
+
"@stackwright-pro/otters": "latest",
|
|
864
|
+
"@stackwright-pro/openapi": "latest",
|
|
865
|
+
"@stackwright-pro/auth": "latest",
|
|
866
|
+
"@stackwright-pro/auth-nextjs": "latest",
|
|
867
|
+
zod: "^3.23.0"
|
|
868
|
+
};
|
|
869
|
+
var BASELINE_DEV_DEPS = {
|
|
870
|
+
"@stoplight/prism-cli": "^5.14.2"
|
|
871
|
+
};
|
|
952
872
|
function registerPackageTools(server2) {
|
|
953
873
|
server2.tool(
|
|
954
874
|
"stackwright_pro_setup_packages",
|
|
955
|
-
"Ensures pro packages are present in a project's package.json. Safe to call multiple times \u2014 never overwrites existing version pins. Use this to bootstrap dependencies before specialist otters run.",
|
|
875
|
+
"Ensures pro packages are present in a project's package.json. Safe to call multiple times \u2014 never overwrites existing version pins. Use this to bootstrap dependencies before specialist otters run. Pass includeBaseline: true to automatically include all required @stackwright-pro/* baseline dependencies. Safe to call on existing projects \u2014 never overwrites pinned versions.",
|
|
956
876
|
{
|
|
957
877
|
// FIX 3 (B-new-1): Zod v4 requires two-arg z.record(keySchema, valueSchema)
|
|
958
|
-
packages:
|
|
959
|
-
'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }'
|
|
878
|
+
packages: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional().default({})).describe(
|
|
879
|
+
'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
|
|
880
|
+
),
|
|
881
|
+
devPackages: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()).describe(
|
|
882
|
+
"devDependencies to add. Same format as packages."
|
|
960
883
|
),
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
884
|
+
scripts: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()).describe(
|
|
885
|
+
"npm scripts to add. Only adds if key does not already exist."
|
|
886
|
+
),
|
|
887
|
+
targetDir: import_zod7.z.string().optional().describe(
|
|
964
888
|
"Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
|
|
965
889
|
),
|
|
966
|
-
runInstall:
|
|
890
|
+
runInstall: boolCoerce(import_zod7.z.boolean().optional().default(true)).describe(
|
|
891
|
+
"Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
|
|
892
|
+
),
|
|
893
|
+
includeBaseline: boolCoerce(import_zod7.z.boolean().optional().default(false)).describe(
|
|
894
|
+
"When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions. Pass boolean true/false."
|
|
895
|
+
)
|
|
967
896
|
},
|
|
968
|
-
async ({ packages, devPackages, scripts, targetDir, runInstall }) => {
|
|
897
|
+
async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
|
|
898
|
+
const mergedPackages = includeBaseline ? { ...BASELINE_DEPS, ...packages } : { ...packages };
|
|
899
|
+
const mergedDevPackages = includeBaseline ? { ...BASELINE_DEV_DEPS, ...devPackages ?? {} } : devPackages;
|
|
969
900
|
const result = setupPackages({
|
|
970
|
-
packages,
|
|
901
|
+
packages: mergedPackages,
|
|
971
902
|
runInstall,
|
|
972
|
-
...
|
|
903
|
+
...mergedDevPackages !== void 0 ? { devPackages: mergedDevPackages } : {},
|
|
973
904
|
...scripts !== void 0 ? { scripts } : {},
|
|
974
905
|
...targetDir !== void 0 ? { targetDir } : {}
|
|
975
906
|
});
|
|
@@ -1007,8 +938,8 @@ function setupPackages(opts) {
|
|
|
1007
938
|
};
|
|
1008
939
|
try {
|
|
1009
940
|
const cwd = process.cwd();
|
|
1010
|
-
const resolvedTarget = opts.targetDir ?
|
|
1011
|
-
const cwdWithSep = cwd.endsWith(
|
|
941
|
+
const resolvedTarget = opts.targetDir ? import_path2.default.resolve(opts.targetDir) : cwd;
|
|
942
|
+
const cwdWithSep = cwd.endsWith(import_path2.default.sep) ? cwd : cwd + import_path2.default.sep;
|
|
1012
943
|
if (resolvedTarget !== cwd && !resolvedTarget.startsWith(cwdWithSep)) {
|
|
1013
944
|
return {
|
|
1014
945
|
success: false,
|
|
@@ -1021,8 +952,8 @@ function setupPackages(opts) {
|
|
|
1021
952
|
error: `Path traversal rejected: target directory is outside the allowed working directory`
|
|
1022
953
|
};
|
|
1023
954
|
}
|
|
1024
|
-
const preResolvePackageJsonPath =
|
|
1025
|
-
if (!(0,
|
|
955
|
+
const preResolvePackageJsonPath = import_path2.default.join(resolvedTarget, "package.json");
|
|
956
|
+
if (!(0, import_fs2.existsSync)(preResolvePackageJsonPath)) {
|
|
1026
957
|
return {
|
|
1027
958
|
success: false,
|
|
1028
959
|
...emptyResult,
|
|
@@ -1031,7 +962,7 @@ function setupPackages(opts) {
|
|
|
1031
962
|
}
|
|
1032
963
|
let realTarget;
|
|
1033
964
|
try {
|
|
1034
|
-
realTarget = (0,
|
|
965
|
+
realTarget = (0, import_fs2.realpathSync)(resolvedTarget);
|
|
1035
966
|
} catch {
|
|
1036
967
|
return {
|
|
1037
968
|
success: false,
|
|
@@ -1043,8 +974,8 @@ function setupPackages(opts) {
|
|
|
1043
974
|
error: `Could not resolve real path of target directory`
|
|
1044
975
|
};
|
|
1045
976
|
}
|
|
1046
|
-
const realCwd = (0,
|
|
1047
|
-
const realCwdWithSep = realCwd.endsWith(
|
|
977
|
+
const realCwd = (0, import_fs2.realpathSync)(cwd);
|
|
978
|
+
const realCwdWithSep = realCwd.endsWith(import_path2.default.sep) ? realCwd : realCwd + import_path2.default.sep;
|
|
1048
979
|
if (realTarget !== realCwd && !realTarget.startsWith(realCwdWithSep)) {
|
|
1049
980
|
return {
|
|
1050
981
|
success: false,
|
|
@@ -1057,8 +988,8 @@ function setupPackages(opts) {
|
|
|
1057
988
|
error: `Path traversal rejected: target directory resolved to a location outside the allowed working directory`
|
|
1058
989
|
};
|
|
1059
990
|
}
|
|
1060
|
-
const realPackageJsonPath =
|
|
1061
|
-
const pkgStat = (0,
|
|
991
|
+
const realPackageJsonPath = import_path2.default.join(realTarget, "package.json");
|
|
992
|
+
const pkgStat = (0, import_fs2.lstatSync)(realPackageJsonPath);
|
|
1062
993
|
if (pkgStat.isSymbolicLink()) {
|
|
1063
994
|
return {
|
|
1064
995
|
...emptyResult,
|
|
@@ -1117,12 +1048,12 @@ function setupPackages(opts) {
|
|
|
1117
1048
|
}
|
|
1118
1049
|
}
|
|
1119
1050
|
}
|
|
1120
|
-
const raw = (0,
|
|
1121
|
-
const PackageJsonSchema =
|
|
1051
|
+
const raw = (0, import_fs2.readFileSync)(realPackageJsonPath, "utf8");
|
|
1052
|
+
const PackageJsonSchema = import_zod7.z.object({
|
|
1122
1053
|
// Zod v4: z.record(keySchema, valueSchema) — two-arg form required
|
|
1123
|
-
dependencies:
|
|
1124
|
-
devDependencies:
|
|
1125
|
-
scripts:
|
|
1054
|
+
dependencies: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional(),
|
|
1055
|
+
devDependencies: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional(),
|
|
1056
|
+
scripts: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()
|
|
1126
1057
|
}).passthrough();
|
|
1127
1058
|
const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
|
|
1128
1059
|
if (!schemaResult.success) {
|
|
@@ -1171,12 +1102,12 @@ function setupPackages(opts) {
|
|
|
1171
1102
|
}
|
|
1172
1103
|
}
|
|
1173
1104
|
}
|
|
1174
|
-
(0,
|
|
1105
|
+
(0, import_fs2.writeFileSync)(realPackageJsonPath, JSON.stringify(parsed, null, 2) + "\n");
|
|
1175
1106
|
let installed = false;
|
|
1176
1107
|
let installError;
|
|
1177
1108
|
if (opts.runInstall) {
|
|
1178
1109
|
try {
|
|
1179
|
-
(0,
|
|
1110
|
+
(0, import_child_process.execSync)("pnpm install", { cwd: realTarget, stdio: "pipe", timeout: 6e4 });
|
|
1180
1111
|
installed = true;
|
|
1181
1112
|
} catch (err) {
|
|
1182
1113
|
installed = false;
|
|
@@ -1202,38 +1133,2418 @@ function setupPackages(opts) {
|
|
|
1202
1133
|
}
|
|
1203
1134
|
}
|
|
1204
1135
|
|
|
1205
|
-
//
|
|
1206
|
-
var
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
"
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1136
|
+
// src/tools/questions.ts
|
|
1137
|
+
var import_promises = require("fs/promises");
|
|
1138
|
+
var import_node_path = require("path");
|
|
1139
|
+
var import_zod8 = require("zod");
|
|
1140
|
+
|
|
1141
|
+
// src/question-adapter.ts
|
|
1142
|
+
function truncate(str, maxLength) {
|
|
1143
|
+
if (str.length <= maxLength) return str;
|
|
1144
|
+
return str.substring(0, maxLength - 1) + "\u2026";
|
|
1145
|
+
}
|
|
1146
|
+
function generateHeader(id) {
|
|
1147
|
+
const parts = id.split("-");
|
|
1148
|
+
if (parts.length >= 2) {
|
|
1149
|
+
const prefix = parts[0].toUpperCase().substring(0, 4);
|
|
1150
|
+
const num = parts[1];
|
|
1151
|
+
return truncate(`${prefix}-${num}`, 12);
|
|
1152
|
+
}
|
|
1153
|
+
return truncate(
|
|
1154
|
+
id.toUpperCase().replace(/[^A-Z0-9]/g, "").substring(0, 12),
|
|
1155
|
+
12
|
|
1156
|
+
);
|
|
1157
|
+
}
|
|
1158
|
+
function generateDefaultOptions(type) {
|
|
1159
|
+
switch (type) {
|
|
1160
|
+
case "confirm":
|
|
1161
|
+
return [
|
|
1162
|
+
{ label: "Yes", description: "Enable or confirm this option" },
|
|
1163
|
+
{ label: "No", description: "Disable or decline this option" }
|
|
1164
|
+
];
|
|
1165
|
+
case "text":
|
|
1166
|
+
return [
|
|
1167
|
+
{ label: "Specify", description: "I will provide a specific value" },
|
|
1168
|
+
{ label: "Skip", description: "Use default or skip this question" }
|
|
1169
|
+
];
|
|
1170
|
+
default:
|
|
1171
|
+
return [
|
|
1172
|
+
{ label: "Option 1", description: "First option" },
|
|
1173
|
+
{ label: "Option 2", description: "Second option" }
|
|
1174
|
+
];
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
function adaptQuestion(q) {
|
|
1178
|
+
const header = generateHeader(q.id);
|
|
1179
|
+
const multiSelect = q.type === "multi-select";
|
|
1180
|
+
let options;
|
|
1181
|
+
if (q.options && q.options.length >= 2) {
|
|
1182
|
+
options = q.options.map((opt) => ({
|
|
1183
|
+
label: truncate(opt.label, 50),
|
|
1184
|
+
description: opt.value !== opt.label ? opt.value : void 0
|
|
1185
|
+
}));
|
|
1186
|
+
} else if (q.options && q.options.length === 1) {
|
|
1187
|
+
options = [
|
|
1188
|
+
...q.options.map((opt) => ({ label: truncate(opt.label, 50), description: opt.value })),
|
|
1189
|
+
{ label: "Other", description: "Specify a different value" }
|
|
1190
|
+
];
|
|
1191
|
+
} else {
|
|
1192
|
+
options = generateDefaultOptions(q.type);
|
|
1193
|
+
}
|
|
1194
|
+
if (options.length < 2) {
|
|
1195
|
+
options.push({ label: "Other", description: "Alternative option" });
|
|
1196
|
+
}
|
|
1197
|
+
options = options.slice(0, 6);
|
|
1198
|
+
return {
|
|
1199
|
+
question: q.question + (q.help ? `
|
|
1200
|
+
|
|
1201
|
+
${q.help}` : ""),
|
|
1202
|
+
header,
|
|
1203
|
+
multi_select: multiSelect,
|
|
1204
|
+
options
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
function adaptQuestions(questions, answers = {}) {
|
|
1208
|
+
const adapted = [];
|
|
1209
|
+
for (const q of questions) {
|
|
1210
|
+
if (q.dependsOn) {
|
|
1211
|
+
const dependsAnswer = answers[q.dependsOn.questionId];
|
|
1212
|
+
if (dependsAnswer === void 0) {
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
const expectedValues = Array.isArray(q.dependsOn.value) ? q.dependsOn.value : [q.dependsOn.value];
|
|
1216
|
+
const answerValue = Array.isArray(dependsAnswer) ? dependsAnswer[0] : dependsAnswer;
|
|
1217
|
+
if (!expectedValues.includes(answerValue)) {
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
adapted.push(adaptQuestion(q));
|
|
1222
|
+
}
|
|
1223
|
+
return adapted;
|
|
1224
|
+
}
|
|
1225
|
+
function parseLLMQuestionsResponse(text) {
|
|
1226
|
+
let jsonStr = text;
|
|
1227
|
+
jsonStr = jsonStr.replace(/```(?:json|javascript)?\s*/gi, "");
|
|
1228
|
+
jsonStr = jsonStr.replace(/```\s*$/gm, "");
|
|
1229
|
+
const firstBrace = jsonStr.indexOf("{");
|
|
1230
|
+
const firstBracket = jsonStr.indexOf("[");
|
|
1231
|
+
let start = -1;
|
|
1232
|
+
if (firstBrace !== -1 && firstBracket !== -1) {
|
|
1233
|
+
start = Math.min(firstBrace, firstBracket);
|
|
1234
|
+
} else if (firstBrace !== -1) {
|
|
1235
|
+
start = firstBrace;
|
|
1236
|
+
} else if (firstBracket !== -1) {
|
|
1237
|
+
start = firstBracket;
|
|
1238
|
+
}
|
|
1239
|
+
if (start === -1) {
|
|
1240
|
+
throw new Error("No JSON found in response");
|
|
1241
|
+
}
|
|
1242
|
+
jsonStr = jsonStr.substring(start);
|
|
1243
|
+
const lastBrace = jsonStr.lastIndexOf("}");
|
|
1244
|
+
const lastBracket = jsonStr.lastIndexOf("]");
|
|
1245
|
+
const end = Math.max(lastBrace, lastBracket);
|
|
1246
|
+
if (end === -1) {
|
|
1247
|
+
throw new Error("Invalid JSON structure");
|
|
1248
|
+
}
|
|
1249
|
+
jsonStr = jsonStr.substring(0, end + 1);
|
|
1250
|
+
jsonStr = jsonStr.replace(/,(\s*[}\]])/g, "$1");
|
|
1251
|
+
jsonStr = jsonStr.replace(/'/g, '"');
|
|
1252
|
+
const parsed = JSON.parse(jsonStr);
|
|
1253
|
+
let questions;
|
|
1254
|
+
if (Array.isArray(parsed)) {
|
|
1255
|
+
questions = parsed;
|
|
1256
|
+
} else if (parsed.questions && Array.isArray(parsed.questions)) {
|
|
1257
|
+
questions = parsed.questions;
|
|
1258
|
+
} else if (parsed.data && Array.isArray(parsed.data.questions)) {
|
|
1259
|
+
questions = parsed.data.questions;
|
|
1260
|
+
} else {
|
|
1261
|
+
throw new Error("No questions array found in response");
|
|
1262
|
+
}
|
|
1263
|
+
function sanitize(obj) {
|
|
1264
|
+
const sanitized = {};
|
|
1265
|
+
for (const key of Object.keys(obj)) {
|
|
1266
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") {
|
|
1267
|
+
continue;
|
|
1268
|
+
}
|
|
1269
|
+
const val = obj[key];
|
|
1270
|
+
if (val && typeof val === "object" && !Array.isArray(val)) {
|
|
1271
|
+
sanitized[key] = sanitize(val);
|
|
1272
|
+
} else if (Array.isArray(val)) {
|
|
1273
|
+
sanitized[key] = val.map(
|
|
1274
|
+
(item) => item && typeof item === "object" && !Array.isArray(item) ? sanitize(item) : item
|
|
1275
|
+
);
|
|
1276
|
+
} else {
|
|
1277
|
+
sanitized[key] = val;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
return sanitized;
|
|
1281
|
+
}
|
|
1282
|
+
questions = questions.map((q) => {
|
|
1283
|
+
if (q && typeof q === "object") {
|
|
1284
|
+
return sanitize(q);
|
|
1285
|
+
}
|
|
1286
|
+
return q;
|
|
1287
|
+
});
|
|
1288
|
+
return questions;
|
|
1289
|
+
}
|
|
1290
|
+
function answersToManifestFormat(answers, questions) {
|
|
1291
|
+
const result = {};
|
|
1292
|
+
for (const answer of answers) {
|
|
1293
|
+
const headerLower = answer.question_header.toLowerCase();
|
|
1294
|
+
const question = questions.find((q) => {
|
|
1295
|
+
const qHeader = generateHeader(q.id).toLowerCase();
|
|
1296
|
+
return qHeader === headerLower || q.id.toLowerCase().includes(headerLower);
|
|
1297
|
+
});
|
|
1298
|
+
if (!question) {
|
|
1299
|
+
const matched = questions.find((q) => {
|
|
1300
|
+
const qHeader = generateHeader(q.id).toLowerCase();
|
|
1301
|
+
return qHeader.startsWith(headerLower.split("-")[0]);
|
|
1302
|
+
});
|
|
1303
|
+
if (matched) {
|
|
1304
|
+
result[matched.id] = answer.selected_options[0] || "";
|
|
1305
|
+
}
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
if (question.type === "multi-select" || answer.selected_options.length > 1) {
|
|
1309
|
+
result[question.id] = answer.selected_options;
|
|
1310
|
+
} else if (question.type === "confirm") {
|
|
1311
|
+
result[question.id] = answer.selected_options[0] === "Yes";
|
|
1312
|
+
} else {
|
|
1313
|
+
if (answer.other_text) {
|
|
1314
|
+
result[question.id] = answer.other_text;
|
|
1315
|
+
} else if (answer.selected_options.length > 0) {
|
|
1316
|
+
const option = question.options?.find((o) => o.label === answer.selected_options[0]);
|
|
1317
|
+
result[question.id] = option?.value ?? answer.selected_options[0];
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
return result;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// src/tools/questions.ts
|
|
1325
|
+
var ManifestQuestionSchema = import_zod8.z.object({
|
|
1326
|
+
id: import_zod8.z.string(),
|
|
1327
|
+
question: import_zod8.z.string(),
|
|
1328
|
+
type: import_zod8.z.enum(["text", "select", "multi-select", "confirm"]),
|
|
1329
|
+
required: import_zod8.z.boolean().optional(),
|
|
1330
|
+
options: import_zod8.z.array(
|
|
1331
|
+
import_zod8.z.object({
|
|
1332
|
+
label: import_zod8.z.string(),
|
|
1333
|
+
value: import_zod8.z.string()
|
|
1334
|
+
})
|
|
1335
|
+
).optional(),
|
|
1336
|
+
default: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.boolean(), import_zod8.z.array(import_zod8.z.string())]).optional(),
|
|
1337
|
+
help: import_zod8.z.string().optional(),
|
|
1338
|
+
dependsOn: import_zod8.z.object({
|
|
1339
|
+
questionId: import_zod8.z.string(),
|
|
1340
|
+
value: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string())])
|
|
1341
|
+
}).optional()
|
|
1342
|
+
});
|
|
1343
|
+
function registerQuestionTools(server2) {
|
|
1344
|
+
server2.tool(
|
|
1345
|
+
"stackwright_pro_present_phase_questions",
|
|
1346
|
+
"Adapt manifest-format questions from a specialist otter and present them to the user via ask_user_question. Pass only the phase name \u2014 this tool reads questions from .stackwright/question-manifest.json automatically. The questions parameter is optional and only needed if the manifest has not been written yet. Use this instead of calling ask_user_question directly \u2014 it handles label truncation (50-char limit), header generation, confirm/text defaults, and correct array formatting automatically. IMPORTANT: This is the ONLY approved way to prepare questions before calling ask_user_question. Never call ask_user_question with raw manifest questions. Never retry ask_user_question validation errors by calling it directly \u2014 always re-call this tool.",
|
|
1347
|
+
{
|
|
1348
|
+
phase: import_zod8.z.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
|
|
1349
|
+
questions: jsonCoerce(import_zod8.z.array(ManifestQuestionSchema).optional()).describe(
|
|
1350
|
+
"Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
|
|
1351
|
+
),
|
|
1352
|
+
answers: jsonCoerce(
|
|
1353
|
+
import_zod8.z.record(import_zod8.z.string(), import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string()), import_zod8.z.boolean()])).optional()
|
|
1354
|
+
).describe("Previously collected answers used to resolve dependsOn conditions")
|
|
1355
|
+
},
|
|
1356
|
+
async ({ phase, questions, answers }) => {
|
|
1357
|
+
let resolvedQuestions;
|
|
1358
|
+
const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
|
|
1359
|
+
if (!SAFE_PHASE.test(phase)) {
|
|
1360
|
+
return {
|
|
1361
|
+
content: [
|
|
1362
|
+
{
|
|
1363
|
+
type: "text",
|
|
1364
|
+
text: JSON.stringify({
|
|
1365
|
+
error: `Invalid phase name: "${phase.slice(0, 50)}". Must be lowercase alphanumeric with hyphens, max 31 chars.`
|
|
1366
|
+
})
|
|
1367
|
+
}
|
|
1368
|
+
],
|
|
1369
|
+
isError: true
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
if (questions && questions.length > 0) {
|
|
1373
|
+
resolvedQuestions = questions;
|
|
1374
|
+
} else {
|
|
1375
|
+
const phaseQuestionPath = (0, import_node_path.join)(process.cwd(), ".stackwright", "questions", `${phase}.json`);
|
|
1376
|
+
try {
|
|
1377
|
+
const raw = await (0, import_promises.readFile)(phaseQuestionPath, "utf-8");
|
|
1378
|
+
const phaseData = JSON.parse(raw);
|
|
1379
|
+
resolvedQuestions = phaseData.questions ?? [];
|
|
1380
|
+
} catch {
|
|
1381
|
+
try {
|
|
1382
|
+
const manifestPath = (0, import_node_path.join)(process.cwd(), ".stackwright", "question-manifest.json");
|
|
1383
|
+
const raw = await (0, import_promises.readFile)(manifestPath, "utf-8");
|
|
1384
|
+
const manifest = JSON.parse(raw);
|
|
1385
|
+
const phaseData = manifest.phases.find((p) => p.phase === phase);
|
|
1386
|
+
resolvedQuestions = phaseData?.questions ?? [];
|
|
1387
|
+
} catch (err) {
|
|
1388
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1389
|
+
return {
|
|
1390
|
+
content: [
|
|
1391
|
+
{
|
|
1392
|
+
type: "text",
|
|
1393
|
+
text: JSON.stringify({
|
|
1394
|
+
error: `Could not read question manifest for phase "${phase}": ${msg}`,
|
|
1395
|
+
hint: "Write the manifest first, or pass questions directly to this tool."
|
|
1396
|
+
})
|
|
1397
|
+
}
|
|
1398
|
+
],
|
|
1399
|
+
isError: true
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
|
|
1405
|
+
if (adapted.length === 0) {
|
|
1406
|
+
return {
|
|
1407
|
+
content: [
|
|
1408
|
+
{
|
|
1409
|
+
type: "text",
|
|
1410
|
+
text: JSON.stringify({
|
|
1411
|
+
phase,
|
|
1412
|
+
skipped: true,
|
|
1413
|
+
reason: "No questions to present (all filtered by dependsOn conditions)",
|
|
1414
|
+
answers: []
|
|
1415
|
+
})
|
|
1416
|
+
}
|
|
1417
|
+
],
|
|
1418
|
+
isError: false
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
return {
|
|
1422
|
+
content: [
|
|
1423
|
+
{
|
|
1424
|
+
type: "text",
|
|
1425
|
+
text: `Adapted ${adapted.length} questions for phase "${phase}". Pass the JSON array below DIRECTLY to ask_user_question as the "questions" parameter. Do NOT JSON.stringify() it. Do NOT wrap it in an object. Pass the parsed array value as-is.`
|
|
1426
|
+
},
|
|
1427
|
+
{
|
|
1428
|
+
type: "text",
|
|
1429
|
+
text: JSON.stringify(adapted)
|
|
1430
|
+
}
|
|
1431
|
+
],
|
|
1432
|
+
isError: false
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/tools/orchestration.ts
|
|
1439
|
+
var import_zod9 = require("zod");
|
|
1440
|
+
var import_fs3 = require("fs");
|
|
1441
|
+
var import_path3 = require("path");
|
|
1442
|
+
var OTTER_NAME_TO_PHASE = [
|
|
1443
|
+
["designer", "designer"],
|
|
1444
|
+
["theme", "theme"],
|
|
1445
|
+
["api", "api"],
|
|
1446
|
+
["auth", "auth"],
|
|
1447
|
+
["dashboard", "dashboard"],
|
|
1448
|
+
["data", "data"],
|
|
1449
|
+
["page", "pages"],
|
|
1450
|
+
["workflow", "workflow"]
|
|
1451
|
+
];
|
|
1452
|
+
var PHASE_TO_OTTER = {
|
|
1453
|
+
designer: "stackwright-pro-designer-otter",
|
|
1454
|
+
theme: "stackwright-pro-theme-otter",
|
|
1455
|
+
api: "stackwright-pro-api-otter",
|
|
1456
|
+
auth: "stackwright-pro-auth-otter",
|
|
1457
|
+
pages: "stackwright-pro-page-otter",
|
|
1458
|
+
dashboard: "stackwright-pro-dashboard-otter",
|
|
1459
|
+
data: "stackwright-pro-data-otter",
|
|
1460
|
+
workflow: "stackwright-pro-workflow-otter"
|
|
1461
|
+
};
|
|
1462
|
+
function detectPhase(otterName) {
|
|
1463
|
+
const lower = otterName.toLowerCase();
|
|
1464
|
+
for (const [keyword, phase] of OTTER_NAME_TO_PHASE) {
|
|
1465
|
+
if (lower.includes(keyword)) return phase;
|
|
1466
|
+
}
|
|
1467
|
+
return lower.replace(/^stackwright-pro-/, "").replace(/-otter$/, "");
|
|
1468
|
+
}
|
|
1469
|
+
function handleParseOtterResponse(input) {
|
|
1470
|
+
const phase = detectPhase(input.otterName);
|
|
1471
|
+
try {
|
|
1472
|
+
const questions = parseLLMQuestionsResponse(input.responseText);
|
|
1473
|
+
return {
|
|
1474
|
+
result: { phase, otter: input.otterName, questions },
|
|
1475
|
+
isError: false
|
|
1476
|
+
};
|
|
1477
|
+
} catch (err) {
|
|
1478
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1479
|
+
return {
|
|
1480
|
+
result: {
|
|
1481
|
+
error: true,
|
|
1482
|
+
otterName: input.otterName,
|
|
1483
|
+
phase,
|
|
1484
|
+
questions: [],
|
|
1485
|
+
parseError: message
|
|
1486
|
+
},
|
|
1487
|
+
isError: true
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
function handleSaveManifest(input) {
|
|
1492
|
+
const cwd = input._cwd ?? process.cwd();
|
|
1493
|
+
const dir = (0, import_path3.join)(cwd, ".stackwright");
|
|
1494
|
+
const filePath = (0, import_path3.join)(dir, "question-manifest.json");
|
|
1495
|
+
try {
|
|
1496
|
+
(0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
1497
|
+
if ((0, import_fs3.existsSync)(filePath)) {
|
|
1498
|
+
const stat = (0, import_fs3.lstatSync)(filePath);
|
|
1499
|
+
if (stat.isSymbolicLink()) {
|
|
1500
|
+
const message = `Refusing to write to symlink: ${filePath}`;
|
|
1501
|
+
return {
|
|
1502
|
+
text: JSON.stringify({ success: false, error: message }),
|
|
1503
|
+
isError: true
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
const manifest = {
|
|
1508
|
+
version: "1.0",
|
|
1509
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1510
|
+
phases: input.phases
|
|
1511
|
+
};
|
|
1512
|
+
(0, import_fs3.writeFileSync)(filePath, JSON.stringify(manifest, null, 2) + "\n");
|
|
1513
|
+
return {
|
|
1514
|
+
text: JSON.stringify({ success: true, path: filePath, phaseCount: input.phases.length }),
|
|
1515
|
+
isError: false
|
|
1516
|
+
};
|
|
1517
|
+
} catch (err) {
|
|
1518
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1519
|
+
return {
|
|
1520
|
+
text: JSON.stringify({ success: false, error: message }),
|
|
1521
|
+
isError: true
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
function handleSavePhaseAnswers(input) {
|
|
1526
|
+
const cwd = input._cwd ?? process.cwd();
|
|
1527
|
+
const dir = (0, import_path3.join)(cwd, ".stackwright", "answers");
|
|
1528
|
+
const filePath = (0, import_path3.join)(dir, `${input.phase}.json`);
|
|
1529
|
+
try {
|
|
1530
|
+
(0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
1531
|
+
let answers;
|
|
1532
|
+
if (input.questions && input.questions.length > 0) {
|
|
1533
|
+
answers = answersToManifestFormat(input.rawAnswers, input.questions);
|
|
1534
|
+
} else {
|
|
1535
|
+
answers = Object.fromEntries(
|
|
1536
|
+
input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
|
|
1537
|
+
);
|
|
1538
|
+
}
|
|
1539
|
+
const payload = {
|
|
1540
|
+
version: "1.0",
|
|
1541
|
+
phase: input.phase,
|
|
1542
|
+
completedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1543
|
+
answers
|
|
1544
|
+
};
|
|
1545
|
+
if ((0, import_fs3.existsSync)(filePath)) {
|
|
1546
|
+
const stat = (0, import_fs3.lstatSync)(filePath);
|
|
1547
|
+
if (stat.isSymbolicLink()) {
|
|
1548
|
+
const message = `Refusing to write to symlink: ${filePath}`;
|
|
1549
|
+
return {
|
|
1550
|
+
text: JSON.stringify({ success: false, error: message }),
|
|
1551
|
+
isError: true
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
(0, import_fs3.writeFileSync)(filePath, JSON.stringify(payload, null, 2) + "\n");
|
|
1556
|
+
return {
|
|
1557
|
+
text: JSON.stringify({
|
|
1558
|
+
success: true,
|
|
1559
|
+
path: filePath,
|
|
1560
|
+
answersCount: Object.keys(answers).length
|
|
1561
|
+
}),
|
|
1562
|
+
isError: false
|
|
1563
|
+
};
|
|
1564
|
+
} catch (err) {
|
|
1565
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1566
|
+
return {
|
|
1567
|
+
text: JSON.stringify({ success: false, error: message }),
|
|
1568
|
+
isError: true
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
function handleReadPhaseAnswers(input) {
|
|
1573
|
+
const cwd = input._cwd ?? process.cwd();
|
|
1574
|
+
const filePath = (0, import_path3.join)(cwd, ".stackwright", "answers", `${input.phase}.json`);
|
|
1575
|
+
if (!(0, import_fs3.existsSync)(filePath)) {
|
|
1576
|
+
return {
|
|
1577
|
+
text: JSON.stringify({ missing: true, phase: input.phase }),
|
|
1578
|
+
isError: false
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
try {
|
|
1582
|
+
const raw = (0, import_fs3.readFileSync)(filePath, "utf8");
|
|
1583
|
+
const parsed = JSON.parse(raw);
|
|
1584
|
+
return { text: JSON.stringify(parsed), isError: false };
|
|
1585
|
+
} catch (err) {
|
|
1586
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1587
|
+
return {
|
|
1588
|
+
text: JSON.stringify({ error: true, phase: input.phase, readError: message }),
|
|
1589
|
+
isError: true
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
function handleGetOtterName(input) {
|
|
1594
|
+
const normalised = input.phase.toLowerCase().trim();
|
|
1595
|
+
const otterName = PHASE_TO_OTTER[normalised];
|
|
1596
|
+
if (!otterName) {
|
|
1597
|
+
return {
|
|
1598
|
+
text: JSON.stringify({ error: true, message: `Unknown phase: ${input.phase}` }),
|
|
1599
|
+
isError: true
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
return {
|
|
1603
|
+
text: JSON.stringify({ phase: normalised, otterName }),
|
|
1604
|
+
isError: false
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
function registerOrchestrationTools(server2) {
|
|
1608
|
+
server2.tool(
|
|
1609
|
+
"stackwright_pro_parse_otter_response",
|
|
1610
|
+
"Parse and validate a specialist otter's QUESTION_COLLECTION_MODE JSON response. Handles JSON extraction from LLM responses (strips markdown, fixes single quotes, trailing commas). Detects the phase from the otter name. Use this immediately after invoke_agent() to get a validated manifest phase object.",
|
|
1611
|
+
{
|
|
1612
|
+
otterName: import_zod9.z.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
|
|
1613
|
+
responseText: import_zod9.z.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
|
|
1614
|
+
},
|
|
1615
|
+
async ({ otterName, responseText }) => {
|
|
1616
|
+
const { result, isError } = handleParseOtterResponse({ otterName, responseText });
|
|
1617
|
+
return {
|
|
1618
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
1619
|
+
isError
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
);
|
|
1623
|
+
server2.tool(
|
|
1624
|
+
"stackwright_pro_save_manifest",
|
|
1625
|
+
"Write the question manifest to .stackwright/question-manifest.json. Call this after collecting and parsing questions from all otters via stackwright_pro_parse_otter_response.",
|
|
1626
|
+
{
|
|
1627
|
+
phases: jsonCoerce(
|
|
1628
|
+
import_zod9.z.array(
|
|
1629
|
+
import_zod9.z.object({
|
|
1630
|
+
phase: import_zod9.z.string(),
|
|
1631
|
+
otter: import_zod9.z.string(),
|
|
1632
|
+
questions: import_zod9.z.array(import_zod9.z.any()),
|
|
1633
|
+
requiredPackages: import_zod9.z.object({
|
|
1634
|
+
dependencies: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional(),
|
|
1635
|
+
devPackages: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional()
|
|
1636
|
+
}).optional()
|
|
1637
|
+
})
|
|
1638
|
+
)
|
|
1639
|
+
).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
|
|
1640
|
+
},
|
|
1641
|
+
async ({ phases }) => {
|
|
1642
|
+
const { text, isError } = handleSaveManifest({ phases });
|
|
1643
|
+
return {
|
|
1644
|
+
content: [{ type: "text", text }],
|
|
1645
|
+
isError
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
);
|
|
1649
|
+
server2.tool(
|
|
1650
|
+
"stackwright_pro_save_phase_answers",
|
|
1651
|
+
"Save user answers for a phase to .stackwright/answers/{phase}.json. Pass rawAnswers directly from ask_user_question and the original manifest questions for label-to-value reverse mapping.",
|
|
1652
|
+
{
|
|
1653
|
+
phase: import_zod9.z.string().describe('Phase name, e.g. "designer"'),
|
|
1654
|
+
rawAnswers: jsonCoerce(
|
|
1655
|
+
import_zod9.z.array(
|
|
1656
|
+
import_zod9.z.object({
|
|
1657
|
+
question_header: import_zod9.z.string(),
|
|
1658
|
+
selected_options: import_zod9.z.array(import_zod9.z.string()),
|
|
1659
|
+
other_text: import_zod9.z.string().nullable().optional()
|
|
1660
|
+
})
|
|
1661
|
+
)
|
|
1662
|
+
).describe(
|
|
1663
|
+
"Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
|
|
1664
|
+
),
|
|
1665
|
+
questions: jsonCoerce(import_zod9.z.array(import_zod9.z.any()).optional()).describe(
|
|
1666
|
+
"Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
|
|
1667
|
+
)
|
|
1668
|
+
},
|
|
1669
|
+
async ({ phase, rawAnswers, questions }) => {
|
|
1670
|
+
const { text, isError } = handleSavePhaseAnswers({
|
|
1671
|
+
phase,
|
|
1672
|
+
rawAnswers,
|
|
1673
|
+
...questions && questions.length > 0 ? { questions } : {}
|
|
1674
|
+
});
|
|
1675
|
+
return {
|
|
1676
|
+
content: [{ type: "text", text }],
|
|
1677
|
+
isError
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
);
|
|
1681
|
+
server2.tool(
|
|
1682
|
+
"stackwright_pro_read_phase_answers",
|
|
1683
|
+
"Read saved answers for a phase from .stackwright/answers/{phase}.json. Returns { missing: true } when no answers exist yet \u2014 use this to skip phases safely in the execution loop.",
|
|
1684
|
+
{
|
|
1685
|
+
phase: import_zod9.z.string().describe('Phase name, e.g. "designer"')
|
|
1686
|
+
},
|
|
1687
|
+
async ({ phase }) => {
|
|
1688
|
+
const { text, isError } = handleReadPhaseAnswers({ phase });
|
|
1689
|
+
return {
|
|
1690
|
+
content: [{ type: "text", text }],
|
|
1691
|
+
isError
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
);
|
|
1695
|
+
server2.tool(
|
|
1696
|
+
"stackwright_pro_get_otter_name",
|
|
1697
|
+
"Get the agent name for a phase (e.g. 'designer' \u2192 'stackwright-pro-designer-otter'). Use this in the execution loop to invoke the correct specialist otter without hardcoding names in the prompt.",
|
|
1698
|
+
{
|
|
1699
|
+
phase: import_zod9.z.string().describe('Phase name, e.g. "designer", "api", "pages"')
|
|
1700
|
+
},
|
|
1701
|
+
async ({ phase }) => {
|
|
1702
|
+
const { text, isError } = handleGetOtterName({ phase });
|
|
1703
|
+
return {
|
|
1704
|
+
content: [{ type: "text", text }],
|
|
1705
|
+
isError
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
);
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
// src/tools/pipeline.ts
|
|
1712
|
+
var import_zod10 = require("zod");
|
|
1713
|
+
var import_fs4 = require("fs");
|
|
1714
|
+
var import_path4 = require("path");
|
|
1715
|
+
var PHASE_ORDER = [
|
|
1716
|
+
"designer",
|
|
1717
|
+
"theme",
|
|
1718
|
+
"api",
|
|
1719
|
+
"auth",
|
|
1720
|
+
"data",
|
|
1721
|
+
"pages",
|
|
1722
|
+
"dashboard",
|
|
1723
|
+
"workflow"
|
|
1724
|
+
];
|
|
1725
|
+
var PHASE_DEPENDENCIES = {
|
|
1726
|
+
designer: [],
|
|
1727
|
+
theme: ["designer"],
|
|
1728
|
+
api: [],
|
|
1729
|
+
auth: [],
|
|
1730
|
+
data: ["api"],
|
|
1731
|
+
pages: ["designer", "theme", "api", "data", "auth"],
|
|
1732
|
+
dashboard: ["designer", "theme", "api", "data"],
|
|
1733
|
+
workflow: ["auth"]
|
|
1734
|
+
};
|
|
1735
|
+
var PHASE_ARTIFACT = {
|
|
1736
|
+
designer: "design-language.json",
|
|
1737
|
+
theme: "theme-tokens.json",
|
|
1738
|
+
api: "api-config.json",
|
|
1739
|
+
auth: "auth-config.json",
|
|
1740
|
+
data: "data-config.json",
|
|
1741
|
+
pages: "pages-manifest.json",
|
|
1742
|
+
dashboard: "dashboard-manifest.json",
|
|
1743
|
+
workflow: "workflow-config.json"
|
|
1744
|
+
};
|
|
1745
|
+
var PHASE_TO_OTTER2 = {
|
|
1746
|
+
designer: "stackwright-pro-designer-otter",
|
|
1747
|
+
theme: "stackwright-pro-theme-otter",
|
|
1748
|
+
api: "stackwright-pro-api-otter",
|
|
1749
|
+
auth: "stackwright-pro-auth-otter",
|
|
1750
|
+
data: "stackwright-pro-data-otter",
|
|
1751
|
+
pages: "stackwright-pro-page-otter",
|
|
1752
|
+
dashboard: "stackwright-pro-dashboard-otter",
|
|
1753
|
+
workflow: "stackwright-pro-workflow-otter"
|
|
1754
|
+
};
|
|
1755
|
+
function isValidPhase(phase) {
|
|
1756
|
+
return PHASE_ORDER.includes(phase);
|
|
1757
|
+
}
|
|
1758
|
+
function defaultPhaseStatus() {
|
|
1759
|
+
return {
|
|
1760
|
+
questionsCollected: false,
|
|
1761
|
+
answered: false,
|
|
1762
|
+
executed: false,
|
|
1763
|
+
artifactWritten: false,
|
|
1764
|
+
retryCount: 0
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
function createDefaultState() {
|
|
1768
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1769
|
+
const phases = {};
|
|
1770
|
+
for (const p of PHASE_ORDER) {
|
|
1771
|
+
phases[p] = defaultPhaseStatus();
|
|
1772
|
+
}
|
|
1773
|
+
return {
|
|
1774
|
+
version: "1.0",
|
|
1775
|
+
currentPhase: PHASE_ORDER[0],
|
|
1776
|
+
status: "setup",
|
|
1777
|
+
phases,
|
|
1778
|
+
startedAt: now,
|
|
1779
|
+
updatedAt: now
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1782
|
+
function statePath(cwd) {
|
|
1783
|
+
return (0, import_path4.join)(cwd, ".stackwright", "pipeline-state.json");
|
|
1784
|
+
}
|
|
1785
|
+
function readState(cwd) {
|
|
1786
|
+
const p = statePath(cwd);
|
|
1787
|
+
if (!(0, import_fs4.existsSync)(p)) return createDefaultState();
|
|
1788
|
+
const raw = JSON.parse(safeReadSync(p));
|
|
1789
|
+
if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
|
|
1790
|
+
return createDefaultState();
|
|
1791
|
+
}
|
|
1792
|
+
return raw;
|
|
1793
|
+
}
|
|
1794
|
+
function safeWriteSync(filePath, content) {
|
|
1795
|
+
if ((0, import_fs4.existsSync)(filePath)) {
|
|
1796
|
+
const stat = (0, import_fs4.lstatSync)(filePath);
|
|
1797
|
+
if (stat.isSymbolicLink()) {
|
|
1798
|
+
throw new Error(`Refusing to write to symlink: ${filePath}`);
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
(0, import_fs4.writeFileSync)(filePath, content);
|
|
1802
|
+
}
|
|
1803
|
+
function safeReadSync(filePath) {
|
|
1804
|
+
if ((0, import_fs4.existsSync)(filePath)) {
|
|
1805
|
+
const stat = (0, import_fs4.lstatSync)(filePath);
|
|
1806
|
+
if (stat.isSymbolicLink()) {
|
|
1807
|
+
throw new Error(`Refusing to read symlink: ${filePath}`);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
return (0, import_fs4.readFileSync)(filePath, "utf-8");
|
|
1811
|
+
}
|
|
1812
|
+
function writeState(cwd, state) {
|
|
1813
|
+
const dir = (0, import_path4.join)(cwd, ".stackwright");
|
|
1814
|
+
(0, import_fs4.mkdirSync)(dir, { recursive: true });
|
|
1815
|
+
state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1816
|
+
safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
|
|
1817
|
+
}
|
|
1818
|
+
function extractJsonFromResponse(text) {
|
|
1819
|
+
let cleaned = text;
|
|
1820
|
+
cleaned = cleaned.replace(/```(?:json)?\s*/gi, "");
|
|
1821
|
+
cleaned = cleaned.replace(/```\s*$/gm, "");
|
|
1822
|
+
const firstBrace = cleaned.indexOf("{");
|
|
1823
|
+
if (firstBrace === -1) throw new Error("No JSON object found in response");
|
|
1824
|
+
cleaned = cleaned.substring(firstBrace);
|
|
1825
|
+
const lastBrace = cleaned.lastIndexOf("}");
|
|
1826
|
+
if (lastBrace === -1) throw new Error("Unclosed JSON object in response");
|
|
1827
|
+
cleaned = cleaned.substring(0, lastBrace + 1);
|
|
1828
|
+
cleaned = cleaned.replace(/,(\s*[}\]])/g, "$1");
|
|
1829
|
+
return JSON.parse(cleaned);
|
|
1830
|
+
}
|
|
1831
|
+
function handleGetPipelineState(_cwd) {
|
|
1832
|
+
const cwd = _cwd ?? process.cwd();
|
|
1833
|
+
try {
|
|
1834
|
+
const state = readState(cwd);
|
|
1835
|
+
return { text: JSON.stringify(state), isError: false };
|
|
1836
|
+
} catch (err) {
|
|
1837
|
+
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
function handleSetPipelineState(input) {
|
|
1841
|
+
const cwd = input._cwd ?? process.cwd();
|
|
1842
|
+
if (input.phase && !isValidPhase(input.phase)) {
|
|
1843
|
+
return {
|
|
1844
|
+
text: JSON.stringify({
|
|
1845
|
+
error: true,
|
|
1846
|
+
message: `Invalid phase: ${input.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
|
|
1847
|
+
}),
|
|
1848
|
+
isError: true
|
|
1849
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
const VALID_FIELDS = ["questionsCollected", "answered", "executed", "artifactWritten"];
|
|
1852
|
+
if (input.field && !VALID_FIELDS.includes(input.field)) {
|
|
1853
|
+
return {
|
|
1854
|
+
text: JSON.stringify({
|
|
1855
|
+
error: true,
|
|
1856
|
+
message: `Invalid field: ${input.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
|
|
1857
|
+
}),
|
|
1858
|
+
isError: true
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1861
|
+
try {
|
|
1862
|
+
const state = readState(cwd);
|
|
1863
|
+
if (input.status) {
|
|
1864
|
+
state.status = input.status;
|
|
1865
|
+
}
|
|
1866
|
+
if (input.phase) {
|
|
1867
|
+
const phase = input.phase;
|
|
1868
|
+
if (!state.phases[phase]) {
|
|
1869
|
+
state.phases[phase] = defaultPhaseStatus();
|
|
1870
|
+
}
|
|
1871
|
+
const phaseState = state.phases[phase];
|
|
1872
|
+
if (input.field && input.value !== void 0) {
|
|
1873
|
+
phaseState[input.field] = input.value;
|
|
1874
|
+
}
|
|
1875
|
+
if (input.incrementRetry) {
|
|
1876
|
+
phaseState.retryCount += 1;
|
|
1877
|
+
}
|
|
1878
|
+
state.currentPhase = phase;
|
|
1879
|
+
}
|
|
1880
|
+
writeState(cwd, state);
|
|
1881
|
+
return { text: JSON.stringify(state), isError: false };
|
|
1882
|
+
} catch (err) {
|
|
1883
|
+
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
function handleCheckExecutionReady(_cwd) {
|
|
1887
|
+
const cwd = _cwd ?? process.cwd();
|
|
1888
|
+
try {
|
|
1889
|
+
const answersDir = (0, import_path4.join)(cwd, ".stackwright", "answers");
|
|
1890
|
+
const answeredPhases = [];
|
|
1891
|
+
const missingPhases = [];
|
|
1892
|
+
for (const phase of PHASE_ORDER) {
|
|
1893
|
+
const answerFile = (0, import_path4.join)(answersDir, `${phase}.json`);
|
|
1894
|
+
if ((0, import_fs4.existsSync)(answerFile)) {
|
|
1895
|
+
try {
|
|
1896
|
+
const raw = safeReadSync(answerFile);
|
|
1897
|
+
const parsed = JSON.parse(raw);
|
|
1898
|
+
if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
|
|
1899
|
+
missingPhases.push(phase);
|
|
1900
|
+
continue;
|
|
1901
|
+
}
|
|
1902
|
+
answeredPhases.push(phase);
|
|
1903
|
+
} catch {
|
|
1904
|
+
missingPhases.push(phase);
|
|
1905
|
+
}
|
|
1906
|
+
} else {
|
|
1907
|
+
missingPhases.push(phase);
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
return {
|
|
1911
|
+
text: JSON.stringify({
|
|
1912
|
+
ready: missingPhases.length === 0,
|
|
1913
|
+
answeredPhases,
|
|
1914
|
+
missingPhases,
|
|
1915
|
+
totalPhases: PHASE_ORDER.length
|
|
1916
|
+
}),
|
|
1917
|
+
isError: false
|
|
1918
|
+
};
|
|
1919
|
+
} catch (err) {
|
|
1920
|
+
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
function handleListArtifacts(_cwd) {
|
|
1924
|
+
const cwd = _cwd ?? process.cwd();
|
|
1925
|
+
try {
|
|
1926
|
+
const artifactsDir = (0, import_path4.join)(cwd, ".stackwright", "artifacts");
|
|
1927
|
+
const artifacts = [];
|
|
1928
|
+
let completedCount = 0;
|
|
1929
|
+
for (const phase of PHASE_ORDER) {
|
|
1930
|
+
const expectedFile = PHASE_ARTIFACT[phase];
|
|
1931
|
+
const fullPath = (0, import_path4.join)(artifactsDir, expectedFile);
|
|
1932
|
+
const exists = (0, import_fs4.existsSync)(fullPath);
|
|
1933
|
+
if (exists) completedCount++;
|
|
1934
|
+
artifacts.push({ phase, expectedFile, exists, path: fullPath });
|
|
1935
|
+
}
|
|
1936
|
+
return {
|
|
1937
|
+
text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
|
|
1938
|
+
isError: false
|
|
1939
|
+
};
|
|
1940
|
+
} catch (err) {
|
|
1941
|
+
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
function handleWritePhaseQuestions(input) {
|
|
1945
|
+
const cwd = input._cwd ?? process.cwd();
|
|
1946
|
+
const { phase, responseText } = input;
|
|
1947
|
+
if (!isValidPhase(phase)) {
|
|
1948
|
+
return {
|
|
1949
|
+
text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
|
|
1950
|
+
isError: true
|
|
1951
|
+
};
|
|
1952
|
+
}
|
|
1953
|
+
try {
|
|
1954
|
+
const questions = parseLLMQuestionsResponse(responseText);
|
|
1955
|
+
let requiredPackages = {
|
|
1956
|
+
dependencies: {},
|
|
1957
|
+
devPackages: {}
|
|
1958
|
+
};
|
|
1959
|
+
try {
|
|
1960
|
+
const fullParsed = extractJsonFromResponse(responseText);
|
|
1961
|
+
if (fullParsed.requiredPackages && typeof fullParsed.requiredPackages === "object") {
|
|
1962
|
+
const rp = fullParsed.requiredPackages;
|
|
1963
|
+
requiredPackages = {
|
|
1964
|
+
dependencies: rp.dependencies ?? {},
|
|
1965
|
+
devPackages: rp.devPackages ?? {}
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
} catch {
|
|
1969
|
+
}
|
|
1970
|
+
const questionsDir = (0, import_path4.join)(cwd, ".stackwright", "questions");
|
|
1971
|
+
(0, import_fs4.mkdirSync)(questionsDir, { recursive: true });
|
|
1972
|
+
const filePath = (0, import_path4.join)(questionsDir, `${phase}.json`);
|
|
1973
|
+
const payload = {
|
|
1974
|
+
version: "1.0",
|
|
1975
|
+
phase,
|
|
1976
|
+
otter: PHASE_TO_OTTER2[phase],
|
|
1977
|
+
collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1978
|
+
questions,
|
|
1979
|
+
requiredPackages
|
|
1980
|
+
};
|
|
1981
|
+
safeWriteSync(filePath, JSON.stringify(payload, null, 2) + "\n");
|
|
1982
|
+
const state = readState(cwd);
|
|
1983
|
+
if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
|
|
1984
|
+
const ps = state.phases[phase];
|
|
1985
|
+
ps.questionsCollected = true;
|
|
1986
|
+
writeState(cwd, state);
|
|
1987
|
+
return {
|
|
1988
|
+
text: JSON.stringify({
|
|
1989
|
+
success: true,
|
|
1990
|
+
phase,
|
|
1991
|
+
questionCount: questions.length,
|
|
1992
|
+
requiredPackages,
|
|
1993
|
+
path: filePath
|
|
1994
|
+
}),
|
|
1995
|
+
isError: false
|
|
1996
|
+
};
|
|
1997
|
+
} catch (err) {
|
|
1998
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1999
|
+
return { text: JSON.stringify({ error: true, phase, message }), isError: true };
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
function handleBuildSpecialistPrompt(input) {
|
|
2003
|
+
const cwd = input._cwd ?? process.cwd();
|
|
2004
|
+
const { phase } = input;
|
|
2005
|
+
if (!isValidPhase(phase)) {
|
|
2006
|
+
return {
|
|
2007
|
+
text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
|
|
2008
|
+
isError: true
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
try {
|
|
2012
|
+
const answersPath = (0, import_path4.join)(cwd, ".stackwright", "answers", `${phase}.json`);
|
|
2013
|
+
let answers = {};
|
|
2014
|
+
if ((0, import_fs4.existsSync)(answersPath)) {
|
|
2015
|
+
answers = JSON.parse(safeReadSync(answersPath));
|
|
2016
|
+
}
|
|
2017
|
+
const deps = PHASE_DEPENDENCIES[phase];
|
|
2018
|
+
const artifactSections = [];
|
|
2019
|
+
const missingDependencies = [];
|
|
2020
|
+
for (const dep of deps) {
|
|
2021
|
+
const artifactFile = PHASE_ARTIFACT[dep];
|
|
2022
|
+
const artifactPath = (0, import_path4.join)(cwd, ".stackwright", "artifacts", artifactFile);
|
|
2023
|
+
if ((0, import_fs4.existsSync)(artifactPath)) {
|
|
2024
|
+
const content = JSON.parse(safeReadSync(artifactPath));
|
|
2025
|
+
const expectedOtter = PHASE_TO_OTTER2[dep];
|
|
2026
|
+
const artifactOtter = content["generatedBy"];
|
|
2027
|
+
if (!artifactOtter) {
|
|
2028
|
+
missingDependencies.push(dep);
|
|
2029
|
+
artifactSections.push(
|
|
2030
|
+
`[${artifactFile}]:
|
|
2031
|
+
(integrity check failed: missing generatedBy field)`
|
|
2032
|
+
);
|
|
2033
|
+
} else if (artifactOtter !== expectedOtter) {
|
|
2034
|
+
missingDependencies.push(dep);
|
|
2035
|
+
artifactSections.push(
|
|
2036
|
+
`[${artifactFile}]:
|
|
2037
|
+
(integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
|
|
2038
|
+
);
|
|
2039
|
+
} else {
|
|
2040
|
+
artifactSections.push(`[${artifactFile}]:
|
|
2041
|
+
${JSON.stringify(content, null, 2)}`);
|
|
2042
|
+
}
|
|
2043
|
+
} else {
|
|
2044
|
+
missingDependencies.push(dep);
|
|
2045
|
+
artifactSections.push(`[${artifactFile}]:
|
|
2046
|
+
(not yet available)`);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
const parts = ["ANSWERS:", JSON.stringify(answers, null, 2)];
|
|
2050
|
+
if (artifactSections.length > 0) {
|
|
2051
|
+
parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
|
|
2052
|
+
}
|
|
2053
|
+
parts.push("", "Execute using these answers and the upstream artifacts provided.");
|
|
2054
|
+
const prompt = parts.join("\n");
|
|
2055
|
+
const dependenciesSatisfied = missingDependencies.length === 0;
|
|
2056
|
+
return {
|
|
2057
|
+
text: JSON.stringify({
|
|
2058
|
+
otterName: PHASE_TO_OTTER2[phase],
|
|
2059
|
+
phase,
|
|
2060
|
+
prompt,
|
|
2061
|
+
dependenciesSatisfied,
|
|
2062
|
+
missingDependencies
|
|
2063
|
+
}),
|
|
2064
|
+
isError: false
|
|
2065
|
+
};
|
|
2066
|
+
} catch (err) {
|
|
2067
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2068
|
+
return { text: JSON.stringify({ error: true, phase, message }), isError: true };
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
var OFF_SCRIPT_PATTERNS = [
|
|
2072
|
+
{
|
|
2073
|
+
pattern: /```(?:ts|tsx|js|jsx|python|bash|sh|sql|ruby|go|rust|java|csharp|c\+\+)\b/,
|
|
2074
|
+
label: "code fence"
|
|
2075
|
+
},
|
|
2076
|
+
{ pattern: /\bimport\s+[\w{]/, label: "import statement" },
|
|
2077
|
+
{ pattern: /\bexport\s+(?:const|function|default|class)\b/, label: "export statement" },
|
|
2078
|
+
{ pattern: /\brequire\s*\(/, label: "require() call" },
|
|
2079
|
+
{ pattern: /\beval\s*\(/, label: "eval() call" },
|
|
2080
|
+
{ pattern: /^#!/m, label: "shebang" },
|
|
2081
|
+
{ pattern: /<script[\s>]/i, label: "script tag" },
|
|
2082
|
+
{ pattern: /\.(ts|tsx|js|jsx)\b.*\bfile\b/i, label: "code file reference" }
|
|
2083
|
+
];
|
|
2084
|
+
var PHASE_REQUIRED_KEYS = {
|
|
2085
|
+
designer: ["designLanguage", "themeTokenSeeds"],
|
|
2086
|
+
theme: ["tokens"],
|
|
2087
|
+
api: ["entities"],
|
|
2088
|
+
auth: ["version", "generatedBy"],
|
|
2089
|
+
data: ["version", "generatedBy"],
|
|
2090
|
+
pages: ["version", "generatedBy"],
|
|
2091
|
+
dashboard: ["version", "generatedBy"],
|
|
2092
|
+
workflow: ["version", "generatedBy"]
|
|
2093
|
+
};
|
|
2094
|
+
function handleValidateArtifact(input) {
|
|
2095
|
+
const cwd = input._cwd ?? process.cwd();
|
|
2096
|
+
const { phase, responseText } = input;
|
|
2097
|
+
if (!isValidPhase(phase)) {
|
|
2098
|
+
return {
|
|
2099
|
+
text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
|
|
2100
|
+
isError: true
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
2103
|
+
for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
|
|
2104
|
+
if (pattern.test(responseText)) {
|
|
2105
|
+
const result = {
|
|
2106
|
+
valid: false,
|
|
2107
|
+
phase,
|
|
2108
|
+
violation: "off-script",
|
|
2109
|
+
retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
|
|
2110
|
+
};
|
|
2111
|
+
return { text: JSON.stringify(result), isError: false };
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
let artifact;
|
|
2115
|
+
try {
|
|
2116
|
+
artifact = extractJsonFromResponse(responseText);
|
|
2117
|
+
} catch {
|
|
2118
|
+
const result = {
|
|
2119
|
+
valid: false,
|
|
2120
|
+
phase,
|
|
2121
|
+
violation: "invalid-json",
|
|
2122
|
+
retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
|
|
2123
|
+
};
|
|
2124
|
+
return { text: JSON.stringify(result), isError: false };
|
|
2125
|
+
}
|
|
2126
|
+
if (!artifact.version || !artifact.generatedBy) {
|
|
2127
|
+
const result = {
|
|
2128
|
+
valid: false,
|
|
2129
|
+
phase,
|
|
2130
|
+
violation: "missing-fields",
|
|
2131
|
+
retryPrompt: 'Your JSON artifact is missing required fields. Every artifact MUST include "version" and "generatedBy" at the top level.'
|
|
2132
|
+
};
|
|
2133
|
+
return { text: JSON.stringify(result), isError: false };
|
|
2134
|
+
}
|
|
2135
|
+
const requiredKeys = PHASE_REQUIRED_KEYS[phase];
|
|
2136
|
+
const missingKeys = requiredKeys.filter((k) => !(k in artifact));
|
|
2137
|
+
if (missingKeys.length > 0) {
|
|
2138
|
+
const result = {
|
|
2139
|
+
valid: false,
|
|
2140
|
+
phase,
|
|
2141
|
+
violation: "schema-mismatch",
|
|
2142
|
+
retryPrompt: `Your ${phase} artifact is missing required keys: ${missingKeys.join(", ")}. Include them and try again.`
|
|
2143
|
+
};
|
|
2144
|
+
return { text: JSON.stringify(result), isError: false };
|
|
2145
|
+
}
|
|
2146
|
+
try {
|
|
2147
|
+
const artifactsDir = (0, import_path4.join)(cwd, ".stackwright", "artifacts");
|
|
2148
|
+
(0, import_fs4.mkdirSync)(artifactsDir, { recursive: true });
|
|
2149
|
+
const artifactFile = PHASE_ARTIFACT[phase];
|
|
2150
|
+
const artifactPath = (0, import_path4.join)(artifactsDir, artifactFile);
|
|
2151
|
+
safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
|
|
2152
|
+
const state = readState(cwd);
|
|
2153
|
+
if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
|
|
2154
|
+
const ps = state.phases[phase];
|
|
2155
|
+
ps.artifactWritten = true;
|
|
2156
|
+
writeState(cwd, state);
|
|
2157
|
+
const topKeys = Object.keys(artifact).slice(0, 5).join(", ");
|
|
2158
|
+
const result = {
|
|
2159
|
+
valid: true,
|
|
2160
|
+
phase,
|
|
2161
|
+
artifactPath,
|
|
2162
|
+
summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
|
|
2163
|
+
};
|
|
2164
|
+
return { text: JSON.stringify(result), isError: false };
|
|
2165
|
+
} catch (err) {
|
|
2166
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2167
|
+
return { text: JSON.stringify({ error: true, phase, message }), isError: true };
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
function registerPipelineTools(server2) {
|
|
2171
|
+
const DESC = "Writes state to .stackwright/ \u2014 the filesystem is the state machine.";
|
|
2172
|
+
const res = (r) => ({
|
|
2173
|
+
content: [{ type: "text", text: r.text }],
|
|
2174
|
+
isError: r.isError
|
|
2175
|
+
});
|
|
2176
|
+
server2.tool(
|
|
2177
|
+
"stackwright_pro_get_pipeline_state",
|
|
2178
|
+
`Read pipeline state from .stackwright/pipeline-state.json. ${DESC}`,
|
|
2179
|
+
{},
|
|
2180
|
+
async () => res(handleGetPipelineState())
|
|
2181
|
+
);
|
|
2182
|
+
server2.tool(
|
|
2183
|
+
"stackwright_pro_set_pipeline_state",
|
|
2184
|
+
`Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
|
|
2185
|
+
{
|
|
2186
|
+
phase: import_zod10.z.string().optional().describe('Phase to update, e.g. "designer"'),
|
|
2187
|
+
field: import_zod10.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
|
|
2188
|
+
value: boolCoerce(import_zod10.z.boolean().optional()).describe(
|
|
2189
|
+
'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
|
|
2190
|
+
),
|
|
2191
|
+
status: import_zod10.z.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
|
|
2192
|
+
incrementRetry: boolCoerce(import_zod10.z.boolean().optional()).describe(
|
|
2193
|
+
"Bump retryCount by 1 \u2014 must be a JSON boolean"
|
|
2194
|
+
)
|
|
2195
|
+
},
|
|
2196
|
+
async (args) => res(
|
|
2197
|
+
handleSetPipelineState({
|
|
2198
|
+
...args.phase != null ? { phase: args.phase } : {},
|
|
2199
|
+
...args.field != null ? { field: args.field } : {},
|
|
2200
|
+
...args.value != null ? { value: args.value } : {},
|
|
2201
|
+
...args.status != null ? { status: args.status } : {},
|
|
2202
|
+
...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
|
|
2203
|
+
})
|
|
2204
|
+
)
|
|
2205
|
+
);
|
|
2206
|
+
server2.tool(
|
|
2207
|
+
"stackwright_pro_check_execution_ready",
|
|
2208
|
+
`Check all phases have answer files in .stackwright/answers/. ${DESC}`,
|
|
2209
|
+
{},
|
|
2210
|
+
async () => res(handleCheckExecutionReady())
|
|
2211
|
+
);
|
|
2212
|
+
server2.tool(
|
|
2213
|
+
"stackwright_pro_list_artifacts",
|
|
2214
|
+
`List phase artifacts in .stackwright/artifacts/ with completedCount/totalCount. ${DESC}`,
|
|
2215
|
+
{},
|
|
2216
|
+
async () => res(handleListArtifacts())
|
|
2217
|
+
);
|
|
2218
|
+
server2.tool(
|
|
2219
|
+
"stackwright_pro_write_phase_questions",
|
|
2220
|
+
`Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
|
|
2221
|
+
{
|
|
2222
|
+
phase: import_zod10.z.string().describe('Phase name, e.g. "designer"'),
|
|
2223
|
+
responseText: import_zod10.z.string().describe("Raw LLM response from QUESTION_COLLECTION_MODE")
|
|
2224
|
+
},
|
|
2225
|
+
async ({ phase, responseText }) => res(handleWritePhaseQuestions({ phase, responseText }))
|
|
2226
|
+
);
|
|
2227
|
+
server2.tool(
|
|
2228
|
+
"stackwright_pro_build_specialist_prompt",
|
|
2229
|
+
`Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
|
|
2230
|
+
{ phase: import_zod10.z.string().describe('Phase to build prompt for, e.g. "pages"') },
|
|
2231
|
+
async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
|
|
2232
|
+
);
|
|
2233
|
+
server2.tool(
|
|
2234
|
+
"stackwright_pro_validate_artifact",
|
|
2235
|
+
`Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
|
|
2236
|
+
{
|
|
2237
|
+
phase: import_zod10.z.string().describe('Phase that produced this artifact, e.g. "designer"'),
|
|
2238
|
+
responseText: import_zod10.z.string().describe("Raw response text from the specialist otter")
|
|
2239
|
+
},
|
|
2240
|
+
async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
|
|
2241
|
+
);
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
// src/tools/safe-write.ts
|
|
2245
|
+
var import_zod11 = require("zod");
|
|
2246
|
+
var import_fs5 = require("fs");
|
|
2247
|
+
var import_path5 = require("path");
|
|
2248
|
+
var OTTER_WRITE_ALLOWLISTS = {
|
|
2249
|
+
"stackwright-pro-designer-otter": [
|
|
2250
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
|
|
2251
|
+
],
|
|
2252
|
+
"stackwright-pro-theme-otter": [
|
|
2253
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
|
|
2254
|
+
],
|
|
2255
|
+
"stackwright-pro-auth-otter": [
|
|
2256
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
|
|
2257
|
+
{ prefix: "config/", suffix: ".yml", description: "Auth YAML config" },
|
|
2258
|
+
{ prefix: "config/", suffix: ".yaml", description: "Auth YAML config" },
|
|
2259
|
+
{
|
|
2260
|
+
prefix: ".env",
|
|
2261
|
+
suffix: "",
|
|
2262
|
+
description: "Dotenv files (.env, .env.local, .env.production, etc.)"
|
|
2263
|
+
}
|
|
2264
|
+
],
|
|
2265
|
+
"stackwright-pro-data-otter": [
|
|
2266
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Data config artifact" },
|
|
2267
|
+
{ prefix: "stackwright.yml", suffix: "", description: "Stackwright config" }
|
|
2268
|
+
],
|
|
2269
|
+
"stackwright-pro-page-otter": [
|
|
2270
|
+
{ prefix: "pages/", suffix: "/content.yml", description: "Page content YAML" },
|
|
2271
|
+
{ prefix: "pages/", suffix: "/content.yaml", description: "Page content YAML" },
|
|
2272
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Pages manifest" }
|
|
2273
|
+
],
|
|
2274
|
+
"stackwright-pro-dashboard-otter": [
|
|
2275
|
+
{ prefix: "pages/", suffix: "/content.yml", description: "Dashboard content YAML" },
|
|
2276
|
+
{ prefix: "pages/", suffix: "/content.yaml", description: "Dashboard content YAML" },
|
|
2277
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Dashboard manifest" }
|
|
2278
|
+
],
|
|
2279
|
+
"stackwright-pro-workflow-otter": [
|
|
2280
|
+
{ prefix: "workflows/", suffix: ".yml", description: "Workflow definition" },
|
|
2281
|
+
{ prefix: "workflows/", suffix: ".yaml", description: "Workflow definition" },
|
|
2282
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Workflow config" }
|
|
2283
|
+
],
|
|
2284
|
+
"stackwright-pro-api-otter": [
|
|
2285
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
|
|
2286
|
+
]
|
|
2287
|
+
};
|
|
2288
|
+
var PROTECTED_PATH_PREFIXES = [
|
|
2289
|
+
".stackwright/pipeline-state.json",
|
|
2290
|
+
".stackwright/questions/",
|
|
2291
|
+
".stackwright/answers/"
|
|
2292
|
+
];
|
|
2293
|
+
function checkPathAllowed(callerOtter, filePath) {
|
|
2294
|
+
const normalized = (0, import_path5.normalize)(filePath);
|
|
2295
|
+
if (normalized.includes("..")) {
|
|
2296
|
+
return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
|
|
2297
|
+
}
|
|
2298
|
+
if ((0, import_path5.isAbsolute)(normalized)) {
|
|
2299
|
+
return {
|
|
2300
|
+
allowed: false,
|
|
2301
|
+
error: "Absolute paths are not allowed \u2014 use paths relative to project root"
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
if (callerOtter === "stackwright-pro-foreman-otter") {
|
|
2305
|
+
return {
|
|
2306
|
+
allowed: false,
|
|
2307
|
+
error: "The foreman otter coordinates \u2014 it does not write files directly"
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
const allowlist = OTTER_WRITE_ALLOWLISTS[callerOtter];
|
|
2311
|
+
if (!allowlist) {
|
|
2312
|
+
return {
|
|
2313
|
+
allowed: false,
|
|
2314
|
+
error: `Unknown otter: "${callerOtter}" is not in the write allowlist`
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
for (const protectedPrefix of PROTECTED_PATH_PREFIXES) {
|
|
2318
|
+
if (normalized === protectedPrefix || normalized.startsWith(protectedPrefix)) {
|
|
2319
|
+
return {
|
|
2320
|
+
allowed: false,
|
|
2321
|
+
error: `Path "${normalized}" is managed by dedicated sink tools, not safe_write`
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
for (const rule of allowlist) {
|
|
2326
|
+
const prefixMatch = normalized.startsWith(rule.prefix);
|
|
2327
|
+
const suffixMatch = rule.suffix === "" || normalized.endsWith(rule.suffix);
|
|
2328
|
+
if (prefixMatch && suffixMatch) {
|
|
2329
|
+
if (rule.prefix === ".env" && rule.suffix === "") {
|
|
2330
|
+
if (!/^\.env(\.[a-zA-Z0-9]{3,})*$/.test(normalized)) {
|
|
2331
|
+
continue;
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
return { allowed: true, rule: rule.description };
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
return {
|
|
2338
|
+
allowed: false,
|
|
2339
|
+
error: `Path "${normalized}" does not match any allowed write pattern for ${callerOtter}`
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
function validateJsonContent(content) {
|
|
2343
|
+
try {
|
|
2344
|
+
JSON.parse(content);
|
|
2345
|
+
return null;
|
|
2346
|
+
} catch (err) {
|
|
2347
|
+
return `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`;
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
function validateYamlContent(content) {
|
|
2351
|
+
const trimmed = content.trimStart();
|
|
2352
|
+
const anchorRefPattern = /\[(\*[\w]+)\]/g;
|
|
2353
|
+
const matches = [...content.matchAll(anchorRefPattern)];
|
|
2354
|
+
if (matches.length >= 20) {
|
|
2355
|
+
return "YAML entity expansion pattern detected \u2014 too many anchor references";
|
|
2356
|
+
}
|
|
2357
|
+
const anchorDefPattern = /&([\w]+)/g;
|
|
2358
|
+
const defs = [...content.matchAll(anchorDefPattern)];
|
|
2359
|
+
if (defs.length >= 10) {
|
|
2360
|
+
const anchorNameCounts = /* @__PURE__ */ new Map();
|
|
2361
|
+
for (const [, name] of defs) {
|
|
2362
|
+
const count = (anchorNameCounts.get(name) ?? 0) + 1;
|
|
2363
|
+
anchorNameCounts.set(name, count);
|
|
2364
|
+
if (count >= 10) {
|
|
2365
|
+
return "YAML entity expansion: repeated anchor definitions detected";
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
if (trimmed.startsWith("import ") || trimmed.startsWith("import{")) {
|
|
2370
|
+
return 'Content starts with "import" \u2014 this looks like code, not YAML';
|
|
2371
|
+
}
|
|
2372
|
+
if (trimmed.startsWith("export ") || trimmed.startsWith("export{")) {
|
|
2373
|
+
return 'Content starts with "export" \u2014 this looks like code, not YAML';
|
|
2374
|
+
}
|
|
2375
|
+
if (trimmed.startsWith("#!"))
|
|
2376
|
+
return "Content starts with shebang \u2014 this looks like a script, not YAML";
|
|
2377
|
+
if (/!!(?:python|ruby|perl|js|java)/i.test(content))
|
|
2378
|
+
return "YAML deserialization attack tags detected";
|
|
2379
|
+
if (trimmed.startsWith("<") && !trimmed.startsWith("<<"))
|
|
2380
|
+
return "Content looks like markup, not YAML";
|
|
2381
|
+
return null;
|
|
2382
|
+
}
|
|
2383
|
+
function validateEnvContent(content) {
|
|
2384
|
+
const lines = content.split("\n");
|
|
2385
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2386
|
+
const raw = lines[i];
|
|
2387
|
+
if (raw === void 0) continue;
|
|
2388
|
+
const line = raw.trim();
|
|
2389
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
2390
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*=/.test(line)) {
|
|
2391
|
+
return `Line ${i + 1} is not a valid env entry (expected KEY=value): "${line}"`;
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
return null;
|
|
2395
|
+
}
|
|
2396
|
+
function validateContent(filePath, content) {
|
|
2397
|
+
if (filePath.endsWith(".json")) return validateJsonContent(content);
|
|
2398
|
+
if (filePath.endsWith(".yml") || filePath.endsWith(".yaml")) return validateYamlContent(content);
|
|
2399
|
+
if (filePath === ".env" || filePath.startsWith(".env")) return validateEnvContent(content);
|
|
2400
|
+
return null;
|
|
2401
|
+
}
|
|
2402
|
+
function handleSafeWrite(input) {
|
|
2403
|
+
const cwd = input._cwd ?? process.cwd();
|
|
2404
|
+
const { callerOtter, filePath, content, createDirectories = true } = input;
|
|
2405
|
+
const check = checkPathAllowed(callerOtter, filePath);
|
|
2406
|
+
if (!check.allowed) {
|
|
2407
|
+
const allowlist = OTTER_WRITE_ALLOWLISTS[callerOtter] ?? [];
|
|
2408
|
+
const allowedPaths = allowlist.map((r) => `${r.prefix}*${r.suffix} (${r.description})`);
|
|
2409
|
+
const result = {
|
|
2410
|
+
success: false,
|
|
2411
|
+
error: check.error ?? "Path not allowed",
|
|
2412
|
+
callerOtter,
|
|
2413
|
+
attemptedPath: filePath,
|
|
2414
|
+
allowedPaths
|
|
2415
|
+
};
|
|
2416
|
+
return { text: JSON.stringify(result), isError: true };
|
|
2417
|
+
}
|
|
2418
|
+
const normalized = (0, import_path5.normalize)(filePath);
|
|
2419
|
+
const fullPath = (0, import_path5.join)(cwd, normalized);
|
|
2420
|
+
if ((0, import_fs5.existsSync)(fullPath)) {
|
|
2421
|
+
try {
|
|
2422
|
+
const stat = (0, import_fs5.lstatSync)(fullPath);
|
|
2423
|
+
if (stat.isSymbolicLink()) {
|
|
2424
|
+
const result = {
|
|
2425
|
+
success: false,
|
|
2426
|
+
error: "Target path is a symlink \u2014 refusing to write through symlinks for security",
|
|
2427
|
+
callerOtter,
|
|
2428
|
+
attemptedPath: filePath,
|
|
2429
|
+
allowedPaths: []
|
|
2430
|
+
};
|
|
2431
|
+
return { text: JSON.stringify(result), isError: true };
|
|
2432
|
+
}
|
|
2433
|
+
} catch {
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
const contentError = validateContent(normalized, content);
|
|
2437
|
+
if (contentError) {
|
|
2438
|
+
const result = {
|
|
2439
|
+
success: false,
|
|
2440
|
+
error: `Content validation failed: ${contentError}`,
|
|
2441
|
+
callerOtter,
|
|
2442
|
+
attemptedPath: filePath,
|
|
2443
|
+
allowedPaths: []
|
|
2444
|
+
};
|
|
2445
|
+
return { text: JSON.stringify(result), isError: true };
|
|
2446
|
+
}
|
|
2447
|
+
try {
|
|
2448
|
+
if (createDirectories) {
|
|
2449
|
+
(0, import_fs5.mkdirSync)((0, import_path5.dirname)(fullPath), { recursive: true });
|
|
2450
|
+
}
|
|
2451
|
+
(0, import_fs5.writeFileSync)(fullPath, content, { encoding: "utf-8" });
|
|
2452
|
+
const result = {
|
|
2453
|
+
success: true,
|
|
2454
|
+
path: normalized,
|
|
2455
|
+
bytesWritten: Buffer.byteLength(content, "utf-8"),
|
|
2456
|
+
allowRule: check.rule ?? "unknown"
|
|
2457
|
+
};
|
|
2458
|
+
return { text: JSON.stringify(result), isError: false };
|
|
2459
|
+
} catch (err) {
|
|
2460
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2461
|
+
const result = {
|
|
2462
|
+
success: false,
|
|
2463
|
+
error: `Write failed: ${message}`,
|
|
2464
|
+
callerOtter,
|
|
2465
|
+
attemptedPath: filePath,
|
|
2466
|
+
allowedPaths: []
|
|
2467
|
+
};
|
|
2468
|
+
return { text: JSON.stringify(result), isError: true };
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
function registerSafeWriteTools(server2) {
|
|
2472
|
+
const DESC = "Controlled file-write chokepoint. Every write from specialist otters goes through this tool with per-otter path allowlists. The LLM cannot write to arbitrary filesystem paths.";
|
|
2473
|
+
server2.tool(
|
|
2474
|
+
"stackwright_pro_safe_write",
|
|
2475
|
+
DESC,
|
|
2476
|
+
{
|
|
2477
|
+
callerOtter: import_zod11.z.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
|
|
2478
|
+
filePath: import_zod11.z.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
|
|
2479
|
+
content: import_zod11.z.string().describe("File content to write"),
|
|
2480
|
+
createDirectories: import_zod11.z.boolean().optional().describe("Create parent directories if they don't exist. Default: true")
|
|
2481
|
+
},
|
|
2482
|
+
async ({ callerOtter, filePath, content, createDirectories }) => {
|
|
2483
|
+
const result = handleSafeWrite({
|
|
2484
|
+
callerOtter,
|
|
2485
|
+
filePath,
|
|
2486
|
+
content,
|
|
2487
|
+
...createDirectories != null ? { createDirectories } : {}
|
|
2488
|
+
});
|
|
2489
|
+
return { content: [{ type: "text", text: result.text }], isError: result.isError };
|
|
2490
|
+
}
|
|
2491
|
+
);
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
// src/tools/auth.ts
|
|
2495
|
+
var import_zod12 = require("zod");
|
|
2496
|
+
var import_fs6 = require("fs");
|
|
2497
|
+
var import_path6 = require("path");
|
|
2498
|
+
function buildHierarchy(roles) {
|
|
2499
|
+
const h = {};
|
|
2500
|
+
for (let i = 0; i < roles.length - 1; i++) {
|
|
2501
|
+
h[roles[i]] = roles.slice(i + 1);
|
|
2502
|
+
}
|
|
2503
|
+
return h;
|
|
2504
|
+
}
|
|
2505
|
+
function hierarchyToYaml(hierarchy, indent) {
|
|
2506
|
+
const entries = Object.entries(hierarchy);
|
|
2507
|
+
if (entries.length === 0) return `${indent}{}`;
|
|
2508
|
+
return entries.map(([role, subs]) => `${indent}${role}: [${subs.join(", ")}]`).join("\n");
|
|
2509
|
+
}
|
|
2510
|
+
function rolesToYaml(roles, indent) {
|
|
2511
|
+
return roles.map((r) => `${indent}- ${r}`).join("\n");
|
|
2512
|
+
}
|
|
2513
|
+
function routesToYaml(routes, defaultRole, indent) {
|
|
2514
|
+
return routes.map((r) => `${indent}- pattern: ${r}
|
|
2515
|
+
${indent} requiredRole: ${defaultRole}`).join("\n");
|
|
2516
|
+
}
|
|
2517
|
+
function upsertAuthBlock(existing, authYaml) {
|
|
2518
|
+
const lines = existing.split("\n");
|
|
2519
|
+
let authStart = -1;
|
|
2520
|
+
let authEnd = lines.length;
|
|
2521
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2522
|
+
if (/^auth:/.test(lines[i])) {
|
|
2523
|
+
authStart = i;
|
|
2524
|
+
} else if (authStart >= 0 && i > authStart && /^\S/.test(lines[i]) && lines[i].trim() !== "") {
|
|
2525
|
+
authEnd = i;
|
|
2526
|
+
break;
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
if (authStart < 0) {
|
|
2530
|
+
return existing.trimEnd() + "\n" + authYaml + "\n";
|
|
2531
|
+
}
|
|
2532
|
+
const before = lines.slice(0, authStart);
|
|
2533
|
+
const after = lines.slice(authEnd);
|
|
2534
|
+
return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
|
|
2535
|
+
}
|
|
2536
|
+
function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
|
|
2537
|
+
const rbacBlock = ` rbac: {
|
|
2538
|
+
roles: ${JSON.stringify(roles)},
|
|
2539
|
+
defaultRole: '${defaultRole}',
|
|
2540
|
+
hierarchy: ${JSON.stringify(hierarchy, null, 4)},
|
|
2541
|
+
},`;
|
|
2542
|
+
const auditBlock = ` audit: {
|
|
2543
|
+
enabled: ${auditEnabled},
|
|
2544
|
+
retentionDays: ${auditRetentionDays},
|
|
2545
|
+
},`;
|
|
2546
|
+
const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
|
|
2547
|
+
const configBlock = `export const config = {
|
|
2548
|
+
matcher: ${JSON.stringify(protectedRoutes)},
|
|
2549
|
+
};`;
|
|
2550
|
+
if (method === "cac") {
|
|
2551
|
+
const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
|
|
2552
|
+
const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
|
|
2553
|
+
const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
|
|
2554
|
+
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
2555
|
+
return `// middleware.ts \u2014 generated by @stackwright-pro/auth
|
|
2556
|
+
// \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
|
|
2557
|
+
// DoD security officer review required before production deployment.
|
|
2558
|
+
// Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
|
|
2559
|
+
import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
|
|
2560
|
+
|
|
2561
|
+
export const middleware = createProMiddleware({
|
|
2562
|
+
method: 'cac',
|
|
2563
|
+
cac: {
|
|
2564
|
+
caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
|
|
2565
|
+
edipiLookup: '${edipiLookup}',
|
|
2566
|
+
ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
|
|
2567
|
+
certHeader: '${certHeader}',
|
|
2568
|
+
},
|
|
2569
|
+
${rbacBlock}
|
|
2570
|
+
${auditBlock}
|
|
2571
|
+
${routesBlock}
|
|
2572
|
+
});
|
|
2573
|
+
|
|
2574
|
+
${configBlock}
|
|
2575
|
+
`;
|
|
2576
|
+
}
|
|
2577
|
+
if (method === "oidc") {
|
|
2578
|
+
const scopes2 = params.oidcScopes ?? "openid profile email";
|
|
2579
|
+
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
2580
|
+
return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
|
|
2581
|
+
import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
|
|
2582
|
+
|
|
2583
|
+
export const middleware = createProMiddleware({
|
|
2584
|
+
method: 'oidc',
|
|
2585
|
+
oidc: {
|
|
2586
|
+
discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
|
|
2587
|
+
clientId: process.env.OIDC_CLIENT_ID!,
|
|
2588
|
+
clientSecret: process.env.OIDC_CLIENT_SECRET!,
|
|
2589
|
+
scopes: '${scopes2}',
|
|
2590
|
+
roleClaim: '${roleClaim}',
|
|
2591
|
+
},
|
|
2592
|
+
${rbacBlock}
|
|
2593
|
+
${auditBlock}
|
|
2594
|
+
${routesBlock}
|
|
2595
|
+
});
|
|
2596
|
+
|
|
2597
|
+
${configBlock}
|
|
2598
|
+
`;
|
|
2599
|
+
}
|
|
2600
|
+
const scopes = params.oauth2Scopes ?? "read write";
|
|
2601
|
+
return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
|
|
2602
|
+
import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
|
|
2603
|
+
|
|
2604
|
+
export const middleware = createProMiddleware({
|
|
2605
|
+
method: 'oauth2',
|
|
2606
|
+
oauth2: {
|
|
2607
|
+
authorizationUrl: process.env.OAUTH2_AUTH_URL!,
|
|
2608
|
+
tokenUrl: process.env.OAUTH2_TOKEN_URL!,
|
|
2609
|
+
clientId: process.env.OAUTH2_CLIENT_ID!,
|
|
2610
|
+
clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
|
|
2611
|
+
scopes: '${scopes}',
|
|
2612
|
+
},
|
|
2613
|
+
${rbacBlock}
|
|
2614
|
+
${auditBlock}
|
|
2615
|
+
${routesBlock}
|
|
2616
|
+
});
|
|
2617
|
+
|
|
2618
|
+
${configBlock}
|
|
2619
|
+
`;
|
|
2620
|
+
}
|
|
2621
|
+
function generateEnvBlock(method, params) {
|
|
2622
|
+
if (method === "cac") {
|
|
2623
|
+
return `# Authentication (CAC/PKI \u2014 DoD)
|
|
2624
|
+
# \u26A0\uFE0F SECURITY REVIEW REQUIRED before production deployment
|
|
2625
|
+
CAC_CA_BUNDLE=./certs/dod-ca-bundle.pem
|
|
2626
|
+
CAC_OCSP_ENDPOINT=https://ocsp.disa.mil
|
|
2627
|
+
`;
|
|
2628
|
+
}
|
|
2629
|
+
if (method === "oidc") {
|
|
2630
|
+
const label = params.provider ?? "OIDC";
|
|
2631
|
+
const discoveryUrl = params.oidcDiscoveryUrl ?? "https://your-provider/.well-known/openid-configuration";
|
|
2632
|
+
return `# Authentication (OIDC \u2014 ${label})
|
|
2633
|
+
OIDC_DISCOVERY_URL=${discoveryUrl}
|
|
2634
|
+
OIDC_CLIENT_ID=your-client-id
|
|
2635
|
+
OIDC_CLIENT_SECRET=your-client-secret
|
|
2636
|
+
`;
|
|
2637
|
+
}
|
|
2638
|
+
const authUrl = params.oauth2AuthUrl ?? "https://your-auth-server/authorize";
|
|
2639
|
+
const tokenUrl = params.oauth2TokenUrl ?? "https://your-auth-server/token";
|
|
2640
|
+
return `# Authentication (OAuth2)
|
|
2641
|
+
OAUTH2_AUTH_URL=${authUrl}
|
|
2642
|
+
OAUTH2_TOKEN_URL=${tokenUrl}
|
|
2643
|
+
OAUTH2_CLIENT_ID=your-client-id
|
|
2644
|
+
OAUTH2_CLIENT_SECRET=your-client-secret
|
|
2645
|
+
`;
|
|
2646
|
+
}
|
|
2647
|
+
function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
|
|
2648
|
+
const rbacSection = ` rbac:
|
|
2649
|
+
roles:
|
|
2650
|
+
${rolesToYaml(roles, " ")}
|
|
2651
|
+
defaultRole: ${defaultRole}
|
|
2652
|
+
hierarchy:
|
|
2653
|
+
${hierarchyToYaml(hierarchy, " ")}`;
|
|
2654
|
+
const auditSection = ` audit:
|
|
2655
|
+
enabled: ${auditEnabled}
|
|
2656
|
+
retentionDays: ${auditRetentionDays}`;
|
|
2657
|
+
const routesSection = ` protectedRoutes:
|
|
2658
|
+
${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
|
|
2659
|
+
const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
|
|
2660
|
+
requiredRole: ${defaultRole}`).join("\n");
|
|
2661
|
+
const providerLine = params.provider ? ` provider: ${params.provider}
|
|
2662
|
+
` : "";
|
|
2663
|
+
if (method === "cac") {
|
|
2664
|
+
const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
|
|
2665
|
+
const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
|
|
2666
|
+
const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
|
|
2667
|
+
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
2668
|
+
return `auth:
|
|
2669
|
+
method: cac
|
|
2670
|
+
${providerLine} middleware: ./middleware.ts
|
|
2671
|
+
cac:
|
|
2672
|
+
caBundle: \${CAC_CA_BUNDLE}
|
|
2673
|
+
edipiLookup: ${edipiLookup}
|
|
2674
|
+
ocspEndpoint: \${CAC_OCSP_ENDPOINT}
|
|
2675
|
+
certHeader: ${certHeader}
|
|
2676
|
+
${rbacSection}
|
|
2677
|
+
protectedRoutes:
|
|
2678
|
+
${routeLines}
|
|
2679
|
+
${auditSection}
|
|
2680
|
+
`;
|
|
2681
|
+
}
|
|
2682
|
+
if (method === "oidc") {
|
|
2683
|
+
const scopes2 = params.oidcScopes ?? "openid profile email";
|
|
2684
|
+
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
2685
|
+
return `auth:
|
|
2686
|
+
method: oidc
|
|
2687
|
+
${providerLine} middleware: ./middleware.ts
|
|
2688
|
+
oidc:
|
|
2689
|
+
discoveryUrl: \${OIDC_DISCOVERY_URL}
|
|
2690
|
+
clientId: \${OIDC_CLIENT_ID}
|
|
2691
|
+
clientSecret: \${OIDC_CLIENT_SECRET}
|
|
2692
|
+
scopes: ${scopes2}
|
|
2693
|
+
roleClaim: ${roleClaim}
|
|
2694
|
+
${rbacSection}
|
|
2695
|
+
protectedRoutes:
|
|
2696
|
+
${routeLines}
|
|
2697
|
+
${auditSection}
|
|
2698
|
+
`;
|
|
2699
|
+
}
|
|
2700
|
+
const scopes = params.oauth2Scopes ?? "read write";
|
|
2701
|
+
return `auth:
|
|
2702
|
+
method: oauth2
|
|
2703
|
+
${providerLine} middleware: ./middleware.ts
|
|
2704
|
+
oauth2:
|
|
2705
|
+
authorizationUrl: \${OAUTH2_AUTH_URL}
|
|
2706
|
+
tokenUrl: \${OAUTH2_TOKEN_URL}
|
|
2707
|
+
clientId: \${OAUTH2_CLIENT_ID}
|
|
2708
|
+
clientSecret: \${OAUTH2_CLIENT_SECRET}
|
|
2709
|
+
scopes: ${scopes}
|
|
2710
|
+
${rbacSection}
|
|
2711
|
+
protectedRoutes:
|
|
2712
|
+
${routeLines}
|
|
2713
|
+
${auditSection}
|
|
2714
|
+
`;
|
|
2715
|
+
}
|
|
2716
|
+
async function configureAuthHandler(params, cwd) {
|
|
2717
|
+
const {
|
|
2718
|
+
method,
|
|
2719
|
+
provider,
|
|
2720
|
+
rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
|
|
2721
|
+
auditEnabled = true,
|
|
2722
|
+
auditRetentionDays = 90,
|
|
2723
|
+
protectedRoutes = ["/dashboard/:path*"]
|
|
2724
|
+
} = params;
|
|
2725
|
+
const roles = rbacRoles;
|
|
2726
|
+
const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
|
|
2727
|
+
const hierarchy = buildHierarchy(roles);
|
|
2728
|
+
if (method === "none") {
|
|
2729
|
+
return {
|
|
2730
|
+
content: [
|
|
2731
|
+
{
|
|
2732
|
+
type: "text",
|
|
2733
|
+
text: JSON.stringify({
|
|
2734
|
+
success: true,
|
|
2735
|
+
method: "none",
|
|
2736
|
+
provider: null,
|
|
2737
|
+
rbacRoles: roles,
|
|
2738
|
+
rbacDefaultRole: defaultRole,
|
|
2739
|
+
protectedRoutesCount: protectedRoutes.length,
|
|
2740
|
+
filesWritten: [],
|
|
2741
|
+
securityWarning: null
|
|
2742
|
+
})
|
|
2743
|
+
}
|
|
2744
|
+
]
|
|
2745
|
+
};
|
|
2746
|
+
}
|
|
2747
|
+
const filesWritten = [];
|
|
2748
|
+
try {
|
|
2749
|
+
const middlewareContent = generateMiddlewareContent(
|
|
2750
|
+
method,
|
|
2751
|
+
params,
|
|
2752
|
+
roles,
|
|
2753
|
+
defaultRole,
|
|
2754
|
+
hierarchy,
|
|
2755
|
+
auditEnabled,
|
|
2756
|
+
auditRetentionDays,
|
|
2757
|
+
protectedRoutes
|
|
2758
|
+
);
|
|
2759
|
+
(0, import_fs6.writeFileSync)((0, import_path6.join)(cwd, "middleware.ts"), middlewareContent, "utf8");
|
|
2760
|
+
filesWritten.push("middleware.ts");
|
|
2761
|
+
} catch (err) {
|
|
2762
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2763
|
+
return {
|
|
2764
|
+
content: [
|
|
2765
|
+
{
|
|
2766
|
+
type: "text",
|
|
2767
|
+
text: JSON.stringify({ success: false, error: `Failed writing middleware.ts: ${msg}` })
|
|
2768
|
+
}
|
|
2769
|
+
],
|
|
2770
|
+
isError: true
|
|
2771
|
+
};
|
|
2772
|
+
}
|
|
2773
|
+
try {
|
|
2774
|
+
const envBlock = generateEnvBlock(method, params);
|
|
2775
|
+
const envPath = (0, import_path6.join)(cwd, ".env.example");
|
|
2776
|
+
if ((0, import_fs6.existsSync)(envPath)) {
|
|
2777
|
+
const existing = (0, import_fs6.readFileSync)(envPath, "utf8");
|
|
2778
|
+
(0, import_fs6.writeFileSync)(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
|
|
2779
|
+
} else {
|
|
2780
|
+
(0, import_fs6.writeFileSync)(envPath, envBlock, "utf8");
|
|
2781
|
+
}
|
|
2782
|
+
filesWritten.push(".env.example");
|
|
2783
|
+
} catch (err) {
|
|
2784
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2785
|
+
return {
|
|
2786
|
+
content: [
|
|
2787
|
+
{
|
|
2788
|
+
type: "text",
|
|
2789
|
+
text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
|
|
2790
|
+
}
|
|
2791
|
+
],
|
|
2792
|
+
isError: true
|
|
2793
|
+
};
|
|
2794
|
+
}
|
|
2795
|
+
try {
|
|
2796
|
+
const authYaml = generateYamlBlock(
|
|
2797
|
+
method,
|
|
2798
|
+
params,
|
|
2799
|
+
roles,
|
|
2800
|
+
defaultRole,
|
|
2801
|
+
hierarchy,
|
|
2802
|
+
auditEnabled,
|
|
2803
|
+
auditRetentionDays,
|
|
2804
|
+
protectedRoutes
|
|
2805
|
+
);
|
|
2806
|
+
const ymlPath = (0, import_path6.join)(cwd, "stackwright.yml");
|
|
2807
|
+
if (!(0, import_fs6.existsSync)(ymlPath)) {
|
|
2808
|
+
(0, import_fs6.writeFileSync)(ymlPath, authYaml, "utf8");
|
|
2809
|
+
} else {
|
|
2810
|
+
const existing = (0, import_fs6.readFileSync)(ymlPath, "utf8");
|
|
2811
|
+
(0, import_fs6.writeFileSync)(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
|
|
2812
|
+
}
|
|
2813
|
+
filesWritten.push("stackwright.yml");
|
|
2814
|
+
} catch (err) {
|
|
2815
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2816
|
+
return {
|
|
2817
|
+
content: [
|
|
2818
|
+
{
|
|
2819
|
+
type: "text",
|
|
2820
|
+
text: JSON.stringify({ success: false, error: `Failed writing stackwright.yml: ${msg}` })
|
|
2821
|
+
}
|
|
2822
|
+
],
|
|
2823
|
+
isError: true
|
|
2824
|
+
};
|
|
2825
|
+
}
|
|
2826
|
+
const securityWarning = method === "cac" ? "SECURITY REVIEW REQUIRED \u2014 CAC certificate chain must be verified before production deployment" : null;
|
|
2827
|
+
return {
|
|
2828
|
+
content: [
|
|
2829
|
+
{
|
|
2830
|
+
type: "text",
|
|
2831
|
+
text: JSON.stringify({
|
|
2832
|
+
success: true,
|
|
2833
|
+
method,
|
|
2834
|
+
provider: provider ?? null,
|
|
2835
|
+
rbacRoles: roles,
|
|
2836
|
+
rbacDefaultRole: defaultRole,
|
|
2837
|
+
protectedRoutesCount: protectedRoutes.length,
|
|
2838
|
+
filesWritten,
|
|
2839
|
+
securityWarning
|
|
2840
|
+
})
|
|
2841
|
+
}
|
|
2842
|
+
]
|
|
2843
|
+
};
|
|
2844
|
+
}
|
|
2845
|
+
function registerAuthTools(server2) {
|
|
2846
|
+
server2.tool(
|
|
2847
|
+
"stackwright_pro_configure_auth",
|
|
2848
|
+
"Generate authentication middleware and configuration for a Next.js Stackwright application. Writes `middleware.ts` from a secure template, appends/updates the `auth:` section in `stackwright.yml`, and generates `.env.example` with required environment variables. \u26A0\uFE0F For CAC/PKI: generated `middleware.ts` carries a SECURITY REVIEW REQUIRED comment \u2014 certificate chain validation must be verified by a DoD security officer before production deployment. This is the ONLY approved path to generating `middleware.ts`. Never write TypeScript auth files directly.",
|
|
2849
|
+
{
|
|
2850
|
+
method: import_zod12.z.enum(["cac", "oidc", "oauth2", "none"]),
|
|
2851
|
+
provider: import_zod12.z.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
|
|
2852
|
+
// CAC
|
|
2853
|
+
cacCaBundle: import_zod12.z.string().optional(),
|
|
2854
|
+
cacEdipiLookup: import_zod12.z.string().optional(),
|
|
2855
|
+
cacOcspEndpoint: import_zod12.z.string().optional(),
|
|
2856
|
+
cacCertHeader: import_zod12.z.string().optional(),
|
|
2857
|
+
// OIDC
|
|
2858
|
+
oidcDiscoveryUrl: import_zod12.z.string().optional(),
|
|
2859
|
+
oidcClientId: import_zod12.z.string().optional(),
|
|
2860
|
+
oidcClientSecret: import_zod12.z.string().optional(),
|
|
2861
|
+
oidcScopes: import_zod12.z.string().optional(),
|
|
2862
|
+
oidcRoleClaim: import_zod12.z.string().optional(),
|
|
2863
|
+
// OAuth2
|
|
2864
|
+
oauth2AuthUrl: import_zod12.z.string().optional(),
|
|
2865
|
+
oauth2TokenUrl: import_zod12.z.string().optional(),
|
|
2866
|
+
oauth2ClientId: import_zod12.z.string().optional(),
|
|
2867
|
+
oauth2ClientSecret: import_zod12.z.string().optional(),
|
|
2868
|
+
oauth2Scopes: import_zod12.z.string().optional(),
|
|
2869
|
+
// RBAC
|
|
2870
|
+
rbacRoles: jsonCoerce(import_zod12.z.array(import_zod12.z.string()).optional()),
|
|
2871
|
+
rbacDefaultRole: import_zod12.z.string().optional(),
|
|
2872
|
+
// Audit
|
|
2873
|
+
auditEnabled: boolCoerce(import_zod12.z.boolean().optional()),
|
|
2874
|
+
auditRetentionDays: numCoerce(import_zod12.z.number().int().positive().optional()),
|
|
2875
|
+
// Routes
|
|
2876
|
+
protectedRoutes: jsonCoerce(import_zod12.z.array(import_zod12.z.string()).optional()),
|
|
2877
|
+
// Injection for tests
|
|
2878
|
+
_cwd: import_zod12.z.string().optional()
|
|
2879
|
+
},
|
|
2880
|
+
async (params) => {
|
|
2881
|
+
const cwd = params._cwd ?? process.cwd();
|
|
2882
|
+
return configureAuthHandler(params, cwd);
|
|
2883
|
+
}
|
|
2884
|
+
);
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
// src/integrity.ts
|
|
2888
|
+
var import_crypto2 = require("crypto");
|
|
2889
|
+
var import_fs7 = require("fs");
|
|
2890
|
+
var import_path7 = require("path");
|
|
2891
|
+
var _checksums = /* @__PURE__ */ new Map([
|
|
2892
|
+
[
|
|
2893
|
+
"stackwright-pro-api-otter.json",
|
|
2894
|
+
"f1cc9edf2dd1df3ebcea1d0ab33d17a358faaf8aa97ee232cd7994042f2eac0d"
|
|
2895
|
+
],
|
|
2896
|
+
[
|
|
2897
|
+
"stackwright-pro-auth-otter.json",
|
|
2898
|
+
"a19e06c503209a8a35fe321d30448623545b36b48c47a6ec064d13406ad1f725"
|
|
2899
|
+
],
|
|
2900
|
+
[
|
|
2901
|
+
"stackwright-pro-dashboard-otter.json",
|
|
2902
|
+
"b3cb3d7554f2e9eed3b57d5e0e3bf85d6ba5b4db5d3af5514391cf0575fcc001"
|
|
2903
|
+
],
|
|
2904
|
+
[
|
|
2905
|
+
"stackwright-pro-data-otter.json",
|
|
2906
|
+
"bfacb87ae82867472a75982215554336a105a658d6cd3dd2c8b819fa1e11d7ac"
|
|
2907
|
+
],
|
|
2908
|
+
[
|
|
2909
|
+
"stackwright-pro-designer-otter.json",
|
|
2910
|
+
"c58fa7c7ead9e6398074e1c7ce3f31a8ef4eb3679f5fa18cc03cae3a87878c88"
|
|
2911
|
+
],
|
|
2912
|
+
[
|
|
2913
|
+
"stackwright-pro-foreman-otter.json",
|
|
2914
|
+
"f52264c1f6297b72f3da6d92d41b6d63356db776242caeab25571e6a8df628e4"
|
|
2915
|
+
],
|
|
2916
|
+
[
|
|
2917
|
+
"stackwright-pro-page-otter.json",
|
|
2918
|
+
"65bec3a3a0dda6b7591bba2de9399f1e3a4fb99cfe1075342f4f4be98d917b67"
|
|
2919
|
+
],
|
|
2920
|
+
[
|
|
2921
|
+
"stackwright-pro-theme-otter.json",
|
|
2922
|
+
"1f182326f1acd3d4091a38c7012085cbb4945893e95be4ca3de72318ad092767"
|
|
2923
|
+
],
|
|
2924
|
+
[
|
|
2925
|
+
"stackwright-pro-workflow-otter.json",
|
|
2926
|
+
"0eec9d6a731678cf547c2a7b0b6fc338ca143c35501365a1e4e5dd2779dd5510"
|
|
2927
|
+
]
|
|
2928
|
+
]);
|
|
2929
|
+
Object.freeze(_checksums);
|
|
2930
|
+
var CANONICAL_CHECKSUMS = _checksums;
|
|
2931
|
+
var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
|
|
2932
|
+
for (const [name, digest] of CANONICAL_CHECKSUMS) {
|
|
2933
|
+
if (!SHA256_HEX_RE.test(digest)) {
|
|
2934
|
+
throw new Error(
|
|
2935
|
+
`Malformed SHA-256 in CANONICAL_CHECKSUMS for "${name}": expected 64 hex chars, got ${digest.length}: "${digest}"`
|
|
2936
|
+
);
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
var MAX_OTTER_BYTES = 1 * 1024 * 1024;
|
|
2940
|
+
function computeSha256(data) {
|
|
2941
|
+
return (0, import_crypto2.createHash)("sha256").update(data).digest("hex");
|
|
2942
|
+
}
|
|
2943
|
+
function safeEqual(a, b) {
|
|
2944
|
+
if (a.length !== b.length) return false;
|
|
2945
|
+
return (0, import_crypto2.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
|
|
2946
|
+
}
|
|
2947
|
+
function verifyOtterFile(filePath) {
|
|
2948
|
+
const filename = (0, import_path7.basename)(filePath);
|
|
2949
|
+
const expected = CANONICAL_CHECKSUMS.get(filename);
|
|
2950
|
+
if (expected === void 0) {
|
|
2951
|
+
return { verified: false, filename, error: `Unknown otter file: not in canonical set` };
|
|
2952
|
+
}
|
|
2953
|
+
let stat;
|
|
2954
|
+
try {
|
|
2955
|
+
stat = (0, import_fs7.lstatSync)(filePath);
|
|
2956
|
+
} catch (err) {
|
|
2957
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2958
|
+
return { verified: false, filename, error: `Cannot stat file: ${msg}` };
|
|
2959
|
+
}
|
|
2960
|
+
if (stat.isSymbolicLink()) {
|
|
2961
|
+
return { verified: false, filename, error: "Refusing to verify symlink" };
|
|
2962
|
+
}
|
|
2963
|
+
const size = stat.size;
|
|
2964
|
+
if (size > MAX_OTTER_BYTES) {
|
|
2965
|
+
return {
|
|
2966
|
+
verified: false,
|
|
2967
|
+
filename,
|
|
2968
|
+
error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`
|
|
2969
|
+
};
|
|
2970
|
+
}
|
|
2971
|
+
let raw;
|
|
2972
|
+
try {
|
|
2973
|
+
raw = (0, import_fs7.readFileSync)(filePath);
|
|
2974
|
+
} catch (err) {
|
|
2975
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2976
|
+
return { verified: false, filename, error: `Cannot read file: ${msg}` };
|
|
2977
|
+
}
|
|
2978
|
+
if (raw.length > MAX_OTTER_BYTES) {
|
|
2979
|
+
return {
|
|
2980
|
+
verified: false,
|
|
2981
|
+
filename,
|
|
2982
|
+
error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`
|
|
2983
|
+
};
|
|
2984
|
+
}
|
|
2985
|
+
const actual = computeSha256(raw);
|
|
2986
|
+
if (!safeEqual(actual, expected)) {
|
|
2987
|
+
return {
|
|
2988
|
+
verified: false,
|
|
2989
|
+
filename,
|
|
2990
|
+
error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}\u2026, got ${actual.substring(0, 8)}\u2026`
|
|
2991
|
+
};
|
|
2992
|
+
}
|
|
2993
|
+
try {
|
|
2994
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
2995
|
+
decoder.decode(raw);
|
|
2996
|
+
} catch {
|
|
2997
|
+
return {
|
|
2998
|
+
verified: false,
|
|
2999
|
+
filename,
|
|
3000
|
+
error: "File is not valid UTF-8 \u2014 may be corrupted or contain binary injection"
|
|
3001
|
+
};
|
|
3002
|
+
}
|
|
3003
|
+
return { verified: true, filename };
|
|
3004
|
+
}
|
|
3005
|
+
function verifyAllOtters(otterDir) {
|
|
3006
|
+
const verified = [];
|
|
3007
|
+
const failed = [];
|
|
3008
|
+
const unknown = [];
|
|
3009
|
+
let entries;
|
|
3010
|
+
try {
|
|
3011
|
+
entries = (0, import_fs7.readdirSync)(otterDir);
|
|
3012
|
+
} catch (err) {
|
|
3013
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3014
|
+
return {
|
|
3015
|
+
verified: [],
|
|
3016
|
+
failed: [{ filename: "<directory>", error: `Cannot read directory: ${msg}` }],
|
|
3017
|
+
unknown: []
|
|
3018
|
+
};
|
|
3019
|
+
}
|
|
3020
|
+
const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
|
|
3021
|
+
for (const filename of otterFiles) {
|
|
3022
|
+
const filePath = (0, import_path7.join)(otterDir, filename);
|
|
3023
|
+
try {
|
|
3024
|
+
if ((0, import_fs7.lstatSync)(filePath).isSymbolicLink()) {
|
|
3025
|
+
failed.push({ filename, error: "Skipped: symlink" });
|
|
3026
|
+
continue;
|
|
3027
|
+
}
|
|
3028
|
+
} catch {
|
|
3029
|
+
}
|
|
3030
|
+
const result = verifyOtterFile(filePath);
|
|
3031
|
+
if (result.verified) {
|
|
3032
|
+
verified.push(result.filename);
|
|
3033
|
+
} else if (result.error?.startsWith("Unknown otter file")) {
|
|
3034
|
+
unknown.push(result.filename);
|
|
3035
|
+
} else {
|
|
3036
|
+
failed.push({ filename: result.filename, error: result.error ?? "Unknown error" });
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {
|
|
3040
|
+
if (!otterFiles.includes(canonicalName)) {
|
|
3041
|
+
failed.push({ filename: canonicalName, error: "Missing from directory" });
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
return { verified, failed, unknown };
|
|
3045
|
+
}
|
|
3046
|
+
var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packages/otters/src/"];
|
|
3047
|
+
function resolveOtterDir() {
|
|
3048
|
+
const cwd = process.cwd();
|
|
3049
|
+
for (const relative of DEFAULT_SEARCH_PATHS) {
|
|
3050
|
+
const candidate = (0, import_path7.join)(cwd, relative);
|
|
3051
|
+
try {
|
|
3052
|
+
(0, import_fs7.lstatSync)(candidate);
|
|
3053
|
+
return candidate;
|
|
3054
|
+
} catch {
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
return null;
|
|
3058
|
+
}
|
|
3059
|
+
function registerIntegrityTools(server2) {
|
|
3060
|
+
server2.tool(
|
|
3061
|
+
"stackwright_pro_verify_otter_integrity",
|
|
3062
|
+
"Verify SHA-256 integrity of all Pro otter agent definitions. Call this at startup before discovering otters. Auto-discovers the otter directory from known paths. Returns verified/failed/unknown lists.",
|
|
3063
|
+
{},
|
|
3064
|
+
async () => {
|
|
3065
|
+
const resolved = resolveOtterDir();
|
|
3066
|
+
if (!resolved) {
|
|
3067
|
+
return {
|
|
3068
|
+
content: [
|
|
3069
|
+
{
|
|
3070
|
+
type: "text",
|
|
3071
|
+
text: JSON.stringify({
|
|
3072
|
+
error: true,
|
|
3073
|
+
message: "Could not locate otter directory. Searched: " + DEFAULT_SEARCH_PATHS.join(", ")
|
|
3074
|
+
})
|
|
3075
|
+
}
|
|
3076
|
+
],
|
|
3077
|
+
isError: true
|
|
3078
|
+
};
|
|
3079
|
+
}
|
|
3080
|
+
const result = verifyAllOtters(resolved);
|
|
3081
|
+
const allGood = result.failed.length === 0 && result.unknown.length === 0;
|
|
3082
|
+
return {
|
|
3083
|
+
content: [
|
|
3084
|
+
{
|
|
3085
|
+
type: "text",
|
|
3086
|
+
text: JSON.stringify({
|
|
3087
|
+
otterDir: resolved,
|
|
3088
|
+
totalCanonical: CANONICAL_CHECKSUMS.size,
|
|
3089
|
+
verifiedCount: result.verified.length,
|
|
3090
|
+
failedCount: result.failed.length,
|
|
3091
|
+
unknownCount: result.unknown.length,
|
|
3092
|
+
verified: result.verified,
|
|
3093
|
+
failed: result.failed,
|
|
3094
|
+
unknown: result.unknown,
|
|
3095
|
+
warning: result.failed.length > 0 ? "SHA-256 mismatches detected (non-blocking). PKI-signed manifest support coming soon." : void 0
|
|
3096
|
+
})
|
|
3097
|
+
}
|
|
3098
|
+
],
|
|
3099
|
+
isError: false
|
|
3100
|
+
};
|
|
3101
|
+
}
|
|
3102
|
+
);
|
|
3103
|
+
}
|
|
3104
|
+
|
|
3105
|
+
// src/tools/domain.ts
|
|
3106
|
+
var import_zod13 = require("zod");
|
|
3107
|
+
var import_fs8 = require("fs");
|
|
3108
|
+
var import_path8 = require("path");
|
|
3109
|
+
function handleListCollections(input) {
|
|
3110
|
+
const cwd = input._cwd ?? process.cwd();
|
|
3111
|
+
const sources = [
|
|
3112
|
+
{
|
|
3113
|
+
path: (0, import_path8.join)(cwd, ".stackwright", "artifacts", "data-config.json"),
|
|
3114
|
+
source: "data-config.json",
|
|
3115
|
+
parse: (raw) => {
|
|
3116
|
+
const parsed = JSON.parse(raw);
|
|
3117
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
3118
|
+
return [];
|
|
3119
|
+
}
|
|
3120
|
+
return extractCollectionsFromArtifact(parsed);
|
|
3121
|
+
}
|
|
3122
|
+
},
|
|
3123
|
+
{
|
|
3124
|
+
path: (0, import_path8.join)(cwd, "stackwright.yml"),
|
|
3125
|
+
source: "stackwright.yml",
|
|
3126
|
+
parse: extractCollectionsFromYaml
|
|
3127
|
+
}
|
|
3128
|
+
];
|
|
3129
|
+
for (const { path: path3, source, parse } of sources) {
|
|
3130
|
+
if (!(0, import_fs8.existsSync)(path3)) continue;
|
|
3131
|
+
try {
|
|
3132
|
+
const collections = parse((0, import_fs8.readFileSync)(path3, "utf8"));
|
|
3133
|
+
return {
|
|
3134
|
+
text: JSON.stringify({ collections, source, collectionCount: collections.length }),
|
|
3135
|
+
isError: false
|
|
3136
|
+
};
|
|
3137
|
+
} catch {
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
return {
|
|
3141
|
+
text: JSON.stringify({
|
|
3142
|
+
collections: [],
|
|
3143
|
+
source: "none",
|
|
3144
|
+
collectionCount: 0,
|
|
3145
|
+
hint: "Run API Otter and Data Otter first"
|
|
3146
|
+
}),
|
|
3147
|
+
isError: false
|
|
3148
|
+
};
|
|
3149
|
+
}
|
|
3150
|
+
function extractCollectionsFromArtifact(raw) {
|
|
3151
|
+
const collections = [];
|
|
3152
|
+
const integrations = raw.integrations ?? raw.collections ?? [];
|
|
3153
|
+
if (!Array.isArray(integrations)) return collections;
|
|
3154
|
+
for (const item of integrations) {
|
|
3155
|
+
if (!item || typeof item !== "object") continue;
|
|
3156
|
+
const obj = item;
|
|
3157
|
+
if (typeof obj.name === "string" && typeof obj.endpoint === "string") {
|
|
3158
|
+
collections.push(makeCollectionInfo(obj.name, obj.endpoint, obj.type));
|
|
3159
|
+
continue;
|
|
3160
|
+
}
|
|
3161
|
+
if (!Array.isArray(obj.collections)) continue;
|
|
3162
|
+
for (const col of obj.collections) {
|
|
3163
|
+
if (!col || typeof col !== "object") continue;
|
|
3164
|
+
const c = col;
|
|
3165
|
+
if (typeof c.name === "string" && typeof c.endpoint === "string") {
|
|
3166
|
+
collections.push(makeCollectionInfo(c.name, c.endpoint, c.type ?? obj.type));
|
|
3167
|
+
}
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
return collections;
|
|
3171
|
+
}
|
|
3172
|
+
function makeCollectionInfo(name, endpoint, type) {
|
|
3173
|
+
return { name, endpoint, ...typeof type === "string" ? { type } : {} };
|
|
3174
|
+
}
|
|
3175
|
+
function extractCollectionsFromYaml(yamlText) {
|
|
3176
|
+
const collections = [];
|
|
3177
|
+
const lines = yamlText.split("\n");
|
|
3178
|
+
let inIntegrations = false;
|
|
3179
|
+
let currentName = null;
|
|
3180
|
+
let currentEndpoint = null;
|
|
3181
|
+
let currentType = null;
|
|
3182
|
+
for (const line of lines) {
|
|
3183
|
+
if (line.length > 1e3) continue;
|
|
3184
|
+
if (/^integrations:\s*$/.test(line)) {
|
|
3185
|
+
inIntegrations = true;
|
|
3186
|
+
continue;
|
|
3187
|
+
}
|
|
3188
|
+
if (inIntegrations && /^[a-z]/.test(line) && !line.startsWith(" ")) {
|
|
3189
|
+
inIntegrations = false;
|
|
3190
|
+
}
|
|
3191
|
+
if (!inIntegrations) continue;
|
|
3192
|
+
const stripQuotes = (s) => s.trim().replace(/^['"]|['"]$/g, "");
|
|
3193
|
+
const typeMatch = line.match(/^\s+type:\s*(.+)$/);
|
|
3194
|
+
if (typeMatch?.[1]) currentType = stripQuotes(typeMatch[1]);
|
|
3195
|
+
const nameMatch = line.match(/^[\s-]+name:\s*(.+)$/);
|
|
3196
|
+
if (nameMatch?.[1]) {
|
|
3197
|
+
if (currentName && currentEndpoint) {
|
|
3198
|
+
collections.push(makeCollectionInfo(currentName, currentEndpoint, currentType));
|
|
3199
|
+
}
|
|
3200
|
+
currentName = stripQuotes(nameMatch[1]);
|
|
3201
|
+
currentEndpoint = null;
|
|
3202
|
+
}
|
|
3203
|
+
const endpointMatch = line.match(/^\s+endpoint:\s*(.+)$/);
|
|
3204
|
+
if (endpointMatch?.[1]) currentEndpoint = stripQuotes(endpointMatch[1]);
|
|
3205
|
+
}
|
|
3206
|
+
if (currentName && currentEndpoint) {
|
|
3207
|
+
collections.push(makeCollectionInfo(currentName, currentEndpoint, currentType));
|
|
3208
|
+
}
|
|
3209
|
+
return collections;
|
|
3210
|
+
}
|
|
3211
|
+
var DATA_STRATEGIES = {
|
|
3212
|
+
"pulse-fast": {
|
|
3213
|
+
strategy: "pulse-fast",
|
|
3214
|
+
mechanism: "Client-side polling via @stackwright-pro/pulse",
|
|
3215
|
+
mechanismPackage: "@stackwright-pro/pulse",
|
|
3216
|
+
pulse: true,
|
|
3217
|
+
requiredPackages: { "@stackwright-pro/pulse": "latest", "@tanstack/react-query": "^5.0.0" },
|
|
3218
|
+
handoffFlags: ["PULSE_MODE=true"],
|
|
3219
|
+
description: "Real-time updates every few seconds. Uses client-side polling. Dashboard Otter should use *_pulse component variants."
|
|
3220
|
+
},
|
|
3221
|
+
"isr-fast": {
|
|
3222
|
+
strategy: "isr-fast",
|
|
3223
|
+
mechanism: "Next.js ISR",
|
|
3224
|
+
revalidateSeconds: 60,
|
|
3225
|
+
pulse: false,
|
|
3226
|
+
requiredPackages: {},
|
|
3227
|
+
handoffFlags: [],
|
|
3228
|
+
description: "Near real-time with 60-second ISR revalidation. Good for dashboards that need minute-level freshness."
|
|
3229
|
+
},
|
|
3230
|
+
"isr-standard": {
|
|
3231
|
+
strategy: "isr-standard",
|
|
3232
|
+
mechanism: "Next.js ISR",
|
|
3233
|
+
revalidateSeconds: 3600,
|
|
3234
|
+
pulse: false,
|
|
3235
|
+
requiredPackages: {},
|
|
3236
|
+
handoffFlags: [],
|
|
3237
|
+
description: "Standard hourly revalidation. Good for most API-backed pages."
|
|
3238
|
+
},
|
|
3239
|
+
"isr-slow": {
|
|
3240
|
+
strategy: "isr-slow",
|
|
3241
|
+
mechanism: "Next.js ISR",
|
|
3242
|
+
revalidateSeconds: 86400,
|
|
3243
|
+
pulse: false,
|
|
3244
|
+
requiredPackages: {},
|
|
3245
|
+
handoffFlags: [],
|
|
3246
|
+
description: "Daily revalidation. Good for infrequently changing data."
|
|
3247
|
+
}
|
|
3248
|
+
};
|
|
3249
|
+
function handleResolveDataStrategy(input) {
|
|
3250
|
+
const key = input.strategy.trim().toLowerCase();
|
|
3251
|
+
const match = DATA_STRATEGIES[key];
|
|
3252
|
+
if (!match) {
|
|
3253
|
+
const validKeys = Object.keys(DATA_STRATEGIES).join(", ");
|
|
3254
|
+
return {
|
|
3255
|
+
text: JSON.stringify({
|
|
3256
|
+
error: true,
|
|
3257
|
+
message: `Unknown strategy: "${input.strategy}". Valid strategies: ${validKeys}`,
|
|
3258
|
+
validStrategies: Object.keys(DATA_STRATEGIES)
|
|
3259
|
+
}),
|
|
3260
|
+
isError: true
|
|
3261
|
+
};
|
|
3262
|
+
}
|
|
3263
|
+
const configureIsrCall = match.pulse ? null : {
|
|
3264
|
+
tool: "stackwright_pro_configure_isr_batch",
|
|
3265
|
+
args: {
|
|
3266
|
+
collections: [{ name: "$COLLECTION", revalidateSeconds: match.revalidateSeconds }]
|
|
3267
|
+
}
|
|
3268
|
+
};
|
|
3269
|
+
return {
|
|
3270
|
+
text: JSON.stringify({ ...match, configureIsrCall }),
|
|
3271
|
+
isError: false
|
|
3272
|
+
};
|
|
3273
|
+
}
|
|
3274
|
+
function fail(errors) {
|
|
3275
|
+
return { text: JSON.stringify({ valid: false, errors, warnings: [] }), isError: true };
|
|
3276
|
+
}
|
|
3277
|
+
function handleValidateWorkflow(input) {
|
|
3278
|
+
const cwd = input._cwd ?? process.cwd();
|
|
3279
|
+
let raw;
|
|
3280
|
+
if (input.workflow && Object.keys(input.workflow).length > 0) {
|
|
3281
|
+
raw = input.workflow;
|
|
3282
|
+
} else {
|
|
3283
|
+
const artifactPath = (0, import_path8.join)(cwd, ".stackwright", "artifacts", "workflow-config.json");
|
|
3284
|
+
if (!(0, import_fs8.existsSync)(artifactPath)) {
|
|
3285
|
+
return fail([
|
|
3286
|
+
{
|
|
3287
|
+
code: "NO_WORKFLOW",
|
|
3288
|
+
message: "No workflow provided and .stackwright/artifacts/workflow-config.json not found. Pass a workflow object or run the workflow otter first."
|
|
3289
|
+
}
|
|
3290
|
+
]);
|
|
3291
|
+
}
|
|
3292
|
+
try {
|
|
3293
|
+
raw = JSON.parse((0, import_fs8.readFileSync)(artifactPath, "utf8"));
|
|
3294
|
+
} catch (err) {
|
|
3295
|
+
return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
const workflow = raw.workflow && typeof raw.workflow === "object" ? raw.workflow : raw;
|
|
3299
|
+
const errors = [];
|
|
3300
|
+
const warnings = [];
|
|
3301
|
+
if (typeof workflow.id !== "string" || !workflow.id) {
|
|
3302
|
+
errors.push({ code: "MISSING_ID", message: "workflow.id is required", path: "workflow.id" });
|
|
3303
|
+
} else if (!/^[a-z0-9-]+$/.test(workflow.id)) {
|
|
3304
|
+
errors.push({
|
|
3305
|
+
code: "INVALID_ID",
|
|
3306
|
+
message: `workflow.id "${workflow.id}" must match ^[a-z0-9-]+$`,
|
|
3307
|
+
path: "workflow.id"
|
|
3308
|
+
});
|
|
3309
|
+
}
|
|
3310
|
+
if (typeof workflow.label !== "string" || !workflow.label) {
|
|
3311
|
+
errors.push({
|
|
3312
|
+
code: "MISSING_LABEL",
|
|
3313
|
+
message: "workflow.label is required",
|
|
3314
|
+
path: "workflow.label"
|
|
3315
|
+
});
|
|
3316
|
+
}
|
|
3317
|
+
const steps = workflow.steps;
|
|
3318
|
+
if (!Array.isArray(steps)) {
|
|
3319
|
+
errors.push({
|
|
3320
|
+
code: "MISSING_STEPS",
|
|
3321
|
+
message: "workflow.steps must be an array",
|
|
3322
|
+
path: "workflow.steps"
|
|
3323
|
+
});
|
|
3324
|
+
return { text: JSON.stringify({ valid: false, errors, warnings }), isError: false };
|
|
3325
|
+
}
|
|
3326
|
+
if (steps.length < 2) {
|
|
3327
|
+
errors.push({
|
|
3328
|
+
code: "TOO_FEW_STEPS",
|
|
3329
|
+
message: "A workflow must have at least 2 steps",
|
|
3330
|
+
path: "workflow.steps"
|
|
3331
|
+
});
|
|
3332
|
+
}
|
|
3333
|
+
const stepIds = /* @__PURE__ */ new Set();
|
|
3334
|
+
const duplicateIds = [];
|
|
3335
|
+
for (const step of steps) {
|
|
3336
|
+
if (!step || typeof step !== "object") continue;
|
|
3337
|
+
const id = step.id;
|
|
3338
|
+
if (typeof id !== "string" || !id) {
|
|
3339
|
+
errors.push({
|
|
3340
|
+
code: "MISSING_STEP_ID",
|
|
3341
|
+
message: "Every step must have an id",
|
|
3342
|
+
path: "workflow.steps"
|
|
3343
|
+
});
|
|
3344
|
+
continue;
|
|
3345
|
+
}
|
|
3346
|
+
if (!/^[a-z0-9_]+$/.test(id)) {
|
|
3347
|
+
errors.push({
|
|
3348
|
+
code: "INVALID_STEP_ID",
|
|
3349
|
+
message: `Step ID "${id}" must match ^[a-z0-9_]+$`,
|
|
3350
|
+
path: `workflow.steps[${id}].id`
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
if (stepIds.has(id)) duplicateIds.push(id);
|
|
3354
|
+
stepIds.add(id);
|
|
3355
|
+
}
|
|
3356
|
+
if (duplicateIds.length > 0) {
|
|
3357
|
+
errors.push({
|
|
3358
|
+
code: "DUPLICATE_STEP_IDS",
|
|
3359
|
+
message: `Duplicate step IDs: ${duplicateIds.join(", ")}`,
|
|
3360
|
+
path: "workflow.steps"
|
|
3361
|
+
});
|
|
3362
|
+
}
|
|
3363
|
+
const initialStep = workflow.initial_step;
|
|
3364
|
+
if (typeof initialStep !== "string" || !initialStep) {
|
|
3365
|
+
errors.push({
|
|
3366
|
+
code: "MISSING_INITIAL_STEP",
|
|
3367
|
+
message: "workflow.initial_step is required",
|
|
3368
|
+
path: "workflow.initial_step"
|
|
3369
|
+
});
|
|
3370
|
+
} else if (!stepIds.has(initialStep)) {
|
|
3371
|
+
errors.push({
|
|
3372
|
+
code: "INVALID_INITIAL_STEP",
|
|
3373
|
+
message: `initial_step "${initialStep}" does not reference an existing step. Valid: ${[...stepIds].join(", ")}`,
|
|
3374
|
+
path: "workflow.initial_step"
|
|
3375
|
+
});
|
|
3376
|
+
}
|
|
3377
|
+
for (const step of steps) {
|
|
3378
|
+
if (!step || typeof step !== "object") continue;
|
|
3379
|
+
const s = step;
|
|
3380
|
+
const stepId = String(s.id ?? "??");
|
|
3381
|
+
validateTransitionTargets(s, stepId, stepIds, errors);
|
|
3382
|
+
collectServiceWarnings(s, stepId, warnings);
|
|
3383
|
+
}
|
|
3384
|
+
if (typeof workflow.persistence === "string" && workflow.persistence.startsWith("service:")) {
|
|
3385
|
+
warnings.push({
|
|
3386
|
+
code: "WARN_SERVICE_REFERENCE",
|
|
3387
|
+
message: 'service: reference at "workflow.persistence" requires @stackwright-pro/services. Prism mock fallback will be used until services layer is configured.',
|
|
3388
|
+
path: "workflow.persistence"
|
|
3389
|
+
});
|
|
3390
|
+
}
|
|
3391
|
+
const hasTerminal = steps.some((step) => {
|
|
3392
|
+
if (!step || typeof step !== "object") return false;
|
|
3393
|
+
return step.type === "terminal";
|
|
3394
|
+
});
|
|
3395
|
+
if (!hasTerminal) {
|
|
3396
|
+
errors.push({
|
|
3397
|
+
code: "NO_TERMINAL_STATE",
|
|
3398
|
+
message: "Workflow must have at least one step with type: terminal",
|
|
3399
|
+
path: "workflow.steps"
|
|
3400
|
+
});
|
|
3401
|
+
}
|
|
3402
|
+
return { text: JSON.stringify({ valid: errors.length === 0, errors, warnings }), isError: false };
|
|
3403
|
+
}
|
|
3404
|
+
function validateTransitionTargets(step, stepId, stepIds, errors) {
|
|
3405
|
+
const check = (target, path3) => {
|
|
3406
|
+
if (typeof target === "string" && !stepIds.has(target)) {
|
|
3407
|
+
errors.push({
|
|
3408
|
+
code: "ORPHANED_TRANSITION",
|
|
3409
|
+
message: `Step "${stepId}" transitions to "${target}" which does not exist`,
|
|
3410
|
+
path: path3
|
|
3411
|
+
});
|
|
3412
|
+
}
|
|
3413
|
+
};
|
|
3414
|
+
const onSubmit = step.on_submit;
|
|
3415
|
+
if (onSubmit && typeof onSubmit === "object") {
|
|
3416
|
+
check(onSubmit.transition, `workflow.steps[${stepId}].on_submit.transition`);
|
|
3417
|
+
}
|
|
3418
|
+
if (Array.isArray(step.actions)) {
|
|
3419
|
+
for (const action of step.actions) {
|
|
3420
|
+
if (!action || typeof action !== "object") continue;
|
|
3421
|
+
const a = action;
|
|
3422
|
+
check(a.transition, `workflow.steps[${stepId}].actions[${a.id ?? "??"}].transition`);
|
|
3423
|
+
}
|
|
3424
|
+
}
|
|
3425
|
+
if (Array.isArray(step.conditions)) {
|
|
3426
|
+
for (const cond of step.conditions) {
|
|
3427
|
+
if (!cond || typeof cond !== "object") continue;
|
|
3428
|
+
const then = cond.then;
|
|
3429
|
+
if (then && typeof then === "object") {
|
|
3430
|
+
check(then.transition, `workflow.steps[${stepId}].conditions`);
|
|
3431
|
+
}
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
if (Array.isArray(step.show_fields_from)) {
|
|
3435
|
+
for (const ref of step.show_fields_from)
|
|
3436
|
+
check(ref, `workflow.steps[${stepId}].show_fields_from`);
|
|
3437
|
+
}
|
|
3438
|
+
const display = step.display;
|
|
3439
|
+
if (display && typeof display === "object") {
|
|
3440
|
+
check(display.source_step, `workflow.steps[${stepId}].display.source_step`);
|
|
3441
|
+
if (Array.isArray(display.source_steps)) {
|
|
3442
|
+
for (const ref of display.source_steps)
|
|
3443
|
+
check(ref, `workflow.steps[${stepId}].display.source_steps`);
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
function collectServiceWarnings(step, stepId, warnings) {
|
|
3448
|
+
const isService = (val) => typeof val === "string" && val.startsWith("service:");
|
|
3449
|
+
const warn = (path3) => {
|
|
3450
|
+
warnings.push({
|
|
3451
|
+
code: "WARN_SERVICE_REFERENCE",
|
|
3452
|
+
message: `service: reference at "${path3}" requires @stackwright-pro/services. Prism mock fallback will be used until services layer is configured.`,
|
|
3453
|
+
path: path3
|
|
3454
|
+
});
|
|
3455
|
+
};
|
|
3456
|
+
const onSubmit = step.on_submit;
|
|
3457
|
+
if (onSubmit && typeof onSubmit === "object" && isService(onSubmit.action))
|
|
3458
|
+
warn(`${stepId}.on_submit.action`);
|
|
3459
|
+
const onEnter = step.on_enter;
|
|
3460
|
+
if (onEnter && typeof onEnter === "object" && isService(onEnter.action))
|
|
3461
|
+
warn(`${stepId}.on_enter.action`);
|
|
3462
|
+
if (Array.isArray(step.actions)) {
|
|
3463
|
+
for (const action of step.actions) {
|
|
3464
|
+
if (!action || typeof action !== "object") continue;
|
|
3465
|
+
const a = action;
|
|
3466
|
+
if (isService(a.action)) warn(`${stepId}.actions.${a.id ?? "??"}.action`);
|
|
3467
|
+
}
|
|
3468
|
+
}
|
|
3469
|
+
if (Array.isArray(step.fields)) {
|
|
3470
|
+
for (const field of step.fields) {
|
|
3471
|
+
if (!field || typeof field !== "object") continue;
|
|
3472
|
+
const f = field;
|
|
3473
|
+
if (isService(f.data_source)) warn(`${stepId}.fields.${f.name ?? "??"}.data_source`);
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
function registerDomainTools(server2) {
|
|
3478
|
+
const res = (r) => ({
|
|
3479
|
+
content: [{ type: "text", text: r.text }],
|
|
3480
|
+
isError: r.isError
|
|
3481
|
+
});
|
|
3482
|
+
server2.tool(
|
|
3483
|
+
"stackwright_pro_list_collections",
|
|
3484
|
+
"List API-backed collections available for page generation. Reads from Data Otter artifact (.stackwright/artifacts/data-config.json) or stackwright.yml. Call this before generating pages that bind to data.",
|
|
3485
|
+
{},
|
|
3486
|
+
async () => res(handleListCollections({}))
|
|
3487
|
+
);
|
|
3488
|
+
server2.tool(
|
|
3489
|
+
"stackwright_pro_resolve_data_strategy",
|
|
3490
|
+
"Look up the data freshness strategy configuration from the user's answer. Returns mechanism, revalidation seconds, required packages, and the exact MCP tool call to make. Replaces the strategy table in the data-otter prompt.",
|
|
3491
|
+
{
|
|
3492
|
+
strategy: import_zod13.z.string().describe(
|
|
3493
|
+
'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
|
|
3494
|
+
)
|
|
3495
|
+
},
|
|
3496
|
+
async ({ strategy }) => res(handleResolveDataStrategy({ strategy }))
|
|
3497
|
+
);
|
|
3498
|
+
server2.tool(
|
|
3499
|
+
"stackwright_pro_validate_workflow",
|
|
3500
|
+
"Validate a workflow definition against the Stackwright workflow schema. Checks step ID uniqueness, transition targets, terminal state existence, and service references. Call this after the workflow otter produces output.",
|
|
3501
|
+
{
|
|
3502
|
+
workflow: jsonCoerce(import_zod13.z.record(import_zod13.z.string(), import_zod13.z.unknown()).optional()).describe(
|
|
3503
|
+
"Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
|
|
3504
|
+
)
|
|
3505
|
+
},
|
|
3506
|
+
async ({ workflow }) => res(handleValidateWorkflow(workflow ? { workflow } : {}))
|
|
3507
|
+
);
|
|
3508
|
+
}
|
|
3509
|
+
|
|
3510
|
+
// package.json
|
|
3511
|
+
var package_default = {
|
|
3512
|
+
dependencies: {
|
|
3513
|
+
"@modelcontextprotocol/sdk": "^1.10.0",
|
|
3514
|
+
"@stackwright-pro/cli-data-explorer": "workspace:*",
|
|
3515
|
+
zod: "^4.3.6"
|
|
3516
|
+
},
|
|
3517
|
+
devDependencies: {
|
|
3518
|
+
"@types/node": "^24.1.0",
|
|
3519
|
+
tsup: "^8.5.0",
|
|
3520
|
+
typescript: "^5.8.3",
|
|
3521
|
+
vitest: "^4.0.18"
|
|
3522
|
+
},
|
|
3523
|
+
scripts: {
|
|
3524
|
+
prepublishOnly: "node scripts/verify-integrity-sync.js",
|
|
3525
|
+
build: "tsup",
|
|
3526
|
+
dev: "tsup --watch",
|
|
3527
|
+
start: "node dist/server.js",
|
|
3528
|
+
test: "vitest run",
|
|
3529
|
+
"test:coverage": "vitest run --coverage"
|
|
3530
|
+
},
|
|
3531
|
+
name: "@stackwright-pro/mcp",
|
|
3532
|
+
version: "0.2.0-alpha.13",
|
|
3533
|
+
description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
|
|
3534
|
+
license: "PROPRIETARY",
|
|
3535
|
+
main: "./dist/server.js",
|
|
3536
|
+
module: "./dist/server.mjs",
|
|
3537
|
+
types: "./dist/server.d.ts",
|
|
3538
|
+
exports: {
|
|
3539
|
+
".": {
|
|
3540
|
+
types: "./dist/server.d.ts",
|
|
3541
|
+
import: "./dist/server.mjs",
|
|
3542
|
+
require: "./dist/server.js"
|
|
3543
|
+
},
|
|
3544
|
+
"./integrity": {
|
|
3545
|
+
types: "./dist/integrity.d.ts",
|
|
3546
|
+
import: "./dist/integrity.mjs",
|
|
3547
|
+
require: "./dist/integrity.js"
|
|
1237
3548
|
}
|
|
1238
3549
|
},
|
|
1239
3550
|
files: [
|
|
@@ -1255,6 +3566,13 @@ registerIsrTools(server);
|
|
|
1255
3566
|
registerDashboardTools(server);
|
|
1256
3567
|
registerClarificationTools(server);
|
|
1257
3568
|
registerPackageTools(server);
|
|
3569
|
+
registerQuestionTools(server);
|
|
3570
|
+
registerOrchestrationTools(server);
|
|
3571
|
+
registerPipelineTools(server);
|
|
3572
|
+
registerSafeWriteTools(server);
|
|
3573
|
+
registerAuthTools(server);
|
|
3574
|
+
registerIntegrityTools(server);
|
|
3575
|
+
registerDomainTools(server);
|
|
1258
3576
|
async function main() {
|
|
1259
3577
|
const transport = new import_stdio.StdioServerTransport();
|
|
1260
3578
|
await server.connect(transport);
|