@agentsh/secure-sandbox 0.1.1 → 0.1.3
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 +191 -0
- package/README.md +1 -1
- package/dist/adapters/blaxel.d.ts +1 -1
- package/dist/adapters/cloudflare.d.ts +1 -1
- package/dist/adapters/daytona.d.ts +1 -1
- package/dist/adapters/e2b.d.ts +1 -1
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/vercel.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +9 -6
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/{types-BwEbraFo.d.ts → types-Cz86hRBQ.d.ts} +15 -2
- package/package.json +2 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding any notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
Copyright 2026 Canyon Road Technologies Inc.
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -38,7 +38,7 @@ const raw = await Sandbox.create({ runtime: 'node24' });
|
|
|
38
38
|
const sandbox = await secureSandbox(adapters.vercel(raw));
|
|
39
39
|
|
|
40
40
|
const { text } = await generateText({
|
|
41
|
-
model: anthropic('claude-sonnet-4-
|
|
41
|
+
model: anthropic('claude-sonnet-4-6'),
|
|
42
42
|
tools: {
|
|
43
43
|
shell: tool({
|
|
44
44
|
description: 'Run a shell command in the sandbox',
|
package/dist/adapters/e2b.d.ts
CHANGED
package/dist/adapters/index.d.ts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as SandboxAdapter, a as SecureConfig, b as SecuredSandbox, T as ThreatFeedsConfig } from './types-
|
|
2
|
-
export { E as ExecResult, I as InstallStrategy, R as ReadFileResult, c as SecurityMode, d as ThreatFeed, W as WriteFileResult } from './types-
|
|
1
|
+
import { S as SandboxAdapter, a as SecureConfig, b as SecuredSandbox, T as ThreatFeedsConfig } from './types-Cz86hRBQ.js';
|
|
2
|
+
export { E as ExecResult, I as InstallStrategy, R as ReadFileResult, c as SecurityMode, d as ThreatFeed, W as WriteFileResult } from './types-Cz86hRBQ.js';
|
|
3
3
|
export { P as PolicyDefinition, i as policies } from './index-D0UvBOzr.js';
|
|
4
4
|
import { ZodIssue } from 'zod';
|
|
5
5
|
export { i as adapters } from './index-aQ1TVPtG.js';
|
package/dist/index.js
CHANGED
|
@@ -204,17 +204,20 @@ async function provision(adapter, config = {}) {
|
|
|
204
204
|
const policy = rawPolicy ? validatePolicy(rawPolicy) : agentDefault();
|
|
205
205
|
let securityMode = "full";
|
|
206
206
|
if (installStrategy === "running") {
|
|
207
|
-
|
|
207
|
+
await healthCheck(adapter);
|
|
208
|
+
securityMode = config.securityMode ?? "full";
|
|
208
209
|
if (minimumSecurityMode && isWeakerThan(securityMode, minimumSecurityMode)) {
|
|
209
210
|
throw new ProvisioningError({
|
|
210
211
|
phase: "install",
|
|
211
|
-
command: "
|
|
212
|
-
stderr: `
|
|
212
|
+
command: "securityMode check",
|
|
213
|
+
stderr: `Security mode '${securityMode}' is weaker than required '${minimumSecurityMode}'`
|
|
213
214
|
});
|
|
214
215
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
216
|
+
let sessionId2 = config.sessionId;
|
|
217
|
+
if (!sessionId2) {
|
|
218
|
+
const envResult = await adapter.exec("sh", ["-c", "echo $AGENTSH_SESSION_ID"]);
|
|
219
|
+
sessionId2 = envResult.stdout.trim();
|
|
220
|
+
}
|
|
218
221
|
if (!sessionId2) {
|
|
219
222
|
throw new ProvisioningError({
|
|
220
223
|
phase: "session",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/integrity.ts","../src/core/config.ts","../src/core/traceparent.ts","../src/core/provision.ts","../src/core/runtime.ts","../src/api.ts"],"sourcesContent":["import { IntegrityError } from './errors.js';\n\nexport const PINNED_VERSION = '0.15.0';\n\nexport const CHECKSUMS: Record<string, Record<string, string>> = {\n '0.15.0': {\n linux_amd64:\n '89f7ebbfd75ffd961245ec62b2602fd0cc387740502ac858dbc39c367c5699c5',\n linux_arm64:\n '3fabbd749f9e98fb9f96ddfc94c389a6868cda7ed3668daa8440c39ceec85f3b',\n },\n '0.14.0': {\n linux_amd64:\n '2ab8ba0d6637fe1a5badf840c3db197161a6f9865d721ed216029d229b1b9bbc',\n linux_arm64:\n '929d18dd9fe36e9b2fa830d7ae64b4fb481853e743ade8674fcfcdc73470ed53',\n },\n};\n\n/**\n * Returns the checksum to verify against.\n * If `override` is provided, returns it directly.\n * Otherwise looks up the checksum in the pinned CHECKSUMS map.\n * Throws IntegrityError if no checksum is found.\n */\nexport function getChecksum(\n version: string,\n arch: string,\n override?: string,\n): string {\n if (override) {\n return override;\n }\n\n const versionChecksums = CHECKSUMS[version];\n if (versionChecksums && versionChecksums[arch]) {\n return versionChecksums[arch];\n }\n\n throw new IntegrityError({\n expected: '',\n actual: '',\n message: `No pinned checksum for agentsh v${version}. Provide \\`agentshChecksum\\` explicitly or use \\`skipIntegrityCheck: true\\`.`,\n });\n}\n\n/**\n * Returns an array of shell commands to try for computing SHA-256 checksums.\n * Each command extracts just the hex hash value from the given file.\n */\nexport function buildVerifyCommand(filePath: string): string[] {\n return [\n `sha256sum \"${filePath}\" | awk '{print $1}'`,\n `shasum -a 256 \"${filePath}\" | awk '{print $1}'`,\n `openssl dgst -sha256 \"${filePath}\" | awk '{print $NF}'`,\n ];\n}\n\n/**\n * Returns the download URL for the agentsh binary.\n * If `overrideUrl` is provided, returns it directly.\n * Otherwise returns the default GitHub releases URL.\n */\nexport function binaryUrl(\n version: string,\n arch: string,\n overrideUrl?: string,\n): string {\n if (overrideUrl) {\n return overrideUrl;\n }\n\n return `https://github.com/canyonroad/agentsh/releases/download/v${version}/agentsh_${version}_${arch}.tar.gz`;\n}\n","import yaml from 'js-yaml';\nimport type { ThreatFeedsConfig } from './types.js';\n\nexport interface ServerConfigOpts {\n workspace: string;\n watchtower?: string;\n enforceRedirects?: boolean;\n realPaths?: boolean;\n threatFeeds?: false | ThreatFeedsConfig;\n}\n\n/**\n * Default threat feeds: URLhaus (malware) + Phishing.Database (phishing).\n * Both are free, open source, and updated frequently.\n */\nexport const defaultThreatFeeds: ThreatFeedsConfig = {\n action: 'deny',\n feeds: [\n {\n name: 'urlhaus',\n url: 'https://urlhaus.abuse.ch/downloads/hostfile/',\n format: 'hostfile',\n refreshInterval: '6h',\n },\n {\n name: 'phishing',\n url: 'https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-domains-ACTIVE.txt',\n format: 'domain-list',\n refreshInterval: '12h',\n },\n ],\n allowlist: [\n 'github.com',\n '*.github.com',\n 'registry.npmjs.org',\n 'registry.yarnpkg.com',\n 'pypi.org',\n 'files.pythonhosted.org',\n 'crates.io',\n 'static.crates.io',\n 'index.crates.io',\n 'proxy.golang.org',\n 'sum.golang.org',\n ],\n};\n\nexport function generateServerConfig(opts: ServerConfigOpts): string {\n const config: Record<string, unknown> = {\n server: {\n http: {\n addr: '127.0.0.1:18080',\n },\n },\n auth: {\n type: 'none',\n },\n policies: {\n system_dir: '/etc/agentsh/system',\n dir: '/etc/agentsh',\n default: 'policy',\n },\n workspace: opts.workspace,\n sandbox: {\n enabled: true,\n allow_degraded: true,\n },\n };\n if (opts.watchtower) config.watchtower = opts.watchtower;\n if (opts.enforceRedirects) config.enforce_redirects = true;\n if (opts.realPaths) config.real_paths = true;\n\n // Threat feeds: enabled by default, opt-out with `threatFeeds: false`\n const feeds = opts.threatFeeds === false ? undefined : (opts.threatFeeds ?? defaultThreatFeeds);\n if (feeds) {\n config.threat_feeds = {\n enabled: true,\n action: feeds.action ?? 'deny',\n feeds: feeds.feeds.map(f => ({\n name: f.name,\n url: f.url,\n format: f.format,\n refresh_interval: f.refreshInterval ?? '6h',\n })),\n ...(feeds.allowlist?.length ? { allowlist: feeds.allowlist } : {}),\n };\n }\n\n return yaml.dump(config, { lineWidth: -1 });\n}\n","/**\n * Read W3C traceparent from the active OpenTelemetry span, if available.\n *\n * Uses dynamic import so @opentelemetry/api is an optional peer dependency.\n * Returns undefined when OTEL is not installed, no span is active, or the\n * trace context is invalid (all-zero trace ID).\n */\nexport async function getTraceparent(): Promise<string | undefined> {\n try {\n const { trace } = await import('@opentelemetry/api');\n const span = trace.getActiveSpan();\n const ctx = span?.spanContext();\n if (!ctx?.traceId || ctx.traceId === '00000000000000000000000000000000') {\n return undefined;\n }\n const flags = (ctx.traceFlags ?? 0).toString(16).padStart(2, '0');\n return `00-${ctx.traceId}-${ctx.spanId}-${flags}`;\n } catch {\n return undefined;\n }\n}\n","import type {\n SandboxAdapter,\n SecureConfig,\n SecurityMode,\n ExecResult,\n} from './types.js';\nimport {\n getChecksum,\n buildVerifyCommand,\n binaryUrl,\n PINNED_VERSION,\n} from './integrity.js';\nimport { generateServerConfig } from './config.js';\nimport { ProvisioningError, IntegrityError } from './errors.js';\nimport { serializePolicy, systemPolicyYaml } from '../policies/serialize.js';\nimport { agentDefault } from '../policies/presets.js';\nimport { validatePolicy } from '../policies/schema.js';\nimport { getTraceparent } from './traceparent.js';\n\n// ─── Security mode ordering (strongest to weakest) ────────────\n\nconst SECURITY_MODE_RANK: Record<SecurityMode, number> = {\n full: 4,\n landlock: 3,\n 'landlock-only': 2,\n minimal: 1,\n};\n\nfunction isWeakerThan(detected: SecurityMode, required: SecurityMode): boolean {\n return SECURITY_MODE_RANK[detected] < SECURITY_MODE_RANK[required];\n}\n\n// ─── Architecture mapping ─────────────────────────────────────\n\nfunction mapArch(uname: string): 'linux_amd64' | 'linux_arm64' {\n const trimmed = uname.trim();\n if (trimmed === 'x86_64') return 'linux_amd64';\n if (trimmed === 'aarch64') return 'linux_arm64';\n throw new ProvisioningError({\n phase: 'install',\n command: 'uname -m',\n stderr: `Unsupported architecture: ${trimmed}`,\n });\n}\n\n// ─── Helper: check if binary exists ───────────────────────────\n\nconst AGENTSH_PATHS = ['/usr/local/bin/agentsh', '/usr/bin/agentsh'];\n\nasync function binaryExists(adapter: SandboxAdapter): Promise<boolean> {\n for (const path of AGENTSH_PATHS) {\n const found = adapter.fileExists\n ? await adapter.fileExists(path)\n : (await adapter.exec('test', ['-f', path])).exitCode === 0;\n if (found) return true;\n }\n return false;\n}\n\n// ─── Helper: sleep ────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// ─── Main provisioning function ───────────────────────────────\n\nexport interface ProvisionResult {\n sessionId: string;\n securityMode: SecurityMode;\n /** When true, the shell shim enforces policy — skip agentsh exec wrapper. */\n passthrough?: boolean;\n}\n\nexport async function provision(\n adapter: SandboxAdapter,\n config: SecureConfig = {},\n): Promise<ProvisionResult> {\n const {\n policy: rawPolicy,\n workspace = '/workspace',\n watchtower,\n installStrategy = 'download',\n agentshVersion = PINNED_VERSION,\n agentshArch: archOverride,\n agentshBinaryUrl,\n agentshChecksum,\n skipIntegrityCheck = false,\n minimumSecurityMode,\n realPaths: realPathsOverride,\n enforceRedirects = false,\n traceParent,\n policyName = 'policy',\n threatFeeds,\n } = config;\n\n // Resolve and validate policy\n const policy = rawPolicy ? validatePolicy(rawPolicy) : agentDefault();\n\n let securityMode: SecurityMode = 'full';\n\n if (installStrategy === 'running') {\n // agentsh is already fully provisioned and running with the shell shim\n // installed. Commands go through the shim automatically, so we don't\n // create a new session (which would deadlock the server via nested\n // agentsh connections). Instead, read the existing session ID from\n // the environment and use passthrough mode at runtime.\n securityMode = await detectSecurityMode(adapter);\n\n if (minimumSecurityMode && isWeakerThan(securityMode, minimumSecurityMode)) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: `Detected security mode '${securityMode}' is weaker than required '${minimumSecurityMode}'`,\n });\n }\n\n await healthCheck(adapter);\n\n // Read the existing session ID from the environment\n const envResult = await adapter.exec('sh', ['-c', 'echo $AGENTSH_SESSION_ID']);\n const sessionId = envResult.stdout.trim();\n if (!sessionId) {\n throw new ProvisioningError({\n phase: 'session',\n command: 'echo $AGENTSH_SESSION_ID',\n stderr: 'AGENTSH_SESSION_ID not set — running strategy requires a pre-created session',\n });\n }\n\n return { sessionId, securityMode, passthrough: true };\n }\n\n // ─── Phase 1: Binary Installation ───────────────────────────\n\n // Step 1: Check if binary exists\n const exists = await binaryExists(adapter);\n\n if (installStrategy === 'preinstalled') {\n if (!exists) {\n throw new ProvisioningError({\n phase: 'install',\n command: AGENTSH_PATHS.map(p => `test -f ${p}`).join(' || '),\n stderr: 'Binary not found but installStrategy is preinstalled',\n });\n }\n // Binary exists and strategy is preinstalled, skip to detect\n } else if (installStrategy === 'download' || installStrategy === 'upload') {\n // If binary already exists, skip installation but still detect\n if (!exists) {\n // Step 2: Detect architecture\n const arch =\n archOverride ?? await detectArch(adapter);\n\n if (installStrategy === 'download') {\n // Step 3a: Download\n await downloadBinary(adapter, agentshVersion, arch, agentshBinaryUrl);\n } else {\n // Step 3b: Upload\n await uploadBinary(adapter, agentshVersion, arch, agentshBinaryUrl);\n }\n\n // Step 4: Verify checksum\n if (!skipIntegrityCheck) {\n await verifyChecksum(\n adapter,\n agentshVersion,\n arch,\n agentshChecksum,\n '/tmp/agentsh.tar.gz',\n );\n }\n\n // Step 5: Install binaries (agentsh + agentsh-shell-shim + agentsh-unixwrap)\n const binaries = [\n { src: '/tmp/agentsh', dest: '/usr/local/bin/agentsh' },\n { src: '/tmp/agentsh-shell-shim', dest: '/usr/bin/agentsh-shell-shim' },\n { src: '/tmp/agentsh-unixwrap', dest: '/usr/local/bin/agentsh-unixwrap' },\n ];\n for (const { src, dest } of binaries) {\n const installResult = await adapter.exec(\n 'install',\n ['-m', '0755', src, dest],\n { sudo: true },\n );\n if (installResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: `install -m 0755 ${src} ${dest}`,\n stderr: installResult.stderr,\n });\n }\n }\n }\n }\n\n // Step 5b: Detect security mode\n securityMode = await detectSecurityMode(adapter);\n\n // Check minimum security mode\n if (minimumSecurityMode && isWeakerThan(securityMode, minimumSecurityMode)) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --json',\n stderr: `Detected security mode '${securityMode}' is weaker than required '${minimumSecurityMode}'`,\n });\n }\n\n // Auto-enable realPaths when FUSE is available (full or landlock modes),\n // unless the user explicitly set it.\n const hasFuse = securityMode === 'full' || securityMode === 'landlock';\n const realPaths = realPathsOverride ?? hasFuse;\n\n // Step 6: Install shell shim\n const shimResult = await adapter.exec(\n 'agentsh',\n [\n 'shim', 'install-shell',\n '--root', '/',\n '--shim', '/usr/bin/agentsh-shell-shim',\n '--bash',\n '--i-understand-this-modifies-the-host',\n ],\n { sudo: true },\n );\n if (shimResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh shim install-shell',\n stderr: shimResult.stderr,\n });\n }\n\n // ─── Phase 2: Policy & Config ───────────────────────────────\n\n // Step 7: Create dirs and make writable for file writes\n const mkdirResult = await adapter.exec(\n 'mkdir',\n ['-p', '/etc/agentsh/system'],\n { sudo: true },\n );\n if (mkdirResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'mkdir -p /etc/agentsh/system',\n stderr: mkdirResult.stderr,\n });\n }\n\n // Temporarily make writable so adapter.writeFile (which may not support sudo) can write\n await adapter.exec('chmod', ['-R', '777', '/etc/agentsh/'], { sudo: true });\n\n await adapter.writeFile(\n '/etc/agentsh/system/policy.yml',\n systemPolicyYaml(),\n { sudo: true },\n );\n\n // Step 8: Write user policy\n await adapter.writeFile(\n '/etc/agentsh/policy.yml',\n serializePolicy(policy),\n { sudo: true },\n );\n\n // Step 9: Write server config\n const serverConfig = generateServerConfig({\n workspace,\n watchtower,\n enforceRedirects,\n realPaths,\n threatFeeds,\n });\n\n await adapter.writeFile('/etc/agentsh/config.yml', serverConfig, {\n sudo: true,\n });\n\n // Step 10: Set permissions\n const chmodDirResult = await adapter.exec(\n 'find',\n ['/etc/agentsh', '-type', 'd', '-exec', 'chmod', '555', '{}', '+'],\n { sudo: true },\n );\n if (chmodDirResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'find /etc/agentsh -type d -exec chmod 555 {} +',\n stderr: chmodDirResult.stderr,\n });\n }\n\n const chmodFileResult = await adapter.exec(\n 'find',\n ['/etc/agentsh', '-type', 'f', '-exec', 'chmod', '444', '{}', '+'],\n { sudo: true },\n );\n if (chmodFileResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'find /etc/agentsh -type f -exec chmod 444 {} +',\n stderr: chmodFileResult.stderr,\n });\n }\n\n const chownResult = await adapter.exec(\n 'chown',\n ['-R', 'root:root', '/etc/agentsh/'],\n { sudo: true },\n );\n if (chownResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'chown -R root:root /etc/agentsh/',\n stderr: chownResult.stderr,\n });\n }\n\n // ─── Phase 3: Server Startup ────────────────────────────────\n\n // Step 10b: Ensure workspace directory exists\n await adapter.exec('mkdir', ['-p', workspace], { sudo: true });\n\n // Step 11: Start server\n const serverResult = await adapter.exec(\n 'agentsh',\n ['server', '--config', '/etc/agentsh/config.yml'],\n { detached: true, sudo: true },\n );\n if (serverResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'startup',\n command: 'agentsh server --config /etc/agentsh/config.yml',\n stderr: serverResult.stderr,\n });\n }\n\n // Step 12: Health check\n await healthCheck(adapter);\n\n // Step 13: Create session\n const sessionResult = await adapter.exec('agentsh', [\n 'session',\n 'create',\n '--workspace',\n workspace,\n '--policy',\n 'policy',\n ]);\n if (sessionResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'session',\n command: 'agentsh session create',\n stderr: sessionResult.stderr,\n });\n }\n\n let sessionId: string;\n try {\n const sessionData = JSON.parse(sessionResult.stdout);\n sessionId = sessionData.session_id;\n } catch {\n // Fallback: parse text output like \"Session session-xxx started\"\n const match = sessionResult.stdout.match(/Session\\s+(session-[^\\s]+)/);\n if (match) {\n sessionId = match[1];\n } else {\n throw new ProvisioningError({\n phase: 'session',\n command: 'agentsh session create',\n stderr: `Failed to parse session output: ${sessionResult.stdout}`,\n });\n }\n }\n\n // Step 13b: Set trace context if traceParent is provided or OTEL span is active\n const effectiveTraceParent = traceParent ?? (await getTraceparent());\n if (effectiveTraceParent) {\n await adapter.exec('curl', [\n '-X',\n 'PUT',\n `http://127.0.0.1:18080/sessions/${sessionId}/trace-context`,\n '-H',\n 'Content-Type: application/json',\n '-d',\n JSON.stringify({ traceparent: effectiveTraceParent }),\n ]);\n }\n\n // ─── Phase 4: Handoff ───────────────────────────────────────\n\n // Step 14: Return result\n return { sessionId, securityMode };\n}\n\n// ─── Phase 1 helpers ──────────────────────────────────────────\n\nasync function detectArch(\n adapter: SandboxAdapter,\n): Promise<'linux_amd64' | 'linux_arm64'> {\n const result = await adapter.exec('uname', ['-m']);\n if (result.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'uname -m',\n stderr: result.stderr,\n });\n }\n return mapArch(result.stdout);\n}\n\nasync function downloadBinary(\n adapter: SandboxAdapter,\n version: string,\n arch: string,\n overrideUrl?: string,\n): Promise<void> {\n const url = binaryUrl(version, arch, overrideUrl);\n\n // Try curl first\n const curlResult = await adapter.exec('curl', [\n '-fsSL',\n url,\n '-o',\n '/tmp/agentsh.tar.gz',\n ]);\n\n if (curlResult.exitCode !== 0) {\n // Fallback to wget (may not be available on all platforms)\n let wgetResult: ExecResult;\n try {\n wgetResult = await adapter.exec('wget', [\n '-q',\n url,\n '-O',\n '/tmp/agentsh.tar.gz',\n ]);\n } catch {\n throw new ProvisioningError({\n phase: 'install',\n command: `curl -fsSL ${url} -o /tmp/agentsh.tar.gz`,\n stderr: curlResult.stderr || 'Download failed (curl failed, wget not available)',\n });\n }\n if (wgetResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: `wget -q ${url} -O /tmp/agentsh.tar.gz`,\n stderr: wgetResult.stderr,\n });\n }\n }\n\n // Extract\n const tarResult = await adapter.exec('tar', [\n 'xz',\n '-C',\n '/tmp/',\n '-f',\n '/tmp/agentsh.tar.gz',\n ]);\n if (tarResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'tar xz -C /tmp/ -f /tmp/agentsh.tar.gz',\n stderr: tarResult.stderr,\n });\n }\n}\n\nasync function uploadBinary(\n adapter: SandboxAdapter,\n version: string,\n arch: string,\n overrideUrl?: string,\n): Promise<void> {\n const url = binaryUrl(version, arch, overrideUrl);\n\n // Download on host side using fetch (Node 18+)\n const response = await fetch(url);\n if (!response.ok) {\n throw new ProvisioningError({\n phase: 'install',\n command: `fetch ${url}`,\n stderr: `HTTP ${response.status}: ${response.statusText}`,\n });\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n\n // Upload tarball to sandbox and extract\n await adapter.writeFile('/tmp/agentsh.tar.gz', buffer);\n const tarResult = await adapter.exec('tar', [\n 'xz',\n '-C',\n '/tmp/',\n '-f',\n '/tmp/agentsh.tar.gz',\n ]);\n if (tarResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'tar xz -C /tmp/ -f /tmp/agentsh.tar.gz',\n stderr: tarResult.stderr,\n });\n }\n}\n\nasync function verifyChecksum(\n adapter: SandboxAdapter,\n version: string,\n arch: string,\n checksumOverride: string | undefined,\n filePath: string,\n): Promise<void> {\n const expected = getChecksum(version, arch, checksumOverride);\n const commands = buildVerifyCommand(filePath);\n\n let actual: string | undefined;\n\n for (const cmd of commands) {\n const result = await adapter.exec('sh', ['-c', cmd]);\n if (result.exitCode === 0 && result.stdout.trim()) {\n actual = result.stdout.trim();\n break;\n }\n }\n\n if (actual === undefined) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'sha256sum / shasum / openssl',\n stderr: 'No checksum tool available in sandbox',\n });\n }\n\n if (actual !== expected) {\n throw new IntegrityError({\n expected,\n actual,\n message: `Checksum mismatch: expected ${expected}, got ${actual}`,\n });\n }\n}\n\nasync function detectSecurityMode(\n adapter: SandboxAdapter,\n): Promise<SecurityMode> {\n const result = await adapter.exec('agentsh', ['detect', '--output', 'json']);\n if (result.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: result.stderr,\n });\n }\n\n // agentsh detect outputs JSON to stderr\n const jsonOutput = result.stderr || result.stdout;\n let parsed: { security_mode: string };\n try {\n parsed = JSON.parse(jsonOutput);\n } catch {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: `Failed to parse detect JSON: ${jsonOutput.slice(0, 200)}`,\n });\n }\n\n const mode = parsed.security_mode;\n const validModes: SecurityMode[] = ['full', 'landlock', 'landlock-only', 'minimal'];\n if (!validModes.includes(mode as SecurityMode)) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: `Unknown security mode: '${mode}'`,\n });\n }\n return mode as SecurityMode;\n}\n\nasync function healthCheck(adapter: SandboxAdapter): Promise<void> {\n const maxRetries = 10;\n const delayMs = 500;\n\n for (let i = 0; i < maxRetries; i++) {\n const result = await adapter.exec('curl', [\n '-sf',\n 'http://127.0.0.1:18080/health',\n ]);\n if (result.exitCode === 0) {\n return;\n }\n if (i < maxRetries - 1) {\n await sleep(delayMs);\n }\n }\n\n throw new ProvisioningError({\n phase: 'startup',\n command: 'curl http://127.0.0.1:18080/health',\n stderr: 'Health check failed after 10 attempts',\n });\n}\n","import type {\n SandboxAdapter,\n SecuredSandbox,\n SecurityMode,\n ExecResult,\n} from './types.js';\nimport { RuntimeError } from './errors.js';\nimport { getTraceparent } from './traceparent.js';\n\n/** Build env object with TRACEPARENT if an OTEL span is active. */\nasync function traceEnv(): Promise<Record<string, string> | undefined> {\n const tp = await getTraceparent();\n return tp ? { TRACEPARENT: tp } : undefined;\n}\n\n/** Parse the JSON envelope from `agentsh exec --output json`. */\nfunction parseExecJson(raw: ExecResult): ExecResult {\n try {\n const json = JSON.parse(raw.stdout);\n const result = json.result ?? {};\n return {\n exitCode: result.exit_code ?? raw.exitCode,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? result.error?.message ?? '',\n };\n } catch {\n // If not valid JSON, return as-is (e.g. mock adapters)\n return raw;\n }\n}\n\nexport function createSecuredSandbox(\n adapter: SandboxAdapter,\n sessionId: string,\n securityMode: SecurityMode,\n options?: { passthrough?: boolean },\n): SecuredSandbox {\n if (options?.passthrough) {\n return createPassthroughSandbox(adapter, sessionId, securityMode);\n }\n return createAgentshSandbox(adapter, sessionId, securityMode);\n}\n\n/**\n * Passthrough mode: the shell shim enforces policy on every command,\n * so we run commands directly through the adapter without wrapping\n * them in `agentsh exec`. Used with the 'running' install strategy.\n */\nfunction createPassthroughSandbox(\n adapter: SandboxAdapter,\n sessionId: string,\n securityMode: SecurityMode,\n): SecuredSandbox {\n return {\n sessionId,\n securityMode,\n\n async exec(command, opts) {\n const result = await adapter.exec('bash', ['-c', command], {\n cwd: opts?.cwd,\n });\n return result;\n },\n\n async writeFile(path, content) {\n const b64 = Buffer.from(content, 'utf-8').toString('base64');\n const result = await adapter.exec('sh', [\n '-c',\n 'printf \"%s\" \"$1\" | base64 -d > \"$2\"',\n '_',\n b64,\n path,\n ]);\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'writeFile failed',\n };\n }\n return { success: true as const, path };\n },\n\n async readFile(path) {\n const result = await adapter.exec('cat', [path]);\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'readFile failed',\n };\n }\n return { success: true as const, path, content: result.stdout };\n },\n\n async stop() {\n await adapter.stop?.();\n },\n };\n}\n\n/** Standard mode: wraps commands in `agentsh exec` for policy enforcement. */\nfunction createAgentshSandbox(\n adapter: SandboxAdapter,\n sessionId: string,\n securityMode: SecurityMode,\n): SecuredSandbox {\n return {\n sessionId,\n securityMode,\n\n async exec(command, opts) {\n const args = [\n 'exec',\n '--output',\n 'json',\n sessionId,\n '--',\n 'bash',\n '-c',\n command,\n ];\n const env = await traceEnv();\n const execOpts = { cwd: opts?.cwd, env };\n const result = await adapter.exec('agentsh', args, execOpts);\n if (isTransportFailure(result)) {\n throw new RuntimeError({\n sessionId,\n command,\n stderr: result.stderr,\n });\n }\n return parseExecJson(result);\n },\n\n async writeFile(path, content) {\n const b64 = Buffer.from(content, 'utf-8').toString('base64');\n const args = [\n 'exec',\n sessionId,\n '--',\n 'sh',\n '-c',\n 'printf \"%s\" \"$1\" | base64 -d > \"$2\"',\n '_',\n b64,\n path,\n ];\n const env = await traceEnv();\n const result = await adapter.exec('agentsh', args, { env });\n if (isTransportFailure(result)) {\n throw new RuntimeError({\n sessionId,\n command: `writeFile ${path}`,\n stderr: result.stderr,\n });\n }\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'writeFile failed',\n };\n }\n return { success: true as const, path };\n },\n\n async readFile(path) {\n const args = ['exec', sessionId, '--', 'cat', path];\n const env = await traceEnv();\n const result = await adapter.exec('agentsh', args, { env });\n if (isTransportFailure(result)) {\n throw new RuntimeError({\n sessionId,\n command: `readFile ${path}`,\n stderr: result.stderr,\n });\n }\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'readFile failed',\n };\n }\n return { success: true as const, path, content: result.stdout };\n },\n\n async stop() {\n await adapter.stop?.();\n },\n };\n}\n\nfunction isTransportFailure(result: ExecResult): boolean {\n return result.exitCode === 127 && result.stderr.includes('agentsh');\n}\n","import type {\n SandboxAdapter,\n SecuredSandbox,\n SecureConfig,\n} from './core/types.js';\nimport { provision } from './core/provision.js';\nimport { createSecuredSandbox } from './core/runtime.js';\n\nexport async function secureSandbox(\n adapter: SandboxAdapter,\n config?: SecureConfig,\n): Promise<SecuredSandbox> {\n const resolvedConfig = config ?? {};\n const { sessionId, securityMode, passthrough } = await provision(adapter, {\n workspace: '/workspace',\n ...resolvedConfig,\n });\n return createSecuredSandbox(adapter, sessionId, securityMode, { passthrough });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,IAAM,iBAAiB;AAEvB,IAAM,YAAoD;AAAA,EAC/D,UAAU;AAAA,IACR,aACE;AAAA,IACF,aACE;AA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I,MAAM,UAAU,SAAS;AAAA,IACxE,WAAW;AAAA,IACX,GAAG;AAAA,EACL,CAAC;AACD,SAAO,qBAAqB,SAAS,WAAW,cAAc,EAAE,YAAY,CAAC;AAC/E;","names":["sessionId"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/integrity.ts","../src/core/config.ts","../src/core/traceparent.ts","../src/core/provision.ts","../src/core/runtime.ts","../src/api.ts"],"sourcesContent":["import { IntegrityError } from './errors.js';\n\nexport const PINNED_VERSION = '0.15.0';\n\nexport const CHECKSUMS: Record<string, Record<string, string>> = {\n '0.15.0': {\n linux_amd64:\n '89f7ebbfd75ffd961245ec62b2602fd0cc387740502ac858dbc39c367c5699c5',\n linux_arm64:\n '3fabbd749f9e98fb9f96ddfc94c389a6868cda7ed3668daa8440c39ceec85f3b',\n },\n '0.14.0': {\n linux_amd64:\n '2ab8ba0d6637fe1a5badf840c3db197161a6f9865d721ed216029d229b1b9bbc',\n linux_arm64:\n '929d18dd9fe36e9b2fa830d7ae64b4fb481853e743ade8674fcfcdc73470ed53',\n },\n};\n\n/**\n * Returns the checksum to verify against.\n * If `override` is provided, returns it directly.\n * Otherwise looks up the checksum in the pinned CHECKSUMS map.\n * Throws IntegrityError if no checksum is found.\n */\nexport function getChecksum(\n version: string,\n arch: string,\n override?: string,\n): string {\n if (override) {\n return override;\n }\n\n const versionChecksums = CHECKSUMS[version];\n if (versionChecksums && versionChecksums[arch]) {\n return versionChecksums[arch];\n }\n\n throw new IntegrityError({\n expected: '',\n actual: '',\n message: `No pinned checksum for agentsh v${version}. Provide \\`agentshChecksum\\` explicitly or use \\`skipIntegrityCheck: true\\`.`,\n });\n}\n\n/**\n * Returns an array of shell commands to try for computing SHA-256 checksums.\n * Each command extracts just the hex hash value from the given file.\n */\nexport function buildVerifyCommand(filePath: string): string[] {\n return [\n `sha256sum \"${filePath}\" | awk '{print $1}'`,\n `shasum -a 256 \"${filePath}\" | awk '{print $1}'`,\n `openssl dgst -sha256 \"${filePath}\" | awk '{print $NF}'`,\n ];\n}\n\n/**\n * Returns the download URL for the agentsh binary.\n * If `overrideUrl` is provided, returns it directly.\n * Otherwise returns the default GitHub releases URL.\n */\nexport function binaryUrl(\n version: string,\n arch: string,\n overrideUrl?: string,\n): string {\n if (overrideUrl) {\n return overrideUrl;\n }\n\n return `https://github.com/canyonroad/agentsh/releases/download/v${version}/agentsh_${version}_${arch}.tar.gz`;\n}\n","import yaml from 'js-yaml';\nimport type { ThreatFeedsConfig } from './types.js';\n\nexport interface ServerConfigOpts {\n workspace: string;\n watchtower?: string;\n enforceRedirects?: boolean;\n realPaths?: boolean;\n threatFeeds?: false | ThreatFeedsConfig;\n}\n\n/**\n * Default threat feeds: URLhaus (malware) + Phishing.Database (phishing).\n * Both are free, open source, and updated frequently.\n */\nexport const defaultThreatFeeds: ThreatFeedsConfig = {\n action: 'deny',\n feeds: [\n {\n name: 'urlhaus',\n url: 'https://urlhaus.abuse.ch/downloads/hostfile/',\n format: 'hostfile',\n refreshInterval: '6h',\n },\n {\n name: 'phishing',\n url: 'https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-domains-ACTIVE.txt',\n format: 'domain-list',\n refreshInterval: '12h',\n },\n ],\n allowlist: [\n 'github.com',\n '*.github.com',\n 'registry.npmjs.org',\n 'registry.yarnpkg.com',\n 'pypi.org',\n 'files.pythonhosted.org',\n 'crates.io',\n 'static.crates.io',\n 'index.crates.io',\n 'proxy.golang.org',\n 'sum.golang.org',\n ],\n};\n\nexport function generateServerConfig(opts: ServerConfigOpts): string {\n const config: Record<string, unknown> = {\n server: {\n http: {\n addr: '127.0.0.1:18080',\n },\n },\n auth: {\n type: 'none',\n },\n policies: {\n system_dir: '/etc/agentsh/system',\n dir: '/etc/agentsh',\n default: 'policy',\n },\n workspace: opts.workspace,\n sandbox: {\n enabled: true,\n allow_degraded: true,\n },\n };\n if (opts.watchtower) config.watchtower = opts.watchtower;\n if (opts.enforceRedirects) config.enforce_redirects = true;\n if (opts.realPaths) config.real_paths = true;\n\n // Threat feeds: enabled by default, opt-out with `threatFeeds: false`\n const feeds = opts.threatFeeds === false ? undefined : (opts.threatFeeds ?? defaultThreatFeeds);\n if (feeds) {\n config.threat_feeds = {\n enabled: true,\n action: feeds.action ?? 'deny',\n feeds: feeds.feeds.map(f => ({\n name: f.name,\n url: f.url,\n format: f.format,\n refresh_interval: f.refreshInterval ?? '6h',\n })),\n ...(feeds.allowlist?.length ? { allowlist: feeds.allowlist } : {}),\n };\n }\n\n return yaml.dump(config, { lineWidth: -1 });\n}\n","/**\n * Read W3C traceparent from the active OpenTelemetry span, if available.\n *\n * Uses dynamic import so @opentelemetry/api is an optional peer dependency.\n * Returns undefined when OTEL is not installed, no span is active, or the\n * trace context is invalid (all-zero trace ID).\n */\nexport async function getTraceparent(): Promise<string | undefined> {\n try {\n const { trace } = await import('@opentelemetry/api');\n const span = trace.getActiveSpan();\n const ctx = span?.spanContext();\n if (!ctx?.traceId || ctx.traceId === '00000000000000000000000000000000') {\n return undefined;\n }\n const flags = (ctx.traceFlags ?? 0).toString(16).padStart(2, '0');\n return `00-${ctx.traceId}-${ctx.spanId}-${flags}`;\n } catch {\n return undefined;\n }\n}\n","import type {\n SandboxAdapter,\n SecureConfig,\n SecurityMode,\n ExecResult,\n} from './types.js';\nimport {\n getChecksum,\n buildVerifyCommand,\n binaryUrl,\n PINNED_VERSION,\n} from './integrity.js';\nimport { generateServerConfig } from './config.js';\nimport { ProvisioningError, IntegrityError } from './errors.js';\nimport { serializePolicy, systemPolicyYaml } from '../policies/serialize.js';\nimport { agentDefault } from '../policies/presets.js';\nimport { validatePolicy } from '../policies/schema.js';\nimport { getTraceparent } from './traceparent.js';\n\n// ─── Security mode ordering (strongest to weakest) ────────────\n\nconst SECURITY_MODE_RANK: Record<SecurityMode, number> = {\n full: 4,\n landlock: 3,\n 'landlock-only': 2,\n minimal: 1,\n};\n\nfunction isWeakerThan(detected: SecurityMode, required: SecurityMode): boolean {\n return SECURITY_MODE_RANK[detected] < SECURITY_MODE_RANK[required];\n}\n\n// ─── Architecture mapping ─────────────────────────────────────\n\nfunction mapArch(uname: string): 'linux_amd64' | 'linux_arm64' {\n const trimmed = uname.trim();\n if (trimmed === 'x86_64') return 'linux_amd64';\n if (trimmed === 'aarch64') return 'linux_arm64';\n throw new ProvisioningError({\n phase: 'install',\n command: 'uname -m',\n stderr: `Unsupported architecture: ${trimmed}`,\n });\n}\n\n// ─── Helper: check if binary exists ───────────────────────────\n\nconst AGENTSH_PATHS = ['/usr/local/bin/agentsh', '/usr/bin/agentsh'];\n\nasync function binaryExists(adapter: SandboxAdapter): Promise<boolean> {\n for (const path of AGENTSH_PATHS) {\n const found = adapter.fileExists\n ? await adapter.fileExists(path)\n : (await adapter.exec('test', ['-f', path])).exitCode === 0;\n if (found) return true;\n }\n return false;\n}\n\n// ─── Helper: sleep ────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// ─── Main provisioning function ───────────────────────────────\n\nexport interface ProvisionResult {\n sessionId: string;\n securityMode: SecurityMode;\n /** When true, the shell shim enforces policy — skip agentsh exec wrapper. */\n passthrough?: boolean;\n}\n\nexport async function provision(\n adapter: SandboxAdapter,\n config: SecureConfig = {},\n): Promise<ProvisionResult> {\n const {\n policy: rawPolicy,\n workspace = '/workspace',\n watchtower,\n installStrategy = 'download',\n agentshVersion = PINNED_VERSION,\n agentshArch: archOverride,\n agentshBinaryUrl,\n agentshChecksum,\n skipIntegrityCheck = false,\n minimumSecurityMode,\n realPaths: realPathsOverride,\n enforceRedirects = false,\n traceParent,\n policyName = 'policy',\n threatFeeds,\n } = config;\n\n // Resolve and validate policy\n const policy = rawPolicy ? validatePolicy(rawPolicy) : agentDefault();\n\n let securityMode: SecurityMode = 'full';\n\n if (installStrategy === 'running') {\n // agentsh is already fully provisioned and running with the shell shim\n // installed. Commands go through the shim automatically, so we don't\n // create a new session (which would deadlock the server via nested\n // agentsh connections). Instead, read the existing session ID from\n // the environment and use passthrough mode at runtime.\n //\n // Skip detectSecurityMode() — running `agentsh detect` inside a sandbox\n // where the shell shim is already installed would route the command\n // through agentsh's exec API, causing the server to try binding port\n // 18080 again (\"address already in use\"). Default to 'full' since\n // pre-provisioned environments typically have full capabilities.\n await healthCheck(adapter);\n\n securityMode = config.securityMode ?? 'full';\n\n if (minimumSecurityMode && isWeakerThan(securityMode, minimumSecurityMode)) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'securityMode check',\n stderr: `Security mode '${securityMode}' is weaker than required '${minimumSecurityMode}'`,\n });\n }\n\n // Read the existing session ID from config or from the environment\n let sessionId = config.sessionId;\n if (!sessionId) {\n const envResult = await adapter.exec('sh', ['-c', 'echo $AGENTSH_SESSION_ID']);\n sessionId = envResult.stdout.trim();\n }\n if (!sessionId) {\n throw new ProvisioningError({\n phase: 'session',\n command: 'echo $AGENTSH_SESSION_ID',\n stderr: 'AGENTSH_SESSION_ID not set — running strategy requires a pre-created session',\n });\n }\n\n return { sessionId, securityMode, passthrough: true };\n }\n\n // ─── Phase 1: Binary Installation ───────────────────────────\n\n // Step 1: Check if binary exists\n const exists = await binaryExists(adapter);\n\n if (installStrategy === 'preinstalled') {\n if (!exists) {\n throw new ProvisioningError({\n phase: 'install',\n command: AGENTSH_PATHS.map(p => `test -f ${p}`).join(' || '),\n stderr: 'Binary not found but installStrategy is preinstalled',\n });\n }\n // Binary exists and strategy is preinstalled, skip to detect\n } else if (installStrategy === 'download' || installStrategy === 'upload') {\n // If binary already exists, skip installation but still detect\n if (!exists) {\n // Step 2: Detect architecture\n const arch =\n archOverride ?? await detectArch(adapter);\n\n if (installStrategy === 'download') {\n // Step 3a: Download\n await downloadBinary(adapter, agentshVersion, arch, agentshBinaryUrl);\n } else {\n // Step 3b: Upload\n await uploadBinary(adapter, agentshVersion, arch, agentshBinaryUrl);\n }\n\n // Step 4: Verify checksum\n if (!skipIntegrityCheck) {\n await verifyChecksum(\n adapter,\n agentshVersion,\n arch,\n agentshChecksum,\n '/tmp/agentsh.tar.gz',\n );\n }\n\n // Step 5: Install binaries (agentsh + agentsh-shell-shim + agentsh-unixwrap)\n const binaries = [\n { src: '/tmp/agentsh', dest: '/usr/local/bin/agentsh' },\n { src: '/tmp/agentsh-shell-shim', dest: '/usr/bin/agentsh-shell-shim' },\n { src: '/tmp/agentsh-unixwrap', dest: '/usr/local/bin/agentsh-unixwrap' },\n ];\n for (const { src, dest } of binaries) {\n const installResult = await adapter.exec(\n 'install',\n ['-m', '0755', src, dest],\n { sudo: true },\n );\n if (installResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: `install -m 0755 ${src} ${dest}`,\n stderr: installResult.stderr,\n });\n }\n }\n }\n }\n\n // Step 5b: Detect security mode\n securityMode = await detectSecurityMode(adapter);\n\n // Check minimum security mode\n if (minimumSecurityMode && isWeakerThan(securityMode, minimumSecurityMode)) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --json',\n stderr: `Detected security mode '${securityMode}' is weaker than required '${minimumSecurityMode}'`,\n });\n }\n\n // Auto-enable realPaths when FUSE is available (full or landlock modes),\n // unless the user explicitly set it.\n const hasFuse = securityMode === 'full' || securityMode === 'landlock';\n const realPaths = realPathsOverride ?? hasFuse;\n\n // Step 6: Install shell shim\n const shimResult = await adapter.exec(\n 'agentsh',\n [\n 'shim', 'install-shell',\n '--root', '/',\n '--shim', '/usr/bin/agentsh-shell-shim',\n '--bash',\n '--i-understand-this-modifies-the-host',\n ],\n { sudo: true },\n );\n if (shimResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh shim install-shell',\n stderr: shimResult.stderr,\n });\n }\n\n // ─── Phase 2: Policy & Config ───────────────────────────────\n\n // Step 7: Create dirs and make writable for file writes\n const mkdirResult = await adapter.exec(\n 'mkdir',\n ['-p', '/etc/agentsh/system'],\n { sudo: true },\n );\n if (mkdirResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'mkdir -p /etc/agentsh/system',\n stderr: mkdirResult.stderr,\n });\n }\n\n // Temporarily make writable so adapter.writeFile (which may not support sudo) can write\n await adapter.exec('chmod', ['-R', '777', '/etc/agentsh/'], { sudo: true });\n\n await adapter.writeFile(\n '/etc/agentsh/system/policy.yml',\n systemPolicyYaml(),\n { sudo: true },\n );\n\n // Step 8: Write user policy\n await adapter.writeFile(\n '/etc/agentsh/policy.yml',\n serializePolicy(policy),\n { sudo: true },\n );\n\n // Step 9: Write server config\n const serverConfig = generateServerConfig({\n workspace,\n watchtower,\n enforceRedirects,\n realPaths,\n threatFeeds,\n });\n\n await adapter.writeFile('/etc/agentsh/config.yml', serverConfig, {\n sudo: true,\n });\n\n // Step 10: Set permissions\n const chmodDirResult = await adapter.exec(\n 'find',\n ['/etc/agentsh', '-type', 'd', '-exec', 'chmod', '555', '{}', '+'],\n { sudo: true },\n );\n if (chmodDirResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'find /etc/agentsh -type d -exec chmod 555 {} +',\n stderr: chmodDirResult.stderr,\n });\n }\n\n const chmodFileResult = await adapter.exec(\n 'find',\n ['/etc/agentsh', '-type', 'f', '-exec', 'chmod', '444', '{}', '+'],\n { sudo: true },\n );\n if (chmodFileResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'find /etc/agentsh -type f -exec chmod 444 {} +',\n stderr: chmodFileResult.stderr,\n });\n }\n\n const chownResult = await adapter.exec(\n 'chown',\n ['-R', 'root:root', '/etc/agentsh/'],\n { sudo: true },\n );\n if (chownResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'policy',\n command: 'chown -R root:root /etc/agentsh/',\n stderr: chownResult.stderr,\n });\n }\n\n // ─── Phase 3: Server Startup ────────────────────────────────\n\n // Step 10b: Ensure workspace directory exists\n await adapter.exec('mkdir', ['-p', workspace], { sudo: true });\n\n // Step 11: Start server\n const serverResult = await adapter.exec(\n 'agentsh',\n ['server', '--config', '/etc/agentsh/config.yml'],\n { detached: true, sudo: true },\n );\n if (serverResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'startup',\n command: 'agentsh server --config /etc/agentsh/config.yml',\n stderr: serverResult.stderr,\n });\n }\n\n // Step 12: Health check\n await healthCheck(adapter);\n\n // Step 13: Create session\n const sessionResult = await adapter.exec('agentsh', [\n 'session',\n 'create',\n '--workspace',\n workspace,\n '--policy',\n 'policy',\n ]);\n if (sessionResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'session',\n command: 'agentsh session create',\n stderr: sessionResult.stderr,\n });\n }\n\n let sessionId: string;\n try {\n const sessionData = JSON.parse(sessionResult.stdout);\n sessionId = sessionData.session_id;\n } catch {\n // Fallback: parse text output like \"Session session-xxx started\"\n const match = sessionResult.stdout.match(/Session\\s+(session-[^\\s]+)/);\n if (match) {\n sessionId = match[1];\n } else {\n throw new ProvisioningError({\n phase: 'session',\n command: 'agentsh session create',\n stderr: `Failed to parse session output: ${sessionResult.stdout}`,\n });\n }\n }\n\n // Step 13b: Set trace context if traceParent is provided or OTEL span is active\n const effectiveTraceParent = traceParent ?? (await getTraceparent());\n if (effectiveTraceParent) {\n await adapter.exec('curl', [\n '-X',\n 'PUT',\n `http://127.0.0.1:18080/sessions/${sessionId}/trace-context`,\n '-H',\n 'Content-Type: application/json',\n '-d',\n JSON.stringify({ traceparent: effectiveTraceParent }),\n ]);\n }\n\n // ─── Phase 4: Handoff ───────────────────────────────────────\n\n // Step 14: Return result\n return { sessionId, securityMode };\n}\n\n// ─── Phase 1 helpers ──────────────────────────────────────────\n\nasync function detectArch(\n adapter: SandboxAdapter,\n): Promise<'linux_amd64' | 'linux_arm64'> {\n const result = await adapter.exec('uname', ['-m']);\n if (result.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'uname -m',\n stderr: result.stderr,\n });\n }\n return mapArch(result.stdout);\n}\n\nasync function downloadBinary(\n adapter: SandboxAdapter,\n version: string,\n arch: string,\n overrideUrl?: string,\n): Promise<void> {\n const url = binaryUrl(version, arch, overrideUrl);\n\n // Try curl first\n const curlResult = await adapter.exec('curl', [\n '-fsSL',\n url,\n '-o',\n '/tmp/agentsh.tar.gz',\n ]);\n\n if (curlResult.exitCode !== 0) {\n // Fallback to wget (may not be available on all platforms)\n let wgetResult: ExecResult;\n try {\n wgetResult = await adapter.exec('wget', [\n '-q',\n url,\n '-O',\n '/tmp/agentsh.tar.gz',\n ]);\n } catch {\n throw new ProvisioningError({\n phase: 'install',\n command: `curl -fsSL ${url} -o /tmp/agentsh.tar.gz`,\n stderr: curlResult.stderr || 'Download failed (curl failed, wget not available)',\n });\n }\n if (wgetResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: `wget -q ${url} -O /tmp/agentsh.tar.gz`,\n stderr: wgetResult.stderr,\n });\n }\n }\n\n // Extract\n const tarResult = await adapter.exec('tar', [\n 'xz',\n '-C',\n '/tmp/',\n '-f',\n '/tmp/agentsh.tar.gz',\n ]);\n if (tarResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'tar xz -C /tmp/ -f /tmp/agentsh.tar.gz',\n stderr: tarResult.stderr,\n });\n }\n}\n\nasync function uploadBinary(\n adapter: SandboxAdapter,\n version: string,\n arch: string,\n overrideUrl?: string,\n): Promise<void> {\n const url = binaryUrl(version, arch, overrideUrl);\n\n // Download on host side using fetch (Node 18+)\n const response = await fetch(url);\n if (!response.ok) {\n throw new ProvisioningError({\n phase: 'install',\n command: `fetch ${url}`,\n stderr: `HTTP ${response.status}: ${response.statusText}`,\n });\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n\n // Upload tarball to sandbox and extract\n await adapter.writeFile('/tmp/agentsh.tar.gz', buffer);\n const tarResult = await adapter.exec('tar', [\n 'xz',\n '-C',\n '/tmp/',\n '-f',\n '/tmp/agentsh.tar.gz',\n ]);\n if (tarResult.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'tar xz -C /tmp/ -f /tmp/agentsh.tar.gz',\n stderr: tarResult.stderr,\n });\n }\n}\n\nasync function verifyChecksum(\n adapter: SandboxAdapter,\n version: string,\n arch: string,\n checksumOverride: string | undefined,\n filePath: string,\n): Promise<void> {\n const expected = getChecksum(version, arch, checksumOverride);\n const commands = buildVerifyCommand(filePath);\n\n let actual: string | undefined;\n\n for (const cmd of commands) {\n const result = await adapter.exec('sh', ['-c', cmd]);\n if (result.exitCode === 0 && result.stdout.trim()) {\n actual = result.stdout.trim();\n break;\n }\n }\n\n if (actual === undefined) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'sha256sum / shasum / openssl',\n stderr: 'No checksum tool available in sandbox',\n });\n }\n\n if (actual !== expected) {\n throw new IntegrityError({\n expected,\n actual,\n message: `Checksum mismatch: expected ${expected}, got ${actual}`,\n });\n }\n}\n\nasync function detectSecurityMode(\n adapter: SandboxAdapter,\n): Promise<SecurityMode> {\n const result = await adapter.exec('agentsh', ['detect', '--output', 'json']);\n if (result.exitCode !== 0) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: result.stderr,\n });\n }\n\n // agentsh detect outputs JSON to stderr\n const jsonOutput = result.stderr || result.stdout;\n let parsed: { security_mode: string };\n try {\n parsed = JSON.parse(jsonOutput);\n } catch {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: `Failed to parse detect JSON: ${jsonOutput.slice(0, 200)}`,\n });\n }\n\n const mode = parsed.security_mode;\n const validModes: SecurityMode[] = ['full', 'landlock', 'landlock-only', 'minimal'];\n if (!validModes.includes(mode as SecurityMode)) {\n throw new ProvisioningError({\n phase: 'install',\n command: 'agentsh detect --output json',\n stderr: `Unknown security mode: '${mode}'`,\n });\n }\n return mode as SecurityMode;\n}\n\nasync function healthCheck(adapter: SandboxAdapter): Promise<void> {\n const maxRetries = 10;\n const delayMs = 500;\n\n for (let i = 0; i < maxRetries; i++) {\n const result = await adapter.exec('curl', [\n '-sf',\n 'http://127.0.0.1:18080/health',\n ]);\n if (result.exitCode === 0) {\n return;\n }\n if (i < maxRetries - 1) {\n await sleep(delayMs);\n }\n }\n\n throw new ProvisioningError({\n phase: 'startup',\n command: 'curl http://127.0.0.1:18080/health',\n stderr: 'Health check failed after 10 attempts',\n });\n}\n","import type {\n SandboxAdapter,\n SecuredSandbox,\n SecurityMode,\n ExecResult,\n} from './types.js';\nimport { RuntimeError } from './errors.js';\nimport { getTraceparent } from './traceparent.js';\n\n/** Build env object with TRACEPARENT if an OTEL span is active. */\nasync function traceEnv(): Promise<Record<string, string> | undefined> {\n const tp = await getTraceparent();\n return tp ? { TRACEPARENT: tp } : undefined;\n}\n\n/** Parse the JSON envelope from `agentsh exec --output json`. */\nfunction parseExecJson(raw: ExecResult): ExecResult {\n try {\n const json = JSON.parse(raw.stdout);\n const result = json.result ?? {};\n return {\n exitCode: result.exit_code ?? raw.exitCode,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? result.error?.message ?? '',\n };\n } catch {\n // If not valid JSON, return as-is (e.g. mock adapters)\n return raw;\n }\n}\n\nexport function createSecuredSandbox(\n adapter: SandboxAdapter,\n sessionId: string,\n securityMode: SecurityMode,\n options?: { passthrough?: boolean },\n): SecuredSandbox {\n if (options?.passthrough) {\n return createPassthroughSandbox(adapter, sessionId, securityMode);\n }\n return createAgentshSandbox(adapter, sessionId, securityMode);\n}\n\n/**\n * Passthrough mode: the shell shim enforces policy on every command,\n * so we run commands directly through the adapter without wrapping\n * them in `agentsh exec`. Used with the 'running' install strategy.\n */\nfunction createPassthroughSandbox(\n adapter: SandboxAdapter,\n sessionId: string,\n securityMode: SecurityMode,\n): SecuredSandbox {\n return {\n sessionId,\n securityMode,\n\n async exec(command, opts) {\n const result = await adapter.exec('bash', ['-c', command], {\n cwd: opts?.cwd,\n });\n return result;\n },\n\n async writeFile(path, content) {\n const b64 = Buffer.from(content, 'utf-8').toString('base64');\n const result = await adapter.exec('sh', [\n '-c',\n 'printf \"%s\" \"$1\" | base64 -d > \"$2\"',\n '_',\n b64,\n path,\n ]);\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'writeFile failed',\n };\n }\n return { success: true as const, path };\n },\n\n async readFile(path) {\n const result = await adapter.exec('cat', [path]);\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'readFile failed',\n };\n }\n return { success: true as const, path, content: result.stdout };\n },\n\n async stop() {\n await adapter.stop?.();\n },\n };\n}\n\n/** Standard mode: wraps commands in `agentsh exec` for policy enforcement. */\nfunction createAgentshSandbox(\n adapter: SandboxAdapter,\n sessionId: string,\n securityMode: SecurityMode,\n): SecuredSandbox {\n return {\n sessionId,\n securityMode,\n\n async exec(command, opts) {\n const args = [\n 'exec',\n '--output',\n 'json',\n sessionId,\n '--',\n 'bash',\n '-c',\n command,\n ];\n const env = await traceEnv();\n const execOpts = { cwd: opts?.cwd, env };\n const result = await adapter.exec('agentsh', args, execOpts);\n if (isTransportFailure(result)) {\n throw new RuntimeError({\n sessionId,\n command,\n stderr: result.stderr,\n });\n }\n return parseExecJson(result);\n },\n\n async writeFile(path, content) {\n const b64 = Buffer.from(content, 'utf-8').toString('base64');\n const args = [\n 'exec',\n sessionId,\n '--',\n 'sh',\n '-c',\n 'printf \"%s\" \"$1\" | base64 -d > \"$2\"',\n '_',\n b64,\n path,\n ];\n const env = await traceEnv();\n const result = await adapter.exec('agentsh', args, { env });\n if (isTransportFailure(result)) {\n throw new RuntimeError({\n sessionId,\n command: `writeFile ${path}`,\n stderr: result.stderr,\n });\n }\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'writeFile failed',\n };\n }\n return { success: true as const, path };\n },\n\n async readFile(path) {\n const args = ['exec', sessionId, '--', 'cat', path];\n const env = await traceEnv();\n const result = await adapter.exec('agentsh', args, { env });\n if (isTransportFailure(result)) {\n throw new RuntimeError({\n sessionId,\n command: `readFile ${path}`,\n stderr: result.stderr,\n });\n }\n if (result.exitCode !== 0) {\n return {\n success: false as const,\n path,\n error: result.stderr || 'readFile failed',\n };\n }\n return { success: true as const, path, content: result.stdout };\n },\n\n async stop() {\n await adapter.stop?.();\n },\n };\n}\n\nfunction isTransportFailure(result: ExecResult): boolean {\n return result.exitCode === 127 && result.stderr.includes('agentsh');\n}\n","import type {\n SandboxAdapter,\n SecuredSandbox,\n SecureConfig,\n} from './core/types.js';\nimport { provision } from './core/provision.js';\nimport { createSecuredSandbox } from './core/runtime.js';\n\nexport async function secureSandbox(\n adapter: SandboxAdapter,\n config?: SecureConfig,\n): Promise<SecuredSandbox> {\n const resolvedConfig = config ?? {};\n const { sessionId, securityMode, passthrough } = await provision(adapter, {\n workspace: '/workspace',\n ...resolvedConfig,\n });\n return createSecuredSandbox(adapter, sessionId, securityMode, { passthrough });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,IAAM,iBAAiB;AAEvB,IAAM,YAAoD;AAAA,EAC/D,UAAU;AAAA,IACR,aACE;AAAA,IACF,aACE;AAAA,EACJ;AAAA,EACA,UAAU;AAAA,IACR,aACE;AAAA,IACF,aACE;AAAA,EACJ;AACF;AAQO,SAAS,YACd,SACA,MACA,UACQ;AACR,MAAI,UAAU;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmB,UAAU,OAAO;AAC1C,MAAI,oBAAoB,iBAAiB,IAAI,GAAG;AAC9C,WAAO,iBAAiB,IAAI;AAAA,EAC9B;AAEA,QAAM,IAAI,eAAe;AAAA,IACvB,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,SAAS,mCAAmC,OAAO;AAAA,EACrD,CAAC;AACH;AAMO,SAAS,mBAAmB,UAA4B;AAC7D,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,kBAAkB,QAAQ;AAAA,IAC1B,yBAAyB,QAAQ;AAAA,EACnC;AACF;AAOO,SAAS,UACd,SACA,MACA,aACQ;AACR,MAAI,aAAa;AACf,WAAO;AAAA,EACT;AAEA,SAAO,4DAA4D,OAAO,YA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YAAM,SAAS,MAAM,QAAQ,KAAK,WAAW,MAAM,EAAE,IAAI,CAAC;AAC1D,UAAI,mBAAmB,MAAM,GAAG;AAC9B,cAAM,IAAI,aAAa;AAAA,UACrB;AAAA,UACA,SAAS,YAAY,IAAI;AAAA,UACzB,QAAQ,OAAO;AAAA,QACjB,CAAC;AAAA,MACH;AACA,UAAI,OAAO,aAAa,GAAG;AACzB,eAAO;AAAA,UACL,SAAS;AAAA,UACT;AAAA,UACA,OAAO,OAAO,UAAU;AAAA,QAC1B;AAAA,MACF;AACA,aAAO,EAAE,SAAS,MAAe,MAAM,SAAS,OAAO,OAAO;AAAA,IAChE;AAAA,IAEA,MAAM,OAAO;AACX,YAAM,QAAQ,OAAO;AAAA,IACvB;AAAA,EACF;AACF;AAEA,SAAS,mBAAmB,QAA6B;AACvD,SAAO,OAAO,aAAa,OAAO,OAAO,OAAO,SAAS,SAAS;AACpE;;;AC5LA,eAAsB,cACpB,SACA,QACyB;AACzB,QAAM,iBAAiB,UAAU,CAAC;AAClC,QAAM,EAAE,WAAW,cAAc,YAAY,IAAI,MAAM,UAAU,SAAS;AAAA,IACxE,WAAW;AAAA,IACX,GAAG;AAAA,EACL,CAAC;AACD,SAAO,qBAAqB,SAAS,WAAW,cAAc,EAAE,YAAY,CAAC;AAC/E;","names":["sessionId"]}
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -118,8 +118,9 @@ interface SecureConfig {
|
|
|
118
118
|
* - 'download': Download from GitHub releases inside the sandbox. Default.
|
|
119
119
|
* - 'upload': Library downloads on host, uploads via adapter.writeFile().
|
|
120
120
|
* - 'running': agentsh is already fully provisioned and running.
|
|
121
|
-
* Skips install, shim, policy, config,
|
|
122
|
-
*
|
|
121
|
+
* Skips install, shim, policy, config, server startup, and security
|
|
122
|
+
* detection. Defaults securityMode to 'full' (override via securityMode).
|
|
123
|
+
* Runs health check and reads the existing session from the environment.
|
|
123
124
|
*/
|
|
124
125
|
installStrategy?: InstallStrategy;
|
|
125
126
|
/** Override agentsh binary version. Default: pinned per library release. */
|
|
@@ -135,6 +136,12 @@ interface SecureConfig {
|
|
|
135
136
|
* Only use if you are providing your own binary via a trusted channel.
|
|
136
137
|
*/
|
|
137
138
|
skipIntegrityCheck?: boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Override the detected security mode. Only used with installStrategy 'running',
|
|
141
|
+
* where `agentsh detect` is skipped (it would conflict with the running server).
|
|
142
|
+
* Default for 'running': 'full'. Ignored for other install strategies.
|
|
143
|
+
*/
|
|
144
|
+
securityMode?: SecurityMode;
|
|
138
145
|
/**
|
|
139
146
|
* Minimum acceptable security mode. If `agentsh detect` reports a
|
|
140
147
|
* weaker mode, provisioning fails with ProvisioningError.
|
|
@@ -165,6 +172,12 @@ interface SecureConfig {
|
|
|
165
172
|
* Default: 'policy' (matches the file written by other install strategies).
|
|
166
173
|
*/
|
|
167
174
|
policyName?: string;
|
|
175
|
+
/**
|
|
176
|
+
* Existing agentsh session ID. Only used with installStrategy 'running'.
|
|
177
|
+
* If not provided, reads $AGENTSH_SESSION_ID from the sandbox environment.
|
|
178
|
+
* Use this when the sandbox exec API doesn't inherit shell profile env vars.
|
|
179
|
+
*/
|
|
180
|
+
sessionId?: string;
|
|
168
181
|
/**
|
|
169
182
|
* Threat intelligence feeds for blocking known-malicious domains.
|
|
170
183
|
* Default: enabled with URLhaus and Phishing.Database feeds.
|