Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

6.3 KB
Raw Blame
import { z } from 'zod';
import {
  ProjectNotFoundError,
  projectDraftSchema,
  projectPatchSchema,
  projectIdSchema,
  projectRevisionIdSchema,
  type ProjectStore,
} from '../projects';
import type { AssetLibrary } from '../assets';
import { nestedRecordDescription, requireActionFields } from './actions';
import type { KilnToolDef } from './registry';

export type ProjectBundleReader = (
  projectId: string,
  revisionId: string,
  profile: 'editable' | 'runtime',
) => Promise<Uint8Array>;

const PROJECT_ACTIONS = ['list', 'get', 'create', 'update', 'export', 'check'] as const;
type ProjectAction = (typeof PROJECT_ACTIONS)[number];
const REQUIREMENTS: Record<ProjectAction, Parameters<typeof requireActionFields>[3]> = {
  list: { required: [] },
  get: { required: ['projectId'] },
  create: { required: ['draft'], shapes: { draft: 'shape:project-draft' } },
  update: {
    required: ['projectId', 'expectedRevision', 'patch'],
    shapes: { patch: 'shape:project-patch' },
  },
  export: { required: ['projectId'] },
  check: { required: ['projectId'] },
};

/** The nested records stay opaque in the advertised schema and are validated when the action runs. */
const record = (description: string) =>
  z.record(z.string(), z.unknown()).optional().describe(description);

/** One flat object: `export` and `check` are offered only when the host can back them. */
export function projectToolInput(actions: readonly ProjectAction[] = PROJECT_ACTIONS) {
  return z.strictObject({
    action: z.enum(actions as [ProjectAction, ...ProjectAction[]]),
    projectId: projectIdSchema.optional().describe('get, update, export, check.'),
    revisionId: projectRevisionIdSchema
      .optional()
      .describe('get, export, check: an exact revision; omit for the current one.'),
    expectedRevision: projectRevisionIdSchema
      .optional()
      .describe('update: the revision being replaced; a stale value is a conflict.'),
    draft: record(
      nestedRecordDescription(
        'create: name, brief, design, inventory, deliveryProfiles, materialDependencies, references, reviews; optional projectId.',
        'shape:project-draft',
      ),
    ),
    patch: record(
      nestedRecordDescription(
        'update: the same top-level fields as draft; each supplied field replaces its previous value whole.',
        'shape:project-patch',
      ),
    ),
    profile: z
      .enum(['editable', 'runtime'])
      .optional()
      .describe(
        'export: editable (default) keeps source and resources; runtime is GLB plus metadata.',
      ),
  });
}

export function createKilnProjectDef(
  store: ProjectStore,
  bundleReader?: ProjectBundleReader,
  assetLibrary?: Pick<AssetLibrary, 'read'>,
): KilnToolDef {
  const schema = projectToolInput(
    PROJECT_ACTIONS.filter(
      (action) => (action !== 'export' || bundleReader) && (action !== 'check' || assetLibrary),
    ),
  );
  return {
    name: 'kiln_project',
    description:
      'Manage optional shared workspace projects: list discovers IDs; get reads the current or an exact historical configuration; create adds a project; update needs the exact expectedRevision and replaces each supplied top-level field. Assets and materials are authored, saved and exported without a project, and creating one never binds unrelated authoring. Design preferences, inventory, references, delivery profiles and pinned material dependencies are versioned; review annotations do not change trusted QA or authorize a release.' +
      (bundleReader
        ? ' export returns an MCP resource URI for an exact editable project ZIP with normalized material maps and recipes, or a runtime GLB/metadata ZIP; only inventory entries linked to saved revisions contribute assets, and referenced concept images and acquisition archives are not embedded.'
        : '') +
      (assetLibrary
        ? ' check measures items that state a placement against each other at pinned revisions: shared volume, and open surfaces inside a neighbour. An unreadable pin is unmeasured, not clear; a positive is not a verdict.'
        : ''),
    inputSchema: schema,
    annotations: {
      readOnlyHint: false,
      destructiveHint: false,
      idempotentHint: false,
      openWorldHint: false,
    },
    run: async (raw) => {
      const input = schema.parse(raw);
      requireActionFields('kiln_project', input.action, input, REQUIREMENTS[input.action]);
      try {
        return await act(input);
      } catch (error) {
        // Rule 9: an unknown id names the call that lists the known ones.
        if (error instanceof ProjectNotFoundError)
          throw new Error(
            `${error.message} kiln_project { action: 'list' } lists the project IDs in this workspace.`,
          );
        throw error;
      }
    },
  };
  async function act(input: z.infer<typeof schema>) {
    switch (input.action) {
      case 'list':
        return { ok: true, projects: await store.list() };
      case 'get':
        return { ok: true, project: await store.read(input.projectId!, input.revisionId) };
      case 'create':
        return { ok: true, project: await store.create(projectDraftSchema.parse(input.draft)) };
      case 'update':
        return {
          ok: true,
          project: await store.update(
            input.projectId!,
            input.expectedRevision!,
            projectPatchSchema.parse(input.patch),
          ),
        };
      case 'check': {
        const { composeProjectModules } = await import('../project-composition');
        return {
          ok: true,
          composition: await composeProjectModules(
            await store.read(input.projectId!, input.revisionId),
            assetLibrary!,
          ),
        };
      }
      case 'export': {
        const profile = input.profile ?? 'editable';
        const project = await store.read(input.projectId!, input.revisionId);
        const bytes = await bundleReader!(project.projectId, project.revisionId, profile);
        const { projectBundleHash } = await import('../project-bundle');
        return {
          ok: true,
          projectId: project.projectId,
          revisionId: project.revisionId,
          profile,
          resource: {
            uri: `kiln://projects/${project.projectId}/${project.revisionId}/${profile}.zip`,
            mimeType: 'application/zip',
            bytes: bytes.length,
            sha256: await projectBundleHash(bytes),
          },
        };
      }
    }
  }
}