[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6F9GK5NSSTKC29DA1S94BJK":3,"skill-same:01M6F9GK5NSSTKC29DA1S94BJK":79},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":47,"linkOnly":48,"markdownContent":49,"markdownBody":50,"frontMatter":51,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":59,"repositoryHtmlUrl":60,"repositoryHomepageUrl":6,"ownerHtmlUrl":61,"ownerBlogUrl":62,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M6F9GK5NSSTKC29DA1S94BJK","twinmind-sdk-patterns",null,"Apply production-ready TwinMind SDK patterns for TypeScript and Python.\nUse when implementing TwinMind integrations, refactoring API usage,\nor establishing team coding standards for meeting AI integration.\nTrigger with phrases like \"twinmind SDK patterns\", \"twinmind best practices\",\n\"twinmind code patterns\", \"idiomatic twinmind\".","Dicklesworthstone\u002Fpi_agent_rust","Dicklesworthstone","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F35050222?v=4","01M6CG26AR942CSVMN1M5E3DSE","Jeff Emanuel","01M6CG26EPP71PSHW1VDS71121",1992,"MIT","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Fplugins-community\u002Fplugins\u002Fsaas-packs\u002Ftwinmind-pack\u002Fskills\u002Ftwinmind-sdk-patterns\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],"sdk","twinmind sdk patterns","patterns","write","when","implementing","production-ready","code patterns","trigger","io","standards","ready","edit","typescript","read","coding","integrations","refactoring","team","api","coding standards","code","python","2026-11-10 10:12:30",false,"---\nname: twinmind-sdk-patterns\ndescription: |\n  Apply production-ready TwinMind SDK patterns for TypeScript and Python.\n  Use when implementing TwinMind integrations, refactoring API usage,\n  or establishing team coding standards for meeting AI integration.\n  Trigger with phrases like \"twinmind SDK patterns\", \"twinmind best practices\",\n  \"twinmind code patterns\", \"idiomatic twinmind\".\nallowed-tools: Read, Write, Edit\nversion: 1.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\n---\n\n# TwinMind SDK Patterns\n\n## Overview\nProduction-ready patterns for TwinMind API integration in TypeScript and Python.\n\n## Prerequisites\n- Completed `twinmind-install-auth` setup\n- Familiarity with async\u002Fawait patterns\n- Understanding of error handling best practices\n- TwinMind Pro or Enterprise API access\n\n## Instructions\n\n### Step 1: Implement Singleton Pattern (Recommended)\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fclient.ts\nimport axios, { AxiosInstance } from 'axios';\n\nlet instance: TwinMindClient | null = null;\n\nexport interface TwinMindConfig {\n  apiKey: string;\n  baseUrl?: string;\n  timeout?: number;\n  retries?: number;\n}\n\nexport class TwinMindClient {\n  private client: AxiosInstance;\n  private config: TwinMindConfig;\n\n  private constructor(config: TwinMindConfig) {\n    this.config = config;\n    this.client = axios.create({\n      baseURL: config.baseUrl || 'https:\u002F\u002Fapi.twinmind.com\u002Fv1',\n      headers: {\n        'Authorization': `Bearer ${config.apiKey}`,\n        'Content-Type': 'application\u002Fjson',\n      },\n      timeout: config.timeout || 30000,\n    });\n  }\n\n  static getInstance(config?: TwinMindConfig): TwinMindClient {\n    if (!instance) {\n      if (!config) {\n        throw new Error('TwinMindClient must be initialized with config');\n      }\n      instance = new TwinMindClient(config);\n    }\n    return instance;\n  }\n\n  static resetInstance(): void {\n    instance = null;\n  }\n}\n\n\u002F\u002F Usage\nexport function getTwinMindClient(): TwinMindClient {\n  return TwinMindClient.getInstance({\n    apiKey: process.env.TWINMIND_API_KEY!,\n  });\n}\n```\n\n### Step 2: Add Error Handling Wrapper\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Ferrors.ts\nexport class TwinMindError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly statusCode?: number,\n    public readonly retryable: boolean = false,\n    public readonly originalError?: Error\n  ) {\n    super(message);\n    this.name = 'TwinMindError';\n  }\n}\n\nexport class TranscriptionError extends TwinMindError {\n  constructor(message: string, originalError?: Error) {\n    super(message, 'TRANSCRIPTION_FAILED', 500, true, originalError);\n  }\n}\n\nexport class RateLimitError extends TwinMindError {\n  constructor(retryAfter: number) {\n    super(`Rate limited. Retry after ${retryAfter}s`, 'RATE_LIMITED', 429, true);\n  }\n}\n\nexport class AuthenticationError extends TwinMindError {\n  constructor() {\n    super('Invalid or expired API key', 'AUTH_FAILED', 401, false);\n  }\n}\n\n\u002F\u002F Safe wrapper function\nasync function safeTwinMindCall\u003CT>(\n  operation: () => Promise\u003CT>\n): Promise\u003C{ data: T | null; error: TwinMindError | null }> {\n  try {\n    const data = await operation();\n    return { data, error: null };\n  } catch (err: any) {\n    const error = mapToTwinMindError(err);\n    console.error({\n      code: error.code,\n      message: error.message,\n      statusCode: error.statusCode,\n      retryable: error.retryable,\n    });\n    return { data: null, error };\n  }\n}\n\nfunction mapToTwinMindError(err: any): TwinMindError {\n  if (err.response?.status === 401) {\n    return new AuthenticationError();\n  }\n  if (err.response?.status === 429) {\n    return new RateLimitError(parseInt(err.response.headers['retry-after'] || '60'));\n  }\n  if (err.response?.status >= 500) {\n    return new TranscriptionError(err.message, err);\n  }\n  return new TwinMindError(err.message, 'UNKNOWN', err.response?.status);\n}\n```\n\n### Step 3: Implement Retry Logic with Backoff\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fretry.ts\ninterface RetryConfig {\n  maxRetries: number;\n  baseDelayMs: number;\n  maxDelayMs: number;\n  jitterMs: number;\n}\n\nconst defaultRetryConfig: RetryConfig = {\n  maxRetries: 3,\n  baseDelayMs: 1000,\n  maxDelayMs: 30000,\n  jitterMs: 500,\n};\n\nasync function withRetry\u003CT>(\n  operation: () => Promise\u003CT>,\n  config: Partial\u003CRetryConfig> = {}\n): Promise\u003CT> {\n  const { maxRetries, baseDelayMs, maxDelayMs, jitterMs } = {\n    ...defaultRetryConfig,\n    ...config,\n  };\n\n  for (let attempt = 0; attempt \u003C= maxRetries; attempt++) {\n    try {\n      return await operation();\n    } catch (err: any) {\n      if (attempt === maxRetries) throw err;\n\n      \u002F\u002F Only retry on retryable errors\n      const status = err.response?.status;\n      if (status && status !== 429 && status \u003C 500) throw err;\n\n      \u002F\u002F Exponential backoff with jitter\n      const delay = Math.min(\n        baseDelayMs * Math.pow(2, attempt) + Math.random() * jitterMs,\n        maxDelayMs\n      );\n\n      console.log(`Attempt ${attempt + 1} failed. Retrying in ${delay.toFixed(0)}ms...`);\n      await new Promise(r => setTimeout(r, delay));\n    }\n  }\n  throw new Error('Unreachable');\n}\n```\n\n### Step 4: Implement Transcript Processing Pipeline\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fpipeline.ts\nimport { z } from 'zod';\n\n\u002F\u002F Zod schemas for validation\nconst SegmentSchema = z.object({\n  start: z.number(),\n  end: z.number(),\n  text: z.string(),\n  confidence: z.number().min(0).max(1),\n  speaker_id: z.string().optional(),\n});\n\nconst TranscriptSchema = z.object({\n  id: z.string(),\n  text: z.string(),\n  duration_seconds: z.number().positive(),\n  language: z.string(),\n  segments: z.array(SegmentSchema),\n  speakers: z.array(z.object({\n    id: z.string(),\n    name: z.string().optional(),\n  })),\n  created_at: z.string().datetime(),\n});\n\nexport type Transcript = z.infer\u003Ctypeof TranscriptSchema>;\nexport type Segment = z.infer\u003Ctypeof SegmentSchema>;\n\n\u002F\u002F Pipeline processing\nexport class TranscriptPipeline {\n  private processors: Array\u003C(t: Transcript) => Transcript> = [];\n\n  addProcessor(processor: (t: Transcript) => Transcript): this {\n    this.processors.push(processor);\n    return this;\n  }\n\n  process(transcript: Transcript): Transcript {\n    return this.processors.reduce((t, processor) => processor(t), transcript);\n  }\n}\n\n\u002F\u002F Built-in processors\nexport const filterLowConfidence = (threshold: number) =>\n  (transcript: Transcript): Transcript => ({\n    ...transcript,\n    segments: transcript.segments.filter(s => s.confidence >= threshold),\n  });\n\nexport const mergeShortSegments = (minDurationMs: number) =>\n  (transcript: Transcript): Transcript => {\n    const merged: Segment[] = [];\n    let buffer: Segment | null = null;\n\n    for (const segment of transcript.segments) {\n      const duration = (segment.end - segment.start) * 1000;\n\n      if (duration \u003C minDurationMs && buffer) {\n        buffer = {\n          ...buffer,\n          end: segment.end,\n          text: `${buffer.text} ${segment.text}`,\n          confidence: (buffer.confidence + segment.confidence) \u002F 2,\n        };\n      } else {\n        if (buffer) merged.push(buffer);\n        buffer = { ...segment };\n      }\n    }\n    if (buffer) merged.push(buffer);\n\n    return { ...transcript, segments: merged };\n  };\n\n\u002F\u002F Usage example\nconst pipeline = new TranscriptPipeline()\n  .addProcessor(filterLowConfidence(0.8))\n  .addProcessor(mergeShortSegments(500));\n```\n\n### Step 5: Implement Caching Layer\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fcache.ts\ninterface CacheEntry\u003CT> {\n  data: T;\n  expiresAt: number;\n}\n\nclass TranscriptCache {\n  private cache = new Map\u003Cstring, CacheEntry\u003Cany>>();\n  private defaultTtlMs: number;\n\n  constructor(defaultTtlMs = 3600000) { \u002F\u002F 1 hour default\n    this.defaultTtlMs = defaultTtlMs;\n  }\n\n  set\u003CT>(key: string, data: T, ttlMs?: number): void {\n    this.cache.set(key, {\n      data,\n      expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs),\n    });\n  }\n\n  get\u003CT>(key: string): T | null {\n    const entry = this.cache.get(key);\n    if (!entry) return null;\n    if (Date.now() > entry.expiresAt) {\n      this.cache.delete(key);\n      return null;\n    }\n    return entry.data as T;\n  }\n\n  async getOrFetch\u003CT>(\n    key: string,\n    fetcher: () => Promise\u003CT>,\n    ttlMs?: number\n  ): Promise\u003CT> {\n    const cached = this.get\u003CT>(key);\n    if (cached) return cached;\n\n    const data = await fetcher();\n    this.set(key, data, ttlMs);\n    return data;\n  }\n\n  invalidate(key: string): void {\n    this.cache.delete(key);\n  }\n\n  clear(): void {\n    this.cache.clear();\n  }\n}\n\nexport const transcriptCache = new TranscriptCache();\n```\n\n## Output\n- Type-safe client singleton\n- Robust error handling with custom error classes\n- Automatic retry with exponential backoff\n- Transcript processing pipeline\n- Caching layer for API responses\n\n## Error Handling\n\n| Pattern | Use Case | Benefit |\n|---------|----------|---------|\n| Safe wrapper | All API calls | Prevents uncaught exceptions |\n| Retry logic | Transient failures | Improves reliability |\n| Pipeline processing | Transcript cleanup | Flexible data transformation |\n| Caching | Repeated queries | Reduces API calls |\n| Zod validation | Response parsing | Runtime type safety |\n\n## Examples\n\n### Python Context Manager\n\n```python\n# twinmind\u002Fclient.py\nfrom contextlib import asynccontextmanager\nfrom typing import AsyncGenerator\nimport httpx\n\nclass TwinMindClient:\n    def __init__(self, api_key: str, base_url: str = \"https:\u002F\u002Fapi.twinmind.com\u002Fv1\"):\n        self.api_key = api_key\n        self.base_url = base_url\n        self._client: httpx.AsyncClient | None = None\n\n    async def __aenter__(self):\n        self._client = httpx.AsyncClient(\n            base_url=self.base_url,\n            headers={\"Authorization\": f\"Bearer {self.api_key}\"},\n            timeout=30.0,\n        )\n        return self\n\n    async def __aexit__(self, *args):\n        if self._client:\n            await self._client.aclose()\n\n    async def transcribe(self, audio_url: str) -> dict:\n        response = await self._client.post(\"\u002Ftranscribe\", json={\"audio_url\": audio_url})\n        response.raise_for_status()\n        return response.json()\n\n\n@asynccontextmanager\nasync def get_twinmind_client() -> AsyncGenerator[TwinMindClient, None]:\n    async with TwinMindClient(os.environ[\"TWINMIND_API_KEY\"]) as client:\n        yield client\n\n\n# Usage\nasync def process_meeting(audio_url: str):\n    async with get_twinmind_client() as client:\n        transcript = await client.transcribe(audio_url)\n        return transcript\n```\n\n### Multi-Tenant Factory Pattern\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Ffactory.ts\nconst clients = new Map\u003Cstring, TwinMindClient>();\n\nexport function getClientForOrganization(orgId: string): TwinMindClient {\n  if (!clients.has(orgId)) {\n    const apiKey = getOrganizationApiKey(orgId);\n    clients.set(orgId, TwinMindClient.getInstance({\n      apiKey,\n      baseUrl: process.env.TWINMIND_API_URL,\n    }));\n  }\n  return clients.get(orgId)!;\n}\n\nfunction getOrganizationApiKey(orgId: string): string {\n  \u002F\u002F Fetch from secrets manager or database\n  return process.env[`TWINMIND_API_KEY_${orgId}`] ||\n         process.env.TWINMIND_API_KEY!;\n}\n```\n\n## Resources\n- [TwinMind API Reference](https:\u002F\u002Ftwinmind.com\u002Fdocs\u002Fapi)\n- [Zod Documentation](https:\u002F\u002Fzod.dev\u002F)\n- [Axios Best Practices](https:\u002F\u002Faxios-http.com\u002Fdocs\u002Fintro)\n\n## Next Steps\nApply patterns in `twinmind-core-workflow-a` for meeting transcription workflows.\n","# TwinMind SDK Patterns\n\n## Overview\nProduction-ready patterns for TwinMind API integration in TypeScript and Python.\n\n## Prerequisites\n- Completed `twinmind-install-auth` setup\n- Familiarity with async\u002Fawait patterns\n- Understanding of error handling best practices\n- TwinMind Pro or Enterprise API access\n\n## Instructions\n\n### Step 1: Implement Singleton Pattern (Recommended)\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fclient.ts\nimport axios, { AxiosInstance } from 'axios';\n\nlet instance: TwinMindClient | null = null;\n\nexport interface TwinMindConfig {\n  apiKey: string;\n  baseUrl?: string;\n  timeout?: number;\n  retries?: number;\n}\n\nexport class TwinMindClient {\n  private client: AxiosInstance;\n  private config: TwinMindConfig;\n\n  private constructor(config: TwinMindConfig) {\n    this.config = config;\n    this.client = axios.create({\n      baseURL: config.baseUrl || 'https:\u002F\u002Fapi.twinmind.com\u002Fv1',\n      headers: {\n        'Authorization': `Bearer ${config.apiKey}`,\n        'Content-Type': 'application\u002Fjson',\n      },\n      timeout: config.timeout || 30000,\n    });\n  }\n\n  static getInstance(config?: TwinMindConfig): TwinMindClient {\n    if (!instance) {\n      if (!config) {\n        throw new Error('TwinMindClient must be initialized with config');\n      }\n      instance = new TwinMindClient(config);\n    }\n    return instance;\n  }\n\n  static resetInstance(): void {\n    instance = null;\n  }\n}\n\n\u002F\u002F Usage\nexport function getTwinMindClient(): TwinMindClient {\n  return TwinMindClient.getInstance({\n    apiKey: process.env.TWINMIND_API_KEY!,\n  });\n}\n```\n\n### Step 2: Add Error Handling Wrapper\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Ferrors.ts\nexport class TwinMindError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly statusCode?: number,\n    public readonly retryable: boolean = false,\n    public readonly originalError?: Error\n  ) {\n    super(message);\n    this.name = 'TwinMindError';\n  }\n}\n\nexport class TranscriptionError extends TwinMindError {\n  constructor(message: string, originalError?: Error) {\n    super(message, 'TRANSCRIPTION_FAILED', 500, true, originalError);\n  }\n}\n\nexport class RateLimitError extends TwinMindError {\n  constructor(retryAfter: number) {\n    super(`Rate limited. Retry after ${retryAfter}s`, 'RATE_LIMITED', 429, true);\n  }\n}\n\nexport class AuthenticationError extends TwinMindError {\n  constructor() {\n    super('Invalid or expired API key', 'AUTH_FAILED', 401, false);\n  }\n}\n\n\u002F\u002F Safe wrapper function\nasync function safeTwinMindCall\u003CT>(\n  operation: () => Promise\u003CT>\n): Promise\u003C{ data: T | null; error: TwinMindError | null }> {\n  try {\n    const data = await operation();\n    return { data, error: null };\n  } catch (err: any) {\n    const error = mapToTwinMindError(err);\n    console.error({\n      code: error.code,\n      message: error.message,\n      statusCode: error.statusCode,\n      retryable: error.retryable,\n    });\n    return { data: null, error };\n  }\n}\n\nfunction mapToTwinMindError(err: any): TwinMindError {\n  if (err.response?.status === 401) {\n    return new AuthenticationError();\n  }\n  if (err.response?.status === 429) {\n    return new RateLimitError(parseInt(err.response.headers['retry-after'] || '60'));\n  }\n  if (err.response?.status >= 500) {\n    return new TranscriptionError(err.message, err);\n  }\n  return new TwinMindError(err.message, 'UNKNOWN', err.response?.status);\n}\n```\n\n### Step 3: Implement Retry Logic with Backoff\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fretry.ts\ninterface RetryConfig {\n  maxRetries: number;\n  baseDelayMs: number;\n  maxDelayMs: number;\n  jitterMs: number;\n}\n\nconst defaultRetryConfig: RetryConfig = {\n  maxRetries: 3,\n  baseDelayMs: 1000,\n  maxDelayMs: 30000,\n  jitterMs: 500,\n};\n\nasync function withRetry\u003CT>(\n  operation: () => Promise\u003CT>,\n  config: Partial\u003CRetryConfig> = {}\n): Promise\u003CT> {\n  const { maxRetries, baseDelayMs, maxDelayMs, jitterMs } = {\n    ...defaultRetryConfig,\n    ...config,\n  };\n\n  for (let attempt = 0; attempt \u003C= maxRetries; attempt++) {\n    try {\n      return await operation();\n    } catch (err: any) {\n      if (attempt === maxRetries) throw err;\n\n      \u002F\u002F Only retry on retryable errors\n      const status = err.response?.status;\n      if (status && status !== 429 && status \u003C 500) throw err;\n\n      \u002F\u002F Exponential backoff with jitter\n      const delay = Math.min(\n        baseDelayMs * Math.pow(2, attempt) + Math.random() * jitterMs,\n        maxDelayMs\n      );\n\n      console.log(`Attempt ${attempt + 1} failed. Retrying in ${delay.toFixed(0)}ms...`);\n      await new Promise(r => setTimeout(r, delay));\n    }\n  }\n  throw new Error('Unreachable');\n}\n```\n\n### Step 4: Implement Transcript Processing Pipeline\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fpipeline.ts\nimport { z } from 'zod';\n\n\u002F\u002F Zod schemas for validation\nconst SegmentSchema = z.object({\n  start: z.number(),\n  end: z.number(),\n  text: z.string(),\n  confidence: z.number().min(0).max(1),\n  speaker_id: z.string().optional(),\n});\n\nconst TranscriptSchema = z.object({\n  id: z.string(),\n  text: z.string(),\n  duration_seconds: z.number().positive(),\n  language: z.string(),\n  segments: z.array(SegmentSchema),\n  speakers: z.array(z.object({\n    id: z.string(),\n    name: z.string().optional(),\n  })),\n  created_at: z.string().datetime(),\n});\n\nexport type Transcript = z.infer\u003Ctypeof TranscriptSchema>;\nexport type Segment = z.infer\u003Ctypeof SegmentSchema>;\n\n\u002F\u002F Pipeline processing\nexport class TranscriptPipeline {\n  private processors: Array\u003C(t: Transcript) => Transcript> = [];\n\n  addProcessor(processor: (t: Transcript) => Transcript): this {\n    this.processors.push(processor);\n    return this;\n  }\n\n  process(transcript: Transcript): Transcript {\n    return this.processors.reduce((t, processor) => processor(t), transcript);\n  }\n}\n\n\u002F\u002F Built-in processors\nexport const filterLowConfidence = (threshold: number) =>\n  (transcript: Transcript): Transcript => ({\n    ...transcript,\n    segments: transcript.segments.filter(s => s.confidence >= threshold),\n  });\n\nexport const mergeShortSegments = (minDurationMs: number) =>\n  (transcript: Transcript): Transcript => {\n    const merged: Segment[] = [];\n    let buffer: Segment | null = null;\n\n    for (const segment of transcript.segments) {\n      const duration = (segment.end - segment.start) * 1000;\n\n      if (duration \u003C minDurationMs && buffer) {\n        buffer = {\n          ...buffer,\n          end: segment.end,\n          text: `${buffer.text} ${segment.text}`,\n          confidence: (buffer.confidence + segment.confidence) \u002F 2,\n        };\n      } else {\n        if (buffer) merged.push(buffer);\n        buffer = { ...segment };\n      }\n    }\n    if (buffer) merged.push(buffer);\n\n    return { ...transcript, segments: merged };\n  };\n\n\u002F\u002F Usage example\nconst pipeline = new TranscriptPipeline()\n  .addProcessor(filterLowConfidence(0.8))\n  .addProcessor(mergeShortSegments(500));\n```\n\n### Step 5: Implement Caching Layer\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Fcache.ts\ninterface CacheEntry\u003CT> {\n  data: T;\n  expiresAt: number;\n}\n\nclass TranscriptCache {\n  private cache = new Map\u003Cstring, CacheEntry\u003Cany>>();\n  private defaultTtlMs: number;\n\n  constructor(defaultTtlMs = 3600000) { \u002F\u002F 1 hour default\n    this.defaultTtlMs = defaultTtlMs;\n  }\n\n  set\u003CT>(key: string, data: T, ttlMs?: number): void {\n    this.cache.set(key, {\n      data,\n      expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs),\n    });\n  }\n\n  get\u003CT>(key: string): T | null {\n    const entry = this.cache.get(key);\n    if (!entry) return null;\n    if (Date.now() > entry.expiresAt) {\n      this.cache.delete(key);\n      return null;\n    }\n    return entry.data as T;\n  }\n\n  async getOrFetch\u003CT>(\n    key: string,\n    fetcher: () => Promise\u003CT>,\n    ttlMs?: number\n  ): Promise\u003CT> {\n    const cached = this.get\u003CT>(key);\n    if (cached) return cached;\n\n    const data = await fetcher();\n    this.set(key, data, ttlMs);\n    return data;\n  }\n\n  invalidate(key: string): void {\n    this.cache.delete(key);\n  }\n\n  clear(): void {\n    this.cache.clear();\n  }\n}\n\nexport const transcriptCache = new TranscriptCache();\n```\n\n## Output\n- Type-safe client singleton\n- Robust error handling with custom error classes\n- Automatic retry with exponential backoff\n- Transcript processing pipeline\n- Caching layer for API responses\n\n## Error Handling\n\n| Pattern | Use Case | Benefit |\n|---------|----------|---------|\n| Safe wrapper | All API calls | Prevents uncaught exceptions |\n| Retry logic | Transient failures | Improves reliability |\n| Pipeline processing | Transcript cleanup | Flexible data transformation |\n| Caching | Repeated queries | Reduces API calls |\n| Zod validation | Response parsing | Runtime type safety |\n\n## Examples\n\n### Python Context Manager\n\n```python\n# twinmind\u002Fclient.py\nfrom contextlib import asynccontextmanager\nfrom typing import AsyncGenerator\nimport httpx\n\nclass TwinMindClient:\n    def __init__(self, api_key: str, base_url: str = \"https:\u002F\u002Fapi.twinmind.com\u002Fv1\"):\n        self.api_key = api_key\n        self.base_url = base_url\n        self._client: httpx.AsyncClient | None = None\n\n    async def __aenter__(self):\n        self._client = httpx.AsyncClient(\n            base_url=self.base_url,\n            headers={\"Authorization\": f\"Bearer {self.api_key}\"},\n            timeout=30.0,\n        )\n        return self\n\n    async def __aexit__(self, *args):\n        if self._client:\n            await self._client.aclose()\n\n    async def transcribe(self, audio_url: str) -> dict:\n        response = await self._client.post(\"\u002Ftranscribe\", json={\"audio_url\": audio_url})\n        response.raise_for_status()\n        return response.json()\n\n\n@asynccontextmanager\nasync def get_twinmind_client() -> AsyncGenerator[TwinMindClient, None]:\n    async with TwinMindClient(os.environ[\"TWINMIND_API_KEY\"]) as client:\n        yield client\n\n\n# Usage\nasync def process_meeting(audio_url: str):\n    async with get_twinmind_client() as client:\n        transcript = await client.transcribe(audio_url)\n        return transcript\n```\n\n### Multi-Tenant Factory Pattern\n\n```typescript\n\u002F\u002F src\u002Ftwinmind\u002Ffactory.ts\nconst clients = new Map\u003Cstring, TwinMindClient>();\n\nexport function getClientForOrganization(orgId: string): TwinMindClient {\n  if (!clients.has(orgId)) {\n    const apiKey = getOrganizationApiKey(orgId);\n    clients.set(orgId, TwinMindClient.getInstance({\n      apiKey,\n      baseUrl: process.env.TWINMIND_API_URL,\n    }));\n  }\n  return clients.get(orgId)!;\n}\n\nfunction getOrganizationApiKey(orgId: string): string {\n  \u002F\u002F Fetch from secrets manager or database\n  return process.env[`TWINMIND_API_KEY_${orgId}`] ||\n         process.env.TWINMIND_API_KEY!;\n}\n```\n\n## Resources\n- [TwinMind API Reference](https:\u002F\u002Ftwinmind.com\u002Fdocs\u002Fapi)\n- [Zod Documentation](https:\u002F\u002Fzod.dev\u002F)\n- [Axios Best Practices](https:\u002F\u002Faxios-http.com\u002Fdocs\u002Fintro)\n\n## Next Steps\nApply patterns in `twinmind-core-workflow-a` for meeting transcription workflows.\n",{"name":5,"author":52,"license":15,"version":53,"description":54,"allowed-tools":55},"Jeremy Longshore \u003Cjeremy@intentsolutions.io>","1.0.0","Apply production-ready TwinMind SDK patterns for TypeScript and Python.\nUse when implementing TwinMind integrations, refactoring API usage,\nor establishing team coding standards for meeting AI integration.\nTrigger with phrases like \"twinmind SDK patterns\", \"twinmind best practices\",\n\"twinmind code patterns\", \"idiomatic twinmind\".\n","Read, Write, Edit","main","90b50ed0778745a80fd5bfb13b1843d45b9e82f7","tests\u002Fext_conformance\u002Fartifacts\u002Fplugins-community\u002Fplugins\u002Fsaas-packs\u002Ftwinmind-pack\u002Fskills\u002Ftwinmind-sdk-patterns",233,"https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust","https:\u002F\u002Fgithub.com\u002FDicklesworthstone","https:\u002F\u002Fwww.jeffreyemanuel.com\u002F","Building in NY","2026-11-15 01:54:15",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add Dicklesworthstone\u002Fpi_agent_rust --skill twinmind-sdk-patterns",{"tool":71,"command":72},"bunx","bunx skills add Dicklesworthstone\u002Fpi_agent_rust --skill twinmind-sdk-patterns",{"tool":74,"command":75},"pnpm","pnpm dlx skills add Dicklesworthstone\u002Fpi_agent_rust --skill twinmind-sdk-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Fplugins-community\u002Fplugins\u002Fsaas-packs\u002Ftwinmind-pack\u002Fskills\u002Ftwinmind-sdk-patterns\u002FSKILL.md",true,[],[80,114,150,173,199,225],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":84,"licenseFileUrl":85,"sourceHtmlUrl":86,"categories":87,"keywords":93,"publishedAt":113},"01M6FCR7G5A005P364Z6ZWCJDP","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fcreative-design\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fcreative-design\u002Ftheme-factory\u002FSKILL.md",[88],{"categoryNo":89,"categoryName":90,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",[94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112],"theme factory","factory","theme","docs","toolkit","generate","artifacts","SET","fly","slides","landing","html","styling","artifact","pages","themes","with","you","fonts","2026-11-11 15:11:14",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":84,"licenseFileUrl":118,"sourceHtmlUrl":119,"categories":120,"keywords":124,"publishedAt":47},"01M6FEGPPK0ZTKCCM0R3E3KS33","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[121],{"categoryNo":122,"categoryName":123,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000009","前端开发",[125,126,100,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,105,143,144,145,146,147,148,149],"web artifacts builder","web","artifacts builder","builder","frontend","css","components","react","component","routing","state management","state","shadcn","file","ui","Tools","Tailwind","use","single-file","simple","ui components","multi","for","jsx","suite",{"skillNo":151,"name":152,"nameZh":6,"description":153,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":84,"licenseFileUrl":154,"sourceHtmlUrl":155,"categories":156,"keywords":161,"publishedAt":47},"01M6FEE9VTK1W4GY21AKREJXRG","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[157,160],{"categoryNo":158,"categoryName":159,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":122,"categoryName":123,"taxonomyType":91,"taxonomyTypeDesc":92},[162,163,164,129,165,166,126,167,98,168,139,169,170,171,172,110,147],"testing","webapp testing","webapp","screenshots","playwright","debugging","browser","logs","applications","behavior","local",{"skillNo":174,"name":175,"nameZh":6,"description":176,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":177,"sourceHtmlUrl":178,"categories":179,"keywords":180,"publishedAt":47},"01M6FE20F7ZTQBFWKF4MPJ2SBX","neuropixels-analysis","Neuropixels neural recording analysis. Load SpikeGLX\u002FOpenEphys data, preprocess, motion correction, Kilosort4 spike sorting, quality metrics, Allen\u002FIBL curation, AI-assisted visual analysis, for Neuropixels 1.0\u002F2.0 extracellular electrophysiology. Use when working with neural recordings, spike sorting, extracellular electrophysiology, or when the user mentions Neuropixels, SpikeGLX, Open Ephys, Kilosort, quality metrics, or unit curation.","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fneuropixels-analysis\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fscientific\u002Fneuropixels-analysis\u002FSKILL.md",[],[181,182,183,184,185,186,187,188,142,189,190,191,192,193,194,195,110,196,197,198,147,28],"analysis","neuropixels analysis","spike","metrics","data","open","quality","user","recordings","Neural","motion","visual","quality metrics","unit","sorting","curation","recording","load",{"skillNo":200,"name":201,"nameZh":6,"description":202,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":84,"licenseFileUrl":203,"sourceHtmlUrl":204,"categories":205,"keywords":209,"publishedAt":47},"01M6FDP0PDK6F1GGX395C7625Z","skill-creator","Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fskill-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fskill-creator\u002FSKILL.md",[206],{"categoryNo":207,"categoryName":208,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000023","Skill与智能体开发",[210,211,212,213,214,215,216,217,40,218,219,220,221,222,110,147,223,28,224],"skill creator","creator","workflows","create","update","capabilities","knowledge","tool","specialized","guide","new skill","existing skill","users","Existing","new",{"skillNo":226,"name":227,"nameZh":6,"description":228,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":229,"sourceHtmlUrl":230,"categories":231,"keywords":233,"publishedAt":47},"01M6FDM8Y7VK7NYG9SM7QPA3PW","notebooklm","Use this skill to query your Google NotebookLM notebooks directly from Claude Code for source-grounded, citation-backed answers from Gemini. Browser automation, library management, persistent auth. Drastically reduced hallucinations through document-only responses.","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fnotebooklm\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FDicklesworthstone\u002Fpi_agent_rust\u002Fblob\u002Fmain\u002Ftests\u002Fext_conformance\u002Fartifacts\u002Ftemplates-davila7\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fnotebooklm\u002FSKILL.md",[232],{"categoryNo":207,"categoryName":208,"taxonomyType":91,"taxonomyTypeDesc":92},[227,234,235,236,237,238,45,168,239,240,142,241,242,243,244,147,245],"google","browser automation","gemini","automation","auth","library","management","only","document","query","Citation","source"]