Логотип Query Layer

Query Layer

ОрганізаціяПопулярне
EpicenterHQ
query-layer

Use when editing TanStack Query integration: createQuery, createMutation, resultQueryOptions, resultMutationOptions, defineQuery, defineMutation, defineKeys, shared cache identity, mutation lifecycle, or service-to-TanStack adapters.

Огляд

ВидавецьEpicenterHQ
Репозиторійepicenter
Назва навичкиquery-layer
Зірки
4.8K
Форки
386
Файли в пакеті
3
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 3

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: EpicenterHQ. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Query Layer у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/query-layer
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/EpicenterHQ/epicenter.git /tmp/epicenter
mkdir -p .claude/skills
cp -r /tmp/epicenter/.agents/skills/query-layer .claude/skills/query-layer
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Query Layer в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Query Layer, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Query Layer не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Query Layer Patterns

Reference Repositories

Upstream Grounding

When TanStack Query behavior, Svelte adapter types, cache invalidation semantics, optimistic updates, or mutation lifecycle callbacks affect correctness, ask DeepWiki a narrow question against TanStack/query before relying on memory. Use it to orient, then verify decisive details against local installed types, source, or official docs before changing code.

Skip DeepWiki for stable basics and repo-local patterns already documented below.

The query layer is the reactive bridge between UI components and the service layer. It wraps service functions or observable operations with caching, mutation lifecycle state, invalidation, and direct imperative access using TanStack Query and Wellcrafted factories.

Related Skills: See services-layer for the service layer these queries consume. See svelte for Svelte-specific TanStack Query patterns. See error-handling for toast/report patterns after Results reach the UI boundary.

Core Architecture

┌─────────────┐     ┌─────────────┐     ┌──────────────┐
│     UI      │ --> │    Query    │ --> │   Services   │
│ Components  │     │    Layer    │     │  (UI-free)   │
└─────────────┘     └─────────────┘     └──────────────┘
      ↑                    │
      └────────────────────┘
         Reactive Updates

Query Layer Responsibilities:

  • Call services with injected settings/configuration
  • Preserve typed service and operation errors unless the adapter introduces a new local failure
  • Manage TanStack Query cache for optimistic updates
  • Provide hook-ready .options for shared definitions and explicit imperative APIs where they exist
  • Own shared cache identity through exported *Keys maps

Wellcrafted Query API Shape

ScopeQueryMutation
Hook-local Result adapterresultQueryOptions(input)resultMutationOptions(input)
Reusable definitiondefineQuery(input)defineMutation(input)

Use resultQueryOptions and resultMutationOptions at one hook call site when a Result-returning function needs to enter TanStack's data/error channels and no imperative API or shared query identity is needed.

The adapters unwrap internally (Ok.data is returned, Err.error is thrown). Pass the Result-returning function; do not unwrap first.

Use defineQuery and defineMutation in shared $lib/queries modules.

Queries expose .options, .fetch(), and .ensure(). They are not callable.

Mutations expose .options and are callable. They do not expose .execute().

Canonical Whispering Query Module Shape

The Whispering query modules these examples came from were removed when Whispering became a standalone file-folder app with no query layer. The shape is still the convention for a $lib/queries module in an app that has one.

For Whispering-style $lib/queries modules, keep source-of-truth declarations close to the work they describe. Factories receive the session-owned runtime explicitly:

typescript
export const audioKeys = defineKeys({
	availability: (id: string, blobId: string, uploadedAt: string | null) =>
		['audio', 'availability', id, blobId, uploadedAt] as const,
});

export function createAudioQueries({ defineQuery }: WhisperingQueryRuntime) {
	return {
		availability: (recording: Accessor<Recording>) =>
			defineQuery({
				queryKey: audioKeys.availability(
					recording().id,
					recording().audioBlobId,
					recording().uploadedAt,
				),
				queryFn: () => getRecordingAudioAvailability(recording()),
			}),
	};
}

Rules:

  • Export *Keys = defineKeys({ ... }) beside the adapter or state module that owns the work.
  • Static keys do not need as const; key factories use as const when literal positions matter.
  • Keep keys in the owning module unless another layer needs the same fallback identity.
  • Inline small single-use input objects. Name an input type only when it is reused, exported, large enough to obscure the function, or carries domain meaning. Put named input types immediately before the adapter namespace that uses them.
  • Keep adapter-local defineErrors namespaces local unless another module needs to name that exact union.

Adapter Boundary: Queries vs Operations

Use $lib/queries as the shared TanStack observation surface. It may wrap a direct service/state call, or a $lib/operations entry point when UI needs shared mutation identity: multiple consumers, cache invalidation, optimistic updates, useIsMutating, or a named mutation key over that operation.

Keep orchestration in $lib/operations: delivery, sounds, analytics, clipboard writes, and multi-step workflows. A reusable operation returns its outcome; a terminal interaction controller may also report it. Do not promote a one-component operation into $lib/queries merely to observe local pending state. The svelte skill owns the component's choice between local createMutation and direct await.

Dependency Direction

txt
UI -> operations/* -> services/* + state/* + $lib/tauri
UI -> queries/*    -> services/* or operations/*, plus narrow state reads/writes for observed lifecycle

Query modules receive the session-owned query runtime and import services, state, or operations. They do not import sibling query modules just to sequence work; cross-adapter coordination belongs in operations.

Error Flow

In Whispering, service and operation errors are already tagged errors. Query adapters pass them through. The UI/report boundary decides how to present them.

txt
Service / Operation       ->  Query Adapter     ->  UI / Report
TaggedError<'Name'>           same error            report.error({ cause: error })

Only define a query-local error when the adapter itself discovers a failure that no lower layer can own, such as a missing recording lookup before calling an operation.

Reactive And Imperative Use

Query-layer adapters provide reactive hook usage and explicit imperative usage.

Reactive Interface: .options

Shared query adapters expose .options as a static object. Svelte hooks read it inside an accessor:

svelte
<script lang="ts">
	import { createQuery, createMutation } from '@tanstack/svelte-query';
	import { getWhisperingQueries } from '$lib/whispering/context';

	const queries = getWhisperingQueries();
	const availability = createQuery(() =>
		queries.audio.availability(() => recording).options,
	);

	const transcribeRecording = createMutation(
		() => queries.transcription.transcribeRecording.options,
	);
</script>

{#if availability.isPending}
	<Spinner />
{:else if availability.error !== null}
	<Error message={availability.error.message} />
{:else}
	<AvailabilityBadge value={availability.data} />
{/if}

Imperative Interface: Queries Choose Cache Policy, Mutations Are Callable

Use outside component context, or whenever the caller needs a direct Result:

typescript
// In an event handler or workflow
async function handleDownload(recording: Recording) {
	const { error } = await queries.download.downloadRecording(recording);
	if (error !== null) {
		report.error({ cause: error });
		return;
	}
	report.success({ title: 'Recording downloaded' });
}

// In a sequential workflow
async function stopAndTranscribe(toastId: string) {
	const { data: url, error: playbackUrlError } =
		await queries.audio.availability(() => recording).fetch();

	if (playbackUrlError !== null) {
		report.error({ cause: playbackUrlError });
		return;
	}

	// Continue with transcription...
}

Use .fetch() when TanStack should evaluate the query's normal staleness policy: fresh cached data may still be returned without a request. Use .ensure() when any cached data is acceptable and fetching is only required when the cache is empty.

When to Use Each

Adapter surfacePattern
Shared reactive querycreateQuery(() => queries.thing.options)
Shared reactive mutationcreateMutation(() => queries.thing.options)
Imperative query readqueries.thing(...).fetch() or queries.thing(...).ensure()
Imperative mutationqueries.thing(input)

For local component operation placement and lifecycle decisions, use the svelte skill's mutation guidance.

Key Rules

  1. Use defineKeys for shared cache identity - Export the key map beside the owner
  2. Use .options (no parentheses) - It's a static object, wrap in accessor for Svelte
  3. Do not translate tagged errors by default - Pass service/operation errors through to the report boundary
  4. Services receive explicit app inputs - The consuming edge injects settings and device config
  5. Keep component lifecycle policy in svelte - This skill owns shared adapter shape and cache behavior
  6. Update cache deliberately - Use optimistic writes only when the cache owner and rollback path are explicit; otherwise invalidate or refetch

References

Load these on demand based on what you're working on:

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Query Layer?

Use when editing TanStack Query integration: createQuery, createMutation, resultQueryOptions, resultMutationOptions, defineQuery, defineMutation, defineKeys, shared cache identity, mutation lifecycle, or service-to-TanStack adapters.

Навіщо використовувати Query Layer у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Query Layer — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Query Layer у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/EpicenterHQ/epicenter/tree/main/.agents/skills/query-layer. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Query Layer?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Query Layer?

Зі скількома забажаєте. У TypingMind ви можете використовувати Query Layer із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Query Layer?

На GitHub цю навичку публікує EpicenterHQ. Умови ліцензування дивіться в репозиторії. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇