@openagentsinc/ai-sdk-sandbox-local 0.1.1-rc.1
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 +15 -0
- package/package.json +32 -0
- package/src/index.test.ts +276 -0
- package/src/index.ts +641 -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 2025 OpenAgents, Inc.
|
|
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,15 @@
|
|
|
1
|
+
# @openagentsinc/ai-sdk-sandbox-local
|
|
2
|
+
|
|
3
|
+
Owner-local `HarnessV1SandboxProvider` for AI SDK harness fixtures.
|
|
4
|
+
|
|
5
|
+
This package is intentionally not a production sandbox. It creates a temporary
|
|
6
|
+
workspace, scopes file APIs to that workspace, launches child processes with
|
|
7
|
+
explicit `HOME`, `CODEX_HOME`, and `CLAUDE_CONFIG_DIR`, and exposes localhost
|
|
8
|
+
port URLs for bridge experiments. It does not provide kernel, network, or
|
|
9
|
+
multi-tenant containment.
|
|
10
|
+
|
|
11
|
+
Use it to prove Khala Code can run AI SDK harnesses without Vercel before the
|
|
12
|
+
same adapter contract is backed by the OpenAgents sandbox/workroom runtime.
|
|
13
|
+
|
|
14
|
+
Set `inheritClaudeConfig: true` for an owner-local Claude Code session that
|
|
15
|
+
must reuse the host CLI's current login instead of an isolated config path.
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@openagentsinc/ai-sdk-sandbox-local",
|
|
3
|
+
"version": "0.1.1-rc.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"files": [
|
|
7
|
+
"src",
|
|
8
|
+
"README.md"
|
|
9
|
+
],
|
|
10
|
+
"type": "module",
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@ai-sdk/harness": "1.0.36",
|
|
20
|
+
"@ai-sdk/provider-utils": "5.0.11",
|
|
21
|
+
"zod": "^4.1.8"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/node": "24.13.1",
|
|
25
|
+
"typescript": "^6.0.3",
|
|
26
|
+
"@types/vite-plus-matchers": "0.0.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "vp test --run",
|
|
30
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { afterEach, describe, expect, test } from "vite-plus/test";
|
|
5
|
+
import { HarnessAgent } from "@ai-sdk/harness/agent";
|
|
6
|
+
import type {
|
|
7
|
+
HarnessV1,
|
|
8
|
+
HarnessV1ContinueTurnOptions,
|
|
9
|
+
HarnessV1LifecycleState,
|
|
10
|
+
HarnessV1Prompt,
|
|
11
|
+
HarnessV1PromptTurnOptions,
|
|
12
|
+
HarnessV1Session,
|
|
13
|
+
HarnessV1StartOptions,
|
|
14
|
+
HarnessV1StreamPart,
|
|
15
|
+
} from "@ai-sdk/harness";
|
|
16
|
+
import { createLocalAiSdkSandboxProvider } from "./index.js";
|
|
17
|
+
|
|
18
|
+
const roots: string[] = [];
|
|
19
|
+
|
|
20
|
+
afterEach(async () => {
|
|
21
|
+
await Promise.all(
|
|
22
|
+
roots.splice(0).map((root) =>
|
|
23
|
+
rm(root, {
|
|
24
|
+
force: true,
|
|
25
|
+
recursive: true,
|
|
26
|
+
}),
|
|
27
|
+
),
|
|
28
|
+
);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe("createLocalAiSdkSandboxProvider", () => {
|
|
32
|
+
test("runs a public HarnessAgent.stream fixture without Vercel", async () => {
|
|
33
|
+
const root = await mkdtemp(resolve(tmpdir(), "openagents-local-provider-"));
|
|
34
|
+
roots.push(root);
|
|
35
|
+
const provider = createLocalAiSdkSandboxProvider({
|
|
36
|
+
defaultPorts: [4321],
|
|
37
|
+
rootDirectory: root,
|
|
38
|
+
});
|
|
39
|
+
const agent = new HarnessAgent({
|
|
40
|
+
harness: fixtureHarness,
|
|
41
|
+
sandbox: provider,
|
|
42
|
+
sandboxConfig: {
|
|
43
|
+
onSession: async ({ session, sessionWorkDir }) => {
|
|
44
|
+
await session.writeTextFile({
|
|
45
|
+
content: "public fixture\n",
|
|
46
|
+
path: `${sessionWorkDir}/README.md`,
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
const session = await agent.createSession({
|
|
52
|
+
sessionId: "fixture-session",
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
const result = await agent.stream({
|
|
57
|
+
prompt: "repair the public fixture",
|
|
58
|
+
session,
|
|
59
|
+
});
|
|
60
|
+
let text = "";
|
|
61
|
+
for await (const delta of result.textStream) {
|
|
62
|
+
text += delta;
|
|
63
|
+
}
|
|
64
|
+
expect(text).toContain("public fixture repaired");
|
|
65
|
+
|
|
66
|
+
const sandbox = await provider.resumeSession?.({
|
|
67
|
+
sessionId: "fixture-session",
|
|
68
|
+
});
|
|
69
|
+
expect(sandbox).toBeDefined();
|
|
70
|
+
if (sandbox === undefined) throw new Error("Missing resumed sandbox.");
|
|
71
|
+
expect(sandbox.defaultWorkingDirectory).toStartWith(root);
|
|
72
|
+
expect(await sandbox.getPortUrl({ port: 4321, protocol: "ws" })).toBe("ws://127.0.0.1:4321/");
|
|
73
|
+
expect(
|
|
74
|
+
await sandbox.readTextFile({
|
|
75
|
+
path: `${sandbox.defaultWorkingDirectory}/codex-fixture-session/result.txt`,
|
|
76
|
+
}),
|
|
77
|
+
).toBe("repair the public fixture\n");
|
|
78
|
+
const env = await sandbox.run({
|
|
79
|
+
command: 'printf \'%s\\n%s\\n%s\' "$HOME" "$CODEX_HOME" "$CLAUDE_CONFIG_DIR"',
|
|
80
|
+
});
|
|
81
|
+
expect(env.stdout).toContain(`${sandbox.defaultWorkingDirectory}/.openagents-home`);
|
|
82
|
+
expect(env.stdout).toContain("/codex");
|
|
83
|
+
expect(env.stdout).toContain("/claude-code");
|
|
84
|
+
await expect(
|
|
85
|
+
sandbox.readTextFile({ path: resolve(tmpdir(), "outside-openagents.txt") }),
|
|
86
|
+
).rejects.toThrow("escapes local sandbox");
|
|
87
|
+
const bootstrapFile = "/tmp/harness/local-provider-test.txt";
|
|
88
|
+
await sandbox.writeTextFile({ content: "bootstrap\n", path: bootstrapFile });
|
|
89
|
+
expect(await sandbox.readTextFile({ path: bootstrapFile })).toBe("bootstrap\n");
|
|
90
|
+
await rm(bootstrapFile, { force: true });
|
|
91
|
+
} finally {
|
|
92
|
+
await session.destroy();
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("restricted view keeps infra controls off the tool-safe surface", async () => {
|
|
97
|
+
const root = await mkdtemp(resolve(tmpdir(), "openagents-local-provider-"));
|
|
98
|
+
roots.push(root);
|
|
99
|
+
const provider = createLocalAiSdkSandboxProvider({ rootDirectory: root });
|
|
100
|
+
const sandbox = await provider.createSession({ sessionId: "restricted" });
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const restricted = sandbox.restricted();
|
|
104
|
+
await restricted.writeTextFile({
|
|
105
|
+
content: "a\nb\nc\n",
|
|
106
|
+
path: "notes.txt",
|
|
107
|
+
});
|
|
108
|
+
expect(
|
|
109
|
+
await restricted.readTextFile({
|
|
110
|
+
endLine: 2,
|
|
111
|
+
path: "notes.txt",
|
|
112
|
+
startLine: 2,
|
|
113
|
+
}),
|
|
114
|
+
).toBe("b");
|
|
115
|
+
expect("stop" in restricted).toBe(false);
|
|
116
|
+
expect("setNetworkPolicy" in restricted).toBe(false);
|
|
117
|
+
await expect(restricted.readTextFile({ path: "../outside.txt" })).rejects.toThrow(
|
|
118
|
+
"escapes local sandbox",
|
|
119
|
+
);
|
|
120
|
+
} finally {
|
|
121
|
+
await sandbox.destroy?.();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("can preserve the host Claude configuration lookup", async () => {
|
|
126
|
+
const root = await mkdtemp(resolve(tmpdir(), "openagents-local-provider-"));
|
|
127
|
+
roots.push(root);
|
|
128
|
+
const provider = createLocalAiSdkSandboxProvider({
|
|
129
|
+
env: { CLAUDE_CONFIG_DIR: "" },
|
|
130
|
+
inheritClaudeConfig: true,
|
|
131
|
+
rootDirectory: root,
|
|
132
|
+
});
|
|
133
|
+
const sandbox = await provider.createSession({ sessionId: "claude-auth" });
|
|
134
|
+
|
|
135
|
+
try {
|
|
136
|
+
const result = await sandbox.run({
|
|
137
|
+
command: "node -p 'JSON.stringify(process.env.CLAUDE_CONFIG_DIR)'",
|
|
138
|
+
});
|
|
139
|
+
expect(result.stdout.trim()).toBe('\"\"');
|
|
140
|
+
expect(sandbox.description).toContain("CLAUDE_CONFIG_DIR: inherited from host");
|
|
141
|
+
} finally {
|
|
142
|
+
await sandbox.destroy?.();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("resolves an ephemeral bridge port when port zero is exposed", async () => {
|
|
147
|
+
const root = await mkdtemp(resolve(tmpdir(), "openagents-local-provider-"));
|
|
148
|
+
roots.push(root);
|
|
149
|
+
const provider = createLocalAiSdkSandboxProvider({
|
|
150
|
+
defaultPorts: [0],
|
|
151
|
+
rootDirectory: root,
|
|
152
|
+
});
|
|
153
|
+
const sandbox = await provider.createSession({ sessionId: "ephemeral-port" });
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
expect(await sandbox.getPortUrl({ port: 54321, protocol: "ws" })).toBe(
|
|
157
|
+
"ws://127.0.0.1:54321/",
|
|
158
|
+
);
|
|
159
|
+
} finally {
|
|
160
|
+
await sandbox.destroy?.();
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const fixtureHarness: HarnessV1 = {
|
|
166
|
+
builtinTools: {},
|
|
167
|
+
harnessId: "codex",
|
|
168
|
+
specificationVersion: "harness-v1",
|
|
169
|
+
doStart: async (options) => makeFixtureSession(options),
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
function makeFixtureSession(options: HarnessV1StartOptions): HarnessV1Session {
|
|
173
|
+
const lifecycle = (): HarnessV1LifecycleState => ({
|
|
174
|
+
data: { sessionId: options.sessionId },
|
|
175
|
+
harnessId: "codex",
|
|
176
|
+
specificationVersion: "harness-v1",
|
|
177
|
+
type: "resume-session",
|
|
178
|
+
});
|
|
179
|
+
const promptTurn = async (turn: HarnessV1PromptTurnOptions) => {
|
|
180
|
+
const text = promptToText(turn.prompt);
|
|
181
|
+
await options.sandboxSession.restricted().writeTextFile({
|
|
182
|
+
content: `${text}\n`,
|
|
183
|
+
path: `${options.sessionWorkDir}/result.txt`,
|
|
184
|
+
});
|
|
185
|
+
turn.emit({ type: "stream-start", modelId: "fixture-model" });
|
|
186
|
+
turn.emit({ type: "text-start", id: "text-1" });
|
|
187
|
+
turn.emit({
|
|
188
|
+
delta: `public fixture repaired: ${text}`,
|
|
189
|
+
id: "text-1",
|
|
190
|
+
type: "text-delta",
|
|
191
|
+
});
|
|
192
|
+
turn.emit({ type: "text-end", id: "text-1" });
|
|
193
|
+
turn.emit({
|
|
194
|
+
finishReason: stopFinishReason,
|
|
195
|
+
type: "finish-step",
|
|
196
|
+
usage: fixtureUsage,
|
|
197
|
+
});
|
|
198
|
+
turn.emit({
|
|
199
|
+
finishReason: stopFinishReason,
|
|
200
|
+
totalUsage: fixtureUsage,
|
|
201
|
+
type: "finish",
|
|
202
|
+
});
|
|
203
|
+
return {
|
|
204
|
+
done: Promise.resolve(),
|
|
205
|
+
submitToolResult: async () => {},
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
const continueTurn = async (turn: HarnessV1ContinueTurnOptions) => {
|
|
209
|
+
turn.emit({ type: "stream-start", modelId: "fixture-model" });
|
|
210
|
+
turn.emit({
|
|
211
|
+
finishReason: stopFinishReason,
|
|
212
|
+
totalUsage: zeroUsage,
|
|
213
|
+
type: "finish",
|
|
214
|
+
});
|
|
215
|
+
return {
|
|
216
|
+
done: Promise.resolve(),
|
|
217
|
+
submitToolResult: async () => {},
|
|
218
|
+
};
|
|
219
|
+
};
|
|
220
|
+
return {
|
|
221
|
+
doCompact: async () => {},
|
|
222
|
+
doContinueTurn: continueTurn,
|
|
223
|
+
doDestroy: async () => {},
|
|
224
|
+
doDetach: async () =>
|
|
225
|
+
lifecycle() as Extract<HarnessV1LifecycleState, { type: "resume-session" }>,
|
|
226
|
+
doPromptTurn: promptTurn,
|
|
227
|
+
doStop: async () => lifecycle() as Extract<HarnessV1LifecycleState, { type: "resume-session" }>,
|
|
228
|
+
doSuspendTurn: async () => ({
|
|
229
|
+
data: { sessionId: options.sessionId },
|
|
230
|
+
harnessId: "codex",
|
|
231
|
+
specificationVersion: "harness-v1",
|
|
232
|
+
type: "continue-turn",
|
|
233
|
+
}),
|
|
234
|
+
isResume: options.resumeFrom !== undefined || options.continueFrom !== undefined,
|
|
235
|
+
sessionId: options.sessionId,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function promptToText(prompt: HarnessV1Prompt): string {
|
|
240
|
+
if (typeof prompt === "string") return prompt;
|
|
241
|
+
if (typeof prompt.content === "string") return prompt.content;
|
|
242
|
+
return prompt.content.map((part) => (part.type === "text" ? part.text : "")).join("");
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const stopFinishReason: Extract<HarnessV1StreamPart, { type: "finish" }>["finishReason"] = {
|
|
246
|
+
raw: undefined,
|
|
247
|
+
unified: "stop",
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const fixtureUsage: Extract<HarnessV1StreamPart, { type: "finish" }>["totalUsage"] = {
|
|
251
|
+
inputTokens: {
|
|
252
|
+
cacheRead: undefined,
|
|
253
|
+
cacheWrite: undefined,
|
|
254
|
+
noCache: 1,
|
|
255
|
+
total: 1,
|
|
256
|
+
},
|
|
257
|
+
outputTokens: {
|
|
258
|
+
reasoning: undefined,
|
|
259
|
+
text: 1,
|
|
260
|
+
total: 1,
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const zeroUsage: Extract<HarnessV1StreamPart, { type: "finish" }>["totalUsage"] = {
|
|
265
|
+
inputTokens: {
|
|
266
|
+
cacheRead: undefined,
|
|
267
|
+
cacheWrite: undefined,
|
|
268
|
+
noCache: undefined,
|
|
269
|
+
total: undefined,
|
|
270
|
+
},
|
|
271
|
+
outputTokens: {
|
|
272
|
+
reasoning: undefined,
|
|
273
|
+
text: undefined,
|
|
274
|
+
total: undefined,
|
|
275
|
+
},
|
|
276
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
import { spawn as spawnChild, type ChildProcessByStdio } from "node:child_process";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { dirname, resolve, sep } from "node:path";
|
|
6
|
+
import type { Readable } from "node:stream";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import type {
|
|
9
|
+
HarnessV1NetworkPolicy,
|
|
10
|
+
HarnessV1NetworkSandboxSession,
|
|
11
|
+
HarnessV1SandboxProvider,
|
|
12
|
+
} from "@ai-sdk/harness";
|
|
13
|
+
import {
|
|
14
|
+
extractLines,
|
|
15
|
+
type Experimental_SandboxProcess,
|
|
16
|
+
type Experimental_SandboxSession,
|
|
17
|
+
} from "@ai-sdk/provider-utils";
|
|
18
|
+
|
|
19
|
+
const DEFAULT_PROVIDER_ID = "openagents-local-sandbox";
|
|
20
|
+
// AI SDK harness adapters place reproducible bridge assets here. It is the
|
|
21
|
+
// only absolute host path accepted by this owner-local provider.
|
|
22
|
+
const HARNESS_BOOTSTRAP_DIRECTORY = "/tmp/harness";
|
|
23
|
+
|
|
24
|
+
export type LocalAiSdkSandboxAccountHomes = Readonly<{
|
|
25
|
+
home: string;
|
|
26
|
+
codexHome: string;
|
|
27
|
+
claudeConfigDir: string;
|
|
28
|
+
}>;
|
|
29
|
+
|
|
30
|
+
export type LocalAiSdkSandboxProviderOptions = Readonly<{
|
|
31
|
+
providerId?: string;
|
|
32
|
+
rootDirectory?: string;
|
|
33
|
+
defaultPorts?: ReadonlyArray<number>;
|
|
34
|
+
defaultNetworkPolicy?: HarnessV1NetworkPolicy;
|
|
35
|
+
env?: Readonly<Record<string, string>>;
|
|
36
|
+
accountHomes?: Partial<LocalAiSdkSandboxAccountHomes>;
|
|
37
|
+
inheritClaudeConfig?: boolean;
|
|
38
|
+
}>;
|
|
39
|
+
|
|
40
|
+
export function createLocalAiSdkSandboxProvider(
|
|
41
|
+
options: LocalAiSdkSandboxProviderOptions = {},
|
|
42
|
+
): HarnessV1SandboxProvider {
|
|
43
|
+
return new LocalAiSdkSandboxProvider(options);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class LocalAiSdkSandboxProvider implements HarnessV1SandboxProvider {
|
|
47
|
+
readonly specificationVersion = "harness-sandbox-v1" as const;
|
|
48
|
+
readonly providerId: string;
|
|
49
|
+
private readonly options: LocalAiSdkSandboxProviderOptions;
|
|
50
|
+
private readonly sessions = new Map<string, LocalAiSdkNetworkSandboxSession>();
|
|
51
|
+
|
|
52
|
+
constructor(options: LocalAiSdkSandboxProviderOptions = {}) {
|
|
53
|
+
this.providerId = options.providerId ?? DEFAULT_PROVIDER_ID;
|
|
54
|
+
this.options = options;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
createSession = async (
|
|
58
|
+
options: {
|
|
59
|
+
sessionId?: string;
|
|
60
|
+
abortSignal?: AbortSignal;
|
|
61
|
+
identity?: string;
|
|
62
|
+
onFirstCreate?: (
|
|
63
|
+
session: Experimental_SandboxSession,
|
|
64
|
+
opts: { abortSignal?: AbortSignal },
|
|
65
|
+
) => Promise<void>;
|
|
66
|
+
} = {},
|
|
67
|
+
): Promise<HarnessV1NetworkSandboxSession> => {
|
|
68
|
+
options.abortSignal?.throwIfAborted();
|
|
69
|
+
const sessionId = options.sessionId ?? `local-${randomUUID()}`;
|
|
70
|
+
const existing = this.sessions.get(sessionId);
|
|
71
|
+
if (existing !== undefined) return existing;
|
|
72
|
+
|
|
73
|
+
const workspaceRoot =
|
|
74
|
+
this.options.rootDirectory === undefined
|
|
75
|
+
? await mkdtemp(resolve(tmpdir(), "openagents-ai-sdk-sandbox-"))
|
|
76
|
+
: resolve(
|
|
77
|
+
this.options.rootDirectory,
|
|
78
|
+
stableWorkspaceName({
|
|
79
|
+
sessionId,
|
|
80
|
+
...(options.identity === undefined ? {} : { identity: options.identity }),
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
await mkdir(workspaceRoot, { recursive: true });
|
|
84
|
+
|
|
85
|
+
const homes = resolveLocalAccountHomes({
|
|
86
|
+
workspaceRoot,
|
|
87
|
+
...(this.options.accountHomes === undefined
|
|
88
|
+
? {}
|
|
89
|
+
: { accountHomes: this.options.accountHomes }),
|
|
90
|
+
});
|
|
91
|
+
await Promise.all([
|
|
92
|
+
mkdir(homes.home, { recursive: true }),
|
|
93
|
+
mkdir(homes.codexHome, { recursive: true }),
|
|
94
|
+
mkdir(homes.claudeConfigDir, { recursive: true }),
|
|
95
|
+
]);
|
|
96
|
+
|
|
97
|
+
const session = new LocalAiSdkNetworkSandboxSession({
|
|
98
|
+
accountHomes: homes,
|
|
99
|
+
defaultNetworkPolicy: this.options.defaultNetworkPolicy ?? {
|
|
100
|
+
mode: "allow-all",
|
|
101
|
+
},
|
|
102
|
+
env: this.options.env ?? {},
|
|
103
|
+
inheritClaudeConfig: this.options.inheritClaudeConfig ?? false,
|
|
104
|
+
id: sessionId,
|
|
105
|
+
ownsWorkspaceRoot: true,
|
|
106
|
+
ports: this.options.defaultPorts ?? [],
|
|
107
|
+
providerId: this.providerId,
|
|
108
|
+
workspaceRoot,
|
|
109
|
+
});
|
|
110
|
+
this.sessions.set(sessionId, session);
|
|
111
|
+
|
|
112
|
+
if (options.onFirstCreate !== undefined) {
|
|
113
|
+
await options.onFirstCreate(session.restricted(), optionalAbortSignal(options.abortSignal));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return session;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
resumeSession = async (options: {
|
|
120
|
+
sessionId: string;
|
|
121
|
+
abortSignal?: AbortSignal;
|
|
122
|
+
}): Promise<HarnessV1NetworkSandboxSession> => {
|
|
123
|
+
options.abortSignal?.throwIfAborted();
|
|
124
|
+
const existing = this.sessions.get(options.sessionId);
|
|
125
|
+
if (existing !== undefined) return existing;
|
|
126
|
+
if (this.options.rootDirectory === undefined) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
"Local AI SDK sandbox resume requires a provider rootDirectory or an in-memory live session.",
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
const workspaceRoot = resolve(this.options.rootDirectory, options.sessionId);
|
|
132
|
+
const homes = resolveLocalAccountHomes({
|
|
133
|
+
workspaceRoot,
|
|
134
|
+
...(this.options.accountHomes === undefined
|
|
135
|
+
? {}
|
|
136
|
+
: { accountHomes: this.options.accountHomes }),
|
|
137
|
+
});
|
|
138
|
+
const session = new LocalAiSdkNetworkSandboxSession({
|
|
139
|
+
accountHomes: homes,
|
|
140
|
+
defaultNetworkPolicy: this.options.defaultNetworkPolicy ?? {
|
|
141
|
+
mode: "allow-all",
|
|
142
|
+
},
|
|
143
|
+
env: this.options.env ?? {},
|
|
144
|
+
inheritClaudeConfig: this.options.inheritClaudeConfig ?? false,
|
|
145
|
+
id: options.sessionId,
|
|
146
|
+
ownsWorkspaceRoot: true,
|
|
147
|
+
ports: this.options.defaultPorts ?? [],
|
|
148
|
+
providerId: this.providerId,
|
|
149
|
+
workspaceRoot,
|
|
150
|
+
});
|
|
151
|
+
this.sessions.set(options.sessionId, session);
|
|
152
|
+
return session;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
destroySession = async (sessionId: string): Promise<void> => {
|
|
156
|
+
const session = this.sessions.get(sessionId);
|
|
157
|
+
if (session === undefined) return;
|
|
158
|
+
this.sessions.delete(sessionId);
|
|
159
|
+
await session.destroy();
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
destroyAllSessions = async (): Promise<void> => {
|
|
163
|
+
const sessions = [...this.sessions.values()];
|
|
164
|
+
this.sessions.clear();
|
|
165
|
+
await Promise.all(sessions.map((session) => session.destroy()));
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export class LocalAiSdkNetworkSandboxSession implements HarnessV1NetworkSandboxSession {
|
|
170
|
+
readonly id: string;
|
|
171
|
+
readonly defaultWorkingDirectory: string;
|
|
172
|
+
private readonly accountHomes: LocalAiSdkSandboxAccountHomes;
|
|
173
|
+
private readonly env: Readonly<Record<string, string>>;
|
|
174
|
+
private readonly inheritClaudeConfig: boolean;
|
|
175
|
+
private readonly ownsWorkspaceRoot: boolean;
|
|
176
|
+
private readonly processes = new Set<LocalSandboxProcess>();
|
|
177
|
+
private readonly providerId: string;
|
|
178
|
+
private networkPolicy: HarnessV1NetworkPolicy;
|
|
179
|
+
private exposedPorts: ReadonlyArray<number>;
|
|
180
|
+
private stopped = false;
|
|
181
|
+
|
|
182
|
+
constructor(
|
|
183
|
+
input: Readonly<{
|
|
184
|
+
accountHomes: LocalAiSdkSandboxAccountHomes;
|
|
185
|
+
defaultNetworkPolicy: HarnessV1NetworkPolicy;
|
|
186
|
+
env: Readonly<Record<string, string>>;
|
|
187
|
+
id: string;
|
|
188
|
+
inheritClaudeConfig: boolean;
|
|
189
|
+
ownsWorkspaceRoot: boolean;
|
|
190
|
+
ports: ReadonlyArray<number>;
|
|
191
|
+
providerId: string;
|
|
192
|
+
workspaceRoot: string;
|
|
193
|
+
}>,
|
|
194
|
+
) {
|
|
195
|
+
this.accountHomes = input.accountHomes;
|
|
196
|
+
this.defaultWorkingDirectory = input.workspaceRoot;
|
|
197
|
+
this.env = input.env;
|
|
198
|
+
this.exposedPorts = [...input.ports];
|
|
199
|
+
this.id = input.id;
|
|
200
|
+
this.inheritClaudeConfig = input.inheritClaudeConfig;
|
|
201
|
+
this.networkPolicy = cloneNetworkPolicy(input.defaultNetworkPolicy);
|
|
202
|
+
this.ownsWorkspaceRoot = input.ownsWorkspaceRoot;
|
|
203
|
+
this.providerId = input.providerId;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
get description(): string {
|
|
207
|
+
return [
|
|
208
|
+
`OpenAgents local AI SDK sandbox (${this.providerId}:${this.id}).`,
|
|
209
|
+
`Workspace root: ${this.defaultWorkingDirectory}`,
|
|
210
|
+
"Owner-local fixture only; this is not production containment.",
|
|
211
|
+
`CODEX_HOME: ${this.accountHomes.codexHome}`,
|
|
212
|
+
this.inheritClaudeConfig
|
|
213
|
+
? "CLAUDE_CONFIG_DIR: inherited from host"
|
|
214
|
+
: `CLAUDE_CONFIG_DIR: ${this.accountHomes.claudeConfigDir}`,
|
|
215
|
+
].join("\n");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
get ports(): ReadonlyArray<number> {
|
|
219
|
+
return [...this.exposedPorts];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
restricted(): Experimental_SandboxSession {
|
|
223
|
+
const session = this;
|
|
224
|
+
return {
|
|
225
|
+
get description() {
|
|
226
|
+
return session.description;
|
|
227
|
+
},
|
|
228
|
+
readFile: (options) => session.readFile(options),
|
|
229
|
+
readBinaryFile: (options) => session.readBinaryFile(options),
|
|
230
|
+
readTextFile: (options) => session.readTextFile(options),
|
|
231
|
+
writeFile: (options) => session.writeFile(options),
|
|
232
|
+
writeBinaryFile: (options) => session.writeBinaryFile(options),
|
|
233
|
+
writeTextFile: (options) => session.writeTextFile(options),
|
|
234
|
+
spawn: (options) => session.spawn(options),
|
|
235
|
+
run: (options) => session.run(options),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
getPortUrl = async (options: {
|
|
240
|
+
port: number;
|
|
241
|
+
protocol?: "http" | "https" | "ws";
|
|
242
|
+
}): Promise<string> => {
|
|
243
|
+
this.assertRunning();
|
|
244
|
+
if (!this.exposedPorts.includes(options.port) && !this.exposedPorts.includes(0)) {
|
|
245
|
+
throw new Error(`Port ${options.port} is not exposed on local sandbox ${this.id}.`);
|
|
246
|
+
}
|
|
247
|
+
const protocol = options.protocol === "ws" ? "ws" : "http";
|
|
248
|
+
return `${protocol}://127.0.0.1:${options.port}/`;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
setNetworkPolicy = async (policy: HarnessV1NetworkPolicy): Promise<void> => {
|
|
252
|
+
this.assertRunning();
|
|
253
|
+
this.networkPolicy = cloneNetworkPolicy(policy);
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
setPorts = async (
|
|
257
|
+
ports: ReadonlyArray<number>,
|
|
258
|
+
options?: { abortSignal?: AbortSignal },
|
|
259
|
+
): Promise<void> => {
|
|
260
|
+
options?.abortSignal?.throwIfAborted();
|
|
261
|
+
this.assertRunning();
|
|
262
|
+
this.exposedPorts = [...ports];
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
stop = async (): Promise<void> => {
|
|
266
|
+
if (this.stopped) return;
|
|
267
|
+
this.stopped = true;
|
|
268
|
+
await Promise.all([...this.processes].map((process) => process.kill()));
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
destroy = async (): Promise<void> => {
|
|
272
|
+
await this.stop();
|
|
273
|
+
if (this.ownsWorkspaceRoot) {
|
|
274
|
+
await rm(this.defaultWorkingDirectory, { force: true, recursive: true });
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
async readFile(options: {
|
|
279
|
+
path: string;
|
|
280
|
+
abortSignal?: AbortSignal;
|
|
281
|
+
}): Promise<ReadableStream<Uint8Array> | null> {
|
|
282
|
+
const bytes = await this.readBinaryFile(options);
|
|
283
|
+
if (bytes === null) return null;
|
|
284
|
+
return bytesToStream(bytes);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async readBinaryFile(options: {
|
|
288
|
+
path: string;
|
|
289
|
+
abortSignal?: AbortSignal;
|
|
290
|
+
}): Promise<Uint8Array | null> {
|
|
291
|
+
options.abortSignal?.throwIfAborted();
|
|
292
|
+
this.assertRunning();
|
|
293
|
+
const hostPath = this.resolvePath(options.path);
|
|
294
|
+
try {
|
|
295
|
+
return new Uint8Array(await readFile(hostPath));
|
|
296
|
+
} catch (error) {
|
|
297
|
+
if (isNodeFileNotFound(error)) return null;
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async readTextFile(options: {
|
|
303
|
+
path: string;
|
|
304
|
+
encoding?: string;
|
|
305
|
+
startLine?: number;
|
|
306
|
+
endLine?: number;
|
|
307
|
+
abortSignal?: AbortSignal;
|
|
308
|
+
}): Promise<string | null> {
|
|
309
|
+
const bytes = await this.readBinaryFile({
|
|
310
|
+
path: options.path,
|
|
311
|
+
...optionalAbortSignal(options.abortSignal),
|
|
312
|
+
});
|
|
313
|
+
if (bytes === null) return null;
|
|
314
|
+
const text = Buffer.from(bytes).toString((options.encoding ?? "utf-8") as BufferEncoding);
|
|
315
|
+
return extractLines({
|
|
316
|
+
text,
|
|
317
|
+
...(options.startLine === undefined ? {} : { startLine: options.startLine }),
|
|
318
|
+
...(options.endLine === undefined ? {} : { endLine: options.endLine }),
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async writeFile(options: {
|
|
323
|
+
path: string;
|
|
324
|
+
content: ReadableStream<Uint8Array>;
|
|
325
|
+
abortSignal?: AbortSignal;
|
|
326
|
+
}): Promise<void> {
|
|
327
|
+
const content = await collectReadableStream(options.content);
|
|
328
|
+
await this.writeBinaryFile({
|
|
329
|
+
path: options.path,
|
|
330
|
+
content,
|
|
331
|
+
...optionalAbortSignal(options.abortSignal),
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async writeBinaryFile(options: {
|
|
336
|
+
path: string;
|
|
337
|
+
content: Uint8Array;
|
|
338
|
+
abortSignal?: AbortSignal;
|
|
339
|
+
}): Promise<void> {
|
|
340
|
+
options.abortSignal?.throwIfAborted();
|
|
341
|
+
this.assertRunning();
|
|
342
|
+
const hostPath = this.resolvePath(options.path);
|
|
343
|
+
await mkdir(dirname(hostPath), { recursive: true });
|
|
344
|
+
await writeFile(hostPath, options.content);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async writeTextFile(options: {
|
|
348
|
+
path: string;
|
|
349
|
+
content: string;
|
|
350
|
+
encoding?: string;
|
|
351
|
+
abortSignal?: AbortSignal;
|
|
352
|
+
}): Promise<void> {
|
|
353
|
+
await this.writeBinaryFile({
|
|
354
|
+
path: options.path,
|
|
355
|
+
content: new Uint8Array(
|
|
356
|
+
Buffer.from(options.content, (options.encoding ?? "utf-8") as BufferEncoding),
|
|
357
|
+
),
|
|
358
|
+
...optionalAbortSignal(options.abortSignal),
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async spawn(options: {
|
|
363
|
+
command: string;
|
|
364
|
+
workingDirectory?: string;
|
|
365
|
+
env?: Record<string, string>;
|
|
366
|
+
abortSignal?: AbortSignal;
|
|
367
|
+
}): Promise<Experimental_SandboxProcess> {
|
|
368
|
+
options.abortSignal?.throwIfAborted();
|
|
369
|
+
this.assertRunning();
|
|
370
|
+
const child = spawnChild("/bin/bash", ["-lc", options.command], {
|
|
371
|
+
cwd:
|
|
372
|
+
options.workingDirectory === undefined
|
|
373
|
+
? this.defaultWorkingDirectory
|
|
374
|
+
: this.resolvePath(options.workingDirectory),
|
|
375
|
+
detached: true,
|
|
376
|
+
env: this.commandEnv(options.env),
|
|
377
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
378
|
+
});
|
|
379
|
+
const process = new LocalSandboxProcess(child, options.abortSignal);
|
|
380
|
+
this.processes.add(process);
|
|
381
|
+
void process.wait().finally(() => {
|
|
382
|
+
this.processes.delete(process);
|
|
383
|
+
});
|
|
384
|
+
return process;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async run(options: {
|
|
388
|
+
command: string;
|
|
389
|
+
workingDirectory?: string;
|
|
390
|
+
env?: Record<string, string>;
|
|
391
|
+
abortSignal?: AbortSignal;
|
|
392
|
+
}): Promise<{ exitCode: number; stdout: string; stderr: string }> {
|
|
393
|
+
const process = await this.spawn(options);
|
|
394
|
+
const [stdout, stderr, result] = await Promise.all([
|
|
395
|
+
streamToText(process.stdout),
|
|
396
|
+
streamToText(process.stderr),
|
|
397
|
+
process.wait(),
|
|
398
|
+
]);
|
|
399
|
+
return {
|
|
400
|
+
exitCode: result.exitCode,
|
|
401
|
+
stderr,
|
|
402
|
+
stdout,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private commandEnv(env?: Record<string, string>): NodeJS.ProcessEnv {
|
|
407
|
+
const commandEnv: NodeJS.ProcessEnv = {
|
|
408
|
+
...stringProcessEnv(process.env),
|
|
409
|
+
...this.env,
|
|
410
|
+
...(env ?? {}),
|
|
411
|
+
CODEX_HOME: this.accountHomes.codexHome,
|
|
412
|
+
HOME: this.accountHomes.home,
|
|
413
|
+
OPENAGENTS_SANDBOX_NETWORK_POLICY: JSON.stringify(this.networkPolicy),
|
|
414
|
+
};
|
|
415
|
+
if (!this.inheritClaudeConfig) {
|
|
416
|
+
commandEnv.CLAUDE_CONFIG_DIR = this.accountHomes.claudeConfigDir;
|
|
417
|
+
}
|
|
418
|
+
return commandEnv;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
private resolvePath(path: string): string {
|
|
422
|
+
if (path.includes("\0")) {
|
|
423
|
+
throw new Error("Sandbox paths cannot contain NUL bytes.");
|
|
424
|
+
}
|
|
425
|
+
const hostPath = path.startsWith(sep)
|
|
426
|
+
? resolve(path)
|
|
427
|
+
: resolve(this.defaultWorkingDirectory, path);
|
|
428
|
+
if (
|
|
429
|
+
!isPathInside(this.defaultWorkingDirectory, hostPath) &&
|
|
430
|
+
!isPathInside(HARNESS_BOOTSTRAP_DIRECTORY, hostPath)
|
|
431
|
+
) {
|
|
432
|
+
throw new Error(
|
|
433
|
+
`Path ${path} escapes local sandbox workspace ${this.defaultWorkingDirectory} or the reserved harness bootstrap directory.`,
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
return hostPath;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private assertRunning(): void {
|
|
440
|
+
if (this.stopped) {
|
|
441
|
+
throw new Error(`Local sandbox ${this.id} is stopped.`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
class LocalSandboxProcess implements Experimental_SandboxProcess {
|
|
447
|
+
readonly pid?: number;
|
|
448
|
+
readonly stderr: ReadableStream<Uint8Array>;
|
|
449
|
+
readonly stdout: ReadableStream<Uint8Array>;
|
|
450
|
+
private readonly child: ChildProcessByStdio<null, Readable, Readable>;
|
|
451
|
+
private readonly done: Promise<{ exitCode: number }>;
|
|
452
|
+
private killed = false;
|
|
453
|
+
|
|
454
|
+
constructor(child: ChildProcessByStdio<null, Readable, Readable>, abortSignal?: AbortSignal) {
|
|
455
|
+
this.child = child;
|
|
456
|
+
if (child.pid !== undefined) this.pid = child.pid;
|
|
457
|
+
this.stderr = nodeReadableToWeb(child.stderr);
|
|
458
|
+
this.stdout = nodeReadableToWeb(child.stdout);
|
|
459
|
+
this.done = new Promise((resolveDone, rejectDone) => {
|
|
460
|
+
child.once("error", rejectDone);
|
|
461
|
+
child.once("close", (code, signal) => {
|
|
462
|
+
if (abortSignal?.aborted) {
|
|
463
|
+
rejectDone(abortSignal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
resolveDone({ exitCode: code ?? (signal === null ? 0 : 1) });
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
if (abortSignal !== undefined) {
|
|
470
|
+
abortSignal.addEventListener(
|
|
471
|
+
"abort",
|
|
472
|
+
() => {
|
|
473
|
+
void this.kill();
|
|
474
|
+
},
|
|
475
|
+
{ once: true },
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
wait(): Promise<{ exitCode: number }> {
|
|
481
|
+
return this.done;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
async kill(): Promise<void> {
|
|
485
|
+
if (this.killed) return;
|
|
486
|
+
this.killed = true;
|
|
487
|
+
if (this.child.pid !== undefined) {
|
|
488
|
+
try {
|
|
489
|
+
process.kill(-this.child.pid, "SIGTERM");
|
|
490
|
+
} catch {
|
|
491
|
+
this.child.kill("SIGTERM");
|
|
492
|
+
}
|
|
493
|
+
} else {
|
|
494
|
+
this.child.kill("SIGTERM");
|
|
495
|
+
}
|
|
496
|
+
await Promise.race([
|
|
497
|
+
this.done.catch(() => undefined),
|
|
498
|
+
new Promise((resolveTimeout) => setTimeout(resolveTimeout, 500)),
|
|
499
|
+
]);
|
|
500
|
+
if (!this.child.killed && this.child.pid !== undefined) {
|
|
501
|
+
try {
|
|
502
|
+
process.kill(-this.child.pid, "SIGKILL");
|
|
503
|
+
} catch {
|
|
504
|
+
this.child.kill("SIGKILL");
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function stableWorkspaceName(
|
|
511
|
+
input: Readonly<{
|
|
512
|
+
identity?: string;
|
|
513
|
+
sessionId: string;
|
|
514
|
+
}>,
|
|
515
|
+
): string {
|
|
516
|
+
if (input.identity === undefined) return input.sessionId;
|
|
517
|
+
return createHash("sha256")
|
|
518
|
+
.update(`${input.sessionId}:${input.identity}`)
|
|
519
|
+
.digest("hex")
|
|
520
|
+
.slice(0, 32);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function resolveLocalAccountHomes(
|
|
524
|
+
input: Readonly<{
|
|
525
|
+
accountHomes?: Partial<LocalAiSdkSandboxAccountHomes>;
|
|
526
|
+
workspaceRoot: string;
|
|
527
|
+
}>,
|
|
528
|
+
): LocalAiSdkSandboxAccountHomes {
|
|
529
|
+
const openagentsHome = resolve(
|
|
530
|
+
input.accountHomes?.home ?? resolve(input.workspaceRoot, ".openagents-home"),
|
|
531
|
+
);
|
|
532
|
+
return {
|
|
533
|
+
claudeConfigDir: resolve(
|
|
534
|
+
input.accountHomes?.claudeConfigDir ?? resolve(openagentsHome, "claude-code"),
|
|
535
|
+
),
|
|
536
|
+
codexHome: resolve(input.accountHomes?.codexHome ?? resolve(openagentsHome, "codex")),
|
|
537
|
+
home: openagentsHome,
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function cloneNetworkPolicy(policy: HarnessV1NetworkPolicy): HarnessV1NetworkPolicy {
|
|
542
|
+
switch (policy.mode) {
|
|
543
|
+
case "allow-all":
|
|
544
|
+
return { mode: "allow-all" };
|
|
545
|
+
case "deny-all":
|
|
546
|
+
return { mode: "deny-all" };
|
|
547
|
+
case "custom":
|
|
548
|
+
return {
|
|
549
|
+
mode: "custom",
|
|
550
|
+
...(policy.allowedHosts === undefined ? {} : { allowedHosts: [...policy.allowedHosts] }),
|
|
551
|
+
...(policy.allowedCIDRs === undefined ? {} : { allowedCIDRs: [...policy.allowedCIDRs] }),
|
|
552
|
+
...(policy.deniedCIDRs === undefined ? {} : { deniedCIDRs: [...policy.deniedCIDRs] }),
|
|
553
|
+
} as HarnessV1NetworkPolicy;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function isPathInside(root: string, candidate: string): boolean {
|
|
558
|
+
const resolvedRoot = resolve(root);
|
|
559
|
+
const resolvedCandidate = resolve(candidate);
|
|
560
|
+
return (
|
|
561
|
+
resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${sep}`)
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function optionalAbortSignal(abortSignal: AbortSignal | undefined): { abortSignal?: AbortSignal } {
|
|
566
|
+
return abortSignal === undefined ? {} : { abortSignal };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function stringProcessEnv(env: NodeJS.ProcessEnv): Record<string, string> {
|
|
570
|
+
const result: Record<string, string> = {};
|
|
571
|
+
for (const [key, value] of Object.entries(env)) {
|
|
572
|
+
if (value !== undefined) result[key] = value;
|
|
573
|
+
}
|
|
574
|
+
return result;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function isNodeFileNotFound(error: unknown): boolean {
|
|
578
|
+
return (
|
|
579
|
+
typeof error === "object" &&
|
|
580
|
+
error !== null &&
|
|
581
|
+
"code" in error &&
|
|
582
|
+
(error as { code?: unknown }).code === "ENOENT"
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {
|
|
587
|
+
return new ReadableStream<Uint8Array>({
|
|
588
|
+
start(controller) {
|
|
589
|
+
controller.enqueue(bytes);
|
|
590
|
+
controller.close();
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
async function collectReadableStream(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
|
|
596
|
+
const reader = stream.getReader();
|
|
597
|
+
const chunks: Uint8Array[] = [];
|
|
598
|
+
let byteLength = 0;
|
|
599
|
+
while (true) {
|
|
600
|
+
const next = await reader.read();
|
|
601
|
+
if (next.done) break;
|
|
602
|
+
chunks.push(next.value);
|
|
603
|
+
byteLength += next.value.byteLength;
|
|
604
|
+
}
|
|
605
|
+
const result = new Uint8Array(byteLength);
|
|
606
|
+
let offset = 0;
|
|
607
|
+
for (const chunk of chunks) {
|
|
608
|
+
result.set(chunk, offset);
|
|
609
|
+
offset += chunk.byteLength;
|
|
610
|
+
}
|
|
611
|
+
return result;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function nodeReadableToWeb(stream: NodeJS.ReadableStream): ReadableStream<Uint8Array> {
|
|
615
|
+
return new ReadableStream<Uint8Array>({
|
|
616
|
+
start(controller) {
|
|
617
|
+
stream.on("data", (chunk: Buffer | Uint8Array | string) => {
|
|
618
|
+
controller.enqueue(toBytes(chunk));
|
|
619
|
+
});
|
|
620
|
+
stream.once("end", () => controller.close());
|
|
621
|
+
stream.once("error", (error) => controller.error(error));
|
|
622
|
+
},
|
|
623
|
+
cancel() {
|
|
624
|
+
if ("destroy" in stream && typeof stream.destroy === "function") {
|
|
625
|
+
stream.destroy();
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
async function streamToText(stream: ReadableStream<Uint8Array>): Promise<string> {
|
|
632
|
+
const bytes = await collectReadableStream(stream);
|
|
633
|
+
return Buffer.from(bytes).toString("utf-8");
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function toBytes(chunk: Buffer | Uint8Array | string): Uint8Array {
|
|
637
|
+
if (typeof chunk === "string") return new TextEncoder().encode(chunk);
|
|
638
|
+
return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export const localAiSdkSandboxProviderModuleUrl = fileURLToPath(import.meta.url);
|