@enclave-vm/react 0.0.1 → 2.9.0
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/LICENSE +201 -0
- package/README.md +288 -0
- package/esm/index.mjs +169 -0
- package/esm/package.json +6 -0
- package/index.js +199 -0
- package/package.json +10 -9
- package/src/EnclaveProvider.js +0 -97
- package/src/EnclaveProvider.js.map +0 -1
- package/src/index.js +0 -19
- package/src/index.js.map +0 -1
- package/src/test-setup.js +0 -7
- package/src/test-setup.js.map +0 -1
- package/src/types.js +0 -10
- package/src/types.js.map +0 -1
- package/src/useEnclaveSession.js +0 -181
- package/src/useEnclaveSession.js.map +0 -1
- /package/{src/EnclaveProvider.d.ts → EnclaveProvider.d.ts} +0 -0
- /package/{src/index.d.ts → index.d.ts} +0 -0
- /package/{src/test-setup.d.ts → test-setup.d.ts} +0 -0
- /package/{src/types.d.ts → types.d.ts} +0 -0
- /package/{src/useEnclaveSession.d.ts → useEnclaveSession.d.ts} +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
# @enclave-vm/react
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@enclave-vm/react)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
|
|
7
|
+
> React hooks and components for the EnclaveJS streaming runtime
|
|
8
|
+
|
|
9
|
+
The @enclave-vm/react package provides React bindings for EnclaveJS, including hooks for code execution, connection management, and pre-built components for common use cases like code editors and output displays.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **React Hooks**: `useEnclave`, `useExecution`, `useSession` hooks
|
|
14
|
+
- **Context Provider**: Share client instance across components
|
|
15
|
+
- **TypeScript Support**: Full type definitions
|
|
16
|
+
- **SSR Compatible**: Works with Next.js and other SSR frameworks
|
|
17
|
+
- **Suspense Ready**: Built-in support for React Suspense
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install @enclave-vm/react @enclave-vm/client
|
|
23
|
+
# or
|
|
24
|
+
yarn add @enclave-vm/react @enclave-vm/client
|
|
25
|
+
# or
|
|
26
|
+
pnpm add @enclave-vm/react @enclave-vm/client
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
import { EnclaveProvider, useEnclave } from '@enclave-vm/react';
|
|
33
|
+
|
|
34
|
+
function App() {
|
|
35
|
+
return (
|
|
36
|
+
<EnclaveProvider url="wss://runtime.example.com">
|
|
37
|
+
<CodeRunner />
|
|
38
|
+
</EnclaveProvider>
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function CodeRunner() {
|
|
43
|
+
const { execute, isConnected, isExecuting } = useEnclave();
|
|
44
|
+
const [result, setResult] = useState(null);
|
|
45
|
+
|
|
46
|
+
const runCode = async () => {
|
|
47
|
+
const res = await execute(`
|
|
48
|
+
const user = await callTool('getUser', { id: 1 });
|
|
49
|
+
return user.name;
|
|
50
|
+
`);
|
|
51
|
+
setResult(res.value);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
return (
|
|
55
|
+
<div>
|
|
56
|
+
<button onClick={runCode} disabled={!isConnected || isExecuting}>
|
|
57
|
+
{isExecuting ? 'Running...' : 'Run Code'}
|
|
58
|
+
</button>
|
|
59
|
+
{result && <div>Result: {result}</div>}
|
|
60
|
+
</div>
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Hooks
|
|
66
|
+
|
|
67
|
+
### useEnclave
|
|
68
|
+
|
|
69
|
+
Main hook for interacting with the EnclaveJS runtime:
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
import { useEnclave } from '@enclave-vm/react';
|
|
73
|
+
|
|
74
|
+
function MyComponent() {
|
|
75
|
+
const {
|
|
76
|
+
// Connection
|
|
77
|
+
isConnected,
|
|
78
|
+
connect,
|
|
79
|
+
disconnect,
|
|
80
|
+
|
|
81
|
+
// Execution
|
|
82
|
+
execute,
|
|
83
|
+
stream,
|
|
84
|
+
isExecuting,
|
|
85
|
+
|
|
86
|
+
// Session
|
|
87
|
+
sessionId,
|
|
88
|
+
createSession,
|
|
89
|
+
destroySession,
|
|
90
|
+
|
|
91
|
+
// Events
|
|
92
|
+
onToolCall,
|
|
93
|
+
onToolResult,
|
|
94
|
+
onLog,
|
|
95
|
+
onError,
|
|
96
|
+
} = useEnclave();
|
|
97
|
+
|
|
98
|
+
// Subscribe to tool calls
|
|
99
|
+
useEffect(() => {
|
|
100
|
+
const unsubscribe = onToolCall((call) => {
|
|
101
|
+
console.log('Tool called:', call.name);
|
|
102
|
+
});
|
|
103
|
+
return unsubscribe;
|
|
104
|
+
}, [onToolCall]);
|
|
105
|
+
|
|
106
|
+
return <div>{isConnected ? 'Connected' : 'Disconnected'}</div>;
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### useExecution
|
|
111
|
+
|
|
112
|
+
Hook for managing individual code executions:
|
|
113
|
+
|
|
114
|
+
```tsx
|
|
115
|
+
import { useExecution } from '@enclave-vm/react';
|
|
116
|
+
|
|
117
|
+
function ExecutionComponent() {
|
|
118
|
+
const { execute, result, error, isLoading, toolCalls } = useExecution();
|
|
119
|
+
|
|
120
|
+
return (
|
|
121
|
+
<div>
|
|
122
|
+
<button onClick={() => execute('return 1 + 1')} disabled={isLoading}>
|
|
123
|
+
Execute
|
|
124
|
+
</button>
|
|
125
|
+
|
|
126
|
+
{isLoading && <div>Executing...</div>}
|
|
127
|
+
{error && <div>Error: {error.message}</div>}
|
|
128
|
+
{result && <div>Result: {JSON.stringify(result.value)}</div>}
|
|
129
|
+
|
|
130
|
+
<div>
|
|
131
|
+
<h3>Tool Calls:</h3>
|
|
132
|
+
{toolCalls.map((call) => (
|
|
133
|
+
<div key={call.id}>
|
|
134
|
+
{call.name}: {JSON.stringify(call.args)}
|
|
135
|
+
</div>
|
|
136
|
+
))}
|
|
137
|
+
</div>
|
|
138
|
+
</div>
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### useSession
|
|
144
|
+
|
|
145
|
+
Hook for persistent session management:
|
|
146
|
+
|
|
147
|
+
```tsx
|
|
148
|
+
import { useSession } from '@enclave-vm/react';
|
|
149
|
+
|
|
150
|
+
function SessionComponent() {
|
|
151
|
+
const { session, create, destroy, execute, isActive } = useSession();
|
|
152
|
+
|
|
153
|
+
useEffect(() => {
|
|
154
|
+
create({ timeout: 60000 });
|
|
155
|
+
return () => destroy();
|
|
156
|
+
}, []);
|
|
157
|
+
|
|
158
|
+
if (!isActive) return <div>No active session</div>;
|
|
159
|
+
|
|
160
|
+
return (
|
|
161
|
+
<div>
|
|
162
|
+
<div>Session: {session.id}</div>
|
|
163
|
+
<button onClick={() => execute('return Date.now()')}>Get Time</button>
|
|
164
|
+
</div>
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Provider Options
|
|
170
|
+
|
|
171
|
+
```tsx
|
|
172
|
+
import { EnclaveProvider } from '@enclave-vm/react';
|
|
173
|
+
|
|
174
|
+
function App() {
|
|
175
|
+
return (
|
|
176
|
+
<EnclaveProvider
|
|
177
|
+
url="wss://runtime.example.com"
|
|
178
|
+
auth={{ token: 'your-token' }}
|
|
179
|
+
autoConnect={true}
|
|
180
|
+
reconnect={{
|
|
181
|
+
enabled: true,
|
|
182
|
+
maxAttempts: 5,
|
|
183
|
+
}}
|
|
184
|
+
onConnected={() => console.log('Connected!')}
|
|
185
|
+
onDisconnected={() => console.log('Disconnected')}
|
|
186
|
+
onError={(error) => console.error(error)}
|
|
187
|
+
>
|
|
188
|
+
<App />
|
|
189
|
+
</EnclaveProvider>
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Streaming Results
|
|
195
|
+
|
|
196
|
+
Handle streaming execution with real-time updates:
|
|
197
|
+
|
|
198
|
+
```tsx
|
|
199
|
+
import { useEnclave } from '@enclave-vm/react';
|
|
200
|
+
|
|
201
|
+
function StreamingComponent() {
|
|
202
|
+
const { stream } = useEnclave();
|
|
203
|
+
const [items, setItems] = useState([]);
|
|
204
|
+
|
|
205
|
+
const runStreaming = async () => {
|
|
206
|
+
setItems([]);
|
|
207
|
+
await stream(
|
|
208
|
+
`
|
|
209
|
+
for (const i of [1, 2, 3, 4, 5]) {
|
|
210
|
+
const data = await callTool('processItem', { id: i });
|
|
211
|
+
yield data;
|
|
212
|
+
}
|
|
213
|
+
`,
|
|
214
|
+
{
|
|
215
|
+
onYield: (value) => {
|
|
216
|
+
setItems((prev) => [...prev, value]);
|
|
217
|
+
},
|
|
218
|
+
},
|
|
219
|
+
);
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
return (
|
|
223
|
+
<div>
|
|
224
|
+
<button onClick={runStreaming}>Start Streaming</button>
|
|
225
|
+
<ul>
|
|
226
|
+
{items.map((item, i) => (
|
|
227
|
+
<li key={i}>{JSON.stringify(item)}</li>
|
|
228
|
+
))}
|
|
229
|
+
</ul>
|
|
230
|
+
</div>
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## Error Boundaries
|
|
236
|
+
|
|
237
|
+
Use with React error boundaries:
|
|
238
|
+
|
|
239
|
+
```tsx
|
|
240
|
+
import { EnclaveErrorBoundary } from '@enclave-vm/react';
|
|
241
|
+
|
|
242
|
+
function App() {
|
|
243
|
+
return (
|
|
244
|
+
<EnclaveErrorBoundary
|
|
245
|
+
fallback={(error, reset) => (
|
|
246
|
+
<div>
|
|
247
|
+
<p>Something went wrong: {error.message}</p>
|
|
248
|
+
<button onClick={reset}>Try again</button>
|
|
249
|
+
</div>
|
|
250
|
+
)}
|
|
251
|
+
>
|
|
252
|
+
<CodeRunner />
|
|
253
|
+
</EnclaveErrorBoundary>
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Server Components (Next.js)
|
|
259
|
+
|
|
260
|
+
For Next.js App Router, use client components:
|
|
261
|
+
|
|
262
|
+
```tsx
|
|
263
|
+
// components/code-runner.tsx
|
|
264
|
+
'use client';
|
|
265
|
+
|
|
266
|
+
import { EnclaveProvider, useEnclave } from '@enclave-vm/react';
|
|
267
|
+
|
|
268
|
+
export function CodeRunner() {
|
|
269
|
+
return (
|
|
270
|
+
<EnclaveProvider url={process.env.NEXT_PUBLIC_ENCLAVE_URL!}>
|
|
271
|
+
<RunnerInner />
|
|
272
|
+
</EnclaveProvider>
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Related Packages
|
|
278
|
+
|
|
279
|
+
| Package | Description |
|
|
280
|
+
| ------------------------------------------- | --------------------------------- |
|
|
281
|
+
| [@enclave-vm/types](../enclavejs-types) | Type definitions and Zod schemas |
|
|
282
|
+
| [@enclave-vm/client](../enclavejs-client) | Browser/Node.js client SDK |
|
|
283
|
+
| [@enclave-vm/stream](../enclavejs-stream) | Streaming protocol implementation |
|
|
284
|
+
| [@enclave-vm/runtime](../enclavejs-runtime) | Standalone runtime worker |
|
|
285
|
+
|
|
286
|
+
## License
|
|
287
|
+
|
|
288
|
+
Apache-2.0
|
package/esm/index.mjs
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// libs/enclavejs-react/src/EnclaveProvider.tsx
|
|
2
|
+
import { createContext, useContext, useMemo, useRef } from "react";
|
|
3
|
+
import { EnclaveClient } from "@enclave-vm/client";
|
|
4
|
+
import { jsx } from "react/jsx-runtime";
|
|
5
|
+
var EnclaveContext = createContext(null);
|
|
6
|
+
function EnclaveProvider({
|
|
7
|
+
config,
|
|
8
|
+
client: providedClient,
|
|
9
|
+
children
|
|
10
|
+
}) {
|
|
11
|
+
const clientRef = useRef(null);
|
|
12
|
+
const client = useMemo(() => {
|
|
13
|
+
if (providedClient) {
|
|
14
|
+
return providedClient;
|
|
15
|
+
}
|
|
16
|
+
if (!clientRef.current) {
|
|
17
|
+
clientRef.current = new EnclaveClient(config);
|
|
18
|
+
}
|
|
19
|
+
return clientRef.current;
|
|
20
|
+
}, [providedClient, config]);
|
|
21
|
+
const contextValue = useMemo(
|
|
22
|
+
() => ({
|
|
23
|
+
client,
|
|
24
|
+
config
|
|
25
|
+
}),
|
|
26
|
+
[client, config]
|
|
27
|
+
);
|
|
28
|
+
return /* @__PURE__ */ jsx(EnclaveContext.Provider, { value: contextValue, children });
|
|
29
|
+
}
|
|
30
|
+
function useEnclaveContext() {
|
|
31
|
+
const context = useContext(EnclaveContext);
|
|
32
|
+
if (!context) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
"useEnclaveContext must be used within an EnclaveProvider. Wrap your component tree with <EnclaveProvider config={{...}}>."
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
return context;
|
|
38
|
+
}
|
|
39
|
+
function useEnclaveClient() {
|
|
40
|
+
const { client } = useEnclaveContext();
|
|
41
|
+
return client;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// libs/enclavejs-react/src/useEnclaveSession.ts
|
|
45
|
+
import { useState, useCallback, useRef as useRef2 } from "react";
|
|
46
|
+
function useEnclaveSession(options = {}) {
|
|
47
|
+
const client = useEnclaveClient();
|
|
48
|
+
const [state, setState] = useState("idle");
|
|
49
|
+
const [sessionId, setSessionId] = useState(null);
|
|
50
|
+
const [result, setResult] = useState(null);
|
|
51
|
+
const [error, setError] = useState(null);
|
|
52
|
+
const [stdout, setStdout] = useState("");
|
|
53
|
+
const [events, setEvents] = useState([]);
|
|
54
|
+
const handleRef = useRef2(null);
|
|
55
|
+
const reset = useCallback(() => {
|
|
56
|
+
setState("idle");
|
|
57
|
+
setSessionId(null);
|
|
58
|
+
setResult(null);
|
|
59
|
+
setError(null);
|
|
60
|
+
setStdout("");
|
|
61
|
+
setEvents([]);
|
|
62
|
+
handleRef.current = null;
|
|
63
|
+
}, []);
|
|
64
|
+
const execute = useCallback(
|
|
65
|
+
async (code) => {
|
|
66
|
+
setState("running");
|
|
67
|
+
setResult(null);
|
|
68
|
+
setError(null);
|
|
69
|
+
setStdout("");
|
|
70
|
+
setEvents([]);
|
|
71
|
+
options.onStart?.();
|
|
72
|
+
const limits = {};
|
|
73
|
+
if (options.timeoutMs !== void 0) {
|
|
74
|
+
limits.sessionTtlMs = options.timeoutMs;
|
|
75
|
+
}
|
|
76
|
+
if (options.maxToolCalls !== void 0) {
|
|
77
|
+
limits.maxToolCalls = options.maxToolCalls;
|
|
78
|
+
}
|
|
79
|
+
if (options.heartbeatIntervalMs !== void 0) {
|
|
80
|
+
limits.heartbeatIntervalMs = options.heartbeatIntervalMs;
|
|
81
|
+
}
|
|
82
|
+
const handle = client.executeStream(code, {
|
|
83
|
+
sessionId: options.sessionId,
|
|
84
|
+
limits: Object.keys(limits).length > 0 ? limits : void 0,
|
|
85
|
+
onEvent: (event) => {
|
|
86
|
+
setEvents((prev) => [...prev, event]);
|
|
87
|
+
},
|
|
88
|
+
onStdout: (chunk) => {
|
|
89
|
+
setStdout((prev) => prev + chunk);
|
|
90
|
+
options.onStdout?.(chunk);
|
|
91
|
+
},
|
|
92
|
+
onLog: (level, message, data) => {
|
|
93
|
+
options.onLog?.(level, message, data);
|
|
94
|
+
},
|
|
95
|
+
onToolCall: (callId, toolName, args) => {
|
|
96
|
+
options.onToolCall?.(callId, toolName, args);
|
|
97
|
+
},
|
|
98
|
+
onToolResultApplied: (callId) => {
|
|
99
|
+
options.onToolResultApplied?.(callId);
|
|
100
|
+
},
|
|
101
|
+
onError: (code2, message) => {
|
|
102
|
+
options.onError?.({ code: code2, message });
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
handleRef.current = handle;
|
|
106
|
+
setSessionId(handle.sessionId);
|
|
107
|
+
try {
|
|
108
|
+
const sessionResult = await handle.wait();
|
|
109
|
+
if (sessionResult.success) {
|
|
110
|
+
setState("completed");
|
|
111
|
+
setResult(sessionResult);
|
|
112
|
+
} else if (sessionResult.error?.code === "CANCELLED") {
|
|
113
|
+
setState("cancelled");
|
|
114
|
+
setResult(sessionResult);
|
|
115
|
+
} else {
|
|
116
|
+
setState("error");
|
|
117
|
+
setResult(sessionResult);
|
|
118
|
+
setError(sessionResult.error ?? { message: "Unknown error" });
|
|
119
|
+
options.onError?.(sessionResult.error ?? { message: "Unknown error" });
|
|
120
|
+
}
|
|
121
|
+
options.onComplete?.(sessionResult);
|
|
122
|
+
return sessionResult;
|
|
123
|
+
} catch (err) {
|
|
124
|
+
const errorInfo = {
|
|
125
|
+
code: "UNEXPECTED_ERROR",
|
|
126
|
+
message: err instanceof Error ? err.message : "Unknown error"
|
|
127
|
+
};
|
|
128
|
+
setState("error");
|
|
129
|
+
setError(errorInfo);
|
|
130
|
+
options.onError?.(errorInfo);
|
|
131
|
+
const errorResult = {
|
|
132
|
+
success: false,
|
|
133
|
+
sessionId: handle.sessionId,
|
|
134
|
+
error: errorInfo,
|
|
135
|
+
events: handle.getEvents()
|
|
136
|
+
};
|
|
137
|
+
setResult(errorResult);
|
|
138
|
+
options.onComplete?.(errorResult);
|
|
139
|
+
return errorResult;
|
|
140
|
+
} finally {
|
|
141
|
+
handleRef.current = null;
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
[client, options]
|
|
145
|
+
);
|
|
146
|
+
const cancel = useCallback(async (reason) => {
|
|
147
|
+
if (handleRef.current) {
|
|
148
|
+
await handleRef.current.cancel(reason);
|
|
149
|
+
}
|
|
150
|
+
}, []);
|
|
151
|
+
return {
|
|
152
|
+
execute,
|
|
153
|
+
cancel,
|
|
154
|
+
state,
|
|
155
|
+
isRunning: state === "running",
|
|
156
|
+
sessionId,
|
|
157
|
+
result,
|
|
158
|
+
error,
|
|
159
|
+
stdout,
|
|
160
|
+
events,
|
|
161
|
+
reset
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
export {
|
|
165
|
+
EnclaveProvider,
|
|
166
|
+
useEnclaveClient,
|
|
167
|
+
useEnclaveContext,
|
|
168
|
+
useEnclaveSession
|
|
169
|
+
};
|
package/esm/package.json
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// libs/enclavejs-react/src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
EnclaveProvider: () => EnclaveProvider,
|
|
24
|
+
useEnclaveClient: () => useEnclaveClient,
|
|
25
|
+
useEnclaveContext: () => useEnclaveContext,
|
|
26
|
+
useEnclaveSession: () => useEnclaveSession
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
|
|
30
|
+
// libs/enclavejs-react/src/EnclaveProvider.tsx
|
|
31
|
+
var import_react = require("react");
|
|
32
|
+
var import_client = require("@enclave-vm/client");
|
|
33
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
34
|
+
var EnclaveContext = (0, import_react.createContext)(null);
|
|
35
|
+
function EnclaveProvider({
|
|
36
|
+
config,
|
|
37
|
+
client: providedClient,
|
|
38
|
+
children
|
|
39
|
+
}) {
|
|
40
|
+
const clientRef = (0, import_react.useRef)(null);
|
|
41
|
+
const client = (0, import_react.useMemo)(() => {
|
|
42
|
+
if (providedClient) {
|
|
43
|
+
return providedClient;
|
|
44
|
+
}
|
|
45
|
+
if (!clientRef.current) {
|
|
46
|
+
clientRef.current = new import_client.EnclaveClient(config);
|
|
47
|
+
}
|
|
48
|
+
return clientRef.current;
|
|
49
|
+
}, [providedClient, config]);
|
|
50
|
+
const contextValue = (0, import_react.useMemo)(
|
|
51
|
+
() => ({
|
|
52
|
+
client,
|
|
53
|
+
config
|
|
54
|
+
}),
|
|
55
|
+
[client, config]
|
|
56
|
+
);
|
|
57
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EnclaveContext.Provider, { value: contextValue, children });
|
|
58
|
+
}
|
|
59
|
+
function useEnclaveContext() {
|
|
60
|
+
const context = (0, import_react.useContext)(EnclaveContext);
|
|
61
|
+
if (!context) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
"useEnclaveContext must be used within an EnclaveProvider. Wrap your component tree with <EnclaveProvider config={{...}}>."
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
return context;
|
|
67
|
+
}
|
|
68
|
+
function useEnclaveClient() {
|
|
69
|
+
const { client } = useEnclaveContext();
|
|
70
|
+
return client;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// libs/enclavejs-react/src/useEnclaveSession.ts
|
|
74
|
+
var import_react2 = require("react");
|
|
75
|
+
function useEnclaveSession(options = {}) {
|
|
76
|
+
const client = useEnclaveClient();
|
|
77
|
+
const [state, setState] = (0, import_react2.useState)("idle");
|
|
78
|
+
const [sessionId, setSessionId] = (0, import_react2.useState)(null);
|
|
79
|
+
const [result, setResult] = (0, import_react2.useState)(null);
|
|
80
|
+
const [error, setError] = (0, import_react2.useState)(null);
|
|
81
|
+
const [stdout, setStdout] = (0, import_react2.useState)("");
|
|
82
|
+
const [events, setEvents] = (0, import_react2.useState)([]);
|
|
83
|
+
const handleRef = (0, import_react2.useRef)(null);
|
|
84
|
+
const reset = (0, import_react2.useCallback)(() => {
|
|
85
|
+
setState("idle");
|
|
86
|
+
setSessionId(null);
|
|
87
|
+
setResult(null);
|
|
88
|
+
setError(null);
|
|
89
|
+
setStdout("");
|
|
90
|
+
setEvents([]);
|
|
91
|
+
handleRef.current = null;
|
|
92
|
+
}, []);
|
|
93
|
+
const execute = (0, import_react2.useCallback)(
|
|
94
|
+
async (code) => {
|
|
95
|
+
setState("running");
|
|
96
|
+
setResult(null);
|
|
97
|
+
setError(null);
|
|
98
|
+
setStdout("");
|
|
99
|
+
setEvents([]);
|
|
100
|
+
options.onStart?.();
|
|
101
|
+
const limits = {};
|
|
102
|
+
if (options.timeoutMs !== void 0) {
|
|
103
|
+
limits.sessionTtlMs = options.timeoutMs;
|
|
104
|
+
}
|
|
105
|
+
if (options.maxToolCalls !== void 0) {
|
|
106
|
+
limits.maxToolCalls = options.maxToolCalls;
|
|
107
|
+
}
|
|
108
|
+
if (options.heartbeatIntervalMs !== void 0) {
|
|
109
|
+
limits.heartbeatIntervalMs = options.heartbeatIntervalMs;
|
|
110
|
+
}
|
|
111
|
+
const handle = client.executeStream(code, {
|
|
112
|
+
sessionId: options.sessionId,
|
|
113
|
+
limits: Object.keys(limits).length > 0 ? limits : void 0,
|
|
114
|
+
onEvent: (event) => {
|
|
115
|
+
setEvents((prev) => [...prev, event]);
|
|
116
|
+
},
|
|
117
|
+
onStdout: (chunk) => {
|
|
118
|
+
setStdout((prev) => prev + chunk);
|
|
119
|
+
options.onStdout?.(chunk);
|
|
120
|
+
},
|
|
121
|
+
onLog: (level, message, data) => {
|
|
122
|
+
options.onLog?.(level, message, data);
|
|
123
|
+
},
|
|
124
|
+
onToolCall: (callId, toolName, args) => {
|
|
125
|
+
options.onToolCall?.(callId, toolName, args);
|
|
126
|
+
},
|
|
127
|
+
onToolResultApplied: (callId) => {
|
|
128
|
+
options.onToolResultApplied?.(callId);
|
|
129
|
+
},
|
|
130
|
+
onError: (code2, message) => {
|
|
131
|
+
options.onError?.({ code: code2, message });
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
handleRef.current = handle;
|
|
135
|
+
setSessionId(handle.sessionId);
|
|
136
|
+
try {
|
|
137
|
+
const sessionResult = await handle.wait();
|
|
138
|
+
if (sessionResult.success) {
|
|
139
|
+
setState("completed");
|
|
140
|
+
setResult(sessionResult);
|
|
141
|
+
} else if (sessionResult.error?.code === "CANCELLED") {
|
|
142
|
+
setState("cancelled");
|
|
143
|
+
setResult(sessionResult);
|
|
144
|
+
} else {
|
|
145
|
+
setState("error");
|
|
146
|
+
setResult(sessionResult);
|
|
147
|
+
setError(sessionResult.error ?? { message: "Unknown error" });
|
|
148
|
+
options.onError?.(sessionResult.error ?? { message: "Unknown error" });
|
|
149
|
+
}
|
|
150
|
+
options.onComplete?.(sessionResult);
|
|
151
|
+
return sessionResult;
|
|
152
|
+
} catch (err) {
|
|
153
|
+
const errorInfo = {
|
|
154
|
+
code: "UNEXPECTED_ERROR",
|
|
155
|
+
message: err instanceof Error ? err.message : "Unknown error"
|
|
156
|
+
};
|
|
157
|
+
setState("error");
|
|
158
|
+
setError(errorInfo);
|
|
159
|
+
options.onError?.(errorInfo);
|
|
160
|
+
const errorResult = {
|
|
161
|
+
success: false,
|
|
162
|
+
sessionId: handle.sessionId,
|
|
163
|
+
error: errorInfo,
|
|
164
|
+
events: handle.getEvents()
|
|
165
|
+
};
|
|
166
|
+
setResult(errorResult);
|
|
167
|
+
options.onComplete?.(errorResult);
|
|
168
|
+
return errorResult;
|
|
169
|
+
} finally {
|
|
170
|
+
handleRef.current = null;
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
[client, options]
|
|
174
|
+
);
|
|
175
|
+
const cancel = (0, import_react2.useCallback)(async (reason) => {
|
|
176
|
+
if (handleRef.current) {
|
|
177
|
+
await handleRef.current.cancel(reason);
|
|
178
|
+
}
|
|
179
|
+
}, []);
|
|
180
|
+
return {
|
|
181
|
+
execute,
|
|
182
|
+
cancel,
|
|
183
|
+
state,
|
|
184
|
+
isRunning: state === "running",
|
|
185
|
+
sessionId,
|
|
186
|
+
result,
|
|
187
|
+
error,
|
|
188
|
+
stdout,
|
|
189
|
+
events,
|
|
190
|
+
reset
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
194
|
+
0 && (module.exports = {
|
|
195
|
+
EnclaveProvider,
|
|
196
|
+
useEnclaveClient,
|
|
197
|
+
useEnclaveContext,
|
|
198
|
+
useEnclaveSession
|
|
199
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enclave-vm/react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.9.0",
|
|
4
4
|
"description": "React hooks and components for the EnclaveJS streaming runtime",
|
|
5
5
|
"author": "AgentFront <info@agentfront.dev>",
|
|
6
6
|
"homepage": "https://github.com/agentfront/enclave",
|
|
@@ -20,21 +20,22 @@
|
|
|
20
20
|
"bugs": {
|
|
21
21
|
"url": "https://github.com/agentfront/enclave/issues"
|
|
22
22
|
},
|
|
23
|
-
"main": "./
|
|
24
|
-
"
|
|
23
|
+
"main": "./index.js",
|
|
24
|
+
"module": "./esm/index.mjs",
|
|
25
|
+
"types": "./index.d.ts",
|
|
25
26
|
"exports": {
|
|
26
27
|
"./package.json": "./package.json",
|
|
27
28
|
".": {
|
|
28
|
-
"types": "./
|
|
29
|
-
"import": "./
|
|
30
|
-
"
|
|
29
|
+
"types": "./index.d.ts",
|
|
30
|
+
"import": "./esm/index.mjs",
|
|
31
|
+
"require": "./index.js",
|
|
32
|
+
"default": "./index.js"
|
|
31
33
|
}
|
|
32
34
|
},
|
|
33
35
|
"dependencies": {
|
|
34
|
-
"@enclave-vm/client": "
|
|
36
|
+
"@enclave-vm/client": "2.9.0"
|
|
35
37
|
},
|
|
36
38
|
"peerDependencies": {
|
|
37
39
|
"react": ">=17.0.0"
|
|
38
|
-
}
|
|
39
|
-
"type": "commonjs"
|
|
40
|
+
}
|
|
40
41
|
}
|
package/src/EnclaveProvider.js
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.EnclaveContext = void 0;
|
|
4
|
-
exports.EnclaveProvider = EnclaveProvider;
|
|
5
|
-
exports.useEnclaveContext = useEnclaveContext;
|
|
6
|
-
exports.useEnclaveClient = useEnclaveClient;
|
|
7
|
-
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
8
|
-
/**
|
|
9
|
-
* EnclaveProvider
|
|
10
|
-
*
|
|
11
|
-
* React context provider for the EnclaveJS client.
|
|
12
|
-
*
|
|
13
|
-
* @packageDocumentation
|
|
14
|
-
*/
|
|
15
|
-
const react_1 = require("react");
|
|
16
|
-
const client_1 = require("@enclave-vm/client");
|
|
17
|
-
/**
|
|
18
|
-
* React context for the Enclave client
|
|
19
|
-
*/
|
|
20
|
-
const EnclaveContext = (0, react_1.createContext)(null);
|
|
21
|
-
exports.EnclaveContext = EnclaveContext;
|
|
22
|
-
/**
|
|
23
|
-
* EnclaveProvider component
|
|
24
|
-
*
|
|
25
|
-
* Provides the EnclaveClient to child components via React context.
|
|
26
|
-
*
|
|
27
|
-
* @example
|
|
28
|
-
* ```tsx
|
|
29
|
-
* function App() {
|
|
30
|
-
* return (
|
|
31
|
-
* <EnclaveProvider config={{ baseUrl: 'https://api.example.com' }}>
|
|
32
|
-
* <MyComponent />
|
|
33
|
-
* </EnclaveProvider>
|
|
34
|
-
* );
|
|
35
|
-
* }
|
|
36
|
-
* ```
|
|
37
|
-
*/
|
|
38
|
-
function EnclaveProvider({ config, client: providedClient, children, }) {
|
|
39
|
-
// Use ref to ensure client is only created once
|
|
40
|
-
const clientRef = (0, react_1.useRef)(null);
|
|
41
|
-
// Create or use provided client
|
|
42
|
-
const client = (0, react_1.useMemo)(() => {
|
|
43
|
-
if (providedClient) {
|
|
44
|
-
return providedClient;
|
|
45
|
-
}
|
|
46
|
-
// Create new client if not already created
|
|
47
|
-
if (!clientRef.current) {
|
|
48
|
-
clientRef.current = new client_1.EnclaveClient(config);
|
|
49
|
-
}
|
|
50
|
-
return clientRef.current;
|
|
51
|
-
}, [providedClient, config]);
|
|
52
|
-
// Memoize context value
|
|
53
|
-
const contextValue = (0, react_1.useMemo)(() => ({
|
|
54
|
-
client,
|
|
55
|
-
config,
|
|
56
|
-
}), [client, config]);
|
|
57
|
-
return (0, jsx_runtime_1.jsx)(EnclaveContext.Provider, { value: contextValue, children: children });
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* useEnclaveContext hook
|
|
61
|
-
*
|
|
62
|
-
* Access the Enclave context directly. Throws if used outside EnclaveProvider.
|
|
63
|
-
*
|
|
64
|
-
* @internal
|
|
65
|
-
*/
|
|
66
|
-
function useEnclaveContext() {
|
|
67
|
-
const context = (0, react_1.useContext)(EnclaveContext);
|
|
68
|
-
if (!context) {
|
|
69
|
-
throw new Error('useEnclaveContext must be used within an EnclaveProvider. ' +
|
|
70
|
-
'Wrap your component tree with <EnclaveProvider config={{...}}>.');
|
|
71
|
-
}
|
|
72
|
-
return context;
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* useEnclaveClient hook
|
|
76
|
-
*
|
|
77
|
-
* Get the EnclaveClient instance from context.
|
|
78
|
-
*
|
|
79
|
-
* @example
|
|
80
|
-
* ```tsx
|
|
81
|
-
* function MyComponent() {
|
|
82
|
-
* const client = useEnclaveClient();
|
|
83
|
-
*
|
|
84
|
-
* const handleClick = async () => {
|
|
85
|
-
* const result = await client.execute('return 1 + 1');
|
|
86
|
-
* console.log(result.value);
|
|
87
|
-
* };
|
|
88
|
-
*
|
|
89
|
-
* return <button onClick={handleClick}>Execute</button>;
|
|
90
|
-
* }
|
|
91
|
-
* ```
|
|
92
|
-
*/
|
|
93
|
-
function useEnclaveClient() {
|
|
94
|
-
const { client } = useEnclaveContext();
|
|
95
|
-
return client;
|
|
96
|
-
}
|
|
97
|
-
//# sourceMappingURL=EnclaveProvider.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnclaveProvider.js","sourceRoot":"","sources":["../../src/EnclaveProvider.tsx"],"names":[],"mappings":";;;AAiCA,0CAgCC;AASD,8CAWC;AAqBD,4CAGC;;AA7GD;;;;;;GAMG;AAEH,iCAA0E;AAC1E,+CAAmD;AAGnD;;GAEG;AACH,MAAM,cAAc,GAAG,IAAA,qBAAa,EAA6B,IAAI,CAAC,CAAC;AAgG9D,wCAAc;AA9FvB;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,eAAe,CAAC,EAC9B,MAAM,EACN,MAAM,EAAE,cAAc,EACtB,QAAQ,GACa;IACrB,gDAAgD;IAChD,MAAM,SAAS,GAAG,IAAA,cAAM,EAAuB,IAAI,CAAC,CAAC;IAErD,gCAAgC;IAChC,MAAM,MAAM,GAAG,IAAA,eAAO,EAAC,GAAG,EAAE;QAC1B,IAAI,cAAc,EAAE,CAAC;YACnB,OAAO,cAAc,CAAC;QACxB,CAAC;QAED,2CAA2C;QAC3C,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;YACvB,SAAS,CAAC,OAAO,GAAG,IAAI,sBAAa,CAAC,MAAM,CAAC,CAAC;QAChD,CAAC;QAED,OAAO,SAAS,CAAC,OAAO,CAAC;IAC3B,CAAC,EAAE,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC,CAAC;IAE7B,wBAAwB;IACxB,MAAM,YAAY,GAAG,IAAA,eAAO,EAC1B,GAAG,EAAE,CAAC,CAAC;QACL,MAAM;QACN,MAAM;KACP,CAAC,EACF,CAAC,MAAM,EAAE,MAAM,CAAC,CACjB,CAAC;IAEF,OAAO,uBAAC,cAAc,CAAC,QAAQ,IAAC,KAAK,EAAE,YAAY,YAAG,QAAQ,GAA2B,CAAC;AAC5F,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB;IAC/B,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,cAAc,CAAC,CAAC;IAE3C,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,4DAA4D;YAC1D,iEAAiE,CACpE,CAAC;IACJ,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,gBAAgB;IAC9B,MAAM,EAAE,MAAM,EAAE,GAAG,iBAAiB,EAAE,CAAC;IACvC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * EnclaveProvider\n *\n * React context provider for the EnclaveJS client.\n *\n * @packageDocumentation\n */\n\nimport React, { createContext, useContext, useMemo, useRef } from 'react';\nimport { EnclaveClient } from '@enclave-vm/client';\nimport type { EnclaveProviderProps, EnclaveContextValue } from './types.js';\n\n/**\n * React context for the Enclave client\n */\nconst EnclaveContext = createContext<EnclaveContextValue | null>(null);\n\n/**\n * EnclaveProvider component\n *\n * Provides the EnclaveClient to child components via React context.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <EnclaveProvider config={{ baseUrl: 'https://api.example.com' }}>\n * <MyComponent />\n * </EnclaveProvider>\n * );\n * }\n * ```\n */\nexport function EnclaveProvider({\n config,\n client: providedClient,\n children,\n}: EnclaveProviderProps): React.ReactElement {\n // Use ref to ensure client is only created once\n const clientRef = useRef<EnclaveClient | null>(null);\n\n // Create or use provided client\n const client = useMemo(() => {\n if (providedClient) {\n return providedClient;\n }\n\n // Create new client if not already created\n if (!clientRef.current) {\n clientRef.current = new EnclaveClient(config);\n }\n\n return clientRef.current;\n }, [providedClient, config]);\n\n // Memoize context value\n const contextValue = useMemo<EnclaveContextValue>(\n () => ({\n client,\n config,\n }),\n [client, config],\n );\n\n return <EnclaveContext.Provider value={contextValue}>{children}</EnclaveContext.Provider>;\n}\n\n/**\n * useEnclaveContext hook\n *\n * Access the Enclave context directly. Throws if used outside EnclaveProvider.\n *\n * @internal\n */\nexport function useEnclaveContext(): EnclaveContextValue {\n const context = useContext(EnclaveContext);\n\n if (!context) {\n throw new Error(\n 'useEnclaveContext must be used within an EnclaveProvider. ' +\n 'Wrap your component tree with <EnclaveProvider config={{...}}>.',\n );\n }\n\n return context;\n}\n\n/**\n * useEnclaveClient hook\n *\n * Get the EnclaveClient instance from context.\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useEnclaveClient();\n *\n * const handleClick = async () => {\n * const result = await client.execute('return 1 + 1');\n * console.log(result.value);\n * };\n *\n * return <button onClick={handleClick}>Execute</button>;\n * }\n * ```\n */\nexport function useEnclaveClient(): EnclaveClient {\n const { client } = useEnclaveContext();\n return client;\n}\n\nexport { EnclaveContext };\n"]}
|
package/src/index.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @enclave-vm/react
|
|
4
|
-
*
|
|
5
|
-
* React hooks and components for the EnclaveJS streaming runtime.
|
|
6
|
-
*
|
|
7
|
-
* @packageDocumentation
|
|
8
|
-
*/
|
|
9
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
-
exports.useEnclaveSession = exports.useEnclaveContext = exports.useEnclaveClient = exports.EnclaveProvider = void 0;
|
|
11
|
-
// Provider and context
|
|
12
|
-
var EnclaveProvider_js_1 = require("./EnclaveProvider.js");
|
|
13
|
-
Object.defineProperty(exports, "EnclaveProvider", { enumerable: true, get: function () { return EnclaveProvider_js_1.EnclaveProvider; } });
|
|
14
|
-
Object.defineProperty(exports, "useEnclaveClient", { enumerable: true, get: function () { return EnclaveProvider_js_1.useEnclaveClient; } });
|
|
15
|
-
Object.defineProperty(exports, "useEnclaveContext", { enumerable: true, get: function () { return EnclaveProvider_js_1.useEnclaveContext; } });
|
|
16
|
-
// Hooks
|
|
17
|
-
var useEnclaveSession_js_1 = require("./useEnclaveSession.js");
|
|
18
|
-
Object.defineProperty(exports, "useEnclaveSession", { enumerable: true, get: function () { return useEnclaveSession_js_1.useEnclaveSession; } });
|
|
19
|
-
//# sourceMappingURL=index.js.map
|
package/src/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,uBAAuB;AACvB,2DAA4F;AAAnF,qHAAA,eAAe,OAAA;AAAE,sHAAA,gBAAgB,OAAA;AAAE,uHAAA,iBAAiB,OAAA;AAE7D,QAAQ;AACR,+DAA2D;AAAlD,yHAAA,iBAAiB,OAAA","sourcesContent":["/**\n * @enclave-vm/react\n *\n * React hooks and components for the EnclaveJS streaming runtime.\n *\n * @packageDocumentation\n */\n\n// Provider and context\nexport { EnclaveProvider, useEnclaveClient, useEnclaveContext } from './EnclaveProvider.js';\n\n// Hooks\nexport { useEnclaveSession } from './useEnclaveSession.js';\n\n// Types\nexport type {\n SessionState,\n UseEnclaveSessionOptions,\n UseEnclaveSessionReturn,\n EnclaveProviderProps,\n EnclaveContextValue,\n} from './types.js';\n\n// Re-export commonly used types from @enclave-vm/client\nexport type {\n EnclaveClient,\n EnclaveClientConfig,\n SessionResult,\n SessionHandle,\n StreamEvent,\n SessionId,\n} from '@enclave-vm/client';\n"]}
|
package/src/test-setup.js
DELETED
package/src/test-setup.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"test-setup.js","sourceRoot":"","sources":["../../src/test-setup.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,qCAAmC","sourcesContent":["/**\n * Test setup for React Testing Library\n */\n\nimport '@testing-library/jest-dom';\n"]}
|
package/src/types.js
DELETED
package/src/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG","sourcesContent":["/**\n * React Types\n *\n * Types for the EnclaveJS React hooks and components.\n *\n * @packageDocumentation\n */\n\nimport type { EnclaveClient, EnclaveClientConfig, SessionResult, StreamEvent, SessionId } from '@enclave-vm/client';\n\n/**\n * Session state enum\n */\nexport type SessionState = 'idle' | 'running' | 'completed' | 'error' | 'cancelled';\n\n/**\n * useEnclaveSession hook options\n */\nexport interface UseEnclaveSessionOptions {\n /**\n * Custom session ID (generated if not provided)\n */\n sessionId?: SessionId;\n\n /**\n * Session timeout in milliseconds\n */\n timeoutMs?: number;\n\n /**\n * Maximum number of tool calls\n */\n maxToolCalls?: number;\n\n /**\n * Heartbeat interval in milliseconds\n */\n heartbeatIntervalMs?: number;\n\n /**\n * Callback when session starts\n */\n onStart?: () => void;\n\n /**\n * Callback for stdout output\n */\n onStdout?: (chunk: string) => void;\n\n /**\n * Callback for log messages\n */\n onLog?: (level: string, message: string, data?: Record<string, unknown>) => void;\n\n /**\n * Callback for tool calls\n */\n onToolCall?: (callId: string, toolName: string, args: unknown) => void;\n\n /**\n * Callback when tool result is applied\n */\n onToolResultApplied?: (callId: string) => void;\n\n /**\n * Callback on completion\n */\n onComplete?: (result: SessionResult) => void;\n\n /**\n * Callback on error\n */\n onError?: (error: { code?: string; message: string }) => void;\n}\n\n/**\n * useEnclaveSession hook return type\n */\nexport interface UseEnclaveSessionReturn<T = unknown> {\n /**\n * Execute code in the enclave\n */\n execute: (code: string) => Promise<SessionResult<T>>;\n\n /**\n * Cancel the current session\n */\n cancel: (reason?: string) => Promise<void>;\n\n /**\n * Current session state\n */\n state: SessionState;\n\n /**\n * Whether a session is currently running\n */\n isRunning: boolean;\n\n /**\n * Current session ID (if running)\n */\n sessionId: SessionId | null;\n\n /**\n * Result of the last execution (if completed)\n */\n result: SessionResult<T> | null;\n\n /**\n * Error from the last execution (if failed)\n */\n error: { code?: string; message: string } | null;\n\n /**\n * Stdout output accumulated during execution\n */\n stdout: string;\n\n /**\n * Events received during execution\n */\n events: StreamEvent[];\n\n /**\n * Reset the hook state\n */\n reset: () => void;\n}\n\n/**\n * EnclaveProvider props\n */\nexport interface EnclaveProviderProps {\n /**\n * Client configuration\n */\n config: EnclaveClientConfig;\n\n /**\n * Pre-created client instance (alternative to config)\n */\n client?: EnclaveClient;\n\n /**\n * Children to render\n */\n children: React.ReactNode;\n}\n\n/**\n * Enclave context value\n */\nexport interface EnclaveContextValue {\n /**\n * The EnclaveClient instance\n */\n client: EnclaveClient;\n\n /**\n * Client configuration\n */\n config: EnclaveClientConfig;\n}\n"]}
|
package/src/useEnclaveSession.js
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* useEnclaveSession Hook
|
|
4
|
-
*
|
|
5
|
-
* React hook for executing code in the EnclaveJS runtime with state management.
|
|
6
|
-
*
|
|
7
|
-
* @packageDocumentation
|
|
8
|
-
*/
|
|
9
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
-
exports.useEnclaveSession = useEnclaveSession;
|
|
11
|
-
const react_1 = require("react");
|
|
12
|
-
const EnclaveProvider_js_1 = require("./EnclaveProvider.js");
|
|
13
|
-
/**
|
|
14
|
-
* useEnclaveSession hook
|
|
15
|
-
*
|
|
16
|
-
* Provides a stateful interface for executing code in the Enclave runtime.
|
|
17
|
-
*
|
|
18
|
-
* @example
|
|
19
|
-
* ```tsx
|
|
20
|
-
* function Calculator() {
|
|
21
|
-
* const { execute, isRunning, result, stdout } = useEnclaveSession({
|
|
22
|
-
* onStdout: (chunk) => console.log(chunk),
|
|
23
|
-
* });
|
|
24
|
-
*
|
|
25
|
-
* const calculate = async () => {
|
|
26
|
-
* const result = await execute('return 1 + 1');
|
|
27
|
-
* console.log('Result:', result.value);
|
|
28
|
-
* };
|
|
29
|
-
*
|
|
30
|
-
* return (
|
|
31
|
-
* <div>
|
|
32
|
-
* <button onClick={calculate} disabled={isRunning}>
|
|
33
|
-
* Calculate
|
|
34
|
-
* </button>
|
|
35
|
-
* {result && <p>Result: {JSON.stringify(result.value)}</p>}
|
|
36
|
-
* <pre>{stdout}</pre>
|
|
37
|
-
* </div>
|
|
38
|
-
* );
|
|
39
|
-
* }
|
|
40
|
-
* ```
|
|
41
|
-
*/
|
|
42
|
-
function useEnclaveSession(options = {}) {
|
|
43
|
-
const client = (0, EnclaveProvider_js_1.useEnclaveClient)();
|
|
44
|
-
// State
|
|
45
|
-
const [state, setState] = (0, react_1.useState)('idle');
|
|
46
|
-
const [sessionId, setSessionId] = (0, react_1.useState)(null);
|
|
47
|
-
const [result, setResult] = (0, react_1.useState)(null);
|
|
48
|
-
const [error, setError] = (0, react_1.useState)(null);
|
|
49
|
-
const [stdout, setStdout] = (0, react_1.useState)('');
|
|
50
|
-
const [events, setEvents] = (0, react_1.useState)([]);
|
|
51
|
-
// Refs for current session handle
|
|
52
|
-
const handleRef = (0, react_1.useRef)(null);
|
|
53
|
-
/**
|
|
54
|
-
* Reset the hook state
|
|
55
|
-
*/
|
|
56
|
-
const reset = (0, react_1.useCallback)(() => {
|
|
57
|
-
setState('idle');
|
|
58
|
-
setSessionId(null);
|
|
59
|
-
setResult(null);
|
|
60
|
-
setError(null);
|
|
61
|
-
setStdout('');
|
|
62
|
-
setEvents([]);
|
|
63
|
-
handleRef.current = null;
|
|
64
|
-
}, []);
|
|
65
|
-
/**
|
|
66
|
-
* Execute code in the enclave
|
|
67
|
-
*/
|
|
68
|
-
const execute = (0, react_1.useCallback)(async (code) => {
|
|
69
|
-
// Reset state for new execution
|
|
70
|
-
setState('running');
|
|
71
|
-
setResult(null);
|
|
72
|
-
setError(null);
|
|
73
|
-
setStdout('');
|
|
74
|
-
setEvents([]);
|
|
75
|
-
// Call onStart callback
|
|
76
|
-
options.onStart?.();
|
|
77
|
-
// Build limits from options
|
|
78
|
-
const limits = {};
|
|
79
|
-
if (options.timeoutMs !== undefined) {
|
|
80
|
-
limits.sessionTtlMs = options.timeoutMs;
|
|
81
|
-
}
|
|
82
|
-
if (options.maxToolCalls !== undefined) {
|
|
83
|
-
limits.maxToolCalls = options.maxToolCalls;
|
|
84
|
-
}
|
|
85
|
-
if (options.heartbeatIntervalMs !== undefined) {
|
|
86
|
-
limits.heartbeatIntervalMs = options.heartbeatIntervalMs;
|
|
87
|
-
}
|
|
88
|
-
// Start streaming execution
|
|
89
|
-
const handle = client.executeStream(code, {
|
|
90
|
-
sessionId: options.sessionId,
|
|
91
|
-
limits: Object.keys(limits).length > 0 ? limits : undefined,
|
|
92
|
-
onEvent: (event) => {
|
|
93
|
-
setEvents((prev) => [...prev, event]);
|
|
94
|
-
},
|
|
95
|
-
onStdout: (chunk) => {
|
|
96
|
-
setStdout((prev) => prev + chunk);
|
|
97
|
-
options.onStdout?.(chunk);
|
|
98
|
-
},
|
|
99
|
-
onLog: (level, message, data) => {
|
|
100
|
-
options.onLog?.(level, message, data);
|
|
101
|
-
},
|
|
102
|
-
onToolCall: (callId, toolName, args) => {
|
|
103
|
-
options.onToolCall?.(callId, toolName, args);
|
|
104
|
-
},
|
|
105
|
-
onToolResultApplied: (callId) => {
|
|
106
|
-
options.onToolResultApplied?.(callId);
|
|
107
|
-
},
|
|
108
|
-
onError: (code, message) => {
|
|
109
|
-
options.onError?.({ code, message });
|
|
110
|
-
},
|
|
111
|
-
});
|
|
112
|
-
handleRef.current = handle;
|
|
113
|
-
setSessionId(handle.sessionId);
|
|
114
|
-
try {
|
|
115
|
-
// Wait for completion
|
|
116
|
-
const sessionResult = (await handle.wait());
|
|
117
|
-
// Update state based on result
|
|
118
|
-
if (sessionResult.success) {
|
|
119
|
-
setState('completed');
|
|
120
|
-
setResult(sessionResult);
|
|
121
|
-
}
|
|
122
|
-
else if (sessionResult.error?.code === 'CANCELLED') {
|
|
123
|
-
setState('cancelled');
|
|
124
|
-
setResult(sessionResult);
|
|
125
|
-
}
|
|
126
|
-
else {
|
|
127
|
-
setState('error');
|
|
128
|
-
setResult(sessionResult);
|
|
129
|
-
setError(sessionResult.error ?? { message: 'Unknown error' });
|
|
130
|
-
options.onError?.(sessionResult.error ?? { message: 'Unknown error' });
|
|
131
|
-
}
|
|
132
|
-
// Call onComplete callback
|
|
133
|
-
options.onComplete?.(sessionResult);
|
|
134
|
-
return sessionResult;
|
|
135
|
-
}
|
|
136
|
-
catch (err) {
|
|
137
|
-
// Handle unexpected errors
|
|
138
|
-
const errorInfo = {
|
|
139
|
-
code: 'UNEXPECTED_ERROR',
|
|
140
|
-
message: err instanceof Error ? err.message : 'Unknown error',
|
|
141
|
-
};
|
|
142
|
-
setState('error');
|
|
143
|
-
setError(errorInfo);
|
|
144
|
-
options.onError?.(errorInfo);
|
|
145
|
-
// Return error result
|
|
146
|
-
const errorResult = {
|
|
147
|
-
success: false,
|
|
148
|
-
sessionId: handle.sessionId,
|
|
149
|
-
error: errorInfo,
|
|
150
|
-
events: handle.getEvents(),
|
|
151
|
-
};
|
|
152
|
-
setResult(errorResult);
|
|
153
|
-
options.onComplete?.(errorResult);
|
|
154
|
-
return errorResult;
|
|
155
|
-
}
|
|
156
|
-
finally {
|
|
157
|
-
handleRef.current = null;
|
|
158
|
-
}
|
|
159
|
-
}, [client, options]);
|
|
160
|
-
/**
|
|
161
|
-
* Cancel the current session
|
|
162
|
-
*/
|
|
163
|
-
const cancel = (0, react_1.useCallback)(async (reason) => {
|
|
164
|
-
if (handleRef.current) {
|
|
165
|
-
await handleRef.current.cancel(reason);
|
|
166
|
-
}
|
|
167
|
-
}, []);
|
|
168
|
-
return {
|
|
169
|
-
execute,
|
|
170
|
-
cancel,
|
|
171
|
-
state,
|
|
172
|
-
isRunning: state === 'running',
|
|
173
|
-
sessionId,
|
|
174
|
-
result,
|
|
175
|
-
error,
|
|
176
|
-
stdout,
|
|
177
|
-
events,
|
|
178
|
-
reset,
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
//# sourceMappingURL=useEnclaveSession.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useEnclaveSession.js","sourceRoot":"","sources":["../../src/useEnclaveSession.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * useEnclaveSession Hook\n *\n * React hook for executing code in the EnclaveJS runtime with state management.\n *\n * @packageDocumentation\n */\n\nimport { useState, useCallback, useRef } from 'react';\nimport type { SessionResult, SessionHandle, StreamEvent, SessionId } from '@enclave-vm/client';\nimport { useEnclaveClient } from './EnclaveProvider.js';\nimport type { SessionState, UseEnclaveSessionOptions, UseEnclaveSessionReturn } from './types.js';\n\n/**\n * useEnclaveSession hook\n *\n * Provides a stateful interface for executing code in the Enclave runtime.\n *\n * @example\n * ```tsx\n * function Calculator() {\n * const { execute, isRunning, result, stdout } = useEnclaveSession({\n * onStdout: (chunk) => console.log(chunk),\n * });\n *\n * const calculate = async () => {\n * const result = await execute('return 1 + 1');\n * console.log('Result:', result.value);\n * };\n *\n * return (\n * <div>\n * <button onClick={calculate} disabled={isRunning}>\n * Calculate\n * </button>\n * {result && <p>Result: {JSON.stringify(result.value)}</p>}\n * <pre>{stdout}</pre>\n * </div>\n * );\n * }\n * ```\n */\nexport function useEnclaveSession<T = unknown>(options: UseEnclaveSessionOptions = {}): UseEnclaveSessionReturn<T> {\n const client = useEnclaveClient();\n\n // State\n const [state, setState] = useState<SessionState>('idle');\n const [sessionId, setSessionId] = useState<SessionId | null>(null);\n const [result, setResult] = useState<SessionResult<T> | null>(null);\n const [error, setError] = useState<{ code?: string; message: string } | null>(null);\n const [stdout, setStdout] = useState<string>('');\n const [events, setEvents] = useState<StreamEvent[]>([]);\n\n // Refs for current session handle\n const handleRef = useRef<SessionHandle | null>(null);\n\n /**\n * Reset the hook state\n */\n const reset = useCallback(() => {\n setState('idle');\n setSessionId(null);\n setResult(null);\n setError(null);\n setStdout('');\n setEvents([]);\n handleRef.current = null;\n }, []);\n\n /**\n * Execute code in the enclave\n */\n const execute = useCallback(\n async (code: string): Promise<SessionResult<T>> => {\n // Reset state for new execution\n setState('running');\n setResult(null);\n setError(null);\n setStdout('');\n setEvents([]);\n\n // Call onStart callback\n options.onStart?.();\n\n // Build limits from options\n const limits: Record<string, number> = {};\n if (options.timeoutMs !== undefined) {\n limits.sessionTtlMs = options.timeoutMs;\n }\n if (options.maxToolCalls !== undefined) {\n limits.maxToolCalls = options.maxToolCalls;\n }\n if (options.heartbeatIntervalMs !== undefined) {\n limits.heartbeatIntervalMs = options.heartbeatIntervalMs;\n }\n\n // Start streaming execution\n const handle = client.executeStream(code, {\n sessionId: options.sessionId,\n limits: Object.keys(limits).length > 0 ? limits : undefined,\n onEvent: (event) => {\n setEvents((prev) => [...prev, event]);\n },\n onStdout: (chunk) => {\n setStdout((prev) => prev + chunk);\n options.onStdout?.(chunk);\n },\n onLog: (level, message, data) => {\n options.onLog?.(level, message, data);\n },\n onToolCall: (callId, toolName, args) => {\n options.onToolCall?.(callId, toolName, args);\n },\n onToolResultApplied: (callId) => {\n options.onToolResultApplied?.(callId);\n },\n onError: (code, message) => {\n options.onError?.({ code, message });\n },\n });\n\n handleRef.current = handle;\n setSessionId(handle.sessionId);\n\n try {\n // Wait for completion\n const sessionResult = (await handle.wait()) as SessionResult<T>;\n\n // Update state based on result\n if (sessionResult.success) {\n setState('completed');\n setResult(sessionResult);\n } else if (sessionResult.error?.code === 'CANCELLED') {\n setState('cancelled');\n setResult(sessionResult);\n } else {\n setState('error');\n setResult(sessionResult);\n setError(sessionResult.error ?? { message: 'Unknown error' });\n options.onError?.(sessionResult.error ?? { message: 'Unknown error' });\n }\n\n // Call onComplete callback\n options.onComplete?.(sessionResult);\n\n return sessionResult;\n } catch (err) {\n // Handle unexpected errors\n const errorInfo = {\n code: 'UNEXPECTED_ERROR',\n message: err instanceof Error ? err.message : 'Unknown error',\n };\n\n setState('error');\n setError(errorInfo);\n options.onError?.(errorInfo);\n\n // Return error result\n const errorResult: SessionResult<T> = {\n success: false,\n sessionId: handle.sessionId,\n error: errorInfo,\n events: handle.getEvents(),\n };\n\n setResult(errorResult);\n options.onComplete?.(errorResult);\n\n return errorResult;\n } finally {\n handleRef.current = null;\n }\n },\n [client, options],\n );\n\n /**\n * Cancel the current session\n */\n const cancel = useCallback(async (reason?: string): Promise<void> => {\n if (handleRef.current) {\n await handleRef.current.cancel(reason);\n }\n }, []);\n\n return {\n execute,\n cancel,\n state,\n isRunning: state === 'running',\n sessionId,\n result,\n error,\n stdout,\n events,\n reset,\n };\n}\n"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|