zeitlich 0.2.49 → 0.2.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -23
- package/dist/adapters/sandbox/daytona/index.cjs.map +1 -1
- package/dist/adapters/sandbox/daytona/index.d.cts +3 -3
- package/dist/adapters/sandbox/daytona/index.d.ts +3 -3
- package/dist/adapters/sandbox/daytona/index.js.map +1 -1
- package/dist/adapters/sandbox/daytona/workflow.d.cts +2 -2
- package/dist/adapters/sandbox/daytona/workflow.d.ts +2 -2
- package/dist/adapters/sandbox/e2b/index.cjs.map +1 -1
- package/dist/adapters/sandbox/e2b/index.d.cts +1 -1
- package/dist/adapters/sandbox/e2b/index.d.ts +1 -1
- package/dist/adapters/sandbox/e2b/index.js.map +1 -1
- package/dist/adapters/sandbox/e2b/workflow.d.cts +1 -1
- package/dist/adapters/sandbox/e2b/workflow.d.ts +1 -1
- package/dist/adapters/thread/anthropic/index.cjs +60 -55
- package/dist/adapters/thread/anthropic/index.cjs.map +1 -1
- package/dist/adapters/thread/anthropic/index.d.cts +20 -15
- package/dist/adapters/thread/anthropic/index.d.ts +20 -15
- package/dist/adapters/thread/anthropic/index.js +60 -55
- package/dist/adapters/thread/anthropic/index.js.map +1 -1
- package/dist/adapters/thread/anthropic/workflow.d.cts +7 -7
- package/dist/adapters/thread/anthropic/workflow.d.ts +7 -7
- package/dist/adapters/thread/google-genai/index.cjs +135 -66
- package/dist/adapters/thread/google-genai/index.cjs.map +1 -1
- package/dist/adapters/thread/google-genai/index.d.cts +200 -26
- package/dist/adapters/thread/google-genai/index.d.ts +200 -26
- package/dist/adapters/thread/google-genai/index.js +135 -66
- package/dist/adapters/thread/google-genai/index.js.map +1 -1
- package/dist/adapters/thread/google-genai/workflow.d.cts +8 -8
- package/dist/adapters/thread/google-genai/workflow.d.ts +8 -8
- package/dist/adapters/thread/langchain/index.cjs +67 -55
- package/dist/adapters/thread/langchain/index.cjs.map +1 -1
- package/dist/adapters/thread/langchain/index.d.cts +20 -15
- package/dist/adapters/thread/langchain/index.d.ts +20 -15
- package/dist/adapters/thread/langchain/index.js +67 -55
- package/dist/adapters/thread/langchain/index.js.map +1 -1
- package/dist/adapters/thread/langchain/workflow.d.cts +7 -7
- package/dist/adapters/thread/langchain/workflow.d.ts +7 -7
- package/dist/{cold-store-DKMAO1Dd.d.ts → cold-store-DyHodfAB.d.ts} +1 -1
- package/dist/{cold-store-CkWoNtMh.d.cts → cold-store-YOx9nmgR.d.cts} +1 -1
- package/dist/index.cjs +15050 -420
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +79 -83
- package/dist/index.d.ts +79 -83
- package/dist/index.js +15051 -417
- package/dist/index.js.map +1 -1
- package/dist/{proxy-B7CWEV-T.d.cts → proxy-2htgGQrc.d.cts} +1 -1
- package/dist/{proxy-ByFHMVRX.d.ts → proxy-CmiTP4pp.d.ts} +1 -1
- package/dist/{thread-manager-nK-WcFzM.d.ts → thread-manager-BJ5pz5Cx.d.cts} +6 -7
- package/dist/{thread-manager-7AW4rhfu.d.ts → thread-manager-BQAbrYXH.d.cts} +6 -7
- package/dist/{thread-manager-Cibe0X5m.d.cts → thread-manager-CcvltOuq.d.ts} +6 -7
- package/dist/{thread-manager-B9rtMEVn.d.cts → thread-manager-DHAbncHX.d.ts} +6 -7
- package/dist/{types-gVa5XCWD.d.ts → types-BQvXWcft.d.ts} +1 -1
- package/dist/{types-XUUFvrJ9.d.cts → types-BjdqxKYp.d.cts} +709 -709
- package/dist/{types-CJ7tCdl6.d.ts → types-D8W5TnSa.d.cts} +3 -3
- package/dist/{types-CJ7tCdl6.d.cts → types-D8W5TnSa.d.ts} +3 -3
- package/dist/{types-DO4Tkwxo.d.ts → types-DEbkLA06.d.ts} +3 -3
- package/dist/{types-DeVNWqlb.d.ts → types-DiI7mZhI.d.ts} +709 -709
- package/dist/{types-BR-k7h0e.d.cts → types-N_LTWe4b.d.cts} +3 -3
- package/dist/{types-CjY93AWZ.d.cts → types-OEN1xrFg.d.cts} +1 -1
- package/dist/{workflow-uhOIj9D-.d.ts → workflow-CcgD6EUB.d.cts} +34 -3
- package/dist/{workflow-KbGsxpfh.d.cts → workflow-DBjPOKBr.d.ts} +34 -3
- package/dist/workflow.cjs +15008 -377
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +3 -3
- package/dist/workflow.d.ts +3 -3
- package/dist/workflow.js +15009 -374
- package/dist/workflow.js.map +1 -1
- package/package.json +10 -37
- package/src/adapters/thread/anthropic/activities.test.ts +115 -0
- package/src/adapters/thread/anthropic/activities.ts +11 -19
- package/src/adapters/thread/anthropic/fork-transform.test.ts +17 -11
- package/src/adapters/thread/anthropic/model-invoker.test.ts +54 -3
- package/src/adapters/thread/anthropic/model-invoker.ts +11 -1
- package/src/adapters/thread/anthropic/thread-manager.test.ts +2 -2
- package/src/adapters/thread/anthropic/thread-manager.ts +3 -4
- package/src/adapters/thread/google-genai/activities.test.ts +162 -0
- package/src/adapters/thread/google-genai/activities.ts +38 -15
- package/src/adapters/thread/google-genai/fork-transform.test.ts +17 -11
- package/src/adapters/thread/google-genai/model-invoker.test.ts +386 -0
- package/src/adapters/thread/google-genai/model-invoker.ts +118 -23
- package/src/adapters/thread/google-genai/thread-manager.test.ts +2 -2
- package/src/adapters/thread/google-genai/thread-manager.ts +3 -4
- package/src/adapters/thread/langchain/activities.test.ts +88 -0
- package/src/adapters/thread/langchain/activities.ts +15 -12
- package/src/adapters/thread/langchain/fork-transform.test.ts +17 -11
- package/src/adapters/thread/langchain/model-invoker.test.ts +74 -0
- package/src/adapters/thread/langchain/model-invoker.ts +16 -3
- package/src/adapters/thread/langchain/thread-manager.test.ts +2 -2
- package/src/adapters/thread/langchain/thread-manager.ts +3 -4
- package/src/index.ts +2 -2
- package/src/lib/sandbox/capability-types.test.ts +2 -2
- package/src/lib/sandbox/manager.ts +2 -6
- package/src/lib/sandbox/sandbox.test.ts +1 -1
- package/src/lib/sandbox/types.ts +2 -2
- package/src/lib/session/session.integration.test.ts +92 -0
- package/src/lib/session/session.ts +23 -11
- package/src/lib/thread/keys.test.ts +9 -9
- package/src/lib/thread/keys.ts +1 -1
- package/src/lib/thread/manager.test.ts +24 -14
- package/src/lib/thread/manager.ts +19 -23
- package/src/lib/thread/snapshot.test.ts +51 -43
- package/src/lib/thread/snapshot.ts +54 -32
- package/src/lib/thread/test-utils.ts +106 -59
- package/src/lib/thread/tiered.test.ts +1 -1
- package/src/lib/thread/types.ts +2 -2
- package/src/lib/tool-router/router.integration.test.ts +44 -0
- package/src/lib/tool-router/router.ts +140 -32
- package/src/lib/workflow.ts +49 -0
- package/src/{adapters/sandbox/inmemory/proxy.ts → test-utils/in-memory-sandbox-proxy.ts} +5 -16
- package/src/{adapters/sandbox/inmemory/index.ts → test-utils/in-memory-sandbox.ts} +11 -3
- package/src/tools/bash/bash.test.ts +1 -1
- package/src/tools/edit/handler.test.ts +1 -1
- package/tsup.config.ts +2 -4
- package/dist/activities-7OcT_vdR.d.cts +0 -162
- package/dist/activities-zG_FBoY2.d.ts +0 -162
- package/dist/adapters/sandbox/inmemory/index.cjs +0 -214
- package/dist/adapters/sandbox/inmemory/index.cjs.map +0 -1
- package/dist/adapters/sandbox/inmemory/index.d.cts +0 -40
- package/dist/adapters/sandbox/inmemory/index.d.ts +0 -40
- package/dist/adapters/sandbox/inmemory/index.js +0 -211
- package/dist/adapters/sandbox/inmemory/index.js.map +0 -1
- package/dist/adapters/sandbox/inmemory/workflow.cjs +0 -36
- package/dist/adapters/sandbox/inmemory/workflow.cjs.map +0 -1
- package/dist/adapters/sandbox/inmemory/workflow.d.cts +0 -27
- package/dist/adapters/sandbox/inmemory/workflow.d.ts +0 -27
- package/dist/adapters/sandbox/inmemory/workflow.js +0 -34
- package/dist/adapters/sandbox/inmemory/workflow.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/adapters/thread/google-genai/adapter-id.ts","../../../../src/lib/thread/keys.ts","../../../../src/lib/thread/manager.ts","../../../../src/lib/thread/snapshot.ts","../../../../src/lib/thread/tiered.ts","../../../../src/adapters/thread/google-genai/thread-manager.ts","../../../../src/lib/activity.ts","../../../../src/adapters/thread/google-genai/model-invoker.ts","../../../../src/adapters/thread/google-genai/activities.ts"],"names":["invokeGoogleGenAIModel"],"mappings":";;;AAYO,IAAM,UAAA,GAAa;;;ACsBnB,IAAM,kBAAA,GAAqB,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA;AAc1C,SAAS,gBAAA,CACd,WACA,QAAA,EACQ;AACR,EAAA,OAAO,CAAA,EAAG,SAAS,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AACxC;AAeO,SAAS,gBAAA,CACd,WACA,QAAA,EACQ;AACR,EAAA,OAAO,CAAA,EAAG,SAAS,CAAA,aAAA,EAAgB,QAAQ,CAAA,CAAA;AAC7C;AAeO,SAAS,iBAAA,CACd,WACA,QAAA,EACQ;AACR,EAAA,OAAO,CAAA,EAAG,SAAS,CAAA,cAAA,EAAiB,QAAQ,CAAA,CAAA;AAC9C;AAkBO,SAAS,iBAAA,CAAkB,UAAkB,OAAA,EAAyB;AAC3E,EAAA,OAAO,CAAA,MAAA,EAAS,OAAO,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AAC5C;;;AC9FA,IAAM,wBAAA,GAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAgB1B,SAAS,oBACd,MAAA,EACsB;AACtB,EAAA,MAAM;AAAA,IACJ,KAAA;AAAA,IACA,QAAA;AAAA,IACA,GAAA,GAAM,UAAA;AAAA,IACN,SAAA,GAAY,CAAC,CAAA,KAAiB,IAAA,CAAK,UAAU,CAAC,CAAA;AAAA,IAC9C,WAAA,GAAc,CAAC,GAAA,KAAmB,IAAA,CAAK,MAAM,GAAG,CAAA;AAAA,IAChD,IAAA;AAAA,IACA,UAAA,GAAa;AAAA,GACf,GAAI,MAAA;AACJ,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AE,WAAA,EAAY,GAAI,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA;AACxE,IAAA,OAAO,MAAA,CAAO,WAAA;AAAA,MACZ,OAAO,OAAA,CAAQ,SAAS,EAAE,GAAA,CAAI,CAAC,CAAC,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA,EAAG,MAAM,CAAA,EAAG,GAAA,CAAI,CAAC,CAAC,CAAA,CAAA,EAAI,CAAC,CAAC;AAAA,KACrE;AAAA,EACF;AAEA,EAAA,MAAM,WAAA,GAAc,CAClB,KAAA,EACA,MAAA,KAEA,6BAAA,CAA8B;AAAA,IAC5B,KAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,OAAO,MAAA,CAAO;AAAA,GACf,CAAA;AAEH,EAAA,MAAM,OAAA,GACJ,MAAA,CAAO,KAAA,IAAS,MAAA,CAAO,MAAA,GACnB,WAAA,CAAY,MAAA,CAAO,KAAA,EAAO,MAAA,CAAO,MAAM,CAAA,IACrC,MAAM;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF,CAAA,CAAA;AAEN,EAAA,OAAO;AAAA,IACL,gBAAA;AAAA,IACA,OAAA;AAAA,IACA,kBAAA,EAAoB,WAAA;AAAA,IACpB,WAAA,EAAa,CAAC,OAAA,KAAY;AAAA,GAC5B;AACF","file":"index.js","sourcesContent":["/**\n * Public adapter identity for the Google GenAI thread adapter.\n *\n * This value is wire format — it appears as the prefix for Temporal\n * activity names (e.g. `googleGenAICodingAgentInitializeThread`) and\n * must never change, since renaming it would orphan existing persisted\n * threads and break in-flight workflows.\n *\n * Re-exported from `zeitlich/adapters/thread/google-genai` so downstream\n * consumers can use the exact same literal the adapter uses internally,\n * typed as the narrow string literal `\"googleGenAI\"`.\n */\nexport const ADAPTER_ID = \"googleGenAI\" as const;\n\n/** Narrow string-literal type for {@link ADAPTER_ID}. */\nexport type AdapterId = typeof ADAPTER_ID;\n","/**\n * Public helpers for zeitlich's Redis thread storage layout.\n *\n * These are the exact string-building primitives zeitlich's internal thread\n * manager uses for every adapter. Downstream consumers that need to read a\n * persisted thread (for evaluation, observability, admin tooling, etc.)\n * should use these helpers rather than reconstructing the key layout by\n * hand — the layout is versioned with this module, so upgrading zeitlich\n * keeps the consumer in sync.\n *\n * The layout is adapter-agnostic: every thread adapter stores messages the\n * same way.\n *\n * @example\n * ```typescript\n * import {\n * getThreadListKey,\n * getThreadMetaKey,\n * THREAD_TTL_SECONDS,\n * } from 'zeitlich';\n *\n * const listKey = getThreadListKey('messages', threadId);\n * const metaKey = getThreadMetaKey('messages', threadId);\n * const ttl = await redis.ttl(listKey); // <= THREAD_TTL_SECONDS\n * ```\n */\n\n/**\n * TTL (in seconds) applied to every thread list and thread meta key that\n * zeitlich's {@link createThreadManager} writes. Exposed so downstream\n * consumers can size their Redis retention / query windows to match.\n *\n * Current value: 90 days.\n */\nexport const THREAD_TTL_SECONDS = 60 * 60 * 24 * 90;\n\n/**\n * Build the Redis list key that holds a thread's serialized messages.\n *\n * Mirrors the exact key used internally by zeitlich's thread manager,\n * so a consumer calling `redis.lrange(getThreadListKey(key, id), 0, -1)`\n * sees the same data the writer wrote.\n *\n * @param threadKey - Thread key (defaults to `\"messages\"` inside the\n * thread manager, but downstream adapters may pass\n * their own value).\n * @param threadId - Thread id as provided to the thread manager.\n */\nexport function getThreadListKey(\n threadKey: string,\n threadId: string\n): string {\n return `${threadKey}:thread:${threadId}`;\n}\n\n/**\n * Build the Redis key that stores a thread's existence marker / metadata.\n *\n * Zeitlich treats the presence of this key as \"thread has been\n * initialized\"; append/load/fork/truncate operations fail when it is\n * missing. Consumers can use it as a cheap existence probe without\n * scanning the message list.\n *\n * @param threadKey - Thread key (defaults to `\"messages\"` inside the\n * thread manager, but downstream adapters may pass\n * their own value).\n * @param threadId - Thread id as provided to the thread manager.\n */\nexport function getThreadMetaKey(\n threadKey: string,\n threadId: string\n): string {\n return `${threadKey}:meta:thread:${threadId}`;\n}\n\n/**\n * Build the Redis key that stores a thread's persisted state slice\n * (tasks + custom state) written by zeitlich's session loop on every\n * exit path.\n *\n * Consumers can read this key with `redis.get(getThreadStateKey(key, id))`\n * and `JSON.parse` the result into a {@link PersistedThreadState}.\n *\n * @param threadKey - Thread key (defaults to `\"messages\"` inside the\n * thread manager, but downstream adapters may pass\n * their own value).\n * @param threadId - Thread id as provided to the thread manager.\n */\nexport function getThreadStateKey(\n threadKey: string,\n threadId: string\n): string {\n return `${threadKey}:state:thread:${threadId}`;\n}\n\n/**\n * Build the Redis key that guards an idempotent append against a\n * duplicate write of the message (or message batch) identified by\n * `dedupId`. Zeitlich's thread manager writes one of these per\n * single-message append (and one per batch for multi-message appends),\n * keyed by the message id returned by the configured `idOf`.\n *\n * Note: the key layout intentionally does **not** include the\n * `threadKey` prefix — the dedup namespace is shared across thread\n * keys for a given `threadId`, mirroring the original internal\n * implementation.\n *\n * @param threadId - Thread id as provided to the thread manager.\n * @param dedupId - Joined message ids (single message id for the\n * common single-append case).\n */\nexport function getThreadDedupKey(threadId: string, dedupId: string): string {\n return `dedup:${dedupId}:thread:${threadId}`;\n}\n","import type { PersistedThreadState } from \"../state/types\";\nimport type { ThreadManagerConfig, BaseThreadManager } from \"./types\";\nimport {\n THREAD_TTL_SECONDS,\n getThreadListKey,\n getThreadMetaKey,\n getThreadStateKey,\n getThreadDedupKey,\n} from \"./keys\";\n\n/**\n * Lua script for atomic idempotent append.\n * Checks a dedup key; if it exists the message was already appended and we\n * return 0. Otherwise appends all messages to the list, sets TTL on both\n * the list and the dedup key, and returns 1.\n *\n * KEYS[1] = dedup key, KEYS[2] = list key\n * ARGV[1] = TTL seconds, ARGV[2..N] = serialised messages\n */\nconst APPEND_IDEMPOTENT_SCRIPT = `\nif redis.call('EXISTS', KEYS[1]) == 1 then\n return 0\nend\nfor i = 2, #ARGV do\n redis.call('RPUSH', KEYS[2], ARGV[i])\nend\nredis.call('EXPIRE', KEYS[2], tonumber(ARGV[1]))\nredis.call('SET', KEYS[1], '1', 'EX', tonumber(ARGV[1]))\nreturn 1\n`;\n\n/**\n * Creates a generic thread manager for handling conversation state in Redis.\n * Framework-agnostic — works with any serializable message type.\n */\nexport function createThreadManager<T>(\n config: ThreadManagerConfig<T>\n): BaseThreadManager<T> {\n const {\n redis,\n threadId,\n key = \"messages\",\n serialize = (m: T): string => JSON.stringify(m),\n deserialize = (raw: string): T => JSON.parse(raw) as T,\n idOf,\n ttlSeconds = THREAD_TTL_SECONDS,\n } = config;\n const redisKey = getThreadListKey(key, threadId);\n const metaKey = getThreadMetaKey(key, threadId);\n const stateKey = getThreadStateKey(key, threadId);\n const dedupKey = (id: string): string => getThreadDedupKey(threadId, id);\n\n async function assertThreadExists(): Promise<void> {\n const exists = await redis.exists(metaKey);\n if (!exists) {\n throw new Error(`Thread \"${threadId}\" (key: ${key}) does not exist`);\n }\n }\n\n return {\n async initialize(): Promise<void> {\n await redis.del(redisKey);\n await redis.set(metaKey, \"1\", \"EX\", ttlSeconds);\n },\n\n async load(): Promise<T[]> {\n await assertThreadExists();\n const data = await redis.lrange(redisKey, 0, -1);\n return data.map(deserialize);\n },\n\n async append(messages: T[]): Promise<void> {\n if (messages.length === 0) return;\n await assertThreadExists();\n\n if (idOf) {\n const dedupId = messages.map(idOf).join(\":\");\n await redis.eval(\n APPEND_IDEMPOTENT_SCRIPT,\n 2,\n dedupKey(dedupId),\n redisKey,\n String(ttlSeconds),\n ...messages.map(serialize)\n );\n } else {\n await redis.rpush(redisKey, ...messages.map(serialize));\n await redis.expire(redisKey, ttlSeconds);\n }\n },\n\n async fork(newThreadId: string): Promise<BaseThreadManager<T>> {\n await assertThreadExists();\n const data = await redis.lrange(redisKey, 0, -1);\n const stateRaw = await redis.get(stateKey);\n const forked = createThreadManager({\n ...config,\n threadId: newThreadId,\n });\n await forked.initialize();\n if (data.length > 0) {\n const newKey = getThreadListKey(key, newThreadId);\n await redis.rpush(newKey, ...data);\n await redis.expire(newKey, ttlSeconds);\n }\n if (stateRaw != null) {\n const newStateKey = getThreadStateKey(key, newThreadId);\n await redis.set(newStateKey, stateRaw, \"EX\", ttlSeconds);\n }\n return forked;\n },\n\n async replaceAll(messages: T[]): Promise<void> {\n await assertThreadExists();\n if (!idOf) {\n throw new Error(\n \"replaceAll requires the thread manager to be configured with `idOf`\"\n );\n }\n const existing = await redis.lrange(redisKey, 0, -1);\n const existingIds = existing\n .map((raw) => idOf(deserialize(raw)))\n .filter((id): id is string => typeof id === \"string\");\n await redis.del(redisKey);\n if (existingIds.length > 0) {\n await redis.del(...existingIds.map(dedupKey));\n }\n if (messages.length > 0) {\n await redis.rpush(redisKey, ...messages.map(serialize));\n await redis.expire(redisKey, ttlSeconds);\n }\n await redis.expire(metaKey, ttlSeconds);\n },\n\n async delete(): Promise<void> {\n await redis.del(redisKey, metaKey, stateKey);\n },\n\n async loadState(): Promise<PersistedThreadState | null> {\n const raw = await redis.get(stateKey);\n if (raw == null) return null;\n return JSON.parse(raw) as PersistedThreadState;\n },\n\n async saveState(state: PersistedThreadState): Promise<void> {\n await assertThreadExists();\n await redis.set(stateKey, JSON.stringify(state), \"EX\", ttlSeconds);\n },\n\n async deleteState(): Promise<void> {\n await redis.del(stateKey);\n },\n\n async length(): Promise<number> {\n await assertThreadExists();\n return redis.llen(redisKey);\n },\n\n async truncateFromId(messageId: string): Promise<void> {\n await assertThreadExists();\n if (!idOf) {\n throw new Error(\n \"truncateFromId requires the thread manager to be configured with `idOf`\"\n );\n }\n const data = await redis.lrange(redisKey, 0, -1);\n let idx = -1;\n const removedIds: string[] = [];\n for (let i = 0; i < data.length; i++) {\n const raw = data[i];\n if (raw === undefined) continue;\n const id = idOf(deserialize(raw));\n if (idx === -1 && id === messageId) idx = i;\n if (idx !== -1) removedIds.push(id);\n }\n if (idx === -1) return;\n if (idx === 0) {\n await redis.del(redisKey);\n await redis.expire(metaKey, ttlSeconds);\n } else {\n await redis.ltrim(redisKey, 0, idx - 1);\n await redis.expire(redisKey, ttlSeconds);\n }\n // Clear dedup markers for the removed messages so that a rewind\n // retry which reuses the same ids (e.g. the same assistantId) can\n // re-append without the idempotent-append Lua script treating it\n // as a duplicate.\n if (removedIds.length > 0) {\n await redis.del(...removedIds.map(dedupKey));\n }\n },\n };\n}\n","/**\n * Pure Redis I/O helpers for moving a thread between the hot tier\n * (Redis lists + meta + state + dedup markers) and the cold tier\n * (a single {@link ThreadSnapshot} blob in a {@link ColdThreadStore}).\n *\n * These helpers know nothing about S3 or the adapter-specific message\n * envelope — they operate on the raw Redis representation. The\n * tiered thread manager in `tiered.ts` is the only consumer.\n */\n\nimport type Redis from \"ioredis\";\nimport type { PersistedThreadState } from \"../state/types\";\nimport type { ThreadSnapshot } from \"./cold-store\";\nimport {\n THREAD_TTL_SECONDS,\n getThreadDedupKey,\n getThreadListKey,\n getThreadMetaKey,\n getThreadStateKey,\n} from \"./keys\";\n\n/** Inputs shared by every snapshot operation. */\ninterface SnapshotCommon {\n redis: Redis;\n threadKey: string;\n threadId: string;\n}\n\n/** Configuration for {@link encodeSnapshot}. */\nexport interface EncodeSnapshotConfig extends SnapshotCommon {\n /**\n * Extract a dedup id from each raw-serialized message currently in\n * the thread's Redis list. When omitted, the resulting snapshot has\n * an empty `dedupIds` array — idempotency guarantees are best-effort\n * once a thread crosses the hot/cold boundary.\n */\n idOf?: (raw: string) => string;\n}\n\n/**\n * Build a {@link ThreadSnapshot} from the current hot-tier state.\n *\n * Returns `null` when no thread exists in the hot tier (the meta key\n * is absent) — callers should treat that as \"nothing to flush\".\n */\nexport async function encodeSnapshot(\n config: EncodeSnapshotConfig\n): Promise<ThreadSnapshot | null> {\n const { redis, threadKey, threadId, idOf } = config;\n const metaKey = getThreadMetaKey(threadKey, threadId);\n if ((await redis.exists(metaKey)) === 0) {\n return null;\n }\n const listKey = getThreadListKey(threadKey, threadId);\n const stateKey = getThreadStateKey(threadKey, threadId);\n const messages = await redis.lrange(listKey, 0, -1);\n const stateRaw = await redis.get(stateKey);\n const state =\n stateRaw == null ? null : (JSON.parse(stateRaw) as PersistedThreadState);\n const dedupIds = idOf ? messages.map(idOf) : [];\n return { v: 1, messages, state, dedupIds };\n}\n\n/** Configuration for {@link applySnapshot}. */\nexport interface ApplySnapshotConfig extends SnapshotCommon {\n snapshot: ThreadSnapshot;\n /** TTL applied to every Redis key. Defaults to {@link THREAD_TTL_SECONDS}. */\n ttlSeconds?: number;\n}\n\n/**\n * Restore a {@link ThreadSnapshot} into the hot tier.\n *\n * Idempotent — if the meta key already exists the thread is already\n * hot and this is a no-op. The meta key is written **last** so a\n * crash mid-restore leaves the thread cold (`load` / `append` will\n * see \"thread does not exist\") and the next session's hydrate retries\n * cleanly.\n */\nexport async function applySnapshot(\n config: ApplySnapshotConfig\n): Promise<void> {\n const {\n redis,\n threadKey,\n threadId,\n snapshot,\n ttlSeconds = THREAD_TTL_SECONDS,\n } = config;\n const metaKey = getThreadMetaKey(threadKey, threadId);\n if ((await redis.exists(metaKey)) === 1) {\n return;\n }\n const listKey = getThreadListKey(threadKey, threadId);\n const stateKey = getThreadStateKey(threadKey, threadId);\n\n // Clear partial residue from any prior half-restored attempt.\n // Awaited *outside* the pipeline so a DEL failure (ACL deny,\n // CROSSSLOT, …) short-circuits before any writes hit the wire —\n // pipelines are non-atomic, so a queued DEL wouldn't stop later\n // commands from accumulating data behind a missing meta marker.\n await redis.del(listKey, stateKey);\n\n // Pipeline the data writes (list/state/dedup) in one round-trip.\n // Meta is written separately, only after every queued command\n // succeeded, preserving the \"meta-last\" crash-safety invariant —\n // a partial restore must leave meta absent so the next hydrate\n // retries cleanly.\n const pipeline = redis.pipeline();\n if (snapshot.messages.length > 0) {\n pipeline.rpush(listKey, ...snapshot.messages);\n pipeline.expire(listKey, ttlSeconds);\n }\n if (snapshot.state != null) {\n pipeline.set(stateKey, JSON.stringify(snapshot.state), \"EX\", ttlSeconds);\n }\n for (const id of snapshot.dedupIds) {\n pipeline.set(getThreadDedupKey(threadId, id), \"1\", \"EX\", ttlSeconds);\n }\n const results = await pipeline.exec();\n if (results) {\n const firstErr = results.find(([err]) => err)?.[0] ?? null;\n if (firstErr) {\n // Compensate: pipelines are non-atomic, so writes queued after\n // a failing command (notably dedup SETs) may have landed. Best-\n // effort clear every key we touched so a leftover dedup marker\n // can't silently skip a future append with the same id.\n await redis\n .del(\n listKey,\n stateKey,\n ...snapshot.dedupIds.map((id) => getThreadDedupKey(threadId, id))\n )\n .catch(() => undefined);\n throw firstErr;\n }\n }\n await redis.set(metaKey, \"1\", \"EX\", ttlSeconds);\n}\n\n/** Configuration for {@link clearHotTier}. */\nexport interface ClearHotTierConfig extends SnapshotCommon {\n /** Dedup ids to delete alongside the list / meta / state keys. */\n dedupIds?: string[];\n}\n\n/**\n * Delete every Redis key the thread manager wrote for `(threadKey,\n * threadId)`. Used by the tiered manager's `flush({ deleteHot: true })`\n * to drop hot-tier memory after a successful archive write.\n */\nexport async function clearHotTier(\n config: ClearHotTierConfig\n): Promise<void> {\n const { redis, threadKey, threadId, dedupIds = [] } = config;\n const keys = [\n getThreadListKey(threadKey, threadId),\n getThreadMetaKey(threadKey, threadId),\n getThreadStateKey(threadKey, threadId),\n ...dedupIds.map((id) => getThreadDedupKey(threadId, id)),\n ];\n await redis.del(...keys);\n}\n","/**\n * Tiered thread manager: Redis hot tier + pluggable cold tier.\n *\n * Wraps {@link createThreadManager} (Redis-only) and adds two\n * session-boundary operations:\n *\n * - `hydrate()` — when the thread is cold (no meta key in Redis),\n * restore the latest {@link ThreadSnapshot} from the cold store.\n * Idempotent; no-op when the thread is already hot or when no\n * snapshot exists.\n * - `flush({ deleteHot })` — write the current Redis state out to the\n * cold store as one snapshot, then (by default) `DEL` the hot-tier\n * keys so idle threads don't sit in Redis memory.\n *\n * All other operations (`append`, `load`, `fork`, `replaceAll`,\n * `truncateFromId`, state I/O) delegate unchanged to the underlying\n * Redis manager, so adapters and tests that use the\n * `BaseThreadManager<T>` interface keep working with zero changes.\n */\n\nimport { createThreadManager } from \"./manager\";\nimport { THREAD_TTL_SECONDS } from \"./keys\";\nimport type { BaseThreadManager, ThreadManagerConfig } from \"./types\";\nimport type { ColdThreadStore } from \"./cold-store\";\nimport {\n applySnapshot,\n clearHotTier,\n encodeSnapshot,\n} from \"./snapshot\";\n\n/** Configuration for {@link createTieredThreadManager}. */\nexport interface TieredThreadManagerConfig<T> extends ThreadManagerConfig<T> {\n /**\n * Cold-tier archive. When omitted, `hydrate()` and `flush()` are\n * no-ops and the manager behaves identically to\n * {@link createThreadManager}.\n */\n coldStore?: ColdThreadStore;\n}\n\n/** Options for {@link TieredThreadManager.flush}. */\nexport interface FlushOptions {\n /**\n * Delete the hot-tier Redis keys after a successful cold-tier\n * write. Defaults to `true` when a cold store is configured —\n * Redis is just a cache and a future continue/fork will\n * re-hydrate in a single round-trip.\n *\n * Set to `false` to keep the hot tier warm (useful for tests or\n * for \"hot-after-flush\" use cases where another session is expected\n * to pick the thread up immediately).\n */\n deleteHot?: boolean;\n}\n\n/**\n * Extension of {@link BaseThreadManager} with the two cold-tier\n * lifecycle methods.\n */\nexport interface TieredThreadManager<T> extends BaseThreadManager<T> {\n /**\n * Restore the latest cold-tier snapshot into Redis when the thread\n * is cold. Idempotent — safe to call from a retried activity.\n */\n hydrate(): Promise<void>;\n /**\n * Write the current Redis state to the cold tier and (optionally)\n * drop the hot-tier keys. Idempotent — last-writer-wins on the\n * cold side.\n */\n flush(opts?: FlushOptions): Promise<void>;\n}\n\n/**\n * Build a thread manager backed by Redis (hot) and an optional\n * pluggable cold store. See module docstring for the lifecycle\n * semantics.\n */\nexport function createTieredThreadManager<T>(\n config: TieredThreadManagerConfig<T>\n): TieredThreadManager<T> {\n const {\n redis,\n threadId,\n key = \"messages\",\n coldStore,\n idOf,\n deserialize = (raw: string): T => JSON.parse(raw) as T,\n ttlSeconds = THREAD_TTL_SECONDS,\n } = config;\n\n const base = createThreadManager<T>(config);\n\n // Snapshot-time `idOf` operates on raw Redis strings — we deserialize\n // here and forward to the configured (deserialized) `idOf`.\n const rawIdOf = idOf\n ? (raw: string): string => idOf(deserialize(raw))\n : undefined;\n\n return Object.assign(base, {\n async hydrate(): Promise<void> {\n if (!coldStore) return;\n const snapshot = await coldStore.read(key, threadId);\n if (!snapshot) return;\n await applySnapshot({\n redis,\n threadKey: key,\n threadId,\n snapshot,\n ttlSeconds,\n });\n },\n\n async flush(opts?: FlushOptions): Promise<void> {\n if (!coldStore) return;\n const snapshot = await encodeSnapshot({\n redis,\n threadKey: key,\n threadId,\n ...(rawIdOf ? { idOf: rawIdOf } : {}),\n });\n if (!snapshot) return;\n await coldStore.write(key, threadId, snapshot);\n const deleteHot = opts?.deleteHot ?? true;\n if (deleteHot) {\n await clearHotTier({\n redis,\n threadKey: key,\n threadId,\n dedupIds: snapshot.dedupIds,\n });\n }\n },\n });\n}\n","import type Redis from \"ioredis\";\nimport type { Content, Part } from \"@google/genai\";\nimport { createThreadManager } from \"../../../lib/thread/manager\";\nimport type {\n ProviderThreadManager,\n ThreadManagerConfig,\n ThreadManagerHooks,\n} from \"../../../lib/thread/types\";\nimport type { GoogleGenAIToolResponse } from \"./activities\";\n\n/** SDK-native content type for Google GenAI human messages */\nexport type GoogleGenAIContent = string | Part[];\n\n/** SDK-native content type for Google GenAI system instructions */\nexport type GoogleGenAISystemContent = string | Part[];\n\n/** A Content with a unique ID for idempotent Redis storage */\nexport interface StoredContent {\n id: string;\n content: Content;\n}\n\nexport type GoogleGenAIThreadManagerHooks = ThreadManagerHooks<\n StoredContent,\n Content\n>;\n\nexport interface GoogleGenAIThreadManagerConfig {\n redis: Redis;\n threadId: string;\n /** Thread key, defaults to 'messages' */\n key?: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n /**\n * Override the default thread TTL (90 days). When pairing the\n * adapter with a durable cold tier, a shorter TTL (hours) is\n * typically more appropriate.\n */\n ttlSeconds?: number;\n}\n\n/** Prepared payload ready to send to the Google GenAI API */\nexport interface GoogleGenAIInvocationPayload {\n contents: Content[];\n systemInstruction?: Part[];\n}\n\n/** Thread manager with Google GenAI Content convenience helpers */\nexport interface GoogleGenAIThreadManager extends ProviderThreadManager<\n StoredContent,\n GoogleGenAIContent,\n GoogleGenAIToolResponse,\n GoogleGenAISystemContent\n> {\n appendModelContent(id: string, parts: Part[]): Promise<void>;\n prepareForInvocation(): Promise<GoogleGenAIInvocationPayload>;\n}\n\n/** Extract the unique id from a {@link StoredContent}. */\nexport function storedContentId(msg: StoredContent): string {\n return msg.id;\n}\n\n/** Normalise content into Part[] */\nfunction toParts(content: GoogleGenAIContent): Part[] {\n if (typeof content === \"string\") {\n return [{ text: content }];\n }\n return content;\n}\n\n/** Convert a string or object into a Record suitable for functionResponse.response */\nfunction toFunctionResponse(\n content: string | Record<string, unknown>\n): Record<string, unknown> {\n if (typeof content === \"object\") {\n return content;\n }\n return { result: content };\n}\n\n/**\n * Merge consecutive Content objects sharing the same role.\n * The Gemini API requires alternating user/model turns; without\n * merging, multiple sequential tool-result messages would violate this.\n */\nfunction mergeConsecutiveContents(contents: Content[]): Content[] {\n const merged: Content[] = [];\n for (const content of contents) {\n const last = merged[merged.length - 1];\n if (last && last.role === content.role) {\n last.parts = [...(last.parts ?? []), ...(content.parts ?? [])];\n } else {\n merged.push({ ...content, parts: [...(content.parts ?? [])] });\n }\n }\n return merged;\n}\n\n/**\n * Creates a Google GenAI-specific thread manager that stores StoredContent\n * instances in Redis and provides convenience helpers for creating and\n * appending typed Content messages.\n */\nexport function createGoogleGenAIThreadManager(\n config: GoogleGenAIThreadManagerConfig\n): GoogleGenAIThreadManager {\n const baseConfig: ThreadManagerConfig<StoredContent> = {\n redis: config.redis,\n threadId: config.threadId,\n key: config.key,\n idOf: storedContentId,\n ...(config.ttlSeconds !== undefined && { ttlSeconds: config.ttlSeconds }),\n };\n\n const base = createThreadManager(baseConfig);\n\n const helpers: Omit<GoogleGenAIThreadManager, keyof typeof base> = {\n async appendUserMessage(\n id: string,\n content: GoogleGenAIContent\n ): Promise<void> {\n await base.append([\n {\n id,\n content: { role: \"user\", parts: toParts(content) },\n },\n ]);\n },\n\n async appendSystemMessage(\n id: string,\n content: GoogleGenAISystemContent\n ): Promise<void> {\n const parts: Part[] =\n typeof content === \"string\" ? [{ text: content }] : content;\n await base.initialize();\n await base.append([\n {\n id,\n content: { role: \"system\", parts },\n },\n ]);\n },\n\n async appendModelContent(id: string, parts: Part[]): Promise<void> {\n await base.append([\n {\n id,\n content: { role: \"model\", parts },\n },\n ]);\n },\n\n async appendToolResult(\n id: string,\n toolCallId: string,\n toolName: string,\n content: GoogleGenAIToolResponse\n ): Promise<void> {\n const parts: Part[] = Array.isArray(content)\n ? (content as Part[])\n : [\n {\n functionResponse: {\n id: toolCallId,\n name: toolName,\n response: toFunctionResponse(content),\n },\n },\n ];\n\n await base.append([\n {\n id,\n content: { role: \"user\", parts },\n },\n ]);\n },\n\n async prepareForInvocation(): Promise<GoogleGenAIInvocationPayload> {\n const stored = await base.load();\n const { onPrepareMessage, onPreparedMessage } = config.hooks ?? {};\n const mapped = onPrepareMessage\n ? stored.map((msg, i) => onPrepareMessage(msg, i, stored))\n : stored;\n\n let systemInstruction: Part[] | undefined;\n const conversationContents: Content[] = [];\n\n for (const item of mapped) {\n if (item.content.role === \"system\") {\n systemInstruction = item.content.parts ?? [];\n } else {\n conversationContents.push(item.content);\n }\n }\n\n const contents = mergeConsecutiveContents(conversationContents);\n return {\n contents: onPreparedMessage\n ? contents.map((msg, i) => onPreparedMessage(msg, i, contents))\n : contents,\n ...(systemInstruction && systemInstruction.length > 0\n ? { systemInstruction }\n : {}),\n };\n },\n };\n\n const manager = Object.assign(base, helpers);\n\n const originalFork = manager.fork.bind(manager);\n manager.fork = async (\n newThreadId: string\n ): Promise<GoogleGenAIThreadManager> => {\n await originalFork(newThreadId);\n const forked = createGoogleGenAIThreadManager({\n ...config,\n threadId: newThreadId,\n });\n const { onForkPrepareThread, onForkTransform } = config.hooks ?? {};\n if (!onForkPrepareThread && !onForkTransform) {\n return forked;\n }\n let next = await forked.load();\n if (onForkPrepareThread) {\n next = await onForkPrepareThread(next);\n }\n if (onForkTransform) {\n next = next.map((msg, i) => onForkTransform(msg, i, next));\n }\n await forked.replaceAll(next);\n return forked;\n };\n\n return manager;\n}\n","import { Context } from \"@temporalio/activity\";\nimport type { WorkflowClient } from \"@temporalio/client\";\nimport type { BaseAgentState, RunAgentConfig } from \"./types\";\nimport type { JsonValue } from \"./state/types\";\nimport type {\n ActivityToolHandler,\n RouterContext,\n ToolHandlerResponse,\n} from \"./tool-router/types\";\n\n/**\n * Safely retrieve Temporal activity heartbeat and cancellation signal.\n * Returns empty object when called outside a Temporal activity (e.g. tests).\n */\nexport function getActivityContext(): {\n heartbeat?: () => void;\n signal?: AbortSignal;\n} {\n try {\n const ctx = Context.current();\n return { heartbeat: () => ctx.heartbeat(), signal: ctx.cancellationSignal };\n } catch {\n return {};\n }\n}\n\n/**\n * Query the parent workflow's state from within an activity.\n * Resolves the workflow handle from the current activity context.\n */\nexport async function queryParentWorkflowState<T>(\n client: WorkflowClient\n): Promise<T> {\n const { workflowExecution } = Context.current().info;\n\n if (!workflowExecution) {\n throw new Error(\"No workflow execution found\");\n }\n\n const handle = client.getHandle(\n workflowExecution.workflowId,\n workflowExecution.runId\n );\n return handle.query<T>(\"getAgentState\");\n}\n\n/**\n * Wraps a handler into a scope-prefixed `RunAgentActivity` by auto-fetching\n * the parent workflow's agent state before each invocation.\n *\n * Returns a `Record` with a single key `run<Scope>` so it can be spread\n * into the activities object alongside adapter activities.\n *\n * @param scope - Workflow scope used to derive the activity name.\n * `\"myAgentWorkflow\"` produces `{ runMyAgentWorkflow: fn }`.\n *\n * @example\n * ```typescript\n * import { createRunAgentActivity } from 'zeitlich';\n *\n * return {\n * ...adapter.createActivities(\"myAgentWorkflow\"),\n * ...createRunAgentActivity(client, adapter.invoker, \"myAgentWorkflow\"),\n * };\n * ```\n */\nexport function createRunAgentActivity<\n R,\n S extends BaseAgentState = BaseAgentState,\n>(\n client: WorkflowClient,\n handler: (config: RunAgentConfig & { state: S }) => Promise<R>,\n scope: string\n): Record<string, (config: RunAgentConfig) => Promise<R>> {\n const name = `run${scope.charAt(0).toUpperCase()}${scope.slice(1)}`;\n return {\n [name]: async (config: RunAgentConfig) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler({ ...config, state });\n },\n };\n}\n\n/**\n * Context injected into tool handlers created via {@link withParentWorkflowState}.\n */\nexport interface AgentStateContext<\n S extends BaseAgentState = BaseAgentState,\n> extends RouterContext {\n state: S;\n}\n\n/**\n * Wraps a tool handler into an `ActivityToolHandler` by auto-fetching the\n * parent workflow's agent state before each invocation.\n *\n * @typeParam S - Custom agent state type (defaults to `BaseAgentState`)\n *\n * @example\n * ```typescript\n * import { withParentWorkflowState, type AgentStateContext } from 'zeitlich';\n *\n * // With custom state:\n * interface MyState extends BaseAgentState { customField: string }\n * const myHandler = withParentWorkflowState<MyArgs, MyResult, MyState>(\n * client,\n * async (args, ctx) => {\n * console.log(ctx.state.customField);\n * return { toolResponse: 'done', data: null };\n * },\n * );\n * ```\n */\nexport function withParentWorkflowState<\n TArgs,\n TResult,\n S extends BaseAgentState = BaseAgentState,\n TToolResponse = JsonValue,\n>(\n client: WorkflowClient,\n handler: (\n args: TArgs,\n context: AgentStateContext<S>\n ) => Promise<ToolHandlerResponse<TResult, TToolResponse>>\n): ActivityToolHandler<TArgs, TResult, RouterContext, TToolResponse> {\n return async (args, context) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler(args, { ...context, state });\n };\n}\n","import type Redis from \"ioredis\";\nimport type {\n GoogleGenAI,\n Content,\n FunctionDeclaration,\n Part,\n GenerateContentResponse,\n} from \"@google/genai\";\nimport type { SerializableToolDefinition } from \"../../../lib/types\";\nimport type { AgentResponse, ModelInvokerConfig } from \"../../../lib/model\";\nimport {\n createGoogleGenAIThreadManager,\n type GoogleGenAIThreadManagerHooks,\n} from \"./thread-manager\";\nimport { getActivityContext } from \"../../../lib/activity\";\n\nexport interface GoogleGenAIModelInvokerConfig {\n redis: Redis;\n client: GoogleGenAI;\n model: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n}\n\nfunction toFunctionDeclarations(\n tools: SerializableToolDefinition[]\n): FunctionDeclaration[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n parametersJsonSchema: t.schema,\n }));\n}\n\n/**\n * Creates a Google GenAI model invoker that satisfies the generic\n * `ModelInvoker<Content>` contract.\n *\n * Internally streams the response and emits Temporal heartbeats on each\n * chunk so that long-running LLM calls remain visible to the scheduler.\n * The caller is responsible for appending the response to the thread.\n *\n * @example\n * ```typescript\n * import { createGoogleGenAIModelInvoker } from 'zeitlich/adapters/thread/google-genai';\n * import { createRunAgentActivity } from 'zeitlich';\n * import { GoogleGenAI } from '@google/genai';\n *\n * const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const invoker = createGoogleGenAIModelInvoker({\n * redis,\n * client,\n * model: 'gemini-2.5-flash',\n * });\n *\n * return { ...createRunAgentActivity(client, invoker, \"myAgent\") };\n * ```\n */\nexport function createGoogleGenAIModelInvoker({\n redis,\n client,\n model,\n hooks,\n}: GoogleGenAIModelInvokerConfig) {\n return async function invokeGoogleGenAIModel(\n config: ModelInvokerConfig\n ): Promise<AgentResponse<Content>> {\n const { threadId, threadKey, state, assistantMessageId } = config;\n const { heartbeat, signal } = getActivityContext();\n\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n hooks,\n });\n // Truncate the thread starting at the id the assistant message\n // will be stored under. No-op on the first attempt; on rewind\n // retry / Temporal reset it wipes the prior attempt's assistant\n // + tool results so the LLM sees the original pre-call state.\n await thread.truncateFromId(assistantMessageId);\n const { contents, systemInstruction } =\n await thread.prepareForInvocation();\n\n const functionDeclarations = toFunctionDeclarations(state.tools);\n const tools =\n functionDeclarations.length > 0 ? [{ functionDeclarations }] : undefined;\n\n const stream = await client.models.generateContentStream({\n model,\n contents,\n config: {\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(tools ? { tools } : {}),\n abortSignal: signal,\n },\n });\n\n const allParts: Part[] = [];\n let lastChunk: GenerateContentResponse | undefined;\n for await (const chunk of stream) {\n lastChunk = chunk;\n allParts.push(...(chunk.candidates?.[0]?.content?.parts ?? []));\n heartbeat?.();\n }\n\n if (!lastChunk) {\n throw new Error(\"Google GenAI stream ended without producing any chunks\");\n }\n\n const modelContent: Content = { role: \"model\", parts: allParts };\n const functionCalls = lastChunk.functionCalls ?? [];\n\n return {\n message: modelContent,\n rawToolCalls: functionCalls.map((fc) => ({\n id: fc.id,\n name: fc.name ?? \"\",\n args: fc.args ?? {},\n })),\n usage: {\n inputTokens: lastChunk.usageMetadata?.promptTokenCount,\n outputTokens: lastChunk.usageMetadata?.candidatesTokenCount,\n cachedReadTokens: lastChunk.usageMetadata?.cachedContentTokenCount,\n },\n };\n };\n}\n\n/**\n * Standalone function for one-shot Google GenAI model invocation.\n * Convenience wrapper around createGoogleGenAIModelInvoker for cases\n * where you don't need to reuse the invoker.\n */\nexport async function invokeGoogleGenAIModel({\n redis,\n client,\n model,\n hooks,\n config,\n}: {\n redis: Redis;\n client: GoogleGenAI;\n model: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n config: ModelInvokerConfig;\n}): Promise<AgentResponse<Content>> {\n const invoker = createGoogleGenAIModelInvoker({\n redis,\n client,\n model,\n hooks,\n });\n return invoker(config);\n}\n","import type Redis from \"ioredis\";\nimport type { GoogleGenAI, Content, Part } from \"@google/genai\";\nimport type { ToolResultConfig } from \"../../../lib/types\";\nimport type { PersistedThreadState } from \"../../../lib/state/types\";\nimport type {\n ActivityToolHandler,\n RouterContext,\n ToolHandlerResponse,\n} from \"../../../lib/tool-router/types\";\nimport type {\n ThreadOps,\n PrefixedThreadOps,\n ScopedPrefix,\n} from \"../../../lib/session/types\";\nimport type { ModelInvoker } from \"../../../lib/model\";\nimport { createTieredThreadManager } from \"../../../lib/thread/tiered\";\nimport type { ColdThreadStore } from \"../../../lib/thread/cold-store\";\nimport {\n createGoogleGenAIThreadManager,\n storedContentId,\n type GoogleGenAIContent,\n type GoogleGenAISystemContent,\n type GoogleGenAIThreadManagerHooks,\n type StoredContent,\n} from \"./thread-manager\";\nimport { createGoogleGenAIModelInvoker } from \"./model-invoker\";\nimport { ADAPTER_ID } from \"./adapter-id\";\n\nexport type GoogleGenAIThreadOps<TScope extends string = \"\"> =\n PrefixedThreadOps<\n ScopedPrefix<TScope, typeof ADAPTER_ID>,\n GoogleGenAIContent\n >;\n\nexport interface GoogleGenAIAdapterConfig {\n redis: Redis;\n client?: GoogleGenAI;\n /** Default model name (e.g. 'gemini-2.5-flash'). If omitted, use `createModelInvoker()` */\n model?: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n /**\n * Optional durable cold tier (e.g. S3, R2, GCS). When provided,\n * the session hydrates the thread on entry (`continue`/`fork`) and\n * flushes it on every exit path. When omitted, the adapter is\n * Redis-only and `hydrateThread`/`flushThread` activities are no-ops.\n */\n coldStore?: ColdThreadStore;\n /**\n * Override the default Redis TTL (90 days). When pairing the\n * adapter with a `coldStore`, a shorter TTL (hours) is typically\n * more appropriate.\n */\n ttlSeconds?: number;\n}\n\n/**\n * Tool response type accepted by the Google GenAI adapter.\n *\n * Handlers can return:\n * - **`string`** — plain text, wrapped in a `functionResponse` part.\n * - **`Record<string, unknown>`** — structured object used as `functionResponse.response`.\n * - **`Part[]`** — pre-built parts used directly as `Content.parts`.\n * The handler is responsible for building correct Part objects (e.g. `functionResponse`,\n * `inlineData`, `text`). Use `context.toolCallId` and `context.toolName` to construct\n * `functionResponse` parts.\n *\n * @example\n * ```typescript\n * adapter.wrapHandler(async (args, ctx) => ({\n * toolResponse: [\n * { functionResponse: { id: ctx.toolCallId, name: ctx.toolName, response: { result: \"done\" } } },\n * { inlineData: { data: base64, mimeType: \"image/png\" } },\n * ],\n * data: null,\n * }));\n * ```\n */\nexport type GoogleGenAIToolResponse = string | Record<string, unknown> | Part[];\n\nexport interface GoogleGenAIAdapter {\n /** Model invoker using the default model (only available when `model` was provided) */\n invoker: ModelInvoker<Content>;\n /** Create an invoker for a specific model name (for multi-model setups) */\n createModelInvoker(model: string, client: GoogleGenAI): ModelInvoker<Content>;\n /**\n * Create prefixed thread activities for registration on the worker.\n *\n * @param scope - Workflow name appended to the adapter prefix.\n * Use different scopes for the main agent vs subagents to avoid collisions.\n *\n * @example\n * ```typescript\n * adapter.createActivities(\"codingAgent\")\n * // → { googleGenAICodingAgentInitializeThread, googleGenAICodingAgentAppendHumanMessage, … }\n *\n * adapter.createActivities(\"researchAgent\")\n * // → { googleGenAIResearchAgentInitializeThread, … }\n * ```\n */\n createActivities<S extends string = \"\">(scope?: S): GoogleGenAIThreadOps<S>;\n\n /**\n * Identity wrapper that types a tool handler for this adapter.\n * Constrains `toolResponse` to {@link GoogleGenAIToolResponse}.\n */\n wrapHandler<TArgs, TResult, TContext extends RouterContext = RouterContext>(\n handler: (\n args: TArgs,\n context: TContext\n ) => Promise<ToolHandlerResponse<TResult, GoogleGenAIToolResponse>>\n ): ActivityToolHandler<TArgs, TResult, TContext, GoogleGenAIToolResponse>;\n}\n\n/**\n * Creates a Google GenAI adapter that bundles thread operations and model\n * invocation using the `@google/genai` SDK.\n *\n * Use `createActivities(scope)` to register scoped thread operations as\n * Temporal activities on the worker. The `invoker` (or invokers created via\n * `createModelInvoker`) should be wrapped with `createRunAgentActivity`.\n *\n * @example\n * ```typescript\n * import { createGoogleGenAIAdapter } from 'zeitlich/adapters/thread/google-genai';\n * import { createRunAgentActivity } from 'zeitlich';\n * import { GoogleGenAI } from '@google/genai';\n *\n * const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const adapter = createGoogleGenAIAdapter({ redis, client, model: 'gemini-2.5-flash' });\n *\n * export function createActivities(temporalClient: WorkflowClient) {\n * return {\n * ...adapter.createActivities(\"codingAgent\"),\n * ...createRunAgentActivity(temporalClient, adapter.invoker, \"codingAgent\"),\n * };\n * }\n * ```\n *\n * @example Multi-agent worker (main + subagent share the adapter)\n * ```typescript\n * export function createActivities(temporalClient: WorkflowClient) {\n * return {\n * ...adapter.createActivities(\"codingAgent\"),\n * ...adapter.createActivities(\"researchAgent\"),\n * ...createRunAgentActivity(temporalClient, adapter.invoker, \"codingAgent\"),\n * ...createRunAgentActivity(\n * temporalClient,\n * adapter.createModelInvoker('gemini-2.5-pro'),\n * \"researchAgent\",\n * ),\n * };\n * }\n * ```\n */\nexport function createGoogleGenAIAdapter(\n config: GoogleGenAIAdapterConfig\n): GoogleGenAIAdapter {\n const { redis } = config;\n\n const baseExtras = {\n ...(config.ttlSeconds !== undefined && { ttlSeconds: config.ttlSeconds }),\n };\n\n const makeProviderThread = (threadId: string, threadKey?: string) =>\n createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n ...baseExtras,\n });\n\n const makeTieredBase = (threadId: string, threadKey?: string) =>\n createTieredThreadManager<StoredContent>({\n redis,\n threadId,\n key: threadKey,\n idOf: storedContentId,\n ...baseExtras,\n ...(config.coldStore && { coldStore: config.coldStore }),\n });\n\n const threadOps: ThreadOps<GoogleGenAIContent> = {\n async initializeThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.initialize();\n },\n\n async appendHumanMessage(\n threadId: string,\n id: string,\n content: GoogleGenAIContent,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendUserMessage(id, content);\n },\n\n async appendSystemMessage(\n threadId: string,\n id: string,\n content: GoogleGenAISystemContent,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendSystemMessage(id, content);\n },\n\n async appendToolResult(id: string, cfg: ToolResultConfig): Promise<void> {\n const { threadId, threadKey, toolCallId, toolName, content } = cfg;\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendToolResult(\n id,\n toolCallId,\n toolName,\n content as GoogleGenAIToolResponse\n );\n },\n\n async appendAgentMessage(\n threadId: string,\n id: string,\n message: Content,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendModelContent(id, message.parts ?? []);\n },\n\n async forkThread(\n sourceThreadId: string,\n targetThreadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId: sourceThreadId,\n key: threadKey,\n hooks: config.hooks,\n ...baseExtras,\n });\n await thread.fork(targetThreadId);\n },\n\n async truncateThread(\n threadId: string,\n messageId: string,\n threadKey?: string,\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.truncateFromId(messageId);\n },\n\n async loadThreadState(\n threadId: string,\n threadKey?: string\n ): Promise<PersistedThreadState | null> {\n const thread = makeProviderThread(threadId, threadKey);\n return thread.loadState();\n },\n\n async saveThreadState(\n threadId: string,\n state: PersistedThreadState,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.saveState(state);\n },\n\n async hydrateThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n if (!config.coldStore) return;\n await makeTieredBase(threadId, threadKey).hydrate();\n },\n\n async flushThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n if (!config.coldStore) return;\n await makeTieredBase(threadId, threadKey).flush();\n },\n };\n\n function createActivities<S extends string = \"\">(\n scope?: S\n ): GoogleGenAIThreadOps<S> {\n const prefix = scope\n ? `${ADAPTER_ID}${scope.charAt(0).toUpperCase()}${scope.slice(1)}`\n : ADAPTER_ID;\n const cap = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);\n return Object.fromEntries(\n Object.entries(threadOps).map(([k, v]) => [`${prefix}${cap(k)}`, v])\n ) as GoogleGenAIThreadOps<S>;\n }\n\n const makeInvoker = (\n model: string,\n client: GoogleGenAI\n ): ModelInvoker<Content> =>\n createGoogleGenAIModelInvoker({\n redis,\n client,\n model,\n hooks: config.hooks,\n });\n\n const invoker: ModelInvoker<Content> =\n config.model && config.client\n ? makeInvoker(config.model, config.client)\n : ((() => {\n throw new Error(\n \"No default model provided to createGoogleGenAIAdapter. \" +\n \"Either pass `model` in the config or use `createModelInvoker(model)` instead.\"\n );\n }) as unknown as ModelInvoker<Content>);\n\n return {\n createActivities,\n invoker,\n createModelInvoker: makeInvoker,\n wrapHandler: (handler) => handler,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/adapters/thread/google-genai/adapter-id.ts","../../../../src/lib/thread/keys.ts","../../../../src/lib/thread/manager.ts","../../../../src/lib/thread/snapshot.ts","../../../../src/lib/thread/tiered.ts","../../../../src/adapters/thread/google-genai/thread-manager.ts","../../../../src/lib/activity.ts","../../../../src/adapters/thread/google-genai/model-invoker.ts","../../../../src/adapters/thread/google-genai/activities.ts"],"names":["invokeGoogleGenAIModel"],"mappings":";;;;AAYO,IAAM,UAAA,GAAa;;;ACsBnB,IAAM,kBAAA,GAAqB,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA;AAc1C,SAAS,gBAAA,CACd,WACA,QAAA,EACQ;AACR,EAAA,OAAO,CAAA,EAAG,SAAS,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AACxC;AAeO,SAAS,gBAAA,CACd,WACA,QAAA,EACQ;AACR,EAAA,OAAO,CAAA,EAAG,SAAS,CAAA,aAAA,EAAgB,QAAQ,CAAA,CAAA;AAC7C;AAeO,SAAS,iBAAA,CACd,WACA,QAAA,EACQ;AACR,EAAA,OAAO,CAAA,EAAG,SAAS,CAAA,cAAA,EAAiB,QAAQ,CAAA,CAAA;AAC9C;AAkBO,SAAS,iBAAA,CAAkB,UAAkB,OAAA,EAAyB;AAC3E,EAAA,OAAO,CAAA,MAAA,EAAS,OAAO,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AAC5C;;;AC9FA,IAAM,wBAAA,GAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAgB1B,SAAS,oBACd,MAAA,EACsB;AACtB,EAAA,MAAM;AAAA,IACJ,KAAA;AAAA,IACA,QAAA;AAAA,IACA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AA,EAAO,OAAO,KAAA;AAAM,GACzD,CAAA;AAEH,EAAA,MAAM,OAAA,GACJ,MAAA,CAAO,KAAA,IAAS,MAAA,CAAO,MAAA,GACnB,WAAA,CAAY,MAAA,CAAO,KAAA,EAAO,MAAA,CAAO,MAAM,CAAA,IACrC,MAAM;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF,CAAA,CAAA;AAEN,EAAA,OAAO;AAAA,IACL,gBAAA;AAAA,IACA,OAAA;AAAA,IACA,kBAAA,EAAoB,WAAA;AAAA,IACpB,WAAA,EAAa,CAAC,OAAA,KAAY;AAAA,GAC5B;AACF","file":"index.js","sourcesContent":["/**\n * Public adapter identity for the Google GenAI thread adapter.\n *\n * This value is wire format — it appears as the prefix for Temporal\n * activity names (e.g. `googleGenAICodingAgentInitializeThread`) and\n * must never change, since renaming it would orphan existing persisted\n * threads and break in-flight workflows.\n *\n * Re-exported from `zeitlich/adapters/thread/google-genai` so downstream\n * consumers can use the exact same literal the adapter uses internally,\n * typed as the narrow string literal `\"googleGenAI\"`.\n */\nexport const ADAPTER_ID = \"googleGenAI\" as const;\n\n/** Narrow string-literal type for {@link ADAPTER_ID}. */\nexport type AdapterId = typeof ADAPTER_ID;\n","/**\n * Public helpers for zeitlich's Redis thread storage layout.\n *\n * These are the exact string-building primitives zeitlich's internal thread\n * manager uses for every adapter. Downstream consumers that need to read a\n * persisted thread (for evaluation, observability, admin tooling, etc.)\n * should use these helpers rather than reconstructing the key layout by\n * hand — the layout is versioned with this module, so upgrading zeitlich\n * keeps the consumer in sync.\n *\n * The layout is adapter-agnostic: every thread adapter stores messages the\n * same way.\n *\n * @example\n * ```typescript\n * import {\n * getThreadListKey,\n * getThreadMetaKey,\n * THREAD_TTL_SECONDS,\n * } from 'zeitlich';\n *\n * const listKey = getThreadListKey('messages', threadId);\n * const metaKey = getThreadMetaKey('messages', threadId);\n * const ttl = await redis.ttl(listKey); // <= THREAD_TTL_SECONDS\n * ```\n */\n\n/**\n * TTL (in seconds) applied to every thread list and thread meta key that\n * zeitlich's {@link createThreadManager} writes. Exposed so downstream\n * consumers can size their Redis retention / query windows to match.\n *\n * Current value: 90 days.\n */\nexport const THREAD_TTL_SECONDS = 60 * 60 * 24 * 90;\n\n/**\n * Build the Redis list key that holds a thread's serialized messages.\n *\n * Mirrors the exact key used internally by zeitlich's thread manager,\n * so a consumer calling `redis.lRange(getThreadListKey(key, id), 0, -1)`\n * sees the same data the writer wrote.\n *\n * @param threadKey - Thread key (defaults to `\"messages\"` inside the\n * thread manager, but downstream adapters may pass\n * their own value).\n * @param threadId - Thread id as provided to the thread manager.\n */\nexport function getThreadListKey(\n threadKey: string,\n threadId: string\n): string {\n return `${threadKey}:thread:${threadId}`;\n}\n\n/**\n * Build the Redis key that stores a thread's existence marker / metadata.\n *\n * Zeitlich treats the presence of this key as \"thread has been\n * initialized\"; append/load/fork/truncate operations fail when it is\n * missing. Consumers can use it as a cheap existence probe without\n * scanning the message list.\n *\n * @param threadKey - Thread key (defaults to `\"messages\"` inside the\n * thread manager, but downstream adapters may pass\n * their own value).\n * @param threadId - Thread id as provided to the thread manager.\n */\nexport function getThreadMetaKey(\n threadKey: string,\n threadId: string\n): string {\n return `${threadKey}:meta:thread:${threadId}`;\n}\n\n/**\n * Build the Redis key that stores a thread's persisted state slice\n * (tasks + custom state) written by zeitlich's session loop on every\n * exit path.\n *\n * Consumers can read this key with `redis.get(getThreadStateKey(key, id))`\n * and `JSON.parse` the result into a {@link PersistedThreadState}.\n *\n * @param threadKey - Thread key (defaults to `\"messages\"` inside the\n * thread manager, but downstream adapters may pass\n * their own value).\n * @param threadId - Thread id as provided to the thread manager.\n */\nexport function getThreadStateKey(\n threadKey: string,\n threadId: string\n): string {\n return `${threadKey}:state:thread:${threadId}`;\n}\n\n/**\n * Build the Redis key that guards an idempotent append against a\n * duplicate write of the message (or message batch) identified by\n * `dedupId`. Zeitlich's thread manager writes one of these per\n * single-message append (and one per batch for multi-message appends),\n * keyed by the message id returned by the configured `idOf`.\n *\n * Note: the key layout intentionally does **not** include the\n * `threadKey` prefix — the dedup namespace is shared across thread\n * keys for a given `threadId`, mirroring the original internal\n * implementation.\n *\n * @param threadId - Thread id as provided to the thread manager.\n * @param dedupId - Joined message ids (single message id for the\n * common single-append case).\n */\nexport function getThreadDedupKey(threadId: string, dedupId: string): string {\n return `dedup:${dedupId}:thread:${threadId}`;\n}\n","import type { PersistedThreadState } from \"../state/types\";\nimport type { ThreadManagerConfig, BaseThreadManager } from \"./types\";\nimport {\n THREAD_TTL_SECONDS,\n getThreadListKey,\n getThreadMetaKey,\n getThreadStateKey,\n getThreadDedupKey,\n} from \"./keys\";\n\n/**\n * Lua script for atomic idempotent append.\n * Checks a dedup key; if it exists the message was already appended and we\n * return 0. Otherwise appends all messages to the list, sets TTL on both\n * the list and the dedup key, and returns 1.\n *\n * KEYS[1] = dedup key, KEYS[2] = list key\n * ARGV[1] = TTL seconds, ARGV[2..N] = serialised messages\n */\nconst APPEND_IDEMPOTENT_SCRIPT = `\nif redis.call('EXISTS', KEYS[1]) == 1 then\n return 0\nend\nfor i = 2, #ARGV do\n redis.call('RPUSH', KEYS[2], ARGV[i])\nend\nredis.call('EXPIRE', KEYS[2], tonumber(ARGV[1]))\nredis.call('SET', KEYS[1], '1', 'EX', tonumber(ARGV[1]))\nreturn 1\n`;\n\n/**\n * Creates a generic thread manager for handling conversation state in Redis.\n * Framework-agnostic — works with any serializable message type.\n */\nexport function createThreadManager<T>(\n config: ThreadManagerConfig<T>\n): BaseThreadManager<T> {\n const {\n redis,\n threadId,\n key = \"messages\",\n serialize = (m: T): string => JSON.stringify(m),\n deserialize = (raw: string): T => JSON.parse(raw) as T,\n idOf,\n ttlSeconds = THREAD_TTL_SECONDS,\n } = config;\n const redisKey = getThreadListKey(key, threadId);\n const metaKey = getThreadMetaKey(key, threadId);\n const stateKey = getThreadStateKey(key, threadId);\n const dedupKey = (id: string): string => getThreadDedupKey(threadId, id);\n\n async function assertThreadExists(): Promise<void> {\n const exists = await redis.exists(metaKey);\n if (!exists) {\n throw new Error(`Thread \"${threadId}\" (key: ${key}) does not exist`);\n }\n }\n\n return {\n async initialize(): Promise<void> {\n await redis.del(redisKey);\n await redis.set(metaKey, \"1\", { EX: ttlSeconds });\n },\n\n async load(): Promise<T[]> {\n await assertThreadExists();\n const data = await redis.lRange(redisKey, 0, -1);\n return data.map(deserialize);\n },\n\n async append(messages: T[]): Promise<void> {\n if (messages.length === 0) return;\n await assertThreadExists();\n\n if (idOf) {\n const dedupId = messages.map(idOf).join(\":\");\n await redis.eval(APPEND_IDEMPOTENT_SCRIPT, {\n keys: [dedupKey(dedupId), redisKey],\n arguments: [String(ttlSeconds), ...messages.map(serialize)],\n });\n } else {\n await redis.rPush(redisKey, messages.map(serialize));\n await redis.expire(redisKey, ttlSeconds);\n }\n },\n\n async fork(newThreadId: string): Promise<BaseThreadManager<T>> {\n await assertThreadExists();\n const data = await redis.lRange(redisKey, 0, -1);\n const stateRaw = await redis.get(stateKey);\n const forked = createThreadManager({\n ...config,\n threadId: newThreadId,\n });\n await forked.initialize();\n if (data.length > 0) {\n const newKey = getThreadListKey(key, newThreadId);\n await redis.rPush(newKey, data);\n await redis.expire(newKey, ttlSeconds);\n }\n if (stateRaw != null) {\n const newStateKey = getThreadStateKey(key, newThreadId);\n await redis.set(newStateKey, stateRaw, { EX: ttlSeconds });\n }\n return forked;\n },\n\n async replaceAll(messages: T[]): Promise<void> {\n await assertThreadExists();\n if (!idOf) {\n throw new Error(\n \"replaceAll requires the thread manager to be configured with `idOf`\"\n );\n }\n const existing = await redis.lRange(redisKey, 0, -1);\n const existingIds = existing\n .map((raw) => idOf(deserialize(raw)))\n .filter((id): id is string => typeof id === \"string\");\n await redis.del(redisKey);\n if (existingIds.length > 0) {\n await redis.del(existingIds.map(dedupKey));\n }\n if (messages.length > 0) {\n await redis.rPush(redisKey, messages.map(serialize));\n await redis.expire(redisKey, ttlSeconds);\n }\n await redis.expire(metaKey, ttlSeconds);\n },\n\n async delete(): Promise<void> {\n await redis.del([redisKey, metaKey, stateKey]);\n },\n\n async loadState(): Promise<PersistedThreadState | null> {\n const raw = await redis.get(stateKey);\n if (raw == null) return null;\n return JSON.parse(raw) as PersistedThreadState;\n },\n\n async saveState(state: PersistedThreadState): Promise<void> {\n await assertThreadExists();\n await redis.set(stateKey, JSON.stringify(state), { EX: ttlSeconds });\n },\n\n async deleteState(): Promise<void> {\n await redis.del(stateKey);\n },\n\n async length(): Promise<number> {\n await assertThreadExists();\n return redis.lLen(redisKey);\n },\n\n async truncateFromId(messageId: string): Promise<void> {\n await assertThreadExists();\n if (!idOf) {\n throw new Error(\n \"truncateFromId requires the thread manager to be configured with `idOf`\"\n );\n }\n const data = await redis.lRange(redisKey, 0, -1);\n let idx = -1;\n const removedIds: string[] = [];\n for (let i = 0; i < data.length; i++) {\n const raw = data[i];\n if (raw === undefined) continue;\n const id = idOf(deserialize(raw));\n if (idx === -1 && id === messageId) idx = i;\n if (idx !== -1) removedIds.push(id);\n }\n if (idx === -1) return;\n if (idx === 0) {\n await redis.del(redisKey);\n await redis.expire(metaKey, ttlSeconds);\n } else {\n await redis.lTrim(redisKey, 0, idx - 1);\n await redis.expire(redisKey, ttlSeconds);\n }\n // Clear dedup markers for the removed messages so that a rewind\n // retry which reuses the same ids (e.g. the same assistantId) can\n // re-append without the idempotent-append Lua script treating it\n // as a duplicate.\n if (removedIds.length > 0) {\n await redis.del(removedIds.map(dedupKey));\n }\n },\n };\n}\n","/**\n * Pure Redis I/O helpers for moving a thread between the hot tier\n * (Redis lists + meta + state + dedup markers) and the cold tier\n * (a single {@link ThreadSnapshot} blob in a {@link ColdThreadStore}).\n *\n * These helpers know nothing about S3 or the adapter-specific message\n * envelope — they operate on the raw Redis representation. The\n * tiered thread manager in `tiered.ts` is the only consumer.\n */\n\nimport type { RedisClientType } from \"redis\";\nimport type { PersistedThreadState } from \"../state/types\";\nimport type { ThreadSnapshot } from \"./cold-store\";\nimport {\n THREAD_TTL_SECONDS,\n getThreadDedupKey,\n getThreadListKey,\n getThreadMetaKey,\n getThreadStateKey,\n} from \"./keys\";\n\n/** Inputs shared by every snapshot operation. */\ninterface SnapshotCommon {\n redis: RedisClientType;\n threadKey: string;\n threadId: string;\n}\n\n/** Configuration for {@link encodeSnapshot}. */\nexport interface EncodeSnapshotConfig extends SnapshotCommon {\n /**\n * Extract a dedup id from each raw-serialized message currently in\n * the thread's Redis list. When omitted, the resulting snapshot has\n * an empty `dedupIds` array — idempotency guarantees are best-effort\n * once a thread crosses the hot/cold boundary.\n */\n idOf?: (raw: string) => string;\n}\n\n/**\n * Build a {@link ThreadSnapshot} from the current hot-tier state.\n *\n * Returns `null` when no thread exists in the hot tier (the meta key\n * is absent) — callers should treat that as \"nothing to flush\".\n */\nexport async function encodeSnapshot(\n config: EncodeSnapshotConfig\n): Promise<ThreadSnapshot | null> {\n const { redis, threadKey, threadId, idOf } = config;\n const metaKey = getThreadMetaKey(threadKey, threadId);\n if ((await redis.exists(metaKey)) === 0) {\n return null;\n }\n const listKey = getThreadListKey(threadKey, threadId);\n const stateKey = getThreadStateKey(threadKey, threadId);\n const messages = await redis.lRange(listKey, 0, -1);\n const stateRaw = await redis.get(stateKey);\n const state =\n stateRaw == null ? null : (JSON.parse(stateRaw) as PersistedThreadState);\n const dedupIds = idOf ? messages.map(idOf) : [];\n return { v: 1, messages, state, dedupIds };\n}\n\n/** Configuration for {@link applySnapshot}. */\nexport interface ApplySnapshotConfig extends SnapshotCommon {\n snapshot: ThreadSnapshot;\n /** TTL applied to every Redis key. Defaults to {@link THREAD_TTL_SECONDS}. */\n ttlSeconds?: number;\n}\n\n/**\n * Restore a {@link ThreadSnapshot} into the hot tier.\n *\n * Idempotent — if the meta key already exists the thread is already\n * hot and this is a no-op. The meta key is written **last** so a\n * crash mid-restore leaves the thread cold (`load` / `append` will\n * see \"thread does not exist\") and the next session's hydrate retries\n * cleanly.\n */\nexport async function applySnapshot(\n config: ApplySnapshotConfig\n): Promise<void> {\n const {\n redis,\n threadKey,\n threadId,\n snapshot,\n ttlSeconds = THREAD_TTL_SECONDS,\n } = config;\n const metaKey = getThreadMetaKey(threadKey, threadId);\n if ((await redis.exists(metaKey)) === 1) {\n return;\n }\n const listKey = getThreadListKey(threadKey, threadId);\n const stateKey = getThreadStateKey(threadKey, threadId);\n\n // Clear partial residue from any prior half-restored attempt.\n // Awaited *outside* the pipeline so a DEL failure (ACL deny,\n // CROSSSLOT, …) short-circuits before any writes hit the wire —\n // pipelines are non-atomic, so a queued DEL wouldn't stop later\n // commands from accumulating data behind a missing meta marker.\n await redis.del([listKey, stateKey]);\n\n // Pipeline the data writes (list/state/dedup) in one round-trip via a\n // non-transactional `MULTI` (`execAsPipeline`). Meta is written\n // separately, only after every queued command succeeded, preserving\n // the \"meta-last\" crash-safety invariant — a partial restore must\n // leave meta absent so the next hydrate retries cleanly.\n const pipeline = redis.multi();\n if (snapshot.messages.length > 0) {\n pipeline.rPush(listKey, snapshot.messages);\n pipeline.expire(listKey, ttlSeconds);\n }\n if (snapshot.state != null) {\n pipeline.set(stateKey, JSON.stringify(snapshot.state), { EX: ttlSeconds });\n }\n for (const id of snapshot.dedupIds) {\n pipeline.set(getThreadDedupKey(threadId, id), \"1\", { EX: ttlSeconds });\n }\n try {\n await pipeline.execAsPipeline();\n } catch (err) {\n // Compensate: pipelines are non-atomic, so writes queued after a\n // failing command (notably dedup SETs) may have landed. Best-effort\n // clear every key we touched so a leftover dedup marker can't\n // silently skip a future append with the same id. node-redis\n // surfaces per-command failures by rejecting `execAsPipeline` with a\n // `MultiErrorReply`; we unwrap it to rethrow the first real error.\n await redis\n .del([\n listKey,\n stateKey,\n ...snapshot.dedupIds.map((id) => getThreadDedupKey(threadId, id)),\n ])\n .catch(() => undefined);\n throw firstPipelineError(err);\n }\n await redis.set(metaKey, \"1\", { EX: ttlSeconds });\n}\n\n/**\n * Unwrap node-redis's `MultiErrorReply` (thrown by `execAsPipeline` when\n * one or more queued commands fail) to the first underlying error so\n * callers see the actual Redis error (OOM, WRONGTYPE, …) rather than the\n * generic aggregate wrapper. The structural check avoids a hard runtime\n * dependency on the `redis` error class.\n */\nfunction firstPipelineError(err: unknown): unknown {\n if (\n err != null &&\n typeof err === \"object\" &&\n \"replies\" in err &&\n Array.isArray((err as { replies: unknown }).replies)\n ) {\n const firstErr = (err as { replies: unknown[] }).replies.find(\n (r): r is Error => r instanceof Error\n );\n if (firstErr) return firstErr;\n }\n return err;\n}\n\n/** Configuration for {@link clearHotTier}. */\nexport interface ClearHotTierConfig extends SnapshotCommon {\n /** Dedup ids to delete alongside the list / meta / state keys. */\n dedupIds?: string[];\n}\n\n/**\n * Delete every Redis key the thread manager wrote for `(threadKey,\n * threadId)`. Used by the tiered manager's `flush({ deleteHot: true })`\n * to drop hot-tier memory after a successful archive write.\n */\nexport async function clearHotTier(\n config: ClearHotTierConfig\n): Promise<void> {\n const { redis, threadKey, threadId, dedupIds = [] } = config;\n const keys = [\n getThreadListKey(threadKey, threadId),\n getThreadMetaKey(threadKey, threadId),\n getThreadStateKey(threadKey, threadId),\n ...dedupIds.map((id) => getThreadDedupKey(threadId, id)),\n ];\n await redis.del(keys);\n}\n","/**\n * Tiered thread manager: Redis hot tier + pluggable cold tier.\n *\n * Wraps {@link createThreadManager} (Redis-only) and adds two\n * session-boundary operations:\n *\n * - `hydrate()` — when the thread is cold (no meta key in Redis),\n * restore the latest {@link ThreadSnapshot} from the cold store.\n * Idempotent; no-op when the thread is already hot or when no\n * snapshot exists.\n * - `flush({ deleteHot })` — write the current Redis state out to the\n * cold store as one snapshot, then (by default) `DEL` the hot-tier\n * keys so idle threads don't sit in Redis memory.\n *\n * All other operations (`append`, `load`, `fork`, `replaceAll`,\n * `truncateFromId`, state I/O) delegate unchanged to the underlying\n * Redis manager, so adapters and tests that use the\n * `BaseThreadManager<T>` interface keep working with zero changes.\n */\n\nimport { createThreadManager } from \"./manager\";\nimport { THREAD_TTL_SECONDS } from \"./keys\";\nimport type { BaseThreadManager, ThreadManagerConfig } from \"./types\";\nimport type { ColdThreadStore } from \"./cold-store\";\nimport {\n applySnapshot,\n clearHotTier,\n encodeSnapshot,\n} from \"./snapshot\";\n\n/** Configuration for {@link createTieredThreadManager}. */\nexport interface TieredThreadManagerConfig<T> extends ThreadManagerConfig<T> {\n /**\n * Cold-tier archive. When omitted, `hydrate()` and `flush()` are\n * no-ops and the manager behaves identically to\n * {@link createThreadManager}.\n */\n coldStore?: ColdThreadStore;\n}\n\n/** Options for {@link TieredThreadManager.flush}. */\nexport interface FlushOptions {\n /**\n * Delete the hot-tier Redis keys after a successful cold-tier\n * write. Defaults to `true` when a cold store is configured —\n * Redis is just a cache and a future continue/fork will\n * re-hydrate in a single round-trip.\n *\n * Set to `false` to keep the hot tier warm (useful for tests or\n * for \"hot-after-flush\" use cases where another session is expected\n * to pick the thread up immediately).\n */\n deleteHot?: boolean;\n}\n\n/**\n * Extension of {@link BaseThreadManager} with the two cold-tier\n * lifecycle methods.\n */\nexport interface TieredThreadManager<T> extends BaseThreadManager<T> {\n /**\n * Restore the latest cold-tier snapshot into Redis when the thread\n * is cold. Idempotent — safe to call from a retried activity.\n */\n hydrate(): Promise<void>;\n /**\n * Write the current Redis state to the cold tier and (optionally)\n * drop the hot-tier keys. Idempotent — last-writer-wins on the\n * cold side.\n */\n flush(opts?: FlushOptions): Promise<void>;\n}\n\n/**\n * Build a thread manager backed by Redis (hot) and an optional\n * pluggable cold store. See module docstring for the lifecycle\n * semantics.\n */\nexport function createTieredThreadManager<T>(\n config: TieredThreadManagerConfig<T>\n): TieredThreadManager<T> {\n const {\n redis,\n threadId,\n key = \"messages\",\n coldStore,\n idOf,\n deserialize = (raw: string): T => JSON.parse(raw) as T,\n ttlSeconds = THREAD_TTL_SECONDS,\n } = config;\n\n const base = createThreadManager<T>(config);\n\n // Snapshot-time `idOf` operates on raw Redis strings — we deserialize\n // here and forward to the configured (deserialized) `idOf`.\n const rawIdOf = idOf\n ? (raw: string): string => idOf(deserialize(raw))\n : undefined;\n\n return Object.assign(base, {\n async hydrate(): Promise<void> {\n if (!coldStore) return;\n const snapshot = await coldStore.read(key, threadId);\n if (!snapshot) return;\n await applySnapshot({\n redis,\n threadKey: key,\n threadId,\n snapshot,\n ttlSeconds,\n });\n },\n\n async flush(opts?: FlushOptions): Promise<void> {\n if (!coldStore) return;\n const snapshot = await encodeSnapshot({\n redis,\n threadKey: key,\n threadId,\n ...(rawIdOf ? { idOf: rawIdOf } : {}),\n });\n if (!snapshot) return;\n await coldStore.write(key, threadId, snapshot);\n const deleteHot = opts?.deleteHot ?? true;\n if (deleteHot) {\n await clearHotTier({\n redis,\n threadKey: key,\n threadId,\n dedupIds: snapshot.dedupIds,\n });\n }\n },\n });\n}\n","import type { RedisClientType as Redis } from \"redis\";\nimport type { Content, Part } from \"@google/genai\";\nimport { createThreadManager } from \"../../../lib/thread/manager\";\nimport type {\n ProviderThreadManager,\n ThreadManagerConfig,\n ThreadManagerHooks,\n} from \"../../../lib/thread/types\";\nimport type { GoogleGenAIToolResponse } from \"./activities\";\n\n/** SDK-native content type for Google GenAI human messages */\nexport type GoogleGenAIContent = string | Part[];\n\n/** SDK-native content type for Google GenAI system instructions */\nexport type GoogleGenAISystemContent = string | Part[];\n\n/** A Content with a unique ID for idempotent Redis storage */\nexport interface StoredContent {\n id: string;\n content: Content;\n}\n\nexport type GoogleGenAIThreadManagerHooks = ThreadManagerHooks<\n StoredContent,\n Content\n>;\n\nexport interface GoogleGenAIThreadManagerConfig {\n redis: Redis;\n threadId: string;\n /** Thread key, defaults to 'messages' */\n key?: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n /**\n * Redis TTL for the thread's keys; defaults to 90 days. Use a shorter\n * value (hours) with a cold tier.\n */\n ttlSeconds?: number;\n}\n\n/** Prepared payload ready to send to the Google GenAI API */\nexport interface GoogleGenAIInvocationPayload {\n contents: Content[];\n systemInstruction?: Part[];\n}\n\n/** Thread manager with Google GenAI Content convenience helpers */\nexport interface GoogleGenAIThreadManager extends ProviderThreadManager<\n StoredContent,\n GoogleGenAIContent,\n GoogleGenAIToolResponse,\n GoogleGenAISystemContent\n> {\n appendModelContent(id: string, parts: Part[]): Promise<void>;\n prepareForInvocation(): Promise<GoogleGenAIInvocationPayload>;\n}\n\n/** Extract the unique id from a {@link StoredContent}. */\nexport function storedContentId(msg: StoredContent): string {\n return msg.id;\n}\n\n/** Normalise content into Part[] */\nfunction toParts(content: GoogleGenAIContent): Part[] {\n if (typeof content === \"string\") {\n return [{ text: content }];\n }\n return content;\n}\n\n/** Convert a string or object into a Record suitable for functionResponse.response */\nfunction toFunctionResponse(\n content: string | Record<string, unknown>\n): Record<string, unknown> {\n if (typeof content === \"object\") {\n return content;\n }\n return { result: content };\n}\n\n/**\n * Merge consecutive Content objects sharing the same role.\n * The Gemini API requires alternating user/model turns; without\n * merging, multiple sequential tool-result messages would violate this.\n */\nfunction mergeConsecutiveContents(contents: Content[]): Content[] {\n const merged: Content[] = [];\n for (const content of contents) {\n const last = merged[merged.length - 1];\n if (last && last.role === content.role) {\n last.parts = [...(last.parts ?? []), ...(content.parts ?? [])];\n } else {\n merged.push({ ...content, parts: [...(content.parts ?? [])] });\n }\n }\n return merged;\n}\n\n/**\n * Creates a Google GenAI-specific thread manager that stores StoredContent\n * instances in Redis and provides convenience helpers for creating and\n * appending typed Content messages.\n */\nexport function createGoogleGenAIThreadManager(\n config: GoogleGenAIThreadManagerConfig\n): GoogleGenAIThreadManager {\n const baseConfig: ThreadManagerConfig<StoredContent> = {\n redis: config.redis,\n threadId: config.threadId,\n key: config.key,\n idOf: storedContentId,\n ...(config.ttlSeconds !== undefined && { ttlSeconds: config.ttlSeconds }),\n };\n\n const base = createThreadManager(baseConfig);\n\n const helpers: Omit<GoogleGenAIThreadManager, keyof typeof base> = {\n async appendUserMessage(\n id: string,\n content: GoogleGenAIContent\n ): Promise<void> {\n await base.append([\n {\n id,\n content: { role: \"user\", parts: toParts(content) },\n },\n ]);\n },\n\n async appendSystemMessage(\n id: string,\n content: GoogleGenAISystemContent\n ): Promise<void> {\n const parts: Part[] =\n typeof content === \"string\" ? [{ text: content }] : content;\n await base.initialize();\n await base.append([\n {\n id,\n content: { role: \"system\", parts },\n },\n ]);\n },\n\n async appendModelContent(id: string, parts: Part[]): Promise<void> {\n await base.append([\n {\n id,\n content: { role: \"model\", parts },\n },\n ]);\n },\n\n async appendToolResult(\n id: string,\n toolCallId: string,\n toolName: string,\n content: GoogleGenAIToolResponse\n ): Promise<void> {\n const parts: Part[] = Array.isArray(content)\n ? (content as Part[])\n : [\n {\n functionResponse: {\n id: toolCallId,\n name: toolName,\n response: toFunctionResponse(content),\n },\n },\n ];\n\n await base.append([\n {\n id,\n content: { role: \"user\", parts },\n },\n ]);\n },\n\n async prepareForInvocation(): Promise<GoogleGenAIInvocationPayload> {\n const stored = await base.load();\n const { onPrepareMessage, onPreparedMessage } = config.hooks ?? {};\n const mapped = onPrepareMessage\n ? stored.map((msg, i) => onPrepareMessage(msg, i, stored))\n : stored;\n\n let systemInstruction: Part[] | undefined;\n const conversationContents: Content[] = [];\n\n for (const item of mapped) {\n if (item.content.role === \"system\") {\n systemInstruction = item.content.parts ?? [];\n } else {\n conversationContents.push(item.content);\n }\n }\n\n const contents = mergeConsecutiveContents(conversationContents);\n return {\n contents: onPreparedMessage\n ? contents.map((msg, i) => onPreparedMessage(msg, i, contents))\n : contents,\n ...(systemInstruction && systemInstruction.length > 0\n ? { systemInstruction }\n : {}),\n };\n },\n };\n\n const manager = Object.assign(base, helpers);\n\n const originalFork = manager.fork.bind(manager);\n manager.fork = async (\n newThreadId: string\n ): Promise<GoogleGenAIThreadManager> => {\n await originalFork(newThreadId);\n const forked = createGoogleGenAIThreadManager({\n ...config,\n threadId: newThreadId,\n });\n const { onForkPrepareThread, onForkTransform } = config.hooks ?? {};\n if (!onForkPrepareThread && !onForkTransform) {\n return forked;\n }\n let next = await forked.load();\n if (onForkPrepareThread) {\n next = await onForkPrepareThread(next);\n }\n if (onForkTransform) {\n next = next.map((msg, i) => onForkTransform(msg, i, next));\n }\n await forked.replaceAll(next);\n return forked;\n };\n\n return manager;\n}\n","import { Context } from \"@temporalio/activity\";\nimport type { WorkflowClient } from \"@temporalio/client\";\nimport type { BaseAgentState, RunAgentConfig } from \"./types\";\nimport type { JsonValue } from \"./state/types\";\nimport type {\n ActivityToolHandler,\n RouterContext,\n ToolHandlerResponse,\n} from \"./tool-router/types\";\n\n/**\n * Safely retrieve Temporal activity heartbeat and cancellation signal.\n * Returns empty object when called outside a Temporal activity (e.g. tests).\n */\nexport function getActivityContext(): {\n heartbeat?: () => void;\n signal?: AbortSignal;\n} {\n try {\n const ctx = Context.current();\n return { heartbeat: () => ctx.heartbeat(), signal: ctx.cancellationSignal };\n } catch {\n return {};\n }\n}\n\n/**\n * Query the parent workflow's state from within an activity.\n * Resolves the workflow handle from the current activity context.\n */\nexport async function queryParentWorkflowState<T>(\n client: WorkflowClient\n): Promise<T> {\n const { workflowExecution } = Context.current().info;\n\n if (!workflowExecution) {\n throw new Error(\"No workflow execution found\");\n }\n\n const handle = client.getHandle(\n workflowExecution.workflowId,\n workflowExecution.runId\n );\n return handle.query<T>(\"getAgentState\");\n}\n\n/**\n * Wraps a handler into a scope-prefixed `RunAgentActivity` by auto-fetching\n * the parent workflow's agent state before each invocation.\n *\n * Returns a `Record` with a single key `run<Scope>` so it can be spread\n * into the activities object alongside adapter activities.\n *\n * @param scope - Workflow scope used to derive the activity name.\n * `\"myAgentWorkflow\"` produces `{ runMyAgentWorkflow: fn }`.\n *\n * @example\n * ```typescript\n * import { createRunAgentActivity } from 'zeitlich';\n *\n * return {\n * ...adapter.createActivities(\"myAgentWorkflow\"),\n * ...createRunAgentActivity(client, adapter.invoker, \"myAgentWorkflow\"),\n * };\n * ```\n */\nexport function createRunAgentActivity<\n R,\n S extends BaseAgentState = BaseAgentState,\n>(\n client: WorkflowClient,\n handler: (config: RunAgentConfig & { state: S }) => Promise<R>,\n scope: string\n): Record<string, (config: RunAgentConfig) => Promise<R>> {\n const name = `run${scope.charAt(0).toUpperCase()}${scope.slice(1)}`;\n return {\n [name]: async (config: RunAgentConfig) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler({ ...config, state });\n },\n };\n}\n\n/**\n * Context injected into tool handlers created via {@link withParentWorkflowState}.\n */\nexport interface AgentStateContext<\n S extends BaseAgentState = BaseAgentState,\n> extends RouterContext {\n state: S;\n}\n\n/**\n * Wraps a tool handler into an `ActivityToolHandler` by auto-fetching the\n * parent workflow's agent state before each invocation.\n *\n * @typeParam S - Custom agent state type (defaults to `BaseAgentState`)\n *\n * @example\n * ```typescript\n * import { withParentWorkflowState, type AgentStateContext } from 'zeitlich';\n *\n * // With custom state:\n * interface MyState extends BaseAgentState { customField: string }\n * const myHandler = withParentWorkflowState<MyArgs, MyResult, MyState>(\n * client,\n * async (args, ctx) => {\n * console.log(ctx.state.customField);\n * return { toolResponse: 'done', data: null };\n * },\n * );\n * ```\n */\nexport function withParentWorkflowState<\n TArgs,\n TResult,\n S extends BaseAgentState = BaseAgentState,\n TToolResponse = JsonValue,\n>(\n client: WorkflowClient,\n handler: (\n args: TArgs,\n context: AgentStateContext<S>\n ) => Promise<ToolHandlerResponse<TResult, TToolResponse>>\n): ActivityToolHandler<TArgs, TResult, RouterContext, TToolResponse> {\n return async (args, context) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler(args, { ...context, state });\n };\n}\n","import type { RedisClientType as Redis } from \"redis\";\nimport { randomBytes } from \"node:crypto\";\nimport type {\n GoogleGenAI,\n Content,\n FunctionDeclaration,\n GenerateContentConfig,\n Part,\n GenerateContentResponse,\n} from \"@google/genai\";\nimport type { SerializableToolDefinition } from \"../../../lib/types\";\nimport type { AgentResponse, ModelInvokerConfig } from \"../../../lib/model\";\nimport {\n createGoogleGenAIThreadManager,\n type GoogleGenAIThreadManagerHooks,\n} from \"./thread-manager\";\nimport { getActivityContext } from \"../../../lib/activity\";\n\nexport interface GoogleGenAIModelInvokerConfig {\n redis: Redis;\n client: GoogleGenAI;\n model: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n /**\n * Redis TTL for the thread's keys; defaults to 90 days. Use a shorter\n * value (hours) with a cold tier. Distinct from `cache.ttlSeconds`\n * (server-side context caching).\n */\n ttlSeconds?: number;\n /** Passed through to `generateContentStream().config`.\n * `systemInstruction`, `tools`, and `abortSignal` are managed by the\n * invoker and will override any values set here. */\n config?: GenerateContentConfig;\n /** Caches the first `splitIndex` messages server-side (with\n * `systemInstruction`, `tools`, and `toolConfig`). Skipped when\n * `contents.length <= splitIndex`. */\n cache?: {\n splitIndex: number;\n /** Default: 300. */\n ttlSeconds?: number;\n };\n}\n\nfunction toFunctionDeclarations(\n tools: SerializableToolDefinition[]\n): FunctionDeclaration[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n parametersJsonSchema: t.schema,\n }));\n}\n\n/**\n * The caller is responsible for appending the returned response to the thread.\n *\n * @example\n * ```typescript\n * import { createGoogleGenAIModelInvoker } from 'zeitlich/adapters/thread/google-genai';\n * import { createRunAgentActivity } from 'zeitlich';\n * import { GoogleGenAI } from '@google/genai';\n *\n * const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const invoker = createGoogleGenAIModelInvoker({\n * redis,\n * client,\n * model: 'gemini-2.5-flash',\n * });\n *\n * return { ...createRunAgentActivity(client, invoker, \"myAgent\") };\n * ```\n */\nexport function createGoogleGenAIModelInvoker({\n redis,\n client,\n model,\n hooks,\n ttlSeconds,\n config: generationConfig,\n cache: cacheConfig,\n}: GoogleGenAIModelInvokerConfig) {\n return async function invokeGoogleGenAIModel(\n config: ModelInvokerConfig\n ): Promise<AgentResponse<Content>> {\n const { threadId, threadKey, state, assistantMessageId } = config;\n const { heartbeat, signal } = getActivityContext();\n\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n hooks,\n ...(ttlSeconds !== undefined && { ttlSeconds }),\n });\n // Truncate the thread starting at the id the assistant message\n // will be stored under. No-op on the first attempt; on rewind\n // retry / Temporal reset it wipes the prior attempt's assistant\n // + tool results so the LLM sees the original pre-call state.\n await thread.truncateFromId(assistantMessageId);\n const { contents, systemInstruction } = await thread.prepareForInvocation();\n\n const functionDeclarations = toFunctionDeclarations(state.tools);\n const tools =\n functionDeclarations.length > 0 ? [{ functionDeclarations }] : undefined;\n\n const {\n systemInstruction: _si,\n tools: _t,\n abortSignal: _as,\n cachedContent: callerCachedContent,\n toolConfig: callerToolConfig,\n ...callerConfig\n } = generationConfig ?? {};\n\n let liveContents = contents;\n let cachedContentName: string | undefined;\n let cachedWriteTokens: number | undefined;\n\n if (\n cacheConfig &&\n cacheConfig.splitIndex > 0 &&\n contents.length > cacheConfig.splitIndex\n ) {\n liveContents = contents.slice(cacheConfig.splitIndex);\n const ttl = cacheConfig.ttlSeconds ?? 300;\n const cacheRedisKey = `${threadKey ?? \"messages\"}:gemini-cache:${model}:${cacheConfig.splitIndex}:thread:${threadId}`;\n\n cachedContentName = (await redis.get(cacheRedisKey)) ?? undefined;\n\n if (!cachedContentName) {\n const cacheInstance = await client.caches.create({\n model,\n config: {\n contents: contents.slice(0, cacheConfig.splitIndex),\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(tools ? { tools } : {}),\n ...(callerToolConfig ? { toolConfig: callerToolConfig } : {}),\n ttl: `${ttl}s`,\n abortSignal: signal,\n },\n });\n if (!cacheInstance?.name) {\n throw new Error(\"Gemini cache creation did not return a cache name\");\n }\n cachedContentName = cacheInstance.name;\n cachedWriteTokens =\n cacheInstance.usageMetadata?.totalTokenCount ?? undefined;\n const redisTtl = ttl - 5;\n if (redisTtl > 0) {\n await redis.set(cacheRedisKey, cachedContentName, { EX: redisTtl });\n }\n }\n }\n\n const stream = await client.models.generateContentStream({\n model,\n contents: liveContents,\n config: {\n ...callerConfig,\n ...(cachedContentName\n ? { cachedContent: cachedContentName }\n : {\n ...(callerCachedContent\n ? { cachedContent: callerCachedContent }\n : {\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(tools ? { tools } : {}),\n }),\n ...(callerToolConfig ? { toolConfig: callerToolConfig } : {}),\n }),\n abortSignal: signal,\n },\n });\n\n const allParts: Part[] = [];\n let lastChunk: GenerateContentResponse | undefined;\n for await (const chunk of stream) {\n lastChunk = chunk;\n allParts.push(...(chunk.candidates?.[0]?.content?.parts ?? []));\n heartbeat?.();\n }\n\n if (!lastChunk) {\n throw new Error(\"Google GenAI stream ended without producing any chunks\");\n }\n\n for (const part of allParts) {\n if (part.functionCall && !part.functionCall.id) {\n part.functionCall.id = randomBytes(8).toString(\"hex\");\n }\n }\n\n const modelContent: Content = { role: \"model\", parts: allParts };\n\n return {\n message: modelContent,\n rawToolCalls: allParts\n .filter(\n (\n p\n ): p is Part & { functionCall: NonNullable<Part[\"functionCall\"]> } =>\n !!p.functionCall\n )\n .map((p) => ({\n id: p.functionCall.id,\n name: p.functionCall.name ?? \"\",\n args: p.functionCall.args ?? {},\n })),\n usage: {\n inputTokens: lastChunk.usageMetadata?.promptTokenCount,\n outputTokens: lastChunk.usageMetadata?.candidatesTokenCount,\n cachedWriteTokens,\n cachedReadTokens: lastChunk.usageMetadata?.cachedContentTokenCount,\n reasonTokens: lastChunk.usageMetadata?.thoughtsTokenCount,\n },\n };\n };\n}\n\nexport async function invokeGoogleGenAIModel({\n redis,\n client,\n model,\n hooks,\n ttlSeconds,\n config,\n generationConfig,\n cache,\n}: {\n redis: Redis;\n client: GoogleGenAI;\n model: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n ttlSeconds?: number;\n config: ModelInvokerConfig;\n generationConfig?: GenerateContentConfig;\n cache?: GoogleGenAIModelInvokerConfig[\"cache\"];\n}): Promise<AgentResponse<Content>> {\n const invoker = createGoogleGenAIModelInvoker({\n redis,\n client,\n model,\n hooks,\n ...(ttlSeconds !== undefined && { ttlSeconds }),\n config: generationConfig,\n cache,\n });\n return invoker(config);\n}\n","import type { RedisClientType as Redis } from \"redis\";\nimport type {\n GoogleGenAI,\n Content,\n Part,\n GenerateContentConfig,\n} from \"@google/genai\";\nimport type { ToolResultConfig } from \"../../../lib/types\";\nimport type { PersistedThreadState } from \"../../../lib/state/types\";\nimport type {\n ActivityToolHandler,\n RouterContext,\n ToolHandlerResponse,\n} from \"../../../lib/tool-router/types\";\nimport type {\n ThreadOps,\n PrefixedThreadOps,\n ScopedPrefix,\n} from \"../../../lib/session/types\";\nimport type { ModelInvoker } from \"../../../lib/model\";\nimport { createTieredThreadManager } from \"../../../lib/thread/tiered\";\nimport type { ColdThreadStore } from \"../../../lib/thread/cold-store\";\nimport {\n createGoogleGenAIThreadManager,\n storedContentId,\n type GoogleGenAIContent,\n type GoogleGenAISystemContent,\n type GoogleGenAIThreadManagerHooks,\n type StoredContent,\n} from \"./thread-manager\";\nimport {\n createGoogleGenAIModelInvoker,\n type GoogleGenAIModelInvokerConfig,\n} from \"./model-invoker\";\nimport { ADAPTER_ID } from \"./adapter-id\";\n\nexport type GoogleGenAIThreadOps<TScope extends string = \"\"> =\n PrefixedThreadOps<\n ScopedPrefix<TScope, typeof ADAPTER_ID>,\n GoogleGenAIContent\n >;\n\nexport interface GoogleGenAIAdapterConfig {\n redis: Redis;\n client?: GoogleGenAI;\n /** Default model name (e.g. 'gemini-2.5-flash'). If omitted, use `createModelInvoker()` */\n model?: string;\n hooks?: GoogleGenAIThreadManagerHooks;\n /**\n * Optional durable cold tier (e.g. S3, R2, GCS). When provided,\n * the session hydrates the thread on entry (`continue`/`fork`) and\n * flushes it on every exit path. When omitted, the adapter is\n * Redis-only and `hydrateThread`/`flushThread` activities are no-ops.\n */\n coldStore?: ColdThreadStore;\n /**\n * Redis TTL for the thread's keys; defaults to 90 days. Use a shorter\n * value (hours) with a cold tier.\n */\n ttlSeconds?: number;\n /**\n * Default generation config forwarded to every invoker the adapter\n * builds (`invoker` and `createModelInvoker`). `systemInstruction`,\n * `tools`, and `abortSignal` are managed by the invoker and override\n * any values set here.\n */\n generationConfig?: GenerateContentConfig;\n /**\n * Default server-side context caching config forwarded to every\n * invoker the adapter builds. See {@link createGoogleGenAIModelInvoker}.\n */\n cache?: GoogleGenAIModelInvokerConfig[\"cache\"];\n}\n\n/**\n * Tool response type accepted by the Google GenAI adapter.\n *\n * Handlers can return:\n * - **`string`** — plain text, wrapped in a `functionResponse` part.\n * - **`Record<string, unknown>`** — structured object used as `functionResponse.response`.\n * - **`Part[]`** — pre-built parts used directly as `Content.parts`.\n * The handler is responsible for building correct Part objects (e.g. `functionResponse`,\n * `inlineData`, `text`). Use `context.toolCallId` and `context.toolName` to construct\n * `functionResponse` parts.\n *\n * @example\n * ```typescript\n * adapter.wrapHandler(async (args, ctx) => ({\n * toolResponse: [\n * { functionResponse: { id: ctx.toolCallId, name: ctx.toolName, response: { result: \"done\" } } },\n * { inlineData: { data: base64, mimeType: \"image/png\" } },\n * ],\n * data: null,\n * }));\n * ```\n */\nexport type GoogleGenAIToolResponse = string | Record<string, unknown> | Part[];\n\nexport interface GoogleGenAIAdapter {\n /** Model invoker using the default model (only available when `model` was provided) */\n invoker: ModelInvoker<Content>;\n /** Create an invoker for a specific model name (for multi-model setups) */\n createModelInvoker(model: string, client: GoogleGenAI): ModelInvoker<Content>;\n /**\n * Create prefixed thread activities for registration on the worker.\n *\n * @param scope - Workflow name appended to the adapter prefix.\n * Use different scopes for the main agent vs subagents to avoid collisions.\n *\n * @example\n * ```typescript\n * adapter.createActivities(\"codingAgent\")\n * // → { googleGenAICodingAgentInitializeThread, googleGenAICodingAgentAppendHumanMessage, … }\n *\n * adapter.createActivities(\"researchAgent\")\n * // → { googleGenAIResearchAgentInitializeThread, … }\n * ```\n */\n createActivities<S extends string = \"\">(scope?: S): GoogleGenAIThreadOps<S>;\n\n /**\n * Identity wrapper that types a tool handler for this adapter.\n * Constrains `toolResponse` to {@link GoogleGenAIToolResponse}.\n */\n wrapHandler<TArgs, TResult, TContext extends RouterContext = RouterContext>(\n handler: (\n args: TArgs,\n context: TContext\n ) => Promise<ToolHandlerResponse<TResult, GoogleGenAIToolResponse>>\n ): ActivityToolHandler<TArgs, TResult, TContext, GoogleGenAIToolResponse>;\n}\n\n/**\n * Creates a Google GenAI adapter that bundles thread operations and model\n * invocation using the `@google/genai` SDK.\n *\n * Use `createActivities(scope)` to register scoped thread operations as\n * Temporal activities on the worker. The `invoker` (or invokers created via\n * `createModelInvoker`) should be wrapped with `createRunAgentActivity`.\n *\n * @example\n * ```typescript\n * import { createGoogleGenAIAdapter } from 'zeitlich/adapters/thread/google-genai';\n * import { createRunAgentActivity } from 'zeitlich';\n * import { GoogleGenAI } from '@google/genai';\n *\n * const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const adapter = createGoogleGenAIAdapter({ redis, client, model: 'gemini-2.5-flash' });\n *\n * export function createActivities(temporalClient: WorkflowClient) {\n * return {\n * ...adapter.createActivities(\"codingAgent\"),\n * ...createRunAgentActivity(temporalClient, adapter.invoker, \"codingAgent\"),\n * };\n * }\n * ```\n *\n * @example Multi-agent worker (main + subagent share the adapter)\n * ```typescript\n * export function createActivities(temporalClient: WorkflowClient) {\n * return {\n * ...adapter.createActivities(\"codingAgent\"),\n * ...adapter.createActivities(\"researchAgent\"),\n * ...createRunAgentActivity(temporalClient, adapter.invoker, \"codingAgent\"),\n * ...createRunAgentActivity(\n * temporalClient,\n * adapter.createModelInvoker('gemini-2.5-pro', client),\n * \"researchAgent\",\n * ),\n * };\n * }\n * ```\n */\nexport function createGoogleGenAIAdapter(\n config: GoogleGenAIAdapterConfig\n): GoogleGenAIAdapter {\n const { redis } = config;\n\n // Single source for the adapter's `redis` handle and configured TTL, spread\n // into every internal thread manager so all of them share one configuration.\n const base = {\n redis,\n ...(config.ttlSeconds !== undefined && { ttlSeconds: config.ttlSeconds }),\n };\n\n const makeProviderThread = (threadId: string, threadKey?: string) =>\n createGoogleGenAIThreadManager({\n ...base,\n threadId,\n key: threadKey,\n });\n\n const makeTieredBase = (threadId: string, threadKey?: string) =>\n createTieredThreadManager<StoredContent>({\n ...base,\n threadId,\n key: threadKey,\n idOf: storedContentId,\n ...(config.coldStore && { coldStore: config.coldStore }),\n });\n\n const threadOps: ThreadOps<GoogleGenAIContent> = {\n async initializeThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.initialize();\n },\n\n async appendHumanMessage(\n threadId: string,\n id: string,\n content: GoogleGenAIContent,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendUserMessage(id, content);\n },\n\n async appendSystemMessage(\n threadId: string,\n id: string,\n content: GoogleGenAISystemContent,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendSystemMessage(id, content);\n },\n\n async appendToolResult(id: string, cfg: ToolResultConfig): Promise<void> {\n const { threadId, threadKey, toolCallId, toolName, content } = cfg;\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendToolResult(\n id,\n toolCallId,\n toolName,\n content as GoogleGenAIToolResponse\n );\n },\n\n async appendAgentMessage(\n threadId: string,\n id: string,\n message: Content,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.appendModelContent(id, message.parts ?? []);\n },\n\n async forkThread(\n sourceThreadId: string,\n targetThreadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n ...base,\n threadId: sourceThreadId,\n key: threadKey,\n hooks: config.hooks,\n });\n await thread.fork(targetThreadId);\n },\n\n async truncateThread(\n threadId: string,\n messageId: string,\n threadKey?: string,\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.truncateFromId(messageId);\n },\n\n async loadThreadState(\n threadId: string,\n threadKey?: string\n ): Promise<PersistedThreadState | null> {\n const thread = makeProviderThread(threadId, threadKey);\n return thread.loadState();\n },\n\n async saveThreadState(\n threadId: string,\n state: PersistedThreadState,\n threadKey?: string\n ): Promise<void> {\n const thread = makeProviderThread(threadId, threadKey);\n await thread.saveState(state);\n },\n\n async hydrateThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n if (!config.coldStore) return;\n await makeTieredBase(threadId, threadKey).hydrate();\n },\n\n async flushThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n if (!config.coldStore) return;\n await makeTieredBase(threadId, threadKey).flush();\n },\n };\n\n function createActivities<S extends string = \"\">(\n scope?: S\n ): GoogleGenAIThreadOps<S> {\n const prefix = scope\n ? `${ADAPTER_ID}${scope.charAt(0).toUpperCase()}${scope.slice(1)}`\n : ADAPTER_ID;\n const cap = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);\n return Object.fromEntries(\n Object.entries(threadOps).map(([k, v]) => [`${prefix}${cap(k)}`, v])\n ) as GoogleGenAIThreadOps<S>;\n }\n\n const makeInvoker = (\n model: string,\n client: GoogleGenAI\n ): ModelInvoker<Content> =>\n createGoogleGenAIModelInvoker({\n ...base,\n client,\n model,\n hooks: config.hooks,\n ...(config.generationConfig !== undefined && {\n config: config.generationConfig,\n }),\n ...(config.cache !== undefined && { cache: config.cache }),\n });\n\n const invoker: ModelInvoker<Content> =\n config.model && config.client\n ? makeInvoker(config.model, config.client)\n : ((() => {\n throw new Error(\n \"No default model provided to createGoogleGenAIAdapter. \" +\n \"Either pass `model` in the config or use `createModelInvoker(model)` instead.\"\n );\n }) as unknown as ModelInvoker<Content>);\n\n return {\n createActivities,\n invoker,\n createModelInvoker: makeInvoker,\n wrapHandler: (handler) => handler,\n };\n}\n"]}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { ActivityInterfaceFor } from '@temporalio/workflow';
|
|
2
|
-
import { T as ThreadOps } from '../../../types-
|
|
3
|
-
import {
|
|
4
|
-
import { c as createThreadOpsProxy } from '../../../proxy-
|
|
5
|
-
export { T as ThreadOpsProxyOptions } from '../../../proxy-
|
|
2
|
+
import { T as ThreadOps } from '../../../types-BjdqxKYp.cjs';
|
|
3
|
+
import { GoogleGenAIContent } from './index.cjs';
|
|
4
|
+
import { c as createThreadOpsProxy } from '../../../proxy-2htgGQrc.cjs';
|
|
5
|
+
export { T as ThreadOpsProxyOptions } from '../../../proxy-2htgGQrc.cjs';
|
|
6
6
|
export { A as ADAPTER_ID, a as AdapterId } from '../../../adapter-id-BB-mmrts.cjs';
|
|
7
7
|
import '@temporalio/common/lib/interfaces';
|
|
8
8
|
import 'zod';
|
|
9
|
-
import '../../../types-
|
|
9
|
+
import '../../../types-D8W5TnSa.cjs';
|
|
10
10
|
import '@temporalio/common';
|
|
11
|
-
import '
|
|
11
|
+
import 'redis';
|
|
12
12
|
import '@google/genai';
|
|
13
|
-
import '../../../cold-store-
|
|
13
|
+
import '../../../cold-store-YOx9nmgR.cjs';
|
|
14
14
|
import '@aws-sdk/client-s3';
|
|
15
|
-
import '../../../types-
|
|
15
|
+
import '../../../types-N_LTWe4b.cjs';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Workflow-safe proxy for Google GenAI thread operations.
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { ActivityInterfaceFor } from '@temporalio/workflow';
|
|
2
|
-
import { T as ThreadOps } from '../../../types-
|
|
3
|
-
import {
|
|
4
|
-
import { c as createThreadOpsProxy } from '../../../proxy-
|
|
5
|
-
export { T as ThreadOpsProxyOptions } from '../../../proxy-
|
|
2
|
+
import { T as ThreadOps } from '../../../types-DiI7mZhI.js';
|
|
3
|
+
import { GoogleGenAIContent } from './index.js';
|
|
4
|
+
import { c as createThreadOpsProxy } from '../../../proxy-CmiTP4pp.js';
|
|
5
|
+
export { T as ThreadOpsProxyOptions } from '../../../proxy-CmiTP4pp.js';
|
|
6
6
|
export { A as ADAPTER_ID, a as AdapterId } from '../../../adapter-id-BB-mmrts.js';
|
|
7
7
|
import '@temporalio/common/lib/interfaces';
|
|
8
8
|
import 'zod';
|
|
9
|
-
import '../../../types-
|
|
9
|
+
import '../../../types-D8W5TnSa.js';
|
|
10
10
|
import '@temporalio/common';
|
|
11
|
-
import '
|
|
11
|
+
import 'redis';
|
|
12
12
|
import '@google/genai';
|
|
13
|
-
import '../../../cold-store-
|
|
13
|
+
import '../../../cold-store-DyHodfAB.js';
|
|
14
14
|
import '@aws-sdk/client-s3';
|
|
15
|
-
import '../../../types-
|
|
15
|
+
import '../../../types-DEbkLA06.js';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Workflow-safe proxy for Google GenAI thread operations.
|