@codeworksh/harness 0.8.0 → 0.9.0-canary.158.1.gdff28d0d

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.
@@ -1,6 +1,8 @@
1
1
  import { t as SandboxDriver } from "./sandbox-BL7BdHZc.mjs";
2
2
  import { Schema } from "effect";
3
- //#region src/sandboxes/daytona/index.d.ts
3
+ declare namespace index_d_exports {
4
+ export { ClientOptions, CreateConfig, Options, ResourcesConfig, RuntimeConfig, config, sandbox as default, make };
5
+ }
4
6
  declare const Options: Schema.Struct<{
5
7
  readonly apiKey: Schema.optional<Schema.String>;
6
8
  readonly apiUrl: Schema.optional<Schema.String>;
@@ -72,5 +74,5 @@ declare const config: (value: CreateConfig) => {
72
74
  };
73
75
  };
74
76
  //#endregion
75
- export { RuntimeConfig as a, sandbox as c, ResourcesConfig as i, CreateConfig as n, config as o, Options as r, make as s, ClientOptions as t };
76
- //# sourceMappingURL=index-BlvIgEtU.d.mts.map
77
+ export { RuntimeConfig as a, make as c, ResourcesConfig as i, sandbox as l, CreateConfig as n, config as o, Options as r, index_d_exports as s, ClientOptions as t };
78
+ //# sourceMappingURL=index-Bh-JSvU4.d.mts.map
@@ -1,6 +1,8 @@
1
1
  import { t as SandboxDriver } from "./sandbox-BL7BdHZc.mjs";
2
2
  import { Schema } from "effect";
3
- //#region src/sandboxes/vercel/index.d.ts
3
+ declare namespace index_d_exports {
4
+ export { ClientOptions, CreateConfig, Options, RuntimeConfig, Source, config, sandbox as default, make };
5
+ }
4
6
  declare const Options: Schema.Struct<{
5
7
  readonly token: Schema.optional<Schema.String>;
6
8
  readonly teamId: Schema.optional<Schema.String>;
@@ -78,5 +80,5 @@ declare const config: (value: CreateConfig) => {
78
80
  };
79
81
  };
80
82
  //#endregion
81
- export { Source as a, sandbox as c, RuntimeConfig as i, CreateConfig as n, config as o, Options as r, make as s, ClientOptions as t };
82
- //# sourceMappingURL=index-BEZ8eL--.d.mts.map
83
+ export { Source as a, make as c, RuntimeConfig as i, sandbox as l, CreateConfig as n, config as o, Options as r, index_d_exports as s, ClientOptions as t };
84
+ //# sourceMappingURL=index-NOtBwGrV.d.mts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeworksh/harness",
3
- "version": "0.8.0",
3
+ "version": "0.9.0-canary.158.1.gdff28d0d",
4
4
  "description": "AI agent harness — agent loop, tools, plugins, sandbox, and more.",
5
5
  "keywords": [
6
6
  "agent",
@@ -66,8 +66,8 @@
66
66
  "node": ">=24.14.1"
67
67
  },
68
68
  "dependencies": {
69
- "@codeworksh/aikit": "^0.14.0",
70
- "@codeworksh/plugin": "0.4.0",
69
+ "@codeworksh/aikit": "0.14.1-canary.158.1.gdff28d0d",
70
+ "@codeworksh/plugin": "0.5.0-canary.158.1.gdff28d0d",
71
71
  "@effect/platform-node": "4.0.5",
72
72
  "@effect/platform-node-shared": "4.0.5",
73
73
  "@effect/sql-sqlite-node": "4.0.5",
@@ -1,7 +1,7 @@
1
1
  import { registerHooks } from "node:module";
2
2
  import { Config, Effect, Option, Schema } from "effect";
3
- import { pathToFileURL } from "node:url";
4
3
  import { statSync } from "node:fs";
4
+ import { pathToFileURL } from "node:url";
5
5
  import path from "node:path";
6
6
  import { Script, constants } from "node:vm";
7
7
  import { Worker } from "node:worker_threads";
@@ -458,4 +458,4 @@ const dimensionNote = (result) => {
458
458
  //#endregion
459
459
  export { decode as a, importModule as c, share as d, resizeInProcess as i, lendResolve as l, dimensionNote as n, load as o, resize as r, load$1 as s, REPLY as t, resolveModule as u };
460
460
 
461
- //# sourceMappingURL=resize-BF1OwDGZ.mjs.map
461
+ //# sourceMappingURL=resize-BUdJMHgx.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"resize-BF1OwDGZ.mjs","names":["load","unpacked"],"sources":["../../src/util/module.ts","../../src/util/unpacked.ts","../../src/tool/image/exif.ts","../../src/tool/image/photon.ts","../../src/tool/image/resize.ts"],"sourcesContent":["/*!\n * Adapted from OpenCode packages/util/src/runtime/import.node.ts.\n *\n * MIT License\n *\n * Copyright (c) 2025 opencode\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n/* oxlint-disable effecttsgo/async-function -- Native module loading exposes a Promise-based importer contract. */\n// Resolution hooks cannot yield to Effect; existence checks must stay synchronous.\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport { statSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { Script, constants } from \"node:vm\";\n\n/**\n * Packages a plugin must share with the harness instead of using the copy installed beside it.\n *\n * A plugin is installed into the store as its own npm tree, so `effect` and the plugin SDK land\n * there a second time. Two copies of the *same version* are still two module instances, and\n * Effect Schema's checks do not survive the crossing: a schema built by one copy and evaluated by\n * the other reports every check as failed, so a tool whose success type is `Schema.Finite` dies\n * on \"Expected a finite number\" for `22800`. Nothing about that is visible at registration --\n * `Schema.isSchema` passes, the JSON Schema is derived correctly, and the tool reaches the model\n * -- so it surfaces on the first call rather than at boot.\n *\n * Resolution is the right place to fix it. A symlink into the store cannot be: a generation is\n * immutable and shared by every project on the machine, while the harness doing the loading is\n * whichever one is running now, and two applications embedding the harness need not agree on\n * where their `effect` lives.\n *\n * Each package maps to the `Symbol.for` key of its {@link SharedRegistry}.\n */\nconst sharedPackages: ReadonlyMap<string, string> = new Map([\n\t[\"effect\", \"codework.v1.effect\"],\n\t[\"@codeworksh/plugin\", \"codework.v1.plugin\"],\n]);\n\n/** One module of a shared package, as a bundled host publishes it. */\nexport interface SharedModule {\n\t/** Its export names; an ES module's exports must be known before it runs. */\n\treadonly names: ReadonlyArray<string>;\n\treadonly load: () => Promise<Record<string, unknown>>;\n}\n\n/**\n * A shared package's modules by specifier (`effect/Schema`), published on\n * `globalThis[Symbol.for(key)]` by a host that is a single bundled file, such as the standalone\n * binary. Such a host has no `effect` on disk to resolve to, so plugins get virtual modules that\n * re-export its own instances. Modules load on first import: `effect` alone has hundreds.\n */\nexport type SharedRegistry = Readonly<Record<string, SharedModule>>;\n\nconst sharedScheme = \"codeworkshared:\";\n\nfunction registryOf(key: string): SharedRegistry | undefined {\n\treturn (globalThis as Record<symbol, SharedRegistry | undefined>)[Symbol.for(key)];\n}\n\n/** Publish a bundled host's registries, by package name, before any plugin loads. */\nexport function share(packages: Readonly<Record<string, SharedRegistry>>): void {\n\tfor (const [name, registry] of Object.entries(packages)) {\n\t\tconst key = sharedPackages.get(name);\n\t\tif (key === undefined) throw new Error(`${name} is not a package shared with plugins`);\n\t\t(globalThis as Record<symbol, SharedRegistry>)[Symbol.for(key)] = registry;\n\t}\n}\n\n/** A virtual module re-exporting the host's instance of `specifier`. */\nfunction sharedSource(key: string, specifier: string, names: ReadonlyArray<string>): string {\n\tconst registry = `globalThis[Symbol.for(${JSON.stringify(key)})]`;\n\treturn [\n\t\t`const m = await ${registry}[${JSON.stringify(specifier)}].load();`,\n\t\t...names.map((name, index) => `const $${index} = m[${JSON.stringify(name)}];`),\n\t\t// String export names, since some are reserved words (`Effect.void`).\n\t\t`export { ${names.map((name, index) => `$${index} as ${JSON.stringify(name)}`).join(\", \")} };`,\n\t].join(\"\\n\");\n}\n\n/** The package a bare specifier names: `effect/Schema` -> `effect`, `@a/b/c` -> `@a/b`. */\nfunction packageOf(specifier: string): string {\n\tif (specifier.startsWith(\".\") || specifier.startsWith(\"/\") || specifier.includes(\":\")) return \"\";\n\tconst segments = specifier.split(\"/\");\n\treturn specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : (segments[0] ?? \"\");\n}\n\n/**\n * Resolve the shared packages to the host's own instances, for as long as `run` takes: from its\n * registry when it published one, otherwise as though this module had imported them. Anything\n * else resolves exactly as it would have.\n */\nasync function withSharedModules<A>(run: () => Promise<A>): Promise<A> {\n\tconst hook = registerHooks({\n\t\tresolve(specifier, context, nextResolve) {\n\t\t\tconst key = sharedPackages.get(packageOf(specifier));\n\t\t\tif (key === undefined) return nextResolve(specifier, context);\n\t\t\tconst registry = registryOf(key);\n\t\t\tif (registry === undefined) return nextResolve(specifier, { ...context, parentURL: import.meta.url });\n\t\t\t// Falling back to the plugin's own copy would bring back the two-instance failure above.\n\t\t\tif (!Object.hasOwn(registry, specifier)) throw new Error(`${specifier} is not shared with plugins`);\n\t\t\treturn { url: `${sharedScheme}${specifier}`, shortCircuit: true };\n\t\t},\n\t\tload(url, context, nextLoad) {\n\t\t\tif (!url.startsWith(sharedScheme)) return nextLoad(url, context);\n\t\t\tconst specifier = url.slice(sharedScheme.length);\n\t\t\tconst key = sharedPackages.get(packageOf(specifier))!;\n\t\t\tconst shared = registryOf(key)![specifier]!;\n\t\t\treturn { format: \"module\", source: sharedSource(key, specifier, shared.names), shortCircuit: true };\n\t\t},\n\t});\n\ttry {\n\t\treturn await run();\n\t} finally {\n\t\thook.deregister();\n\t}\n}\n\n/** Use Node's main loader even when the caller runs inside a bundler or test VM. */\nexport async function importModule(specifier: string): Promise<unknown> {\n\tconst imported: unknown = await withSharedModules(\n\t\t() =>\n\t\t\tnew Script(`import(${JSON.stringify(specifier)})`, {\n\t\t\t\timportModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,\n\t\t\t}).runInThisContext() as Promise<unknown>,\n\t);\n\tif (typeof imported !== \"object\" || imported === null) return imported;\n\tconst module = imported as Record<string, unknown>;\n\tconst exports = module[\"module.exports\"];\n\tif (exports !== module.default || (typeof exports !== \"object\" && typeof exports !== \"function\") || exports === null)\n\t\treturn imported;\n\treturn Object.assign({}, module, exports);\n}\n\n/**\n * `import.meta.resolve`. The main module of a single executable application, the standalone\n * binary, has none, and its own `import()` reaches only built-ins: there the host calls\n * {@link lendResolve} before anything resolves.\n */\nlet metaResolve = (specifier: string): string => import.meta.resolve(specifier);\n\n/**\n * Borrow `import.meta.resolve` from a `data:` module loaded through the main loader, when this\n * module has none. Not done at the top level: the binary bundles this module into an import cycle,\n * where a top-level `await` never settles.\n */\nexport async function lendResolve(): Promise<void> {\n\tif (typeof import.meta.resolve === \"function\") return;\n\tconst lender = (await importModule(\"data:text/javascript,export default (s) => import.meta.resolve(s)\")) as {\n\t\treadonly default: (specifier: string) => string;\n\t};\n\tmetaResolve = lender.default;\n}\n\n/** Node resolution scoped synchronously to the caller. */\nexport function resolveModule(specifier: string, directory: string, conditions?: ReadonlyArray<string>): string {\n\tconst hook = registerHooks({\n\t\tresolve(target, context, nextResolve) {\n\t\t\treturn nextResolve(target, {\n\t\t\t\t...context,\n\t\t\t\tparentURL: pathToFileURL(path.join(directory, \"package.json\")).href,\n\t\t\t\t...(conditions === undefined ? {} : { conditions: [...new Set([...context.conditions, ...conditions])] }),\n\t\t\t});\n\t\t},\n\t});\n\ttry {\n\t\tconst resolve = (target: string) => {\n\t\t\tconst resolved = metaResolve(path.isAbsolute(target) ? pathToFileURL(target).href : target);\n\t\t\tif (resolved.startsWith(\"file:\")) statSync(new URL(resolved));\n\t\t\treturn resolved;\n\t\t};\n\t\ttry {\n\t\t\treturn resolve(specifier);\n\t\t} catch (error) {\n\t\t\tif (path.extname(specifier) || !missing(error)) throw error;\n\t\t\tfor (const extension of [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\", \".cts\", \".cjs\"]) {\n\t\t\t\ttry {\n\t\t\t\t\treturn resolve(specifier + extension);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tif (!missing(cause)) throw cause;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t} finally {\n\t\thook.deregister();\n\t}\n}\n\nfunction missing(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t\"code\" in error &&\n\t\t[\"ENOENT\", \"ENOTDIR\", \"ERR_MODULE_NOT_FOUND\"].includes(String(error.code))\n\t);\n}\n","import { type Cause, Config, Effect, Option } from \"effect\";\nimport { importModule, resolveModule } from \"./module.ts\";\n\n/**\n * Import a package that reads files from beside its own modules (WASM, workers, native addons),\n * so cannot be bundled. The standalone binary unpacks such packages into\n * `CODEWORK_PACKAGES/node_modules`; anywhere else they resolve from here as usual.\n */\nexport const load = (name: string): Effect.Effect<unknown, Cause.UnknownError> =>\n\tEffect.gen(function* () {\n\t\tconst directory = yield* Config.option(Config.String(\"CODEWORK_PACKAGES\")).pipe(Effect.orDie);\n\t\tconst url = Option.isNone(directory)\n\t\t\t? import.meta.resolve(name)\n\t\t\t: yield* Effect.try(() => resolveModule(name, directory.value));\n\t\t// The binary's own `import()` reaches only built-ins.\n\t\treturn yield* Effect.tryPromise(() => importModule(url));\n\t});\n","import type { Photon, PhotonImage } from \"./photon.ts\";\n\n/**\n * EXIF orientation for JPEG and WebP. Photon decodes pixels as stored, so a phone\n * photo taken sideways would reach the model sideways without this.\n */\n\nconst readOrientationFromTiff = (bytes: Uint8Array, tiffStart: number): number => {\n\tif (tiffStart + 8 > bytes.length) return 1;\n\tconst le = ((byte(bytes, tiffStart) << 8) | byte(bytes, tiffStart + 1)) === 0x4949;\n\tconst read16 = (pos: number): number =>\n\t\tle ? byte(bytes, pos) | (byte(bytes, pos + 1) << 8) : (byte(bytes, pos) << 8) | byte(bytes, pos + 1);\n\tconst read32 = (pos: number): number =>\n\t\tle\n\t\t\t? (byte(bytes, pos) |\n\t\t\t\t\t(byte(bytes, pos + 1) << 8) |\n\t\t\t\t\t(byte(bytes, pos + 2) << 16) |\n\t\t\t\t\t(byte(bytes, pos + 3) << 24)) >>>\n\t\t\t\t0\n\t\t\t: ((byte(bytes, pos) << 24) |\n\t\t\t\t\t(byte(bytes, pos + 1) << 16) |\n\t\t\t\t\t(byte(bytes, pos + 2) << 8) |\n\t\t\t\t\tbyte(bytes, pos + 3)) >>>\n\t\t\t\t0;\n\n\tconst ifdStart = tiffStart + read32(tiffStart + 4);\n\tif (ifdStart + 2 > bytes.length) return 1;\n\tconst entryCount = read16(ifdStart);\n\tfor (let index = 0; index < entryCount; index++) {\n\t\tconst entryPos = ifdStart + 2 + index * 12;\n\t\tif (entryPos + 12 > bytes.length) return 1;\n\t\tif (read16(entryPos) === 0x0112) {\n\t\t\tconst value = read16(entryPos + 8);\n\t\t\treturn value >= 1 && value <= 8 ? value : 1;\n\t\t}\n\t}\n\treturn 1;\n};\n\nconst findJpegTiffOffset = (bytes: Uint8Array): number => {\n\tlet offset = 2;\n\twhile (offset < bytes.length - 1) {\n\t\tif (bytes[offset] !== 0xff) return -1;\n\t\tconst marker = bytes[offset + 1];\n\t\tif (marker === 0xff) {\n\t\t\toffset++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (marker === 0xe1) {\n\t\t\tconst segmentStart = offset + 4;\n\t\t\tif (segmentStart + 6 > bytes.length) return -1;\n\t\t\tif (hasExifHeader(bytes, segmentStart)) return segmentStart + 6;\n\t\t}\n\t\tif (offset + 4 > bytes.length) return -1;\n\t\toffset += 2 + ((byte(bytes, offset + 2) << 8) | byte(bytes, offset + 3));\n\t}\n\treturn -1;\n};\n\nconst findWebpTiffOffset = (bytes: Uint8Array): number => {\n\tlet offset = 12;\n\twhile (offset + 8 <= bytes.length) {\n\t\tconst chunkId = String.fromCharCode(...bytes.subarray(offset, offset + 4));\n\t\tconst chunkSize =\n\t\t\tbyte(bytes, offset + 4) |\n\t\t\t(byte(bytes, offset + 5) << 8) |\n\t\t\t(byte(bytes, offset + 6) << 16) |\n\t\t\t(byte(bytes, offset + 7) << 24);\n\t\tconst dataStart = offset + 8;\n\t\tif (chunkId === \"EXIF\") {\n\t\t\tif (dataStart + chunkSize > bytes.length) return -1;\n\t\t\t// Some WebP files carry an \"Exif\\0\\0\" prefix before the TIFF header.\n\t\t\treturn chunkSize >= 6 && hasExifHeader(bytes, dataStart) ? dataStart + 6 : dataStart;\n\t\t}\n\t\t// RIFF chunks are padded to an even size.\n\t\toffset = dataStart + chunkSize + (chunkSize % 2);\n\t}\n\treturn -1;\n};\n\nconst hasExifHeader = (bytes: Uint8Array, offset: number): boolean =>\n\t[0x45, 0x78, 0x69, 0x66, 0x00, 0x00].every((value, index) => bytes[offset + index] === value);\n\nconst orientationOf = (bytes: Uint8Array): number => {\n\tlet tiffOffset = -1;\n\tif (bytes[0] === 0xff && bytes[1] === 0xd8) tiffOffset = findJpegTiffOffset(bytes);\n\telse if (\n\t\tString.fromCharCode(...bytes.subarray(0, 4)) === \"RIFF\" &&\n\t\tString.fromCharCode(...bytes.subarray(8, 12)) === \"WEBP\"\n\t)\n\t\ttiffOffset = findWebpTiffOffset(bytes);\n\treturn tiffOffset === -1 ? 1 : readOrientationFromTiff(bytes, tiffOffset);\n};\n\nconst byte = (bytes: Uint8Array, index: number): number => bytes[index] ?? 0;\n\ntype DstIndex = (x: number, y: number, w: number, h: number) => number;\n\nconst rotate90 = (photon: Photon, image: PhotonImage, dstIndex: DstIndex): PhotonImage => {\n\tconst w = image.get_width();\n\tconst h = image.get_height();\n\tconst src = image.get_raw_pixels();\n\tconst dst = new Uint8Array(src.length);\n\tfor (let y = 0; y < h; y++) {\n\t\tfor (let x = 0; x < w; x++) {\n\t\t\tdst.set(src.subarray((y * w + x) * 4, (y * w + x) * 4 + 4), dstIndex(x, y, w, h) * 4);\n\t\t}\n\t}\n\treturn new photon.PhotonImage(dst, h, w);\n};\n\nconst clockwise: DstIndex = (x, y, _w, h) => x * h + (h - 1 - y);\nconst counterClockwise: DstIndex = (x, y, w, h) => (w - 1 - x) * h + y;\n\n/** Flips mutate `image`; rotations return a new image, which the caller frees alongside the old one. */\nexport const applyOrientation = (photon: Photon, image: PhotonImage, originalBytes: Uint8Array): PhotonImage => {\n\tswitch (orientationOf(originalBytes)) {\n\t\tcase 2:\n\t\t\tphoton.fliph(image);\n\t\t\treturn image;\n\t\tcase 3:\n\t\t\tphoton.fliph(image);\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 4:\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 5: {\n\t\t\tconst rotated = rotate90(photon, image, clockwise);\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 6:\n\t\t\treturn rotate90(photon, image, clockwise);\n\t\tcase 7: {\n\t\t\tconst rotated = rotate90(photon, image, counterClockwise);\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 8:\n\t\t\treturn rotate90(photon, image, counterClockwise);\n\t\tdefault:\n\t\t\treturn image;\n\t}\n};\n","import { Effect } from \"effect\";\nimport { load as unpacked } from \"../../util/unpacked.ts\";\nimport { applyOrientation } from \"./exif.ts\";\n\nexport type Photon = typeof import(\"@silvia-odwyer/photon-node\");\nexport type PhotonImage = import(\"@silvia-odwyer/photon-node\").PhotonImage;\n\n/** Photon, loaded once on first use; `undefined` when its WASM cannot load, so images degrade instead of failing reads. */\nexport const load: Effect.Effect<Photon | undefined> = Effect.cached(\n\tunpacked(\"@silvia-odwyer/photon-node\").pipe(\n\t\tEffect.map((module) => module as Photon),\n\t\tEffect.orElseSucceed(() => undefined),\n\t),\n).pipe(Effect.runSync);\n\n/** Decode with EXIF orientation applied. The caller frees the result. */\nexport const decode = (photon: Photon, bytes: Uint8Array): PhotonImage => {\n\tconst raw = photon.PhotonImage.new_from_byteslice(bytes);\n\tconst oriented = applyOrientation(photon, raw, bytes);\n\tif (oriented !== raw) raw.free();\n\treturn oriented;\n};\n","import { Config, Effect, Option, Schema } from \"effect\";\nimport { pathToFileURL } from \"node:url\";\nimport { Worker } from \"node:worker_threads\";\nimport { decode, load } from \"./photon.ts\";\n\nexport interface ResizeOptions {\n\treadonly maxWidth: number;\n\treadonly maxHeight: number;\n\t/** Most bytes of base64 payload. */\n\treadonly maxBytes: number;\n\treadonly jpegQuality: number;\n}\n\nexport interface Resized {\n\t/** base64 */\n\treadonly data: string;\n\treadonly mimeType: string;\n\treadonly originalWidth: number;\n\treadonly originalHeight: number;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly wasResized: boolean;\n}\n\n// 4.5MB of base64 leaves headroom below Anthropic's 5MB image limit.\nexport const defaults: ResizeOptions = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: 4.5 * 1024 * 1024,\n\tjpegQuality: 80,\n};\n\n/** Tags worker replies: Node posts its own messages on the worker channel too (e.g. under `--watch`). */\nexport const REPLY = \"codework:photon-image-resize\";\n\nexport type Reply = { type: typeof REPLY; result: Resized | null } | { type: typeof REPLY; error: string };\n\nconst base64 = (bytes: Uint8Array) => {\n\tconst data = Buffer.from(bytes).toString(\"base64\");\n\treturn { data, size: data.length };\n};\n\n/**\n * Fit an image within the dimensions and encoded size, in this thread. `null`\n * when Photon is unavailable or nothing fits. Fits by: scaling to the max\n * dimensions, keeping the smaller of PNG and JPEG, lowering JPEG quality, then\n * shrinking by a quarter at a time down to 1x1.\n */\nexport const resizeInProcess = (\n\tinput: Uint8Array,\n\tmimeType: string,\n\toptions: ResizeOptions = defaults,\n): Effect.Effect<Resized | null> =>\n\tEffect.map(load, (photon) => {\n\t\tif (photon === undefined) return null;\n\t\tlet image: ReturnType<typeof decode> | undefined;\n\t\ttry {\n\t\t\timage = decode(photon, input);\n\t\t\tconst originalWidth = image.get_width();\n\t\t\tconst originalHeight = image.get_height();\n\t\t\tconst inputSize = Math.ceil(input.byteLength / 3) * 4;\n\t\t\tif (originalWidth <= options.maxWidth && originalHeight <= options.maxHeight && inputSize < options.maxBytes) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: Buffer.from(input).toString(\"base64\"),\n\t\t\t\t\tmimeType,\n\t\t\t\t\toriginalWidth,\n\t\t\t\t\toriginalHeight,\n\t\t\t\t\twidth: originalWidth,\n\t\t\t\t\theight: originalHeight,\n\t\t\t\t\twasResized: false,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// A side never scales below one pixel, or a thin image would vanish.\n\t\t\tlet width = originalWidth;\n\t\t\tlet height = originalHeight;\n\t\t\tif (width > options.maxWidth) {\n\t\t\t\theight = Math.max(1, Math.round((height * options.maxWidth) / width));\n\t\t\t\twidth = options.maxWidth;\n\t\t\t}\n\t\t\tif (height > options.maxHeight) {\n\t\t\t\twidth = Math.max(1, Math.round((width * options.maxHeight) / height));\n\t\t\t\theight = options.maxHeight;\n\t\t\t}\n\n\t\t\tconst qualities = [...new Set([options.jpegQuality, 85, 70, 55, 40])];\n\t\t\twhile (true) {\n\t\t\t\tconst resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);\n\t\t\t\ttry {\n\t\t\t\t\tconst candidates = [\n\t\t\t\t\t\t{ ...base64(resized.get_bytes()), mimeType: \"image/png\" },\n\t\t\t\t\t\t...qualities.map((quality) => ({\n\t\t\t\t\t\t\t...base64(resized.get_bytes_jpeg(quality)),\n\t\t\t\t\t\t\tmimeType: \"image/jpeg\",\n\t\t\t\t\t\t})),\n\t\t\t\t\t];\n\t\t\t\t\tconst fit = candidates.find((candidate) => candidate.size < options.maxBytes);\n\t\t\t\t\tif (fit !== undefined) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tdata: fit.data,\n\t\t\t\t\t\t\tmimeType: fit.mimeType,\n\t\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\t\twidth,\n\t\t\t\t\t\t\theight,\n\t\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tresized.free();\n\t\t\t\t}\n\t\t\t\tconst nextWidth = Math.max(1, Math.floor(width * 0.75));\n\t\t\t\tconst nextHeight = Math.max(1, Math.floor(height * 0.75));\n\t\t\t\tif (nextWidth === width && nextHeight === height) return null;\n\t\t\t\twidth = nextWidth;\n\t\t\t\theight = nextHeight;\n\t\t\t}\n\t\t} catch {\n\t\t\treturn null;\n\t\t} finally {\n\t\t\timage?.free();\n\t\t}\n\t});\n\n// From source the worker sits beside this module; packed, this module lands in a\n// chunk at the package's output root while the worker keeps its own entry path. The\n// standalone binary unpacks a bundled worker and names it.\nconst workerUrl = Effect.gen(function* () {\n\tconst unpacked = yield* Config.option(Config.String(\"CODEWORK_IMAGE_WORKER\"));\n\tif (Option.isSome(unpacked)) return pathToFileURL(unpacked.value);\n\treturn import.meta.url.endsWith(\".ts\")\n\t\t? new URL(\"./worker.ts\", import.meta.url)\n\t\t: new URL(\"./tool/image/worker.mjs\", import.meta.url);\n}).pipe(Effect.orDie);\n\n/** The worker could not resize; the caller falls back to this thread. */\nclass WorkerError extends Schema.TaggedError<WorkerError>()(\"ImageResizeWorkerError\", { message: Schema.String }) {}\n\nconst inWorker = (input: Uint8Array, mimeType: string, options: ResizeOptions) =>\n\tEffect.flatMap(workerUrl, (url) =>\n\t\tEffect.callback<Resized | null, WorkerError>((resume) => {\n\t\t\tlet worker: Worker;\n\t\t\ttry {\n\t\t\t\tworker = new Worker(url);\n\t\t\t} catch (cause) {\n\t\t\t\t// e.g. a Node permission model without worker access: resize in this thread instead.\n\t\t\t\tresume(Effect.fail(new WorkerError({ message: String(cause) })));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst done = (effect: Effect.Effect<Resized | null, WorkerError>) => {\n\t\t\t\tresume(effect);\n\t\t\t\tvoid worker.terminate().catch(() => undefined);\n\t\t\t};\n\t\t\tworker.on(\"message\", (message: unknown) => {\n\t\t\t\tconst reply = message as Partial<Reply> | null;\n\t\t\t\tif (reply?.type !== REPLY) return;\n\t\t\t\tdone(\n\t\t\t\t\t\"error\" in reply\n\t\t\t\t\t\t? Effect.fail(new WorkerError({ message: reply.error }))\n\t\t\t\t\t\t: Effect.succeed((reply as { result: Resized | null }).result),\n\t\t\t\t);\n\t\t\t});\n\t\t\tworker.once(\"error\", (error: Error) => done(Effect.fail(new WorkerError({ message: error.message }))));\n\t\t\tworker.once(\"exit\", (code) =>\n\t\t\t\tdone(Effect.fail(new WorkerError({ message: `Image resize worker exited with code ${code}` }))),\n\t\t\t);\n\t\t\t// Transferring detaches the buffer, so hand over a copy and leave the caller's bytes intact.\n\t\t\tconst bytes = new Uint8Array(input);\n\t\t\tworker.postMessage({ input: bytes, mimeType, options }, [bytes.buffer]);\n\t\t\treturn Effect.promise(() => worker.terminate());\n\t\t}),\n\t);\n\n/**\n * {@link resizeInProcess} on a worker thread, so decoding and encoding a large\n * image never blocks the harness's event loop. Falls back to this thread when a\n * worker cannot start, so a read still works.\n */\nexport const resize = (input: Uint8Array, mimeType: string, options: ResizeOptions = defaults) =>\n\tinWorker(input, mimeType, options).pipe(Effect.catch(() => resizeInProcess(input, mimeType, options)));\n\n/** Tells the model how to map coordinates on a resized image back to the original. */\nexport const dimensionNote = (result: Resized): string | undefined => {\n\tif (!result.wasResized) return undefined;\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,iCAA8C,IAAI,IAAI,CAC3D,CAAC,UAAU,oBAAoB,GAC/B,CAAC,sBAAsB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AU,OAAmB,UAAkB,UAAyB,aACpF,SAAS,OAAO,UAAU,OAAO,CAAC,CAAC,KAAK,OAAO,YAAY,gBAAgB,OAAO,UAAU,OAAO,CAAC,CAAC;;AAGtG,MAAa,iBAAiB,WAAwC;CACrE,IAAI,CAAC,OAAO,YAAY,OAAO,KAAA;CAC/B,MAAM,QAAQ,OAAO,gBAAgB,OAAO;CAC5C,OAAO,oBAAoB,OAAO,cAAc,GAAG,OAAO,eAAe,iBAAiB,OAAO,MAAM,GAAG,OAAO,OAAO,4BAA4B,MAAM,QAAQ,CAAC,EAAE;AACtK"}
1
+ {"version":3,"file":"resize-BUdJMHgx.mjs","names":["load","unpacked"],"sources":["../../src/util/module.ts","../../src/util/unpacked.ts","../../src/tool/image/exif.ts","../../src/tool/image/photon.ts","../../src/tool/image/resize.ts"],"sourcesContent":["/*!\n * Adapted from OpenCode packages/util/src/runtime/import.node.ts.\n *\n * MIT License\n *\n * Copyright (c) 2025 opencode\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n/* oxlint-disable effecttsgo/async-function -- Native module loading exposes a Promise-based importer contract. */\n// Resolution hooks cannot yield to Effect; existence checks must stay synchronous.\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport { statSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { Script, constants } from \"node:vm\";\n\n/**\n * Packages a plugin must share with the harness instead of using the copy installed beside it.\n *\n * A plugin is installed into the store as its own npm tree, so `effect` and the plugin SDK land\n * there a second time. Two copies of the *same version* are still two module instances, and\n * Effect Schema's checks do not survive the crossing: a schema built by one copy and evaluated by\n * the other reports every check as failed, so a tool whose success type is `Schema.Finite` dies\n * on \"Expected a finite number\" for `22800`. Nothing about that is visible at registration --\n * `Schema.isSchema` passes, the JSON Schema is derived correctly, and the tool reaches the model\n * -- so it surfaces on the first call rather than at boot.\n *\n * Resolution is the right place to fix it. A symlink into the store cannot be: a generation is\n * immutable and shared by every project on the machine, while the harness doing the loading is\n * whichever one is running now, and two applications embedding the harness need not agree on\n * where their `effect` lives.\n *\n * Each package maps to the `Symbol.for` key of its {@link SharedRegistry}.\n */\nconst sharedPackages: ReadonlyMap<string, string> = new Map([\n\t[\"effect\", \"codework.v1.effect\"],\n\t[\"@codeworksh/plugin\", \"codework.v1.plugin\"],\n]);\n\n/** One module of a shared package, as a bundled host publishes it. */\nexport interface SharedModule {\n\t/** Its export names; an ES module's exports must be known before it runs. */\n\treadonly names: ReadonlyArray<string>;\n\treadonly load: () => Promise<Record<string, unknown>>;\n}\n\n/**\n * A shared package's modules by specifier (`effect/Schema`), published on\n * `globalThis[Symbol.for(key)]` by a host that is a single bundled file, such as the standalone\n * binary. Such a host has no `effect` on disk to resolve to, so plugins get virtual modules that\n * re-export its own instances. Modules load on first import: `effect` alone has hundreds.\n */\nexport type SharedRegistry = Readonly<Record<string, SharedModule>>;\n\nconst sharedScheme = \"codeworkshared:\";\n\nfunction registryOf(key: string): SharedRegistry | undefined {\n\treturn (globalThis as Record<symbol, SharedRegistry | undefined>)[Symbol.for(key)];\n}\n\n/** Publish a bundled host's registries, by package name, before any plugin loads. */\nexport function share(packages: Readonly<Record<string, SharedRegistry>>): void {\n\tfor (const [name, registry] of Object.entries(packages)) {\n\t\tconst key = sharedPackages.get(name);\n\t\tif (key === undefined) throw new Error(`${name} is not a package shared with plugins`);\n\t\t(globalThis as Record<symbol, SharedRegistry>)[Symbol.for(key)] = registry;\n\t}\n}\n\n/** A virtual module re-exporting the host's instance of `specifier`. */\nfunction sharedSource(key: string, specifier: string, names: ReadonlyArray<string>): string {\n\tconst registry = `globalThis[Symbol.for(${JSON.stringify(key)})]`;\n\treturn [\n\t\t`const m = await ${registry}[${JSON.stringify(specifier)}].load();`,\n\t\t...names.map((name, index) => `const $${index} = m[${JSON.stringify(name)}];`),\n\t\t// String export names, since some are reserved words (`Effect.void`).\n\t\t`export { ${names.map((name, index) => `$${index} as ${JSON.stringify(name)}`).join(\", \")} };`,\n\t].join(\"\\n\");\n}\n\n/** The package a bare specifier names: `effect/Schema` -> `effect`, `@a/b/c` -> `@a/b`. */\nfunction packageOf(specifier: string): string {\n\tif (specifier.startsWith(\".\") || specifier.startsWith(\"/\") || specifier.includes(\":\")) return \"\";\n\tconst segments = specifier.split(\"/\");\n\treturn specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : (segments[0] ?? \"\");\n}\n\n/**\n * Resolve the shared packages to the host's own instances, for as long as `run` takes: from its\n * registry when it published one, otherwise as though this module had imported them. Anything\n * else resolves exactly as it would have.\n */\nasync function withSharedModules<A>(run: () => Promise<A>): Promise<A> {\n\tconst hook = registerHooks({\n\t\tresolve(specifier, context, nextResolve) {\n\t\t\tconst key = sharedPackages.get(packageOf(specifier));\n\t\t\tif (key === undefined) return nextResolve(specifier, context);\n\t\t\tconst registry = registryOf(key);\n\t\t\tif (registry === undefined) return nextResolve(specifier, { ...context, parentURL: import.meta.url });\n\t\t\t// Falling back to the plugin's own copy would bring back the two-instance failure above.\n\t\t\tif (!Object.hasOwn(registry, specifier)) throw new Error(`${specifier} is not shared with plugins`);\n\t\t\treturn { url: `${sharedScheme}${specifier}`, shortCircuit: true };\n\t\t},\n\t\tload(url, context, nextLoad) {\n\t\t\tif (!url.startsWith(sharedScheme)) return nextLoad(url, context);\n\t\t\tconst specifier = url.slice(sharedScheme.length);\n\t\t\tconst key = sharedPackages.get(packageOf(specifier))!;\n\t\t\tconst shared = registryOf(key)![specifier]!;\n\t\t\treturn { format: \"module\", source: sharedSource(key, specifier, shared.names), shortCircuit: true };\n\t\t},\n\t});\n\ttry {\n\t\treturn await run();\n\t} finally {\n\t\thook.deregister();\n\t}\n}\n\n/** Use Node's main loader even when the caller runs inside a bundler or test VM. */\nexport async function importModule(specifier: string): Promise<unknown> {\n\tconst imported: unknown = await withSharedModules(\n\t\t() =>\n\t\t\tnew Script(`import(${JSON.stringify(specifier)})`, {\n\t\t\t\timportModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,\n\t\t\t}).runInThisContext() as Promise<unknown>,\n\t);\n\tif (typeof imported !== \"object\" || imported === null) return imported;\n\tconst module = imported as Record<string, unknown>;\n\tconst exports = module[\"module.exports\"];\n\tif (exports !== module.default || (typeof exports !== \"object\" && typeof exports !== \"function\") || exports === null)\n\t\treturn imported;\n\treturn Object.assign({}, module, exports);\n}\n\n/**\n * `import.meta.resolve`. The main module of a single executable application, the standalone\n * binary, has none, and its own `import()` reaches only built-ins: there the host calls\n * {@link lendResolve} before anything resolves.\n */\nlet metaResolve = (specifier: string): string => import.meta.resolve(specifier);\n\n/**\n * Borrow `import.meta.resolve` from a `data:` module loaded through the main loader, when this\n * module has none. Not done at the top level: the binary bundles this module into an import cycle,\n * where a top-level `await` never settles.\n */\nexport async function lendResolve(): Promise<void> {\n\tif (typeof import.meta.resolve === \"function\") return;\n\tconst lender = (await importModule(\"data:text/javascript,export default (s) => import.meta.resolve(s)\")) as {\n\t\treadonly default: (specifier: string) => string;\n\t};\n\tmetaResolve = lender.default;\n}\n\n/** Node resolution scoped synchronously to the caller. */\nexport function resolveModule(specifier: string, directory: string, conditions?: ReadonlyArray<string>): string {\n\tconst hook = registerHooks({\n\t\tresolve(target, context, nextResolve) {\n\t\t\treturn nextResolve(target, {\n\t\t\t\t...context,\n\t\t\t\tparentURL: pathToFileURL(path.join(directory, \"package.json\")).href,\n\t\t\t\t...(conditions === undefined ? {} : { conditions: [...new Set([...context.conditions, ...conditions])] }),\n\t\t\t});\n\t\t},\n\t});\n\ttry {\n\t\tconst resolve = (target: string) => {\n\t\t\tconst resolved = metaResolve(path.isAbsolute(target) ? pathToFileURL(target).href : target);\n\t\t\tif (resolved.startsWith(\"file:\")) statSync(new URL(resolved));\n\t\t\treturn resolved;\n\t\t};\n\t\ttry {\n\t\t\treturn resolve(specifier);\n\t\t} catch (error) {\n\t\t\tif (path.extname(specifier) || !missing(error)) throw error;\n\t\t\tfor (const extension of [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\", \".cts\", \".cjs\"]) {\n\t\t\t\ttry {\n\t\t\t\t\treturn resolve(specifier + extension);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tif (!missing(cause)) throw cause;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t} finally {\n\t\thook.deregister();\n\t}\n}\n\nfunction missing(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t\"code\" in error &&\n\t\t[\"ENOENT\", \"ENOTDIR\", \"ERR_MODULE_NOT_FOUND\"].includes(String(error.code))\n\t);\n}\n","import { type Cause, Config, Effect, Option } from \"effect\";\nimport { importModule, resolveModule } from \"./module.ts\";\n\n/**\n * Import a package that reads files from beside its own modules (WASM, workers, native addons),\n * so cannot be bundled. The standalone binary unpacks such packages into\n * `CODEWORK_PACKAGES/node_modules`; anywhere else they resolve from here as usual.\n */\nexport const load = (name: string): Effect.Effect<unknown, Cause.UnknownError> =>\n\tEffect.gen(function* () {\n\t\tconst directory = yield* Config.option(Config.String(\"CODEWORK_PACKAGES\")).pipe(Effect.orDie);\n\t\tconst url = Option.isNone(directory)\n\t\t\t? import.meta.resolve(name)\n\t\t\t: yield* Effect.try(() => resolveModule(name, directory.value));\n\t\t// The binary's own `import()` reaches only built-ins.\n\t\treturn yield* Effect.tryPromise(() => importModule(url));\n\t});\n","import type { Photon, PhotonImage } from \"./photon.ts\";\n\n/**\n * EXIF orientation for JPEG and WebP. Photon decodes pixels as stored, so a phone\n * photo taken sideways would reach the model sideways without this.\n */\n\nconst readOrientationFromTiff = (bytes: Uint8Array, tiffStart: number): number => {\n\tif (tiffStart + 8 > bytes.length) return 1;\n\tconst le = ((byte(bytes, tiffStart) << 8) | byte(bytes, tiffStart + 1)) === 0x4949;\n\tconst read16 = (pos: number): number =>\n\t\tle ? byte(bytes, pos) | (byte(bytes, pos + 1) << 8) : (byte(bytes, pos) << 8) | byte(bytes, pos + 1);\n\tconst read32 = (pos: number): number =>\n\t\tle\n\t\t\t? (byte(bytes, pos) |\n\t\t\t\t\t(byte(bytes, pos + 1) << 8) |\n\t\t\t\t\t(byte(bytes, pos + 2) << 16) |\n\t\t\t\t\t(byte(bytes, pos + 3) << 24)) >>>\n\t\t\t\t0\n\t\t\t: ((byte(bytes, pos) << 24) |\n\t\t\t\t\t(byte(bytes, pos + 1) << 16) |\n\t\t\t\t\t(byte(bytes, pos + 2) << 8) |\n\t\t\t\t\tbyte(bytes, pos + 3)) >>>\n\t\t\t\t0;\n\n\tconst ifdStart = tiffStart + read32(tiffStart + 4);\n\tif (ifdStart + 2 > bytes.length) return 1;\n\tconst entryCount = read16(ifdStart);\n\tfor (let index = 0; index < entryCount; index++) {\n\t\tconst entryPos = ifdStart + 2 + index * 12;\n\t\tif (entryPos + 12 > bytes.length) return 1;\n\t\tif (read16(entryPos) === 0x0112) {\n\t\t\tconst value = read16(entryPos + 8);\n\t\t\treturn value >= 1 && value <= 8 ? value : 1;\n\t\t}\n\t}\n\treturn 1;\n};\n\nconst findJpegTiffOffset = (bytes: Uint8Array): number => {\n\tlet offset = 2;\n\twhile (offset < bytes.length - 1) {\n\t\tif (bytes[offset] !== 0xff) return -1;\n\t\tconst marker = bytes[offset + 1];\n\t\tif (marker === 0xff) {\n\t\t\toffset++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (marker === 0xe1) {\n\t\t\tconst segmentStart = offset + 4;\n\t\t\tif (segmentStart + 6 > bytes.length) return -1;\n\t\t\tif (hasExifHeader(bytes, segmentStart)) return segmentStart + 6;\n\t\t}\n\t\tif (offset + 4 > bytes.length) return -1;\n\t\toffset += 2 + ((byte(bytes, offset + 2) << 8) | byte(bytes, offset + 3));\n\t}\n\treturn -1;\n};\n\nconst findWebpTiffOffset = (bytes: Uint8Array): number => {\n\tlet offset = 12;\n\twhile (offset + 8 <= bytes.length) {\n\t\tconst chunkId = String.fromCharCode(...bytes.subarray(offset, offset + 4));\n\t\tconst chunkSize =\n\t\t\tbyte(bytes, offset + 4) |\n\t\t\t(byte(bytes, offset + 5) << 8) |\n\t\t\t(byte(bytes, offset + 6) << 16) |\n\t\t\t(byte(bytes, offset + 7) << 24);\n\t\tconst dataStart = offset + 8;\n\t\tif (chunkId === \"EXIF\") {\n\t\t\tif (dataStart + chunkSize > bytes.length) return -1;\n\t\t\t// Some WebP files carry an \"Exif\\0\\0\" prefix before the TIFF header.\n\t\t\treturn chunkSize >= 6 && hasExifHeader(bytes, dataStart) ? dataStart + 6 : dataStart;\n\t\t}\n\t\t// RIFF chunks are padded to an even size.\n\t\toffset = dataStart + chunkSize + (chunkSize % 2);\n\t}\n\treturn -1;\n};\n\nconst hasExifHeader = (bytes: Uint8Array, offset: number): boolean =>\n\t[0x45, 0x78, 0x69, 0x66, 0x00, 0x00].every((value, index) => bytes[offset + index] === value);\n\nconst orientationOf = (bytes: Uint8Array): number => {\n\tlet tiffOffset = -1;\n\tif (bytes[0] === 0xff && bytes[1] === 0xd8) tiffOffset = findJpegTiffOffset(bytes);\n\telse if (\n\t\tString.fromCharCode(...bytes.subarray(0, 4)) === \"RIFF\" &&\n\t\tString.fromCharCode(...bytes.subarray(8, 12)) === \"WEBP\"\n\t)\n\t\ttiffOffset = findWebpTiffOffset(bytes);\n\treturn tiffOffset === -1 ? 1 : readOrientationFromTiff(bytes, tiffOffset);\n};\n\nconst byte = (bytes: Uint8Array, index: number): number => bytes[index] ?? 0;\n\ntype DstIndex = (x: number, y: number, w: number, h: number) => number;\n\nconst rotate90 = (photon: Photon, image: PhotonImage, dstIndex: DstIndex): PhotonImage => {\n\tconst w = image.get_width();\n\tconst h = image.get_height();\n\tconst src = image.get_raw_pixels();\n\tconst dst = new Uint8Array(src.length);\n\tfor (let y = 0; y < h; y++) {\n\t\tfor (let x = 0; x < w; x++) {\n\t\t\tdst.set(src.subarray((y * w + x) * 4, (y * w + x) * 4 + 4), dstIndex(x, y, w, h) * 4);\n\t\t}\n\t}\n\treturn new photon.PhotonImage(dst, h, w);\n};\n\nconst clockwise: DstIndex = (x, y, _w, h) => x * h + (h - 1 - y);\nconst counterClockwise: DstIndex = (x, y, w, h) => (w - 1 - x) * h + y;\n\n/** Flips mutate `image`; rotations return a new image, which the caller frees alongside the old one. */\nexport const applyOrientation = (photon: Photon, image: PhotonImage, originalBytes: Uint8Array): PhotonImage => {\n\tswitch (orientationOf(originalBytes)) {\n\t\tcase 2:\n\t\t\tphoton.fliph(image);\n\t\t\treturn image;\n\t\tcase 3:\n\t\t\tphoton.fliph(image);\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 4:\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 5: {\n\t\t\tconst rotated = rotate90(photon, image, clockwise);\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 6:\n\t\t\treturn rotate90(photon, image, clockwise);\n\t\tcase 7: {\n\t\t\tconst rotated = rotate90(photon, image, counterClockwise);\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 8:\n\t\t\treturn rotate90(photon, image, counterClockwise);\n\t\tdefault:\n\t\t\treturn image;\n\t}\n};\n","import { Effect } from \"effect\";\nimport { load as unpacked } from \"../../util/unpacked.ts\";\nimport { applyOrientation } from \"./exif.ts\";\n\nexport type Photon = typeof import(\"@silvia-odwyer/photon-node\");\nexport type PhotonImage = import(\"@silvia-odwyer/photon-node\").PhotonImage;\n\n/** Photon, loaded once on first use; `undefined` when its WASM cannot load, so images degrade instead of failing reads. */\nexport const load: Effect.Effect<Photon | undefined> = Effect.cached(\n\tunpacked(\"@silvia-odwyer/photon-node\").pipe(\n\t\tEffect.map((module) => module as Photon),\n\t\tEffect.orElseSucceed(() => undefined),\n\t),\n).pipe(Effect.runSync);\n\n/** Decode with EXIF orientation applied. The caller frees the result. */\nexport const decode = (photon: Photon, bytes: Uint8Array): PhotonImage => {\n\tconst raw = photon.PhotonImage.new_from_byteslice(bytes);\n\tconst oriented = applyOrientation(photon, raw, bytes);\n\tif (oriented !== raw) raw.free();\n\treturn oriented;\n};\n","import { Config, Effect, Option, Schema } from \"effect\";\nimport { pathToFileURL } from \"node:url\";\nimport { Worker } from \"node:worker_threads\";\nimport { decode, load } from \"./photon.ts\";\n\nexport interface ResizeOptions {\n\treadonly maxWidth: number;\n\treadonly maxHeight: number;\n\t/** Most bytes of base64 payload. */\n\treadonly maxBytes: number;\n\treadonly jpegQuality: number;\n}\n\nexport interface Resized {\n\t/** base64 */\n\treadonly data: string;\n\treadonly mimeType: string;\n\treadonly originalWidth: number;\n\treadonly originalHeight: number;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly wasResized: boolean;\n}\n\n// 4.5MB of base64 leaves headroom below Anthropic's 5MB image limit.\nconst defaults: ResizeOptions = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: 4.5 * 1024 * 1024,\n\tjpegQuality: 80,\n};\n\n/** Tags worker replies: Node posts its own messages on the worker channel too (e.g. under `--watch`). */\nexport const REPLY = \"codework:photon-image-resize\";\n\nexport type Reply = { type: typeof REPLY; result: Resized | null } | { type: typeof REPLY; error: string };\n\nconst base64 = (bytes: Uint8Array) => {\n\tconst data = Buffer.from(bytes).toString(\"base64\");\n\treturn { data, size: data.length };\n};\n\n/**\n * Fit an image within the dimensions and encoded size, in this thread. `null`\n * when Photon is unavailable or nothing fits. Fits by: scaling to the max\n * dimensions, keeping the smaller of PNG and JPEG, lowering JPEG quality, then\n * shrinking by a quarter at a time down to 1x1.\n */\nexport const resizeInProcess = (\n\tinput: Uint8Array,\n\tmimeType: string,\n\toptions: ResizeOptions = defaults,\n): Effect.Effect<Resized | null> =>\n\tEffect.map(load, (photon) => {\n\t\tif (photon === undefined) return null;\n\t\tlet image: ReturnType<typeof decode> | undefined;\n\t\ttry {\n\t\t\timage = decode(photon, input);\n\t\t\tconst originalWidth = image.get_width();\n\t\t\tconst originalHeight = image.get_height();\n\t\t\tconst inputSize = Math.ceil(input.byteLength / 3) * 4;\n\t\t\tif (originalWidth <= options.maxWidth && originalHeight <= options.maxHeight && inputSize < options.maxBytes) {\n\t\t\t\treturn {\n\t\t\t\t\tdata: Buffer.from(input).toString(\"base64\"),\n\t\t\t\t\tmimeType,\n\t\t\t\t\toriginalWidth,\n\t\t\t\t\toriginalHeight,\n\t\t\t\t\twidth: originalWidth,\n\t\t\t\t\theight: originalHeight,\n\t\t\t\t\twasResized: false,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// A side never scales below one pixel, or a thin image would vanish.\n\t\t\tlet width = originalWidth;\n\t\t\tlet height = originalHeight;\n\t\t\tif (width > options.maxWidth) {\n\t\t\t\theight = Math.max(1, Math.round((height * options.maxWidth) / width));\n\t\t\t\twidth = options.maxWidth;\n\t\t\t}\n\t\t\tif (height > options.maxHeight) {\n\t\t\t\twidth = Math.max(1, Math.round((width * options.maxHeight) / height));\n\t\t\t\theight = options.maxHeight;\n\t\t\t}\n\n\t\t\tconst qualities = [...new Set([options.jpegQuality, 85, 70, 55, 40])];\n\t\t\twhile (true) {\n\t\t\t\tconst resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);\n\t\t\t\ttry {\n\t\t\t\t\tconst candidates = [\n\t\t\t\t\t\t{ ...base64(resized.get_bytes()), mimeType: \"image/png\" },\n\t\t\t\t\t\t...qualities.map((quality) => ({\n\t\t\t\t\t\t\t...base64(resized.get_bytes_jpeg(quality)),\n\t\t\t\t\t\t\tmimeType: \"image/jpeg\",\n\t\t\t\t\t\t})),\n\t\t\t\t\t];\n\t\t\t\t\tconst fit = candidates.find((candidate) => candidate.size < options.maxBytes);\n\t\t\t\t\tif (fit !== undefined) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tdata: fit.data,\n\t\t\t\t\t\t\tmimeType: fit.mimeType,\n\t\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\t\twidth,\n\t\t\t\t\t\t\theight,\n\t\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tresized.free();\n\t\t\t\t}\n\t\t\t\tconst nextWidth = Math.max(1, Math.floor(width * 0.75));\n\t\t\t\tconst nextHeight = Math.max(1, Math.floor(height * 0.75));\n\t\t\t\tif (nextWidth === width && nextHeight === height) return null;\n\t\t\t\twidth = nextWidth;\n\t\t\t\theight = nextHeight;\n\t\t\t}\n\t\t} catch {\n\t\t\treturn null;\n\t\t} finally {\n\t\t\timage?.free();\n\t\t}\n\t});\n\n// From source the worker sits beside this module; packed, this module lands in a\n// chunk at the package's output root while the worker keeps its own entry path. The\n// standalone binary unpacks a bundled worker and names it.\nconst workerUrl = Effect.gen(function* () {\n\tconst unpacked = yield* Config.option(Config.String(\"CODEWORK_IMAGE_WORKER\"));\n\tif (Option.isSome(unpacked)) return pathToFileURL(unpacked.value);\n\treturn import.meta.url.endsWith(\".ts\")\n\t\t? new URL(\"./worker.ts\", import.meta.url)\n\t\t: new URL(\"./tool/image/worker.mjs\", import.meta.url);\n}).pipe(Effect.orDie);\n\n/** The worker could not resize; the caller falls back to this thread. */\nclass WorkerError extends Schema.TaggedError<WorkerError>()(\"ImageResizeWorkerError\", { message: Schema.String }) {}\n\nconst inWorker = (input: Uint8Array, mimeType: string, options: ResizeOptions) =>\n\tEffect.flatMap(workerUrl, (url) =>\n\t\tEffect.callback<Resized | null, WorkerError>((resume) => {\n\t\t\tlet worker: Worker;\n\t\t\ttry {\n\t\t\t\tworker = new Worker(url);\n\t\t\t} catch (cause) {\n\t\t\t\t// e.g. a Node permission model without worker access: resize in this thread instead.\n\t\t\t\tresume(Effect.fail(new WorkerError({ message: String(cause) })));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst done = (effect: Effect.Effect<Resized | null, WorkerError>) => {\n\t\t\t\tresume(effect);\n\t\t\t\tvoid worker.terminate().catch(() => undefined);\n\t\t\t};\n\t\t\tworker.on(\"message\", (message: unknown) => {\n\t\t\t\tconst reply = message as Partial<Reply> | null;\n\t\t\t\tif (reply?.type !== REPLY) return;\n\t\t\t\tdone(\n\t\t\t\t\t\"error\" in reply\n\t\t\t\t\t\t? Effect.fail(new WorkerError({ message: reply.error }))\n\t\t\t\t\t\t: Effect.succeed((reply as { result: Resized | null }).result),\n\t\t\t\t);\n\t\t\t});\n\t\t\tworker.once(\"error\", (error: Error) => done(Effect.fail(new WorkerError({ message: error.message }))));\n\t\t\tworker.once(\"exit\", (code) =>\n\t\t\t\tdone(Effect.fail(new WorkerError({ message: `Image resize worker exited with code ${code}` }))),\n\t\t\t);\n\t\t\t// Transferring detaches the buffer, so hand over a copy and leave the caller's bytes intact.\n\t\t\tconst bytes = new Uint8Array(input);\n\t\t\tworker.postMessage({ input: bytes, mimeType, options }, [bytes.buffer]);\n\t\t\treturn Effect.promise(() => worker.terminate());\n\t\t}),\n\t);\n\n/**\n * {@link resizeInProcess} on a worker thread, so decoding and encoding a large\n * image never blocks the harness's event loop. Falls back to this thread when a\n * worker cannot start, so a read still works.\n */\nexport const resize = (input: Uint8Array, mimeType: string, options: ResizeOptions = defaults) =>\n\tinWorker(input, mimeType, options).pipe(Effect.catch(() => resizeInProcess(input, mimeType, options)));\n\n/** Tells the model how to map coordinates on a resized image back to the original. */\nexport const dimensionNote = (result: Resized): string | undefined => {\n\tif (!result.wasResized) return undefined;\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,iCAA8C,IAAI,IAAI,CAC3D,CAAC,UAAU,oBAAoB,GAC/B,CAAC,sBAAsB,oBAAoB,CAC5C,CAAC;AAiBD,MAAM,eAAe;AAErB,SAAS,WAAW,KAAyC;CAC5D,OAAQ,WAA0D,OAAO,IAAI,GAAG;AACjF;;AAGA,SAAgB,MAAM,UAA0D;CAC/E,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO,QAAQ,QAAQ,GAAG;EACxD,MAAM,MAAM,eAAe,IAAI,IAAI;EACnC,IAAI,QAAQ,KAAA,GAAW,MAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;EACrF,WAA+C,OAAO,IAAI,GAAG,KAAK;CACnE;AACD;;AAGA,SAAS,aAAa,KAAa,WAAmB,OAAsC;CAE3F,OAAO;EACN,mBAAmB,yBAFsB,KAAK,UAAU,GAAG,EAAE,IAEjC,GAAG,KAAK,UAAU,SAAS,EAAE;EACzD,GAAG,MAAM,KAAK,MAAM,UAAU,UAAU,MAAM,OAAO,KAAK,UAAU,IAAI,EAAE,GAAG;EAE7E,YAAY,MAAM,KAAK,MAAM,UAAU,IAAI,MAAM,MAAM,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE;CAC3F,CAAC,CAAC,KA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,KAAK,IAAI,YAAY,EAAE,SAAS,MAAM,MAAM,CAAC,CAAC,IACrD,OAAO,QAAS,MAAqC,MAAM,CAC/D;CACD,CAAC;CACD,OAAO,KAAK,UAAU,UAAiB,KAAK,OAAO,KAAK,IAAI,YAAY,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAAC,CAAC;CACrG,OAAO,KAAK,SAAS,SACpB,KAAK,OAAO,KAAK,IAAI,YAAY,EAAE,SAAS,wCAAwC,OAAO,CAAC,CAAC,CAAC,CAC/F;CAEA,MAAM,QAAQ,IAAI,WAAW,KAAK;CAClC,OAAO,YAAY;EAAE,OAAO;EAAO;EAAU;CAAQ,GAAG,CAAC,MAAM,MAAM,CAAC;CACtE,OAAO,OAAO,cAAc,OAAO,UAAU,CAAC;AAC/C,CAAC,CACF;;;;;;AAOD,MAAa,UAAU,OAAmB,UAAkB,UAAyB,aACpF,SAAS,OAAO,UAAU,OAAO,CAAC,CAAC,KAAK,OAAO,YAAY,gBAAgB,OAAO,UAAU,OAAO,CAAC,CAAC;;AAGtG,MAAa,iBAAiB,WAAwC;CACrE,IAAI,CAAC,OAAO,YAAY,OAAO,KAAA;CAC/B,MAAM,QAAQ,OAAO,gBAAgB,OAAO;CAC5C,OAAO,oBAAoB,OAAO,cAAc,GAAG,OAAO,eAAe,iBAAiB,OAAO,MAAM,GAAG,OAAO,OAAO,4BAA4B,MAAM,QAAQ,CAAC,EAAE;AACtK"}
@@ -1,25 +1,25 @@
1
1
  import { n as __reExport, t as __exportAll } from "./rolldown-runtime-B4FMCO8f.mjs";
2
2
  import { posix } from "@codeworksh/plugin/posix";
3
- //#region src/sandbox/instance.ts
4
- var instance_exports = /* @__PURE__ */ __exportAll({});
5
- import * as import__codeworksh_plugin_sandbox_instance from "@codeworksh/plugin/sandbox/instance";
6
- __reExport(instance_exports, import__codeworksh_plugin_sandbox_instance);
3
+ //#region src/sandbox/fs/filesystem.ts
4
+ var filesystem_exports = /* @__PURE__ */ __exportAll({});
5
+ import * as import__codeworksh_plugin_sandbox_filesystem from "@codeworksh/plugin/sandbox/filesystem";
6
+ __reExport(filesystem_exports, import__codeworksh_plugin_sandbox_filesystem);
7
7
  //#endregion
8
8
  //#region src/sandbox/io.ts
9
9
  var io_exports = /* @__PURE__ */ __exportAll({});
10
10
  import * as import__codeworksh_plugin_sandbox_io from "@codeworksh/plugin/sandbox/io";
11
11
  __reExport(io_exports, import__codeworksh_plugin_sandbox_io);
12
12
  //#endregion
13
+ //#region src/sandbox/instance.ts
14
+ var instance_exports = /* @__PURE__ */ __exportAll({});
15
+ import * as import__codeworksh_plugin_sandbox_instance from "@codeworksh/plugin/sandbox/instance";
16
+ __reExport(instance_exports, import__codeworksh_plugin_sandbox_instance);
17
+ //#endregion
13
18
  //#region src/sandbox/errors.ts
14
19
  var errors_exports = /* @__PURE__ */ __exportAll({});
15
20
  import * as import__codeworksh_plugin_sandbox_errors from "@codeworksh/plugin/sandbox/errors";
16
21
  __reExport(errors_exports, import__codeworksh_plugin_sandbox_errors);
17
22
  //#endregion
18
- //#region src/sandbox/fs/filesystem.ts
19
- var filesystem_exports = /* @__PURE__ */ __exportAll({});
20
- import * as import__codeworksh_plugin_sandbox_filesystem from "@codeworksh/plugin/sandbox/filesystem";
21
- __reExport(filesystem_exports, import__codeworksh_plugin_sandbox_filesystem);
22
- //#endregion
23
23
  //#region src/sandbox/shell/shell.ts
24
24
  var shell_exports = /* @__PURE__ */ __exportAll({});
25
25
  import * as import__codeworksh_plugin_sandbox_shell from "@codeworksh/plugin/sandbox/shell";
@@ -30,6 +30,6 @@ var resource_exports = /* @__PURE__ */ __exportAll({});
30
30
  import * as import__codeworksh_plugin_sandbox_resource from "@codeworksh/plugin/sandbox/resource";
31
31
  __reExport(resource_exports, import__codeworksh_plugin_sandbox_resource);
32
32
  //#endregion
33
- export { io_exports as a, errors_exports as i, shell_exports as n, posix as o, filesystem_exports as r, instance_exports as s, resource_exports as t };
33
+ export { io_exports as a, instance_exports as i, shell_exports as n, filesystem_exports as o, errors_exports as r, posix as s, resource_exports as t };
34
34
 
35
- //# sourceMappingURL=resource-Ddd8Mdv2.mjs.map
35
+ //# sourceMappingURL=resource-KATRDaiR.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-KATRDaiR.mjs","names":[],"sources":["../../src/sandbox/fs/filesystem.ts","../../src/sandbox/io.ts","../../src/sandbox/instance.ts","../../src/sandbox/errors.ts","../../src/sandbox/shell/shell.ts","../../src/sandbox/resource.ts"],"sourcesContent":["export * from \"@codeworksh/plugin/sandbox/filesystem\";\n","export * from \"@codeworksh/plugin/sandbox/io\";\n","export * from \"@codeworksh/plugin/sandbox/instance\";\n","export * from \"@codeworksh/plugin/sandbox/errors\";\n","export * from \"@codeworksh/plugin/sandbox/shell\";\n","export * from \"@codeworksh/plugin/sandbox/resource\";\n"],"mappings":""}
@@ -1,2 +1,2 @@
1
- import { a as RuntimeConfig, c as sandbox, i as ResourcesConfig, n as CreateConfig, o as config, r as Options, s as make, t as ClientOptions } from "../../index-BlvIgEtU.mjs";
1
+ import { a as RuntimeConfig, c as make, i as ResourcesConfig, l as sandbox, n as CreateConfig, o as config, r as Options, t as ClientOptions } from "../../index-Bh-JSvU4.mjs";
2
2
  export { ClientOptions, CreateConfig, Options, ResourcesConfig, RuntimeConfig, config, sandbox as default, make };
@@ -1,2 +1,2 @@
1
- import { a as RuntimeConfig, c as sandbox, i as ResourcesConfig, n as CreateConfig, o as config, r as Options, s as make, t as ClientOptions } from "../../daytona-CL_P5Ei_.mjs";
1
+ import { a as RuntimeConfig, c as sandbox, i as ResourcesConfig, n as CreateConfig, o as config, r as Options, s as make, t as ClientOptions } from "../../daytona-B46o451y.mjs";
2
2
  export { ClientOptions, CreateConfig, Options, ResourcesConfig, RuntimeConfig, config, sandbox as default, make };
@@ -1,2 +1,2 @@
1
- import { a as Source, c as sandbox, i as RuntimeConfig, n as CreateConfig, o as config, r as Options, s as make, t as ClientOptions } from "../../index-BEZ8eL--.mjs";
1
+ import { a as Source, c as make, i as RuntimeConfig, l as sandbox, n as CreateConfig, o as config, r as Options, t as ClientOptions } from "../../index-NOtBwGrV.mjs";
2
2
  export { ClientOptions, CreateConfig, Options, RuntimeConfig, Source, config, sandbox as default, make };
@@ -1,2 +1,2 @@
1
- import { a as Source, c as sandbox, i as RuntimeConfig, n as CreateConfig, o as config, r as Options, s as make, t as ClientOptions } from "../../vercel-DF8lAK1L.mjs";
1
+ import { a as Source, c as sandbox, i as RuntimeConfig, n as CreateConfig, o as config, r as Options, s as make, t as ClientOptions } from "../../vercel-_1x7N4NW.mjs";
2
2
  export { ClientOptions, CreateConfig, Options, RuntimeConfig, Source, config, sandbox as default, make };
@@ -1,4 +1,4 @@
1
- import { i as resizeInProcess, t as REPLY } from "../../resize-BF1OwDGZ.mjs";
1
+ import { i as resizeInProcess, t as REPLY } from "../../resize-BUdJMHgx.mjs";
2
2
  import { Effect } from "effect";
3
3
  import { parentPort } from "node:worker_threads";
4
4
  //#region src/tool/image/worker.ts
@@ -1,4 +1,4 @@
1
- import { i as errors_exports, n as shell_exports, o as posix, r as filesystem_exports, s as instance_exports, t as resource_exports } from "./resource-Ddd8Mdv2.mjs";
1
+ import { i as instance_exports, n as shell_exports, o as filesystem_exports, r as errors_exports, s as posix, t as resource_exports } from "./resource-KATRDaiR.mjs";
2
2
  import { SandboxDriver, SandboxProvider } from "./sandbox.mjs";
3
3
  import { Context, Effect, Layer, Option, Schema, Stream } from "effect";
4
4
  import { Buffer } from "node:buffer";
@@ -381,4 +381,4 @@ const config = (value) => ({
381
381
  //#endregion
382
382
  export { Source as a, sandbox as c, RuntimeConfig as i, CreateConfig as n, config as o, Options as r, make as s, ClientOptions as t };
383
383
 
384
- //# sourceMappingURL=vercel-DF8lAK1L.mjs.map
384
+ //# sourceMappingURL=vercel-_1x7N4NW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel-_1x7N4NW.mjs","names":["make","SandboxInstance","makeRedactor","sanitizeSandboxError","SandboxFileSystem","resolveCwd","ShellError","quoteArgv","RemoteFileSystem.make","Shell","SandboxResource","EnvVercel.credentialsFrom","EnvVercel.sanitizeProviderError","EnvVercel.createSandbox","EnvVercel.SPILL_PATH","EnvVercel.transport"],"sources":["../../src/sandboxes/vercel/fs.ts","../../src/sandboxes/vercel/provider.ts","../../src/sandboxes/vercel/index.ts"],"sourcesContent":["import { posix } from \"../../util/posix.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\n\n// The provider contract and FileStat live in `filesystem.ts` (the single source of truth, VFS-free).\n// A remote provider implements this Interface; `make` wraps\n// it into the same runtime surface the local vfs backend exposes.\nexport type FileStat = SandboxFileSystem.FileStat;\n\n// Remote-aware callers can opt into metadata that is not part of the generic\n// SandboxFileSystem surface. In particular, `stat` keeps the familiar\n// provider-level meaning, while `lstat` explicitly asks for the directory entry\n// itself so symlink identity is not inferred from a method with mixed provider\n// semantics.\nexport interface Interface extends SandboxFileSystem.Provider {\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\nexport interface Options {\n\t/**\n\t * Optional remote working directory for relative paths. When omitted, relative\n\t * paths are passed through so the remote provider can use its own default cwd.\n\t */\n\treadonly cwd?: string;\n}\n\nconst resolvePath = (path: string, options?: Options) => {\n\tconst normalized = posix.normalize(path);\n\tif (options?.cwd === undefined || posix.isAbsolute(normalized)) return normalized;\n\treturn posix.normalize(posix.join(options.cwd, normalized));\n};\n\n/**\n * Wrap a remote provider into the runtime filesystem surface: resolve relative\n * paths against `cwd`, and nothing else. Parent creation and `rm` option\n * validation are the runtime's job and live in `SandboxFileSystem.fromProvider`,\n * which every backend passes through — putting them here would cover only the\n * backends that happen to use this wrapper.\n */\nexport const make = (provider: Interface, options?: Options): SandboxFileSystem.Provider => {\n\tconst resolve = (path: string) => resolvePath(path, options);\n\n\treturn {\n\t\treadFile: (path) => provider.readFile(resolve(path)),\n\t\treadFileBuffer: (path) => provider.readFileBuffer(resolve(path)),\n\t\treadBytes: (path, offset, length) => provider.readBytes(resolve(path), offset, length),\n\t\twriteFile: (path, content) => provider.writeFile(resolve(path), content),\n\t\tstat: (path) => provider.stat(resolve(path)),\n\t\t...(provider.lstat === undefined ? {} : { lstat: (path: string) => provider.lstat!(resolve(path)) }),\n\t\treaddir: (path) => provider.readdir(resolve(path)),\n\t\texists: (path) => provider.exists(resolve(path)),\n\t\tmkdir: (path, mkdirOptions) => provider.mkdir(resolve(path), mkdirOptions),\n\t\t// option validation happens in `fromProvider`, before any mutation\n\t\trm: (path, rmOptions) => provider.rm(resolve(path), rmOptions),\n\t\trealpath: (path) => provider.realpath(resolve(path)),\n\t\tscanLines: (path, scanOptions) => provider.scanLines(resolve(path), scanOptions),\n\t};\n};\n","/* oxlint-disable effecttsgo/async-function -- Vercel's sandbox SDK boundary is Promise-based. */\nimport { Context, Effect, Layer, Schema, Stream } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { makeRedactor, type Redactor, sanitizeError as sanitizeSandboxError } from \"../../sandbox/errors.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\nimport { SandboxInstance } from \"../../sandbox/instance.ts\";\nimport { SandboxIO } from \"../../sandbox/io.ts\";\nimport { SandboxResource } from \"../../sandbox/resource.ts\";\nimport {\n\ttype ExecChunk,\n\ttype ExecResult,\n\ttype ISandboxExe,\n\tquoteArgv,\n\tresolveCwd,\n\tShell,\n\tShellError,\n} from \"../../sandbox/shell/shell.ts\";\nimport * as RemoteFileSystem from \"./fs.ts\";\n\nconst utf8 = new TextEncoder();\ntype Command = import(\"@vercel/sandbox\").Command;\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\n/** Vercel's namespace-intrinsic working directory. */\nexport const DEFAULT_CWD = \"/vercel/sandbox\";\n/** Where oversized tool output is written inside the sandbox. */\nexport const SPILL_PATH = \"/tmp\";\n\nexport class VercelError extends Schema.TaggedError<VercelError>()(\"VercelError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nconst ApiFailure = Schema.Struct({\n\tjson: Schema.Struct({\n\t\terror: Schema.Struct({\n\t\t\tmessage: Schema.optional(Schema.String),\n\t\t\tcode: Schema.optional(Schema.String),\n\t\t}),\n\t}),\n});\nconst isApiFailure = Schema.is(ApiFailure);\n\n/** Prefer Vercel's structured API failure while retaining the shared redaction boundary. */\nexport const sanitizeProviderError = (\n\tcause: unknown,\n\tredact: Redactor = makeRedactor(),\n): SandboxInstance.PersistedError => {\n\tconst fallback = sanitizeSandboxError(cause, redact);\n\tif (!isApiFailure(cause)) return fallback;\n\tconst message = cause.json.error.message?.trim();\n\tconst code = cause.json.error.code?.trim();\n\treturn {\n\t\t...fallback,\n\t\t...(message === undefined || message.length === 0 ? {} : { message: redact(message) }),\n\t\t...(code === undefined || code.length === 0 ? {} : { code: redact(code) }),\n\t};\n};\n\n/**\n * Vercel API credentials. Either all three are provided together or none are:\n * when omitted, the SDK resolves them from the `VERCEL_OIDC_TOKEN` env var\n * (the token's payload carries the project and team ids).\n */\nexport interface Credentials {\n\treadonly token: string;\n\treadonly teamId: string;\n\treadonly projectId: string;\n}\n\nexport interface Options {\n\t/** Auth token (OIDC or access token). Falls back to `VERCEL_OIDC_TOKEN`. */\n\treadonly token?: string | undefined;\n\t/** Team id. Derived from the OIDC token when omitted. */\n\treadonly teamId?: string | undefined;\n\t/** Project id. Derived from the OIDC token when omitted. */\n\treadonly projectId?: string | undefined;\n\t/** Reuse an existing sandbox by name instead of creating one. */\n\treadonly sandboxName?: string | undefined;\n\t/** Explicit name for a newly created sandbox. */\n\treadonly name?: string | undefined;\n\t/** Provider-side diagnostic labels (maximum five). */\n\treadonly tags?: Record<string, string> | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot id to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Source to seed the sandbox filesystem from (git or tarball). */\n\treadonly source?:\n\t\t| {\n\t\t\t\treadonly type: \"git\";\n\t\t\t\treadonly url: string;\n\t\t\t\treadonly revision?: string | undefined;\n\t\t\t\treadonly depth?: number | undefined;\n\t\t }\n\t\t| { readonly type: \"tarball\"; readonly url: string };\n\t/** Runtime used by the sandbox. Defaults to the SDK default (`node24`). */\n\treadonly runtime?: string | undefined;\n\t/** Ports to expose from the sandbox (max 4). */\n\treadonly ports?: number[] | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** vCPU allocation (memory scales at 2048 MB per vCPU). */\n\treadonly vcpus?: number | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `/vercel/sandbox`;\n\t * omitted values use that namespace default.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Milliseconds before the sandbox auto-terminates. */\n\treadonly timeout?: number | undefined;\n\t/** Per-command timeout in milliseconds. Omit for no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandboxes/vercel/provider/Remote\") {}\n\n// Vercel requires all three credential fields together or none — partial\n// credentials are rejected by the SDK — so only forward them when complete.\nexport const credentialsFrom = (options: Options): Credentials | undefined =>\n\toptions.token !== undefined && options.teamId !== undefined && options.projectId !== undefined\n\t\t? { token: options.token, teamId: options.teamId, projectId: options.projectId }\n\t\t: undefined;\n\nexport const createSandbox = async (options: Options, creds: Credentials | undefined = credentialsFrom(options)) => {\n\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\tconst withCreds = <T extends object>(params: T) => (creds ? { ...params, ...creds } : params);\n\tconst source =\n\t\toptions.source?.type === \"git\"\n\t\t\t? {\n\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\turl: options.source.url,\n\t\t\t\t\t...(options.source.revision === undefined ? {} : { revision: options.source.revision }),\n\t\t\t\t\t...(options.source.depth === undefined ? {} : { depth: options.source.depth }),\n\t\t\t\t}\n\t\t\t: options.source;\n\tconst base = {\n\t\t...(options.name === undefined ? {} : { name: options.name }),\n\t\t...(options.tags === undefined ? {} : { tags: options.tags }),\n\t\t...(options.envVars === undefined ? {} : { env: options.envVars }),\n\t\t...(options.ports === undefined ? {} : { ports: options.ports }),\n\t\t...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n\t\t...(options.vcpus === undefined ? {} : { resources: { vcpus: options.vcpus } }),\n\t};\n\treturn options.snapshot !== undefined\n\t\t? Sandbox.create(withCreds({ ...base, source: { type: \"snapshot\" as const, snapshotId: options.snapshot } }))\n\t\t: Sandbox.create(\n\t\t\t\twithCreds({\n\t\t\t\t\t...base,\n\t\t\t\t\t...(options.runtime === undefined ? {} : { runtime: options.runtime }),\n\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t}),\n\t\t\t);\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\t\t\t\tconst creds = credentialsFrom(options);\n\t\t\t\tconst sandbox = options.sandboxName\n\t\t\t\t\t? await Sandbox.get(creds ? { ...creds, name: options.sandboxName } : { name: options.sandboxName })\n\t\t\t\t\t: await createSandbox(options, creds);\n\t\t\t\treturn { sandbox };\n\t\t\t},\n\t\t\tcatch: (cause) => new VercelError({ sanitized: sanitizeProviderError(cause) }),\n\t\t}),\n\t);\n\ninterface Stats {\n\treadonly size: number;\n\treadonly mtime: Date;\n\treadonly isFile: () => boolean;\n\treadonly isDirectory: () => boolean;\n\treadonly isSymbolicLink: () => boolean;\n}\n\nconst statsFrom = (stats: Stats): RemoteFileSystem.FileStat => {\n\tconst mtime = stats.mtime;\n\n\t// omit size/mtime the stat could not report — never fabricate\n\treturn {\n\t\tisFile: stats.isFile(),\n\t\tisDirectory: stats.isDirectory(),\n\t\tisSymbolicLink: stats.isSymbolicLink(),\n\t\t...(Number.isFinite(stats.size) ? { size: stats.size } : {}),\n\t\t...(mtime instanceof Date && !Number.isNaN(mtime.getTime()) ? { mtime } : {}),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t| \"readFile\"\n\t| \"readFileBuffer\"\n\t| \"readBytes\"\n\t| \"writeFile\"\n\t| \"stat\"\n\t| \"lstat\"\n\t| \"readdir\"\n\t| \"exists\"\n\t| \"mkdir\"\n\t| \"rm\"\n\t| \"realpath\"\n\t| \"scanLines\"\n>;\n\n// The Vercel `fs` surface is `node:fs/promises`-compatible, so the provider\n// maps almost directly. The `RemoteFileSystem.make` wrapper resolves relative\n// paths against `cwd` and guarantees parent creation on `writeFile`. Only\n// `realpath` has no fs counterpart and shells out.\nconst providerFrom = (sandbox: RemoteSandbox, options: Options): RemoteFilesystemProvider => {\n\tconst run = async (argv: ReadonlyArray<string>) => {\n\t\tconst result = await (await spawnArgv(sandbox, options, argv)).wait();\n\t\treturn { exitCode: result.exitCode, stdout: await result.stdout(), stderr: await result.stderr() };\n\t};\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: (path: string) => sandbox.fs.readFile(path, \"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.readFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.writeFile(path, typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content)),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.stat(path)),\n\t\t// Keep symlink identity explicit: Vercel's `stat` follows symlinks\n\t\t// (`stat -L`), so remote-aware callers must ask for `lstat` when they\n\t\t// need the entry itself instead of the target's metadata.\n\t\tlstat: async (path: string) => statsFrom(await sandbox.fs.lstat(path)),\n\t\t// `withFileTypes` lists via `find`, which includes dotfiles (`.git` …);\n\t\t// the bare `readdir` shells out to `ls -1` and would drop them.\n\t\treaddir: async (path: string) => (await sandbox.fs.readdir(path, { withFileTypes: true })).map((e) => e.name),\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.stat(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tif (SandboxFileSystem.isNotFoundError(cause)) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tawait sandbox.fs.mkdir(\n\t\t\t\tpath,\n\t\t\t\tmkdirOptions?.recursive === undefined ? {} : { recursive: mkdirOptions.recursive },\n\t\t\t);\n\t\t},\n\t\t// `rm -f` is native, so force/recursive delegate straight through; the\n\t\t// wrapper has already rejected any unsupported option before we get here.\n\t\trm: (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) =>\n\t\t\tsandbox.fs.rm(path, {\n\t\t\t\t...(rmOptions?.recursive === undefined ? {} : { recursive: rmOptions.recursive }),\n\t\t\t\t...(rmOptions?.force === undefined ? {} : { force: rmOptions.force }),\n\t\t\t}),\n\t\trealpath: async (path: string) => {\n\t\t\tfor (const script of SandboxFileSystem.realpathScripts) {\n\t\t\t\tconst result = await (await spawnArgv(sandbox, options, [\"sh\", \"-c\", script, \"_\", path])).wait();\n\t\t\t\tif (result.exitCode === 0) return (await result.stdout()).trimEnd();\n\t\t\t}\n\t\t\t// same shape `fs.stat` rejects with, so `isNotFoundError` recognises it\n\t\t\tthrow Object.assign(new Error(`ENOENT: no such file or directory, realpath '${path}'`), { code: \"ENOENT\" });\n\t\t},\n\t\tscanLines: SandboxFileSystem.Scan.viaShell(run),\n\t\treadBytes: SandboxFileSystem.readBytesViaShell(run),\n\t};\n\n\treturn filesystem;\n};\n\n// Arbitrary command strings run through `sh -c` to match the single-string\n// contract the rest of the harness expects. Commands run **detached** so the\n// returned `Command` exposes `kill`/`logs`/`wait`: a `cwd`/`env` is threaded in,\n// and the per-command `execTimeout` is a server-side SIGKILL deadline.\nconst spawn = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => spawnArgv(sandbox, options, [\"sh\", \"-c\", command], env, cwd);\n\n// Vercel spawns a program with a real argument vector, so `execArgv` needs no\n// quoting at all — the args never pass through a shell.\nconst spawnArgv = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\targv: ReadonlyArray<string>,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => {\n\tconst resolvedCwd = resolveCwd(options.cwd, cwd);\n\treturn sandbox.runCommand({\n\t\tcmd: argv[0]!,\n\t\targs: argv.slice(1),\n\t\t...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }),\n\t\t...(env === undefined ? {} : { env }),\n\t\tdetached: true,\n\t\t...(options.execTimeout === undefined ? {} : { timeoutMs: options.execTimeout }),\n\t});\n};\n\n// Acquire a detached command and register its kill as a scope finalizer, so an\n// interrupt / timeout from the consumer actually terminates the remote process\n// (best-effort SIGKILL) instead of leaving it running server-side.\n// `command` labels failures only; the spawn itself is supplied by the caller so\n// string and argv execution share one kill finalizer.\nconst acquireWith = (command: string, run: () => Promise<Command>) =>\n\tEffect.acquireRelease(Effect.tryPromise({ try: run, catch: (cause) => new ShellError({ command, cause }) }), (cmd) =>\n\t\tEffect.promise(() => cmd.kill(\"SIGKILL\").catch(() => {})),\n\t);\n\n// Vercel reports stdout and stderr separately with a distinct exit code, so the\n// shell surfaces both streams faithfully.\nconst collect = (command: string) => (cmd: Command) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<ExecResult> => {\n\t\t\tconst result = await cmd.wait();\n\t\t\tconst [stdout, stderr] = await Promise.all([result.stdout(), result.stderr()]);\n\t\t\treturn { stdout, stderr, exitCode: result.exitCode };\n\t\t},\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t});\n\nconst acquireCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n) => acquireWith(command, () => spawn(sandbox, options, command, env, cwd));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) => {\n\t\t// quoted for the error label only — the spawn passes argv through untouched\n\t\tconst command = quoteArgv(argv);\n\t\treturn acquireWith(command, () => spawnArgv(sandbox, options, argv, opts?.env, opts?.cwd)).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\t};\n\ntype Logs = ReturnType<Command[\"logs\"]>;\ntype LogLine = Logs extends AsyncGenerator<infer L> ? L : never;\n\n// The SDK's `return()` waits for the pending read of the HTTP log stream, which\n// never ends while a surviving child (e.g. `tee`) holds stdout open; abort the\n// read first so closing the stream's scope cannot hang.\nconst closable = (logs: Logs): AsyncIterable<LogLine, void> => ({\n\t[Symbol.asyncIterator]: () => ({\n\t\tnext: () => logs.next(),\n\t\treturn: async () => {\n\t\t\tlogs.close();\n\t\t\tawait logs.return().catch(() => {});\n\t\t\treturn { done: true, value: undefined };\n\t\t},\n\t}),\n});\n\n// Streaming output via `Command.logs` (an async generator of stdout/stderr\n// entries), followed by the exit code from `wait`. The kill finalizer fires when\n// the consuming scope closes (interrupt / timeout).\nconst stream =\n\t(sandbox: RemoteSandbox, options: Options): NonNullable<ISandboxExe[\"stream\"]> =>\n\t(command, opts) =>\n\t\tStream.unwrap(\n\t\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\t\tEffect.map((cmd) => {\n\t\t\t\t\tconst logs = Stream.fromAsyncIterable(\n\t\t\t\t\t\tclosable(cmd.logs()),\n\t\t\t\t\t\t(cause) => new ShellError({ command, cause }),\n\t\t\t\t\t).pipe(Stream.map((log): ExecChunk => ({ _tag: log.stream, bytes: utf8.encode(log.data) })));\n\t\t\t\t\tconst exit = Stream.fromEffect(\n\t\t\t\t\t\tEffect.tryPromise({ try: () => cmd.wait(), catch: (cause) => new ShellError({ command, cause }) }),\n\t\t\t\t\t).pipe(Stream.map((finished): ExecChunk => ({ _tag: \"exit\", exitCode: finished.exitCode })));\n\t\t\t\t\treturn Stream.concat(logs, exit);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tSandboxFileSystem.fromProvider(\n\t\t\t\tRemoteFileSystem.make(\n\t\t\t\t\tproviderFrom(sandbox, options),\n\t\t\t\t\toptions.cwd === undefined ? undefined : { cwd: options.cwd },\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * The controller binds a cwd per mount, so neither filesystem nor shell stores\n * one here. The returned layer owns no provider resource and has no deletion\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, options))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Vercel's locator is the sandbox name. See `SandboxResource` for why this is a\n// shared tag rather than a Vercel-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.name })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, () =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"vercel\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: DEFAULT_CWD,\n\t\t\t\tspillPath: SPILL_PATH,\n\t\t\t\t...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Vercel sandbox provides the runtime filesystem service directly plus the\n * sandbox's native remote shell. It intentionally does not provide VFS: remote\n * filesystems have no synchronous filesystem surface.\n */\nexport const services = (\n\toptions: Options = {},\n): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, VercelError> => {\n\tconst mounted = { ...options, cwd: SandboxIO.resolveMountCwd(DEFAULT_CWD, options.cwd) };\n\treturn Layer.mergeAll(\n\t\tSandboxIO.withMutation(Layer.mergeAll(filesystemLayer(mounted), shellLayer(mounted), identityLayer(mounted))),\n\t\tresourceLayer,\n\t).pipe(Layer.provide(remote(mounted)));\n};\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver, SandboxInstance, SandboxProvider } from \"../../sandbox.ts\";\nimport * as EnvVercel from \"./provider.ts\";\n\nexport const Options = Schema.Struct({\n\ttoken: Schema.optional(Schema.String),\n\tteamId: Schema.optional(Schema.String),\n\tprojectId: Schema.optional(Schema.String),\n});\nexport type Options = typeof Options.Type;\nexport const ClientOptions = Options;\nexport type ClientOptions = Options;\n\nexport const Source = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"git\"),\n\t\turl: Schema.String,\n\t\trevision: Schema.optional(Schema.String),\n\t\tdepth: Schema.optional(Schema.Finite),\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"tarball\"),\n\t\turl: Schema.String,\n\t}),\n]);\nexport type Source = typeof Source.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\tsource: Schema.optional(Source),\n\truntime: Schema.optional(Schema.String),\n\tports: Schema.optional(Schema.Array(Schema.Finite)),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tvcpus: Schema.optional(Schema.Finite),\n\ttimeout: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tspillPath: Schema.optional(SandboxDriver.AbsolutePath),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"vercel\");\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\nconst statusFrom = (\n\tstatus: RemoteSandbox[\"status\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => ({\n\tstatus:\n\t\tstatus === \"stopped\"\n\t\t\t? \"offline\"\n\t\t\t: status === \"stopping\" || status === \"snapshotting\"\n\t\t\t\t? \"suspending\"\n\t\t\t\t: status === \"failed\" || status === \"aborted\"\n\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t: \"online\",\n\tproviderStatus: status,\n});\n\nconst isNotFound = (cause: unknown): boolean => {\n\tif (typeof cause !== \"object\" || cause === null) return false;\n\tconst response = \"response\" in cause && cause.response instanceof Response ? cause.response : undefined;\n\tconst code =\n\t\t\"code\" in cause && typeof cause.code === \"string\"\n\t\t\t? cause.code\n\t\t\t: \"json\" in cause &&\n\t\t\t\t typeof cause.json === \"object\" &&\n\t\t\t\t cause.json !== null &&\n\t\t\t\t \"error\" in cause.json &&\n\t\t\t\t typeof cause.json.error === \"object\" &&\n\t\t\t\t cause.json.error !== null &&\n\t\t\t\t \"code\" in cause.json.error &&\n\t\t\t\t typeof cause.json.error.code === \"string\"\n\t\t\t\t? cause.json.error.code\n\t\t\t\t: undefined;\n\treturn response?.status === 404 || code === \"not_found\" || code === \"sandbox_not_found\";\n};\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst credentials = EnvVercel.credentialsFrom(client);\n\tconst redact = SandboxProvider.makeRedactor([client.token ?? \"\"]);\n\n\tconst attempt = <A>(\n\t\toperation: string,\n\t\trun: () => Promise<A>,\n\t): Effect.Effect<A, SandboxProvider.SandboxProviderError> =>\n\t\tEffect.tryPromise({\n\t\t\ttry: run,\n\t\t\tcatch: (cause) =>\n\t\t\t\tSandboxProvider.providerError({\n\t\t\t\t\tdriver: name,\n\t\t\t\t\toperation,\n\t\t\t\t\tcause,\n\t\t\t\t\tredact,\n\t\t\t\t\tsanitize: EnvVercel.sanitizeProviderError,\n\t\t\t\t\tnotFound: isNotFound(cause),\n\t\t\t\t}),\n\t\t});\n\n\tconst get = (providerResourceId: string, resume: boolean, operation: string) =>\n\t\tattempt(operation, () =>\n\t\t\timport(\"@vercel/sandbox\").then(({ Sandbox }) =>\n\t\t\t\tSandbox.get(\n\t\t\t\t\tcredentials === undefined\n\t\t\t\t\t\t? { name: providerResourceId, resume }\n\t\t\t\t\t\t: { ...credentials, name: providerResourceId, resume },\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.status),\n\t\tmetadata: {\n\t\t\tcwd: sandbox.cwd,\n\t\t},\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\tinspect: true,\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\tcancels: true,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst source =\n\t\t\t\t\tconfig.source?.type === \"git\"\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\t\t\t\turl: config.source.url,\n\t\t\t\t\t\t\t\t...(config.source.revision === undefined ? {} : { revision: config.source.revision }),\n\t\t\t\t\t\t\t\t...(config.source.depth === undefined ? {} : { depth: config.source.depth }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: config.source;\n\t\t\t\tconst sandbox = yield* attempt(\"create\", () =>\n\t\t\t\t\tEnvVercel.createSandbox(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...client,\n\t\t\t\t\t\t\t...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }),\n\t\t\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t\t\t\t...(config.runtime === undefined ? {} : { runtime: config.runtime }),\n\t\t\t\t\t\t\t...(config.ports === undefined ? {} : { ports: [...config.ports] }),\n\t\t\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t\t\t...(config.vcpus === undefined ? {} : { vcpus: config.vcpus }),\n\t\t\t\t\t\t\t...(config.timeout === undefined ? {} : { timeout: config.timeout }),\n\t\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t\t\ttags: {\n\t\t\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcredentials,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.status);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.name,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: {\n\t\t\t\t\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t\t\tspillPath: SandboxDriver.AbsolutePath.make(EnvVercel.SPILL_PATH),\n\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tcwd: sandbox.cwd,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.map(get(providerResourceId, false, \"runtimeConfigFor\"), (sandbox) => ({\n\t\t\t\tdefaultCwd: overrides?.defaultCwd ?? SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\tspillPath: overrides?.spillPath ?? SandboxDriver.AbsolutePath.make(EnvVercel.SPILL_PATH),\n\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t})),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.map(\n\t\t\t\t\tget(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t),\n\t\t\t\t\t(sandbox) =>\n\t\t\t\t\t\tEnvVercel.transport(\n\t\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\ttrue,\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nconst sandbox = SandboxDriver.module({\n\tapiVersion: SandboxDriver.apiVersion,\n\tname,\n\toptions: Options,\n\tmake,\n});\n\nexport const config = (value: CreateConfig) => ({ driver: \"vercel\" as const, config: value });\n\nexport default sandbox;\n"],"mappings":";;;;;AAyBA,MAAM,eAAe,MAAc,YAAsB;CACxD,MAAM,aAAa,MAAM,UAAU,IAAI;CACvC,IAAI,SAAS,QAAQ,KAAA,KAAa,MAAM,WAAW,UAAU,GAAG,OAAO;CACvE,OAAO,MAAM,UAAU,MAA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E,GACzD,MACA,QACD,IACC,YACAC,UACC,SACA,MAAM,cAAc,gBAAgB,KAAA,IACjC,KAAA,IACA,EAAE,aAAa,MAAM,cAAc,YAAY,CACnD,CACF,CACD;EACD,UAAU,UACT,OAAO,IACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,OACA,SACD,GACA,QACD;EACD,OAAO,UACN,OAAO,IACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,MACA,MACD,GACA,QACD;EACD,OAAO,UACN,OAAO,QACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,OACA,MACD,IACC,YAAY,QAAQ,cAAc,QAAQ,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,UAAU,SAAS,OAAO,CAAC,CAAC,CAC5F;EACD,UAAU,UACT,OAAO,QACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,OACA,SACD,IACC,YAAY,QAAQ,iBAAiB,QAAQ,OAAO,CAAC,CACvD;CACF,CAAC;AACF;AAEA,MAAM,UAAU,cAAc,OAAO;CACpC,YAAY,cAAc;CAC1B;CACA,SAAS;CACT;AACD,CAAC;AAED,MAAa,UAAU,WAAyB;CAAE,QAAQ;CAAmB,QAAQ;AAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"daytona-CL_P5Ei_.mjs","names":["make","SandboxIO","SandboxInstance","quoteArgv","quote","SandboxFileSystem","resolveCwd","ShellError","RemoteFileSystem.make","Shell","SandboxResource","EnvDaytona.SPILL_PATH","EnvDaytona.mountCwd","EnvDaytona.transport"],"sources":["../../src/sandboxes/daytona/fs.ts","../../src/sandboxes/daytona/provider.ts","../../src/sandboxes/daytona/index.ts"],"sourcesContent":["import { posix } from \"../../util/posix.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\n\nexport type FileStat = SandboxFileSystem.FileStat;\n\nexport interface Interface extends SandboxFileSystem.Provider {\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\nexport interface Options {\n\treadonly cwd?: string;\n}\n\nconst resolvePath = (path: string, options?: Options) => {\n\tconst normalized = posix.normalize(path);\n\tif (options?.cwd === undefined || posix.isAbsolute(normalized)) return normalized;\n\treturn posix.normalize(posix.join(options.cwd, normalized));\n};\n\n/** Resolve provider paths without adding policy or mutable working-directory state. */\nexport const make = (provider: Interface, options?: Options): SandboxFileSystem.Provider => {\n\tconst resolve = (path: string) => resolvePath(path, options);\n\n\treturn {\n\t\treadFile: (path) => provider.readFile(resolve(path)),\n\t\treadFileBuffer: (path) => provider.readFileBuffer(resolve(path)),\n\t\treadBytes: (path, offset, length) => provider.readBytes(resolve(path), offset, length),\n\t\twriteFile: (path, content) => provider.writeFile(resolve(path), content),\n\t\tstat: (path) => provider.stat(resolve(path)),\n\t\t...(provider.lstat === undefined ? {} : { lstat: (path: string) => provider.lstat!(resolve(path)) }),\n\t\treaddir: (path) => provider.readdir(resolve(path)),\n\t\texists: (path) => provider.exists(resolve(path)),\n\t\tmkdir: (path, mkdirOptions) => provider.mkdir(resolve(path), mkdirOptions),\n\t\trm: (path, rmOptions) => provider.rm(resolve(path), rmOptions),\n\t\trealpath: (path) => provider.realpath(resolve(path)),\n\t\tscanLines: (path, scanOptions) => provider.scanLines(resolve(path), scanOptions),\n\t};\n};\n\nexport const withProvider = make;\n","/* oxlint-disable effecttsgo/async-function -- Daytona's SDK boundary is Promise-based. */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { posix } from \"../../util/posix.ts\";\nimport { sanitizeError } from \"../../sandbox/errors.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\nimport { SandboxInstance } from \"../../sandbox/instance.ts\";\nimport { SandboxIO } from \"../../sandbox/io.ts\";\nimport { SandboxResource } from \"../../sandbox/resource.ts\";\nimport { type ISandboxExe, quote, quoteArgv, resolveCwd, Shell, ShellError } from \"../../sandbox/shell/shell.ts\";\nimport * as RemoteFileSystem from \"./fs.ts\";\n\ntype CodeLanguage = import(\"@daytona/sdk\").CodeLanguage;\ntype Daytona = import(\"@daytona/sdk\").Daytona;\ntype FileInfo = import(\"@daytona/sdk\").FileInfo;\ntype Image = import(\"@daytona/sdk\").Image;\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\n/** Fallback when Daytona cannot report a snapshot/image-specific work directory. */\nexport const DEFAULT_CWD = \"/home/daytona\";\n/** Where oversized tool output is written inside the sandbox. */\nexport const SPILL_PATH = \"/tmp\";\n\n/**\n * The mount cwd for a Daytona namespace.\n *\n * An absolute override replaces the namespace default outright, so the\n * `getWorkDir()` round-trip is skipped: it would discover a value we then throw\n * away. Otherwise the sandbox's own work directory is the default, and\n * {@link DEFAULT_CWD} covers a snapshot or image that reports none.\n *\n * Taken as a thunk rather than read off the sandbox so all three branches are\n * testable without provisioning one — this decides where every Daytona mount\n * roots, and §8.1 makes a wrong answer here resolve silently rather than fail.\n */\nexport const mountCwd = async (\n\tcwd: string | undefined,\n\tgetWorkDir: () => Promise<string | undefined>,\n): Promise<string> => {\n\tconst defaultCwd = posix.isAbsolute(cwd ?? \"\") ? DEFAULT_CWD : ((await getWorkDir()) ?? DEFAULT_CWD);\n\treturn SandboxIO.resolveMountCwd(defaultCwd, cwd);\n};\n\nexport class DaytonaError extends Schema.TaggedError<DaytonaError>()(\"DaytonaError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nexport interface Options {\n\t/** API key. Falls back to the `DAYTONA_API_KEY` env var when omitted. */\n\treadonly apiKey?: string | undefined;\n\t/** API URL. Falls back to `DAYTONA_API_URL` / the SDK default. */\n\treadonly apiUrl?: string | undefined;\n\t/** Target region. Falls back to `DAYTONA_TARGET` / the SDK default. */\n\treadonly target?: string | undefined;\n\t/** Reuse an existing sandbox by id or name instead of creating one. */\n\treadonly sandboxId?: string | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Image (registry reference or declarative `Image`) to create the sandbox from. */\n\treadonly image?: string | Image | undefined;\n\t/** Runtime used for code execution. Defaults to `\"typescript\"`. */\n\treadonly language?: CodeLanguage | string | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** Resource allocation (cpu / memory / disk). */\n\treadonly resources?: Resources | undefined;\n\t/** OS user to run as inside the sandbox. */\n\treadonly user?: string | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `getWorkDir()`;\n\t * omitted values use it, with `/home/daytona` as the provider fallback.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Idle minutes before the sandbox auto-stops. */\n\treadonly autoStopInterval?: number | undefined;\n\t/** Per-command timeout in seconds. 0 means no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n\treadonly cwd: string;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandboxes/daytona/provider/Remote\") {}\n\nconst assertCommandSucceeded = (command: string, result: { exitCode: number; result?: string }) => {\n\tif (result.exitCode !== 0) throw new Error(result.result || `command failed (${result.exitCode}): ${command}`);\n};\n\nconst dateFrom = (value: string | undefined) => {\n\tif (value === undefined) return undefined;\n\treturn Option.getOrUndefined(DateTime.make(value).pipe(Option.map(DateTime.toDateUtc)));\n};\n\nexport const createSandbox = (daytona: Daytona, options: Options) => {\n\tconst base = {\n\t\tlanguage: options.language ?? \"typescript\",\n\t\t...(options.envVars === undefined ? {} : { envVars: options.envVars }),\n\t\t...(options.user === undefined ? {} : { user: options.user }),\n\t\t...(options.autoStopInterval === undefined ? {} : { autoStopInterval: options.autoStopInterval }),\n\t\tautoDeleteInterval: -1,\n\t};\n\treturn options.image !== undefined\n\t\t? daytona.create({\n\t\t\t\t...base,\n\t\t\t\timage: options.image,\n\t\t\t\t...(options.resources === undefined ? {} : { resources: options.resources }),\n\t\t\t})\n\t\t: daytona.create({ ...base, ...(options.snapshot === undefined ? {} : { snapshot: options.snapshot }) });\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Daytona } = await import(\"@daytona/sdk\");\n\t\t\t\tconst daytona = new Daytona({\n\t\t\t\t\t...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),\n\t\t\t\t\t...(options.apiUrl === undefined ? {} : { apiUrl: options.apiUrl }),\n\t\t\t\t\t...(options.target === undefined ? {} : { target: options.target }),\n\t\t\t\t});\n\t\t\t\tconst sandbox = options.sandboxId\n\t\t\t\t\t? await daytona.get(options.sandboxId)\n\t\t\t\t\t: await createSandbox(daytona, options);\n\t\t\t\treturn {\n\t\t\t\t\tsandbox,\n\t\t\t\t\tcwd: await mountCwd(options.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t};\n\t\t\t},\n\t\t\tcatch: (cause) => new DaytonaError({ sanitized: sanitizeError(cause) }),\n\t\t}),\n\t);\n\nexport const statsFrom = (info: FileInfo): RemoteFileSystem.FileStat => {\n\tconst symlink = info.mode === undefined ? undefined : info.mode.startsWith(\"l\");\n\tconst mtime = dateFrom(info.modifiedAt ?? info.modTime);\n\n\t// omit size/mtime/isSymbolicLink the toolbox did not report — never fabricate\n\treturn {\n\t\tisFile: !info.isDir && symlink !== true,\n\t\tisDirectory: info.isDir,\n\t\t...(symlink === undefined ? {} : { isSymbolicLink: symlink }),\n\t\t...(info.size === undefined ? {} : { size: info.size }),\n\t\t...(mtime === undefined ? {} : { mtime }),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t| \"readFile\"\n\t| \"readFileBuffer\"\n\t| \"readBytes\"\n\t| \"writeFile\"\n\t| \"stat\"\n\t| \"lstat\"\n\t| \"readdir\"\n\t| \"exists\"\n\t| \"mkdir\"\n\t| \"rm\"\n\t| \"realpath\"\n\t| \"scanLines\"\n>;\n\nconst enoent = (operation: string, path: string) =>\n\tObject.assign(new Error(`ENOENT: no such file or directory, ${operation} '${path}'`), { code: \"ENOENT\" });\n\n/** The toolbox rejects a missing path with its own 404; the filesystem contract expects `ENOENT`. */\nconst missing =\n\t(operation: string, path: string) =>\n\tasync (cause: unknown): Promise<never> => {\n\t\tconst { DaytonaFileNotFoundError } = await import(\"@daytona/sdk\");\n\t\tthrow cause instanceof DaytonaFileNotFoundError ? Object.assign(enoent(operation, path), { cause }) : cause;\n\t};\n\nconst providerFrom = (sandbox: RemoteSandbox, options: Options) => {\n\tconst run = async (argv: ReadonlyArray<string>) => {\n\t\tconst result = await sandbox.process.executeCommand(quoteArgv(argv), options.cwd, undefined, options.execTimeout);\n\t\treturn { exitCode: result.exitCode, stdout: result.result ?? \"\" };\n\t};\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: async (path: string) =>\n\t\t\t(await sandbox.fs.downloadFile(path).catch(missing(\"open\", path))).toString(\"utf8\"),\n\t\treadFileBuffer: async (path: string) =>\n\t\t\tnew Uint8Array(await sandbox.fs.downloadFile(path).catch(missing(\"open\", path))),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.uploadFile(typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content), path),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.getFileDetails(path).catch(missing(\"stat\", path))),\n\t\t// The toolbox file-details endpoint follows symlinks. Detect the entry\n\t\t// with the sandbox shell first so lstat never reports target metadata as\n\t\t// if it described the link itself.\n\t\tlstat: async (path: string) => {\n\t\t\tconst command = `test -L ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tif (result.exitCode === 0) {\n\t\t\t\treturn { isFile: false, isDirectory: false, isSymbolicLink: true };\n\t\t\t}\n\t\t\tif (result.exitCode === 1)\n\t\t\t\treturn statsFrom(await sandbox.fs.getFileDetails(path).catch(missing(\"lstat\", path)));\n\t\t\tassertCommandSucceeded(command, result);\n\t\t\tthrow new Error(`unreachable lstat result for ${path}`);\n\t\t},\n\t\treaddir: async (path: string) =>\n\t\t\t(await sandbox.fs.listFiles(path).catch(missing(\"scandir\", path))).map((entry) => entry.name),\n\t\t// Only a genuine 404 means \"absent\". Auth, rate-limit, and transport\n\t\t// failures propagate: a caller that deletes records on absence must not\n\t\t// be told a path is gone because the API was briefly unreachable.\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.getFileDetails(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tconst { DaytonaNotFoundError } = await import(\"@daytona/sdk\");\n\t\t\t\tif (cause instanceof DaytonaNotFoundError) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\t// `createFolder` is `mkdir -p`; plain `mkdir` fails on a missing parent.\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tconst command = mkdirOptions?.recursive ? `mkdir -p ${quote(path)}` : `mkdir ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tassertCommandSucceeded(command, result);\n\t\t},\n\t\trm: async (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) => {\n\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.deleteFile(path, rmOptions?.recursive);\n\t\t\t} catch (cause) {\n\t\t\t\tif (await filesystem.exists(path)) throw cause;\n\t\t\t\tif (rmOptions?.force) return;\n\t\t\t\tthrow Object.assign(enoent(\"rm\", path), { cause });\n\t\t\t}\n\t\t},\n\t\trealpath: async (path: string) => {\n\t\t\tfor (const script of SandboxFileSystem.realpathScripts) {\n\t\t\t\tconst command = quoteArgv([\"sh\", \"-c\", script, \"_\", path]);\n\t\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\t\tif (result.exitCode === 0) return (result.result ?? \"\").trimEnd();\n\t\t\t}\n\t\t\tthrow enoent(\"realpath\", path);\n\t\t},\n\t\tscanLines: SandboxFileSystem.Scan.viaShell(run),\n\t\treadBytes: SandboxFileSystem.readBytesViaShell(run),\n\t};\n\n\treturn filesystem;\n};\n\n// Daytona's execute API folds stderr into `result` and reports a single exit\n// code, so the shell surfaces the combined output as stdout and leaves stderr\n// empty rather than inventing a split.\nconst runCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\topts?: { env?: Record<string, string>; cwd?: string },\n) =>\n\tEffect.tryPromise({\n\t\ttry: () =>\n\t\t\tsandbox.process.executeCommand(command, resolveCwd(options.cwd, opts?.cwd), opts?.env, options.execTimeout),\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t}).pipe(Effect.map((response) => ({ stdout: response.result ?? \"\", stderr: \"\", exitCode: response.exitCode })));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\trunCommand(sandbox, options, command, opts);\n\n// `executeCommand` takes a single string, so the vector is quoted here rather\n// than spawned; the per-call cwd rides the toolbox's own cwd argument instead\n// of a `cd` prefix.\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) =>\n\t\trunCommand(sandbox, options, quoteArgv(argv), opts);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn SandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, mounted), { cwd }));\n\t\t}),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn Shell.of({ exec: exec(sandbox, mounted), execArgv: execArgv(sandbox, mounted) });\n\t\t}),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * Mount wrappers supply an absolute cwd to every public operation. Internal\n * filesystem helper commands already receive absolute paths, so the transport\n * itself keeps no mutable working-directory state and owns no resource\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, options))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Daytona's locator is the sandbox id. See `SandboxResource` for why this is a\n// shared tag rather than a Daytona-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.id })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, ({ cwd }) =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"daytona\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: cwd,\n\t\t\t\tspillPath: SPILL_PATH,\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Daytona sandbox provides the runtime filesystem service directly plus\n * the sandbox's native remote shell. It intentionally does not provide VFS:\n * remote filesystems have no synchronous filesystem surface.\n */\nexport const layer = (options: Options = {}): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, DaytonaError> =>\n\tLayer.mergeAll(\n\t\tSandboxIO.withMutation(Layer.mergeAll(filesystemLayer(options), shellLayer(options), identityLayer(options))),\n\t\tresourceLayer,\n\t).pipe(Layer.provide(remote(options)));\n\nexport const services = layer;\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver, SandboxInstance, SandboxProvider } from \"../../sandbox.ts\";\nimport * as EnvDaytona from \"./provider.ts\";\n\nexport const Options = Schema.Struct({\n\tapiKey: Schema.optional(Schema.String),\n\tapiUrl: Schema.optional(Schema.String),\n\ttarget: Schema.optional(Schema.String),\n});\nexport type Options = typeof Options.Type;\nexport const ClientOptions = Options;\nexport type ClientOptions = Options;\n\nexport const ResourcesConfig = Schema.Struct({\n\tcpu: Schema.optional(Schema.Finite),\n\tgpu: Schema.optional(Schema.Finite),\n\tmemory: Schema.optional(Schema.Finite),\n\tdisk: Schema.optional(Schema.Finite),\n});\nexport type ResourcesConfig = typeof ResourcesConfig.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\timage: Schema.optional(Schema.String),\n\tlanguage: Schema.optional(Schema.String),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tresources: Schema.optional(ResourcesConfig),\n\tuser: Schema.optional(Schema.String),\n\tcwd: Schema.optional(Schema.String),\n\tautoStopInterval: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tspillPath: Schema.optional(SandboxDriver.AbsolutePath),\n\tuser: Schema.optional(Schema.String),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"daytona\");\ntype DaytonaSdk = typeof import(\"@daytona/sdk\");\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\nconst statusFrom = (\n\tstate: RemoteSandbox[\"state\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => {\n\tconst providerStatus = state ?? \"unknown\";\n\treturn {\n\t\tstatus:\n\t\t\tstate === \"stopped\" || state === \"archived\"\n\t\t\t\t? \"offline\"\n\t\t\t\t: state === \"stopping\" || state === \"archiving\" || state === \"snapshotting\" || state === \"destroying\"\n\t\t\t\t\t? \"suspending\"\n\t\t\t\t\t: state === \"destroyed\"\n\t\t\t\t\t\t? \"unavail\"\n\t\t\t\t\t\t: state === \"error\" || state === \"build_failed\" || state === \"unknown\"\n\t\t\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t\t\t: \"online\",\n\t\tproviderStatus,\n\t};\n};\n\nconst shouldWake = (sandbox: RemoteSandbox): boolean => sandbox.state === \"stopped\" || sandbox.state === \"archived\";\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst redact = SandboxProvider.makeRedactor([client.apiKey ?? \"\"]);\n\tconst daytona = (sdk: DaytonaSdk) =>\n\t\tnew sdk.Daytona({\n\t\t\t...(client.apiKey === undefined ? {} : { apiKey: client.apiKey }),\n\t\t\t...(client.apiUrl === undefined ? {} : { apiUrl: client.apiUrl }),\n\t\t\t...(client.target === undefined ? {} : { target: client.target }),\n\t\t});\n\n\tconst attempt = <A>(\n\t\toperation: string,\n\t\trun: (sdk: DaytonaSdk) => Promise<A>,\n\t): Effect.Effect<A, SandboxProvider.SandboxProviderError> =>\n\t\tEffect.suspend(() => {\n\t\t\tlet sdk: DaytonaSdk | undefined;\n\t\t\treturn Effect.tryPromise({\n\t\t\t\ttry: () =>\n\t\t\t\t\timport(\"@daytona/sdk\").then((loaded) => {\n\t\t\t\t\t\tsdk = loaded;\n\t\t\t\t\t\treturn run(loaded);\n\t\t\t\t\t}),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tSandboxProvider.providerError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\tredact,\n\t\t\t\t\t\tnotFound: sdk !== undefined && cause instanceof sdk.DaytonaNotFoundError,\n\t\t\t\t\t}),\n\t\t\t});\n\t\t});\n\n\tconst get = (providerResourceId: string, operation: string) =>\n\t\tattempt(operation, (sdk) => daytona(sdk).get(providerResourceId));\n\n\tconst refresh = (sandbox: RemoteSandbox, operation: string) =>\n\t\tattempt(operation, () => sandbox.refreshData()).pipe(Effect.as(sandbox));\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.state),\n\t\tmetadata: {\n\t\t\ttarget: sandbox.target,\n\t\t},\n\t});\n\n\tconst wake = (sandbox: RemoteSandbox, operation: string) =>\n\t\tshouldWake(sandbox)\n\t\t\t? attempt(operation, () => sandbox.start()).pipe(Effect.map(() => sandbox))\n\t\t\t: Effect.succeed(sandbox);\n\n\tconst runtime = (\n\t\tdefaultCwd: string,\n\t\tinput: { readonly user?: string | undefined; readonly execTimeout?: number | undefined },\n\t) => ({\n\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(defaultCwd),\n\t\tspillPath: SandboxDriver.AbsolutePath.make(EnvDaytona.SPILL_PATH),\n\t\t...(input.user === undefined ? {} : { user: input.user }),\n\t\t...(input.execTimeout === undefined ? {} : { execTimeout: input.execTimeout }),\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\tinspect: true,\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\t// Installed SDK 0.187.0 has no cancellation signal on\n\t\t\t// executeCommand; session execution cannot carry cwd/env safely.\n\t\t\tcancels: false,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst base = {\n\t\t\t\t\tlanguage: config.language ?? \"typescript\",\n\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t...(config.user === undefined ? {} : { user: config.user }),\n\t\t\t\t\t...(config.autoStopInterval === undefined ? {} : { autoStopInterval: config.autoStopInterval }),\n\t\t\t\t\tautoDeleteInterval: -1,\n\t\t\t\t\tlabels: {\n\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst sandbox = yield* attempt(\"create\", (loaded) => {\n\t\t\t\t\tconst sdk = daytona(loaded);\n\t\t\t\t\treturn config.image === undefined\n\t\t\t\t\t\t? sdk.create({ ...base, ...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }) })\n\t\t\t\t\t\t: sdk.create({\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\timage: config.image,\n\t\t\t\t\t\t\t\t...(config.resources === undefined ? {} : { resources: config.resources as Resources }),\n\t\t\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst defaultCwd = yield* attempt(\"create.cwd\", () =>\n\t\t\t\t\tEnvDaytona.mountCwd(config.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.state);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.id,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: runtime(defaultCwd, config),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttarget: sandbox.target,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst sandbox = yield* get(providerResourceId, \"runtimeConfigFor\");\n\t\t\t\tconst defaultCwd =\n\t\t\t\t\toverrides?.defaultCwd ??\n\t\t\t\t\tSandboxDriver.AbsolutePath.make(\n\t\t\t\t\t\tyield* attempt(\"runtimeConfigFor.cwd\", () =>\n\t\t\t\t\t\t\tEnvDaytona.mountCwd(undefined, () => sandbox.getWorkDir()),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tdefaultCwd,\n\t\t\t\t\tspillPath: overrides?.spillPath ?? SandboxDriver.AbsolutePath.make(EnvDaytona.SPILL_PATH),\n\t\t\t\t\t...(overrides?.user === undefined ? { user: sandbox.user } : { user: overrides.user }),\n\t\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t\t};\n\t\t\t}),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst sandbox = yield* get(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t);\n\t\t\t\t\tyield* wake(sandbox, \"attach.wake\");\n\t\t\t\t\treturn EnvDaytona.transport(\n\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(refresh(sandbox, \"inspect.refresh\"), observed),\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(wake(sandbox, \"wake.start\"), observed),\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nconst sandbox = SandboxDriver.module({\n\tapiVersion: SandboxDriver.apiVersion,\n\tname,\n\toptions: Options,\n\tmake,\n});\n\nexport const config = (value: CreateConfig) => ({ driver: \"daytona\" as const, config: value });\n\nexport default sandbox;\n"],"mappings":";;;;;AAaA,MAAM,eAAe,MAAc,YAAsB;CACxD,MAAM,aAAa,MAAM,UAAU,IAAI;CACvC,IAAI,SAAS,QAAQ,KAAA,KAAa,MAAM,WAAW,UAAU,GAAG,OAAO;CACvE,OAAO,MAAM,UAAU,MAAM,KAAK,QAAQ,KAAK,UAAU,CAAC;AAC3D;;AAGA,MAAaA,UAAQ,UAAqB,YAAkD;CAC3F,MAAM,WAAW,SAAiB,YAAY,MAAM,OAAO;CAE3D,OAAO;EACN,WAAW,SAAS,SAAS,SAAS,QAAQ,IAAI,CAAC;EACnD,iBAAiB,SAAS,SAAS,eAAe,QAAQ,IAAI,CAAC;EAC/D,YAAY,MAAM,QAAQ,WAAW,SAAS,UA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,SAAS,UACR,MAAM,OACL,OAAO,IAAI,aAAa;GACvB,MAAM,UAAU,OAAO,IACtB,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,QACD;GACA,OAAO,KAAK,SAAS,aAAa;GAClC,OAAOC,UACN,SACA,MAAM,cAAc,gBAAgB,KAAA,IACjC,KAAA,IACA,EAAE,aAAa,MAAM,cAAc,YAAY,CACnD;EACD,CAAC,CACF;EACD,UAAU,UACT,OAAO,QACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,SACD,IACC,YAAY,OAAO,IAAI,QAAQ,SAAS,iBAAiB,GAAG,QAAQ,CACtE;EACD,OAAO,UACN,OAAO,QACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,MACD,IACC,YAAY,OAAO,IAAI,KAAK,SAAS,YAAY,GAAG,QAAQ,CAC9D;EACD,OAAO,UACN,OAAO,QACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,MACD,IACC,YAAY,QAAQ,cAAc,QAAQ,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,UAAU,SAAS,OAAO,CAAC,CAAC,CAC5F;EACD,UAAU,UACT,OAAO,QACN,IACC,OAAO,UAAU,MAAM,0BAA0B,MAAM,EAAE,GACzD,SACD,IACC,YAAY,QAAQ,iBAAiB,QAAQ,OAAO,CAAC,CACvD;CACF,CAAC;AACF;AAEA,MAAM,UAAU,cAAc,OAAO;CACpC,YAAY,cAAc;CAC1B;CACA,SAAS;CACT;AACD,CAAC;AAED,MAAa,UAAU,WAAyB;CAAE,QAAQ;CAAoB,QAAQ;AAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resource-Ddd8Mdv2.mjs","names":[],"sources":["../../src/sandbox/instance.ts","../../src/sandbox/io.ts","../../src/sandbox/errors.ts","../../src/sandbox/fs/filesystem.ts","../../src/sandbox/shell/shell.ts","../../src/sandbox/resource.ts"],"sourcesContent":["export * from \"@codeworksh/plugin/sandbox/instance\";\n","export * from \"@codeworksh/plugin/sandbox/io\";\n","export * from \"@codeworksh/plugin/sandbox/errors\";\n","export * from \"@codeworksh/plugin/sandbox/filesystem\";\n","export * from \"@codeworksh/plugin/sandbox/shell\";\n","export * from \"@codeworksh/plugin/sandbox/resource\";\n"],"mappings":""}