Rhys Sullivanrm unused variables0205ac18 months agoHistory
1405 lines · 41.0 KB · TypeScript
RawDownload
import { sha256Hex } from "@executor/codemode-core";import * as ParseResult from "effect/ParseResult";import { Schema } from "effect"; import {  type CapabilityId,  DiagnosticIdSchema,  type DiagnosticId,  DocumentIdSchema,  type DocumentId,  type ExecutableId,  ResourceIdSchema,  type ResourceId,  type ResponseSymbolId,  type ResponseSetId,  type ShapeSymbolId,  ShapeSymbolIdSchema,  type SymbolId,} from "./ids";import {  CatalogFragmentV1Schema,  type CatalogFragmentV1,  CatalogSnapshotV1Schema,  CatalogV1Schema,  type CatalogV1,  type Capability,  type ContentSpec,  type DocumentationBlock,  type Executable,  type ImportDiagnostic,  type ImportMetadata,  type InteractionSpec,  type ResponseSet,  type ResponseSymbol,  type ShapeSymbol,  type StatusMatch,  type Symbol as IrSymbol,} from "./model"; export interface ToolDescriptor {  toolPath: string[];  capabilityId: CapabilityId;  title?: string;  summary?: string;  effect: Capability["semantics"]["effect"];  interaction: {    mayRequireApproval: boolean;    mayElicit: boolean;  };  callShapeId: ShapeSymbolId;  resultShapeId?: ShapeSymbolId;  responseSetId: ResponseSetId;  diagnosticCounts: {    warning: number;    error: number;  };} export interface ToolSearchDoc {  capabilityId: CapabilityId;  toolPath: string[];  title?: string;  summary?: string;  tags?: string[];  protocolHints: string[];  authHints: string[];  effect: Capability["semantics"]["effect"];} export interface CapabilitySummaryView {  capabilityId: CapabilityId;  toolPath: string[];  summary?: string;  executableIds: ExecutableId[];  auth: Capability["auth"];  interaction: InteractionSpec;  callShapeId: ShapeSymbolId;  resultShapeId?: ShapeSymbolId;  responseSetId: ResponseSetId;  diagnosticIds?: DiagnosticId[];} export interface SymbolShallowView {  symbolId: SymbolId;  kind: IrSymbol["kind"];  title?: string;  summary?: string;  edges: Array<{ label: string; targetId: SymbolId }>;} export interface SymbolExpandedView {  symbolId: SymbolId;  symbol: IrSymbol;  diagnostics?: ImportDiagnostic[];} export interface ProjectedCatalog {  catalog: CatalogV1;  toolDescriptors: Record<CapabilityId, ToolDescriptor>;  searchDocs: Record<CapabilityId, ToolSearchDoc>;  capabilityViews: Record<CapabilityId, CapabilitySummaryView>;} export interface CatalogInvariantViolation {  code:    | "missing_symbol_provenance"    | "missing_entity_provenance"    | "missing_document"    | "missing_provenance_document"    | "missing_resource_context"    | "missing_reference_target"    | "missing_unresolved_ref_diagnostic"    | "missing_executable"    | "missing_response_set"    | "missing_projection_shape"    | "missing_scope"    | "missing_service_scope"    | "invalid_preferred_executable"    | "missing_projection_synthetic_marker";  message: string;  entityId?: string;} export type DecodeCatalogError = Error; type CatalogSnapshotV1 = {  version: "ir.v1.snapshot";  import: ImportMetadata;  catalog: CatalogV1;}; const decodeCatalogSync = Schema.decodeUnknownSync(  CatalogV1Schema as Schema.Schema<CatalogV1, unknown, never>,);const decodeCatalogSnapshotSync = Schema.decodeUnknownSync(  CatalogSnapshotV1Schema as Schema.Schema<CatalogSnapshotV1, unknown, never>,);const decodeCatalogFragmentSync = Schema.decodeUnknownSync(  CatalogFragmentV1Schema as Schema.Schema<CatalogFragmentV1, unknown, never>,); const stableStringify = (value: unknown): string => {  if (value === null || typeof value !== "object") {    return JSON.stringify(value);  }   if (Array.isArray(value)) {    return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;  }   const entries = Object.entries(value as Record<string, unknown>)    .sort(([left], [right]) => left.localeCompare(right))    .map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`);  return `{${entries.join(",")}}`;}; const stableHash = (value: unknown): string => sha256Hex(stableStringify(value)).slice(0, 16); const unique = <T>(values: readonly T[]): T[] => [...new Set(values)]; const cloneCatalog = (catalog: CatalogV1): CatalogV1 => ({  version: catalog.version,  documents: { ...catalog.documents },  resources: { ...catalog.resources },  scopes: { ...catalog.scopes },  symbols: { ...catalog.symbols },  capabilities: { ...catalog.capabilities },  executables: { ...catalog.executables },  responseSets: { ...catalog.responseSets },  diagnostics: { ...catalog.diagnostics },}); const mutableRecord = <K extends string, V>(value: Readonly<Record<K, V>>): Record<K, V> =>  value as unknown as Record<K, V>; const createStableEntityId = <A extends string>(  make: (value: string) => A,  prefix: string,  value: unknown,): A => make(`${prefix}_${stableHash(value)}`); const emptyCatalog = (): CatalogV1 => ({  version: "ir.v1",  documents: {},  resources: {},  scopes: {},  symbols: {},  capabilities: {},  executables: {},  responseSets: {},  diagnostics: {},}); const authHintStrings = (catalog: CatalogV1, auth: Capability["auth"]): string[] => {  switch (auth.kind) {    case "none":      return ["none"];    case "scheme": {      const scheme = catalog.symbols[auth.schemeId];      if (!scheme || scheme.kind !== "securityScheme") {        return ["unknown"];      }      return [        scheme.schemeType,        ...((auth.scopes ?? []).map((scope: string) => `scope:${scope}`)),      ];    }    case "allOf":    case "anyOf":      return unique(auth.items.flatMap((item: Capability["auth"]) => authHintStrings(catalog, item)));  }}; const docsSummary = (docs: DocumentationBlock | undefined): string | undefined =>  docs?.summary ?? docs?.description; const getResponseSymbol = (  catalog: CatalogV1,  responseId: ResponseSymbolId,): ResponseSymbol | undefined => {  const symbol = catalog.symbols[responseId];  return symbol && symbol.kind === "response" ? symbol : undefined;}; const isJsonMediaType = (mediaType: string): boolean => {  const normalized = mediaType.trim().toLowerCase();  return normalized === "application/json"    || normalized.endsWith("+json")    || normalized === "text/json";}; const createDiagnostic = (  catalog: CatalogV1,  input: Omit<ImportDiagnostic, "id"> & { idSeed: unknown },): DiagnosticId => {  const diagnosticId = createStableEntityId(    DiagnosticIdSchema.make,    "diag",    input.idSeed,  );   mutableRecord(catalog.diagnostics)[diagnosticId] = {    id: diagnosticId,    level: input.level,    code: input.code,    message: input.message,    ...(input.relatedSymbolIds ? { relatedSymbolIds: input.relatedSymbolIds } : {}),    provenance: input.provenance,  };   return diagnosticId;}; const ensureProjectionResource = (  catalog: CatalogV1,  capability: Capability,): ResourceId => {  const resourceId = createStableEntityId(    ResourceIdSchema.make,    "res",    {      kind: "projection",      capabilityId: capability.id,    },  );   if (!catalog.resources[resourceId]) {    const serviceScope = catalog.scopes[capability.serviceScopeId];    const documentId = serviceScope?.provenance[0]?.documentId      ?? DocumentIdSchema.make(`doc_projection_${stableHash(capability.id)}`);     if (!catalog.documents[documentId]) {      mutableRecord(catalog.documents)[documentId] = {        id: documentId,        kind: "custom",        title: `Projection resource for ${capability.id}`,        fetchedAt: new Date(0).toISOString(),        rawRef: `synthetic://projection/${capability.id}`,      };    }     mutableRecord(catalog.resources)[resourceId] = {      id: resourceId,      documentId,      canonicalUri: `synthetic://projection/${capability.id}`,      baseUri: `synthetic://projection/${capability.id}`,      anchors: {},      dynamicAnchors: {},      synthetic: true,      provenance: capability.provenance,    };     createDiagnostic(catalog, {      idSeed: {        code: "synthetic_resource_context_created",        capabilityId: capability.id,      },      level: "info",      code: "synthetic_resource_context_created",      message: `Created synthetic projection resource for ${capability.id}`,      provenance: capability.provenance,    });  }   return resourceId;}; const createSyntheticShape = (  catalog: CatalogV1,  input: {    capability: Capability;    label: string;    node: ShapeSymbol["node"];    title?: string;    docs?: DocumentationBlock;    diagnostic?:      | {          level: ImportDiagnostic["level"];          code: ImportDiagnostic["code"];          message: string;          relatedSymbolIds?: SymbolId[];        }      | undefined;  },): ShapeSymbolId => {  const resourceId = ensureProjectionResource(catalog, input.capability);  const shapeId = createStableEntityId(    ShapeSymbolIdSchema.make,    "shape",    {      capabilityId: input.capability.id,      label: input.label,      node: input.node,    },  );   if (!catalog.symbols[shapeId]) {    const diagnostics = input.diagnostic      ? [          createDiagnostic(catalog, {            idSeed: {              code: input.diagnostic.code,              shapeId,            },            level: input.diagnostic.level,            code: input.diagnostic.code,            message: input.diagnostic.message,            ...(input.diagnostic.relatedSymbolIds              ? { relatedSymbolIds: input.diagnostic.relatedSymbolIds }              : {}),            provenance: input.capability.provenance,          }),        ]      : undefined;     mutableRecord(catalog.symbols)[shapeId] = {      id: shapeId,      kind: "shape",      resourceId,      ...(input.title ? { title: input.title } : {}),      ...(input.docs ? { docs: input.docs } : {}),      node: input.node,      synthetic: true,      provenance: input.capability.provenance,      ...(diagnostics ? { diagnosticIds: diagnostics } : {}),    };  }   return shapeId;}; const contentShapeId = (  catalog: CatalogV1,  capability: Capability,  contents: readonly ContentSpec[] | undefined,  label: string,): ShapeSymbolId | undefined => {  const shapeIds = unique(    (contents ?? [])      .map((content) => content.shapeId)      .filter((shapeId): shapeId is ShapeSymbolId => shapeId !== undefined),  );   if (shapeIds.length === 0) {    return undefined;  }   if (shapeIds.length === 1) {    return shapeIds[0];  }   return createSyntheticShape(catalog, {    capability,    label,    title: `${capability.surface.title ?? capability.id} content union`,    node: {      type: "anyOf",      items: shapeIds,    },    diagnostic: {      level: "warning",      code: "projection_result_shape_synthesized",      message: `Synthesized content union for ${capability.id}`,      relatedSymbolIds: shapeIds,    },  });};  const chooseExecutable = (catalog: CatalogV1, capability: Capability): Executable => {  const preferredId = capability.preferredExecutableId;  if (preferredId) {    const preferred = catalog.executables[preferredId];    if (preferred) {      return preferred;    }  }   const executables = capability.executableIds    .map((executableId) => catalog.executables[executableId])    .filter((executable): executable is Executable => executable !== undefined);   if (executables.length === 0) {    throw new Error(`Capability ${capability.id} has no executables`);  }   return executables[0];}; const scoreStatusMatch = (match: StatusMatch): number => {  switch (match.kind) {    case "exact":      return match.status === 200 ? 100 : match.status >= 200 && match.status < 300 ? 80 : 10;    case "range":      return match.value === "2XX" ? 60 : 5;    case "default":      return 40;  }}; const responseContentCandidates = (  response: ResponseSymbol,): Array<{ mediaType: string; shapeId: ShapeSymbolId }> =>  (response.contents ?? [])    .flatMap((content) =>      content.shapeId ? [{ mediaType: content.mediaType, shapeId: content.shapeId }] : [],    ); type RankedResponseVariantEntry = {  variant: ResponseSet["variants"][number];  response: ResponseSymbol;  score: number;}; const responseVariantEntries = (  catalog: CatalogV1,  responseSet: ResponseSet,): RankedResponseVariantEntry[] =>  [...responseSet.variants]    .map((variant) => {      const response = getResponseSymbol(catalog, variant.responseId);      return response        ? {            variant,            response,            score: scoreStatusMatch(variant.match),          }        : null;    })    .filter((entry): entry is RankedResponseVariantEntry => entry !== null); const isSuccessStatusMatch = (match: StatusMatch): boolean => {  switch (match.kind) {    case "exact":      return match.status >= 200 && match.status < 300;    case "range":      return match.value === "2XX";    case "default":      return false;  }}; const contentShapeIdFromResponseEntries = (  catalog: CatalogV1,  capability: Capability,  label: string,  title: string,  entries: readonly RankedResponseVariantEntry[],): ShapeSymbolId | undefined => {  const jsonCandidates = entries.flatMap(({ response }) =>    responseContentCandidates(response).filter((candidate) => isJsonMediaType(candidate.mediaType)),  );   if (jsonCandidates.length > 0) {    return contentShapeId(      catalog,      capability,      jsonCandidates.map((candidate) => ({        mediaType: candidate.mediaType,        shapeId: candidate.shapeId,

Lines 1–500 of 1405.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t