# How the `packages/shared` Directory Facilitates Business Logic in Craft Agents

> Discover how the packages shared directory centralizes Craft Agents business logic. Access workspace lifecycle, config, automation, and credentials via a clean public API.

- Repository: [Craft Ai Agents/craft-agents-oss](https://github.com/craft-ai-agents/craft-agents-oss)
- Tags: internals
- Published: 2026-07-04

---

**The `packages/shared` directory serves as the centralized business logic layer for Craft Agents, exposing a clean public API via `@craft-agent/shared/*` that handles workspace lifecycle, configuration persistence, automation orchestration, and secure credential management across all consumers including the Electron UI and CLI tools.**

The `packages/shared` package in the `craft-ai-agents/craft-agents-oss` repository encapsulates all reusable, domain-specific code that implements the product's core business rules. By isolating these concerns into a single importable package, the architecture ensures that every consumer delegates business decisions to a consistent, type-safe source of truth rather than duplicating logic.

## Core Architecture and Entry Point

The shared layer exposes its functionality through a barrel export pattern centralized in [`packages/shared/src/index.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/index.ts). This entry point explicitly documents its purpose as *"Shared business logic for Craft Agent"* and re-exports twelve distinct functional domains including Agent SDK wrappers, Auth flows, HTTP clients, Configuration management, Credential storage, MCP clients, Prompt generation, Source management, Utilities, Validation, Version handling, and Workspace orchestration.

This modular structure ensures that consumers import only what they need while maintaining strict boundaries between domains. Each submodule encapsulates specific business rules—for example, the Workspaces module handles path generation and permission validation, while the Config module centralizes persistent storage of user preferences and model selections.

## Workspace Management and Lifecycle

The Workspaces domain implements the foundational organizational unit for Craft Agents. Located in [`packages/shared/src/workspaces/index.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/workspaces/index.ts), this module exports types like `WorkspaceConfig` and `CreateWorkspaceInput` alongside storage helpers that enforce business rules for workspace creation.

The `createWorkspaceAtPath` function handles slug generation and folder creation, while `discoverWorkspacesInDefaultLocation` manages workspace discovery. These utilities ensure consistent naming conventions, path validation, and permission handling across the application:

```typescript
import { createWorkspaceAtPath, generateSlug } from '@craft-agent/shared/workspaces';
import { resolve } from 'node:path';

async function makeWorkspace(name: string) {
  const slug = await generateSlug(name);
  const workspacePath = resolve('/var/craft-workspaces', slug);
  await createWorkspaceAtPath({ name, slug }, workspacePath);
  console.log(`Workspace "${name}" created at ${workspacePath}`);
}

```

## Configuration Persistence and Validation

Centralized configuration management prevents drift between the Electron UI and CLI tools. The Config domain in [`packages/shared/src/config/index.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/config/index.ts) exports `loadStoredConfig` and `saveWorkspaceConfig` functions that provide a canonical interface for reading and writing user preferences, theme settings, and model configurations.

This layer handles validation, default value injection, and schema enforcement, ensuring that every component of the application reads from the same source of truth:

```typescript
import { loadStoredConfig } from '@craft-agent/shared/config';

async function initConfig() {
  const cfg = await loadStoredConfig();
  console.log('Current theme:', cfg.theme);
}

```

## Automation Orchestration Engine

The `AutomationSystem` class in [`packages/shared/src/automations/automation-system.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/automations/automation-system.ts) coordinates event-driven business logic including webhook handling, scheduler management, and session-metadata diffing. This engine isolates automation rules from UI concerns, ensuring no global state leaks between workspaces.

The system initializes with workspace-specific parameters and executes agent events through a type-safe interface:

```typescript
import { AutomationSystem } from '@craft-agent/shared/automations';

async function fireAgentEvent(workspaceId: string, workspaceRoot: string) {
  const sys = new AutomationSystem({
    workspaceId,
    workspaceRootPath: workspaceRoot,
    enableScheduler: true,
  });

  const matched = await sys.executeAgentEvent('AgentMessage', { text: 'Hello' });
  console.log(`Matched ${matched} automation(s)`);
}

```

## Secure Credential Management

The Credentials domain abstracts platform-specific storage mechanisms behind a unified API. The `getCredentialManager` function in [`packages/shared/src/credentials/manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/credentials/manager.ts) returns an interface that handles both environment variables and encrypted storage backends without exposing implementation details to consumers.

This abstraction ensures that API keys and secrets are retrieved consistently across development and production environments:

```typescript
import { getCredentialManager } from '@craft-agent/shared/credentials';

async function getApiKey() {
  const manager = getCredentialManager();
  const apiKey = await manager.get('CRAFT_API_KEY');
  return apiKey;
}

```

## Utility and Validation Layers

Supporting business logic enforcement, the Utils and Validation domains provide consistent logging via [`packages/shared/src/utils/debug.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/utils/debug.ts) and schema validation utilities. These helpers ensure that business rule violations surface uniformly across the codebase with structured error handling.

The Version domain in [`packages/shared/src/version/index.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/version/index.ts) additionally provides build metadata access through [`install.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/install.ts) and [`manifest.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/manifest.ts), enabling upgrade checks and telemetry that respect the shared layer's business rules.

## Summary

- **[`packages/shared/src/index.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/index.ts)** serves as the public API entry point, documenting the layer's role as the central business logic repository.
- **Workspace management** enforces naming, path generation, and permission rules through `createWorkspaceAtPath` and `discoverWorkspacesInDefaultLocation`.
- **Configuration persistence** provides canonical read/write access via `loadStoredConfig` and `saveWorkspaceConfig`.
- **Automation orchestration** isolates event-driven logic within the `AutomationSystem` class to prevent state leakage.
- **Credential abstraction** secures secrets through `getCredentialManager` without exposing storage backend details.
- **Cross-platform consistency** ensures the Electron UI, CLI tools, and external SDKs all consume identical business rules.

## Frequently Asked Questions

### What is the primary purpose of the `packages/shared` directory in Craft Agents?

The `packages/shared` directory consolidates all domain-specific business logic into a single package that exposes a public API via `@craft-agent/shared/*`. It ensures that every consumer—including the Electron UI, CLI tools, and external SDKs—follows identical rules for workspace management, configuration handling, and security without duplicating code.

### How does the shared package handle workspace management?

The Workspaces domain in [`packages/shared/src/workspaces/index.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/workspaces/index.ts) provides types like `WorkspaceConfig` and functions such as `createWorkspaceAtPath` and `generateSlug`. These utilities encapsulate business rules for workspace naming conventions, path validation, and folder creation, ensuring consistent organizational unit handling across the application.

### What automation capabilities does the shared layer provide?

The `AutomationSystem` class in [`packages/shared/src/automations/automation-system.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/automations/automation-system.ts) coordinates event-driven automations, scheduler execution, and webhook handling. It isolates automation business logic from UI concerns and provides methods like `executeAgentEvent` to process workspace-specific triggers without leaking global state.

### How does the shared directory manage secure credentials?

The Credentials domain abstracts storage complexity through `getCredentialManager` in [`packages/shared/src/credentials/manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/credentials/manager.ts). This function returns a manager interface that handles both environment variables and encrypted storage backends, allowing any module to retrieve secrets like `CRAFT_API_KEY` without implementing platform-specific storage logic.