@open-insight/core 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,676 @@
1
+ import { n as __reExport, t as __exportAll$1 } from "./rolldown-runtime-BBjsoOtd.mjs";
2
+ import { Context, Crypto, Data, Effect, Encoding, FileSystem, Latch, Layer, Match, Option, Path, Ref, Schema, SchemaGetter, SchemaIssue, Stream } from "effect";
3
+ import { Cmd, Copy, DockerfileParser, Entrypoint, Env, Run, User, Workdir } from "dockerfile-ast";
4
+ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
5
+ import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner";
6
+ import { ChildProcess } from "effect/unstable/process";
7
+ import "effect/unstable/ai";
8
+ import { AssistantMessage, Message, Prompt as Trajectory, SystemMessage, ToolMessage, UserMessage } from "effect/unstable/ai/Prompt";
9
+ //#region src/sandbox/snapshot/instruction.ts
10
+ var instruction_exports = /* @__PURE__ */ __exportAll$1({
11
+ Instruction: () => Instruction,
12
+ Instructions: () => Instructions,
13
+ assert: () => assert,
14
+ available: () => available,
15
+ cmd: () => cmd,
16
+ copy: () => copy,
17
+ entrypoint: () => entrypoint,
18
+ env: () => env,
19
+ make: () => make$4,
20
+ run: () => run,
21
+ user: () => user,
22
+ workdir: () => workdir
23
+ });
24
+ const Instruction = Schema.TaggedUnion({
25
+ Workdir: { path: Schema.String },
26
+ User: {
27
+ /**
28
+ * Accepts either `"user"` or `"user:group"`.
29
+ */
30
+ user: Schema.String },
31
+ Run: { cmd: Schema.String },
32
+ Env: { env: Schema.Record(Schema.String, Schema.String) },
33
+ Copy: {
34
+ src: Schema.Array(Schema.String),
35
+ dest: Schema.String
36
+ },
37
+ Cmd: { cmd: Schema.Array(Schema.String) },
38
+ Entrypoint: { cmd: Schema.Array(Schema.String) }
39
+ });
40
+ const workdir = (workdir) => Instruction.make({
41
+ _tag: "Workdir",
42
+ path: workdir
43
+ });
44
+ const user = (user) => Instruction.make({
45
+ _tag: "User",
46
+ user
47
+ });
48
+ const run = (cmd) => Instruction.make({
49
+ _tag: "Run",
50
+ cmd
51
+ });
52
+ const assert = (...cmd) => Instruction.make({
53
+ _tag: "Run",
54
+ cmd: cmd.join(" && ") + " || exit 1"
55
+ });
56
+ const available = (...program) => assert(...program.map((p) => `command -v ${p}`));
57
+ const env = (env) => Instruction.make({
58
+ _tag: "Env",
59
+ env
60
+ });
61
+ const copy = (src, dest) => Instruction.make({
62
+ _tag: "Copy",
63
+ src,
64
+ dest
65
+ });
66
+ const cmd = (cmd) => Instruction.make({
67
+ _tag: "Cmd",
68
+ cmd
69
+ });
70
+ const entrypoint = (cmd) => Instruction.make({
71
+ _tag: "Entrypoint",
72
+ cmd
73
+ });
74
+ const Instructions = Schema.Array(Instruction);
75
+ const make$4 = (...instructions) => Instructions.make(instructions);
76
+ //#endregion
77
+ //#region src/sandbox/snapshot/schema.ts
78
+ /**
79
+ * OCI image reference (e.g. `docker.io/library/node:18-alpine`).
80
+ */
81
+ const Image = Schema.String;
82
+ var Snapshot = class extends Schema.Class("Snapshot")({
83
+ image: Image,
84
+ instructions: Instructions
85
+ }) {};
86
+ /**
87
+ * The name of the snapshot.
88
+ *
89
+ * Each snapshot must use this name and mapped to different hash tags.
90
+ */
91
+ const SNAPSHOT_NAME = "open-insight-snapshot";
92
+ const make$3 = (args) => Snapshot.make(args);
93
+ //#endregion
94
+ //#region src/sandbox/snapshot/decode.ts
95
+ const encodeInstruction = (instruction) => Instruction.match(instruction, {
96
+ Workdir: ({ path }) => `WORKDIR ${path}`,
97
+ User: ({ user }) => `USER ${user}`,
98
+ Run: ({ cmd }) => `RUN ${cmd}`,
99
+ Env: ({ env }) => {
100
+ return `ENV ${Object.keys(env).sort().map((key) => `${key}=${env[key]}`).join(" ")}`;
101
+ },
102
+ Copy: ({ src, dest }) => `COPY ${JSON.stringify([...src, dest])}`,
103
+ Cmd: ({ cmd }) => `CMD ${JSON.stringify(cmd)}`,
104
+ Entrypoint: ({ cmd }) => `ENTRYPOINT ${JSON.stringify(cmd)}`
105
+ });
106
+ const invalidContainerfile = (containerfile, message) => new SchemaIssue.InvalidValue(Option.some(containerfile), { message });
107
+ const requireArguments = Effect.fn("containerfile/requireArguments")(function* (containerfile, instruction) {
108
+ const argumentsContent = instruction.getArgumentsContent();
109
+ if (argumentsContent === null) return yield* Effect.fail(invalidContainerfile(containerfile, `${instruction.getKeyword()} instruction is missing arguments`));
110
+ return argumentsContent;
111
+ });
112
+ const requireNoFlags = Effect.fn("containerfile/requireNoFlags")(function* (containerfile, instruction) {
113
+ if (instruction.getFlags().length !== 0) return yield* Effect.fail(invalidContainerfile(containerfile, `${instruction.getKeyword()} flags are not supported by Snapshot`));
114
+ });
115
+ const decodeJsonArguments = Effect.fn("containerfile/decodeJsonArguments")(function* (containerfile, instruction) {
116
+ const openingBracket = instruction.getOpeningBracket();
117
+ const closingBracket = instruction.getClosingBracket();
118
+ if (openingBracket === null || closingBracket === null) return yield* Effect.fail(invalidContainerfile(containerfile, `${instruction.getKeyword()} must use JSON array form`));
119
+ return instruction.getJSONStrings().map((argument) => argument.getJSONValue());
120
+ });
121
+ const decodeCopyArguments = Effect.fn("containerfile/decodeCopyArguments")(function* (containerfile, instruction) {
122
+ const openingBracket = instruction.getOpeningBracket();
123
+ const closingBracket = instruction.getClosingBracket();
124
+ if (openingBracket === null && closingBracket === null) return instruction.getArguments().map((argument) => argument.getValue());
125
+ if (openingBracket !== null && closingBracket !== null) return instruction.getJSONStrings().map((argument) => argument.getJSONValue());
126
+ return yield* Effect.fail(invalidContainerfile(containerfile, "COPY has an incomplete JSON array"));
127
+ });
128
+ const decodeInstruction = Effect.fn("containerfile/decodeInstruction")(function* (containerfile, instruction) {
129
+ if (instruction instanceof Workdir) return Instruction.make({
130
+ _tag: "Workdir",
131
+ path: yield* requireArguments(containerfile, instruction)
132
+ });
133
+ if (instruction instanceof User) return Instruction.make({
134
+ _tag: "User",
135
+ user: yield* requireArguments(containerfile, instruction)
136
+ });
137
+ if (instruction instanceof Run) {
138
+ yield* requireNoFlags(containerfile, instruction);
139
+ return Instruction.make({
140
+ _tag: "Run",
141
+ cmd: yield* requireArguments(containerfile, instruction)
142
+ });
143
+ }
144
+ if (instruction instanceof Env) {
145
+ const env = {};
146
+ for (const property of instruction.getProperties()) {
147
+ const key = property.getName();
148
+ const value = property.getValue();
149
+ if (value === null) return yield* Effect.fail(invalidContainerfile(containerfile, `ENV ${key} is missing a value`));
150
+ env[key] = value;
151
+ }
152
+ return Instruction.make({
153
+ _tag: "Env",
154
+ env
155
+ });
156
+ }
157
+ if (instruction instanceof Copy) {
158
+ yield* requireNoFlags(containerfile, instruction);
159
+ const argumentsContent = yield* decodeCopyArguments(containerfile, instruction);
160
+ if (argumentsContent.length < 2) return yield* Effect.fail(invalidContainerfile(containerfile, "COPY must include at least one source and one destination"));
161
+ return Instruction.make({
162
+ _tag: "Copy",
163
+ src: argumentsContent.slice(0, -1),
164
+ dest: argumentsContent[argumentsContent.length - 1]
165
+ });
166
+ }
167
+ if (instruction instanceof Cmd) {
168
+ yield* requireNoFlags(containerfile, instruction);
169
+ return Instruction.make({
170
+ _tag: "Cmd",
171
+ cmd: yield* decodeJsonArguments(containerfile, instruction)
172
+ });
173
+ }
174
+ if (instruction instanceof Entrypoint) {
175
+ yield* requireNoFlags(containerfile, instruction);
176
+ return Instruction.make({
177
+ _tag: "Entrypoint",
178
+ cmd: yield* decodeJsonArguments(containerfile, instruction)
179
+ });
180
+ }
181
+ return yield* Effect.fail(invalidContainerfile(containerfile, `${instruction.getKeyword()} instruction is not supported by Snapshot`));
182
+ });
183
+ const decodeContainerfile = Effect.fn("containerfile")(function* (containerfile) {
184
+ const dockerfile = yield* Effect.try({
185
+ try: () => DockerfileParser.parse(containerfile),
186
+ catch: (cause) => invalidContainerfile(containerfile, `Failed to parse Containerfile: ${String(cause)}`)
187
+ });
188
+ const froms = dockerfile.getFROMs();
189
+ if (froms.length !== 1) return yield* Effect.fail(invalidContainerfile(containerfile, `Expected exactly one FROM instruction, found ${froms.length}`));
190
+ const image = froms[0].getImage();
191
+ if (image === null) return yield* Effect.fail(invalidContainerfile(containerfile, "FROM instruction is missing an image"));
192
+ const instructions = [];
193
+ for (const instruction of dockerfile.getInstructions()) {
194
+ if (instruction === froms[0]) continue;
195
+ instructions.push(yield* decodeInstruction(containerfile, instruction));
196
+ }
197
+ return Snapshot.make({
198
+ image,
199
+ instructions
200
+ });
201
+ });
202
+ const Containerfile = Schema.String.pipe(Schema.decodeTo(Snapshot, {
203
+ decode: SchemaGetter.transformOrFail(decodeContainerfile),
204
+ encode: SchemaGetter.transform(({ image, instructions }) => {
205
+ return `${[`FROM ${image}`, ...instructions.map(encodeInstruction)].join("\n")}\n`;
206
+ })
207
+ }));
208
+ const encode = (snapshot) => Schema.encodeEffect(Containerfile)(snapshot);
209
+ const decode = (containerfile) => Schema.decodeEffect(Containerfile)(containerfile);
210
+ //#endregion
211
+ //#region src/sandbox/snapshot/derive.ts
212
+ const hash = Effect.fn(function* (snapshot) {
213
+ const crypto = yield* Crypto.Crypto;
214
+ const containerfile = yield* encode(snapshot);
215
+ const bytes = new TextEncoder().encode(containerfile);
216
+ const digest = yield* crypto.digest("SHA-256", bytes);
217
+ return Encoding.encodeHex(digest);
218
+ });
219
+ /**
220
+ * Get the name of a snapshot. The built snapshot must be tagged with this name.
221
+ *
222
+ * - The name of a snapshot is always `open-insight-snapshot`.
223
+ * - The tag of a snapshot is the SHA-256 hash of the snapshot's content.
224
+ */
225
+ const makeName$1 = Effect.fn(function* (snapshot) {
226
+ return `${SNAPSHOT_NAME}:${yield* hash(snapshot)}`;
227
+ });
228
+ /**
229
+ * Create a snapshot from an OCI image reference.
230
+ */
231
+ const fromImage = (image) => Snapshot.make({
232
+ image,
233
+ instructions: []
234
+ });
235
+ /**
236
+ * Extend an existing snapshot with a set of new instructions, without changing the base image.
237
+ */
238
+ const extend = ({ snapshot, instructions }) => Snapshot.make({
239
+ image: snapshot.image,
240
+ instructions: [...snapshot.instructions, ...instructions]
241
+ });
242
+ /**
243
+ * Derive a new snapshot from an existing snapshot with a set of new instructions.
244
+ *
245
+ * Note that the base image of the given snapshot must exist.
246
+ */
247
+ const derive = Effect.fn(function* ({ snapshot, instructions }) {
248
+ const image = yield* makeName$1(snapshot);
249
+ return Snapshot.make({
250
+ image,
251
+ instructions
252
+ });
253
+ });
254
+ //#endregion
255
+ //#region src/sandbox/context/schema.ts
256
+ const DistFileType = Schema.Literal(".tar.gz");
257
+ const ModeSchema = Schema.TaggedUnion({
258
+ Dir: { path: Schema.String },
259
+ Dist: {
260
+ url: Schema.String,
261
+ fileType: DistFileType
262
+ },
263
+ Script: {},
264
+ Cwd: {}
265
+ });
266
+ /**
267
+ * Context dir for snapshot update operations.
268
+ *
269
+ * Any file operations (e.g. COPY) must be resolved relative to this path.
270
+ */
271
+ const ContextSchema = Schema.String;
272
+ //#endregion
273
+ //#region src/sandbox/context/dist.ts
274
+ const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString);
275
+ const extractTarGz = Effect.fn(function* (archivePath) {
276
+ const fs = yield* FileSystem.FileSystem;
277
+ const spawner = yield* ChildProcessSpawner;
278
+ const dir = yield* fs.makeTempDirectory({ prefix: "open-insight-dist-" });
279
+ const exitCode = yield* spawner.exitCode(ChildProcess.make("tar", [
280
+ "-xzf",
281
+ archivePath,
282
+ "-C",
283
+ dir
284
+ ]));
285
+ if (exitCode !== 0) return yield* Effect.fail(/* @__PURE__ */ new Error(`tar exited with code ${exitCode}`));
286
+ return dir;
287
+ });
288
+ const resolveDistContext = Effect.fn(function* ({ url, fileType }) {
289
+ const fs = yield* FileSystem.FileSystem;
290
+ const parsedUrl = yield* decodeUrl(url);
291
+ const archivePath = yield* fs.makeTempFile({
292
+ prefix: "open-insight-dist-",
293
+ suffix: fileType
294
+ });
295
+ const bytes = yield* HttpClient.get(parsedUrl).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap((response) => response.arrayBuffer), Effect.map((buffer) => new Uint8Array(buffer)));
296
+ yield* fs.writeFile(archivePath, bytes);
297
+ if (fileType === ".tar.gz") return yield* extractTarGz(archivePath);
298
+ return yield* Effect.fail(/* @__PURE__ */ new Error(`Unsupported dist file type: ${String(fileType)}`));
299
+ });
300
+ const resolveDist = Effect.fn(function* (mode) {
301
+ return yield* resolveDistContext(mode).pipe(Effect.mapError(SandboxError.contextResolve(mode)));
302
+ });
303
+ //#endregion
304
+ //#region src/sandbox/context/index.ts
305
+ var context_exports = /* @__PURE__ */ __exportAll$1({
306
+ ContextSchema: () => ContextSchema,
307
+ Cwd: () => Cwd,
308
+ DistFileType: () => DistFileType,
309
+ ModeSchema: () => ModeSchema,
310
+ Script: () => Script,
311
+ make: () => make$2,
312
+ makeDir: () => makeDir,
313
+ makeDist: () => makeDist,
314
+ resolve: () => resolve
315
+ });
316
+ const resolve = Effect.fn(function* (mode) {
317
+ const path = yield* Path.Path;
318
+ return yield* ModeSchema.match(mode, {
319
+ Dir: ({ path }) => Effect.succeed(path),
320
+ Dist: resolveDist,
321
+ Script: () => Effect.succeed(import.meta.dirname),
322
+ Cwd: () => Effect.succeed(path.resolve("."))
323
+ });
324
+ });
325
+ const make$2 = (args) => ModeSchema.make(args);
326
+ /**
327
+ * Indicates that the context should be a specific directory.
328
+ */
329
+ const makeDir = (path) => ModeSchema.make({
330
+ _tag: "Dir",
331
+ path
332
+ });
333
+ /**
334
+ * Indicates that the context should be downloaded from a distribution archive.
335
+ */
336
+ const makeDist = ({ url, fileType }) => ModeSchema.make({
337
+ _tag: "Dist",
338
+ url,
339
+ fileType
340
+ });
341
+ /**
342
+ * Indicates that the context should be the script's directory.
343
+ * This is useful for resolving relative paths in scripts.
344
+ */
345
+ const Script = ModeSchema.make({ _tag: "Script" });
346
+ /**
347
+ * Indicates that the context should be the current working directory.
348
+ */
349
+ const Cwd = ModeSchema.make({ _tag: "Cwd" });
350
+ //#endregion
351
+ //#region src/sandbox/snapshot/build.ts
352
+ const fromContainerfile = Effect.fn(function* ({ context, filePath }) {
353
+ const fs = yield* FileSystem.FileSystem;
354
+ const path = yield* Path.Path;
355
+ const contextDir = yield* resolve(context);
356
+ const containerfilePath = path.join(contextDir, filePath);
357
+ return yield* decode(yield* fs.readFileString(containerfilePath));
358
+ });
359
+ //#endregion
360
+ //#region src/sandbox/snapshot/index.ts
361
+ var snapshot_exports = /* @__PURE__ */ __exportAll$1({
362
+ Containerfile: () => Containerfile,
363
+ Image: () => Image,
364
+ Inst: () => instruction_exports,
365
+ SNAPSHOT_NAME: () => SNAPSHOT_NAME,
366
+ Snapshot: () => Snapshot,
367
+ decode: () => decode,
368
+ derive: () => derive,
369
+ encode: () => encode,
370
+ extend: () => extend,
371
+ fromContainerfile: () => fromContainerfile,
372
+ fromImage: () => fromImage,
373
+ hash: () => hash,
374
+ make: () => make$3,
375
+ makeName: () => makeName$1
376
+ });
377
+ //#endregion
378
+ //#region src/sandbox/error.ts
379
+ var error_exports = /* @__PURE__ */ __exportAll$1({
380
+ ContextResolveError: () => ContextResolveError,
381
+ InstructionUnsupportedError: () => InstructionUnsupportedError,
382
+ ProviderError: () => ProviderError,
383
+ SandboxError: () => SandboxError,
384
+ SandboxErrorReason: () => SandboxErrorReason,
385
+ SandboxExecError: () => SandboxExecError,
386
+ SandboxExposeError: () => SandboxExposeError,
387
+ SnapshotError: () => SnapshotError,
388
+ SnapshotUnsupportedError: () => SnapshotUnsupportedError
389
+ });
390
+ var ContextResolveError = class extends Schema.TaggedErrorClass()("ContextResolveError", {
391
+ mode: ModeSchema,
392
+ cause: Schema.Defect()
393
+ }) {};
394
+ var SnapshotError = class extends Schema.TaggedErrorClass()("SnapshotError", {
395
+ kind: Schema.Union([Schema.Literal("build"), Schema.Literal("use")]),
396
+ snapshot: Snapshot,
397
+ cause: Schema.Defect(),
398
+ message: Schema.optional(Schema.String)
399
+ }) {};
400
+ var ProviderError = class extends Schema.TaggedErrorClass()("ProviderError", {
401
+ name: Schema.String,
402
+ cause: Schema.Defect()
403
+ }) {};
404
+ var SandboxExecError = class extends Schema.TaggedErrorClass()("SandboxExecError", {
405
+ name: Schema.String,
406
+ operation: Schema.String,
407
+ cause: Schema.Defect()
408
+ }) {};
409
+ var SandboxExposeError = class extends Schema.TaggedErrorClass()("SandboxExposeError", {
410
+ name: Schema.String,
411
+ sandboxPort: Schema.Number,
412
+ hostPort: Schema.Number,
413
+ cause: Schema.Defect()
414
+ }) {};
415
+ var SnapshotUnsupportedError = class extends Schema.TaggedErrorClass()("SnapshotUnsupportedError", {
416
+ name: Schema.String,
417
+ snapshot: Snapshot,
418
+ cause: Schema.Defect()
419
+ }) {};
420
+ var InstructionUnsupportedError = class extends Schema.TaggedErrorClass()("InstructionUnsupportedError", {
421
+ name: Schema.String,
422
+ snapshot: Snapshot,
423
+ instruction: Instruction
424
+ }) {};
425
+ const SandboxErrorReason = Schema.Union([
426
+ ContextResolveError,
427
+ ProviderError,
428
+ SnapshotError,
429
+ SandboxExecError,
430
+ SandboxExposeError,
431
+ SnapshotUnsupportedError,
432
+ InstructionUnsupportedError
433
+ ]);
434
+ var SandboxError = class extends Schema.TaggedErrorClass()("SandboxError", { reason: SandboxErrorReason }) {
435
+ static contextResolve = (mode) => (cause) => this.make({ reason: ContextResolveError.make({
436
+ mode,
437
+ cause
438
+ }) });
439
+ static provider = (name) => (cause) => this.make({ reason: ProviderError.make({
440
+ name,
441
+ cause
442
+ }) });
443
+ static snapshotBuild = (snapshot) => (cause) => this.make({ reason: SnapshotError.make({
444
+ kind: "build",
445
+ snapshot,
446
+ cause
447
+ }) });
448
+ static snapshotUsage = (snapshot) => (cause) => this.make({ reason: SnapshotError.make({
449
+ kind: "use",
450
+ snapshot,
451
+ cause
452
+ }) });
453
+ static sandboxExec = ({ name, operation }) => (cause) => this.make({ reason: SandboxExecError.make({
454
+ name,
455
+ operation,
456
+ cause
457
+ }) });
458
+ static sandboxExpose = ({ name, sandboxPort, hostPort }) => (cause) => this.make({ reason: SandboxExposeError.make({
459
+ name,
460
+ sandboxPort,
461
+ hostPort,
462
+ cause
463
+ }) });
464
+ static snapshotUnsupported = (name, snapshot) => (cause) => this.make({ reason: SnapshotUnsupportedError.make({
465
+ name,
466
+ snapshot,
467
+ cause
468
+ }) });
469
+ static instructionUnsupported = (name, snapshot, instruction) => this.make({ reason: InstructionUnsupportedError.make({
470
+ name,
471
+ snapshot,
472
+ instruction
473
+ }) });
474
+ };
475
+ //#endregion
476
+ //#region src/sandbox/provider/service.ts
477
+ var ProviderService$1 = class extends Context.Service()("sandbox/ProviderService") {};
478
+ //#endregion
479
+ //#region src/sandbox/provider/utils.ts
480
+ const bashQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
481
+ const formatBash = (command) => [command.command, ...command.args].map(bashQuote).join(" ");
482
+ //#endregion
483
+ //#region src/sandbox/provider/index.ts
484
+ var provider_exports = /* @__PURE__ */ __exportAll$1({
485
+ ProviderService: () => ProviderService$1,
486
+ bashQuote: () => bashQuote,
487
+ formatBash: () => formatBash
488
+ });
489
+ //#endregion
490
+ //#region ../utils/dist/rolldown-runtime-D7D4PA-g.mjs
491
+ var __defProp = Object.defineProperty;
492
+ var __exportAll = (all, no_symbols) => {
493
+ let target = {};
494
+ for (var name in all) __defProp(target, name, {
495
+ get: all[name],
496
+ enumerable: true
497
+ });
498
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
499
+ return target;
500
+ };
501
+ //#endregion
502
+ //#region ../utils/dist/index.mjs
503
+ var spawn_exports = /* @__PURE__ */ __exportAll({
504
+ SpawnError: () => SpawnError,
505
+ SpawnExitCodeError: () => SpawnExitCodeError,
506
+ SpawnService: () => SpawnService
507
+ });
508
+ var SpawnExitCodeError = class extends Data.TaggedError("SpawnExitCodeError") {
509
+ get message() {
510
+ return `process exited with code ${this.exitCode}`;
511
+ }
512
+ };
513
+ var SpawnError = class SpawnError extends Data.TaggedError("SpawnError") {
514
+ get message() {
515
+ return this.reason.message;
516
+ }
517
+ static platform = (err) => new SpawnError({ reason: err });
518
+ static exit = ({ exitCode, stdout, stderr }) => new SpawnError({ reason: new SpawnExitCodeError({
519
+ exitCode,
520
+ stdout,
521
+ stderr
522
+ }) });
523
+ };
524
+ var SpawnService = class SpawnService extends Context.Service()("packages/utils/SpawnService") {
525
+ static layer = Layer.effect(SpawnService, Effect.gen(function* () {
526
+ const spawner = yield* ChildProcessSpawner;
527
+ const streamText = (stream) => Stream.mkString(Stream.decodeText(stream));
528
+ const spawn = Effect.fn(function* (command) {
529
+ const handle = yield* spawner.spawn(command).pipe(Effect.mapError(SpawnError.platform));
530
+ const exitCode = yield* handle.exitCode.pipe(Effect.mapError(SpawnError.platform));
531
+ if (exitCode !== 0) {
532
+ const output = yield* Effect.all({
533
+ stdout: streamText(handle.stdout),
534
+ stderr: streamText(handle.stderr)
535
+ }, { concurrency: "unbounded" }).pipe(Effect.mapError(SpawnError.platform));
536
+ return yield* SpawnError.exit({
537
+ exitCode,
538
+ ...output
539
+ });
540
+ }
541
+ return handle;
542
+ });
543
+ const streamString = (command, options) => spawn(command).pipe(Effect.map((handle) => Stream.decodeText(options?.includeStderr === true ? handle.all : handle.stdout).pipe(Stream.mapError(SpawnError.platform))), Stream.unwrap);
544
+ const streamLines = (command, options) => Stream.splitLines(streamString(command, options));
545
+ const exitCode = (command) => spawn(command).pipe(Effect.scoped, Effect.flatMap((handle) => handle.exitCode.pipe(Effect.mapError(SpawnError.platform))));
546
+ const string = (command, options) => Stream.mkString(streamString(command, options));
547
+ const lines = (command, options) => Stream.runCollect(streamLines(command, options));
548
+ return {
549
+ spawn,
550
+ exitCode,
551
+ streamString,
552
+ streamLines,
553
+ lines,
554
+ string
555
+ };
556
+ }));
557
+ };
558
+ Effect.fn(function* (count) {
559
+ const countDown = yield* Ref.make(count);
560
+ const latch = yield* Latch.make();
561
+ return {
562
+ open: Effect.gen(function* () {
563
+ if ((yield* Ref.updateAndGet(countDown, (c) => c - 1)) <= 0) yield* latch.open;
564
+ }),
565
+ await: latch.await
566
+ };
567
+ });
568
+ //#endregion
569
+ //#region src/sandbox/sandbox/promise.ts
570
+ const asPromise = (_sandbox) => {
571
+ throw new Error("Not implemented yet");
572
+ };
573
+ //#endregion
574
+ //#region src/sandbox/sandbox/index.ts
575
+ const SANDBOX_NAME = "open-insight-sandbox";
576
+ const makeName = Effect.fn(function* (snapshot) {
577
+ const crypto = yield* Crypto.Crypto;
578
+ return `${SANDBOX_NAME}-${yield* hash(snapshot)}-${yield* crypto.randomUUIDv4}`;
579
+ });
580
+ const make = Effect.fn(function* ({ $: sandbox$, expose, download, upload, readFile, writeFile }) {
581
+ const spawner = yield* spawn_exports.SpawnService;
582
+ const $ = Effect.fn(function* (command, input) {
583
+ return yield* Match.value(command).pipe(Match.tag("StandardCommand", (cmd) => sandbox$(cmd, input)), Match.tag("PipedCommand", (cmd) => Effect.gen(function* () {
584
+ const output = yield* $(cmd.left, input);
585
+ return yield* $(cmd.right, output);
586
+ })), Match.exhaustive);
587
+ });
588
+ return {
589
+ $,
590
+ readFile: readFile === "cat" ? Effect.fn(function* ({ sandboxPath }) {
591
+ return yield* $(ChildProcess.make`cat ${sandboxPath}`);
592
+ }) : readFile,
593
+ writeFile: writeFile === "tee" ? Effect.fn(function* ({ sandboxPath, content }) {
594
+ yield* $(ChildProcess.make`tee ${sandboxPath}`, content);
595
+ }) : writeFile,
596
+ download: download === "rsync" ? Effect.fn(function* ({ sandboxPath, hostPath }) {
597
+ const content = yield* $(ChildProcess.make`cat ${sandboxPath}`);
598
+ yield* spawner.string(ChildProcess.make("tee", [hostPath], { stdin: { stream: Stream.make(content).pipe(Stream.encodeText) } })).pipe(Effect.mapError((e) => SandboxError.sandboxExec({
599
+ name: "host",
600
+ operation: `download ${sandboxPath} -> ${hostPath}`
601
+ })(e)));
602
+ }) : download,
603
+ upload: upload === "rsync" ? Effect.fn(function* ({ sandboxPath, hostPath }) {
604
+ const content = yield* spawner.string(ChildProcess.make`cat ${hostPath}`).pipe(Effect.mapError((e) => SandboxError.sandboxExec({
605
+ name: "host",
606
+ operation: `upload ${hostPath} -> ${sandboxPath}`
607
+ })(e)));
608
+ yield* $(ChildProcess.make`tee ${sandboxPath}`, content);
609
+ }) : upload,
610
+ expose
611
+ };
612
+ });
613
+ //#endregion
614
+ //#region src/sandbox/resource.ts
615
+ const NonNegativeNumber = Schema.Number.check(Schema.isGreaterThanOrEqualTo(0));
616
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
617
+ const ResourceLimitsSchema = Schema.Struct({
618
+ numCPUs: Schema.optionalKey(NonNegativeNumber).annotate({ description: "Maximum CPU cores available to the sandbox. Use fractional values such as 0.5 for half a core." }),
619
+ numGPUs: Schema.optionalKey(NonNegativeInt).annotate({ description: "Maximum GPU devices available to the sandbox." }),
620
+ memoryMiB: Schema.optionalKey(NonNegativeInt).annotate({ description: "Maximum memory available to the sandbox, in MiB." }),
621
+ diskMiB: Schema.optionalKey(NonNegativeInt).annotate({ description: "Maximum writable disk space available to the sandbox, in MiB." })
622
+ }).annotate({ description: "Sandbox resource limit configuration." });
623
+ //#endregion
624
+ //#region src/sandbox/index.ts
625
+ var sandbox_exports = /* @__PURE__ */ __exportAll$1({
626
+ Context: () => context_exports,
627
+ ContextResolveError: () => ContextResolveError,
628
+ Error: () => error_exports,
629
+ InstructionUnsupportedError: () => InstructionUnsupportedError,
630
+ ProviderError: () => ProviderError,
631
+ ProviderService: () => ProviderService$1,
632
+ ResourceLimitsSchema: () => ResourceLimitsSchema,
633
+ SANDBOX_NAME: () => SANDBOX_NAME,
634
+ SandboxError: () => SandboxError,
635
+ SandboxErrorReason: () => SandboxErrorReason,
636
+ SandboxExecError: () => SandboxExecError,
637
+ SandboxExposeError: () => SandboxExposeError,
638
+ Snapshot: () => snapshot_exports,
639
+ SnapshotError: () => SnapshotError,
640
+ SnapshotUnsupportedError: () => SnapshotUnsupportedError,
641
+ asPromise: () => asPromise,
642
+ bashQuote: () => bashQuote,
643
+ formatBash: () => formatBash,
644
+ make: () => make,
645
+ makeName: () => makeName
646
+ });
647
+ //#endregion
648
+ //#region src/agent/error.ts
649
+ var StreamError = class extends Schema.TaggedErrorClass()("StreamError", { cause: Schema.Defect() }) {};
650
+ const AgentErrorReason = Schema.Union([StreamError]);
651
+ var AgentError = class AgentError extends Schema.TaggedErrorClass()("AgentError", { reason: AgentErrorReason }) {
652
+ static stream = (error) => new AgentError({ reason: new StreamError({ cause: error }) });
653
+ };
654
+ //#endregion
655
+ //#region src/agent/service.ts
656
+ var ProviderService = class extends Context.Service()("agent/AgentService") {};
657
+ //#endregion
658
+ //#region src/agent/index.ts
659
+ var agent_exports = /* @__PURE__ */ __exportAll$1({
660
+ AgentError: () => AgentError,
661
+ AgentErrorReason: () => AgentErrorReason,
662
+ AssistantMessage: () => AssistantMessage,
663
+ Message: () => Message,
664
+ ProviderService: () => ProviderService,
665
+ StreamError: () => StreamError,
666
+ SystemMessage: () => SystemMessage,
667
+ ToolMessage: () => ToolMessage,
668
+ Trajectory: () => Trajectory,
669
+ UserMessage: () => UserMessage
670
+ });
671
+ import * as import_effect_unstable_ai from "effect/unstable/ai";
672
+ __reExport(agent_exports, import_effect_unstable_ai);
673
+ //#endregion
674
+ export { derive as A, Instructions as B, Script as C, resolve as D, makeDist as E, encode as F, Image as I, Snapshot as L, fromImage as M, hash as N, ContextSchema as O, makeName$1 as P, make$3 as R, Cwd as S, makeDir as T, instruction_exports as V, bashQuote as _, Trajectory as a, SandboxError as b, ProviderService as c, ResourceLimitsSchema as d, make as f, provider_exports as g, spawn_exports as h, ToolMessage as i, extend as j, ModeSchema as k, AgentError as l, asPromise as m, Message as n, UserMessage as o, makeName as p, SystemMessage as r, agent_exports as s, AssistantMessage as t, sandbox_exports as u, formatBash as v, make$2 as w, snapshot_exports as x, ProviderService$1 as y, Instruction as z };
675
+
676
+ //# sourceMappingURL=agent-2V5_4nlu.mjs.map