zeitlich 0.2.25 → 0.2.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activities-DE3_q9yq.d.ts +140 -0
- package/dist/activities-p8PDlRIK.d.cts +140 -0
- package/dist/adapters/sandbox/virtual/index.cjs.map +1 -1
- package/dist/adapters/sandbox/virtual/index.d.cts +8 -7
- package/dist/adapters/sandbox/virtual/index.d.ts +8 -7
- package/dist/adapters/sandbox/virtual/index.js.map +1 -1
- package/dist/adapters/sandbox/virtual/workflow.d.cts +3 -2
- package/dist/adapters/sandbox/virtual/workflow.d.ts +3 -2
- package/dist/adapters/thread/anthropic/index.cjs +363 -0
- package/dist/adapters/thread/anthropic/index.cjs.map +1 -0
- package/dist/adapters/thread/anthropic/index.d.cts +151 -0
- package/dist/adapters/thread/anthropic/index.d.ts +151 -0
- package/dist/adapters/thread/anthropic/index.js +358 -0
- package/dist/adapters/thread/anthropic/index.js.map +1 -0
- package/dist/adapters/thread/anthropic/workflow.cjs +38 -0
- package/dist/adapters/thread/anthropic/workflow.cjs.map +1 -0
- package/dist/adapters/thread/anthropic/workflow.d.cts +37 -0
- package/dist/adapters/thread/anthropic/workflow.d.ts +37 -0
- package/dist/adapters/thread/anthropic/workflow.js +36 -0
- package/dist/adapters/thread/anthropic/workflow.js.map +1 -0
- package/dist/adapters/thread/google-genai/index.cjs +102 -99
- package/dist/adapters/thread/google-genai/index.cjs.map +1 -1
- package/dist/adapters/thread/google-genai/index.d.cts +14 -113
- package/dist/adapters/thread/google-genai/index.d.ts +14 -113
- package/dist/adapters/thread/google-genai/index.js +103 -99
- package/dist/adapters/thread/google-genai/index.js.map +1 -1
- package/dist/adapters/thread/google-genai/workflow.cjs +9 -4
- package/dist/adapters/thread/google-genai/workflow.cjs.map +1 -1
- package/dist/adapters/thread/google-genai/workflow.d.cts +10 -5
- package/dist/adapters/thread/google-genai/workflow.d.ts +10 -5
- package/dist/adapters/thread/google-genai/workflow.js +9 -4
- package/dist/adapters/thread/google-genai/workflow.js.map +1 -1
- package/dist/adapters/thread/langchain/index.cjs +73 -63
- package/dist/adapters/thread/langchain/index.cjs.map +1 -1
- package/dist/adapters/thread/langchain/index.d.cts +39 -40
- package/dist/adapters/thread/langchain/index.d.ts +39 -40
- package/dist/adapters/thread/langchain/index.js +73 -64
- package/dist/adapters/thread/langchain/index.js.map +1 -1
- package/dist/adapters/thread/langchain/workflow.cjs +9 -4
- package/dist/adapters/thread/langchain/workflow.cjs.map +1 -1
- package/dist/adapters/thread/langchain/workflow.d.cts +10 -5
- package/dist/adapters/thread/langchain/workflow.d.ts +10 -5
- package/dist/adapters/thread/langchain/workflow.js +9 -4
- package/dist/adapters/thread/langchain/workflow.js.map +1 -1
- package/dist/index.cjs +27 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -12
- package/dist/index.d.ts +13 -12
- package/dist/index.js +28 -11
- package/dist/index.js.map +1 -1
- package/dist/proxy-BK1ydQt0.d.ts +24 -0
- package/dist/proxy-BMAsMHdp.d.cts +24 -0
- package/dist/{queries-DwBe2CAA.d.ts → queries-BCgJ9Sr5.d.ts} +1 -1
- package/dist/{queries-BYGBImeC.d.cts → queries-DwnE2bu3.d.cts} +1 -1
- package/dist/thread-manager-Bh9x847n.d.ts +31 -0
- package/dist/thread-manager-BlHua5_v.d.cts +39 -0
- package/dist/thread-manager-Bz8txKKj.d.cts +31 -0
- package/dist/thread-manager-dzaJHQEA.d.ts +39 -0
- package/dist/types-BfIQABzu.d.cts +73 -0
- package/dist/types-CIkYBoF8.d.ts +73 -0
- package/dist/{types-hmferhc2.d.ts → types-CvJyXDYt.d.ts} +44 -123
- package/dist/{types-LVKmCNds.d.ts → types-DFUNSYbj.d.ts} +1 -1
- package/dist/{types-Bf8KV0Ci.d.cts → types-DRnz-OZp.d.cts} +1 -1
- package/dist/{types-7PeMi1bD.d.cts → types-DSOefLpY.d.cts} +44 -123
- package/dist/{types-D_igp10o.d.cts → types-mCVxKIZb.d.cts} +233 -137
- package/dist/{types-D_igp10o.d.ts → types-mCVxKIZb.d.ts} +233 -137
- package/dist/workflow.cjs +25 -9
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +11 -11
- package/dist/workflow.d.ts +11 -11
- package/dist/workflow.js +26 -10
- package/dist/workflow.js.map +1 -1
- package/package.json +26 -1
- package/src/adapters/sandbox/virtual/with-virtual-sandbox.ts +8 -3
- package/src/adapters/thread/anthropic/activities.ts +226 -0
- package/src/adapters/thread/anthropic/index.ts +44 -0
- package/src/adapters/thread/anthropic/model-invoker.ts +129 -0
- package/src/adapters/thread/anthropic/proxy.ts +33 -0
- package/src/adapters/thread/anthropic/thread-manager.test.ts +137 -0
- package/src/adapters/thread/anthropic/thread-manager.ts +202 -0
- package/src/adapters/thread/google-genai/activities.ts +110 -33
- package/src/adapters/thread/google-genai/index.ts +3 -1
- package/src/adapters/thread/google-genai/model-invoker.ts +13 -42
- package/src/adapters/thread/google-genai/proxy.ts +6 -34
- package/src/adapters/thread/google-genai/thread-manager.test.ts +159 -0
- package/src/adapters/thread/google-genai/thread-manager.ts +96 -105
- package/src/adapters/thread/langchain/activities.ts +56 -21
- package/src/adapters/thread/langchain/hooks.ts +37 -0
- package/src/adapters/thread/langchain/index.ts +6 -1
- package/src/adapters/thread/langchain/model-invoker.ts +13 -12
- package/src/adapters/thread/langchain/proxy.ts +6 -34
- package/src/adapters/thread/langchain/thread-manager.test.ts +144 -0
- package/src/adapters/thread/langchain/thread-manager.ts +55 -98
- package/src/index.ts +5 -1
- package/src/lib/activity.ts +4 -3
- package/src/lib/hooks/types.ts +12 -12
- package/src/lib/model/types.ts +2 -0
- package/src/lib/session/session-edge-cases.integration.test.ts +24 -6
- package/src/lib/session/session.ts +18 -14
- package/src/lib/session/types.ts +31 -14
- package/src/lib/subagent/handler.ts +15 -8
- package/src/lib/subagent/types.ts +3 -2
- package/src/lib/thread/index.ts +3 -0
- package/src/lib/thread/manager.ts +4 -7
- package/src/lib/thread/proxy.ts +57 -0
- package/src/lib/thread/types.ts +44 -0
- package/src/lib/tool-router/auto-append-sandbox.integration.test.ts +54 -0
- package/src/lib/tool-router/auto-append.ts +5 -2
- package/src/lib/tool-router/router-edge-cases.integration.test.ts +9 -5
- package/src/lib/tool-router/router.ts +13 -7
- package/src/lib/tool-router/types.ts +20 -13
- package/src/lib/tool-router/with-sandbox.ts +4 -3
- package/src/lib/types.ts +7 -14
- package/src/workflow.ts +0 -4
- package/tsup.config.ts +5 -0
- package/dist/types-35POpVfa.d.cts +0 -40
- package/dist/types-35POpVfa.d.ts +0 -40
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import Redis from 'ioredis';
|
|
2
|
+
import { Part, Content, GoogleGenAI } from '@google/genai';
|
|
3
|
+
import { R as RouterContext, T as ToolHandlerResponse, A as ActivityToolHandler } from './types-mCVxKIZb.js';
|
|
4
|
+
import { a as ModelInvoker, P as PrefixedThreadOps, S as ScopedPrefix } from './types-CvJyXDYt.js';
|
|
5
|
+
import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-CIkYBoF8.js';
|
|
6
|
+
|
|
7
|
+
/** SDK-native content type for Google GenAI human messages */
|
|
8
|
+
type GoogleGenAIContent = string | Part[];
|
|
9
|
+
/** A Content with a unique ID for idempotent Redis storage */
|
|
10
|
+
interface StoredContent {
|
|
11
|
+
id: string;
|
|
12
|
+
content: Content;
|
|
13
|
+
}
|
|
14
|
+
type GoogleGenAIThreadManagerHooks = ThreadManagerHooks<StoredContent, Content>;
|
|
15
|
+
interface GoogleGenAIThreadManagerConfig {
|
|
16
|
+
redis: Redis;
|
|
17
|
+
threadId: string;
|
|
18
|
+
/** Thread key, defaults to 'messages' */
|
|
19
|
+
key?: string;
|
|
20
|
+
hooks?: GoogleGenAIThreadManagerHooks;
|
|
21
|
+
}
|
|
22
|
+
/** Prepared payload ready to send to the Google GenAI API */
|
|
23
|
+
interface GoogleGenAIInvocationPayload {
|
|
24
|
+
contents: Content[];
|
|
25
|
+
systemInstruction?: string;
|
|
26
|
+
}
|
|
27
|
+
/** Thread manager with Google GenAI Content convenience helpers */
|
|
28
|
+
interface GoogleGenAIThreadManager extends ProviderThreadManager<StoredContent, GoogleGenAIContent, GoogleGenAIToolResponse> {
|
|
29
|
+
appendModelContent(id: string, parts: Part[]): Promise<void>;
|
|
30
|
+
prepareForInvocation(): Promise<GoogleGenAIInvocationPayload>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a Google GenAI-specific thread manager that stores StoredContent
|
|
34
|
+
* instances in Redis and provides convenience helpers for creating and
|
|
35
|
+
* appending typed Content messages.
|
|
36
|
+
*/
|
|
37
|
+
declare function createGoogleGenAIThreadManager(config: GoogleGenAIThreadManagerConfig): GoogleGenAIThreadManager;
|
|
38
|
+
|
|
39
|
+
declare const ADAPTER_PREFIX: "googleGenAI";
|
|
40
|
+
type GoogleGenAIThreadOps<TScope extends string = ""> = PrefixedThreadOps<ScopedPrefix<TScope, typeof ADAPTER_PREFIX>, GoogleGenAIContent>;
|
|
41
|
+
interface GoogleGenAIAdapterConfig {
|
|
42
|
+
redis: Redis;
|
|
43
|
+
client?: GoogleGenAI;
|
|
44
|
+
/** Default model name (e.g. 'gemini-2.5-flash'). If omitted, use `createModelInvoker()` */
|
|
45
|
+
model?: string;
|
|
46
|
+
hooks?: GoogleGenAIThreadManagerHooks;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Tool response type accepted by the Google GenAI adapter.
|
|
50
|
+
*
|
|
51
|
+
* Handlers can return:
|
|
52
|
+
* - **`string`** — plain text, wrapped in a `functionResponse` part.
|
|
53
|
+
* - **`Record<string, unknown>`** — structured object used as `functionResponse.response`.
|
|
54
|
+
* - **`Part[]`** — pre-built parts used directly as `Content.parts`.
|
|
55
|
+
* The handler is responsible for building correct Part objects (e.g. `functionResponse`,
|
|
56
|
+
* `inlineData`, `text`). Use `context.toolCallId` and `context.toolName` to construct
|
|
57
|
+
* `functionResponse` parts.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* adapter.wrapHandler(async (args, ctx) => ({
|
|
62
|
+
* toolResponse: [
|
|
63
|
+
* { functionResponse: { id: ctx.toolCallId, name: ctx.toolName, response: { result: "done" } } },
|
|
64
|
+
* { inlineData: { data: base64, mimeType: "image/png" } },
|
|
65
|
+
* ],
|
|
66
|
+
* data: null,
|
|
67
|
+
* }));
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
type GoogleGenAIToolResponse = string | Record<string, unknown> | Part[];
|
|
71
|
+
interface GoogleGenAIAdapter {
|
|
72
|
+
/** Model invoker using the default model (only available when `model` was provided) */
|
|
73
|
+
invoker: ModelInvoker<Content>;
|
|
74
|
+
/** Create an invoker for a specific model name (for multi-model setups) */
|
|
75
|
+
createModelInvoker(model: string, client: GoogleGenAI): ModelInvoker<Content>;
|
|
76
|
+
/**
|
|
77
|
+
* Create prefixed thread activities for registration on the worker.
|
|
78
|
+
*
|
|
79
|
+
* @param scope - Workflow name appended to the adapter prefix.
|
|
80
|
+
* Use different scopes for the main agent vs subagents to avoid collisions.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* adapter.createActivities("codingAgent")
|
|
85
|
+
* // → { googleGenAICodingAgentInitializeThread, googleGenAICodingAgentAppendHumanMessage, … }
|
|
86
|
+
*
|
|
87
|
+
* adapter.createActivities("researchAgent")
|
|
88
|
+
* // → { googleGenAIResearchAgentInitializeThread, … }
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
createActivities<S extends string = "">(scope?: S): GoogleGenAIThreadOps<S>;
|
|
92
|
+
/**
|
|
93
|
+
* Identity wrapper that types a tool handler for this adapter.
|
|
94
|
+
* Constrains `toolResponse` to {@link GoogleGenAIToolResponse}.
|
|
95
|
+
*/
|
|
96
|
+
wrapHandler<TArgs, TResult, TContext extends RouterContext = RouterContext>(handler: (args: TArgs, context: TContext) => Promise<ToolHandlerResponse<TResult, GoogleGenAIToolResponse>>): ActivityToolHandler<TArgs, TResult, TContext, GoogleGenAIToolResponse>;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Creates a Google GenAI adapter that bundles thread operations and model
|
|
100
|
+
* invocation using the `@google/genai` SDK.
|
|
101
|
+
*
|
|
102
|
+
* Use `createActivities(scope)` to register scoped thread operations as
|
|
103
|
+
* Temporal activities on the worker. The `invoker` (or invokers created via
|
|
104
|
+
* `createModelInvoker`) should be wrapped with `createRunAgentActivity`.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```typescript
|
|
108
|
+
* import { createGoogleGenAIAdapter } from 'zeitlich/adapters/thread/google-genai';
|
|
109
|
+
* import { createRunAgentActivity } from 'zeitlich';
|
|
110
|
+
* import { GoogleGenAI } from '@google/genai';
|
|
111
|
+
*
|
|
112
|
+
* const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
|
|
113
|
+
* const adapter = createGoogleGenAIAdapter({ redis, client, model: 'gemini-2.5-flash' });
|
|
114
|
+
*
|
|
115
|
+
* export function createActivities(temporalClient: WorkflowClient) {
|
|
116
|
+
* return {
|
|
117
|
+
* ...adapter.createActivities("codingAgent"),
|
|
118
|
+
* runCodingAgent: createRunAgentActivity(temporalClient, adapter.invoker),
|
|
119
|
+
* };
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* @example Multi-agent worker (main + subagent share the adapter)
|
|
124
|
+
* ```typescript
|
|
125
|
+
* export function createActivities(temporalClient: WorkflowClient) {
|
|
126
|
+
* return {
|
|
127
|
+
* ...adapter.createActivities("codingAgent"),
|
|
128
|
+
* ...adapter.createActivities("researchAgent"),
|
|
129
|
+
* runCodingAgent: createRunAgentActivity(temporalClient, adapter.invoker),
|
|
130
|
+
* runResearchAgent: createRunAgentActivity(
|
|
131
|
+
* temporalClient,
|
|
132
|
+
* adapter.createModelInvoker('gemini-2.5-pro'),
|
|
133
|
+
* ),
|
|
134
|
+
* };
|
|
135
|
+
* }
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
declare function createGoogleGenAIAdapter(config: GoogleGenAIAdapterConfig): GoogleGenAIAdapter;
|
|
139
|
+
|
|
140
|
+
export { type GoogleGenAIThreadManagerHooks as G, type StoredContent as S, type GoogleGenAIAdapter as a, type GoogleGenAIAdapterConfig as b, type GoogleGenAIContent as c, type GoogleGenAIInvocationPayload as d, type GoogleGenAIThreadManager as e, type GoogleGenAIThreadManagerConfig as f, type GoogleGenAIThreadOps as g, type GoogleGenAIToolResponse as h, createGoogleGenAIAdapter as i, createGoogleGenAIThreadManager as j };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import Redis from 'ioredis';
|
|
2
|
+
import { Part, Content, GoogleGenAI } from '@google/genai';
|
|
3
|
+
import { R as RouterContext, T as ToolHandlerResponse, A as ActivityToolHandler } from './types-mCVxKIZb.cjs';
|
|
4
|
+
import { a as ModelInvoker, P as PrefixedThreadOps, S as ScopedPrefix } from './types-DSOefLpY.cjs';
|
|
5
|
+
import { T as ThreadManagerHooks, P as ProviderThreadManager } from './types-BfIQABzu.cjs';
|
|
6
|
+
|
|
7
|
+
/** SDK-native content type for Google GenAI human messages */
|
|
8
|
+
type GoogleGenAIContent = string | Part[];
|
|
9
|
+
/** A Content with a unique ID for idempotent Redis storage */
|
|
10
|
+
interface StoredContent {
|
|
11
|
+
id: string;
|
|
12
|
+
content: Content;
|
|
13
|
+
}
|
|
14
|
+
type GoogleGenAIThreadManagerHooks = ThreadManagerHooks<StoredContent, Content>;
|
|
15
|
+
interface GoogleGenAIThreadManagerConfig {
|
|
16
|
+
redis: Redis;
|
|
17
|
+
threadId: string;
|
|
18
|
+
/** Thread key, defaults to 'messages' */
|
|
19
|
+
key?: string;
|
|
20
|
+
hooks?: GoogleGenAIThreadManagerHooks;
|
|
21
|
+
}
|
|
22
|
+
/** Prepared payload ready to send to the Google GenAI API */
|
|
23
|
+
interface GoogleGenAIInvocationPayload {
|
|
24
|
+
contents: Content[];
|
|
25
|
+
systemInstruction?: string;
|
|
26
|
+
}
|
|
27
|
+
/** Thread manager with Google GenAI Content convenience helpers */
|
|
28
|
+
interface GoogleGenAIThreadManager extends ProviderThreadManager<StoredContent, GoogleGenAIContent, GoogleGenAIToolResponse> {
|
|
29
|
+
appendModelContent(id: string, parts: Part[]): Promise<void>;
|
|
30
|
+
prepareForInvocation(): Promise<GoogleGenAIInvocationPayload>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a Google GenAI-specific thread manager that stores StoredContent
|
|
34
|
+
* instances in Redis and provides convenience helpers for creating and
|
|
35
|
+
* appending typed Content messages.
|
|
36
|
+
*/
|
|
37
|
+
declare function createGoogleGenAIThreadManager(config: GoogleGenAIThreadManagerConfig): GoogleGenAIThreadManager;
|
|
38
|
+
|
|
39
|
+
declare const ADAPTER_PREFIX: "googleGenAI";
|
|
40
|
+
type GoogleGenAIThreadOps<TScope extends string = ""> = PrefixedThreadOps<ScopedPrefix<TScope, typeof ADAPTER_PREFIX>, GoogleGenAIContent>;
|
|
41
|
+
interface GoogleGenAIAdapterConfig {
|
|
42
|
+
redis: Redis;
|
|
43
|
+
client?: GoogleGenAI;
|
|
44
|
+
/** Default model name (e.g. 'gemini-2.5-flash'). If omitted, use `createModelInvoker()` */
|
|
45
|
+
model?: string;
|
|
46
|
+
hooks?: GoogleGenAIThreadManagerHooks;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Tool response type accepted by the Google GenAI adapter.
|
|
50
|
+
*
|
|
51
|
+
* Handlers can return:
|
|
52
|
+
* - **`string`** — plain text, wrapped in a `functionResponse` part.
|
|
53
|
+
* - **`Record<string, unknown>`** — structured object used as `functionResponse.response`.
|
|
54
|
+
* - **`Part[]`** — pre-built parts used directly as `Content.parts`.
|
|
55
|
+
* The handler is responsible for building correct Part objects (e.g. `functionResponse`,
|
|
56
|
+
* `inlineData`, `text`). Use `context.toolCallId` and `context.toolName` to construct
|
|
57
|
+
* `functionResponse` parts.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* adapter.wrapHandler(async (args, ctx) => ({
|
|
62
|
+
* toolResponse: [
|
|
63
|
+
* { functionResponse: { id: ctx.toolCallId, name: ctx.toolName, response: { result: "done" } } },
|
|
64
|
+
* { inlineData: { data: base64, mimeType: "image/png" } },
|
|
65
|
+
* ],
|
|
66
|
+
* data: null,
|
|
67
|
+
* }));
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
type GoogleGenAIToolResponse = string | Record<string, unknown> | Part[];
|
|
71
|
+
interface GoogleGenAIAdapter {
|
|
72
|
+
/** Model invoker using the default model (only available when `model` was provided) */
|
|
73
|
+
invoker: ModelInvoker<Content>;
|
|
74
|
+
/** Create an invoker for a specific model name (for multi-model setups) */
|
|
75
|
+
createModelInvoker(model: string, client: GoogleGenAI): ModelInvoker<Content>;
|
|
76
|
+
/**
|
|
77
|
+
* Create prefixed thread activities for registration on the worker.
|
|
78
|
+
*
|
|
79
|
+
* @param scope - Workflow name appended to the adapter prefix.
|
|
80
|
+
* Use different scopes for the main agent vs subagents to avoid collisions.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* adapter.createActivities("codingAgent")
|
|
85
|
+
* // → { googleGenAICodingAgentInitializeThread, googleGenAICodingAgentAppendHumanMessage, … }
|
|
86
|
+
*
|
|
87
|
+
* adapter.createActivities("researchAgent")
|
|
88
|
+
* // → { googleGenAIResearchAgentInitializeThread, … }
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
createActivities<S extends string = "">(scope?: S): GoogleGenAIThreadOps<S>;
|
|
92
|
+
/**
|
|
93
|
+
* Identity wrapper that types a tool handler for this adapter.
|
|
94
|
+
* Constrains `toolResponse` to {@link GoogleGenAIToolResponse}.
|
|
95
|
+
*/
|
|
96
|
+
wrapHandler<TArgs, TResult, TContext extends RouterContext = RouterContext>(handler: (args: TArgs, context: TContext) => Promise<ToolHandlerResponse<TResult, GoogleGenAIToolResponse>>): ActivityToolHandler<TArgs, TResult, TContext, GoogleGenAIToolResponse>;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Creates a Google GenAI adapter that bundles thread operations and model
|
|
100
|
+
* invocation using the `@google/genai` SDK.
|
|
101
|
+
*
|
|
102
|
+
* Use `createActivities(scope)` to register scoped thread operations as
|
|
103
|
+
* Temporal activities on the worker. The `invoker` (or invokers created via
|
|
104
|
+
* `createModelInvoker`) should be wrapped with `createRunAgentActivity`.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```typescript
|
|
108
|
+
* import { createGoogleGenAIAdapter } from 'zeitlich/adapters/thread/google-genai';
|
|
109
|
+
* import { createRunAgentActivity } from 'zeitlich';
|
|
110
|
+
* import { GoogleGenAI } from '@google/genai';
|
|
111
|
+
*
|
|
112
|
+
* const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
|
|
113
|
+
* const adapter = createGoogleGenAIAdapter({ redis, client, model: 'gemini-2.5-flash' });
|
|
114
|
+
*
|
|
115
|
+
* export function createActivities(temporalClient: WorkflowClient) {
|
|
116
|
+
* return {
|
|
117
|
+
* ...adapter.createActivities("codingAgent"),
|
|
118
|
+
* runCodingAgent: createRunAgentActivity(temporalClient, adapter.invoker),
|
|
119
|
+
* };
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* @example Multi-agent worker (main + subagent share the adapter)
|
|
124
|
+
* ```typescript
|
|
125
|
+
* export function createActivities(temporalClient: WorkflowClient) {
|
|
126
|
+
* return {
|
|
127
|
+
* ...adapter.createActivities("codingAgent"),
|
|
128
|
+
* ...adapter.createActivities("researchAgent"),
|
|
129
|
+
* runCodingAgent: createRunAgentActivity(temporalClient, adapter.invoker),
|
|
130
|
+
* runResearchAgent: createRunAgentActivity(
|
|
131
|
+
* temporalClient,
|
|
132
|
+
* adapter.createModelInvoker('gemini-2.5-pro'),
|
|
133
|
+
* ),
|
|
134
|
+
* };
|
|
135
|
+
* }
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
declare function createGoogleGenAIAdapter(config: GoogleGenAIAdapterConfig): GoogleGenAIAdapter;
|
|
139
|
+
|
|
140
|
+
export { type GoogleGenAIThreadManagerHooks as G, type StoredContent as S, type GoogleGenAIAdapter as a, type GoogleGenAIAdapterConfig as b, type GoogleGenAIContent as c, type GoogleGenAIInvocationPayload as d, type GoogleGenAIThreadManager as e, type GoogleGenAIThreadManagerConfig as f, type GoogleGenAIThreadOps as g, type GoogleGenAIToolResponse as h, createGoogleGenAIAdapter as i, createGoogleGenAIThreadManager as j };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/lib/sandbox/types.ts","../../../../src/adapters/sandbox/virtual/filesystem.ts","../../../../src/lib/thread/id.ts","../../../../src/adapters/sandbox/virtual/provider.ts","../../../../src/lib/activity.ts","../../../../src/adapters/sandbox/virtual/with-virtual-sandbox.ts","../../../../src/adapters/sandbox/virtual/queries.ts","../../../../src/adapters/sandbox/virtual/index.ts"],"names":["ApplicationFailure","posix","path","uuid4","Context"],"mappings":";;;;;;;;AAkLO,IAAM,wBAAA,GAAN,cAAuCA,yBAAA,CAAmB;AAAA,EAC/D,YAAY,SAAA,EAAmB;AAC7B,IAAA,KAAA;AAAA,MACE,6BAA6B,SAAS,CAAA,CAAA;AAAA,MACtC,0BAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF,CAAA;AC3KA,SAAS,aAAA,CAAc,CAAA,EAAW,aAAA,GAAgB,GAAA,EAAa;AAC7D,EAAA,OAAOC,UAAA,CAAM,OAAA,CAAQ,aAAA,EAAe,CAAC,CAAA;AACvC;AAGA,SAAS,UAAU,CAAA,EAAmB;AACpC,EAAA,MAAM,GAAA,GAAM,CAAA,CAAE,WAAA,C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AAA,IACX,WAAA,EAAa;AAAA,GACf;AAAA,EAES,EAAA;AAAA,EAYT,MAAM,IAAA,CAAK,QAAA,EAAkB,QAAA,EAA6C;AACxE,IAAA,MAAM,IAAI,yBAAyB,MAAM,CAAA;AAAA,EAC3C;AAAA,EAEA,MAAM,OAAA,GAAyB;AAAA,EAE/B;AACF,CAAA;AAaO,SAAS,qBAId,EAAA,EACA,IAAA,EACA,QAAA,EACA,GAAA,EACA,gBAAgB,GAAA,EACa;AAC7B,EAAA,OAAO,IAAI,kBAAA,CAAmB,EAAA,EAAI,IAAA,EAAM,QAAA,EAAU,KAAK,aAAa,CAAA;AACtE","file":"index.cjs","sourcesContent":["// ============================================================================\n// Sandbox Filesystem\n// ============================================================================\n\nexport interface DirentEntry {\n name: string;\n isFile: boolean;\n isDirectory: boolean;\n isSymbolicLink: boolean;\n}\n\nexport interface FileStat {\n isFile: boolean;\n isDirectory: boolean;\n isSymbolicLink: boolean;\n size: number;\n mtime: Date;\n}\n\n/**\n * Provider-agnostic filesystem interface.\n *\n * Implementations that don't support a method should throw\n * {@link SandboxNotSupportedError}.\n */\nexport interface SandboxFileSystem {\n /** Base directory used when resolving relative paths. */\n readonly workspaceBase: string;\n readFile(path: string): Promise<string>;\n readFileBuffer(path: string): Promise<Uint8Array>;\n writeFile(path: string, content: string | Uint8Array): Promise<void>;\n appendFile(path: string, content: string | Uint8Array): Promise<void>;\n exists(path: string): Promise<boolean>;\n stat(path: string): Promise<FileStat>;\n mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;\n readdir(path: string): Promise<string[]>;\n readdirWithFileTypes(path: string): Promise<DirentEntry[]>;\n rm(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n cp(\n src: string,\n dest: string,\n options?: { recursive?: boolean }\n ): Promise<void>;\n mv(src: string, dest: string): Promise<void>;\n readlink(path: string): Promise<string>;\n resolvePath(base: string, path: string): string;\n}\n\n// ============================================================================\n// Execution\n// ============================================================================\n\nexport interface ExecOptions {\n timeout?: number;\n cwd?: string;\n env?: Record<string, string>;\n}\n\nexport interface ExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n// ============================================================================\n// Capabilities\n// ============================================================================\n\nexport interface SandboxCapabilities {\n /** Sandbox supports filesystem operations */\n filesystem: boolean;\n /** Sandbox supports shell/command execution */\n execution: boolean;\n /** Sandbox state can be persisted and restored */\n persistence: boolean;\n}\n\n// ============================================================================\n// Sandbox\n// ============================================================================\n\nexport interface Sandbox {\n readonly id: string;\n readonly capabilities: SandboxCapabilities;\n readonly fs: SandboxFileSystem;\n\n exec(command: string, options?: ExecOptions): Promise<ExecResult>;\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// Snapshots\n// ============================================================================\n\nexport interface SandboxSnapshot {\n sandboxId: string;\n providerId: string;\n /** Provider-specific serialised state */\n data: unknown;\n createdAt: string;\n}\n\n// ============================================================================\n// Provider\n// ============================================================================\n\nexport interface SandboxCreateOptions {\n /** Preferred sandbox ID (provider may ignore) */\n id?: string;\n /** Seed the filesystem with these files */\n initialFiles?: Record<string, string | Uint8Array>;\n /** Environment variables available inside the sandbox */\n env?: Record<string, string>;\n}\n\nexport interface SandboxCreateResult {\n sandbox: Sandbox;\n /** Optional state to merge into the workflow's `AgentState` via the session. */\n stateUpdate?: Record<string, unknown>;\n}\n\nexport interface SandboxProvider<\n TOptions extends SandboxCreateOptions = SandboxCreateOptions,\n TSandbox extends Sandbox = Sandbox,\n> {\n readonly id: string;\n readonly capabilities: SandboxCapabilities;\n\n create(options?: TOptions): Promise<SandboxCreateResult>;\n get(sandboxId: string): Promise<TSandbox>;\n destroy(sandboxId: string): Promise<void>;\n pause(sandboxId: string, ttlSeconds?: number): Promise<void>;\n snapshot(sandboxId: string): Promise<SandboxSnapshot>;\n restore(snapshot: SandboxSnapshot): Promise<Sandbox>;\n fork(sandboxId: string): Promise<Sandbox>;\n}\n\n// ============================================================================\n// SandboxOps — workflow-side activity interface (like ThreadOps)\n// ============================================================================\n\nexport interface SandboxOps<\n TOptions extends SandboxCreateOptions = SandboxCreateOptions,\n> {\n createSandbox(\n options?: TOptions\n ): Promise<{ sandboxId: string; stateUpdate?: Record<string, unknown> }>;\n destroySandbox(sandboxId: string): Promise<void>;\n pauseSandbox(sandboxId: string): Promise<void>;\n snapshotSandbox(sandboxId: string): Promise<SandboxSnapshot>;\n forkSandbox(sandboxId: string): Promise<string>;\n}\n\n/**\n * Maps generic {@link SandboxOps} method names to adapter-prefixed names.\n *\n * @example\n * ```typescript\n * type InMemOps = PrefixedSandboxOps<\"inMemory\">;\n * // → { inMemoryCreateSandbox, inMemoryDestroySandbox, inMemorySnapshotSandbox }\n * ```\n */\nexport type PrefixedSandboxOps<\n TPrefix extends string,\n TOptions extends SandboxCreateOptions = SandboxCreateOptions,\n> = {\n [K in keyof SandboxOps<TOptions> as `${TPrefix}${Capitalize<K & string>}`]: SandboxOps<TOptions>[K];\n};\n\n// ============================================================================\n// Errors\n// ============================================================================\n\nimport { ApplicationFailure } from \"@temporalio/common\";\n\nexport class SandboxNotSupportedError extends ApplicationFailure {\n constructor(operation: string) {\n super(\n `Sandbox does not support: ${operation}`,\n \"SandboxNotSupportedError\",\n true\n );\n }\n}\n\nexport class SandboxNotFoundError extends ApplicationFailure {\n constructor(sandboxId: string) {\n super(`Sandbox not found: ${sandboxId}`, \"SandboxNotFoundError\", true);\n }\n}\n","import type {\n SandboxFileSystem,\n DirentEntry,\n FileStat,\n} from \"../../../lib/sandbox/types\";\nimport { SandboxNotSupportedError } from \"../../../lib/sandbox/types\";\nimport { posix } from \"node:path\";\nimport type {\n FileEntry,\n FileEntryMetadata,\n FileResolver,\n TreeMutation,\n} from \"./types\";\n\n/** Normalize a path against the provided workspace base. */\nfunction normalisePath(p: string, workspaceBase = \"/\"): string {\n return posix.resolve(workspaceBase, p);\n}\n\n/** Return the parent directory of a normalised path (\"/a/b\" → \"/a\"). */\nfunction parentDir(p: string): string {\n const idx = p.lastIndexOf(\"/\");\n return idx <= 0 ? \"/\" : p.slice(0, idx);\n}\n\n/**\n * Collect the set of implicit directory paths from a flat file list.\n * E.g. \"/a/b/c.ts\" contributes \"/a/b\", \"/a\", \"/\".\n */\nfunction inferDirectories(\n entries: { path: string }[],\n workspaceBase: string\n): Set<string> {\n const dirs = new Set<string>();\n dirs.add(\"/\");\n for (const entry of entries) {\n let dir = parentDir(normalisePath(entry.path, workspaceBase));\n while (dir !== \"/\" && !dirs.has(dir)) {\n dirs.add(dir);\n dir = parentDir(dir);\n }\n dirs.add(\"/\");\n }\n return dirs;\n}\n\n/**\n * Ephemeral {@link SandboxFileSystem} backed by a {@link FileResolver}.\n *\n * Created fresh for each tool invocation from the current workflow file tree.\n * Directory structure is inferred from file paths. All mutations are tracked\n * and can be retrieved via {@link getMutations} after the handler completes.\n */\nexport class VirtualSandboxFileSystem<\n TCtx = unknown,\n TMeta = FileEntryMetadata,\n> implements SandboxFileSystem {\n readonly workspaceBase: string;\n private entries: Map<string, FileEntry<TMeta>>;\n private directories: Set<string>;\n private mutations: TreeMutation<TMeta>[] = [];\n\n constructor(\n tree: FileEntry<TMeta>[],\n private resolver: FileResolver<TCtx, TMeta>,\n private ctx: TCtx,\n workspaceBase = \"/\",\n ) {\n this.workspaceBase = normalisePath(workspaceBase);\n this.entries = new Map(\n tree.map((e) => [normalisePath(e.path, this.workspaceBase), e])\n );\n this.directories = inferDirectories(tree, this.workspaceBase);\n }\n\n /** Return all mutations accumulated during this invocation. */\n getMutations(): TreeMutation<TMeta>[] {\n return this.mutations;\n }\n\n /** Look up a file entry by virtual path. */\n getEntry(path: string): FileEntry<TMeta> | undefined {\n return this.entries.get(normalisePath(path, this.workspaceBase));\n }\n\n // --------------------------------------------------------------------------\n // Read operations — delegate to resolver lazily\n // --------------------------------------------------------------------------\n\n async readFile(path: string): Promise<string> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n if (!entry) throw new Error(`ENOENT: no such file: ${path}`);\n return this.resolver.readFile(entry.id, this.ctx, entry.metadata);\n }\n\n async readFileBuffer(path: string): Promise<Uint8Array> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n if (!entry) throw new Error(`ENOENT: no such file: ${path}`);\n return this.resolver.readFileBuffer(entry.id, this.ctx, entry.metadata);\n }\n\n // --------------------------------------------------------------------------\n // Metadata operations — pure, resolved from the tree\n // --------------------------------------------------------------------------\n\n async exists(path: string): Promise<boolean> {\n const norm = normalisePath(path, this.workspaceBase);\n return this.entries.has(norm) || this.directories.has(norm);\n }\n\n async stat(path: string): Promise<FileStat> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n if (entry) {\n return {\n isFile: true,\n isDirectory: false,\n isSymbolicLink: false,\n size: entry.size,\n mtime: new Date(entry.mtime),\n };\n }\n if (this.directories.has(norm)) {\n return {\n isFile: false,\n isDirectory: true,\n isSymbolicLink: false,\n size: 0,\n mtime: new Date(),\n };\n }\n throw new Error(`ENOENT: no such file or directory: ${path}`);\n }\n\n async readdir(path: string): Promise<string[]> {\n const norm = normalisePath(path, this.workspaceBase);\n if (!this.directories.has(norm)) {\n throw new Error(`ENOENT: no such directory: ${path}`);\n }\n const prefix = norm === \"/\" ? \"/\" : norm + \"/\";\n const names = new Set<string>();\n\n for (const p of this.entries.keys()) {\n if (p.startsWith(prefix)) {\n const rest = p.slice(prefix.length);\n const seg = rest.split(\"/\")[0];\n if (seg) names.add(seg);\n }\n }\n for (const d of this.directories) {\n if (d.startsWith(prefix) && d !== norm) {\n const rest = d.slice(prefix.length);\n const seg = rest.split(\"/\")[0];\n if (seg) names.add(seg);\n }\n }\n return [...names].sort();\n }\n\n async readdirWithFileTypes(path: string): Promise<DirentEntry[]> {\n const names = await this.readdir(path);\n const norm = normalisePath(path, this.workspaceBase);\n const prefix = norm === \"/\" ? \"/\" : norm + \"/\";\n\n return names.map((name) => {\n const full = prefix + name;\n const isFile = this.entries.has(full);\n const isDirectory = this.directories.has(full);\n return { name, isFile, isDirectory, isSymbolicLink: false };\n });\n }\n\n // --------------------------------------------------------------------------\n // Write operations — delegate to resolver, record mutations\n // --------------------------------------------------------------------------\n\n async writeFile(path: string, content: string | Uint8Array): Promise<void> {\n const norm = normalisePath(path, this.workspaceBase);\n const existing = this.entries.get(norm);\n\n if (existing) {\n await this.resolver.writeFile(\n existing.id,\n content,\n this.ctx,\n existing.metadata\n );\n const size =\n typeof content === \"string\"\n ? new TextEncoder().encode(content).byteLength\n : content.byteLength;\n const updated: FileEntry<TMeta> = {\n ...existing,\n size,\n mtime: new Date().toISOString(),\n };\n this.entries.set(norm, updated);\n this.mutations.push({ type: \"update\", path: norm, entry: updated });\n } else {\n const entry = await this.resolver.createFile(norm, content, this.ctx);\n const normalised = { ...entry, path: norm };\n this.entries.set(norm, normalised);\n this.addParentDirectories(norm);\n this.mutations.push({ type: \"add\", entry: normalised });\n }\n }\n\n async appendFile(path: string, content: string | Uint8Array): Promise<void> {\n const norm = normalisePath(path, this.workspaceBase);\n const existing = this.entries.get(norm);\n\n if (!existing) {\n return this.writeFile(path, content);\n }\n\n const current = await this.resolver.readFile(\n existing.id,\n this.ctx,\n existing.metadata\n );\n const appended =\n typeof content === \"string\"\n ? current + content\n : current + new TextDecoder().decode(content);\n await this.resolver.writeFile(\n existing.id,\n appended,\n this.ctx,\n existing.metadata\n );\n\n const size = new TextEncoder().encode(appended).byteLength;\n const updated: FileEntry<TMeta> = {\n ...existing,\n size,\n mtime: new Date().toISOString(),\n };\n this.entries.set(norm, updated);\n this.mutations.push({ type: \"update\", path: norm, entry: updated });\n }\n\n async mkdir(\n _path: string,\n _options?: { recursive?: boolean }\n ): Promise<void> {\n const norm = normalisePath(_path, this.workspaceBase);\n if (this.directories.has(norm)) return;\n\n if (_options?.recursive) {\n this.addParentDirectories(norm + \"/placeholder\");\n this.directories.add(norm);\n } else {\n const parent = parentDir(norm);\n if (!this.directories.has(parent)) {\n throw new Error(`ENOENT: no such directory: ${parent}`);\n }\n this.directories.add(norm);\n }\n }\n\n async rm(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n\n if (entry) {\n await this.resolver.deleteFile(entry.id, this.ctx, entry.metadata);\n this.entries.delete(norm);\n this.mutations.push({ type: \"remove\", path: norm });\n return;\n }\n\n if (this.directories.has(norm)) {\n if (!options?.recursive) {\n throw new Error(`EISDIR: is a directory (use recursive): ${path}`);\n }\n const prefix = norm === \"/\" ? \"/\" : norm + \"/\";\n for (const [p, e] of this.entries) {\n if (p.startsWith(prefix)) {\n await this.resolver.deleteFile(e.id, this.ctx, e.metadata);\n this.entries.delete(p);\n this.mutations.push({ type: \"remove\", path: p });\n }\n }\n for (const d of this.directories) {\n if (d.startsWith(prefix)) this.directories.delete(d);\n }\n this.directories.delete(norm);\n return;\n }\n\n if (!options?.force) {\n throw new Error(`ENOENT: no such file or directory: ${path}`);\n }\n }\n\n async cp(\n src: string,\n dest: string,\n _options?: { recursive?: boolean }\n ): Promise<void> {\n const normSrc = normalisePath(src, this.workspaceBase);\n const normDest = normalisePath(dest, this.workspaceBase);\n\n const entry = this.entries.get(normSrc);\n if (entry) {\n const content = await this.resolver.readFile(\n entry.id,\n this.ctx,\n entry.metadata\n );\n await this.writeFile(normDest, content);\n return;\n }\n\n if (!this.directories.has(normSrc)) {\n throw new Error(`ENOENT: no such file or directory: ${src}`);\n }\n if (!_options?.recursive) {\n throw new Error(`EISDIR: is a directory (use recursive): ${src}`);\n }\n\n const prefix = normSrc === \"/\" ? \"/\" : normSrc + \"/\";\n for (const [p, e] of this.entries) {\n if (p.startsWith(prefix)) {\n const relative = p.slice(normSrc.length);\n const content = await this.resolver.readFile(\n e.id,\n this.ctx,\n e.metadata\n );\n await this.writeFile(normDest + relative, content);\n }\n }\n }\n\n async mv(src: string, dest: string): Promise<void> {\n await this.cp(src, dest, { recursive: true });\n await this.rm(src, { recursive: true });\n }\n\n // --------------------------------------------------------------------------\n // Unsupported\n // --------------------------------------------------------------------------\n\n async readlink(_path: string): Promise<string> {\n throw new SandboxNotSupportedError(\"readlink\");\n }\n\n resolvePath(base: string, path: string): string {\n return posix.resolve(normalisePath(base, this.workspaceBase), path);\n }\n\n // --------------------------------------------------------------------------\n // Helpers\n // --------------------------------------------------------------------------\n\n private addParentDirectories(filePath: string): void {\n let dir = parentDir(normalisePath(filePath, this.workspaceBase));\n while (!this.directories.has(dir)) {\n this.directories.add(dir);\n dir = parentDir(dir);\n }\n }\n}\n","import { uuid4 } from \"@temporalio/workflow\";\n\nconst BASE62 =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a compact, workflow-deterministic identifier.\n *\n * Uses Temporal's `uuid4()` internally (seeded by the workflow's RNG),\n * then re-encodes the hex bytes into a base-62 alphabet for a shorter,\n * more token-efficient identifier (~3 tokens vs ~10 for a full UUID).\n *\n * Suitable for thread IDs, child workflow IDs, or any workflow-scoped identifier.\n *\n * @param length - Number of base-62 characters (default 12, ~71 bits of entropy)\n */\nexport function getShortId(length = 12): string {\n const hex = uuid4().replace(/-/g, \"\");\n let result = \"\";\n for (let i = 0; i < length; i++) {\n const byte = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n result += BASE62[byte % BASE62.length];\n }\n return result;\n}\n","import type {\n SandboxCapabilities,\n SandboxCreateResult,\n SandboxProvider,\n} from \"../../../lib/sandbox/types\";\nimport { SandboxNotSupportedError } from \"../../../lib/sandbox/types\";\nimport { getShortId } from \"../../../lib/thread/id\";\nimport { createVirtualSandbox } from \"./index\";\nimport type {\n FileEntryMetadata,\n FileResolver,\n VirtualSandboxCreateOptions,\n} from \"./types\";\n\n/**\n * Stateless {@link SandboxProvider} backed by a {@link FileResolver}.\n *\n * The provider holds **no internal state**. All sandbox state (sandboxId,\n * fileTree, resolverContext, workspaceBase) is returned as a `stateUpdate` from\n * {@link create} and merged into the workflow's `AgentState` by the session.\n * {@link withVirtualSandbox} reads this state back on every tool invocation.\n *\n * @example\n * ```typescript\n * const provider = new VirtualSandboxProvider(resolver);\n * const manager = new SandboxManager(provider);\n *\n * export const activities = {\n * ...manager.createActivities(\"CodingAgent\"),\n * readFile: withVirtualSandbox(client, provider, readHandler),\n * };\n * ```\n */\nexport class VirtualSandboxProvider<\n TCtx = unknown,\n TMeta = FileEntryMetadata,\n> implements SandboxProvider<VirtualSandboxCreateOptions<TCtx>> {\n readonly id = \"virtual\";\n readonly capabilities: SandboxCapabilities = {\n filesystem: true,\n execution: false,\n persistence: true,\n };\n\n readonly resolver: FileResolver<TCtx, TMeta>;\n\n constructor(resolver: FileResolver<TCtx, TMeta>) {\n this.resolver = resolver;\n }\n\n async create(\n options?: VirtualSandboxCreateOptions<TCtx>\n ): Promise<SandboxCreateResult> {\n if (!options || !(\"resolverContext\" in options)) {\n throw new Error(\"VirtualSandboxProvider.create requires resolverContext\");\n }\n\n const sandboxId = options.id ?? getShortId();\n const fileTree = await this.resolver.resolveEntries(\n options.resolverContext\n );\n const workspaceBase = options.workspaceBase ?? \"/\";\n\n const sandbox = createVirtualSandbox(\n sandboxId,\n fileTree,\n this.resolver,\n options.resolverContext,\n workspaceBase,\n );\n\n if (options.initialFiles) {\n for (const [path, content] of Object.entries(options.initialFiles)) {\n await sandbox.fs.writeFile(path, content);\n }\n for (const m of sandbox.fs.getMutations()) {\n if (m.type === \"add\") fileTree.push(m.entry);\n }\n }\n\n return {\n sandbox,\n stateUpdate: {\n sandboxId,\n fileTree,\n resolverContext: options.resolverContext,\n workspaceBase,\n },\n };\n }\n\n async get(): Promise<never> {\n throw new SandboxNotSupportedError(\n \"get (virtual sandbox state lives in workflow AgentState)\"\n );\n }\n\n async destroy(): Promise<void> {\n // No-op — no internal state to clean up\n }\n\n async pause(): Promise<void> {\n // No-op — virtual sandbox state lives in workflow AgentState\n }\n\n async fork(_sandboxId: string): Promise<never> {\n throw new Error(\"Not implemented\");\n }\n\n async snapshot(): Promise<never> {\n throw new SandboxNotSupportedError(\n \"snapshot (virtual sandbox state lives in workflow AgentState)\"\n );\n }\n\n async restore(): Promise<never> {\n throw new SandboxNotSupportedError(\n \"restore (virtual sandbox state lives in workflow AgentState)\"\n );\n }\n}\n","import { Context } from \"@temporalio/activity\";\nimport type { WorkflowClient } from \"@temporalio/client\";\nimport type { BaseAgentState, RunAgentConfig } from \"./types\";\nimport type {\n ActivityToolHandler,\n RouterContext,\n ToolHandlerResponse,\n} from \"./tool-router/types\";\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 `RunAgentActivity` by auto-fetching the parent\n * workflow's agent state before each invocation.\n *\n * @example\n * ```typescript\n * import { createRunAgentActivity } from 'zeitlich';\n * import { createLangChainModelInvoker } from 'zeitlich/adapters/thread/langchain';\n *\n * const invoker = createLangChainModelInvoker({ redis, model });\n * return { runAgent: createRunAgentActivity(client, invoker) };\n * ```\n */\nexport function createRunAgentActivity<R, S extends BaseAgentState = BaseAgentState>(\n client: WorkflowClient,\n handler: (config: RunAgentConfig & { state: S }) => Promise<R>,\n): (config: RunAgentConfig) => Promise<R> {\n return async (config: RunAgentConfig) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler({ ...config, state });\n };\n}\n\n/**\n * Context injected into tool handlers created via {@link withParentWorkflowState}.\n */\nexport interface AgentStateContext<S extends BaseAgentState = BaseAgentState> 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<TArgs, TResult, S extends BaseAgentState = BaseAgentState>(\n client: WorkflowClient,\n handler: (\n args: TArgs,\n context: AgentStateContext<S>,\n ) => Promise<ToolHandlerResponse<TResult>>,\n): ActivityToolHandler<TArgs, TResult> {\n return async (args, context) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler(args, { ...context, state });\n };\n}\n","import type { WorkflowClient } from \"@temporalio/client\";\nimport { queryParentWorkflowState } from \"../../../lib/activity\";\nimport type { ActivityToolHandler } from \"../../../lib/tool-router/types\";\nimport type {\n FileEntryMetadata,\n TreeMutation,\n VirtualSandboxContext,\n VirtualSandboxState,\n} from \"./types\";\nimport type { VirtualSandboxProvider } from \"./provider\";\nimport { createVirtualSandbox } from \"./index\";\n\n/**\n * Wraps a tool handler that needs a virtual sandbox, automatically querying\n * the parent workflow for the current file tree and resolver context.\n *\n * On each invocation the wrapper:\n * 1. Queries the workflow's `AgentState` for `fileTree`, `resolverContext`, and `workspaceBase`\n * 2. Creates an ephemeral {@link VirtualSandbox} from tree + provider's resolver\n * 3. Runs the inner handler\n * 4. Returns the handler's result together with any {@link TreeMutation}s\n *\n * The consumer applies mutations back to workflow state via a post-tool hook.\n *\n * @param client - Temporal `WorkflowClient` for querying the parent workflow\n * @param agentName - Agent name (used to derive the state query name)\n * @param provider - {@link VirtualSandboxProvider} (wraps the resolver)\n * @param handler - Inner handler expecting a {@link VirtualSandboxContext}\n *\n * @example\n * ```typescript\n * import { withVirtualSandbox, type VirtualSandboxContext } from 'zeitlich';\n *\n * const readHandler: ActivityToolHandler<FileReadArgs, ReadResult, VirtualSandboxContext> =\n * async (args, { sandbox }) => {\n * const content = await sandbox.fs.readFile(args.path);\n * return { toolResponse: content, data: { path: args.path, content } };\n * };\n *\n * // At activity registration:\n * const provider = new VirtualSandboxProvider(resolver);\n * const handler = withVirtualSandbox(client, \"myAgent\", provider, readHandler);\n * ```\n */\nexport function withVirtualSandbox<\n TArgs,\n TResult,\n TCtx,\n TMeta = FileEntryMetadata,\n>(\n client: WorkflowClient,\n provider: VirtualSandboxProvider<TCtx, TMeta>,\n handler: ActivityToolHandler<\n TArgs,\n TResult,\n VirtualSandboxContext<TCtx, TMeta>\n >\n): ActivityToolHandler<\n TArgs,\n (TResult & { treeMutations: TreeMutation<TMeta>[] }) | null\n> {\n return async (args, context) => {\n const state =\n await queryParentWorkflowState<VirtualSandboxState<TCtx, TMeta>>(client);\n\n const { sandboxId, fileTree, resolverContext, workspaceBase } = state;\n if (!fileTree || !sandboxId) {\n return {\n toolResponse: `Error: No fileTree/sandboxId in agent state. The ${context.toolName} tool requires a virtual sandbox.`,\n data: null,\n };\n }\n\n const sandbox = createVirtualSandbox(\n sandboxId,\n fileTree,\n provider.resolver,\n resolverContext,\n workspaceBase ?? \"/\",\n );\n const response = await handler(args, { ...context, sandbox });\n const mutations = sandbox.fs.getMutations();\n\n return {\n toolResponse: response.toolResponse,\n data: {\n ...(response.data ?? {}),\n treeMutations: mutations,\n } as TResult & { treeMutations: TreeMutation<TMeta>[] },\n };\n };\n}\n","import type { FileEntry } from \"./types\";\n\n/**\n * Structural constraint: accepts any `AgentStateManager<T>` whose custom\n * state includes `fileTree: FileEntry<TMeta>[]`.\n */\nexport interface FileTreeAccessor<TMeta> {\n get(key: \"fileTree\"): FileEntry<TMeta>[];\n}\n\n/**\n * Check whether any file in the tree has a `metadata.mimeType` that matches\n * the given pattern.\n *\n * Patterns:\n * - Exact: `\"application/pdf\"`\n * - Wildcard type: `\"image/*\"`\n *\n * Useful for conditionally enabling tools:\n *\n * ```ts\n * { enabled: hasFileWithMimeType(stateManager, \"image/*\") }\n * { enabled: hasFileWithMimeType(stateManager, [\"image/*\", \"application/pdf\"]) }\n * ```\n */\nexport function hasFileWithMimeType<TMeta>(\n stateManager: FileTreeAccessor<TMeta>,\n pattern: string | string[],\n): boolean {\n const tree = stateManager.get(\"fileTree\");\n const matchers = (Array.isArray(pattern) ? pattern : [pattern]).map(buildMatcher);\n return tree.some((entry) => {\n const meta = entry.metadata as Record<string, unknown> | undefined;\n const mime = meta?.mimeType;\n return typeof mime === \"string\" && matchers.some((m) => m(mime));\n });\n}\n\n/**\n * Return all entries whose `metadata.mimeType` matches the given pattern.\n */\nexport function filesWithMimeType<TMeta>(\n stateManager: FileTreeAccessor<TMeta>,\n pattern: string,\n): FileEntry<TMeta>[] {\n const tree = stateManager.get(\"fileTree\");\n const match = buildMatcher(pattern);\n return tree.filter((entry) => {\n const meta = entry.metadata as Record<string, unknown> | undefined;\n const mime = meta?.mimeType;\n return typeof mime === \"string\" && match(mime);\n });\n}\n\n/**\n * Check whether the tree contains a directory whose name matches the given\n * pattern. Directories are inferred from file paths.\n *\n * Patterns:\n * - Exact: `\"src\"`\n * - Glob with `*` wildcard: `\"test*\"`, `\"*.generated\"`\n *\n * ```ts\n * { enabled: hasDirectory(stateManager, \"test*\") }\n * ```\n */\nexport function hasDirectory<TMeta>(\n stateManager: FileTreeAccessor<TMeta>,\n pattern: string,\n): boolean {\n const tree = stateManager.get(\"fileTree\");\n const match = buildGlobMatcher(pattern);\n return tree.some((entry) => {\n const segments = entry.path.split(\"/\").filter(Boolean);\n return segments.slice(0, -1).some(match);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Internal matchers\n// ---------------------------------------------------------------------------\n\nfunction buildMatcher(pattern: string): (value: string) => boolean {\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return (v) => v.startsWith(prefix);\n }\n return (v) => v === pattern;\n}\n\nfunction buildGlobMatcher(pattern: string): (value: string) => boolean {\n if (!pattern.includes(\"*\")) return (v) => v === pattern;\n const re = new RegExp(\n \"^\" + pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\") + \"$\",\n );\n return (v) => re.test(v);\n}\n","import type {\n Sandbox,\n SandboxCapabilities,\n ExecOptions,\n ExecResult,\n} from \"../../../lib/sandbox/types\";\nimport { SandboxNotSupportedError } from \"../../../lib/sandbox/types\";\nimport { VirtualSandboxFileSystem } from \"./filesystem\";\nimport type {\n FileEntry,\n FileEntryMetadata,\n FileResolver,\n VirtualSandbox,\n} from \"./types\";\n\n// ============================================================================\n// VirtualSandbox\n// ============================================================================\n\nclass VirtualSandboxImpl<\n TCtx = unknown,\n TMeta = FileEntryMetadata,\n> implements Sandbox\n{\n readonly capabilities: SandboxCapabilities = {\n filesystem: true,\n execution: false,\n persistence: true,\n };\n\n readonly fs: VirtualSandboxFileSystem<TCtx, TMeta>;\n\n constructor(\n readonly id: string,\n tree: FileEntry<TMeta>[],\n resolver: FileResolver<TCtx, TMeta>,\n ctx: TCtx,\n workspaceBase = \"/\",\n ) {\n this.fs = new VirtualSandboxFileSystem(tree, resolver, ctx, workspaceBase);\n }\n\n async exec(_command: string, _options?: ExecOptions): Promise<ExecResult> {\n throw new SandboxNotSupportedError(\"exec\");\n }\n\n async destroy(): Promise<void> {\n // Ephemeral — nothing to clean up\n }\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\n/**\n * Create an ephemeral {@link Sandbox} from a file tree and resolver.\n *\n * Used internally by {@link withVirtualSandbox} and\n * {@link VirtualSandboxProvider}; consumers can also call this directly\n * if they need a sandbox outside the wrapper pattern.\n */\nexport function createVirtualSandbox<\n TCtx,\n TMeta = FileEntryMetadata,\n>(\n id: string,\n tree: FileEntry<TMeta>[],\n resolver: FileResolver<TCtx, TMeta>,\n ctx: TCtx,\n workspaceBase = \"/\",\n): VirtualSandbox<TCtx, TMeta> {\n return new VirtualSandboxImpl(id, tree, resolver, ctx, workspaceBase);\n}\n\n// Re-exports for convenience\nexport { VirtualSandboxFileSystem } from \"./filesystem\";\nexport { VirtualSandboxProvider } from \"./provider\";\nexport { withVirtualSandbox } from \"./with-virtual-sandbox\";\nexport { hasFileWithMimeType, filesWithMimeType, hasDirectory } from \"./queries\";\nexport type { FileTreeAccessor } from \"./queries\";\nexport type {\n FileEntry,\n FileEntryMetadata,\n FileResolver,\n VirtualFileTree,\n VirtualSandboxCreateOptions,\n VirtualSandboxState,\n VirtualSandboxContext,\n VirtualSandbox,\n TreeMutation,\n} from \"./types\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/lib/sandbox/types.ts","../../../../src/adapters/sandbox/virtual/filesystem.ts","../../../../src/lib/thread/id.ts","../../../../src/adapters/sandbox/virtual/provider.ts","../../../../src/lib/activity.ts","../../../../src/adapters/sandbox/virtual/with-virtual-sandbox.ts","../../../../src/adapters/sandbox/virtual/queries.ts","../../../../src/adapters/sandbox/virtual/index.ts"],"names":["ApplicationFailure","posix","path","uuid4","Context"],"mappings":";;;;;;;;AAkLO,IAAM,wBAAA,GAAN,cAAuCA,yBAAA,CAAmB;AAAA,EAC/D,YAAY,SAAA,EAAmB;AAC7B,IAAA,KAAA;AAAA,MACE,6BAA6B,SAAS,CAAA,CAAA;AAAA,MACtC,0BAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF,CAAA;AC3KA,SAAS,aAAA,CAAc,CAAA,EAAW,aAAA,GAAgB,GAAA,EAAa;AAC7D,EAAA,OAAOC,UAAA,CAAM,OAAA,CAAQ,aAAA,EAAe,CAAC,CAAA;AACvC;AAGA,SAAS,UAAU,CAAA,EAAmB;AACpC,EAAA,MAAM,GAAA,GAAM,CAAA,CAAE,WAAA,CAAY,GAAG,CAAA;AAC7B,EAAA,OAAO,OAAO,CAAA,GAAI,GAAA,GAAM,CAAA,CAAE,KAAA,CAAM,GAAG,GAAG,CAAA;AACxC;AAMA,SAAS,gBAAA,CACP,SACA,aAAA,EACa;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AACZ,EAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,IAAA,IAAI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;AAC7B,EAAA,OAAO,IAAI,kBAAA,CAAmB,EAAA,EAAI,IAAA,EAAM,QAAA,EAAU,KAAK,aAAa,CAAA;AACtE","file":"index.cjs","sourcesContent":["// ============================================================================\n// Sandbox Filesystem\n// ============================================================================\n\nexport interface DirentEntry {\n name: string;\n isFile: boolean;\n isDirectory: boolean;\n isSymbolicLink: boolean;\n}\n\nexport interface FileStat {\n isFile: boolean;\n isDirectory: boolean;\n isSymbolicLink: boolean;\n size: number;\n mtime: Date;\n}\n\n/**\n * Provider-agnostic filesystem interface.\n *\n * Implementations that don't support a method should throw\n * {@link SandboxNotSupportedError}.\n */\nexport interface SandboxFileSystem {\n /** Base directory used when resolving relative paths. */\n readonly workspaceBase: string;\n readFile(path: string): Promise<string>;\n readFileBuffer(path: string): Promise<Uint8Array>;\n writeFile(path: string, content: string | Uint8Array): Promise<void>;\n appendFile(path: string, content: string | Uint8Array): Promise<void>;\n exists(path: string): Promise<boolean>;\n stat(path: string): Promise<FileStat>;\n mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;\n readdir(path: string): Promise<string[]>;\n readdirWithFileTypes(path: string): Promise<DirentEntry[]>;\n rm(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n cp(\n src: string,\n dest: string,\n options?: { recursive?: boolean }\n ): Promise<void>;\n mv(src: string, dest: string): Promise<void>;\n readlink(path: string): Promise<string>;\n resolvePath(base: string, path: string): string;\n}\n\n// ============================================================================\n// Execution\n// ============================================================================\n\nexport interface ExecOptions {\n timeout?: number;\n cwd?: string;\n env?: Record<string, string>;\n}\n\nexport interface ExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n// ============================================================================\n// Capabilities\n// ============================================================================\n\nexport interface SandboxCapabilities {\n /** Sandbox supports filesystem operations */\n filesystem: boolean;\n /** Sandbox supports shell/command execution */\n execution: boolean;\n /** Sandbox state can be persisted and restored */\n persistence: boolean;\n}\n\n// ============================================================================\n// Sandbox\n// ============================================================================\n\nexport interface Sandbox {\n readonly id: string;\n readonly capabilities: SandboxCapabilities;\n readonly fs: SandboxFileSystem;\n\n exec(command: string, options?: ExecOptions): Promise<ExecResult>;\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// Snapshots\n// ============================================================================\n\nexport interface SandboxSnapshot {\n sandboxId: string;\n providerId: string;\n /** Provider-specific serialised state */\n data: unknown;\n createdAt: string;\n}\n\n// ============================================================================\n// Provider\n// ============================================================================\n\nexport interface SandboxCreateOptions {\n /** Preferred sandbox ID (provider may ignore) */\n id?: string;\n /** Seed the filesystem with these files */\n initialFiles?: Record<string, string | Uint8Array>;\n /** Environment variables available inside the sandbox */\n env?: Record<string, string>;\n}\n\nexport interface SandboxCreateResult {\n sandbox: Sandbox;\n /** Optional state to merge into the workflow's `AgentState` via the session. */\n stateUpdate?: Record<string, unknown>;\n}\n\nexport interface SandboxProvider<\n TOptions extends SandboxCreateOptions = SandboxCreateOptions,\n TSandbox extends Sandbox = Sandbox,\n> {\n readonly id: string;\n readonly capabilities: SandboxCapabilities;\n\n create(options?: TOptions): Promise<SandboxCreateResult>;\n get(sandboxId: string): Promise<TSandbox>;\n destroy(sandboxId: string): Promise<void>;\n pause(sandboxId: string, ttlSeconds?: number): Promise<void>;\n snapshot(sandboxId: string): Promise<SandboxSnapshot>;\n restore(snapshot: SandboxSnapshot): Promise<Sandbox>;\n fork(sandboxId: string): Promise<Sandbox>;\n}\n\n// ============================================================================\n// SandboxOps — workflow-side activity interface (like ThreadOps)\n// ============================================================================\n\nexport interface SandboxOps<\n TOptions extends SandboxCreateOptions = SandboxCreateOptions,\n> {\n createSandbox(\n options?: TOptions\n ): Promise<{ sandboxId: string; stateUpdate?: Record<string, unknown> }>;\n destroySandbox(sandboxId: string): Promise<void>;\n pauseSandbox(sandboxId: string): Promise<void>;\n snapshotSandbox(sandboxId: string): Promise<SandboxSnapshot>;\n forkSandbox(sandboxId: string): Promise<string>;\n}\n\n/**\n * Maps generic {@link SandboxOps} method names to adapter-prefixed names.\n *\n * @example\n * ```typescript\n * type InMemOps = PrefixedSandboxOps<\"inMemory\">;\n * // → { inMemoryCreateSandbox, inMemoryDestroySandbox, inMemorySnapshotSandbox }\n * ```\n */\nexport type PrefixedSandboxOps<\n TPrefix extends string,\n TOptions extends SandboxCreateOptions = SandboxCreateOptions,\n> = {\n [K in keyof SandboxOps<TOptions> as `${TPrefix}${Capitalize<K & string>}`]: SandboxOps<TOptions>[K];\n};\n\n// ============================================================================\n// Errors\n// ============================================================================\n\nimport { ApplicationFailure } from \"@temporalio/common\";\n\nexport class SandboxNotSupportedError extends ApplicationFailure {\n constructor(operation: string) {\n super(\n `Sandbox does not support: ${operation}`,\n \"SandboxNotSupportedError\",\n true\n );\n }\n}\n\nexport class SandboxNotFoundError extends ApplicationFailure {\n constructor(sandboxId: string) {\n super(`Sandbox not found: ${sandboxId}`, \"SandboxNotFoundError\", true);\n }\n}\n","import type {\n SandboxFileSystem,\n DirentEntry,\n FileStat,\n} from \"../../../lib/sandbox/types\";\nimport { SandboxNotSupportedError } from \"../../../lib/sandbox/types\";\nimport { posix } from \"node:path\";\nimport type {\n FileEntry,\n FileEntryMetadata,\n FileResolver,\n TreeMutation,\n} from \"./types\";\n\n/** Normalize a path against the provided workspace base. */\nfunction normalisePath(p: string, workspaceBase = \"/\"): string {\n return posix.resolve(workspaceBase, p);\n}\n\n/** Return the parent directory of a normalised path (\"/a/b\" → \"/a\"). */\nfunction parentDir(p: string): string {\n const idx = p.lastIndexOf(\"/\");\n return idx <= 0 ? \"/\" : p.slice(0, idx);\n}\n\n/**\n * Collect the set of implicit directory paths from a flat file list.\n * E.g. \"/a/b/c.ts\" contributes \"/a/b\", \"/a\", \"/\".\n */\nfunction inferDirectories(\n entries: { path: string }[],\n workspaceBase: string\n): Set<string> {\n const dirs = new Set<string>();\n dirs.add(\"/\");\n for (const entry of entries) {\n let dir = parentDir(normalisePath(entry.path, workspaceBase));\n while (dir !== \"/\" && !dirs.has(dir)) {\n dirs.add(dir);\n dir = parentDir(dir);\n }\n dirs.add(\"/\");\n }\n return dirs;\n}\n\n/**\n * Ephemeral {@link SandboxFileSystem} backed by a {@link FileResolver}.\n *\n * Created fresh for each tool invocation from the current workflow file tree.\n * Directory structure is inferred from file paths. All mutations are tracked\n * and can be retrieved via {@link getMutations} after the handler completes.\n */\nexport class VirtualSandboxFileSystem<\n TCtx = unknown,\n TMeta = FileEntryMetadata,\n> implements SandboxFileSystem {\n readonly workspaceBase: string;\n private entries: Map<string, FileEntry<TMeta>>;\n private directories: Set<string>;\n private mutations: TreeMutation<TMeta>[] = [];\n\n constructor(\n tree: FileEntry<TMeta>[],\n private resolver: FileResolver<TCtx, TMeta>,\n private ctx: TCtx,\n workspaceBase = \"/\",\n ) {\n this.workspaceBase = normalisePath(workspaceBase);\n this.entries = new Map(\n tree.map((e) => [normalisePath(e.path, this.workspaceBase), e])\n );\n this.directories = inferDirectories(tree, this.workspaceBase);\n }\n\n /** Return all mutations accumulated during this invocation. */\n getMutations(): TreeMutation<TMeta>[] {\n return this.mutations;\n }\n\n /** Look up a file entry by virtual path. */\n getEntry(path: string): FileEntry<TMeta> | undefined {\n return this.entries.get(normalisePath(path, this.workspaceBase));\n }\n\n // --------------------------------------------------------------------------\n // Read operations — delegate to resolver lazily\n // --------------------------------------------------------------------------\n\n async readFile(path: string): Promise<string> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n if (!entry) throw new Error(`ENOENT: no such file: ${path}`);\n return this.resolver.readFile(entry.id, this.ctx, entry.metadata);\n }\n\n async readFileBuffer(path: string): Promise<Uint8Array> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n if (!entry) throw new Error(`ENOENT: no such file: ${path}`);\n return this.resolver.readFileBuffer(entry.id, this.ctx, entry.metadata);\n }\n\n // --------------------------------------------------------------------------\n // Metadata operations — pure, resolved from the tree\n // --------------------------------------------------------------------------\n\n async exists(path: string): Promise<boolean> {\n const norm = normalisePath(path, this.workspaceBase);\n return this.entries.has(norm) || this.directories.has(norm);\n }\n\n async stat(path: string): Promise<FileStat> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n if (entry) {\n return {\n isFile: true,\n isDirectory: false,\n isSymbolicLink: false,\n size: entry.size,\n mtime: new Date(entry.mtime),\n };\n }\n if (this.directories.has(norm)) {\n return {\n isFile: false,\n isDirectory: true,\n isSymbolicLink: false,\n size: 0,\n mtime: new Date(),\n };\n }\n throw new Error(`ENOENT: no such file or directory: ${path}`);\n }\n\n async readdir(path: string): Promise<string[]> {\n const norm = normalisePath(path, this.workspaceBase);\n if (!this.directories.has(norm)) {\n throw new Error(`ENOENT: no such directory: ${path}`);\n }\n const prefix = norm === \"/\" ? \"/\" : norm + \"/\";\n const names = new Set<string>();\n\n for (const p of this.entries.keys()) {\n if (p.startsWith(prefix)) {\n const rest = p.slice(prefix.length);\n const seg = rest.split(\"/\")[0];\n if (seg) names.add(seg);\n }\n }\n for (const d of this.directories) {\n if (d.startsWith(prefix) && d !== norm) {\n const rest = d.slice(prefix.length);\n const seg = rest.split(\"/\")[0];\n if (seg) names.add(seg);\n }\n }\n return [...names].sort();\n }\n\n async readdirWithFileTypes(path: string): Promise<DirentEntry[]> {\n const names = await this.readdir(path);\n const norm = normalisePath(path, this.workspaceBase);\n const prefix = norm === \"/\" ? \"/\" : norm + \"/\";\n\n return names.map((name) => {\n const full = prefix + name;\n const isFile = this.entries.has(full);\n const isDirectory = this.directories.has(full);\n return { name, isFile, isDirectory, isSymbolicLink: false };\n });\n }\n\n // --------------------------------------------------------------------------\n // Write operations — delegate to resolver, record mutations\n // --------------------------------------------------------------------------\n\n async writeFile(path: string, content: string | Uint8Array): Promise<void> {\n const norm = normalisePath(path, this.workspaceBase);\n const existing = this.entries.get(norm);\n\n if (existing) {\n await this.resolver.writeFile(\n existing.id,\n content,\n this.ctx,\n existing.metadata\n );\n const size =\n typeof content === \"string\"\n ? new TextEncoder().encode(content).byteLength\n : content.byteLength;\n const updated: FileEntry<TMeta> = {\n ...existing,\n size,\n mtime: new Date().toISOString(),\n };\n this.entries.set(norm, updated);\n this.mutations.push({ type: \"update\", path: norm, entry: updated });\n } else {\n const entry = await this.resolver.createFile(norm, content, this.ctx);\n const normalised = { ...entry, path: norm };\n this.entries.set(norm, normalised);\n this.addParentDirectories(norm);\n this.mutations.push({ type: \"add\", entry: normalised });\n }\n }\n\n async appendFile(path: string, content: string | Uint8Array): Promise<void> {\n const norm = normalisePath(path, this.workspaceBase);\n const existing = this.entries.get(norm);\n\n if (!existing) {\n return this.writeFile(path, content);\n }\n\n const current = await this.resolver.readFile(\n existing.id,\n this.ctx,\n existing.metadata\n );\n const appended =\n typeof content === \"string\"\n ? current + content\n : current + new TextDecoder().decode(content);\n await this.resolver.writeFile(\n existing.id,\n appended,\n this.ctx,\n existing.metadata\n );\n\n const size = new TextEncoder().encode(appended).byteLength;\n const updated: FileEntry<TMeta> = {\n ...existing,\n size,\n mtime: new Date().toISOString(),\n };\n this.entries.set(norm, updated);\n this.mutations.push({ type: \"update\", path: norm, entry: updated });\n }\n\n async mkdir(\n _path: string,\n _options?: { recursive?: boolean }\n ): Promise<void> {\n const norm = normalisePath(_path, this.workspaceBase);\n if (this.directories.has(norm)) return;\n\n if (_options?.recursive) {\n this.addParentDirectories(norm + \"/placeholder\");\n this.directories.add(norm);\n } else {\n const parent = parentDir(norm);\n if (!this.directories.has(parent)) {\n throw new Error(`ENOENT: no such directory: ${parent}`);\n }\n this.directories.add(norm);\n }\n }\n\n async rm(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void> {\n const norm = normalisePath(path, this.workspaceBase);\n const entry = this.entries.get(norm);\n\n if (entry) {\n await this.resolver.deleteFile(entry.id, this.ctx, entry.metadata);\n this.entries.delete(norm);\n this.mutations.push({ type: \"remove\", path: norm });\n return;\n }\n\n if (this.directories.has(norm)) {\n if (!options?.recursive) {\n throw new Error(`EISDIR: is a directory (use recursive): ${path}`);\n }\n const prefix = norm === \"/\" ? \"/\" : norm + \"/\";\n for (const [p, e] of this.entries) {\n if (p.startsWith(prefix)) {\n await this.resolver.deleteFile(e.id, this.ctx, e.metadata);\n this.entries.delete(p);\n this.mutations.push({ type: \"remove\", path: p });\n }\n }\n for (const d of this.directories) {\n if (d.startsWith(prefix)) this.directories.delete(d);\n }\n this.directories.delete(norm);\n return;\n }\n\n if (!options?.force) {\n throw new Error(`ENOENT: no such file or directory: ${path}`);\n }\n }\n\n async cp(\n src: string,\n dest: string,\n _options?: { recursive?: boolean }\n ): Promise<void> {\n const normSrc = normalisePath(src, this.workspaceBase);\n const normDest = normalisePath(dest, this.workspaceBase);\n\n const entry = this.entries.get(normSrc);\n if (entry) {\n const content = await this.resolver.readFile(\n entry.id,\n this.ctx,\n entry.metadata\n );\n await this.writeFile(normDest, content);\n return;\n }\n\n if (!this.directories.has(normSrc)) {\n throw new Error(`ENOENT: no such file or directory: ${src}`);\n }\n if (!_options?.recursive) {\n throw new Error(`EISDIR: is a directory (use recursive): ${src}`);\n }\n\n const prefix = normSrc === \"/\" ? \"/\" : normSrc + \"/\";\n for (const [p, e] of this.entries) {\n if (p.startsWith(prefix)) {\n const relative = p.slice(normSrc.length);\n const content = await this.resolver.readFile(\n e.id,\n this.ctx,\n e.metadata\n );\n await this.writeFile(normDest + relative, content);\n }\n }\n }\n\n async mv(src: string, dest: string): Promise<void> {\n await this.cp(src, dest, { recursive: true });\n await this.rm(src, { recursive: true });\n }\n\n // --------------------------------------------------------------------------\n // Unsupported\n // --------------------------------------------------------------------------\n\n async readlink(_path: string): Promise<string> {\n throw new SandboxNotSupportedError(\"readlink\");\n }\n\n resolvePath(base: string, path: string): string {\n return posix.resolve(normalisePath(base, this.workspaceBase), path);\n }\n\n // --------------------------------------------------------------------------\n // Helpers\n // --------------------------------------------------------------------------\n\n private addParentDirectories(filePath: string): void {\n let dir = parentDir(normalisePath(filePath, this.workspaceBase));\n while (!this.directories.has(dir)) {\n this.directories.add(dir);\n dir = parentDir(dir);\n }\n }\n}\n","import { uuid4 } from \"@temporalio/workflow\";\n\nconst BASE62 =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a compact, workflow-deterministic identifier.\n *\n * Uses Temporal's `uuid4()` internally (seeded by the workflow's RNG),\n * then re-encodes the hex bytes into a base-62 alphabet for a shorter,\n * more token-efficient identifier (~3 tokens vs ~10 for a full UUID).\n *\n * Suitable for thread IDs, child workflow IDs, or any workflow-scoped identifier.\n *\n * @param length - Number of base-62 characters (default 12, ~71 bits of entropy)\n */\nexport function getShortId(length = 12): string {\n const hex = uuid4().replace(/-/g, \"\");\n let result = \"\";\n for (let i = 0; i < length; i++) {\n const byte = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n result += BASE62[byte % BASE62.length];\n }\n return result;\n}\n","import type {\n SandboxCapabilities,\n SandboxCreateResult,\n SandboxProvider,\n} from \"../../../lib/sandbox/types\";\nimport { SandboxNotSupportedError } from \"../../../lib/sandbox/types\";\nimport { getShortId } from \"../../../lib/thread/id\";\nimport { createVirtualSandbox } from \"./index\";\nimport type {\n FileEntryMetadata,\n FileResolver,\n VirtualSandboxCreateOptions,\n} from \"./types\";\n\n/**\n * Stateless {@link SandboxProvider} backed by a {@link FileResolver}.\n *\n * The provider holds **no internal state**. All sandbox state (sandboxId,\n * fileTree, resolverContext, workspaceBase) is returned as a `stateUpdate` from\n * {@link create} and merged into the workflow's `AgentState` by the session.\n * {@link withVirtualSandbox} reads this state back on every tool invocation.\n *\n * @example\n * ```typescript\n * const provider = new VirtualSandboxProvider(resolver);\n * const manager = new SandboxManager(provider);\n *\n * export const activities = {\n * ...manager.createActivities(\"CodingAgent\"),\n * readFile: withVirtualSandbox(client, provider, readHandler),\n * };\n * ```\n */\nexport class VirtualSandboxProvider<\n TCtx = unknown,\n TMeta = FileEntryMetadata,\n> implements SandboxProvider<VirtualSandboxCreateOptions<TCtx>> {\n readonly id = \"virtual\";\n readonly capabilities: SandboxCapabilities = {\n filesystem: true,\n execution: false,\n persistence: true,\n };\n\n readonly resolver: FileResolver<TCtx, TMeta>;\n\n constructor(resolver: FileResolver<TCtx, TMeta>) {\n this.resolver = resolver;\n }\n\n async create(\n options?: VirtualSandboxCreateOptions<TCtx>\n ): Promise<SandboxCreateResult> {\n if (!options || !(\"resolverContext\" in options)) {\n throw new Error(\"VirtualSandboxProvider.create requires resolverContext\");\n }\n\n const sandboxId = options.id ?? getShortId();\n const fileTree = await this.resolver.resolveEntries(\n options.resolverContext\n );\n const workspaceBase = options.workspaceBase ?? \"/\";\n\n const sandbox = createVirtualSandbox(\n sandboxId,\n fileTree,\n this.resolver,\n options.resolverContext,\n workspaceBase,\n );\n\n if (options.initialFiles) {\n for (const [path, content] of Object.entries(options.initialFiles)) {\n await sandbox.fs.writeFile(path, content);\n }\n for (const m of sandbox.fs.getMutations()) {\n if (m.type === \"add\") fileTree.push(m.entry);\n }\n }\n\n return {\n sandbox,\n stateUpdate: {\n sandboxId,\n fileTree,\n resolverContext: options.resolverContext,\n workspaceBase,\n },\n };\n }\n\n async get(): Promise<never> {\n throw new SandboxNotSupportedError(\n \"get (virtual sandbox state lives in workflow AgentState)\"\n );\n }\n\n async destroy(): Promise<void> {\n // No-op — no internal state to clean up\n }\n\n async pause(): Promise<void> {\n // No-op — virtual sandbox state lives in workflow AgentState\n }\n\n async fork(_sandboxId: string): Promise<never> {\n throw new Error(\"Not implemented\");\n }\n\n async snapshot(): Promise<never> {\n throw new SandboxNotSupportedError(\n \"snapshot (virtual sandbox state lives in workflow AgentState)\"\n );\n }\n\n async restore(): Promise<never> {\n throw new SandboxNotSupportedError(\n \"restore (virtual sandbox state lives in workflow AgentState)\"\n );\n }\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 * 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 `RunAgentActivity` by auto-fetching the parent\n * workflow's agent state before each invocation.\n *\n * @example\n * ```typescript\n * import { createRunAgentActivity } from 'zeitlich';\n * import { createLangChainModelInvoker } from 'zeitlich/adapters/thread/langchain';\n *\n * const invoker = createLangChainModelInvoker({ redis, model });\n * return { runAgent: createRunAgentActivity(client, invoker) };\n * ```\n */\nexport function createRunAgentActivity<R, S extends BaseAgentState = BaseAgentState>(\n client: WorkflowClient,\n handler: (config: RunAgentConfig & { state: S }) => Promise<R>,\n): (config: RunAgentConfig) => Promise<R> {\n return async (config: RunAgentConfig) => {\n const state = await queryParentWorkflowState<S>(client);\n return handler({ ...config, state });\n };\n}\n\n/**\n * Context injected into tool handlers created via {@link withParentWorkflowState}.\n */\nexport interface AgentStateContext<S extends BaseAgentState = BaseAgentState> 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<TArgs, TResult, S extends BaseAgentState = BaseAgentState, TToolResponse = JsonValue>(\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 { WorkflowClient } from \"@temporalio/client\";\nimport { queryParentWorkflowState } from \"../../../lib/activity\";\nimport type { JsonValue } from \"../../../lib/state/types\";\nimport type { ActivityToolHandler, RouterContext } from \"../../../lib/tool-router/types\";\nimport type {\n FileEntryMetadata,\n TreeMutation,\n VirtualSandboxContext,\n VirtualSandboxState,\n} from \"./types\";\nimport type { VirtualSandboxProvider } from \"./provider\";\nimport { createVirtualSandbox } from \"./index\";\n\n/**\n * Wraps a tool handler that needs a virtual sandbox, automatically querying\n * the parent workflow for the current file tree and resolver context.\n *\n * On each invocation the wrapper:\n * 1. Queries the workflow's `AgentState` for `fileTree`, `resolverContext`, and `workspaceBase`\n * 2. Creates an ephemeral {@link VirtualSandbox} from tree + provider's resolver\n * 3. Runs the inner handler\n * 4. Returns the handler's result together with any {@link TreeMutation}s\n *\n * The consumer applies mutations back to workflow state via a post-tool hook.\n *\n * @param client - Temporal `WorkflowClient` for querying the parent workflow\n * @param agentName - Agent name (used to derive the state query name)\n * @param provider - {@link VirtualSandboxProvider} (wraps the resolver)\n * @param handler - Inner handler expecting a {@link VirtualSandboxContext}\n *\n * @example\n * ```typescript\n * import { withVirtualSandbox, type VirtualSandboxContext } from 'zeitlich';\n *\n * const readHandler: ActivityToolHandler<FileReadArgs, ReadResult, VirtualSandboxContext> =\n * async (args, { sandbox }) => {\n * const content = await sandbox.fs.readFile(args.path);\n * return { toolResponse: content, data: { path: args.path, content } };\n * };\n *\n * // At activity registration:\n * const provider = new VirtualSandboxProvider(resolver);\n * const handler = withVirtualSandbox(client, \"myAgent\", provider, readHandler);\n * ```\n */\nexport function withVirtualSandbox<\n TArgs,\n TResult,\n TCtx,\n TMeta = FileEntryMetadata,\n TToolResponse = JsonValue,\n>(\n client: WorkflowClient,\n provider: VirtualSandboxProvider<TCtx, TMeta>,\n handler: ActivityToolHandler<\n TArgs,\n TResult,\n VirtualSandboxContext<TCtx, TMeta>,\n TToolResponse\n >\n): ActivityToolHandler<\n TArgs,\n (TResult & { treeMutations: TreeMutation<TMeta>[] }) | null,\n RouterContext,\n TToolResponse | string\n> {\n return async (args, context) => {\n const state =\n await queryParentWorkflowState<VirtualSandboxState<TCtx, TMeta>>(client);\n\n const { sandboxId, fileTree, resolverContext, workspaceBase } = state;\n if (!fileTree || !sandboxId) {\n return {\n toolResponse: `Error: No fileTree/sandboxId in agent state. The ${context.toolName} tool requires a virtual sandbox.`,\n data: null,\n };\n }\n\n const sandbox = createVirtualSandbox(\n sandboxId,\n fileTree,\n provider.resolver,\n resolverContext,\n workspaceBase ?? \"/\",\n );\n const response = await handler(args, { ...context, sandbox });\n const mutations = sandbox.fs.getMutations();\n\n return {\n toolResponse: response.toolResponse,\n data: {\n ...(response.data ?? {}),\n treeMutations: mutations,\n } as TResult & { treeMutations: TreeMutation<TMeta>[] },\n };\n };\n}\n","import type { FileEntry } from \"./types\";\n\n/**\n * Structural constraint: accepts any `AgentStateManager<T>` whose custom\n * state includes `fileTree: FileEntry<TMeta>[]`.\n */\nexport interface FileTreeAccessor<TMeta> {\n get(key: \"fileTree\"): FileEntry<TMeta>[];\n}\n\n/**\n * Check whether any file in the tree has a `metadata.mimeType` that matches\n * the given pattern.\n *\n * Patterns:\n * - Exact: `\"application/pdf\"`\n * - Wildcard type: `\"image/*\"`\n *\n * Useful for conditionally enabling tools:\n *\n * ```ts\n * { enabled: hasFileWithMimeType(stateManager, \"image/*\") }\n * { enabled: hasFileWithMimeType(stateManager, [\"image/*\", \"application/pdf\"]) }\n * ```\n */\nexport function hasFileWithMimeType<TMeta>(\n stateManager: FileTreeAccessor<TMeta>,\n pattern: string | string[],\n): boolean {\n const tree = stateManager.get(\"fileTree\");\n const matchers = (Array.isArray(pattern) ? pattern : [pattern]).map(buildMatcher);\n return tree.some((entry) => {\n const meta = entry.metadata as Record<string, unknown> | undefined;\n const mime = meta?.mimeType;\n return typeof mime === \"string\" && matchers.some((m) => m(mime));\n });\n}\n\n/**\n * Return all entries whose `metadata.mimeType` matches the given pattern.\n */\nexport function filesWithMimeType<TMeta>(\n stateManager: FileTreeAccessor<TMeta>,\n pattern: string,\n): FileEntry<TMeta>[] {\n const tree = stateManager.get(\"fileTree\");\n const match = buildMatcher(pattern);\n return tree.filter((entry) => {\n const meta = entry.metadata as Record<string, unknown> | undefined;\n const mime = meta?.mimeType;\n return typeof mime === \"string\" && match(mime);\n });\n}\n\n/**\n * Check whether the tree contains a directory whose name matches the given\n * pattern. Directories are inferred from file paths.\n *\n * Patterns:\n * - Exact: `\"src\"`\n * - Glob with `*` wildcard: `\"test*\"`, `\"*.generated\"`\n *\n * ```ts\n * { enabled: hasDirectory(stateManager, \"test*\") }\n * ```\n */\nexport function hasDirectory<TMeta>(\n stateManager: FileTreeAccessor<TMeta>,\n pattern: string,\n): boolean {\n const tree = stateManager.get(\"fileTree\");\n const match = buildGlobMatcher(pattern);\n return tree.some((entry) => {\n const segments = entry.path.split(\"/\").filter(Boolean);\n return segments.slice(0, -1).some(match);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Internal matchers\n// ---------------------------------------------------------------------------\n\nfunction buildMatcher(pattern: string): (value: string) => boolean {\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return (v) => v.startsWith(prefix);\n }\n return (v) => v === pattern;\n}\n\nfunction buildGlobMatcher(pattern: string): (value: string) => boolean {\n if (!pattern.includes(\"*\")) return (v) => v === pattern;\n const re = new RegExp(\n \"^\" + pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\") + \"$\",\n );\n return (v) => re.test(v);\n}\n","import type {\n Sandbox,\n SandboxCapabilities,\n ExecOptions,\n ExecResult,\n} from \"../../../lib/sandbox/types\";\nimport { SandboxNotSupportedError } from \"../../../lib/sandbox/types\";\nimport { VirtualSandboxFileSystem } from \"./filesystem\";\nimport type {\n FileEntry,\n FileEntryMetadata,\n FileResolver,\n VirtualSandbox,\n} from \"./types\";\n\n// ============================================================================\n// VirtualSandbox\n// ============================================================================\n\nclass VirtualSandboxImpl<\n TCtx = unknown,\n TMeta = FileEntryMetadata,\n> implements Sandbox\n{\n readonly capabilities: SandboxCapabilities = {\n filesystem: true,\n execution: false,\n persistence: true,\n };\n\n readonly fs: VirtualSandboxFileSystem<TCtx, TMeta>;\n\n constructor(\n readonly id: string,\n tree: FileEntry<TMeta>[],\n resolver: FileResolver<TCtx, TMeta>,\n ctx: TCtx,\n workspaceBase = \"/\",\n ) {\n this.fs = new VirtualSandboxFileSystem(tree, resolver, ctx, workspaceBase);\n }\n\n async exec(_command: string, _options?: ExecOptions): Promise<ExecResult> {\n throw new SandboxNotSupportedError(\"exec\");\n }\n\n async destroy(): Promise<void> {\n // Ephemeral — nothing to clean up\n }\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\n/**\n * Create an ephemeral {@link Sandbox} from a file tree and resolver.\n *\n * Used internally by {@link withVirtualSandbox} and\n * {@link VirtualSandboxProvider}; consumers can also call this directly\n * if they need a sandbox outside the wrapper pattern.\n */\nexport function createVirtualSandbox<\n TCtx,\n TMeta = FileEntryMetadata,\n>(\n id: string,\n tree: FileEntry<TMeta>[],\n resolver: FileResolver<TCtx, TMeta>,\n ctx: TCtx,\n workspaceBase = \"/\",\n): VirtualSandbox<TCtx, TMeta> {\n return new VirtualSandboxImpl(id, tree, resolver, ctx, workspaceBase);\n}\n\n// Re-exports for convenience\nexport { VirtualSandboxFileSystem } from \"./filesystem\";\nexport { VirtualSandboxProvider } from \"./provider\";\nexport { withVirtualSandbox } from \"./with-virtual-sandbox\";\nexport { hasFileWithMimeType, filesWithMimeType, hasDirectory } from \"./queries\";\nexport type { FileTreeAccessor } from \"./queries\";\nexport type {\n FileEntry,\n FileEntryMetadata,\n FileResolver,\n VirtualFileTree,\n VirtualSandboxCreateOptions,\n VirtualSandboxState,\n VirtualSandboxContext,\n VirtualSandbox,\n TreeMutation,\n} from \"./types\";\n"]}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { a as FileEntryMetadata, V as VirtualSandboxCreateOptions, b as FileResolver, c as VirtualSandboxContext, T as TreeMutation, F as FileEntry, d as VirtualSandbox } from '../../../types-
|
|
2
|
-
export { e as VirtualFileTree, f as VirtualSandboxFileSystem, g as VirtualSandboxState } from '../../../types-
|
|
1
|
+
import { a as FileEntryMetadata, V as VirtualSandboxCreateOptions, b as FileResolver, c as VirtualSandboxContext, T as TreeMutation, F as FileEntry, d as VirtualSandbox } from '../../../types-DRnz-OZp.cjs';
|
|
2
|
+
export { e as VirtualFileTree, f as VirtualSandboxFileSystem, g as VirtualSandboxState } from '../../../types-DRnz-OZp.cjs';
|
|
3
3
|
import { b as SandboxProvider, c as SandboxCapabilities, e as SandboxCreateResult } from '../../../types-ChAMwU3q.cjs';
|
|
4
4
|
import { WorkflowClient } from '@temporalio/client';
|
|
5
|
-
import { A as ActivityToolHandler } from '../../../types-
|
|
6
|
-
export { F as FileTreeAccessor, f as filesWithMimeType, h as hasDirectory, a as hasFileWithMimeType } from '../../../queries-
|
|
5
|
+
import { J as JsonValue, A as ActivityToolHandler, R as RouterContext } from '../../../types-mCVxKIZb.cjs';
|
|
6
|
+
export { F as FileTreeAccessor, f as filesWithMimeType, h as hasDirectory, a as hasFileWithMimeType } from '../../../queries-DwnE2bu3.cjs';
|
|
7
7
|
import '@temporalio/common';
|
|
8
|
-
import 'zod';
|
|
9
8
|
import '@temporalio/workflow';
|
|
9
|
+
import '@temporalio/common/lib/interfaces';
|
|
10
|
+
import 'zod';
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Stateless {@link SandboxProvider} backed by a {@link FileResolver}.
|
|
@@ -73,9 +74,9 @@ declare class VirtualSandboxProvider<TCtx = unknown, TMeta = FileEntryMetadata>
|
|
|
73
74
|
* const handler = withVirtualSandbox(client, "myAgent", provider, readHandler);
|
|
74
75
|
* ```
|
|
75
76
|
*/
|
|
76
|
-
declare function withVirtualSandbox<TArgs, TResult, TCtx, TMeta = FileEntryMetadata>(client: WorkflowClient, provider: VirtualSandboxProvider<TCtx, TMeta>, handler: ActivityToolHandler<TArgs, TResult, VirtualSandboxContext<TCtx, TMeta
|
|
77
|
+
declare function withVirtualSandbox<TArgs, TResult, TCtx, TMeta = FileEntryMetadata, TToolResponse = JsonValue>(client: WorkflowClient, provider: VirtualSandboxProvider<TCtx, TMeta>, handler: ActivityToolHandler<TArgs, TResult, VirtualSandboxContext<TCtx, TMeta>, TToolResponse>): ActivityToolHandler<TArgs, (TResult & {
|
|
77
78
|
treeMutations: TreeMutation<TMeta>[];
|
|
78
|
-
}) | null>;
|
|
79
|
+
}) | null, RouterContext, TToolResponse | string>;
|
|
79
80
|
|
|
80
81
|
/**
|
|
81
82
|
* Create an ephemeral {@link Sandbox} from a file tree and resolver.
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { a as FileEntryMetadata, V as VirtualSandboxCreateOptions, b as FileResolver, c as VirtualSandboxContext, T as TreeMutation, F as FileEntry, d as VirtualSandbox } from '../../../types-
|
|
2
|
-
export { e as VirtualFileTree, f as VirtualSandboxFileSystem, g as VirtualSandboxState } from '../../../types-
|
|
1
|
+
import { a as FileEntryMetadata, V as VirtualSandboxCreateOptions, b as FileResolver, c as VirtualSandboxContext, T as TreeMutation, F as FileEntry, d as VirtualSandbox } from '../../../types-DFUNSYbj.js';
|
|
2
|
+
export { e as VirtualFileTree, f as VirtualSandboxFileSystem, g as VirtualSandboxState } from '../../../types-DFUNSYbj.js';
|
|
3
3
|
import { b as SandboxProvider, c as SandboxCapabilities, e as SandboxCreateResult } from '../../../types-ChAMwU3q.js';
|
|
4
4
|
import { WorkflowClient } from '@temporalio/client';
|
|
5
|
-
import { A as ActivityToolHandler } from '../../../types-
|
|
6
|
-
export { F as FileTreeAccessor, f as filesWithMimeType, h as hasDirectory, a as hasFileWithMimeType } from '../../../queries-
|
|
5
|
+
import { J as JsonValue, A as ActivityToolHandler, R as RouterContext } from '../../../types-mCVxKIZb.js';
|
|
6
|
+
export { F as FileTreeAccessor, f as filesWithMimeType, h as hasDirectory, a as hasFileWithMimeType } from '../../../queries-BCgJ9Sr5.js';
|
|
7
7
|
import '@temporalio/common';
|
|
8
|
-
import 'zod';
|
|
9
8
|
import '@temporalio/workflow';
|
|
9
|
+
import '@temporalio/common/lib/interfaces';
|
|
10
|
+
import 'zod';
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Stateless {@link SandboxProvider} backed by a {@link FileResolver}.
|
|
@@ -73,9 +74,9 @@ declare class VirtualSandboxProvider<TCtx = unknown, TMeta = FileEntryMetadata>
|
|
|
73
74
|
* const handler = withVirtualSandbox(client, "myAgent", provider, readHandler);
|
|
74
75
|
* ```
|
|
75
76
|
*/
|
|
76
|
-
declare function withVirtualSandbox<TArgs, TResult, TCtx, TMeta = FileEntryMetadata>(client: WorkflowClient, provider: VirtualSandboxProvider<TCtx, TMeta>, handler: ActivityToolHandler<TArgs, TResult, VirtualSandboxContext<TCtx, TMeta
|
|
77
|
+
declare function withVirtualSandbox<TArgs, TResult, TCtx, TMeta = FileEntryMetadata, TToolResponse = JsonValue>(client: WorkflowClient, provider: VirtualSandboxProvider<TCtx, TMeta>, handler: ActivityToolHandler<TArgs, TResult, VirtualSandboxContext<TCtx, TMeta>, TToolResponse>): ActivityToolHandler<TArgs, (TResult & {
|
|
77
78
|
treeMutations: TreeMutation<TMeta>[];
|
|
78
|
-
}) | null>;
|
|
79
|
+
}) | null, RouterContext, TToolResponse | string>;
|
|
79
80
|
|
|
80
81
|
/**
|
|
81
82
|
* Create an ephemeral {@link Sandbox} from a file tree and resolver.
|