Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
fix: ts-agent-sdk - add templates, remove hardcoded paths
Jezf8a572125470
diff --git a/skills/ts-agent-sdk/README.md b/skills/ts-agent-sdk/README.mdindex 0ec3f557..a023e0ca 100644--- a/skills/ts-agent-sdk/README.md+++ b/skills/ts-agent-sdk/README.md@@ -38,7 +38,10 @@ await docs.createDocument({ spaceId: 'wiki', title: 'Guide', content: '...' })3. Generate typed clients for each server's tools4. Create example scripts in `scripts/sdk/`-## Template Repository+## Templates-Full pattern documentation and examples at:-`/home/jez/Documents/ts-agent-sdk/`+SDK templates bundled at `templates/` — copy to your project's `scripts/sdk/`:++```bash+cp -r ~/.claude/skills/ts-agent-sdk/templates/* ./scripts/sdk/+```diff --git a/skills/ts-agent-sdk/SKILL.md b/skills/ts-agent-sdk/SKILL.mdindex 61d633e0..ba1b4349 100644--- a/skills/ts-agent-sdk/SKILL.md+++ b/skills/ts-agent-sdk/SKILL.md@@ -14,10 +14,14 @@ This skill generates typed TypeScript SDKs that allow AI agents (primarily Claud## Template Location-The core SDK template files are at:-`/home/jez/Documents/ts-agent-sdk/template/scripts/sdk/`+The core SDK template files are bundled with this skill at:+`templates/`-Copy these files to the target project's `scripts/sdk/` directory as a starting point.+Copy these files to the target project's `scripts/sdk/` directory as a starting point:++```bash+cp -r ~/.claude/skills/ts-agent-sdk/templates/* ./scripts/sdk/+```## SDK Generation Workflowdiff --git a/skills/ts-agent-sdk/templates/api/base.ts b/skills/ts-agent-sdk/templates/api/base.tsnew file mode 100644index 00000000..d504d02f--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/base.ts@@ -0,0 +1,108 @@+/**+ * ts-agent-sdk Base HTTP Client+ *+ * Provides common HTTP functionality for all API clients.+ */++import { NetworkError, RateLimitError } from '../errors';++export interface RequestOptions {+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';+ headers?: Record<string, string>;+ body?: unknown;+ timeout?: number;+}++export interface APIResponse<T = unknown> {+ data: T;+ status: number;+ headers: Headers;+}++/**+ * Make an HTTP request with standard error handling.+ */+export async function request<T>(url: string, options: RequestOptions = {}): Promise<APIResponse<T>> {+ const { method = 'GET', headers = {}, body, timeout = 30000 } = options;++ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), timeout);++ try {+ const response = await fetch(url, {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...headers,+ },+ body: body ? JSON.stringify(body) : undefined,+ signal: controller.signal,+ });++ clearTimeout(timeoutId);++ // Handle rate limiting+ if (response.status === 429) {+ const retryAfter = parseInt(response.headers.get('Retry-After') || '60', 10);+ throw new RateLimitError(retryAfter);+ }++ // Parse response+ const contentType = response.headers.get('Content-Type') || '';+ let data: T;++ if (contentType.includes('application/json')) {+ data = await response.json();+ } else {+ data = (await response.text()) as T;+ }++ // Check for error status+ if (!response.ok) {+ const errorMessage = typeof data === 'object' && data !== null && 'error' in data+ ? (data as { error: { message?: string } }).error?.message || JSON.stringify(data)+ : String(data);+ throw new Error(`API error (${response.status}): ${errorMessage}`);+ }++ return {+ data,+ status: response.status,+ headers: response.headers,+ };+ } catch (error) {+ clearTimeout(timeoutId);++ if (error instanceof RateLimitError) {+ throw error;+ }++ if (error instanceof Error) {+ if (error.name === 'AbortError') {+ throw new NetworkError(`Request timed out after ${timeout}ms`);+ }+ if (error.message.includes('API error')) {+ throw error;+ }+ throw new NetworkError(error.message, error);+ }++ throw new NetworkError('Unknown error occurred');+ }+}++/**+ * Make a GET request.+ */+export async function get<T>(url: string, headers?: Record<string, string>): Promise<T> {+ const response = await request<T>(url, { method: 'GET', headers });+ return response.data;+}++/**+ * Make a POST request.+ */+export async function post<T>(url: string, body: unknown, headers?: Record<string, string>): Promise<T> {+ const response = await request<T>(url, { method: 'POST', body, headers });+ return response.data;+}diff --git a/skills/ts-agent-sdk/templates/api/config.ts b/skills/ts-agent-sdk/templates/api/config.tsnew file mode 100644index 00000000..ffb13007--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/config.ts@@ -0,0 +1,66 @@+/**+ * ts-agent-sdk API Configuration+ *+ * Environment variables for external API access:+ * - SDK_GEMINI_API_KEY: Google Gemini API key+ * - SDK_WORKERS_AI_ACCOUNT_ID: Cloudflare account ID for Workers AI+ * - SDK_WORKERS_AI_API_TOKEN: Cloudflare API token for Workers AI+ * - SDK_SLACK_WEBHOOK_URL: Slack incoming webhook URL+ */++export interface APIConfig {+ gemini: {+ apiKey: string;+ defaultModel: string;+ };+ workersAI: {+ accountId: string;+ apiToken: string;+ };+ slack: {+ webhookUrl: string;+ };+}++/**+ * Load API configuration from environment variables.+ */+export function loadAPIConfig(): APIConfig {+ return {+ gemini: {+ apiKey: process.env.SDK_GEMINI_API_KEY || '',+ defaultModel: process.env.SDK_GEMINI_MODEL || 'gemini-2.5-flash',+ },+ workersAI: {+ accountId: process.env.SDK_WORKERS_AI_ACCOUNT_ID || process.env.SDK_CF_ACCOUNT_ID || '',+ apiToken: process.env.SDK_WORKERS_AI_API_TOKEN || process.env.SDK_CF_API_TOKEN || '',+ },+ slack: {+ webhookUrl: process.env.SDK_SLACK_WEBHOOK_URL || '',+ },+ };+}++/**+ * Validate that required API keys are present.+ */+export function validateGeminiConfig(config: APIConfig): void {+ if (!config.gemini.apiKey) {+ throw new Error('SDK_GEMINI_API_KEY is required for Gemini API calls.');+ }+}++export function validateWorkersAIConfig(config: APIConfig): void {+ if (!config.workersAI.accountId) {+ throw new Error('SDK_WORKERS_AI_ACCOUNT_ID is required for Workers AI calls.');+ }+ if (!config.workersAI.apiToken) {+ throw new Error('SDK_WORKERS_AI_API_TOKEN is required for Workers AI calls.');+ }+}++export function validateSlackConfig(config: APIConfig): void {+ if (!config.slack.webhookUrl) {+ throw new Error('SDK_SLACK_WEBHOOK_URL is required for Slack notifications.');+ }+}diff --git a/skills/ts-agent-sdk/templates/api/gemini.ts b/skills/ts-agent-sdk/templates/api/gemini.tsnew file mode 100644index 00000000..107a0fb5--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/gemini.ts@@ -0,0 +1,145 @@+/**+ * ts-agent-sdk Gemini AI Client+ *+ * Typed wrapper for Google Gemini API.+ *+ * Environment Variables:+ * - SDK_GEMINI_API_KEY: Your Gemini API key+ * - SDK_GEMINI_MODEL: Default model (default: gemini-2.5-flash)+ */++import { post } from './base';+import { loadAPIConfig, validateGeminiConfig } from './config';++const GEMINI_API_BASE = 'https://generativelanguage.googleapis.com/v1beta/models';++export interface GenerateOptions {+ model?: string;+ maxTokens?: number;+ temperature?: number;+ topP?: number;+ stopSequences?: string[];+}++export interface GeminiContent {+ role: 'user' | 'model';+ parts: { text: string }[];+}++interface GeminiResponse {+ candidates: {+ content: {+ parts: { text: string }[];+ };+ finishReason: string;+ }[];+ usageMetadata?: {+ promptTokenCount: number;+ candidatesTokenCount: number;+ totalTokenCount: number;+ };+}++/**+ * Gemini AI Client for text generation, summarization, and structured extraction.+ */+export class GeminiClient {+ private apiKey: string;+ private defaultModel: string;++ constructor() {+ const config = loadAPIConfig();+ this.apiKey = config.gemini.apiKey;+ this.defaultModel = config.gemini.defaultModel;+ }++ /**+ * Generate text from a prompt.+ */+ async generateText(prompt: string, options: GenerateOptions = {}): Promise<string> {+ this.ensureConfigured();++ const model = options.model || this.defaultModel;+ const url = `${GEMINI_API_BASE}/${model}:generateContent?key=${this.apiKey}`;++ const response = await post<GeminiResponse>(url, {+ contents: [{ role: 'user', parts: [{ text: prompt }] }],+ generationConfig: {+ maxOutputTokens: options.maxTokens,+ temperature: options.temperature,+ topP: options.topP,+ stopSequences: options.stopSequences,+ },+ });++ return response.candidates[0]?.content?.parts[0]?.text || '';+ }++ /**+ * Generate a summary of the provided content.+ */+ async summarize(content: string, options: GenerateOptions = {}): Promise<string> {+ const prompt = `Please provide a concise summary of the following content:\n\n${content}`;+ return this.generateText(prompt, options);+ }++ /**+ * Extract structured JSON from content using a schema description.+ * @param prompt - Instructions for extraction including the content+ * @param schemaDescription - Description of the expected JSON structure+ */+ async extractJson<T>(prompt: string, schemaDescription: string): Promise<T> {+ const fullPrompt = `${prompt}++Respond ONLY with valid JSON matching this structure:+${schemaDescription}++Do not include any markdown formatting, code blocks, or explanations. Return only the raw JSON.`;++ const response = await this.generateText(fullPrompt, { temperature: 0 });++ // Clean up response - remove markdown code blocks if present+ let cleaned = response.trim();+ if (cleaned.startsWith('```json')) {+ cleaned = cleaned.slice(7);+ } else if (cleaned.startsWith('```')) {+ cleaned = cleaned.slice(3);+ }+ if (cleaned.endsWith('```')) {+ cleaned = cleaned.slice(0, -3);+ }++ return JSON.parse(cleaned.trim()) as T;+ }++ /**+ * Multi-turn conversation.+ */+ async chat(messages: GeminiContent[], options: GenerateOptions = {}): Promise<string> {+ this.ensureConfigured();++ const model = options.model || this.defaultModel;+ const url = `${GEMINI_API_BASE}/${model}:generateContent?key=${this.apiKey}`;++ const response = await post<GeminiResponse>(url, {+ contents: messages,+ generationConfig: {+ maxOutputTokens: options.maxTokens,+ temperature: options.temperature,+ topP: options.topP,+ stopSequences: options.stopSequences,+ },+ });++ return response.candidates[0]?.content?.parts[0]?.text || '';+ }++ private ensureConfigured(): void {+ const config = loadAPIConfig();+ validateGeminiConfig(config);+ this.apiKey = config.gemini.apiKey;+ }+}++// Default singleton instance+export const gemini = new GeminiClient();diff --git a/skills/ts-agent-sdk/templates/api/index.ts b/skills/ts-agent-sdk/templates/api/index.tsnew file mode 100644index 00000000..eda6edaa--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/index.ts@@ -0,0 +1,49 @@+/**+ * ts-agent-sdk Direct API Module+ *+ * Typed clients for external API calls.+ *+ * Environment Variables:+ * - SDK_GEMINI_API_KEY: Google Gemini API key+ * - SDK_WORKERS_AI_ACCOUNT_ID: Cloudflare account ID+ * - SDK_WORKERS_AI_API_TOKEN: Cloudflare API token+ * - SDK_SLACK_WEBHOOK_URL: Slack incoming webhook URL+ */++// Configuration+export { loadAPIConfig, validateGeminiConfig, validateWorkersAIConfig, validateSlackConfig } from './config';+export type { APIConfig } from './config';++// Base HTTP client+export { request, get, post } from './base';+export type { RequestOptions, APIResponse } from './base';++// Gemini AI+export { GeminiClient, gemini } from './gemini';+export type { GenerateOptions, GeminiContent } from './gemini';++// Cloudflare Workers AI+export { WorkersAIClient, workersAI, WORKERS_AI_MODELS } from './workers-ai';+export type { TextGenerationInput, TextGenerationResponse, EmbeddingsInput, EmbeddingsResponse } from './workers-ai';++// Slack+export { SlackClient, slack } from './slack';+export type { SlackBlock, SlackMessage } from './slack';++// Webhooks+export { WebhookClient, webhook, triggerN8n, triggerZapier, triggerMake } from './webhook';+export type { WebhookResponse } from './webhook';++// Public APIs+export * as holidays from './public/holidays';+export {+ getPublicHolidays,+ getNextPublicHoliday,+ getNextPublicHolidays,+ isPublicHoliday,+ isTodayPublicHoliday,+ getAvailableCountries,+ getCountryInfo,+ COUNTRY_CODES,+} from './public/holidays';+export type { PublicHoliday, CountryInfo } from './public/holidays';diff --git a/skills/ts-agent-sdk/templates/api/public/holidays.ts b/skills/ts-agent-sdk/templates/api/public/holidays.tsnew file mode 100644index 00000000..72b0bae5--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/public/holidays.ts@@ -0,0 +1,158 @@+/**+ * ts-agent-sdk Public Holidays API+ *+ * Wrapper for Nager.Date Public Holiday API.+ * @see https://date.nager.at/Api+ *+ * No API key required - this is a free public API.+ */++import { get } from '../base';++const NAGER_API_BASE = 'https://date.nager.at/api/v3';++export interface PublicHoliday {+ date: string;+ localName: string;+ name: string;+ countryCode: string;+ fixed: boolean;+ global: boolean;+ counties: string[] | null;+ launchYear: number | null;+ types: ('Public' | 'Bank' | 'School' | 'Authorities' | 'Optional' | 'Observance')[];+}++export interface CountryInfo {+ commonName: string;+ officialName: string;+ countryCode: string;+ region: string;+ borders: string[] | null;+}++/**+ * Get public holidays for a specific year and country.+ *+ * @param year - The year (e.g., 2025)+ * @param countryCode - ISO 3166-1 alpha-2 country code (e.g., 'AU', 'US', 'GB')+ *+ * @example+ * const holidays = await getPublicHolidays(2025, 'AU');+ */+export async function getPublicHolidays(year: number, countryCode: string): Promise<PublicHoliday[]> {+ const url = `${NAGER_API_BASE}/PublicHolidays/${year}/${countryCode.toUpperCase()}`;+ return get<PublicHoliday[]>(url);+}++/**+ * Get the next public holiday for a country.+ *+ * @param countryCode - ISO 3166-1 alpha-2 country code+ *+ * @example+ * const next = await getNextPublicHoliday('AU');+ * if (next) console.log(`Next holiday: ${next.name} on ${next.date}`);+ */+export async function getNextPublicHoliday(countryCode: string): Promise<PublicHoliday | null> {+ const url = `${NAGER_API_BASE}/NextPublicHolidays/${countryCode.toUpperCase()}`;++ try {+ const holidays = await get<PublicHoliday[]>(url);+ return holidays[0] || null;+ } catch {+ return null;+ }+}++/**+ * Get the next public holidays (up to a limit) for a country.+ *+ * @param countryCode - ISO 3166-1 alpha-2 country code+ * @param limit - Maximum number of holidays to return (default: 5)+ */+export async function getNextPublicHolidays(+ countryCode: string,+ limit: number = 5+): Promise<PublicHoliday[]> {+ const url = `${NAGER_API_BASE}/NextPublicHolidays/${countryCode.toUpperCase()}`;++ try {+ const holidays = await get<PublicHoliday[]>(url);+ return holidays.slice(0, limit);+ } catch {+ return [];+ }+}++/**+ * Check if a specific date is a public holiday.+ *+ * @param date - The date to check (YYYY-MM-DD format or Date object)+ * @param countryCode - ISO 3166-1 alpha-2 country code+ */+export async function isPublicHoliday(+ date: string | Date,+ countryCode: string+): Promise<{ isHoliday: boolean; holiday?: PublicHoliday }> {+ const dateStr = date instanceof Date ? date.toISOString().split('T')[0] : date;+ const year = parseInt(dateStr.split('-')[0], 10);++ const holidays = await getPublicHolidays(year, countryCode);+ const holiday = holidays.find((h) => h.date === dateStr);++ return {+ isHoliday: !!holiday,+ holiday,+ };+}++/**+ * Get list of available countries.+ */+export async function getAvailableCountries(): Promise<CountryInfo[]> {+ const url = `${NAGER_API_BASE}/AvailableCountries`;+ return get<CountryInfo[]>(url);+}++/**+ * Get country information.+ *+ * @param countryCode - ISO 3166-1 alpha-2 country code+ */+export async function getCountryInfo(countryCode: string): Promise<CountryInfo> {+ const url = `${NAGER_API_BASE}/CountryInfo/${countryCode.toUpperCase()}`;+ return get<CountryInfo>(url);+}++/**+ * Check if today is a public holiday.+ *+ * @param countryCode - ISO 3166-1 alpha-2 country code+ */+export async function isTodayPublicHoliday(+ countryCode: string+): Promise<{ isHoliday: boolean; holiday?: PublicHoliday }> {+ const today = new Date().toISOString().split('T')[0];+ return isPublicHoliday(today, countryCode);+}++// Convenience export for common country codes+export const COUNTRY_CODES = {+ AUSTRALIA: 'AU',+ AUSTRIA: 'AT',+ BELGIUM: 'BE',+ BRAZIL: 'BR',+ CANADA: 'CA',+ FRANCE: 'FR',+ GERMANY: 'DE',+ IRELAND: 'IE',+ ITALY: 'IT',+ JAPAN: 'JP',+ NETHERLANDS: 'NL',+ NEW_ZEALAND: 'NZ',+ SPAIN: 'ES',+ SWITZERLAND: 'CH',+ UNITED_KINGDOM: 'GB',+ UNITED_STATES: 'US',+} as const;diff --git a/skills/ts-agent-sdk/templates/api/slack.ts b/skills/ts-agent-sdk/templates/api/slack.tsnew file mode 100644index 00000000..c0687ec8--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/slack.ts@@ -0,0 +1,147 @@+/**+ * ts-agent-sdk Slack Client+ *+ * Send notifications via Slack incoming webhooks.+ *+ * Environment Variables:+ * - SDK_SLACK_WEBHOOK_URL: Slack incoming webhook URL+ */++import { post } from './base';+import { loadAPIConfig, validateSlackConfig } from './config';++export interface SlackBlock {+ type: 'section' | 'divider' | 'header' | 'context' | 'actions';+ text?: {+ type: 'mrkdwn' | 'plain_text';+ text: string;+ emoji?: boolean;+ };+ fields?: {+ type: 'mrkdwn' | 'plain_text';+ text: string;+ }[];+ elements?: unknown[];+ accessory?: unknown;+}++export interface SlackMessage {+ text?: string;+ blocks?: SlackBlock[];+ attachments?: unknown[];+ mrkdwn?: boolean;+}++/**+ * Slack Client for sending webhook notifications.+ */+export class SlackClient {+ private webhookUrl: string;++ constructor(webhookUrl?: string) {+ const config = loadAPIConfig();+ this.webhookUrl = webhookUrl || config.slack.webhookUrl;+ }++ /**+ * Post a simple text message.+ */+ async postMessage(text: string): Promise<void> {+ this.ensureConfigured();+ await post<string>(this.webhookUrl, { text });+ }++ /**+ * Post a message with Block Kit blocks for rich formatting.+ * @see https://api.slack.com/block-kit+ */+ async postBlocks(blocks: SlackBlock[], fallbackText?: string): Promise<void> {+ this.ensureConfigured();+ await post<string>(this.webhookUrl, {+ text: fallbackText || 'New message',+ blocks,+ });+ }++ /**+ * Post a formatted notification with title, message, and optional fields.+ */+ async postNotification(options: {+ title: string;+ message: string;+ fields?: { label: string; value: string }[];+ color?: 'good' | 'warning' | 'danger' | string;+ }): Promise<void> {+ const blocks: SlackBlock[] = [+ {+ type: 'header',+ text: { type: 'plain_text', text: options.title, emoji: true },+ },+ {+ type: 'section',+ text: { type: 'mrkdwn', text: options.message },+ },+ ];++ if (options.fields && options.fields.length > 0) {+ blocks.push({+ type: 'section',+ fields: options.fields.map((f) => ({+ type: 'mrkdwn' as const,+ text: `*${f.label}:*\n${f.value}`,+ })),+ });+ }++ await this.postBlocks(blocks, options.title);+ }++ /**+ * Post an error notification.+ */+ async postError(title: string, error: Error | string, context?: Record<string, string>): Promise<void> {+ const errorMessage = error instanceof Error ? error.message : error;+ const stack = error instanceof Error ? error.stack : undefined;++ const blocks: SlackBlock[] = [+ {+ type: 'header',+ text: { type: 'plain_text', text: `🚨 ${title}`, emoji: true },+ },+ {+ type: 'section',+ text: { type: 'mrkdwn', text: `\`\`\`${errorMessage}\`\`\`` },+ },+ ];++ if (context) {+ blocks.push({+ type: 'context',+ elements: Object.entries(context).map(([key, value]) => ({+ type: 'mrkdwn',+ text: `*${key}:* ${value}`,+ })),+ });+ }++ if (stack) {+ blocks.push({+ type: 'section',+ text: { type: 'mrkdwn', text: `<details>\n\`\`\`${stack.slice(0, 500)}\`\`\`\n</details>` },+ });+ }++ await this.postBlocks(blocks, title);+ }++ private ensureConfigured(): void {+ if (!this.webhookUrl) {+ const config = loadAPIConfig();+ validateSlackConfig(config);+ this.webhookUrl = config.slack.webhookUrl;+ }+ }+}++// Default singleton instance+export const slack = new SlackClient();diff --git a/skills/ts-agent-sdk/templates/api/webhook.ts b/skills/ts-agent-sdk/templates/api/webhook.tsnew file mode 100644index 00000000..ef6d4ec7--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/webhook.ts@@ -0,0 +1,114 @@+/**+ * ts-agent-sdk Webhook Client+ *+ * Generic webhook client for triggering external services,+ * including n8n workflows.+ */++import { post, get } from './base';++export interface WebhookResponse<T = unknown> {+ success: boolean;+ data?: T;+ error?: string;+}++/**+ * Generic Webhook Client for calling external HTTP endpoints.+ */+export class WebhookClient {+ /**+ * POST data to a webhook URL.+ */+ async post<T = unknown>(url: string, data: unknown, headers?: Record<string, string>): Promise<T> {+ return post<T>(url, data, headers);+ }++ /**+ * GET data from a webhook URL.+ */+ async get<T = unknown>(url: string, headers?: Record<string, string>): Promise<T> {+ return get<T>(url, headers);+ }++ /**+ * Trigger a webhook with an event payload.+ * Standard format for event-driven integrations.+ */+ async trigger<T = unknown>(+ url: string,+ event: string,+ payload: unknown,+ metadata?: Record<string, string>+ ): Promise<T> {+ return post<T>(url, {+ event,+ payload,+ metadata: {+ timestamp: new Date().toISOString(),+ source: 'ts-agent-sdk',+ ...metadata,+ },+ });+ }+}++// Default singleton instance+export const webhook = new WebhookClient();++/**+ * n8n Webhook helper.+ *+ * Triggers n8n workflows via webhook.+ *+ * @param webhookPath - The n8n webhook path (e.g., 'abc123' or 'production/abc123')+ * @param data - Data to send to the workflow+ * @param options - Optional configuration+ *+ * @example+ * // Trigger n8n webhook+ * await triggerN8n('abc123', { name: 'John', email: '[email protected]' });+ *+ * // With custom base URL (self-hosted n8n)+ * await triggerN8n('abc123', data, { baseUrl: 'https://n8n.mycompany.com' });+ */+export async function triggerN8n<T = unknown>(+ webhookPath: string,+ data: unknown,+ options: {+ baseUrl?: string;+ production?: boolean;+ } = {}+): Promise<T> {+ const baseUrl = options.baseUrl || 'https://app.n8n.cloud';+ const prefix = options.production !== false ? 'webhook' : 'webhook-test';++ // Handle paths that already include production/test prefix+ const fullPath = webhookPath.includes('/')+ ? webhookPath+ : `${prefix}/${webhookPath}`;++ const url = `${baseUrl}/${fullPath}`;++ return post<T>(url, data);+}++/**+ * Zapier Webhook helper.+ *+ * @param webhookUrl - Full Zapier webhook URL+ * @param data - Data to send to the Zap+ */+export async function triggerZapier<T = unknown>(webhookUrl: string, data: unknown): Promise<T> {+ return post<T>(webhookUrl, data);+}++/**+ * Make Webhook helper.+ *+ * @param webhookUrl - Full Make (Integromat) webhook URL+ * @param data - Data to send to the scenario+ */+export async function triggerMake<T = unknown>(webhookUrl: string, data: unknown): Promise<T> {+ return post<T>(webhookUrl, data);+}diff --git a/skills/ts-agent-sdk/templates/api/workers-ai.ts b/skills/ts-agent-sdk/templates/api/workers-ai.tsnew file mode 100644index 00000000..42f73c38--- /dev/null+++ b/skills/ts-agent-sdk/templates/api/workers-ai.ts@@ -0,0 +1,164 @@+/**+ * ts-agent-sdk Workers AI Client+ *+ * Typed wrapper for Cloudflare Workers AI REST API.+ *+ * Environment Variables:+ * - SDK_WORKERS_AI_ACCOUNT_ID or SDK_CF_ACCOUNT_ID: Cloudflare account ID+ * - SDK_WORKERS_AI_API_TOKEN or SDK_CF_API_TOKEN: Cloudflare API token+ */++import { post } from './base';+import { loadAPIConfig, validateWorkersAIConfig } from './config';++/**+ * Workers AI model categories and common models.+ */+export const WORKERS_AI_MODELS = {+ textGeneration: [+ '@cf/meta/llama-3.1-8b-instruct',+ '@cf/meta/llama-3.2-3b-instruct',+ '@cf/mistral/mistral-7b-instruct-v0.2',+ '@hf/google/gemma-7b-it',+ ],+ textEmbeddings: [+ '@cf/baai/bge-base-en-v1.5',+ '@cf/baai/bge-large-en-v1.5',+ '@cf/baai/bge-small-en-v1.5',+ ],+ textClassification: [+ '@cf/huggingface/distilbert-sst-2-int8',+ ],+ imageClassification: [+ '@cf/microsoft/resnet-50',+ ],+ speechToText: [+ '@cf/openai/whisper',+ ],+} as const;++export interface TextGenerationInput {+ prompt: string;+ max_tokens?: number;+ temperature?: number;+ top_p?: number;+ stream?: boolean;+}++export interface TextGenerationResponse {+ response: string;+}++export interface EmbeddingsInput {+ text: string | string[];+}++export interface EmbeddingsResponse {+ data: number[][];+ shape: number[];+}++/**+ * Workers AI Client for running AI models on Cloudflare's edge.+ */+export class WorkersAIClient {+ private accountId: string;+ private apiToken: string;++ constructor() {+ const config = loadAPIConfig();+ this.accountId = config.workersAI.accountId;+ this.apiToken = config.workersAI.apiToken;+ }++ /**+ * Run any Workers AI model with arbitrary input.+ */+ async run<T>(model: string, input: unknown): Promise<T> {+ this.ensureConfigured();++ const url = `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/ai/run/${model}`;++ const response = await post<{ success: boolean; result: T; errors: unknown[] }>(+ url,+ input,+ { Authorization: `Bearer ${this.apiToken}` }+ );++ if (!response.success) {+ throw new Error(`Workers AI error: ${JSON.stringify(response.errors)}`);+ }++ return response.result;+ }++ /**+ * Generate text using a language model.+ */+ async textGeneration(+ prompt: string,+ model: string = WORKERS_AI_MODELS.textGeneration[0],+ options: Omit<TextGenerationInput, 'prompt'> = {}+ ): Promise<string> {+ const result = await this.run<TextGenerationResponse>(model, {+ prompt,+ ...options,+ });+ return result.response;+ }++ /**+ * Generate text embeddings for semantic search.+ */+ async textEmbeddings(+ text: string | string[],+ model: string = WORKERS_AI_MODELS.textEmbeddings[0]+ ): Promise<number[][]> {+ const result = await this.run<EmbeddingsResponse>(model, { text });+ return result.data;+ }++ /**+ * Classify text sentiment or category.+ */+ async textClassification(+ text: string,+ model: string = WORKERS_AI_MODELS.textClassification[0]+ ): Promise<{ label: string; score: number }[]> {+ return this.run<{ label: string; score: number }[]>(model, { text });+ }++ /**+ * List available models.+ */+ async listModels(): Promise<{ id: string; name: string; task: string }[]> {+ this.ensureConfigured();++ const url = `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/ai/models/search`;++ const response = await post<{+ success: boolean;+ result: { id: string; name: string; task: { name: string } }[];+ }>(+ url,+ {},+ { Authorization: `Bearer ${this.apiToken}` }+ );++ return response.result.map((m) => ({+ id: m.id,+ name: m.name,+ task: m.task.name,+ }));+ }++ private ensureConfigured(): void {+ const config = loadAPIConfig();+ validateWorkersAIConfig(config);+ this.accountId = config.workersAI.accountId;+ this.apiToken = config.workersAI.apiToken;+ }+}++// Default singleton instance+export const workersAI = new WorkersAIClient();diff --git a/skills/ts-agent-sdk/templates/client.ts b/skills/ts-agent-sdk/templates/client.tsnew file mode 100644index 00000000..0c22c40b--- /dev/null+++ b/skills/ts-agent-sdk/templates/client.ts@@ -0,0 +1,166 @@+/**+ * ts-agent-sdk MCP Client+ *+ * Wraps MCP JSON-RPC calls with typed interfaces and error handling.+ */++import { loadConfig, validateConfig, type SDKConfig } from './config';+import {+ SDKError,+ AuthError,+ RateLimitError,+ MCPError,+ NetworkError,+} from './errors';++/**+ * Standard response wrapper from MCP tools.+ * Tools return { success: true, ...data } or { success: false, error: string }+ */+export interface MCPResponse<T = unknown> {+ success: boolean;+ data?: T;+ error?: string;+}++/**+ * JSON-RPC 2.0 response structure+ */+interface JsonRpcResponse {+ jsonrpc: '2.0';+ id: number;+ result?: {+ content?: Array<{ type: string; text: string }>;+ isError?: boolean;+ };+ error?: {+ code: number;+ message: string;+ };+}++/**+ * MCP Client for making typed tool calls.+ *+ * Usage:+ * ```typescript+ * const client = new MCPClient();+ * const result = await client.callTool('/api/mcp-docs/message', 'list_spaces', {});+ * ```+ */+export class MCPClient {+ private config: SDKConfig;+ private requestId = 0;++ constructor(config?: Partial<SDKConfig>) {+ this.config = { ...loadConfig(), ...config };+ validateConfig(this.config);+ }++ /**+ * Call an MCP tool with typed input and output.+ *+ * @param endpoint - The MCP endpoint path (e.g., '/api/mcp-docs/message')+ * @param toolName - The tool name (e.g., 'create_document')+ * @param args - Tool arguments matching the tool's input schema+ * @returns The tool's response data+ * @throws {AuthError} If authentication fails+ * @throws {RateLimitError} If rate limited+ * @throws {MCPError} If the tool returns an error+ * @throws {NetworkError} If the request fails+ */+ async callTool<TInput extends Record<string, unknown>, TOutput>(+ endpoint: string,+ toolName: string,+ args: TInput+ ): Promise<TOutput> {+ const url = `${this.config.baseUrl}${endpoint}`;++ const payload = {+ jsonrpc: '2.0' as const,+ method: 'tools/call',+ params: {+ name: toolName,+ arguments: args,+ },+ id: ++this.requestId,+ };++ let response: Response;++ try {+ response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(this.config.apiToken && {+ Authorization: `Bearer ${this.config.apiToken}`,+ }),+ },+ body: JSON.stringify(payload),+ });+ } catch (error) {+ throw new NetworkError(+ `Failed to connect to ${url}`,+ error instanceof Error ? error : undefined+ );+ }++ // Handle HTTP-level errors+ if (response.status === 401) {+ throw new AuthError();+ }++ if (response.status === 429) {+ const retryAfter = parseInt(response.headers.get('Retry-After') || '60', 10);+ throw new RateLimitError(retryAfter);+ }++ if (!response.ok) {+ const text = await response.text().catch(() => 'Unknown error');+ throw new SDKError(`HTTP ${response.status}: ${text}`, `HTTP_${response.status}`);+ }++ // Parse JSON-RPC response+ const json: JsonRpcResponse = await response.json();++ // Handle JSON-RPC level errors+ if (json.error) {+ throw new MCPError(json.error.message, json.error.code);+ }++ // Extract tool result from MCP response format+ const result = json.result;+ if (!result?.content?.[0]) {+ throw new MCPError('Empty response from MCP server');+ }++ const content = result.content[0];+ if (content.type !== 'text') {+ throw new MCPError(`Unexpected content type: ${content.type}`);+ }++ // Parse the JSON string inside the text content+ const parsed = JSON.parse(content.text);++ // Handle tool-level errors+ if (result.isError || parsed.success === false) {+ throw new MCPError(parsed.error || 'Tool execution failed');+ }++ return parsed as TOutput;+ }++ /**+ * Get the current configuration (for debugging).+ */+ getConfig(): Readonly<SDKConfig> {+ return { ...this.config };+ }+}++/**+ * Default client instance.+ * Uses environment variables for configuration.+ */+export const defaultClient = new MCPClient();diff --git a/skills/ts-agent-sdk/templates/config.ts b/skills/ts-agent-sdk/templates/config.tsnew file mode 100644index 00000000..885098a8--- /dev/null+++ b/skills/ts-agent-sdk/templates/config.ts@@ -0,0 +1,57 @@+/**+ * ts-agent-sdk Configuration+ *+ * Environment variables:+ * - SDK_MODE: 'local' | 'remote' | 'auto' (default: 'auto')+ * - SDK_BASE_URL: Target Worker URL (required for remote mode)+ * - SDK_API_TOKEN: Bearer token for authentication+ */++export type ExecutionMode = 'local' | 'remote' | 'auto';++export interface SDKConfig {+ mode: ExecutionMode;+ baseUrl: string;+ apiToken: string;+}++/**+ * Load SDK configuration from environment variables.+ * Call this at startup or let the client handle it automatically.+ */+export function loadConfig(): SDKConfig {+ const mode = (process.env.SDK_MODE as ExecutionMode) || 'auto';+ let baseUrl = process.env.SDK_BASE_URL || '';++ // Auto-detect: if no URL provided or explicitly local, use localhost+ if (mode === 'auto' && !baseUrl) {+ baseUrl = 'http://localhost:8787';+ } else if (mode === 'local') {+ baseUrl = baseUrl || 'http://localhost:8787';+ }++ return {+ mode,+ baseUrl,+ apiToken: process.env.SDK_API_TOKEN || '',+ };+}++/**+ * Validate configuration and throw helpful errors if misconfigured.+ */+export function validateConfig(config: SDKConfig): void {+ if (config.mode === 'remote' && !config.baseUrl) {+ throw new Error(+ 'SDK_BASE_URL is required when SDK_MODE=remote. ' ++ 'Set it to your deployed Worker URL (e.g., https://app.workers.dev)'+ );+ }++ if (config.mode === 'remote' && !config.apiToken) {+ throw new Error(+ 'SDK_API_TOKEN is required when SDK_MODE=remote. ' ++ 'Generate an API token from your app and set it in the environment.'+ );+ }+}diff --git a/skills/ts-agent-sdk/templates/db/client.ts b/skills/ts-agent-sdk/templates/db/client.tsnew file mode 100644index 00000000..7d60755d--- /dev/null+++ b/skills/ts-agent-sdk/templates/db/client.ts@@ -0,0 +1,272 @@+/**+ * ts-agent-sdk Database Client+ *+ * Executes SQL queries against Cloudflare D1.+ * Supports both local (wrangler CLI) and remote (REST API) modes.+ */++import { execSync } from 'child_process';+import { loadDBConfig, resolveDBMode, validateRemoteConfig, type DBConfig } from './config';+import type { D1QueryResult, D1APIResponse, CountOptions, SelectOptions, SQLParam } from './types';++/**+ * Database Client for D1 queries.+ */+export class DBClient {+ private config: DBConfig;+ private effectiveMode: 'local' | 'remote';++ constructor() {+ this.config = loadDBConfig();+ this.effectiveMode = resolveDBMode(this.config);+ }++ /**+ * Get the current execution mode.+ */+ getMode(): 'local' | 'remote' {+ return this.effectiveMode;+ }++ /**+ * Execute a raw SQL query.+ *+ * @param sql - SQL query string+ * @param params - Parameters to bind (for parameterized queries)+ * @returns Array of result rows+ *+ * @example+ * const docs = await db.query<Document>('SELECT * FROM documents WHERE status = ?', ['published']);+ */+ async query<T = Record<string, unknown>>(sql: string, params?: SQLParam[]): Promise<T[]> {+ if (this.effectiveMode === 'local') {+ return this.executeLocal<T>(sql, params);+ } else {+ return this.executeRemote<T>(sql, params);+ }+ }++ /**+ * Execute a SQL statement that modifies data.+ *+ * @param sql - SQL statement (INSERT, UPDATE, DELETE)+ * @param params - Parameters to bind+ * @returns Number of rows affected+ */+ async execute(sql: string, params?: SQLParam[]): Promise<{ changes: number; lastRowId?: number }> {+ const result = await this.queryRaw<Record<string, unknown>>(sql, params);+ return {+ changes: result.meta?.changes || 0,+ lastRowId: result.meta?.last_row_id,+ };+ }++ /**+ * Execute query and return raw D1 result with metadata.+ */+ async queryRaw<T = Record<string, unknown>>(sql: string, params?: SQLParam[]): Promise<D1QueryResult<T>> {+ if (this.effectiveMode === 'local') {+ return this.executeLocalRaw<T>(sql, params);+ } else {+ return this.executeRemoteRaw<T>(sql, params);+ }+ }++ /**+ * Count rows in a table.+ *+ * @param table - Table name+ * @param options - Optional where clause+ *+ * @example+ * const totalDocs = await db.count('documents');+ * const publishedDocs = await db.count('documents', { where: { status: 'published' } });+ */+ async count(table: string, options: CountOptions = {}): Promise<number> {+ const { whereClause, params } = this.buildWhereClause(options.where);+ const sql = `SELECT COUNT(*) as count FROM ${this.escapeIdentifier(table)}${whereClause}`;+ const result = await this.query<{ count: number }>(sql, params);+ return result[0]?.count || 0;+ }++ /**+ * Select rows from a table.+ *+ * @param table - Table name+ * @param options - Select options (columns, where, orderBy, limit, offset)+ *+ * @example+ * const docs = await db.select('documents', {+ * columns: ['id', 'title', 'status'],+ * where: { status: 'published' },+ * orderBy: { column: 'createdAt', direction: 'DESC' },+ * limit: 10,+ * });+ */+ async select<T = Record<string, unknown>>(table: string, options: SelectOptions = {}): Promise<T[]> {+ const columns = options.columns?.map((c) => this.escapeIdentifier(c)).join(', ') || '*';+ const { whereClause, params } = this.buildWhereClause(options.where);++ let sql = `SELECT ${columns} FROM ${this.escapeIdentifier(table)}${whereClause}`;++ if (options.orderBy) {+ const orderBy =+ typeof options.orderBy === 'string'+ ? options.orderBy+ : `${this.escapeIdentifier(options.orderBy.column)} ${options.orderBy.direction}`;+ sql += ` ORDER BY ${orderBy}`;+ }++ if (options.limit !== undefined) {+ sql += ` LIMIT ${options.limit}`;+ }++ if (options.offset !== undefined) {+ sql += ` OFFSET ${options.offset}`;+ }++ return this.query<T>(sql, params);+ }++ /**+ * Get a single row by ID.+ */+ async getById<T = Record<string, unknown>>(+ table: string,+ id: string | number,+ idColumn: string = 'id'+ ): Promise<T | null> {+ const sql = `SELECT * FROM ${this.escapeIdentifier(table)} WHERE ${this.escapeIdentifier(idColumn)} = ? LIMIT 1`;+ const results = await this.query<T>(sql, [id]);+ return results[0] || null;+ }++ // ─────────────────────────────────────────────────────────────────────────────+ // Private methods+ // ─────────────────────────────────────────────────────────────────────────────++ private async executeLocal<T>(sql: string, params?: SQLParam[]): Promise<T[]> {+ const result = await this.executeLocalRaw<T>(sql, params);+ return result.results;+ }++ private async executeLocalRaw<T>(sql: string, params?: SQLParam[]): Promise<D1QueryResult<T>> {+ // Build the wrangler command+ const dbName = this.config.databaseName;++ // Escape the SQL for shell+ const escapedSql = sql.replace(/'/g, "'\\''");++ // For parameterized queries, we need to substitute the params+ // Note: This is a simplified approach. For production, consider using --json flag+ let finalSql = escapedSql;+ if (params && params.length > 0) {+ let paramIndex = 0;+ finalSql = escapedSql.replace(/\?/g, () => {+ const param = params[paramIndex++];+ if (param === null) return 'NULL';+ if (typeof param === 'string') return `'${param.replace(/'/g, "''")}'`;+ if (typeof param === 'boolean') return param ? '1' : '0';+ return String(param);+ });+ }++ try {+ const output = execSync(`npx wrangler d1 execute ${dbName} --local --json --command='${finalSql}'`, {+ encoding: 'utf-8',+ maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large results+ });++ // Parse JSON output+ const parsed = JSON.parse(output);++ // Wrangler returns an array of results+ if (Array.isArray(parsed) && parsed.length > 0) {+ return parsed[0] as D1QueryResult<T>;+ }++ return {+ success: true,+ results: [],+ meta: {},+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`Local D1 query failed: ${message}`);+ }+ }++ private async executeRemote<T>(sql: string, params?: SQLParam[]): Promise<T[]> {+ const result = await this.executeRemoteRaw<T>(sql, params);+ return result.results;+ }++ private async executeRemoteRaw<T>(sql: string, params?: SQLParam[]): Promise<D1QueryResult<T>> {+ validateRemoteConfig(this.config);++ const { accountId, databaseId, apiToken } = this.config;+ const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/d1/database/${databaseId}/query`;++ const response = await fetch(url, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${apiToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ sql,+ params: params || [],+ }),+ });++ if (!response.ok) {+ const text = await response.text();+ throw new Error(`D1 API error (${response.status}): ${text}`);+ }++ const data = (await response.json()) as D1APIResponse<T>;++ if (!data.success) {+ const errorMessages = data.errors.map((e) => e.message).join(', ');+ throw new Error(`D1 query failed: ${errorMessages}`);+ }++ // D1 REST API returns array of results, we want the first one+ return data.result[0] || { success: true, results: [], meta: {} };+ }++ private buildWhereClause(where?: Record<string, unknown>): { whereClause: string; params: SQLParam[] } {+ if (!where || Object.keys(where).length === 0) {+ return { whereClause: '', params: [] };+ }++ const conditions: string[] = [];+ const params: SQLParam[] = [];++ for (const [key, value] of Object.entries(where)) {+ if (value === null) {+ conditions.push(`${this.escapeIdentifier(key)} IS NULL`);+ } else if (Array.isArray(value)) {+ const placeholders = value.map(() => '?').join(', ');+ conditions.push(`${this.escapeIdentifier(key)} IN (${placeholders})`);+ params.push(...(value as SQLParam[]));+ } else {+ conditions.push(`${this.escapeIdentifier(key)} = ?`);+ params.push(value as SQLParam);+ }+ }++ return {+ whereClause: ` WHERE ${conditions.join(' AND ')}`,+ params,+ };+ }++ private escapeIdentifier(identifier: string): string {+ // SQLite uses double quotes for identifiers+ return `"${identifier.replace(/"/g, '""')}"`;+ }+}++// Default singleton instance+export const db = new DBClient();diff --git a/skills/ts-agent-sdk/templates/db/config.ts b/skills/ts-agent-sdk/templates/db/config.tsnew file mode 100644index 00000000..9d7eed62--- /dev/null+++ b/skills/ts-agent-sdk/templates/db/config.ts@@ -0,0 +1,90 @@+/**+ * ts-agent-sdk Database Configuration+ *+ * Environment variables for D1 database access:+ * - SDK_DB_MODE: 'local' | 'remote' | 'auto' (default: 'auto')+ * - SDK_D1_DATABASE_NAME: D1 database binding name from wrangler.jsonc+ * - SDK_D1_DATABASE_ID: D1 database ID (required for remote mode)+ * - SDK_CF_ACCOUNT_ID: Cloudflare account ID (required for remote mode)+ * - SDK_CF_API_TOKEN: Cloudflare API token (required for remote mode)+ */++import { existsSync } from 'fs';++export type DBMode = 'local' | 'remote' | 'auto';++export interface DBConfig {+ mode: DBMode;+ databaseName: string;+ databaseId: string;+ accountId: string;+ apiToken: string;+}++/**+ * Load database configuration from environment variables.+ */+export function loadDBConfig(): DBConfig {+ return {+ mode: (process.env.SDK_DB_MODE as DBMode) || 'auto',+ databaseName: process.env.SDK_D1_DATABASE_NAME || 'DB',+ databaseId: process.env.SDK_D1_DATABASE_ID || '',+ accountId: process.env.SDK_CF_ACCOUNT_ID || '',+ apiToken: process.env.SDK_CF_API_TOKEN || '',+ };+}++/**+ * Resolve the effective mode (auto → local or remote).+ *+ * Auto-detection logic:+ * - If wrangler.jsonc exists in current directory → local+ * - Otherwise → remote+ */+export function resolveDBMode(config: DBConfig): 'local' | 'remote' {+ if (config.mode === 'auto') {+ // Check for wrangler config in current directory or parent+ const hasWranglerConfig =+ existsSync('./wrangler.jsonc') ||+ existsSync('./wrangler.toml') ||+ existsSync('./wrangler.json');++ return hasWranglerConfig ? 'local' : 'remote';+ }+ return config.mode;+}++/**+ * Validate configuration for remote mode.+ */+export function validateRemoteConfig(config: DBConfig): void {+ if (!config.databaseId) {+ throw new Error(+ 'SDK_D1_DATABASE_ID is required for remote database access. ' ++ 'Find it in Cloudflare dashboard or wrangler.jsonc.'+ );+ }+ if (!config.accountId) {+ throw new Error(+ 'SDK_CF_ACCOUNT_ID is required for remote database access. ' ++ 'Find it in Cloudflare dashboard.'+ );+ }+ if (!config.apiToken) {+ throw new Error(+ 'SDK_CF_API_TOKEN is required for remote database access. ' ++ 'Create one at https://dash.cloudflare.com/profile/api-tokens'+ );+ }+}++/**+ * Get the wrangler config path if it exists.+ */+export function getWranglerConfigPath(): string | null {+ const paths = ['./wrangler.jsonc', './wrangler.toml', './wrangler.json'];+ for (const path of paths) {+ if (existsSync(path)) return path;+ }+ return null;+}diff --git a/skills/ts-agent-sdk/templates/db/index.ts b/skills/ts-agent-sdk/templates/db/index.tsnew file mode 100644index 00000000..1e58ae27--- /dev/null+++ b/skills/ts-agent-sdk/templates/db/index.ts@@ -0,0 +1,35 @@+/**+ * ts-agent-sdk Direct DB Module+ *+ * Execute SQL queries directly against Cloudflare D1.+ *+ * Environment Variables:+ * - SDK_DB_MODE: 'local' | 'remote' | 'auto' (default: 'auto')+ * - SDK_D1_DATABASE_NAME: D1 database binding name (default: 'DB')+ * - SDK_D1_DATABASE_ID: D1 database ID (for remote mode)+ * - SDK_CF_ACCOUNT_ID: Cloudflare account ID (for remote mode)+ * - SDK_CF_API_TOKEN: Cloudflare API token (for remote mode)+ */++// Configuration+export {+ loadDBConfig,+ resolveDBMode,+ validateRemoteConfig,+ getWranglerConfigPath,+ type DBConfig,+ type DBMode,+} from './config';++// Types+export type {+ D1QueryResult,+ D1APIResponse,+ CountOptions,+ SelectOptions,+ SQLParam,+ AggregateResult,+} from './types';++// Client+export { DBClient, db } from './client';diff --git a/skills/ts-agent-sdk/templates/db/types.ts b/skills/ts-agent-sdk/templates/db/types.tsnew file mode 100644index 00000000..02b28b68--- /dev/null+++ b/skills/ts-agent-sdk/templates/db/types.ts@@ -0,0 +1,67 @@+/**+ * ts-agent-sdk Database Types+ *+ * Common types for database operations.+ */++/**+ * Result of a D1 query.+ */+export interface D1QueryResult<T = Record<string, unknown>> {+ success: boolean;+ results: T[];+ meta: {+ served_by?: string;+ duration?: number;+ changes?: number;+ last_row_id?: number;+ changed_db?: boolean;+ size_after?: number;+ rows_read?: number;+ rows_written?: number;+ };+}++/**+ * Result from Cloudflare D1 REST API.+ */+export interface D1APIResponse<T = Record<string, unknown>> {+ success: boolean;+ errors: { code: number; message: string }[];+ messages: string[];+ result: D1QueryResult<T>[];+}++/**+ * Options for count queries.+ */+export interface CountOptions {+ where?: Record<string, unknown>;+}++/**+ * Options for select queries.+ */+export interface SelectOptions {+ columns?: string[];+ where?: Record<string, unknown>;+ orderBy?: string | { column: string; direction: 'ASC' | 'DESC' };+ limit?: number;+ offset?: number;+}++/**+ * Represents a parameter that can be bound to a SQL query.+ */+export type SQLParam = string | number | boolean | null | Uint8Array;++/**+ * Aggregate function result.+ */+export interface AggregateResult {+ count?: number;+ sum?: number;+ avg?: number;+ min?: number | string;+ max?: number | string;+}diff --git a/skills/ts-agent-sdk/templates/errors.ts b/skills/ts-agent-sdk/templates/errors.tsnew file mode 100644index 00000000..a231a238--- /dev/null+++ b/skills/ts-agent-sdk/templates/errors.ts@@ -0,0 +1,106 @@+/**+ * ts-agent-sdk Error Classes+ *+ * Typed errors for consistent error handling across SDK operations.+ * Each error has a code property for programmatic handling.+ */++/**+ * Base SDK error class. All SDK errors extend this.+ */+export class SDKError extends Error {+ code: string;++ constructor(message: string, code: string) {+ super(message);+ this.name = 'SDKError';+ this.code = code;+ // Maintains proper stack trace in V8 environments+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, this.constructor);+ }+ }+}++/**+ * Authentication failed (401).+ * Check SDK_API_TOKEN is set and valid.+ */+export class AuthError extends SDKError {+ constructor(message: string = 'Authentication failed. Check your API token.') {+ super(message, 'AUTH_ERROR');+ this.name = 'AuthError';+ }+}++/**+ * Input validation failed.+ * The request was rejected due to invalid input data.+ */+export class ValidationError extends SDKError {+ field?: string;++ constructor(message: string, field?: string) {+ super(message, 'VALIDATION_ERROR');+ this.name = 'ValidationError';+ this.field = field;+ }+}++/**+ * Resource not found (404).+ * The requested resource doesn't exist or you don't have access.+ */+export class NotFoundError extends SDKError {+ resourceType: string;+ resourceId: string;++ constructor(resourceType: string, resourceId: string) {+ super(`${resourceType} not found: ${resourceId}`, 'NOT_FOUND');+ this.name = 'NotFoundError';+ this.resourceType = resourceType;+ this.resourceId = resourceId;+ }+}++/**+ * Rate limited (429).+ * Too many requests. Wait before retrying.+ */+export class RateLimitError extends SDKError {+ retryAfterSeconds: number;++ constructor(retryAfterSeconds: number = 60) {+ super(`Rate limited. Retry after ${retryAfterSeconds} seconds.`, 'RATE_LIMIT');+ this.name = 'RateLimitError';+ this.retryAfterSeconds = retryAfterSeconds;+ }+}++/**+ * MCP protocol error.+ * The MCP server returned an error response.+ */+export class MCPError extends SDKError {+ mcpCode?: number;++ constructor(message: string, mcpCode?: number) {+ super(message, 'MCP_ERROR');+ this.name = 'MCPError';+ this.mcpCode = mcpCode;+ }+}++/**+ * Network or connection error.+ * Could not reach the server.+ */+export class NetworkError extends SDKError {+ cause?: Error;++ constructor(message: string = 'Network error. Could not reach server.', cause?: Error) {+ super(message, 'NETWORK_ERROR');+ this.name = 'NetworkError';+ this.cause = cause;+ }+}diff --git a/skills/ts-agent-sdk/templates/index.ts b/skills/ts-agent-sdk/templates/index.tsnew file mode 100644index 00000000..370e4d7a--- /dev/null+++ b/skills/ts-agent-sdk/templates/index.ts@@ -0,0 +1,65 @@+/**+ * ts-agent-sdk+ *+ * TypeScript SDK for AI agents to interact with web applications.+ * Supports three access patterns:+ *+ * 1. **MCP Wrapper** - Typed wrapper around MCP server tools+ * 2. **Direct DB** - SQL queries against Cloudflare D1+ * 3. **Direct API** - External service calls (AI, webhooks, etc.)+ *+ * Usage:+ * ```typescript+ * import { docs, db, api } from './sdk';+ *+ * // Pattern 1: MCP Wrapper+ * const result = await docs.createDocument({+ * spaceId: 'wiki',+ * title: 'Getting Started',+ * content: '# Welcome',+ * });+ *+ * // Pattern 2: Direct DB+ * const stats = await db.query('SELECT status, COUNT(*) FROM documents GROUP BY status');+ *+ * // Pattern 3: Direct API+ * const summary = await api.gemini.summarize(content);+ * await api.slack.postMessage('Document created!');+ * ```+ *+ * Environment Variables:+ * - SDK_MODE: 'local' | 'remote' | 'auto' (default: 'auto')+ * - SDK_BASE_URL: Target Worker URL (MCP)+ * - SDK_API_TOKEN: Bearer token for MCP authentication+ * - SDK_GEMINI_API_KEY: Gemini API key+ * - SDK_CF_ACCOUNT_ID: Cloudflare account ID+ * - SDK_CF_API_TOKEN: Cloudflare API token+ * - SDK_D1_DATABASE_ID: D1 database ID+ * - SDK_SLACK_WEBHOOK_URL: Slack webhook URL+ */++// Core exports+export { loadConfig, validateConfig, type SDKConfig, type ExecutionMode } from './config';+export {+ SDKError,+ AuthError,+ ValidationError,+ NotFoundError,+ RateLimitError,+ MCPError,+ NetworkError,+} from './errors';+export { MCPClient, defaultClient, type MCPResponse } from './client';++// Direct DB exports+export * as db from './db';+export { DBClient, db as dbClient } from './db';++// Direct API exports+export * as api from './api';+export { gemini, workersAI, slack, webhook, triggerN8n } from './api';+export * as holidays from './api/public/holidays';++// Module exports (uncomment and add as you generate modules)+// export { docs } from './docs';+// export { enquiries } from './enquiries';