@giselles-ai/sandbox-agent 0.1.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/dist/index.d.ts +10 -0
- package/dist/index.js +201 -0
- package/dist/react/index.d.ts +73 -0
- package/dist/react/index.js +821 -0
- package/package.json +48 -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/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type AgentRunnerOptions = {
|
|
2
|
+
apiKey?: string;
|
|
3
|
+
baseUrl?: string;
|
|
4
|
+
};
|
|
5
|
+
type AgentRunnerHandler = {
|
|
6
|
+
POST: (request: Request) => Promise<Response>;
|
|
7
|
+
};
|
|
8
|
+
declare function handleAgentRunner(options?: AgentRunnerOptions): AgentRunnerHandler;
|
|
9
|
+
|
|
10
|
+
export { type AgentRunnerHandler, type AgentRunnerOptions, handleAgentRunner };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var DEFAULT_ENDPOINT = "https://studio.giselles.ai/agent-api";
|
|
4
|
+
var DEBUG_ENABLED = process.env.GISELLE_AGENT_DEBUG === "true" || process.env.DEBUG === "1";
|
|
5
|
+
function debugLog(context, message) {
|
|
6
|
+
if (!DEBUG_ENABLED) {
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
console.info("[agent-runner]", JSON.stringify({ ...context, message }));
|
|
10
|
+
}
|
|
11
|
+
var agentRunSchema = z.object({
|
|
12
|
+
type: z.literal("agent.run"),
|
|
13
|
+
message: z.string().min(1),
|
|
14
|
+
document: z.string().optional(),
|
|
15
|
+
session_id: z.string().min(1).optional(),
|
|
16
|
+
sandbox_id: z.string().min(1).optional()
|
|
17
|
+
});
|
|
18
|
+
function invalidRequestResponse(detail) {
|
|
19
|
+
return Response.json(
|
|
20
|
+
{
|
|
21
|
+
ok: false,
|
|
22
|
+
errorCode: "INVALID_REQUEST",
|
|
23
|
+
message: "Invalid request payload.",
|
|
24
|
+
error: detail
|
|
25
|
+
},
|
|
26
|
+
{ status: 400 }
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
function invalidConfigResponse(message) {
|
|
30
|
+
return Response.json(
|
|
31
|
+
{
|
|
32
|
+
ok: false,
|
|
33
|
+
errorCode: "INVALID_CONFIG",
|
|
34
|
+
message
|
|
35
|
+
},
|
|
36
|
+
{ status: 500 }
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
function badGatewayResponse(message) {
|
|
40
|
+
return Response.json(
|
|
41
|
+
{
|
|
42
|
+
ok: false,
|
|
43
|
+
errorCode: "UPSTREAM_UNAVAILABLE",
|
|
44
|
+
message
|
|
45
|
+
},
|
|
46
|
+
{ status: 502 }
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
function resolveApiKey(input) {
|
|
50
|
+
return input?.apiKey?.trim() || process.env.GISELLE_SANDBOX_AGENT_API_KEY?.trim() || process.env.GISELLE_API_KEY?.trim() || "";
|
|
51
|
+
}
|
|
52
|
+
function parseAbsoluteEndpoint(baseUrl) {
|
|
53
|
+
try {
|
|
54
|
+
const url = new URL(baseUrl);
|
|
55
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
return url.toString();
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function resolveEndpoint(input) {
|
|
64
|
+
const baseUrl = input.baseUrl?.trim();
|
|
65
|
+
if (baseUrl) {
|
|
66
|
+
const endpoint = parseAbsoluteEndpoint(baseUrl);
|
|
67
|
+
if (!endpoint) {
|
|
68
|
+
return {
|
|
69
|
+
ok: false,
|
|
70
|
+
message: "`baseUrl` must be an absolute HTTP(S) endpoint URL, e.g. https://studio.giselles.ai/agent-api."
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
debugLog(
|
|
74
|
+
{
|
|
75
|
+
baseUrl: input.baseUrl
|
|
76
|
+
},
|
|
77
|
+
`resolveEndpoint: using baseUrl -> ${endpoint}`
|
|
78
|
+
);
|
|
79
|
+
return { ok: true, endpoint };
|
|
80
|
+
}
|
|
81
|
+
debugLog(
|
|
82
|
+
{
|
|
83
|
+
baseUrl: input.baseUrl
|
|
84
|
+
},
|
|
85
|
+
`resolveEndpoint: using default -> ${DEFAULT_ENDPOINT}`
|
|
86
|
+
);
|
|
87
|
+
return { ok: true, endpoint: DEFAULT_ENDPOINT };
|
|
88
|
+
}
|
|
89
|
+
function handleAgentRunner(options) {
|
|
90
|
+
const apiKey = resolveApiKey(options);
|
|
91
|
+
const optionSnapshot = {
|
|
92
|
+
baseUrl: options?.baseUrl?.trim(),
|
|
93
|
+
hasApiKey: Boolean(apiKey),
|
|
94
|
+
hasInlineApiKey: Boolean(options?.apiKey?.trim()),
|
|
95
|
+
hasEnvApiKey: Boolean(process.env.GISELLE_SANDBOX_AGENT_API_KEY?.trim()) || Boolean(process.env.GISELLE_API_KEY?.trim())
|
|
96
|
+
};
|
|
97
|
+
debugLog(
|
|
98
|
+
optionSnapshot,
|
|
99
|
+
`handleAgentRunner initialized (${options ? "custom options" : "default options"})`
|
|
100
|
+
);
|
|
101
|
+
return {
|
|
102
|
+
POST: async (request) => {
|
|
103
|
+
debugLog(
|
|
104
|
+
{
|
|
105
|
+
baseUrl: optionSnapshot.baseUrl
|
|
106
|
+
},
|
|
107
|
+
`POST request start: host=${new URL(request.url).host}`
|
|
108
|
+
);
|
|
109
|
+
const payload = await request.json().catch(() => null);
|
|
110
|
+
const parsed = agentRunSchema.safeParse(payload);
|
|
111
|
+
if (!parsed.success) {
|
|
112
|
+
debugLog(
|
|
113
|
+
{
|
|
114
|
+
baseUrl: optionSnapshot.baseUrl
|
|
115
|
+
},
|
|
116
|
+
`payload invalid: ${parsed.error.issues.length} issues`
|
|
117
|
+
);
|
|
118
|
+
return invalidRequestResponse(parsed.error.flatten());
|
|
119
|
+
}
|
|
120
|
+
const endpointResult = resolveEndpoint({
|
|
121
|
+
baseUrl: options?.baseUrl
|
|
122
|
+
});
|
|
123
|
+
if (!endpointResult.ok) {
|
|
124
|
+
debugLog(
|
|
125
|
+
{
|
|
126
|
+
baseUrl: optionSnapshot.baseUrl
|
|
127
|
+
},
|
|
128
|
+
`invalid endpoint config: ${endpointResult.message}`
|
|
129
|
+
);
|
|
130
|
+
return invalidConfigResponse(endpointResult.message);
|
|
131
|
+
}
|
|
132
|
+
debugLog(
|
|
133
|
+
{
|
|
134
|
+
baseUrl: optionSnapshot.baseUrl
|
|
135
|
+
},
|
|
136
|
+
`POST forwarding to endpoint: ${endpointResult.endpoint}`
|
|
137
|
+
);
|
|
138
|
+
const headers = {
|
|
139
|
+
"content-type": "application/json"
|
|
140
|
+
};
|
|
141
|
+
if (apiKey) {
|
|
142
|
+
headers.authorization = `Bearer ${apiKey}`;
|
|
143
|
+
debugLog(
|
|
144
|
+
{
|
|
145
|
+
baseUrl: optionSnapshot.baseUrl
|
|
146
|
+
},
|
|
147
|
+
"Authorization header attached"
|
|
148
|
+
);
|
|
149
|
+
} else {
|
|
150
|
+
debugLog(
|
|
151
|
+
{
|
|
152
|
+
baseUrl: optionSnapshot.baseUrl
|
|
153
|
+
},
|
|
154
|
+
"Authorization header skipped (apiKey missing)"
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
let upstreamResponse;
|
|
158
|
+
try {
|
|
159
|
+
upstreamResponse = await fetch(endpointResult.endpoint, {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers,
|
|
162
|
+
body: JSON.stringify(parsed.data),
|
|
163
|
+
signal: request.signal
|
|
164
|
+
});
|
|
165
|
+
} catch (error) {
|
|
166
|
+
debugLog(
|
|
167
|
+
{
|
|
168
|
+
baseUrl: optionSnapshot.baseUrl
|
|
169
|
+
},
|
|
170
|
+
`upstream fetch failed: ${error instanceof Error ? error.message : String(error)}`
|
|
171
|
+
);
|
|
172
|
+
const message = error instanceof Error ? error.message : "Failed to connect to upstream API.";
|
|
173
|
+
return badGatewayResponse(message);
|
|
174
|
+
}
|
|
175
|
+
debugLog(
|
|
176
|
+
{
|
|
177
|
+
baseUrl: optionSnapshot.baseUrl
|
|
178
|
+
},
|
|
179
|
+
`upstream responded: status=${upstreamResponse.status}, content-type=${upstreamResponse.headers.get("content-type") ?? "(none)"}, content-encoding=${upstreamResponse.headers.get("content-encoding") ?? "(none)"}`
|
|
180
|
+
);
|
|
181
|
+
const responseHeaders = new Headers(upstreamResponse.headers);
|
|
182
|
+
responseHeaders.delete("content-encoding");
|
|
183
|
+
responseHeaders.delete("Content-Encoding");
|
|
184
|
+
responseHeaders.delete("content-length");
|
|
185
|
+
responseHeaders.delete("transfer-encoding");
|
|
186
|
+
responseHeaders.set(
|
|
187
|
+
"Content-Type",
|
|
188
|
+
responseHeaders.get("Content-Type") ?? "application/x-ndjson; charset=utf-8"
|
|
189
|
+
);
|
|
190
|
+
responseHeaders.set("Cache-Control", "no-cache, no-transform");
|
|
191
|
+
return new Response(upstreamResponse.body, {
|
|
192
|
+
status: upstreamResponse.status,
|
|
193
|
+
statusText: upstreamResponse.statusText,
|
|
194
|
+
headers: responseHeaders
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
export {
|
|
200
|
+
handleAgentRunner
|
|
201
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import { ReactNode, Dispatch, SetStateAction } from 'react';
|
|
3
|
+
import { BrowserToolStatus, SnapshotField, BrowserToolAction, ExecutionReport } from '@giselles-ai/browser-tool';
|
|
4
|
+
|
|
5
|
+
type PromptPanelProps = {
|
|
6
|
+
defaultInstruction?: string;
|
|
7
|
+
defaultDocument?: string;
|
|
8
|
+
mount?: "bottom-right" | "inline";
|
|
9
|
+
};
|
|
10
|
+
declare function PromptPanel({ defaultInstruction, defaultDocument, mount, }: PromptPanelProps): react_jsx_runtime.JSX.Element;
|
|
11
|
+
|
|
12
|
+
type RunInput = {
|
|
13
|
+
instruction: string;
|
|
14
|
+
document?: string;
|
|
15
|
+
};
|
|
16
|
+
type BrowserToolPlan = {
|
|
17
|
+
fields: SnapshotField[];
|
|
18
|
+
actions: BrowserToolAction[];
|
|
19
|
+
warnings: string[];
|
|
20
|
+
};
|
|
21
|
+
type BrowserToolProviderProps = {
|
|
22
|
+
endpoint: string;
|
|
23
|
+
children: ReactNode;
|
|
24
|
+
};
|
|
25
|
+
type BrowserToolContextValue = {
|
|
26
|
+
endpoint: string;
|
|
27
|
+
status: BrowserToolStatus;
|
|
28
|
+
lastPlan: BrowserToolPlan | null;
|
|
29
|
+
lastExecution: ExecutionReport | null;
|
|
30
|
+
error: string | null;
|
|
31
|
+
setError: Dispatch<SetStateAction<string | null>>;
|
|
32
|
+
run: (input: RunInput) => Promise<BrowserToolPlan>;
|
|
33
|
+
apply: (actions: BrowserToolAction[], fields: SnapshotField[]) => ExecutionReport;
|
|
34
|
+
};
|
|
35
|
+
declare function BrowserToolProvider({ endpoint, children, }: BrowserToolProviderProps): react_jsx_runtime.JSX.Element;
|
|
36
|
+
|
|
37
|
+
type AgentMessage = {
|
|
38
|
+
id: string;
|
|
39
|
+
role: "user" | "assistant";
|
|
40
|
+
content: string;
|
|
41
|
+
};
|
|
42
|
+
type ToolEvent = {
|
|
43
|
+
id: string;
|
|
44
|
+
toolId: string;
|
|
45
|
+
toolName: string;
|
|
46
|
+
status?: "success" | "error";
|
|
47
|
+
parameters?: unknown;
|
|
48
|
+
output?: unknown;
|
|
49
|
+
};
|
|
50
|
+
type BridgeStatus = "idle" | "connecting" | "connected" | "error";
|
|
51
|
+
type AgentStatus = BridgeStatus | "running";
|
|
52
|
+
type UseAgentOptions = {
|
|
53
|
+
endpoint: string;
|
|
54
|
+
};
|
|
55
|
+
type AgentHookState = {
|
|
56
|
+
status: AgentStatus;
|
|
57
|
+
messages: AgentMessage[];
|
|
58
|
+
tools: ToolEvent[];
|
|
59
|
+
warnings: string[];
|
|
60
|
+
stderrLogs: string[];
|
|
61
|
+
sandboxId: string | null;
|
|
62
|
+
geminiSessionId: string | null;
|
|
63
|
+
error: string | null;
|
|
64
|
+
sendMessage: (input: {
|
|
65
|
+
message: string;
|
|
66
|
+
document?: string;
|
|
67
|
+
}) => Promise<void>;
|
|
68
|
+
};
|
|
69
|
+
declare function useAgent({ endpoint }: UseAgentOptions): AgentHookState;
|
|
70
|
+
|
|
71
|
+
declare function useBrowserTool(): BrowserToolContextValue;
|
|
72
|
+
|
|
73
|
+
export { type AgentHookState, type AgentMessage, type AgentStatus, BrowserToolProvider, PromptPanel, type ToolEvent, type UseAgentOptions, useAgent, useBrowserTool };
|
|
@@ -0,0 +1,821 @@
|
|
|
1
|
+
// src/react/prompt-panel.tsx
|
|
2
|
+
import { useMemo as useMemo2, useState as useState2 } from "react";
|
|
3
|
+
|
|
4
|
+
// src/react/use-browser-tool.ts
|
|
5
|
+
import { useContext } from "react";
|
|
6
|
+
|
|
7
|
+
// src/react/provider.tsx
|
|
8
|
+
import { execute, snapshot } from "@giselles-ai/browser-tool/dom";
|
|
9
|
+
import {
|
|
10
|
+
createContext,
|
|
11
|
+
useCallback,
|
|
12
|
+
useMemo,
|
|
13
|
+
useState
|
|
14
|
+
} from "react";
|
|
15
|
+
import { jsx } from "react/jsx-runtime";
|
|
16
|
+
var BrowserToolContext = createContext(
|
|
17
|
+
null
|
|
18
|
+
);
|
|
19
|
+
function isRecord(value) {
|
|
20
|
+
return Boolean(value) && typeof value === "object";
|
|
21
|
+
}
|
|
22
|
+
function isAction(value) {
|
|
23
|
+
if (!isRecord(value) || typeof value.action !== "string" || typeof value.fieldId !== "string") {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
if (value.action === "click") {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
if ((value.action === "fill" || value.action === "select") && typeof value.value === "string") {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
function parseWarnings(value) {
|
|
35
|
+
if (!Array.isArray(value)) {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
return value.filter((item) => typeof item === "string");
|
|
39
|
+
}
|
|
40
|
+
function BrowserToolProvider({
|
|
41
|
+
endpoint,
|
|
42
|
+
children
|
|
43
|
+
}) {
|
|
44
|
+
const [status, setStatus] = useState("idle");
|
|
45
|
+
const [lastPlan, setLastPlan] = useState(null);
|
|
46
|
+
const [lastExecution, setLastExecution] = useState(
|
|
47
|
+
null
|
|
48
|
+
);
|
|
49
|
+
const [error, setError] = useState(null);
|
|
50
|
+
const run = useCallback(
|
|
51
|
+
async ({ instruction, document }) => {
|
|
52
|
+
const trimmedInstruction = instruction.trim();
|
|
53
|
+
if (!trimmedInstruction) {
|
|
54
|
+
throw new Error("Instruction is required.");
|
|
55
|
+
}
|
|
56
|
+
setError(null);
|
|
57
|
+
setStatus("snapshotting");
|
|
58
|
+
try {
|
|
59
|
+
const fields = snapshot();
|
|
60
|
+
setStatus("planning");
|
|
61
|
+
const response = await fetch(endpoint, {
|
|
62
|
+
method: "POST",
|
|
63
|
+
headers: {
|
|
64
|
+
"content-type": "application/json"
|
|
65
|
+
},
|
|
66
|
+
body: JSON.stringify({
|
|
67
|
+
instruction: trimmedInstruction,
|
|
68
|
+
document: document?.trim() ? document.trim() : void 0,
|
|
69
|
+
fields
|
|
70
|
+
})
|
|
71
|
+
});
|
|
72
|
+
const payload = await response.json().catch(() => null);
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
const message = isRecord(payload) && typeof payload.error === "string" ? payload.error : `Planning failed with status ${response.status}`;
|
|
75
|
+
throw new Error(message);
|
|
76
|
+
}
|
|
77
|
+
const actions = isRecord(payload) && Array.isArray(payload.actions) ? payload.actions.filter(isAction) : [];
|
|
78
|
+
const warnings = isRecord(payload) ? parseWarnings(payload.warnings) : [];
|
|
79
|
+
const plan = {
|
|
80
|
+
fields,
|
|
81
|
+
actions,
|
|
82
|
+
warnings
|
|
83
|
+
};
|
|
84
|
+
setLastPlan(plan);
|
|
85
|
+
setLastExecution(null);
|
|
86
|
+
setStatus("ready");
|
|
87
|
+
return plan;
|
|
88
|
+
} catch (runError) {
|
|
89
|
+
const message = runError instanceof Error ? runError.message : "Failed to run planner.";
|
|
90
|
+
setError(message);
|
|
91
|
+
setStatus("error");
|
|
92
|
+
throw runError;
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
[endpoint]
|
|
96
|
+
);
|
|
97
|
+
const apply = useCallback(
|
|
98
|
+
(actions, fields) => {
|
|
99
|
+
setError(null);
|
|
100
|
+
setStatus("applying");
|
|
101
|
+
try {
|
|
102
|
+
const report = execute(actions, fields);
|
|
103
|
+
setLastExecution(report);
|
|
104
|
+
setStatus("idle");
|
|
105
|
+
return report;
|
|
106
|
+
} catch (applyError) {
|
|
107
|
+
const message = applyError instanceof Error ? applyError.message : "Failed to apply actions.";
|
|
108
|
+
setError(message);
|
|
109
|
+
setStatus("error");
|
|
110
|
+
throw applyError;
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
[]
|
|
114
|
+
);
|
|
115
|
+
const contextValue = useMemo(
|
|
116
|
+
() => ({
|
|
117
|
+
endpoint,
|
|
118
|
+
status,
|
|
119
|
+
lastPlan,
|
|
120
|
+
lastExecution,
|
|
121
|
+
error,
|
|
122
|
+
setError,
|
|
123
|
+
run,
|
|
124
|
+
apply
|
|
125
|
+
}),
|
|
126
|
+
[apply, endpoint, error, lastExecution, lastPlan, run, status]
|
|
127
|
+
);
|
|
128
|
+
return /* @__PURE__ */ jsx(BrowserToolContext.Provider, { value: contextValue, children });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/react/use-browser-tool.ts
|
|
132
|
+
function useBrowserTool() {
|
|
133
|
+
const context = useContext(BrowserToolContext);
|
|
134
|
+
if (!context) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
"useBrowserTool must be used inside <BrowserToolProvider />."
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return context;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/react/prompt-panel.tsx
|
|
143
|
+
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
144
|
+
function describeAction(action) {
|
|
145
|
+
if (action.action === "click") {
|
|
146
|
+
return `click ${action.fieldId}`;
|
|
147
|
+
}
|
|
148
|
+
if (action.action === "fill") {
|
|
149
|
+
return `fill ${action.fieldId} = ${JSON.stringify(action.value)}`;
|
|
150
|
+
}
|
|
151
|
+
return `select ${action.fieldId} = ${JSON.stringify(action.value)}`;
|
|
152
|
+
}
|
|
153
|
+
function PromptPanel({
|
|
154
|
+
defaultInstruction = "",
|
|
155
|
+
defaultDocument = "",
|
|
156
|
+
mount = "bottom-right"
|
|
157
|
+
}) {
|
|
158
|
+
const { status, run, apply, lastPlan, lastExecution, error, setError } = useBrowserTool();
|
|
159
|
+
const [instruction, setInstruction] = useState2(defaultInstruction);
|
|
160
|
+
const [documentText, setDocumentText] = useState2(defaultDocument);
|
|
161
|
+
const [notice, setNotice] = useState2(null);
|
|
162
|
+
const isPlanning = status === "snapshotting" || status === "planning";
|
|
163
|
+
const isApplying = status === "applying";
|
|
164
|
+
const combinedWarnings = useMemo2(() => {
|
|
165
|
+
const planWarnings = lastPlan?.warnings ?? [];
|
|
166
|
+
const executionWarnings = lastExecution?.warnings ?? [];
|
|
167
|
+
return [...planWarnings, ...executionWarnings];
|
|
168
|
+
}, [lastExecution, lastPlan]);
|
|
169
|
+
async function handlePlan() {
|
|
170
|
+
if (!instruction.trim()) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
setNotice(null);
|
|
174
|
+
setError(null);
|
|
175
|
+
try {
|
|
176
|
+
const plan = await run({
|
|
177
|
+
instruction: instruction.trim(),
|
|
178
|
+
document: documentText.trim() || void 0
|
|
179
|
+
});
|
|
180
|
+
if (plan.actions.length === 0) {
|
|
181
|
+
setNotice(
|
|
182
|
+
"No actions were generated. Try giving more explicit instructions."
|
|
183
|
+
);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
setNotice(
|
|
187
|
+
`Plan created: ${plan.actions.length} action(s). Review and click Apply.`
|
|
188
|
+
);
|
|
189
|
+
} catch (planError) {
|
|
190
|
+
setNotice(
|
|
191
|
+
planError instanceof Error ? planError.message : "Planning failed."
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function handleApply() {
|
|
196
|
+
if (!lastPlan || lastPlan.actions.length === 0) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
setNotice(null);
|
|
200
|
+
setError(null);
|
|
201
|
+
const report = apply(lastPlan.actions, lastPlan.fields);
|
|
202
|
+
setNotice(
|
|
203
|
+
`Applied ${report.applied} action(s), skipped ${report.skipped}.`
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
const wrapperClass = mount === "bottom-right" ? "fixed bottom-4 right-4 z-50 w-[min(28rem,calc(100vw-2rem))]" : "w-full max-w-xl";
|
|
207
|
+
return /* @__PURE__ */ jsx2("section", { className: wrapperClass, children: /* @__PURE__ */ jsxs("div", { className: "rounded-2xl border border-slate-700 bg-slate-950/95 p-4 shadow-2xl backdrop-blur", children: [
|
|
208
|
+
/* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center justify-between", children: [
|
|
209
|
+
/* @__PURE__ */ jsx2("p", { className: "text-xs uppercase tracking-[0.15em] text-cyan-300", children: "Browser Tool Prompt Panel" }),
|
|
210
|
+
/* @__PURE__ */ jsxs("p", { className: "text-[11px] text-slate-400", children: [
|
|
211
|
+
"status: ",
|
|
212
|
+
status
|
|
213
|
+
] })
|
|
214
|
+
] }),
|
|
215
|
+
/* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
|
|
216
|
+
/* @__PURE__ */ jsxs("label", { className: "block", children: [
|
|
217
|
+
/* @__PURE__ */ jsx2("span", { className: "mb-1 block text-xs text-slate-300", children: "Instruction" }),
|
|
218
|
+
/* @__PURE__ */ jsx2(
|
|
219
|
+
"textarea",
|
|
220
|
+
{
|
|
221
|
+
rows: 2,
|
|
222
|
+
value: instruction,
|
|
223
|
+
onChange: (event) => setInstruction(event.target.value),
|
|
224
|
+
placeholder: "Fill title and body with a concise summary...",
|
|
225
|
+
className: "w-full rounded-lg border border-slate-700 bg-slate-900/90 px-3 py-2 text-sm text-slate-100 outline-none focus:border-cyan-400"
|
|
226
|
+
}
|
|
227
|
+
)
|
|
228
|
+
] }),
|
|
229
|
+
/* @__PURE__ */ jsxs("label", { className: "block", children: [
|
|
230
|
+
/* @__PURE__ */ jsx2("span", { className: "mb-1 block text-xs text-slate-300", children: "Document (optional)" }),
|
|
231
|
+
/* @__PURE__ */ jsx2(
|
|
232
|
+
"textarea",
|
|
233
|
+
{
|
|
234
|
+
rows: 4,
|
|
235
|
+
value: documentText,
|
|
236
|
+
onChange: (event) => setDocumentText(event.target.value),
|
|
237
|
+
placeholder: "Paste source document here",
|
|
238
|
+
className: "w-full rounded-lg border border-slate-700 bg-slate-900/90 px-3 py-2 text-sm text-slate-100 outline-none focus:border-cyan-400"
|
|
239
|
+
}
|
|
240
|
+
)
|
|
241
|
+
] }),
|
|
242
|
+
/* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
|
|
243
|
+
/* @__PURE__ */ jsx2(
|
|
244
|
+
"button",
|
|
245
|
+
{
|
|
246
|
+
type: "button",
|
|
247
|
+
onClick: handlePlan,
|
|
248
|
+
disabled: !instruction.trim() || isPlanning || isApplying,
|
|
249
|
+
className: "rounded-lg bg-cyan-400 px-3 py-2 text-sm font-semibold text-slate-950 transition hover:bg-cyan-300 disabled:cursor-not-allowed disabled:opacity-50",
|
|
250
|
+
children: isPlanning ? "Planning..." : "Plan"
|
|
251
|
+
}
|
|
252
|
+
),
|
|
253
|
+
/* @__PURE__ */ jsx2(
|
|
254
|
+
"button",
|
|
255
|
+
{
|
|
256
|
+
type: "button",
|
|
257
|
+
onClick: handleApply,
|
|
258
|
+
disabled: !lastPlan || lastPlan.actions.length === 0 || isPlanning || isApplying,
|
|
259
|
+
className: "rounded-lg border border-slate-600 px-3 py-2 text-sm font-semibold text-slate-100 transition hover:border-slate-400 disabled:cursor-not-allowed disabled:opacity-50",
|
|
260
|
+
children: isApplying ? "Applying..." : "Apply"
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
] }),
|
|
264
|
+
notice ? /* @__PURE__ */ jsx2("p", { className: "text-xs text-slate-300", children: notice }) : null,
|
|
265
|
+
error ? /* @__PURE__ */ jsx2("p", { className: "text-xs text-rose-400", children: error }) : null
|
|
266
|
+
] }),
|
|
267
|
+
/* @__PURE__ */ jsxs("div", { className: "mt-4 border-t border-slate-800 pt-3", children: [
|
|
268
|
+
/* @__PURE__ */ jsx2("p", { className: "text-xs font-medium uppercase tracking-[0.12em] text-slate-400", children: "Action Plan" }),
|
|
269
|
+
!lastPlan ? /* @__PURE__ */ jsx2("p", { className: "mt-2 text-xs text-slate-500", children: "No plan yet." }) : lastPlan.actions.length === 0 ? /* @__PURE__ */ jsx2("p", { className: "mt-2 text-xs text-slate-500", children: "Planner returned no actions." }) : /* @__PURE__ */ jsx2("ul", { className: "mt-2 space-y-1", children: lastPlan.actions.map((action, index) => /* @__PURE__ */ jsx2(
|
|
270
|
+
"li",
|
|
271
|
+
{
|
|
272
|
+
className: "rounded-md border border-slate-800 bg-slate-900/80 px-2 py-1 text-xs text-slate-200",
|
|
273
|
+
children: describeAction(action)
|
|
274
|
+
},
|
|
275
|
+
`${action.fieldId}-${action.action}-${index}`
|
|
276
|
+
)) }),
|
|
277
|
+
combinedWarnings.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "mt-3 rounded-md border border-amber-400/30 bg-amber-400/10 p-2", children: [
|
|
278
|
+
/* @__PURE__ */ jsx2("p", { className: "text-[11px] font-semibold uppercase tracking-[0.12em] text-amber-200", children: "Warnings" }),
|
|
279
|
+
/* @__PURE__ */ jsx2("ul", { className: "mt-1 space-y-1 text-xs text-amber-100", children: combinedWarnings.map((warning, index) => /* @__PURE__ */ jsxs(
|
|
280
|
+
"li",
|
|
281
|
+
{
|
|
282
|
+
children: [
|
|
283
|
+
"- ",
|
|
284
|
+
warning
|
|
285
|
+
]
|
|
286
|
+
},
|
|
287
|
+
`${warning}-${// biome-ignore lint/suspicious/noArrayIndexKey: wip
|
|
288
|
+
index}`
|
|
289
|
+
)) })
|
|
290
|
+
] }) : null
|
|
291
|
+
] })
|
|
292
|
+
] }) });
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// src/react/use-agent.ts
|
|
296
|
+
import { execute as execute2, snapshot as snapshot2 } from "@giselles-ai/browser-tool/dom";
|
|
297
|
+
import { useCallback as useCallback2, useEffect, useMemo as useMemo3, useRef, useState as useState3 } from "react";
|
|
298
|
+
var LOG_PREFIX = "[agent-bridge-client]";
|
|
299
|
+
function isRecord2(value) {
|
|
300
|
+
return Boolean(value) && typeof value === "object";
|
|
301
|
+
}
|
|
302
|
+
function asString(value) {
|
|
303
|
+
return typeof value === "string" ? value : null;
|
|
304
|
+
}
|
|
305
|
+
function asNumber(value) {
|
|
306
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
307
|
+
}
|
|
308
|
+
function extractWarnings(value) {
|
|
309
|
+
if (!isRecord2(value) || !Array.isArray(value.warnings)) {
|
|
310
|
+
return [];
|
|
311
|
+
}
|
|
312
|
+
return value.warnings.filter(
|
|
313
|
+
(warning) => typeof warning === "string"
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
function extractJsonObjects(buffer) {
|
|
317
|
+
const objects = [];
|
|
318
|
+
let depth = 0;
|
|
319
|
+
let inString = false;
|
|
320
|
+
let escaped = false;
|
|
321
|
+
let startIndex = -1;
|
|
322
|
+
for (let index = 0; index < buffer.length; index += 1) {
|
|
323
|
+
const char = buffer[index];
|
|
324
|
+
if (escaped) {
|
|
325
|
+
escaped = false;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (char === "\\") {
|
|
329
|
+
escaped = true;
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (char === '"') {
|
|
333
|
+
inString = !inString;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (inString) {
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (char === "{") {
|
|
340
|
+
if (depth === 0) {
|
|
341
|
+
startIndex = index;
|
|
342
|
+
}
|
|
343
|
+
depth += 1;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (char === "}") {
|
|
347
|
+
depth -= 1;
|
|
348
|
+
if (depth === 0 && startIndex >= 0) {
|
|
349
|
+
objects.push(buffer.slice(startIndex, index + 1));
|
|
350
|
+
startIndex = -1;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (depth > 0 && startIndex >= 0) {
|
|
355
|
+
return {
|
|
356
|
+
objects,
|
|
357
|
+
rest: buffer.slice(startIndex)
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
return {
|
|
361
|
+
objects,
|
|
362
|
+
rest: ""
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function dedupeStringArray(next) {
|
|
366
|
+
const nextSet = new Set(next);
|
|
367
|
+
return Array.from(nextSet);
|
|
368
|
+
}
|
|
369
|
+
function useAgent({ endpoint }) {
|
|
370
|
+
const [bridgeStatus, setBridgeStatus] = useState3("idle");
|
|
371
|
+
const [running, setRunning] = useState3(false);
|
|
372
|
+
const [messages, setMessages] = useState3([]);
|
|
373
|
+
const [tools, setTools] = useState3([]);
|
|
374
|
+
const [warnings, setWarnings] = useState3([]);
|
|
375
|
+
const [stderrLogs, setStderrLogs] = useState3([]);
|
|
376
|
+
const [sandboxId, setSandboxId] = useState3(null);
|
|
377
|
+
const [geminiSessionId, setGeminiSessionId] = useState3(null);
|
|
378
|
+
const [error, setError] = useState3(null);
|
|
379
|
+
const normalizedEndpoint = useMemo3(
|
|
380
|
+
() => endpoint.replace(/\/+$/, ""),
|
|
381
|
+
[endpoint]
|
|
382
|
+
);
|
|
383
|
+
const eventSourceRef = useRef(null);
|
|
384
|
+
const reconnectTimerRef = useRef(null);
|
|
385
|
+
const mountedRef = useRef(true);
|
|
386
|
+
const sessionRef = useRef(null);
|
|
387
|
+
const messagesAssistantId = useRef(null);
|
|
388
|
+
const assistantBufferRef = useRef("");
|
|
389
|
+
const cleanupBridge = useCallback2(() => {
|
|
390
|
+
if (eventSourceRef.current) {
|
|
391
|
+
eventSourceRef.current.close();
|
|
392
|
+
eventSourceRef.current = null;
|
|
393
|
+
}
|
|
394
|
+
if (reconnectTimerRef.current) {
|
|
395
|
+
clearTimeout(reconnectTimerRef.current);
|
|
396
|
+
reconnectTimerRef.current = null;
|
|
397
|
+
}
|
|
398
|
+
}, []);
|
|
399
|
+
const handleBridgeResponse = useCallback2(
|
|
400
|
+
async (payload) => {
|
|
401
|
+
const currentSession = sessionRef.current;
|
|
402
|
+
if (!currentSession) {
|
|
403
|
+
console.warn(`${LOG_PREFIX} respond.skip.no-session`, {
|
|
404
|
+
payloadType: payload.type
|
|
405
|
+
});
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
const requestId = typeof payload.requestId === "string" ? payload.requestId : void 0;
|
|
409
|
+
const responseType = typeof payload.type === "string" ? payload.type : void 0;
|
|
410
|
+
console.info(`${LOG_PREFIX} respond.out`, {
|
|
411
|
+
sessionId: currentSession.sessionId,
|
|
412
|
+
requestId,
|
|
413
|
+
responseType
|
|
414
|
+
});
|
|
415
|
+
const bridgeBase = currentSession.bridgeUrl ?? normalizedEndpoint;
|
|
416
|
+
const response = await fetch(bridgeBase, {
|
|
417
|
+
method: "POST",
|
|
418
|
+
headers: {
|
|
419
|
+
"content-type": "application/json"
|
|
420
|
+
},
|
|
421
|
+
body: JSON.stringify({
|
|
422
|
+
type: "bridge.respond",
|
|
423
|
+
sessionId: currentSession.sessionId,
|
|
424
|
+
token: currentSession.token,
|
|
425
|
+
response: payload
|
|
426
|
+
})
|
|
427
|
+
});
|
|
428
|
+
console.info(`${LOG_PREFIX} respond.result`, {
|
|
429
|
+
sessionId: currentSession.sessionId,
|
|
430
|
+
requestId,
|
|
431
|
+
status: response.status,
|
|
432
|
+
ok: response.ok
|
|
433
|
+
});
|
|
434
|
+
},
|
|
435
|
+
[normalizedEndpoint]
|
|
436
|
+
);
|
|
437
|
+
const handleBridgeEvent = useCallback2(
|
|
438
|
+
async (event) => {
|
|
439
|
+
if (!isRecord2(event) || typeof event.type !== "string") {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (event.type === "ready") {
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const requestId = asString(event.requestId);
|
|
446
|
+
if (!requestId) {
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
try {
|
|
450
|
+
if (event.type === "error_response") {
|
|
451
|
+
const message = asString(event.message);
|
|
452
|
+
if (message) {
|
|
453
|
+
setError(message);
|
|
454
|
+
}
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (event.type === "snapshot_request") {
|
|
458
|
+
console.info(`${LOG_PREFIX} sse.snapshot_request`, {
|
|
459
|
+
requestId
|
|
460
|
+
});
|
|
461
|
+
const fields = snapshot2();
|
|
462
|
+
console.info(`${LOG_PREFIX} sse.snapshot_result`, {
|
|
463
|
+
requestId,
|
|
464
|
+
fieldCount: fields.length
|
|
465
|
+
});
|
|
466
|
+
await handleBridgeResponse({
|
|
467
|
+
type: "snapshot_response",
|
|
468
|
+
requestId,
|
|
469
|
+
fields
|
|
470
|
+
});
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (event.type === "execute_request") {
|
|
474
|
+
console.info(`${LOG_PREFIX} sse.execute_request`, {
|
|
475
|
+
requestId,
|
|
476
|
+
actionCount: Array.isArray(event.actions) ? event.actions.length : 0
|
|
477
|
+
});
|
|
478
|
+
const actions = Array.isArray(event.actions) ? event.actions : [];
|
|
479
|
+
const fields = Array.isArray(event.fields) ? event.fields : [];
|
|
480
|
+
const report = execute2(actions, fields);
|
|
481
|
+
console.info(`${LOG_PREFIX} sse.execute_result`, {
|
|
482
|
+
requestId,
|
|
483
|
+
applied: report.applied,
|
|
484
|
+
skipped: report.skipped
|
|
485
|
+
});
|
|
486
|
+
setWarnings(
|
|
487
|
+
(current) => dedupeStringArray([...current, ...report.warnings])
|
|
488
|
+
);
|
|
489
|
+
await handleBridgeResponse({
|
|
490
|
+
type: "execute_response",
|
|
491
|
+
requestId,
|
|
492
|
+
report
|
|
493
|
+
});
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
await handleBridgeResponse({
|
|
497
|
+
type: "error_response",
|
|
498
|
+
requestId,
|
|
499
|
+
message: `Unsupported bridge request type: ${event.type}`
|
|
500
|
+
});
|
|
501
|
+
} catch (bridgeError) {
|
|
502
|
+
const message = bridgeError instanceof Error ? bridgeError.message : "Bridge execution failed.";
|
|
503
|
+
setError(message);
|
|
504
|
+
setBridgeStatus("error");
|
|
505
|
+
await handleBridgeResponse({
|
|
506
|
+
type: "error_response",
|
|
507
|
+
requestId,
|
|
508
|
+
message
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
},
|
|
512
|
+
[handleBridgeResponse]
|
|
513
|
+
);
|
|
514
|
+
const connect = useCallback2(() => {
|
|
515
|
+
const currentSession = sessionRef.current;
|
|
516
|
+
if (!currentSession) {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
cleanupBridge();
|
|
520
|
+
setBridgeStatus("connecting");
|
|
521
|
+
const bridgeBase = currentSession.bridgeUrl ?? normalizedEndpoint;
|
|
522
|
+
const source = new EventSource(
|
|
523
|
+
`${bridgeBase}?type=bridge.events&sessionId=${encodeURIComponent(currentSession.sessionId)}&token=${encodeURIComponent(currentSession.token)}`
|
|
524
|
+
);
|
|
525
|
+
console.info(`${LOG_PREFIX} sse.connect`, {
|
|
526
|
+
sessionId: currentSession.sessionId
|
|
527
|
+
});
|
|
528
|
+
eventSourceRef.current = source;
|
|
529
|
+
source.onopen = () => {
|
|
530
|
+
if (!mountedRef.current) {
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
setBridgeStatus("connected");
|
|
534
|
+
console.info(`${LOG_PREFIX} sse.open`, {
|
|
535
|
+
sessionId: currentSession.sessionId
|
|
536
|
+
});
|
|
537
|
+
};
|
|
538
|
+
source.onmessage = (message) => {
|
|
539
|
+
console.info(`${LOG_PREFIX} sse.message.raw`, {
|
|
540
|
+
sessionId: currentSession.sessionId,
|
|
541
|
+
data: message.data
|
|
542
|
+
});
|
|
543
|
+
try {
|
|
544
|
+
const payload = JSON.parse(message.data);
|
|
545
|
+
console.info(`${LOG_PREFIX} sse.message.parsed`, {
|
|
546
|
+
sessionId: currentSession.sessionId,
|
|
547
|
+
type: typeof payload === "object" && payload && "type" in payload && typeof payload.type === "string" ? payload.type : "unknown"
|
|
548
|
+
});
|
|
549
|
+
void handleBridgeEvent(payload);
|
|
550
|
+
} catch (error2) {
|
|
551
|
+
console.error(`${LOG_PREFIX} sse.message.parse_error`, {
|
|
552
|
+
sessionId: currentSession.sessionId,
|
|
553
|
+
error: error2 instanceof Error ? error2.message : String(error2),
|
|
554
|
+
data: message.data
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
source.onerror = () => {
|
|
559
|
+
if (!mountedRef.current) {
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
setBridgeStatus("connecting");
|
|
563
|
+
console.warn(`${LOG_PREFIX} sse.error`, {
|
|
564
|
+
sessionId: currentSession.sessionId
|
|
565
|
+
});
|
|
566
|
+
if (!reconnectTimerRef.current) {
|
|
567
|
+
reconnectTimerRef.current = setTimeout(() => {
|
|
568
|
+
reconnectTimerRef.current = null;
|
|
569
|
+
connect();
|
|
570
|
+
}, 1500);
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
}, [cleanupBridge, handleBridgeEvent, normalizedEndpoint]);
|
|
574
|
+
useEffect(() => {
|
|
575
|
+
mountedRef.current = true;
|
|
576
|
+
return () => {
|
|
577
|
+
mountedRef.current = false;
|
|
578
|
+
cleanupBridge();
|
|
579
|
+
};
|
|
580
|
+
}, [cleanupBridge]);
|
|
581
|
+
const handleStreamEvent = useCallback2(
|
|
582
|
+
(event) => {
|
|
583
|
+
if (typeof event.type !== "string") {
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
if (event.type === "bridge.session") {
|
|
587
|
+
const sessionId = asString(event.sessionId);
|
|
588
|
+
const token = asString(event.token);
|
|
589
|
+
const bridgeUrl = asString(event.bridgeUrl);
|
|
590
|
+
const expiresAt = asNumber(event.expiresAt) ?? Date.now() + 10 * 60 * 1e3;
|
|
591
|
+
if (!sessionId || !token) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
sessionRef.current = {
|
|
595
|
+
sessionId,
|
|
596
|
+
token,
|
|
597
|
+
expiresAt,
|
|
598
|
+
bridgeUrl
|
|
599
|
+
};
|
|
600
|
+
console.info(`${LOG_PREFIX} stream.bridge_session`, {
|
|
601
|
+
sessionId
|
|
602
|
+
});
|
|
603
|
+
connect();
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
if (event.type === "sandbox") {
|
|
607
|
+
const nextSandboxId = asString(event.sandbox_id);
|
|
608
|
+
if (nextSandboxId) {
|
|
609
|
+
setSandboxId(nextSandboxId);
|
|
610
|
+
}
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
if (event.type === "init") {
|
|
614
|
+
const nextSessionId = asString(event.session_id);
|
|
615
|
+
if (nextSessionId) {
|
|
616
|
+
setGeminiSessionId(nextSessionId);
|
|
617
|
+
}
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
if (event.type === "stderr") {
|
|
621
|
+
const text = asString(event.content);
|
|
622
|
+
if (text) {
|
|
623
|
+
setStderrLogs((current) => [...current, text]);
|
|
624
|
+
}
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (event.type === "message") {
|
|
628
|
+
const role = asString(event.role);
|
|
629
|
+
const content = asString(event.content) ?? "";
|
|
630
|
+
const isDelta = Boolean(event.delta);
|
|
631
|
+
if (role === "assistant") {
|
|
632
|
+
if (isDelta) {
|
|
633
|
+
const currentId = messagesAssistantId.current;
|
|
634
|
+
if (!currentId) {
|
|
635
|
+
const nextId = crypto.randomUUID();
|
|
636
|
+
messagesAssistantId.current = nextId;
|
|
637
|
+
assistantBufferRef.current = content;
|
|
638
|
+
setMessages((current) => [
|
|
639
|
+
...current,
|
|
640
|
+
{ id: nextId, role: "assistant", content }
|
|
641
|
+
]);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
const merged = `${assistantBufferRef.current}${content}`;
|
|
645
|
+
assistantBufferRef.current = merged;
|
|
646
|
+
setMessages(
|
|
647
|
+
(current) => current.map(
|
|
648
|
+
(message) => message.id === currentId ? { ...message, content: merged } : message
|
|
649
|
+
)
|
|
650
|
+
);
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
if (content.trim().length > 0) {
|
|
654
|
+
const nextId = crypto.randomUUID();
|
|
655
|
+
messagesAssistantId.current = nextId;
|
|
656
|
+
assistantBufferRef.current = content;
|
|
657
|
+
setMessages((current) => [
|
|
658
|
+
...current,
|
|
659
|
+
{ id: nextId, role: "assistant", content }
|
|
660
|
+
]);
|
|
661
|
+
}
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
if (role === "user" && content.trim().length > 0) {
|
|
665
|
+
setMessages((current) => {
|
|
666
|
+
const last = current[current.length - 1];
|
|
667
|
+
if (last && last.role === "user" && last.content === content) {
|
|
668
|
+
return current;
|
|
669
|
+
}
|
|
670
|
+
return [
|
|
671
|
+
...current,
|
|
672
|
+
{ id: crypto.randomUUID(), role: "user", content }
|
|
673
|
+
];
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (event.type === "tool_use") {
|
|
679
|
+
const toolId = asString(event.tool_id) ?? crypto.randomUUID();
|
|
680
|
+
const toolName = asString(event.tool_name) ?? "tool";
|
|
681
|
+
setTools((current) => [
|
|
682
|
+
...current,
|
|
683
|
+
{
|
|
684
|
+
id: crypto.randomUUID(),
|
|
685
|
+
toolId,
|
|
686
|
+
toolName,
|
|
687
|
+
parameters: event.parameters
|
|
688
|
+
}
|
|
689
|
+
]);
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
if (event.type === "tool_result") {
|
|
693
|
+
const toolId = asString(event.tool_id);
|
|
694
|
+
if (!toolId) {
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
const status2 = asString(event.status);
|
|
698
|
+
const nextStatus = status2 === "success" || status2 === "error" ? status2 : void 0;
|
|
699
|
+
setTools(
|
|
700
|
+
(current) => current.map(
|
|
701
|
+
(tool) => tool.toolId === toolId ? {
|
|
702
|
+
...tool,
|
|
703
|
+
status: nextStatus,
|
|
704
|
+
output: event.output
|
|
705
|
+
} : tool
|
|
706
|
+
)
|
|
707
|
+
);
|
|
708
|
+
const parsedWarnings = extractWarnings(event.output);
|
|
709
|
+
if (parsedWarnings.length > 0) {
|
|
710
|
+
setWarnings(
|
|
711
|
+
(current) => dedupeStringArray([...current, ...parsedWarnings])
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
[connect]
|
|
717
|
+
);
|
|
718
|
+
const sendMessage = useCallback2(
|
|
719
|
+
async ({ message, document }) => {
|
|
720
|
+
const trimmedMessage = message.trim();
|
|
721
|
+
if (!trimmedMessage || running) {
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
cleanupBridge();
|
|
725
|
+
sessionRef.current = null;
|
|
726
|
+
setBridgeStatus("idle");
|
|
727
|
+
setError(null);
|
|
728
|
+
setRunning(true);
|
|
729
|
+
assistantBufferRef.current = "";
|
|
730
|
+
messagesAssistantId.current = null;
|
|
731
|
+
setMessages((current) => [
|
|
732
|
+
...current,
|
|
733
|
+
{ id: crypto.randomUUID(), role: "user", content: trimmedMessage }
|
|
734
|
+
]);
|
|
735
|
+
try {
|
|
736
|
+
console.info(`${LOG_PREFIX} run.start`, {
|
|
737
|
+
messageLength: trimmedMessage.length,
|
|
738
|
+
hasDocument: Boolean(document?.trim())
|
|
739
|
+
});
|
|
740
|
+
const response = await fetch(normalizedEndpoint, {
|
|
741
|
+
method: "POST",
|
|
742
|
+
headers: {
|
|
743
|
+
"content-type": "application/json"
|
|
744
|
+
},
|
|
745
|
+
body: JSON.stringify({
|
|
746
|
+
type: "agent.run",
|
|
747
|
+
message: trimmedMessage,
|
|
748
|
+
document: document?.trim() ? document.trim() : void 0,
|
|
749
|
+
session_id: geminiSessionId ?? void 0,
|
|
750
|
+
sandbox_id: sandboxId ?? void 0
|
|
751
|
+
})
|
|
752
|
+
});
|
|
753
|
+
if (!response.ok || !response.body) {
|
|
754
|
+
throw new Error(`Failed to start stream (${response.status}).`);
|
|
755
|
+
}
|
|
756
|
+
console.info(`${LOG_PREFIX} run.stream.open`, {
|
|
757
|
+
status: response.status
|
|
758
|
+
});
|
|
759
|
+
const reader = response.body.getReader();
|
|
760
|
+
const decoder = new TextDecoder();
|
|
761
|
+
let buffer = "";
|
|
762
|
+
while (true) {
|
|
763
|
+
const { done, value } = await reader.read();
|
|
764
|
+
if (done) {
|
|
765
|
+
break;
|
|
766
|
+
}
|
|
767
|
+
buffer += decoder.decode(value, { stream: true });
|
|
768
|
+
const parsed = extractJsonObjects(buffer);
|
|
769
|
+
buffer = parsed.rest;
|
|
770
|
+
for (const objectText of parsed.objects) {
|
|
771
|
+
try {
|
|
772
|
+
const parsedEvent = JSON.parse(objectText);
|
|
773
|
+
handleStreamEvent(parsedEvent);
|
|
774
|
+
} catch {
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
if (buffer.trim().length > 0) {
|
|
779
|
+
try {
|
|
780
|
+
const parsedEvent = JSON.parse(buffer);
|
|
781
|
+
handleStreamEvent(parsedEvent);
|
|
782
|
+
} catch {
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
} catch (sendError) {
|
|
786
|
+
const messageText = sendError instanceof Error ? sendError.message : "Failed to send message.";
|
|
787
|
+
setError(messageText);
|
|
788
|
+
setBridgeStatus("error");
|
|
789
|
+
throw sendError;
|
|
790
|
+
} finally {
|
|
791
|
+
setRunning(false);
|
|
792
|
+
}
|
|
793
|
+
},
|
|
794
|
+
[
|
|
795
|
+
cleanupBridge,
|
|
796
|
+
geminiSessionId,
|
|
797
|
+
handleStreamEvent,
|
|
798
|
+
normalizedEndpoint,
|
|
799
|
+
running,
|
|
800
|
+
sandboxId
|
|
801
|
+
]
|
|
802
|
+
);
|
|
803
|
+
const status = running ? "running" : bridgeStatus;
|
|
804
|
+
return {
|
|
805
|
+
status,
|
|
806
|
+
messages,
|
|
807
|
+
tools,
|
|
808
|
+
warnings,
|
|
809
|
+
stderrLogs,
|
|
810
|
+
sandboxId,
|
|
811
|
+
geminiSessionId,
|
|
812
|
+
error,
|
|
813
|
+
sendMessage
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
export {
|
|
817
|
+
BrowserToolProvider,
|
|
818
|
+
PromptPanel,
|
|
819
|
+
useAgent,
|
|
820
|
+
useBrowserTool
|
|
821
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@giselles-ai/sandbox-agent",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"sideEffects": false,
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/giselles-ai/agent-container.git",
|
|
10
|
+
"directory": "packages/sandbox-agent"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./react": {
|
|
22
|
+
"types": "./dist/react/index.d.ts",
|
|
23
|
+
"import": "./dist/react/index.js",
|
|
24
|
+
"default": "./dist/react/index.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"zod": "4.3.6",
|
|
29
|
+
"@giselles-ai/browser-tool": "0.1.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"react": ">=19.0.0",
|
|
33
|
+
"react-dom": ">=19.0.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "25.0.10",
|
|
37
|
+
"@types/react": "19.2.10",
|
|
38
|
+
"@types/react-dom": "19.2.3",
|
|
39
|
+
"tsup": "8.5.1",
|
|
40
|
+
"typescript": "5.9.3"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "pnpm clean && tsup --config tsup.ts",
|
|
44
|
+
"clean": "rm -rf dist *.tsbuildinfo",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
46
|
+
"format": "pnpm exec biome check --write ."
|
|
47
|
+
}
|
|
48
|
+
}
|