import { applyCookiePlacementsToHeaders, applyHttpQueryPlacementsToUrl, applyJsonBodyPlacements, sha256Hex, standardSchemaFromJsonSchema, toTool, type HttpRequestPlacements, type ToolDescriptor, type ToolMap, type ToolMetadata, type ToolPath, typeSignatureFromSchema,} from "@executor/codemode-core";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import { buildClientSchema, getIntrospectionQuery, getNamedType, isEnumType, isInputObjectType, isInterfaceType, isLeafType, isListType, isNonNullType, isObjectType, isScalarType, isUnionType, type GraphQLArgument, type GraphQLField, type GraphQLInputObjectType, type GraphQLInputType, type GraphQLInterfaceType, type GraphQLNamedType, type GraphQLObjectType, type GraphQLOutputType, type GraphQLSchema, type IntrospectionQuery,} from "graphql";import * as HashMap from "effect/HashMap";import * as Option from "effect/Option"; type JsonSchema = Record<string, unknown>;type GraphqlSchemaRefTable = Record<string, string>; type GraphqlToolKind = "request" | "field"; type GraphqlOperationType = "query" | "mutation"; const GRAPHQL_PRESENTATION_TYPE_MAX_LENGTH = 320; type GraphqlManifestToolBase = { toolId: string; rawToolId: string | null; toolName: string; description: string | null; inputSchema?: JsonSchema; outputSchema?: JsonSchema; exampleInput?: unknown;}; export type GraphqlRequestToolManifestEntry = GraphqlManifestToolBase & { kind: "request";}; export type GraphqlFieldToolManifestEntry = GraphqlManifestToolBase & { kind: "field"; group: GraphqlOperationType; leaf: string; fieldName: string; operationType: GraphqlOperationType; operationName: string; operationDocument: string; searchTerms: readonly string[];}; export type GraphqlToolManifestEntry = | GraphqlRequestToolManifestEntry | GraphqlFieldToolManifestEntry; export type GraphqlToolManifest = { version: 2; sourceHash: string; queryTypeName: string | null; mutationTypeName: string | null; subscriptionTypeName: string | null; schemaRefTable?: GraphqlSchemaRefTable; tools: readonly GraphqlToolManifestEntry[];}; export type GraphqlToolDefinition = { toolId: string; rawToolId: string | null; name: string; description: string; group: string | null; leaf: string | null; fieldName: string | null; operationType: GraphqlOperationType | null; operationName: string | null; operationDocument: string | null; searchTerms: readonly string[];}; export type GraphqlToolPresentation = { inputTypePreview: string; outputTypePreview: string; inputSchema?: JsonSchema; outputSchema?: JsonSchema; exampleInput?: unknown; providerData: GraphqlToolProviderData;}; type GraphqlToolPresentationResolver = { resolve(definition: GraphqlToolDefinition): GraphqlToolPresentation;}; const GraphqlToolKindSchema = Schema.Literal("request", "field"); const GraphqlOperationTypeSchema = Schema.Literal("query", "mutation"); export const GraphqlToolProviderDataSchema = Schema.Struct({ kind: Schema.Literal("graphql"), toolKind: GraphqlToolKindSchema, toolId: Schema.String, rawToolId: Schema.NullOr(Schema.String), group: Schema.NullOr(Schema.String), leaf: Schema.NullOr(Schema.String), fieldName: Schema.NullOr(Schema.String), operationType: Schema.NullOr(GraphqlOperationTypeSchema), operationName: Schema.NullOr(Schema.String), operationDocument: Schema.NullOr(Schema.String), queryTypeName: Schema.NullOr(Schema.String), mutationTypeName: Schema.NullOr(Schema.String), subscriptionTypeName: Schema.NullOr(Schema.String),}); export type GraphqlToolProviderData = typeof GraphqlToolProviderDataSchema.Type; type SelectedGraphqlOutput = { selectionSet: string; schema: JsonSchema;}; type GraphqlHttpInvocation = { endpoint: string; path: string; defaultHeaders?: Readonly<Record<string, string>>; credentialHeaders?: Readonly<Record<string, string>>; credentialPlacements?: HttpRequestPlacements; query: string; variables?: Record<string, unknown>; operationName?: string; requestHeaders?: Record<string, string>;}; const BLOCKED_RESPONSE_HEADER_NAMES = new Set([ "authorization", "authentication-info", "cookie", "proxy-authenticate", "proxy-authorization", "set-cookie", "set-cookie2", "www-authenticate", "x-api-key", "x-auth-token", "x-csrf-token",]); const PREFERRED_LEAF_FIELD_NAMES = [ "id", "identifier", "key", "slug", "name", "title", "number", "url", "state", "status", "success",] as const; const PREFERRED_NESTED_FIELD_NAMES = [ "node", "nodes", "edge", "edges", "pageInfo", "viewer", "user", "users", "team", "teams", "project", "projects", "organization", "issue", "issues", "creator", "assignee", "items",] as const; const asToolPath = (value: string): ToolPath => value as ToolPath; const asRecord = (value: unknown): Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {}; const asString = (value: unknown): string | null => typeof value === "string" && value.trim().length > 0 ? value : null; const asStringRecord = (value: unknown): Record<string, string> => { const record = asRecord(value); const normalized: Record<string, string> = {}; for (const [key, entry] of Object.entries(record)) { if (typeof entry === "string") { normalized[key] = entry; } } return normalized;}; const sanitizeResponseHeaders = ( headers: Readonly<Record<string, string>>,): Record<string, string> => { const sanitized: Record<string, string> = {}; for (const [rawName, rawValue] of Object.entries(headers)) { const name = rawName.trim().toLowerCase(); if (name.length === 0 || BLOCKED_RESPONSE_HEADER_NAMES.has(name)) { continue; } sanitized[name] = rawValue; } return sanitized;}; const normalizeHttpUrl = (value: string): string => { const trimmed = value.trim(); if (trimmed.length === 0) { throw new Error("GraphQL endpoint is empty"); } const parsed = new URL(trimmed); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new Error("GraphQL endpoint must be http or https"); } return parsed.toString();}; const graphqlToolError = (message: string, cause?: unknown): Error => new Error(cause instanceof Error ? `${message}: ${cause.message}` : message); const parseGraphqlResponseBody = async ( response: Response,): Promise<unknown> => { const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""; if (contentType.includes("application/json")) { return await response.json(); } return await response.text();}; const hasGraphqlErrors = (value: unknown): boolean => Array.isArray(asRecord(value).errors); const splitWords = (value: string): Array<string> => value .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, "$1 $2") .replace(/[^a-zA-Z0-9]+/g, " ") .trim() .split(/\s+/) .filter((part) => part.length > 0); const toCamelCase = (value: string): string => { const words = splitWords(value).map((part) => part.toLowerCase()); if (words.length === 0) { return "tool"; } const [first, ...rest] = words; return `${first}${rest.map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join("")}`;}; const toPascalCase = (value: string): string => { const camel = toCamelCase(value); return `${camel[0]?.toUpperCase() ?? ""}${camel.slice(1)}`;}; const toTitleCase = (value: string): string => splitWords(value) .map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`) .join(" "); const withSchemaDescription = ( schema: JsonSchema, description: string | null | undefined,): JsonSchema => { const trimmed = description?.trim(); return trimmed ? { ...schema, description: trimmed } : schema;}; const withSchemaDefault = (schema: JsonSchema, value: unknown): JsonSchema => value !== undefined ? { ...schema, default: value } : schema; const withSchemaDeprecation = ( schema: JsonSchema, deprecationReason: string | null | undefined,): JsonSchema => { const trimmed = deprecationReason?.trim(); return trimmed ? { ...schema, deprecated: true, "x-deprecationReason": trimmed } : schema;}; const introspectionQueryFromDocument = ( documentText: string,): IntrospectionQuery => { let parsed: unknown; try { parsed = JSON.parse(documentText) as unknown; } catch (cause) { throw new Error( `GraphQL document is not valid JSON: ${cause instanceof Error ? cause.message : String(cause)}`, ); } const record = asRecord(parsed); if (Array.isArray(record.errors) && record.errors.length > 0) { const messages = record.errors .map((entry) => asString(asRecord(entry).message)) .filter((message): message is string => message !== null); throw new Error( messages.length > 0 ? `GraphQL introspection returned errors: ${messages.join("; ")}` : "GraphQL introspection returned errors", ); } const data = record.data; if (!data || typeof data !== "object" || !("__schema" in data)) { throw new Error("GraphQL introspection document is missing data.__schema"); } return data as IntrospectionQuery;}; const GRAPHQL_REQUEST_INPUT_SCHEMA = { type: "object", properties: { query: { type: "string", description: "GraphQL query or mutation document.", }, variables: { type: "object", description: "Optional GraphQL variables.", additionalProperties: true, }, operationName: { type: "string", description: "Optional GraphQL operation name.", }, headers: { type: "object", description: "Optional per-request headers.", additionalProperties: { type: "string", }, }, }, required: ["query"], additionalProperties: false,} as const; const GRAPHQL_REQUEST_OUTPUT_SCHEMA = { type: "object", properties: { status: { type: "number", }, headers: { type: "object", additionalProperties: { type: "string", }, }, body: {}, }, required: ["status", "headers", "body"], additionalProperties: false,} as const; export const GRAPHQL_INTROSPECTION_QUERY = getIntrospectionQuery({ descriptions: true, inputValueDeprecation: true, schemaDescription: true,}); const scalarInputSchema = (name: string): JsonSchema => { switch (name) { case "String": case "ID": case "Date": case "DateTime": case "DateTimeOrDuration": case "Duration": case "UUID": case "TimelessDate": case "TimelessDateOrDuration": case "URI": return { type: "string" }; case "Int": case "Float": return { type: "number" }; case "Boolean": return { type: "boolean" }; case "JSONObject": return { type: "object", additionalProperties: true, }; case "JSONString": return { type: "string" }; case "JSON": return {}; default: return {}; }}; const scalarExampleValue = (name: string): unknown => { switch (name) { case "String": return "value"; case "ID": return "id"; case "Date": return "2026-03-08"; case "DateTime": case "DateTimeOrDuration": return "2026-03-08T00:00:00.000Z"; case "UUID": return "00000000-0000-0000-0000-000000000000"; case "TimelessDate": case "TimelessDateOrDuration": return "2026-03-08"; case "Duration": return "P1D"; case "URI": return "https://example.com"; case "Int": return 1; case "Float": return 1.5; case "Boolean": return true; case "JSONObject": return {}; case "JSONString": return "{}"; default: return {}; }}; const GRAPHQL_SCHEMA_REF_PREFIX = "#/$defs/graphql"; const graphqlScalarRef = (name: string): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/scalars/${name}`; const graphqlEnumRef = (name: string): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/enums/${name}`; const graphqlInputObjectRef = (name: string): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/input/${name}`; const graphqlOutputTypeRef = (name: string, depth: number): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/output/${depth === 0 ? name : `${name}__depth${depth}`}`; const schemaRef = (ref: string): JsonSchema => ({ $ref: ref,}); const typenameOnlyObjectSchema = (): JsonSchema => ({ type: "object", properties: { __typename: { type: "string" },Lines 1–500 of 1747. Load more
import { applyCookiePlacementsToHeaders, applyHttpQueryPlacementsToUrl, applyJsonBodyPlacements, sha256Hex, standardSchemaFromJsonSchema, toTool, type HttpRequestPlacements, type ToolDescriptor, type ToolMap, type ToolMetadata, type ToolPath, typeSignatureFromSchema, } from "@executor/codemode-core"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { buildClientSchema, getIntrospectionQuery, getNamedType, isEnumType, isInputObjectType, isInterfaceType, isLeafType, isListType, isNonNullType, isObjectType, isScalarType, isUnionType, type GraphQLArgument, type GraphQLField, type GraphQLInputObjectType, type GraphQLInputType, type GraphQLInterfaceType, type GraphQLNamedType, type GraphQLObjectType, type GraphQLOutputType, type GraphQLSchema, type IntrospectionQuery, } from "graphql"; import * as HashMap from "effect/HashMap"; import * as Option from "effect/Option"; type JsonSchema = Record<string, unknown>; type GraphqlSchemaRefTable = Record<string, string>; type GraphqlToolKind = "request" | "field"; type GraphqlOperationType = "query" | "mutation"; const GRAPHQL_PRESENTATION_TYPE_MAX_LENGTH = 320; type GraphqlManifestToolBase = { toolId: string; rawToolId: string | null; toolName: string; description: string | null; inputSchema?: JsonSchema; outputSchema?: JsonSchema; exampleInput?: unknown; }; export type GraphqlRequestToolManifestEntry = GraphqlManifestToolBase & { kind: "request"; }; export type GraphqlFieldToolManifestEntry = GraphqlManifestToolBase & { kind: "field"; group: GraphqlOperationType; leaf: string; fieldName: string; operationType: GraphqlOperationType; operationName: string; operationDocument: string; searchTerms: readonly string[]; }; export type GraphqlToolManifestEntry = | GraphqlRequestToolManifestEntry | GraphqlFieldToolManifestEntry; export type GraphqlToolManifest = { version: 2; sourceHash: string; queryTypeName: string | null; mutationTypeName: string | null; subscriptionTypeName: string | null; schemaRefTable?: GraphqlSchemaRefTable; tools: readonly GraphqlToolManifestEntry[]; }; export type GraphqlToolDefinition = { toolId: string; rawToolId: string | null; name: string; description: string; group: string | null; leaf: string | null; fieldName: string | null; operationType: GraphqlOperationType | null; operationName: string | null; operationDocument: string | null; searchTerms: readonly string[]; }; export type GraphqlToolPresentation = { inputTypePreview: string; outputTypePreview: string; inputSchema?: JsonSchema; outputSchema?: JsonSchema; exampleInput?: unknown; providerData: GraphqlToolProviderData; }; type GraphqlToolPresentationResolver = { resolve(definition: GraphqlToolDefinition): GraphqlToolPresentation; }; const GraphqlToolKindSchema = Schema.Literal("request", "field"); const GraphqlOperationTypeSchema = Schema.Literal("query", "mutation"); export const GraphqlToolProviderDataSchema = Schema.Struct({ kind: Schema.Literal("graphql"), toolKind: GraphqlToolKindSchema, toolId: Schema.String, rawToolId: Schema.NullOr(Schema.String), group: Schema.NullOr(Schema.String), leaf: Schema.NullOr(Schema.String), fieldName: Schema.NullOr(Schema.String), operationType: Schema.NullOr(GraphqlOperationTypeSchema), operationName: Schema.NullOr(Schema.String), operationDocument: Schema.NullOr(Schema.String), queryTypeName: Schema.NullOr(Schema.String), mutationTypeName: Schema.NullOr(Schema.String), subscriptionTypeName: Schema.NullOr(Schema.String), }); export type GraphqlToolProviderData = typeof GraphqlToolProviderDataSchema.Type; type SelectedGraphqlOutput = { selectionSet: string; schema: JsonSchema; }; type GraphqlHttpInvocation = { endpoint: string; path: string; defaultHeaders?: Readonly<Record<string, string>>; credentialHeaders?: Readonly<Record<string, string>>; credentialPlacements?: HttpRequestPlacements; query: string; variables?: Record<string, unknown>; operationName?: string; requestHeaders?: Record<string, string>; }; const BLOCKED_RESPONSE_HEADER_NAMES = new Set([ "authorization", "authentication-info", "cookie", "proxy-authenticate", "proxy-authorization", "set-cookie", "set-cookie2", "www-authenticate", "x-api-key", "x-auth-token", "x-csrf-token", ]); const PREFERRED_LEAF_FIELD_NAMES = [ "id", "identifier", "key", "slug", "name", "title", "number", "url", "state", "status", "success", ] as const; const PREFERRED_NESTED_FIELD_NAMES = [ "node", "nodes", "edge", "edges", "pageInfo", "viewer", "user", "users", "team", "teams", "project", "projects", "organization", "issue", "issues", "creator", "assignee", "items", ] as const; const asToolPath = (value: string): ToolPath => value as ToolPath; const asRecord = (value: unknown): Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {}; const asString = (value: unknown): string | null => typeof value === "string" && value.trim().length > 0 ? value : null; const asStringRecord = (value: unknown): Record<string, string> => { const record = asRecord(value); const normalized: Record<string, string> = {}; for (const [key, entry] of Object.entries(record)) { if (typeof entry === "string") { normalized[key] = entry; } } return normalized; }; const sanitizeResponseHeaders = ( headers: Readonly<Record<string, string>>, ): Record<string, string> => { const sanitized: Record<string, string> = {}; for (const [rawName, rawValue] of Object.entries(headers)) { const name = rawName.trim().toLowerCase(); if (name.length === 0 || BLOCKED_RESPONSE_HEADER_NAMES.has(name)) { continue; } sanitized[name] = rawValue; } return sanitized; }; const normalizeHttpUrl = (value: string): string => { const trimmed = value.trim(); if (trimmed.length === 0) { throw new Error("GraphQL endpoint is empty"); } const parsed = new URL(trimmed); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new Error("GraphQL endpoint must be http or https"); } return parsed.toString(); }; const graphqlToolError = (message: string, cause?: unknown): Error => new Error(cause instanceof Error ? `${message}: ${cause.message}` : message); const parseGraphqlResponseBody = async ( response: Response, ): Promise<unknown> => { const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""; if (contentType.includes("application/json")) { return await response.json(); } return await response.text(); }; const hasGraphqlErrors = (value: unknown): boolean => Array.isArray(asRecord(value).errors); const splitWords = (value: string): Array<string> => value .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, "$1 $2") .replace(/[^a-zA-Z0-9]+/g, " ") .trim() .split(/\s+/) .filter((part) => part.length > 0); const toCamelCase = (value: string): string => { const words = splitWords(value).map((part) => part.toLowerCase()); if (words.length === 0) { return "tool"; } const [first, ...rest] = words; return `${first}${rest.map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join("")}`; }; const toPascalCase = (value: string): string => { const camel = toCamelCase(value); return `${camel[0]?.toUpperCase() ?? ""}${camel.slice(1)}`; }; const toTitleCase = (value: string): string => splitWords(value) .map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`) .join(" "); const withSchemaDescription = ( schema: JsonSchema, description: string | null | undefined, ): JsonSchema => { const trimmed = description?.trim(); return trimmed ? { ...schema, description: trimmed } : schema; }; const withSchemaDefault = (schema: JsonSchema, value: unknown): JsonSchema => value !== undefined ? { ...schema, default: value } : schema; const withSchemaDeprecation = ( schema: JsonSchema, deprecationReason: string | null | undefined, ): JsonSchema => { const trimmed = deprecationReason?.trim(); return trimmed ? { ...schema, deprecated: true, "x-deprecationReason": trimmed } : schema; }; const introspectionQueryFromDocument = ( documentText: string, ): IntrospectionQuery => { let parsed: unknown; try { parsed = JSON.parse(documentText) as unknown; } catch (cause) { throw new Error( `GraphQL document is not valid JSON: ${cause instanceof Error ? cause.message : String(cause)}`, ); } const record = asRecord(parsed); if (Array.isArray(record.errors) && record.errors.length > 0) { const messages = record.errors .map((entry) => asString(asRecord(entry).message)) .filter((message): message is string => message !== null); throw new Error( messages.length > 0 ? `GraphQL introspection returned errors: ${messages.join("; ")}` : "GraphQL introspection returned errors", ); } const data = record.data; if (!data || typeof data !== "object" || !("__schema" in data)) { throw new Error("GraphQL introspection document is missing data.__schema"); } return data as IntrospectionQuery; }; const GRAPHQL_REQUEST_INPUT_SCHEMA = { type: "object", properties: { query: { type: "string", description: "GraphQL query or mutation document.", }, variables: { type: "object", description: "Optional GraphQL variables.", additionalProperties: true, }, operationName: { type: "string", description: "Optional GraphQL operation name.", }, headers: { type: "object", description: "Optional per-request headers.", additionalProperties: { type: "string", }, }, }, required: ["query"], additionalProperties: false, } as const; const GRAPHQL_REQUEST_OUTPUT_SCHEMA = { type: "object", properties: { status: { type: "number", }, headers: { type: "object", additionalProperties: { type: "string", }, }, body: {}, }, required: ["status", "headers", "body"], additionalProperties: false, } as const; export const GRAPHQL_INTROSPECTION_QUERY = getIntrospectionQuery({ descriptions: true, inputValueDeprecation: true, schemaDescription: true, }); const scalarInputSchema = (name: string): JsonSchema => { switch (name) { case "String": case "ID": case "Date": case "DateTime": case "DateTimeOrDuration": case "Duration": case "UUID": case "TimelessDate": case "TimelessDateOrDuration": case "URI": return { type: "string" }; case "Int": case "Float": return { type: "number" }; case "Boolean": return { type: "boolean" }; case "JSONObject": return { type: "object", additionalProperties: true, }; case "JSONString": return { type: "string" }; case "JSON": return {}; default: return {}; } }; const scalarExampleValue = (name: string): unknown => { switch (name) { case "String": return "value"; case "ID": return "id"; case "Date": return "2026-03-08"; case "DateTime": case "DateTimeOrDuration": return "2026-03-08T00:00:00.000Z"; case "UUID": return "00000000-0000-0000-0000-000000000000"; case "TimelessDate": case "TimelessDateOrDuration": return "2026-03-08"; case "Duration": return "P1D"; case "URI": return "https://example.com"; case "Int": return 1; case "Float": return 1.5; case "Boolean": return true; case "JSONObject": return {}; case "JSONString": return "{}"; default: return {}; } }; const GRAPHQL_SCHEMA_REF_PREFIX = "#/$defs/graphql"; const graphqlScalarRef = (name: string): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/scalars/${name}`; const graphqlEnumRef = (name: string): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/enums/${name}`; const graphqlInputObjectRef = (name: string): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/input/${name}`; const graphqlOutputTypeRef = (name: string, depth: number): string => `${GRAPHQL_SCHEMA_REF_PREFIX}/output/${depth === 0 ? name : `${name}__depth${depth}`}`; const schemaRef = (ref: string): JsonSchema => ({ $ref: ref, }); const typenameOnlyObjectSchema = (): JsonSchema => ({ type: "object", properties: { __typename: { type: "string" },