zeitlich 0.2.37 → 0.2.38

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.
Files changed (131) hide show
  1. package/dist/{activities-Bb-nAjwQ.d.ts → activities-BKhMtKDd.d.ts} +4 -2
  2. package/dist/{activities-vkI4_3CC.d.cts → activities-CDcwkRZs.d.cts} +4 -2
  3. package/dist/adapters/sandbox/bedrock/index.cjs +3 -3
  4. package/dist/adapters/sandbox/bedrock/index.cjs.map +1 -1
  5. package/dist/adapters/sandbox/bedrock/index.d.cts +6 -6
  6. package/dist/adapters/sandbox/bedrock/index.d.ts +6 -6
  7. package/dist/adapters/sandbox/bedrock/index.js +3 -3
  8. package/dist/adapters/sandbox/bedrock/index.js.map +1 -1
  9. package/dist/adapters/sandbox/bedrock/workflow.d.cts +2 -2
  10. package/dist/adapters/sandbox/bedrock/workflow.d.ts +2 -2
  11. package/dist/adapters/sandbox/daytona/index.cjs +3 -3
  12. package/dist/adapters/sandbox/daytona/index.cjs.map +1 -1
  13. package/dist/adapters/sandbox/daytona/index.d.cts +4 -4
  14. package/dist/adapters/sandbox/daytona/index.d.ts +4 -4
  15. package/dist/adapters/sandbox/daytona/index.js +3 -3
  16. package/dist/adapters/sandbox/daytona/index.js.map +1 -1
  17. package/dist/adapters/sandbox/daytona/workflow.d.cts +1 -1
  18. package/dist/adapters/sandbox/daytona/workflow.d.ts +1 -1
  19. package/dist/adapters/sandbox/e2b/index.cjs +26 -14
  20. package/dist/adapters/sandbox/e2b/index.cjs.map +1 -1
  21. package/dist/adapters/sandbox/e2b/index.d.cts +24 -4
  22. package/dist/adapters/sandbox/e2b/index.d.ts +24 -4
  23. package/dist/adapters/sandbox/e2b/index.js +26 -14
  24. package/dist/adapters/sandbox/e2b/index.js.map +1 -1
  25. package/dist/adapters/sandbox/e2b/workflow.d.cts +1 -1
  26. package/dist/adapters/sandbox/e2b/workflow.d.ts +1 -1
  27. package/dist/adapters/sandbox/inmemory/index.cjs +3 -3
  28. package/dist/adapters/sandbox/inmemory/index.cjs.map +1 -1
  29. package/dist/adapters/sandbox/inmemory/index.d.cts +4 -4
  30. package/dist/adapters/sandbox/inmemory/index.d.ts +4 -4
  31. package/dist/adapters/sandbox/inmemory/index.js +3 -3
  32. package/dist/adapters/sandbox/inmemory/index.js.map +1 -1
  33. package/dist/adapters/sandbox/inmemory/workflow.d.cts +1 -1
  34. package/dist/adapters/sandbox/inmemory/workflow.d.ts +1 -1
  35. package/dist/adapters/thread/anthropic/index.cjs +23 -3
  36. package/dist/adapters/thread/anthropic/index.cjs.map +1 -1
  37. package/dist/adapters/thread/anthropic/index.d.cts +5 -5
  38. package/dist/adapters/thread/anthropic/index.d.ts +5 -5
  39. package/dist/adapters/thread/anthropic/index.js +23 -3
  40. package/dist/adapters/thread/anthropic/index.js.map +1 -1
  41. package/dist/adapters/thread/anthropic/workflow.cjs +2 -1
  42. package/dist/adapters/thread/anthropic/workflow.cjs.map +1 -1
  43. package/dist/adapters/thread/anthropic/workflow.d.cts +5 -5
  44. package/dist/adapters/thread/anthropic/workflow.d.ts +5 -5
  45. package/dist/adapters/thread/anthropic/workflow.js +2 -1
  46. package/dist/adapters/thread/anthropic/workflow.js.map +1 -1
  47. package/dist/adapters/thread/google-genai/index.cjs +27 -3
  48. package/dist/adapters/thread/google-genai/index.cjs.map +1 -1
  49. package/dist/adapters/thread/google-genai/index.d.cts +5 -5
  50. package/dist/adapters/thread/google-genai/index.d.ts +5 -5
  51. package/dist/adapters/thread/google-genai/index.js +27 -3
  52. package/dist/adapters/thread/google-genai/index.js.map +1 -1
  53. package/dist/adapters/thread/google-genai/workflow.cjs +2 -1
  54. package/dist/adapters/thread/google-genai/workflow.cjs.map +1 -1
  55. package/dist/adapters/thread/google-genai/workflow.d.cts +5 -5
  56. package/dist/adapters/thread/google-genai/workflow.d.ts +5 -5
  57. package/dist/adapters/thread/google-genai/workflow.js +2 -1
  58. package/dist/adapters/thread/google-genai/workflow.js.map +1 -1
  59. package/dist/adapters/thread/langchain/index.cjs +23 -3
  60. package/dist/adapters/thread/langchain/index.cjs.map +1 -1
  61. package/dist/adapters/thread/langchain/index.d.cts +5 -5
  62. package/dist/adapters/thread/langchain/index.d.ts +5 -5
  63. package/dist/adapters/thread/langchain/index.js +23 -3
  64. package/dist/adapters/thread/langchain/index.js.map +1 -1
  65. package/dist/adapters/thread/langchain/workflow.cjs +2 -1
  66. package/dist/adapters/thread/langchain/workflow.cjs.map +1 -1
  67. package/dist/adapters/thread/langchain/workflow.d.cts +5 -5
  68. package/dist/adapters/thread/langchain/workflow.d.ts +5 -5
  69. package/dist/adapters/thread/langchain/workflow.js +2 -1
  70. package/dist/adapters/thread/langchain/workflow.js.map +1 -1
  71. package/dist/index.cjs +120 -30
  72. package/dist/index.cjs.map +1 -1
  73. package/dist/index.d.cts +11 -11
  74. package/dist/index.d.ts +11 -11
  75. package/dist/index.js +121 -31
  76. package/dist/index.js.map +1 -1
  77. package/dist/{proxy-0smGKvx8.d.ts → proxy-CUlKSvZS.d.ts} +1 -1
  78. package/dist/{proxy-DEtowJyd.d.cts → proxy-D_3x7RN4.d.cts} +1 -1
  79. package/dist/{thread-manager-C-C4pI2z.d.ts → thread-manager-CVu7o2cs.d.ts} +4 -2
  80. package/dist/{thread-manager-D4vgzYrh.d.cts → thread-manager-HSwyh28L.d.cts} +4 -2
  81. package/dist/{thread-manager-3fszQih4.d.ts → thread-manager-c1gPopAG.d.ts} +4 -2
  82. package/dist/{thread-manager-CzYln2OC.d.cts → thread-manager-wGi-LqIP.d.cts} +4 -2
  83. package/dist/{types-B37hKoWA.d.ts → types-BH_IRryz.d.ts} +10 -1
  84. package/dist/{types-D08CXPh8.d.cts → types-BaOw4hKI.d.cts} +10 -1
  85. package/dist/{types-CPKDl-y_.d.ts → types-C06FwR96.d.cts} +59 -4
  86. package/dist/{types-CNuWnvy9.d.ts → types-DAsQ21Rt.d.ts} +1 -1
  87. package/dist/{types-BO7Yju20.d.cts → types-DNr31FzL.d.ts} +59 -4
  88. package/dist/{types-DWEUmYAJ.d.cts → types-lm8tMNJQ.d.cts} +1 -1
  89. package/dist/{types-tQL9njTu.d.cts → types-yx0LzPGn.d.cts} +21 -7
  90. package/dist/{types-tQL9njTu.d.ts → types-yx0LzPGn.d.ts} +21 -7
  91. package/dist/{workflow-CjXHbZZc.d.ts → workflow-CSCkpwAL.d.ts} +2 -2
  92. package/dist/{workflow-Do_lzJpT.d.cts → workflow-DuvMZ8Vm.d.cts} +2 -2
  93. package/dist/workflow.cjs +94 -18
  94. package/dist/workflow.cjs.map +1 -1
  95. package/dist/workflow.d.cts +3 -3
  96. package/dist/workflow.d.ts +3 -3
  97. package/dist/workflow.js +95 -19
  98. package/dist/workflow.js.map +1 -1
  99. package/package.json +2 -2
  100. package/src/adapters/sandbox/bedrock/index.ts +12 -3
  101. package/src/adapters/sandbox/daytona/index.ts +12 -3
  102. package/src/adapters/sandbox/e2b/index.ts +36 -14
  103. package/src/adapters/sandbox/e2b/types.ts +16 -0
  104. package/src/adapters/sandbox/inmemory/index.ts +12 -3
  105. package/src/adapters/thread/anthropic/activities.ts +9 -0
  106. package/src/adapters/thread/anthropic/model-invoker.ts +3 -1
  107. package/src/adapters/thread/anthropic/thread-manager.ts +3 -0
  108. package/src/adapters/thread/google-genai/activities.ts +13 -0
  109. package/src/adapters/thread/google-genai/model-invoker.ts +3 -1
  110. package/src/adapters/thread/google-genai/thread-manager.ts +3 -0
  111. package/src/adapters/thread/langchain/activities.ts +9 -0
  112. package/src/adapters/thread/langchain/model-invoker.ts +2 -1
  113. package/src/adapters/thread/langchain/thread-manager.ts +3 -0
  114. package/src/lib/lifecycle.ts +11 -4
  115. package/src/lib/model/types.ts +10 -0
  116. package/src/lib/sandbox/manager.ts +26 -18
  117. package/src/lib/sandbox/types.ts +27 -7
  118. package/src/lib/session/session-edge-cases.integration.test.ts +265 -1
  119. package/src/lib/session/session.integration.test.ts +22 -1
  120. package/src/lib/session/session.ts +61 -7
  121. package/src/lib/session/types.ts +12 -0
  122. package/src/lib/subagent/subagent.integration.test.ts +100 -104
  123. package/src/lib/thread/manager.ts +18 -0
  124. package/src/lib/thread/proxy.ts +1 -0
  125. package/src/lib/thread/types.ts +9 -0
  126. package/src/lib/tool-router/index.ts +2 -0
  127. package/src/lib/tool-router/router-edge-cases.integration.test.ts +92 -0
  128. package/src/lib/tool-router/router.integration.test.ts +12 -0
  129. package/src/lib/tool-router/router.ts +89 -16
  130. package/src/lib/tool-router/types.ts +34 -1
  131. package/src/workflow.ts +2 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/lib/thread/manager.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":["Context","invokeGoogleGenAIModel"],"mappings":";;;;;AAEA,IAAM,kBAAA,GAAqB,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA;AAW1C,IAAM,wBAAA,GAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAYjC,SAAS,YAAA,CAAa,UAAkB,GAAA,EAAqB;AAC3D,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AAClC;AAMO,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;AAAA,GACF,GAAI,MAAA;AACJ,EAAA,MAAM,QAAA,GAAW,YAAA,CAAa,QAAA,EAAU,GAAG,CAAA;AAC3C,EAAA,MAAM,OAAA,GAAU,YAAA,CAAa,QAA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,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.cjs","sourcesContent":["import type { ThreadManagerConfig, BaseThreadManager } from \"./types\";\n\nconst THREAD_TTL_SECONDS = 60 * 60 * 24 * 90; // 90 days\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\nfunction getThreadKey(threadId: string, key: string): string {\n return `${key}:thread:${threadId}`;\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 } = config;\n const redisKey = getThreadKey(threadId, key);\n const metaKey = getThreadKey(threadId, `${key}:meta`);\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\", THREAD_TTL_SECONDS);\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 const dedupKey = getThreadKey(threadId, `dedup:${dedupId}`);\n await redis.eval(\n APPEND_IDEMPOTENT_SCRIPT,\n 2,\n dedupKey,\n redisKey,\n String(THREAD_TTL_SECONDS),\n ...messages.map(serialize)\n );\n } else {\n await redis.rpush(redisKey, ...messages.map(serialize));\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\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 forked = createThreadManager({\n ...config,\n threadId: newThreadId,\n });\n await forked.initialize();\n if (data.length > 0) {\n const newKey = getThreadKey(newThreadId, key);\n await redis.rpush(newKey, ...data);\n await redis.expire(newKey, THREAD_TTL_SECONDS);\n }\n return forked;\n },\n\n async delete(): Promise<void> {\n await redis.del(redisKey, metaKey);\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\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\nfunction 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 };\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 return Object.assign(base, helpers);\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 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 } = config;\n const { heartbeat, signal } = getActivityContext();\n\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n hooks,\n });\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 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 {\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 {\n createGoogleGenAIThreadManager,\n type GoogleGenAIContent,\n type GoogleGenAISystemContent,\n type GoogleGenAIThreadManagerHooks,\n} from \"./thread-manager\";\nimport { createGoogleGenAIModelInvoker } from \"./model-invoker\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\" as const;\n\nexport type GoogleGenAIThreadOps<TScope extends string = \"\"> =\n PrefixedThreadOps<\n ScopedPrefix<TScope, typeof ADAPTER_PREFIX>,\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\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 threadOps: ThreadOps<GoogleGenAIContent> = {\n async initializeThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 });\n await thread.fork(targetThreadId);\n },\n };\n\n function createActivities<S extends string = \"\">(\n scope?: S\n ): GoogleGenAIThreadOps<S> {\n const prefix = scope\n ? `${ADAPTER_PREFIX}${scope.charAt(0).toUpperCase()}${scope.slice(1)}`\n : ADAPTER_PREFIX;\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/lib/thread/manager.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":["Context","invokeGoogleGenAIModel"],"mappings":";;;;;AAEA,IAAM,kBAAA,GAAqB,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA;AAW1C,IAAM,wBAAA,GAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAYjC,SAAS,YAAA,CAAa,UAAkB,GAAA,EAAqB;AAC3D,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AAClC;AAMO,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;AAAA,GACF,GAAI,MAAA;AACJ,EAAA,MAAM,QAAA,GAAW,YAAA,CAAa,QAAA,EAAU,GAAG,CAAA;AAC3C,EAAA,MAAM,OAAA,GAAU,YAAA,CAAa,QAAA,EAAU,CAAA,EAAG,GAAG,CAAA,KAAA,CAAO,CAAA;AAEpD,EAAA,eAAe,kBAAA,GAAoC;AACjD,IAAA,MAAM,MAAA,GAAS,MAAM,KAAA,CAAM,MAAA,CAAO,OAAO,CAAA;AACzC,I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IACpB,WAAA,EAAa,CAAC,OAAA,KAAY;AAAA,GAC5B;AACF","file":"index.cjs","sourcesContent":["import type { ThreadManagerConfig, BaseThreadManager } from \"./types\";\n\nconst THREAD_TTL_SECONDS = 60 * 60 * 24 * 90; // 90 days\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\nfunction getThreadKey(threadId: string, key: string): string {\n return `${key}:thread:${threadId}`;\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 } = config;\n const redisKey = getThreadKey(threadId, key);\n const metaKey = getThreadKey(threadId, `${key}:meta`);\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\", THREAD_TTL_SECONDS);\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 const dedupKey = getThreadKey(threadId, `dedup:${dedupId}`);\n await redis.eval(\n APPEND_IDEMPOTENT_SCRIPT,\n 2,\n dedupKey,\n redisKey,\n String(THREAD_TTL_SECONDS),\n ...messages.map(serialize)\n );\n } else {\n await redis.rpush(redisKey, ...messages.map(serialize));\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\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 forked = createThreadManager({\n ...config,\n threadId: newThreadId,\n });\n await forked.initialize();\n if (data.length > 0) {\n const newKey = getThreadKey(newThreadId, key);\n await redis.rpush(newKey, ...data);\n await redis.expire(newKey, THREAD_TTL_SECONDS);\n }\n return forked;\n },\n\n async delete(): Promise<void> {\n await redis.del(redisKey, metaKey);\n },\n\n async length(): Promise<number> {\n await assertThreadExists();\n return redis.llen(redisKey);\n },\n\n async truncate(length: number): Promise<void> {\n await assertThreadExists();\n if (length <= 0) {\n await redis.del(redisKey);\n await redis.expire(metaKey, THREAD_TTL_SECONDS);\n } else {\n await redis.ltrim(redisKey, 0, length - 1);\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\n }\n // Dedup keys for removed messages are left to expire via their TTL.\n // Post-truncate appends use fresh ids so collisions do not occur in practice.\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\n/** Prepared payload ready to send to the Google GenAI API */\nexport interface GoogleGenAIInvocationPayload {\n contents: Content[];\n systemInstruction?: Part[];\n /** Number of stored messages loaded from Redis before preparation. */\n storedLength: number;\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\nfunction 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 };\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 storedLength: stored.length,\n };\n },\n };\n\n return Object.assign(base, helpers);\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 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 } = config;\n const { heartbeat, signal } = getActivityContext();\n\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n hooks,\n });\n const { contents, systemInstruction, storedLength } =\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 threadLengthAtCall: storedLength,\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 {\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 {\n createGoogleGenAIThreadManager,\n type GoogleGenAIContent,\n type GoogleGenAISystemContent,\n type GoogleGenAIThreadManagerHooks,\n} from \"./thread-manager\";\nimport { createGoogleGenAIModelInvoker } from \"./model-invoker\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\" as const;\n\nexport type GoogleGenAIThreadOps<TScope extends string = \"\"> =\n PrefixedThreadOps<\n ScopedPrefix<TScope, typeof ADAPTER_PREFIX>,\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\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 threadOps: ThreadOps<GoogleGenAIContent> = {\n async initializeThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 });\n await thread.fork(targetThreadId);\n },\n\n async truncateThread(\n threadId: string,\n length: number,\n threadKey?: string,\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\n await thread.truncate(length);\n },\n };\n\n function createActivities<S extends string = \"\">(\n scope?: S\n ): GoogleGenAIThreadOps<S> {\n const prefix = scope\n ? `${ADAPTER_PREFIX}${scope.charAt(0).toUpperCase()}${scope.slice(1)}`\n : ADAPTER_PREFIX;\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,14 +1,14 @@
1
- import { G as GoogleGenAIThreadManagerHooks } from '../../../activities-vkI4_3CC.cjs';
2
- export { a as GoogleGenAIAdapter, b as GoogleGenAIAdapterConfig, c as GoogleGenAIContent, d as GoogleGenAIInvocationPayload, e as GoogleGenAIThreadManager, f as GoogleGenAIThreadManagerConfig, g as GoogleGenAIThreadOps, h as GoogleGenAIToolResponse, S as StoredContent, i as createGoogleGenAIAdapter, j as createGoogleGenAIThreadManager } from '../../../activities-vkI4_3CC.cjs';
1
+ import { G as GoogleGenAIThreadManagerHooks } from '../../../activities-CDcwkRZs.cjs';
2
+ export { a as GoogleGenAIAdapter, b as GoogleGenAIAdapterConfig, c as GoogleGenAIContent, d as GoogleGenAIInvocationPayload, e as GoogleGenAIThreadManager, f as GoogleGenAIThreadManagerConfig, g as GoogleGenAIThreadOps, h as GoogleGenAIToolResponse, S as StoredContent, i as createGoogleGenAIAdapter, j as createGoogleGenAIThreadManager } from '../../../activities-CDcwkRZs.cjs';
3
3
  import Redis from 'ioredis';
4
4
  import { GoogleGenAI, Content } from '@google/genai';
5
- import { M as ModelInvokerConfig, A as AgentResponse } from '../../../types-BO7Yju20.cjs';
6
- import '../../../types-D08CXPh8.cjs';
5
+ import { M as ModelInvokerConfig, A as AgentResponse } from '../../../types-C06FwR96.cjs';
6
+ import '../../../types-BaOw4hKI.cjs';
7
7
  import '@temporalio/common';
8
8
  import '@temporalio/workflow';
9
9
  import '@temporalio/common/lib/interfaces';
10
10
  import 'zod';
11
- import '../../../types-tQL9njTu.cjs';
11
+ import '../../../types-yx0LzPGn.cjs';
12
12
 
13
13
  interface GoogleGenAIModelInvokerConfig {
14
14
  redis: Redis;
@@ -1,14 +1,14 @@
1
- import { G as GoogleGenAIThreadManagerHooks } from '../../../activities-Bb-nAjwQ.js';
2
- export { a as GoogleGenAIAdapter, b as GoogleGenAIAdapterConfig, c as GoogleGenAIContent, d as GoogleGenAIInvocationPayload, e as GoogleGenAIThreadManager, f as GoogleGenAIThreadManagerConfig, g as GoogleGenAIThreadOps, h as GoogleGenAIToolResponse, S as StoredContent, i as createGoogleGenAIAdapter, j as createGoogleGenAIThreadManager } from '../../../activities-Bb-nAjwQ.js';
1
+ import { G as GoogleGenAIThreadManagerHooks } from '../../../activities-BKhMtKDd.js';
2
+ export { a as GoogleGenAIAdapter, b as GoogleGenAIAdapterConfig, c as GoogleGenAIContent, d as GoogleGenAIInvocationPayload, e as GoogleGenAIThreadManager, f as GoogleGenAIThreadManagerConfig, g as GoogleGenAIThreadOps, h as GoogleGenAIToolResponse, S as StoredContent, i as createGoogleGenAIAdapter, j as createGoogleGenAIThreadManager } from '../../../activities-BKhMtKDd.js';
3
3
  import Redis from 'ioredis';
4
4
  import { GoogleGenAI, Content } from '@google/genai';
5
- import { M as ModelInvokerConfig, A as AgentResponse } from '../../../types-CPKDl-y_.js';
6
- import '../../../types-B37hKoWA.js';
5
+ import { M as ModelInvokerConfig, A as AgentResponse } from '../../../types-DNr31FzL.js';
6
+ import '../../../types-BH_IRryz.js';
7
7
  import '@temporalio/common';
8
8
  import '@temporalio/workflow';
9
9
  import '@temporalio/common/lib/interfaces';
10
10
  import 'zod';
11
- import '../../../types-tQL9njTu.js';
11
+ import '../../../types-yx0LzPGn.js';
12
12
 
13
13
  interface GoogleGenAIModelInvokerConfig {
14
14
  redis: Redis;
@@ -79,6 +79,20 @@ function createThreadManager(config) {
79
79
  },
80
80
  async delete() {
81
81
  await redis.del(redisKey, metaKey);
82
+ },
83
+ async length() {
84
+ await assertThreadExists();
85
+ return redis.llen(redisKey);
86
+ },
87
+ async truncate(length) {
88
+ await assertThreadExists();
89
+ if (length <= 0) {
90
+ await redis.del(redisKey);
91
+ await redis.expire(metaKey, THREAD_TTL_SECONDS);
92
+ } else {
93
+ await redis.ltrim(redisKey, 0, length - 1);
94
+ await redis.expire(redisKey, THREAD_TTL_SECONDS);
95
+ }
82
96
  }
83
97
  };
84
98
  }
@@ -179,7 +193,8 @@ function createGoogleGenAIThreadManager(config) {
179
193
  const contents = mergeConsecutiveContents(conversationContents);
180
194
  return {
181
195
  contents: onPreparedMessage ? contents.map((msg, i) => onPreparedMessage(msg, i, contents)) : contents,
182
- ...systemInstruction && systemInstruction.length > 0 ? { systemInstruction } : {}
196
+ ...systemInstruction && systemInstruction.length > 0 ? { systemInstruction } : {},
197
+ storedLength: stored.length
183
198
  };
184
199
  }
185
200
  };
@@ -217,7 +232,7 @@ function createGoogleGenAIModelInvoker({
217
232
  key: threadKey,
218
233
  hooks
219
234
  });
220
- const { contents, systemInstruction } = await thread.prepareForInvocation();
235
+ const { contents, systemInstruction, storedLength } = await thread.prepareForInvocation();
221
236
  const functionDeclarations = toFunctionDeclarations(state.tools);
222
237
  const tools = functionDeclarations.length > 0 ? [{ functionDeclarations }] : void 0;
223
238
  const stream = await client.models.generateContentStream({
@@ -252,7 +267,8 @@ function createGoogleGenAIModelInvoker({
252
267
  inputTokens: lastChunk.usageMetadata?.promptTokenCount,
253
268
  outputTokens: lastChunk.usageMetadata?.candidatesTokenCount,
254
269
  cachedReadTokens: lastChunk.usageMetadata?.cachedContentTokenCount
255
- }
270
+ },
271
+ threadLengthAtCall: storedLength
256
272
  };
257
273
  };
258
274
  }
@@ -330,6 +346,14 @@ function createGoogleGenAIAdapter(config) {
330
346
  key: threadKey
331
347
  });
332
348
  await thread.fork(targetThreadId);
349
+ },
350
+ async truncateThread(threadId, length, threadKey) {
351
+ const thread = createGoogleGenAIThreadManager({
352
+ redis,
353
+ threadId,
354
+ key: threadKey
355
+ });
356
+ await thread.truncate(length);
333
357
  }
334
358
  };
335
359
  function createActivities(scope) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/lib/thread/manager.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":";;;AAEA,IAAM,kBAAA,GAAqB,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA;AAW1C,IAAM,wBAAA,GAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAYjC,SAAS,YAAA,CAAa,UAAkB,GAAA,EAAqB;AAC3D,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AAClC;AAMO,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;AAAA,GACF,GAAI,MAAA;AACJ,EAAA,MAAM,QAAA,GAAW,YAAA,CAAa,QAAA,EAAU,GAAG,CAAA;AAC3C,EAAA,MAAM,OAAA,GAAU,YAAA,CAAa,QAAA,EAAU,CAAA,EAAG,GAAG,CAAA,KAAA,CAAO,CAAA;AAEpD,EAAA,eAAe,kBAAA,GAAoC;AACjD,IAAA,MAAM,MAAA,GAAS,MAAM,KAAA,CAAM,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,QAAA,EAAW,QAAQ,CAAA,QAAA,EAAW,GAAG,CAAA,gBAAA,CAAkB,CAAA;AAAA,IACrE;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,MAAM,UAAA,GAA4B;AAChC,MAAA,MAAM,KAAA,CAAM,I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,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":["import type { ThreadManagerConfig, BaseThreadManager } from \"./types\";\n\nconst THREAD_TTL_SECONDS = 60 * 60 * 24 * 90; // 90 days\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\nfunction getThreadKey(threadId: string, key: string): string {\n return `${key}:thread:${threadId}`;\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 } = config;\n const redisKey = getThreadKey(threadId, key);\n const metaKey = getThreadKey(threadId, `${key}:meta`);\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\", THREAD_TTL_SECONDS);\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 const dedupKey = getThreadKey(threadId, `dedup:${dedupId}`);\n await redis.eval(\n APPEND_IDEMPOTENT_SCRIPT,\n 2,\n dedupKey,\n redisKey,\n String(THREAD_TTL_SECONDS),\n ...messages.map(serialize)\n );\n } else {\n await redis.rpush(redisKey, ...messages.map(serialize));\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\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 forked = createThreadManager({\n ...config,\n threadId: newThreadId,\n });\n await forked.initialize();\n if (data.length > 0) {\n const newKey = getThreadKey(newThreadId, key);\n await redis.rpush(newKey, ...data);\n await redis.expire(newKey, THREAD_TTL_SECONDS);\n }\n return forked;\n },\n\n async delete(): Promise<void> {\n await redis.del(redisKey, metaKey);\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\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\nfunction 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 };\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 return Object.assign(base, helpers);\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 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 } = config;\n const { heartbeat, signal } = getActivityContext();\n\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n hooks,\n });\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 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 {\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 {\n createGoogleGenAIThreadManager,\n type GoogleGenAIContent,\n type GoogleGenAISystemContent,\n type GoogleGenAIThreadManagerHooks,\n} from \"./thread-manager\";\nimport { createGoogleGenAIModelInvoker } from \"./model-invoker\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\" as const;\n\nexport type GoogleGenAIThreadOps<TScope extends string = \"\"> =\n PrefixedThreadOps<\n ScopedPrefix<TScope, typeof ADAPTER_PREFIX>,\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\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 threadOps: ThreadOps<GoogleGenAIContent> = {\n async initializeThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 });\n await thread.fork(targetThreadId);\n },\n };\n\n function createActivities<S extends string = \"\">(\n scope?: S\n ): GoogleGenAIThreadOps<S> {\n const prefix = scope\n ? `${ADAPTER_PREFIX}${scope.charAt(0).toUpperCase()}${scope.slice(1)}`\n : ADAPTER_PREFIX;\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/lib/thread/manager.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":";;;AAEA,IAAM,kBAAA,GAAqB,EAAA,GAAK,EAAA,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MAAA,CAAO,CAAC,CAAA,CAAE,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":["import type { ThreadManagerConfig, BaseThreadManager } from \"./types\";\n\nconst THREAD_TTL_SECONDS = 60 * 60 * 24 * 90; // 90 days\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\nfunction getThreadKey(threadId: string, key: string): string {\n return `${key}:thread:${threadId}`;\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 } = config;\n const redisKey = getThreadKey(threadId, key);\n const metaKey = getThreadKey(threadId, `${key}:meta`);\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\", THREAD_TTL_SECONDS);\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 const dedupKey = getThreadKey(threadId, `dedup:${dedupId}`);\n await redis.eval(\n APPEND_IDEMPOTENT_SCRIPT,\n 2,\n dedupKey,\n redisKey,\n String(THREAD_TTL_SECONDS),\n ...messages.map(serialize)\n );\n } else {\n await redis.rpush(redisKey, ...messages.map(serialize));\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\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 forked = createThreadManager({\n ...config,\n threadId: newThreadId,\n });\n await forked.initialize();\n if (data.length > 0) {\n const newKey = getThreadKey(newThreadId, key);\n await redis.rpush(newKey, ...data);\n await redis.expire(newKey, THREAD_TTL_SECONDS);\n }\n return forked;\n },\n\n async delete(): Promise<void> {\n await redis.del(redisKey, metaKey);\n },\n\n async length(): Promise<number> {\n await assertThreadExists();\n return redis.llen(redisKey);\n },\n\n async truncate(length: number): Promise<void> {\n await assertThreadExists();\n if (length <= 0) {\n await redis.del(redisKey);\n await redis.expire(metaKey, THREAD_TTL_SECONDS);\n } else {\n await redis.ltrim(redisKey, 0, length - 1);\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\n }\n // Dedup keys for removed messages are left to expire via their TTL.\n // Post-truncate appends use fresh ids so collisions do not occur in practice.\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\n/** Prepared payload ready to send to the Google GenAI API */\nexport interface GoogleGenAIInvocationPayload {\n contents: Content[];\n systemInstruction?: Part[];\n /** Number of stored messages loaded from Redis before preparation. */\n storedLength: number;\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\nfunction 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 };\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 storedLength: stored.length,\n };\n },\n };\n\n return Object.assign(base, helpers);\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 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 } = config;\n const { heartbeat, signal } = getActivityContext();\n\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n hooks,\n });\n const { contents, systemInstruction, storedLength } =\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 threadLengthAtCall: storedLength,\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 {\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 {\n createGoogleGenAIThreadManager,\n type GoogleGenAIContent,\n type GoogleGenAISystemContent,\n type GoogleGenAIThreadManagerHooks,\n} from \"./thread-manager\";\nimport { createGoogleGenAIModelInvoker } from \"./model-invoker\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\" as const;\n\nexport type GoogleGenAIThreadOps<TScope extends string = \"\"> =\n PrefixedThreadOps<\n ScopedPrefix<TScope, typeof ADAPTER_PREFIX>,\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\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 threadOps: ThreadOps<GoogleGenAIContent> = {\n async initializeThread(\n threadId: string,\n threadKey?: string\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\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 });\n await thread.fork(targetThreadId);\n },\n\n async truncateThread(\n threadId: string,\n length: number,\n threadKey?: string,\n ): Promise<void> {\n const thread = createGoogleGenAIThreadManager({\n redis,\n threadId,\n key: threadKey,\n });\n await thread.truncate(length);\n },\n };\n\n function createActivities<S extends string = \"\">(\n scope?: S\n ): GoogleGenAIThreadOps<S> {\n const prefix = scope\n ? `${ADAPTER_PREFIX}${scope.charAt(0).toUpperCase()}${scope.slice(1)}`\n : ADAPTER_PREFIX;\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"]}
@@ -24,7 +24,8 @@ function createThreadOpsProxy(adapterPrefix, scope, options) {
24
24
  appendToolResult: acts[p("appendToolResult")],
25
25
  appendAgentMessage: acts[p("appendAgentMessage")],
26
26
  appendSystemMessage: acts[p("appendSystemMessage")],
27
- forkThread: acts[p("forkThread")]
27
+ forkThread: acts[p("forkThread")],
28
+ truncateThread: acts[p("truncateThread")]
28
29
  };
29
30
  }
30
31
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/lib/thread/proxy.ts","../../../../src/adapters/thread/google-genai/proxy.ts"],"names":["workflowInfo","proxyActivities"],"mappings":";;;;;AAwBO,SAAS,oBAAA,CACd,aAAA,EACA,KAAA,EACA,OAAA,EACiC;AACjC,EAAA,MAAM,aAAA,GAAgB,KAAA,IAASA,qBAAA,EAAa,CAAE,YAAA;AAG9C,EAAA,MAAM,IAAA,GAAOC,wBAAA;AAAA,IACX,OAAA,IAAW;AAAA,MACT,mBAAA,EAAqB,KAAA;AAAA,MACrB,KAAA,EAAO;AAAA,QACL,eAAA,EAAiB,CAAA;AAAA,QACjB,eAAA,EAAiB,IAAA;AAAA,QACjB,eAAA,EAAiB,KAAA;AAAA,QACjB,kBAAA,EAAoB;AAAA;AACtB;AACF,GACF;AAEA,EAAA,MAAM,MAAA,GAAS,CAAA,EAAG,aAAa,CAAA,EAAG,cAAc,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,EAAa,CAAA,EAAG,aAAA,CAAc,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAChG,EAAA,MAAM,IAAI,CAAC,GAAA,KACT,CAAA,EAAG,MAAM,GAAG,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,aAAa,CAAA,EAAG,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAExD,EAAA,OAAO;AAAA,IACL,gBAAA,EAAkB,IAAA,CAAK,CAAA,CAAE,kBAAkB,CAAC,CAAA;AAAA,IAC5C,kBAAA,EAAoB,IAAA,CAAK,CAAA,CAAE,oBAAoB,CAAC,CAAA;AAAA,IAChD,gBAAA,EAAkB,IAAA,CAAK,CAAA,CAAE,kBAAkB,CAAC,CAAA;AAAA,IAC5C,kBAAA,EAAoB,IAAA,CAAK,CAAA,CAAE,oBAAoB,CAAC,CAAA;AAAA,IAChD,mBAAA,EAAqB,IAAA,CAAK,CAAA,CAAE,qBAAqB,CAAC,CAAA;AAAA,IAClD,UAAA,EAAY,IAAA,CAAK,CAAA,CAAE,YAAY,CAAC;AAAA,GAClC;AACF;;;AC/BA,IAAM,cAAA,GAAiB,aAAA;AAEhB,SAAS,yBAAA,CACd,OACA,OAAA,EACqD;AACrD,EAAA,OAAO,oBAAA;AAAA,IACL,cAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF;AACF","file":"workflow.cjs","sourcesContent":["/**\n * Shared proxy helper for thread operations.\n *\n * Each adapter re-exports a thin wrapper that supplies its prefix and\n * casts the return type to carry the adapter's native content type.\n */\nimport {\n proxyActivities,\n workflowInfo,\n type ActivityInterfaceFor,\n} from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../session/types\";\n\n/**\n * Creates a workflow-safe Temporal activity proxy for {@link ThreadOps}.\n *\n * The proxy resolves activity names by combining the adapter prefix with\n * the workflow scope, so each adapter + workflow combination gets its own\n * namespace.\n *\n * @param adapterPrefix - Adapter identifier (e.g. \"anthropic\", \"googleGenAI\", \"langChain\")\n * @param scope - Optional workflow scope override. Defaults to `workflowInfo().workflowType`.\n * @param options - Optional Temporal `proxyActivities` options.\n */\nexport function createThreadOpsProxy(\n adapterPrefix: string,\n scope?: string,\n options?: Parameters<typeof proxyActivities>[0]\n): ActivityInterfaceFor<ThreadOps> {\n const resolvedScope = scope ?? workflowInfo().workflowType;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const acts = proxyActivities<Record<string, (...args: any[]) => any>>(\n options ?? {\n startToCloseTimeout: \"10s\",\n retry: {\n maximumAttempts: 6,\n initialInterval: \"5s\",\n maximumInterval: \"15m\",\n backoffCoefficient: 4,\n },\n }\n );\n\n const prefix = `${adapterPrefix}${resolvedScope.charAt(0).toUpperCase()}${resolvedScope.slice(1)}`;\n const p = (key: string): string =>\n `${prefix}${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n\n return {\n initializeThread: acts[p(\"initializeThread\")],\n appendHumanMessage: acts[p(\"appendHumanMessage\")],\n appendToolResult: acts[p(\"appendToolResult\")],\n appendAgentMessage: acts[p(\"appendAgentMessage\")],\n appendSystemMessage: acts[p(\"appendSystemMessage\")],\n forkThread: acts[p(\"forkThread\")],\n } as ActivityInterfaceFor<ThreadOps>;\n}\n","/**\n * Workflow-safe proxy for Google GenAI thread operations.\n *\n * Import this from `zeitlich/adapters/thread/google-genai/workflow`\n * in your Temporal workflow files.\n *\n * By default the scope is derived from `workflowInfo().workflowType`,\n * so activities are automatically namespaced per workflow.\n *\n * @example\n * ```typescript\n * import { proxyGoogleGenAIThreadOps } from 'zeitlich/adapters/thread/google-genai/workflow';\n *\n * // Auto-scoped to the current workflow name\n * const threadOps = proxyGoogleGenAIThreadOps();\n *\n * // Explicit scope override\n * const threadOps = proxyGoogleGenAIThreadOps(\"customScope\");\n * ```\n */\nimport { type ActivityInterfaceFor } from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../../../lib/session/types\";\nimport type { GoogleGenAIContent } from \"./thread-manager\";\nimport { createThreadOpsProxy } from \"../../../lib/thread/proxy\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\";\n\nexport function proxyGoogleGenAIThreadOps(\n scope?: string,\n options?: Parameters<typeof createThreadOpsProxy>[2]\n): ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>> {\n return createThreadOpsProxy(\n ADAPTER_PREFIX,\n scope,\n options\n ) as ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>>;\n}\n"]}
1
+ {"version":3,"sources":["../../../../src/lib/thread/proxy.ts","../../../../src/adapters/thread/google-genai/proxy.ts"],"names":["workflowInfo","proxyActivities"],"mappings":";;;;;AAwBO,SAAS,oBAAA,CACd,aAAA,EACA,KAAA,EACA,OAAA,EACiC;AACjC,EAAA,MAAM,aAAA,GAAgB,KAAA,IAASA,qBAAA,EAAa,CAAE,YAAA;AAG9C,EAAA,MAAM,IAAA,GAAOC,wBAAA;AAAA,IACX,OAAA,IAAW;AAAA,MACT,mBAAA,EAAqB,KAAA;AAAA,MACrB,KAAA,EAAO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thin wrapper that supplies its prefix and\n * casts the return type to carry the adapter's native content type.\n */\nimport {\n proxyActivities,\n workflowInfo,\n type ActivityInterfaceFor,\n} from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../session/types\";\n\n/**\n * Creates a workflow-safe Temporal activity proxy for {@link ThreadOps}.\n *\n * The proxy resolves activity names by combining the adapter prefix with\n * the workflow scope, so each adapter + workflow combination gets its own\n * namespace.\n *\n * @param adapterPrefix - Adapter identifier (e.g. \"anthropic\", \"googleGenAI\", \"langChain\")\n * @param scope - Optional workflow scope override. Defaults to `workflowInfo().workflowType`.\n * @param options - Optional Temporal `proxyActivities` options.\n */\nexport function createThreadOpsProxy(\n adapterPrefix: string,\n scope?: string,\n options?: Parameters<typeof proxyActivities>[0]\n): ActivityInterfaceFor<ThreadOps> {\n const resolvedScope = scope ?? workflowInfo().workflowType;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const acts = proxyActivities<Record<string, (...args: any[]) => any>>(\n options ?? {\n startToCloseTimeout: \"10s\",\n retry: {\n maximumAttempts: 6,\n initialInterval: \"5s\",\n maximumInterval: \"15m\",\n backoffCoefficient: 4,\n },\n }\n );\n\n const prefix = `${adapterPrefix}${resolvedScope.charAt(0).toUpperCase()}${resolvedScope.slice(1)}`;\n const p = (key: string): string =>\n `${prefix}${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n\n return {\n initializeThread: acts[p(\"initializeThread\")],\n appendHumanMessage: acts[p(\"appendHumanMessage\")],\n appendToolResult: acts[p(\"appendToolResult\")],\n appendAgentMessage: acts[p(\"appendAgentMessage\")],\n appendSystemMessage: acts[p(\"appendSystemMessage\")],\n forkThread: acts[p(\"forkThread\")],\n truncateThread: acts[p(\"truncateThread\")],\n } as ActivityInterfaceFor<ThreadOps>;\n}\n","/**\n * Workflow-safe proxy for Google GenAI thread operations.\n *\n * Import this from `zeitlich/adapters/thread/google-genai/workflow`\n * in your Temporal workflow files.\n *\n * By default the scope is derived from `workflowInfo().workflowType`,\n * so activities are automatically namespaced per workflow.\n *\n * @example\n * ```typescript\n * import { proxyGoogleGenAIThreadOps } from 'zeitlich/adapters/thread/google-genai/workflow';\n *\n * // Auto-scoped to the current workflow name\n * const threadOps = proxyGoogleGenAIThreadOps();\n *\n * // Explicit scope override\n * const threadOps = proxyGoogleGenAIThreadOps(\"customScope\");\n * ```\n */\nimport { type ActivityInterfaceFor } from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../../../lib/session/types\";\nimport type { GoogleGenAIContent } from \"./thread-manager\";\nimport { createThreadOpsProxy } from \"../../../lib/thread/proxy\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\";\n\nexport function proxyGoogleGenAIThreadOps(\n scope?: string,\n options?: Parameters<typeof createThreadOpsProxy>[2]\n): ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>> {\n return createThreadOpsProxy(\n ADAPTER_PREFIX,\n scope,\n options\n ) as ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>>;\n}\n"]}
@@ -1,14 +1,14 @@
1
1
  import { ActivityInterfaceFor } from '@temporalio/workflow';
2
- import { T as ThreadOps } from '../../../types-BO7Yju20.cjs';
3
- import { c as GoogleGenAIContent } from '../../../activities-vkI4_3CC.cjs';
4
- import { c as createThreadOpsProxy } from '../../../proxy-DEtowJyd.cjs';
2
+ import { T as ThreadOps } from '../../../types-C06FwR96.cjs';
3
+ import { c as GoogleGenAIContent } from '../../../activities-CDcwkRZs.cjs';
4
+ import { c as createThreadOpsProxy } from '../../../proxy-D_3x7RN4.cjs';
5
5
  import '@temporalio/common';
6
6
  import '@temporalio/common/lib/interfaces';
7
7
  import 'zod';
8
- import '../../../types-tQL9njTu.cjs';
8
+ import '../../../types-yx0LzPGn.cjs';
9
9
  import 'ioredis';
10
10
  import '@google/genai';
11
- import '../../../types-D08CXPh8.cjs';
11
+ import '../../../types-BaOw4hKI.cjs';
12
12
 
13
13
  /**
14
14
  * Workflow-safe proxy for Google GenAI thread operations.
@@ -1,14 +1,14 @@
1
1
  import { ActivityInterfaceFor } from '@temporalio/workflow';
2
- import { T as ThreadOps } from '../../../types-CPKDl-y_.js';
3
- import { c as GoogleGenAIContent } from '../../../activities-Bb-nAjwQ.js';
4
- import { c as createThreadOpsProxy } from '../../../proxy-0smGKvx8.js';
2
+ import { T as ThreadOps } from '../../../types-DNr31FzL.js';
3
+ import { c as GoogleGenAIContent } from '../../../activities-BKhMtKDd.js';
4
+ import { c as createThreadOpsProxy } from '../../../proxy-CUlKSvZS.js';
5
5
  import '@temporalio/common';
6
6
  import '@temporalio/common/lib/interfaces';
7
7
  import 'zod';
8
- import '../../../types-tQL9njTu.js';
8
+ import '../../../types-yx0LzPGn.js';
9
9
  import 'ioredis';
10
10
  import '@google/genai';
11
- import '../../../types-B37hKoWA.js';
11
+ import '../../../types-BH_IRryz.js';
12
12
 
13
13
  /**
14
14
  * Workflow-safe proxy for Google GenAI thread operations.
@@ -22,7 +22,8 @@ function createThreadOpsProxy(adapterPrefix, scope, options) {
22
22
  appendToolResult: acts[p("appendToolResult")],
23
23
  appendAgentMessage: acts[p("appendAgentMessage")],
24
24
  appendSystemMessage: acts[p("appendSystemMessage")],
25
- forkThread: acts[p("forkThread")]
25
+ forkThread: acts[p("forkThread")],
26
+ truncateThread: acts[p("truncateThread")]
26
27
  };
27
28
  }
28
29
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/lib/thread/proxy.ts","../../../../src/adapters/thread/google-genai/proxy.ts"],"names":[],"mappings":";;;AAwBO,SAAS,oBAAA,CACd,aAAA,EACA,KAAA,EACA,OAAA,EACiC;AACjC,EAAA,MAAM,aAAA,GAAgB,KAAA,IAAS,YAAA,EAAa,CAAE,YAAA;AAG9C,EAAA,MAAM,IAAA,GAAO,eAAA;AAAA,IACX,OAAA,IAAW;AAAA,MACT,mBAAA,EAAqB,KAAA;AAAA,MACrB,KAAA,EAAO;AAAA,QACL,eAAA,EAAiB,CAAA;AAAA,QACjB,eAAA,EAAiB,IAAA;AAAA,QACjB,eAAA,EAAiB,KAAA;AAAA,QACjB,kBAAA,EAAoB;AAAA;AACtB;AACF,GACF;AAEA,EAAA,MAAM,MAAA,GAAS,CAAA,EAAG,aAAa,CAAA,EAAG,cAAc,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,EAAa,CAAA,EAAG,aAAA,CAAc,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAChG,EAAA,MAAM,IAAI,CAAC,GAAA,KACT,CAAA,EAAG,MAAM,GAAG,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,aAAa,CAAA,EAAG,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAExD,EAAA,OAAO;AAAA,IACL,gBAAA,EAAkB,IAAA,CAAK,CAAA,CAAE,kBAAkB,CAAC,CAAA;AAAA,IAC5C,kBAAA,EAAoB,IAAA,CAAK,CAAA,CAAE,oBAAoB,CAAC,CAAA;AAAA,IAChD,gBAAA,EAAkB,IAAA,CAAK,CAAA,CAAE,kBAAkB,CAAC,CAAA;AAAA,IAC5C,kBAAA,EAAoB,IAAA,CAAK,CAAA,CAAE,oBAAoB,CAAC,CAAA;AAAA,IAChD,mBAAA,EAAqB,IAAA,CAAK,CAAA,CAAE,qBAAqB,CAAC,CAAA;AAAA,IAClD,UAAA,EAAY,IAAA,CAAK,CAAA,CAAE,YAAY,CAAC;AAAA,GAClC;AACF;;;AC/BA,IAAM,cAAA,GAAiB,aAAA;AAEhB,SAAS,yBAAA,CACd,OACA,OAAA,EACqD;AACrD,EAAA,OAAO,oBAAA;AAAA,IACL,cAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF;AACF","file":"workflow.js","sourcesContent":["/**\n * Shared proxy helper for thread operations.\n *\n * Each adapter re-exports a thin wrapper that supplies its prefix and\n * casts the return type to carry the adapter's native content type.\n */\nimport {\n proxyActivities,\n workflowInfo,\n type ActivityInterfaceFor,\n} from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../session/types\";\n\n/**\n * Creates a workflow-safe Temporal activity proxy for {@link ThreadOps}.\n *\n * The proxy resolves activity names by combining the adapter prefix with\n * the workflow scope, so each adapter + workflow combination gets its own\n * namespace.\n *\n * @param adapterPrefix - Adapter identifier (e.g. \"anthropic\", \"googleGenAI\", \"langChain\")\n * @param scope - Optional workflow scope override. Defaults to `workflowInfo().workflowType`.\n * @param options - Optional Temporal `proxyActivities` options.\n */\nexport function createThreadOpsProxy(\n adapterPrefix: string,\n scope?: string,\n options?: Parameters<typeof proxyActivities>[0]\n): ActivityInterfaceFor<ThreadOps> {\n const resolvedScope = scope ?? workflowInfo().workflowType;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const acts = proxyActivities<Record<string, (...args: any[]) => any>>(\n options ?? {\n startToCloseTimeout: \"10s\",\n retry: {\n maximumAttempts: 6,\n initialInterval: \"5s\",\n maximumInterval: \"15m\",\n backoffCoefficient: 4,\n },\n }\n );\n\n const prefix = `${adapterPrefix}${resolvedScope.charAt(0).toUpperCase()}${resolvedScope.slice(1)}`;\n const p = (key: string): string =>\n `${prefix}${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n\n return {\n initializeThread: acts[p(\"initializeThread\")],\n appendHumanMessage: acts[p(\"appendHumanMessage\")],\n appendToolResult: acts[p(\"appendToolResult\")],\n appendAgentMessage: acts[p(\"appendAgentMessage\")],\n appendSystemMessage: acts[p(\"appendSystemMessage\")],\n forkThread: acts[p(\"forkThread\")],\n } as ActivityInterfaceFor<ThreadOps>;\n}\n","/**\n * Workflow-safe proxy for Google GenAI thread operations.\n *\n * Import this from `zeitlich/adapters/thread/google-genai/workflow`\n * in your Temporal workflow files.\n *\n * By default the scope is derived from `workflowInfo().workflowType`,\n * so activities are automatically namespaced per workflow.\n *\n * @example\n * ```typescript\n * import { proxyGoogleGenAIThreadOps } from 'zeitlich/adapters/thread/google-genai/workflow';\n *\n * // Auto-scoped to the current workflow name\n * const threadOps = proxyGoogleGenAIThreadOps();\n *\n * // Explicit scope override\n * const threadOps = proxyGoogleGenAIThreadOps(\"customScope\");\n * ```\n */\nimport { type ActivityInterfaceFor } from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../../../lib/session/types\";\nimport type { GoogleGenAIContent } from \"./thread-manager\";\nimport { createThreadOpsProxy } from \"../../../lib/thread/proxy\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\";\n\nexport function proxyGoogleGenAIThreadOps(\n scope?: string,\n options?: Parameters<typeof createThreadOpsProxy>[2]\n): ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>> {\n return createThreadOpsProxy(\n ADAPTER_PREFIX,\n scope,\n options\n ) as ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>>;\n}\n"]}
1
+ {"version":3,"sources":["../../../../src/lib/thread/proxy.ts","../../../../src/adapters/thread/google-genai/proxy.ts"],"names":[],"mappings":";;;AAwBO,SAAS,oBAAA,CACd,aAAA,EACA,KAAA,EACA,OAAA,EACiC;AACjC,EAAA,MAAM,aAAA,GAAgB,KAAA,IAAS,YAAA,EAAa,CAAE,YAAA;AAG9C,EAAA,MAAM,IAAA,GAAO,eAAA;AAAA,IACX,OAAA,IAAW;AAAA,MACT,mBAAA,EAAqB,KAAA;AAAA,MACrB,KAAA,EAAO;AAAA,QACL,eAAA,EAAiB,CAAA;AAAA,QACjB,eAAA,EAAiB,IAAA;AAAA,QACjB,eAAA,EAAiB,KAAA;AAAA,QACjB,kBAAA,EAAoB;AAAA;AACtB;AACF,GACF;AAEA,EAAA,MAAM,MAAA,GAAS,CAAA,EAAG,aAAa,CAAA,EAAG,cAAc,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,EAAa,CAAA,EAAG,aAAA,CAAc,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAChG,EAAA,MAAM,IAAI,CAAC,GAAA,KACT,CAAA,EAAG,MAAM,GAAG,GAAA,CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,aAAa,CAAA,EAAG,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAExD,EAAA,OAAO;AAAA,IACL,gBAAA,EAAkB,IAAA,CAAK,CAAA,CAAE,kBAAkB,CAAC,CAAA;AAAA,IAC5C,kBAAA,EAAoB,IAAA,CAAK,CAAA,CAAE,oBAAoB,CAAC,CAAA;AAAA,IAChD,gBAAA,EAAkB,IAAA,CAAK,CAAA,CAAE,kBAAkB,CAAC,CAAA;AAAA,IAC5C,kBAAA,EAAoB,IAAA,CAAK,CAAA,CAAE,oBAAoB,CAAC,CAAA;AAAA,IAChD,mBAAA,EAAqB,IAAA,CAAK,CAAA,CAAE,qBAAqB,CAAC,CAAA;AAAA,IAClD,UAAA,EAAY,IAAA,CAAK,CAAA,CAAE,YAAY,CAAC,CAAA;AAAA,IAChC,cAAA,EAAgB,IAAA,CAAK,CAAA,CAAE,gBAAgB,CAAC;AAAA,GAC1C;AACF;;;AChCA,IAAM,cAAA,GAAiB,aAAA;AAEhB,SAAS,yBAAA,CACd,OACA,OAAA,EACqD;AACrD,EAAA,OAAO,oBAAA;AAAA,IACL,cAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF;AACF","file":"workflow.js","sourcesContent":["/**\n * Shared proxy helper for thread operations.\n *\n * Each adapter re-exports a thin wrapper that supplies its prefix and\n * casts the return type to carry the adapter's native content type.\n */\nimport {\n proxyActivities,\n workflowInfo,\n type ActivityInterfaceFor,\n} from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../session/types\";\n\n/**\n * Creates a workflow-safe Temporal activity proxy for {@link ThreadOps}.\n *\n * The proxy resolves activity names by combining the adapter prefix with\n * the workflow scope, so each adapter + workflow combination gets its own\n * namespace.\n *\n * @param adapterPrefix - Adapter identifier (e.g. \"anthropic\", \"googleGenAI\", \"langChain\")\n * @param scope - Optional workflow scope override. Defaults to `workflowInfo().workflowType`.\n * @param options - Optional Temporal `proxyActivities` options.\n */\nexport function createThreadOpsProxy(\n adapterPrefix: string,\n scope?: string,\n options?: Parameters<typeof proxyActivities>[0]\n): ActivityInterfaceFor<ThreadOps> {\n const resolvedScope = scope ?? workflowInfo().workflowType;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const acts = proxyActivities<Record<string, (...args: any[]) => any>>(\n options ?? {\n startToCloseTimeout: \"10s\",\n retry: {\n maximumAttempts: 6,\n initialInterval: \"5s\",\n maximumInterval: \"15m\",\n backoffCoefficient: 4,\n },\n }\n );\n\n const prefix = `${adapterPrefix}${resolvedScope.charAt(0).toUpperCase()}${resolvedScope.slice(1)}`;\n const p = (key: string): string =>\n `${prefix}${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n\n return {\n initializeThread: acts[p(\"initializeThread\")],\n appendHumanMessage: acts[p(\"appendHumanMessage\")],\n appendToolResult: acts[p(\"appendToolResult\")],\n appendAgentMessage: acts[p(\"appendAgentMessage\")],\n appendSystemMessage: acts[p(\"appendSystemMessage\")],\n forkThread: acts[p(\"forkThread\")],\n truncateThread: acts[p(\"truncateThread\")],\n } as ActivityInterfaceFor<ThreadOps>;\n}\n","/**\n * Workflow-safe proxy for Google GenAI thread operations.\n *\n * Import this from `zeitlich/adapters/thread/google-genai/workflow`\n * in your Temporal workflow files.\n *\n * By default the scope is derived from `workflowInfo().workflowType`,\n * so activities are automatically namespaced per workflow.\n *\n * @example\n * ```typescript\n * import { proxyGoogleGenAIThreadOps } from 'zeitlich/adapters/thread/google-genai/workflow';\n *\n * // Auto-scoped to the current workflow name\n * const threadOps = proxyGoogleGenAIThreadOps();\n *\n * // Explicit scope override\n * const threadOps = proxyGoogleGenAIThreadOps(\"customScope\");\n * ```\n */\nimport { type ActivityInterfaceFor } from \"@temporalio/workflow\";\nimport type { ThreadOps } from \"../../../lib/session/types\";\nimport type { GoogleGenAIContent } from \"./thread-manager\";\nimport { createThreadOpsProxy } from \"../../../lib/thread/proxy\";\n\nconst ADAPTER_PREFIX = \"googleGenAI\";\n\nexport function proxyGoogleGenAIThreadOps(\n scope?: string,\n options?: Parameters<typeof createThreadOpsProxy>[2]\n): ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>> {\n return createThreadOpsProxy(\n ADAPTER_PREFIX,\n scope,\n options\n ) as ActivityInterfaceFor<ThreadOps<GoogleGenAIContent>>;\n}\n"]}