@deepagents/context 7.2.0 → 7.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +2 -2
- package/dist/index.js +1459 -1265
- package/dist/index.js.map +4 -4
- package/dist/lib/agent.d.ts +15 -4
- package/dist/lib/agent.d.ts.map +1 -1
- package/dist/lib/chat.d.ts +4 -2
- package/dist/lib/chat.d.ts.map +1 -1
- package/dist/lib/engine.d.ts.map +1 -1
- package/dist/lib/resolvers/loader-resolver.d.ts.map +1 -1
- package/dist/lib/sandbox/apple-container-sandbox.d.ts +7 -4
- package/dist/lib/sandbox/apple-container-sandbox.d.ts.map +1 -1
- package/dist/lib/sandbox/cli-process.d.ts +21 -21
- package/dist/lib/sandbox/cli-process.d.ts.map +1 -1
- package/dist/lib/sandbox/container-engine.d.ts +59 -40
- package/dist/lib/sandbox/container-engine.d.ts.map +1 -1
- package/dist/lib/sandbox/container-sandbox.d.ts +29 -35
- package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -1
- package/dist/lib/sandbox/daytona-sandbox.d.ts.map +1 -1
- package/dist/lib/sandbox/docker-sandbox.d.ts +88 -19
- package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
- package/dist/lib/sandbox/installers/installer.d.ts +5 -4
- package/dist/lib/sandbox/installers/installer.d.ts.map +1 -1
- package/dist/lib/sandbox/subcommand.d.ts.map +1 -1
- package/dist/lib/sandbox/types.d.ts +1 -1
- package/dist/lib/sandbox/types.d.ts.map +1 -1
- package/dist/lib/store/ddl.sqlite.d.ts +1 -1
- package/dist/lib/store/ddl.sqlite.d.ts.map +1 -1
- package/dist/lib/store/ddl.sqlserver.d.ts.map +1 -1
- package/dist/lib/store/sqlite.store.d.ts +1 -1
- package/dist/lib/store/sqlite.store.d.ts.map +1 -1
- package/dist/lib/stream/ddl.stream.sqlite.d.ts +1 -1
- package/dist/lib/stream/ddl.stream.sqlite.d.ts.map +1 -1
- package/dist/lib/stream/sqlite.stream-store.d.ts +1 -1
- package/dist/lib/stream/sqlite.stream-store.d.ts.map +1 -1
- package/dist/lib/telemetry/create-telemetry-integration.d.ts.map +1 -1
- package/dist/lib/telemetry/file/index.js +1 -7
- package/dist/lib/telemetry/file/index.js.map +2 -2
- package/dist/lib/telemetry/index.js +1 -7
- package/dist/lib/telemetry/index.js.map +2 -2
- package/dist/lib/telemetry/redact-telemetry-event.d.ts.map +1 -1
- package/dist/lib/tracing/exporter.d.ts.map +1 -1
- package/dist/lib/tracing/index.js +2 -1
- package/dist/lib/tracing/index.js.map +2 -2
- package/package.json +8 -6
package/dist/index.js
CHANGED
|
@@ -152,9 +152,10 @@ import {
|
|
|
152
152
|
isStepCount,
|
|
153
153
|
smoothStream,
|
|
154
154
|
streamText,
|
|
155
|
+
toUIMessageStream,
|
|
155
156
|
tool
|
|
156
157
|
} from "ai";
|
|
157
|
-
import
|
|
158
|
+
import { styleText } from "node:util";
|
|
158
159
|
import z from "zod";
|
|
159
160
|
import {
|
|
160
161
|
createRepairToolCall,
|
|
@@ -397,8 +398,8 @@ var Agent = class _Agent {
|
|
|
397
398
|
/**
|
|
398
399
|
* Stream a response from the agent.
|
|
399
400
|
*
|
|
400
|
-
* When guardrails are configured, `toUIMessageStream()`
|
|
401
|
-
* self-correction behavior. Direct access to
|
|
401
|
+
* When guardrails are configured, `toUIMessageStream()` provides
|
|
402
|
+
* self-correction behavior. Direct access to `result.stream` bypasses guardrails.
|
|
402
403
|
*
|
|
403
404
|
* @example
|
|
404
405
|
* ```typescript
|
|
@@ -427,14 +428,24 @@ var Agent = class _Agent {
|
|
|
427
428
|
prepareStep
|
|
428
429
|
);
|
|
429
430
|
if (this.#guardrails.length === 0) {
|
|
430
|
-
return
|
|
431
|
+
return {
|
|
432
|
+
result,
|
|
433
|
+
toUIMessageStream: (uiOptions) => toUIMessageStream({
|
|
434
|
+
stream: result.stream,
|
|
435
|
+
tools: this.tools,
|
|
436
|
+
...uiOptions
|
|
437
|
+
})
|
|
438
|
+
};
|
|
431
439
|
}
|
|
432
|
-
return
|
|
440
|
+
return {
|
|
433
441
|
result,
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
442
|
+
toUIMessageStream: this.#guardedUIMessageStream(
|
|
443
|
+
result,
|
|
444
|
+
options?.toolsContext,
|
|
445
|
+
options,
|
|
446
|
+
prepareStep
|
|
447
|
+
)
|
|
448
|
+
};
|
|
438
449
|
}
|
|
439
450
|
#withPrepareStep(prepareContext) {
|
|
440
451
|
const prepareStep = this.#options.prepareStep;
|
|
@@ -498,21 +509,20 @@ var Agent = class _Agent {
|
|
|
498
509
|
});
|
|
499
510
|
}
|
|
500
511
|
/**
|
|
501
|
-
*
|
|
512
|
+
* Build a UI message stream with guardrail protection.
|
|
502
513
|
*
|
|
503
514
|
* When a guardrail fails:
|
|
504
515
|
* 1. The feedback is written to the output stream (user sees the correction)
|
|
505
516
|
* 2. A finish-step is emitted, triggering onStepEnd to persist the self-correction
|
|
506
517
|
* 3. A new stream is started and the model continues from the correction
|
|
507
518
|
*/
|
|
508
|
-
#
|
|
519
|
+
#guardedUIMessageStream(result, toolsContext, config, prepareStep) {
|
|
509
520
|
const maxRetries = config?.maxRetries ?? this.#options.maxGuardrailRetries ?? 3;
|
|
510
521
|
const context = this.#options.context;
|
|
511
522
|
if (!context) {
|
|
512
523
|
throw new Error(`Agent ${this.#options.name} is missing a context.`);
|
|
513
524
|
}
|
|
514
|
-
|
|
515
|
-
result.toUIMessageStream = (options) => {
|
|
525
|
+
return (options) => {
|
|
516
526
|
const assistantMsgId = options?.generateMessageId?.();
|
|
517
527
|
let stepSaved = null;
|
|
518
528
|
return createUIMessageStream({
|
|
@@ -546,7 +556,11 @@ var Agent = class _Agent {
|
|
|
546
556
|
let guardrailFailed = false;
|
|
547
557
|
let failureFeedback = "";
|
|
548
558
|
let openTextId;
|
|
549
|
-
const uiStream =
|
|
559
|
+
const uiStream = toUIMessageStream({
|
|
560
|
+
stream: currentResult.stream,
|
|
561
|
+
tools: this.tools,
|
|
562
|
+
...options
|
|
563
|
+
});
|
|
550
564
|
for await (const part of uiStream) {
|
|
551
565
|
if (part.type === "text-start") openTextId = chunkId(part);
|
|
552
566
|
if (part.type === "text-end") openTextId = void 0;
|
|
@@ -559,7 +573,8 @@ var Agent = class _Agent {
|
|
|
559
573
|
guardrailFailed = true;
|
|
560
574
|
failureFeedback = checkResult.feedback;
|
|
561
575
|
console.log(
|
|
562
|
-
|
|
576
|
+
styleText(
|
|
577
|
+
"yellow",
|
|
563
578
|
`[${this.#options.name}] Guardrail triggered (attempt ${attempt}/${maxRetries}): ${failureFeedback.slice(0, 50)}...`
|
|
564
579
|
)
|
|
565
580
|
);
|
|
@@ -567,7 +582,8 @@ var Agent = class _Agent {
|
|
|
567
582
|
}
|
|
568
583
|
if (checkResult.type === "stop") {
|
|
569
584
|
console.log(
|
|
570
|
-
|
|
585
|
+
styleText(
|
|
586
|
+
"red",
|
|
571
587
|
`[${this.#options.name}] Guardrail stopped - unrecoverable error, no retry`
|
|
572
588
|
)
|
|
573
589
|
);
|
|
@@ -583,7 +599,8 @@ var Agent = class _Agent {
|
|
|
583
599
|
}
|
|
584
600
|
if (attempt >= maxRetries) {
|
|
585
601
|
console.error(
|
|
586
|
-
|
|
602
|
+
styleText(
|
|
603
|
+
"red",
|
|
587
604
|
`[${this.#options.name}] Guardrail retry limit (${maxRetries}) exceeded.`
|
|
588
605
|
)
|
|
589
606
|
);
|
|
@@ -607,7 +624,6 @@ var Agent = class _Agent {
|
|
|
607
624
|
}
|
|
608
625
|
});
|
|
609
626
|
};
|
|
610
|
-
return result;
|
|
611
627
|
}
|
|
612
628
|
asTool(props) {
|
|
613
629
|
return {
|
|
@@ -765,7 +781,7 @@ function structuredOutput(options) {
|
|
|
765
781
|
ignoreIncompleteToolCalls: true,
|
|
766
782
|
tools
|
|
767
783
|
}),
|
|
768
|
-
stopWhen: DEFAULT_STOP_WHEN,
|
|
784
|
+
stopWhen: options.stopWhen ?? DEFAULT_STOP_WHEN,
|
|
769
785
|
repairToolCall: createRepairToolCall(
|
|
770
786
|
options.model,
|
|
771
787
|
callOptions?.abortSignal
|
|
@@ -807,7 +823,7 @@ function structuredOutput(options) {
|
|
|
807
823
|
ignoreIncompleteToolCalls: true,
|
|
808
824
|
tools
|
|
809
825
|
}),
|
|
810
|
-
stopWhen: DEFAULT_STOP_WHEN,
|
|
826
|
+
stopWhen: options.stopWhen ?? DEFAULT_STOP_WHEN,
|
|
811
827
|
experimental_transform: callOptions?.transform ?? smoothStream(),
|
|
812
828
|
toolsContext: callOptions?.toolsContext,
|
|
813
829
|
output: Output.object({ schema: options.schema }),
|
|
@@ -1566,7 +1582,7 @@ ${entries}`;
|
|
|
1566
1582
|
let intersection = new Set(Object.keys(objects[0]));
|
|
1567
1583
|
for (const obj of objects) {
|
|
1568
1584
|
const keys = new Set(Object.keys(obj));
|
|
1569
|
-
intersection =
|
|
1585
|
+
intersection = intersection.intersection(keys);
|
|
1570
1586
|
for (const value of Object.values(obj)) {
|
|
1571
1587
|
if (value == null) continue;
|
|
1572
1588
|
if (!this.#isPrimitiveValue(value)) {
|
|
@@ -3047,6 +3063,7 @@ function pushLimited2(collected, chunk, maxItems, resolverName) {
|
|
|
3047
3063
|
}
|
|
3048
3064
|
|
|
3049
3065
|
// packages/context/src/lib/resolvers/loader-resolver.ts
|
|
3066
|
+
import { untilAborted } from "@zukhruf/async";
|
|
3050
3067
|
var FragmentLoaderResolver = class {
|
|
3051
3068
|
#resolvers;
|
|
3052
3069
|
#maxDepth;
|
|
@@ -3077,7 +3094,7 @@ var FragmentLoaderResolver = class {
|
|
|
3077
3094
|
}
|
|
3078
3095
|
async #walkData(value, ctx, depth, ancestors, path6) {
|
|
3079
3096
|
if (ctx.signal?.aborted) {
|
|
3080
|
-
throw ctx.signal.reason
|
|
3097
|
+
throw ctx.signal.reason;
|
|
3081
3098
|
}
|
|
3082
3099
|
if (depth > this.#maxDepth) {
|
|
3083
3100
|
throw new Error(
|
|
@@ -3093,10 +3110,7 @@ var FragmentLoaderResolver = class {
|
|
|
3093
3110
|
}
|
|
3094
3111
|
let resolved;
|
|
3095
3112
|
try {
|
|
3096
|
-
resolved = await
|
|
3097
|
-
handler.resolve(value, ctx),
|
|
3098
|
-
ctx.signal
|
|
3099
|
-
);
|
|
3113
|
+
resolved = await untilAborted(handler.resolve(value, ctx), ctx.signal);
|
|
3100
3114
|
} catch (cause) {
|
|
3101
3115
|
throw new Error(
|
|
3102
3116
|
`Async fragment '${path6}' failed in ${handler.name}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
@@ -3152,26 +3166,6 @@ var FragmentLoaderResolver = class {
|
|
|
3152
3166
|
}
|
|
3153
3167
|
return value;
|
|
3154
3168
|
}
|
|
3155
|
-
#raceWithSignal(promise, signal) {
|
|
3156
|
-
if (!signal) return promise;
|
|
3157
|
-
if (signal.aborted) {
|
|
3158
|
-
return Promise.reject(signal.reason ?? new Error("Resolver aborted"));
|
|
3159
|
-
}
|
|
3160
|
-
return new Promise((resolve3, reject) => {
|
|
3161
|
-
const onAbort = () => reject(signal.reason ?? new Error("Resolver aborted"));
|
|
3162
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
3163
|
-
promise.then(
|
|
3164
|
-
(value) => {
|
|
3165
|
-
signal.removeEventListener("abort", onAbort);
|
|
3166
|
-
resolve3(value);
|
|
3167
|
-
},
|
|
3168
|
-
(err) => {
|
|
3169
|
-
signal.removeEventListener("abort", onAbort);
|
|
3170
|
-
reject(err);
|
|
3171
|
-
}
|
|
3172
|
-
);
|
|
3173
|
-
});
|
|
3174
|
-
}
|
|
3175
3169
|
};
|
|
3176
3170
|
|
|
3177
3171
|
// packages/context/src/lib/resolvers/index.ts
|
|
@@ -3296,10 +3290,8 @@ var SavePipeline = class _SavePipeline {
|
|
|
3296
3290
|
|
|
3297
3291
|
// packages/context/src/lib/store/sqlite.store.ts
|
|
3298
3292
|
import { Declaration } from "@zukhruf/sqlite-drift";
|
|
3293
|
+
import { open } from "@zukhruf/sqlite-open";
|
|
3299
3294
|
import { transaction } from "@zukhruf/sqlite-transaction";
|
|
3300
|
-
import {
|
|
3301
|
-
DatabaseSync
|
|
3302
|
-
} from "node:sqlite";
|
|
3303
3295
|
import { z as z4 } from "zod";
|
|
3304
3296
|
|
|
3305
3297
|
// packages/context/src/lib/store/columns.ts
|
|
@@ -3315,12 +3307,10 @@ function parseJsonObject(text) {
|
|
|
3315
3307
|
|
|
3316
3308
|
// packages/context/src/lib/store/ddl.sqlite.ts
|
|
3317
3309
|
var SETUP = `
|
|
3318
|
-
PRAGMA journal_mode = WAL;
|
|
3319
3310
|
PRAGMA synchronous = NORMAL;
|
|
3320
3311
|
PRAGMA cache_size = -64000;
|
|
3321
3312
|
PRAGMA temp_store = MEMORY;
|
|
3322
3313
|
PRAGMA mmap_size = 268435456;
|
|
3323
|
-
PRAGMA busy_timeout = 5000;
|
|
3324
3314
|
`;
|
|
3325
3315
|
var statements = [
|
|
3326
3316
|
// createdAt/updatedAt: DEFAULT for insert, inline SET for updates
|
|
@@ -3549,7 +3539,7 @@ var SqliteContextStore = class extends ContextStore {
|
|
|
3549
3539
|
#sql;
|
|
3550
3540
|
constructor(pathOrDb) {
|
|
3551
3541
|
super();
|
|
3552
|
-
this.#db = typeof pathOrDb === "string" ?
|
|
3542
|
+
this.#db = typeof pathOrDb === "string" ? open(pathOrDb) : pathOrDb;
|
|
3553
3543
|
this.#db.exec(SETUP);
|
|
3554
3544
|
tables.apply(this.#db);
|
|
3555
3545
|
search.apply(this.#db);
|
|
@@ -4229,17 +4219,17 @@ var ContextEngine = class _ContextEngine {
|
|
|
4229
4219
|
`Active branch not found for chat "${this.#chatId}" after upsertChat`
|
|
4230
4220
|
);
|
|
4231
4221
|
}
|
|
4232
|
-
const
|
|
4233
|
-
this.#session =
|
|
4234
|
-
return
|
|
4222
|
+
const open3 = new OpenChat(chat2, branch);
|
|
4223
|
+
this.#session = open3;
|
|
4224
|
+
return open3;
|
|
4235
4225
|
}
|
|
4236
4226
|
/**
|
|
4237
4227
|
* Create a new branch from a specific message.
|
|
4238
4228
|
* Shared logic between rewind() and btw().
|
|
4239
4229
|
*/
|
|
4240
|
-
async #createBranchFrom(
|
|
4230
|
+
async #createBranchFrom(open3, messageId, switchTo) {
|
|
4241
4231
|
const branches = await this.#store.listBranches(this.#chatId);
|
|
4242
|
-
const baseName =
|
|
4232
|
+
const baseName = open3.branch.name;
|
|
4243
4233
|
const samePrefix = branches.filter(
|
|
4244
4234
|
(it) => it.name === baseName || it.name.startsWith(`${baseName}-v`)
|
|
4245
4235
|
);
|
|
@@ -4255,7 +4245,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
4255
4245
|
await this.#store.createBranch(newBranch);
|
|
4256
4246
|
if (switchTo) {
|
|
4257
4247
|
await this.#store.setActiveBranch(this.#chatId, newBranch.id);
|
|
4258
|
-
|
|
4248
|
+
open3.branch = { ...newBranch, isActive: true };
|
|
4259
4249
|
this.#pendingMessages = [];
|
|
4260
4250
|
}
|
|
4261
4251
|
const chain = await this.#store.getMessageChain(messageId);
|
|
@@ -4308,8 +4298,8 @@ var ContextEngine = class _ContextEngine {
|
|
|
4308
4298
|
* Includes persisted messages and pending messages in the turn count.
|
|
4309
4299
|
*/
|
|
4310
4300
|
async #getChainContext(pending = this.#pendingMessages) {
|
|
4311
|
-
const
|
|
4312
|
-
const stored =
|
|
4301
|
+
const open3 = await this.#open();
|
|
4302
|
+
const stored = open3.branch.headMessageId ? await this.#store.getMessageChain(open3.branch.headMessageId) : [];
|
|
4313
4303
|
return summarizeChain(stored, pending);
|
|
4314
4304
|
}
|
|
4315
4305
|
async getTurnCount() {
|
|
@@ -4317,10 +4307,10 @@ var ContextEngine = class _ContextEngine {
|
|
|
4317
4307
|
return turn;
|
|
4318
4308
|
}
|
|
4319
4309
|
async firstUserMessage() {
|
|
4320
|
-
const
|
|
4321
|
-
if (
|
|
4310
|
+
const open3 = await this.#open();
|
|
4311
|
+
if (open3.branch.headMessageId) {
|
|
4322
4312
|
const chain = await this.#store.getMessageChain(
|
|
4323
|
-
|
|
4313
|
+
open3.branch.headMessageId
|
|
4324
4314
|
);
|
|
4325
4315
|
for (const msg of chain) {
|
|
4326
4316
|
if (msg.name === "user") {
|
|
@@ -4349,7 +4339,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
4349
4339
|
* @throws if the pending tail is missing an id (programming error).
|
|
4350
4340
|
*/
|
|
4351
4341
|
async headMessage() {
|
|
4352
|
-
const
|
|
4342
|
+
const open3 = await this.#open();
|
|
4353
4343
|
if (this.#pendingMessages.length > 0) {
|
|
4354
4344
|
const tail = this.#pendingMessages[this.#pendingMessages.length - 1];
|
|
4355
4345
|
if (!tail.id) {
|
|
@@ -4359,8 +4349,8 @@ var ContextEngine = class _ContextEngine {
|
|
|
4359
4349
|
}
|
|
4360
4350
|
return { id: tail.id, name: tail.name };
|
|
4361
4351
|
}
|
|
4362
|
-
if (
|
|
4363
|
-
const msg = await this.#store.getMessage(
|
|
4352
|
+
if (open3.branch.headMessageId) {
|
|
4353
|
+
const msg = await this.#store.getMessage(open3.branch.headMessageId);
|
|
4364
4354
|
if (msg) return { id: msg.id, name: msg.name };
|
|
4365
4355
|
}
|
|
4366
4356
|
return void 0;
|
|
@@ -4380,12 +4370,12 @@ var ContextEngine = class _ContextEngine {
|
|
|
4380
4370
|
* For id-lookup use `headMessage()` instead — that one keeps placeholders.
|
|
4381
4371
|
*/
|
|
4382
4372
|
async getMessages() {
|
|
4383
|
-
const
|
|
4373
|
+
const open3 = await this.#open();
|
|
4384
4374
|
const messages = [];
|
|
4385
4375
|
const indexById = /* @__PURE__ */ new Map();
|
|
4386
|
-
if (
|
|
4376
|
+
if (open3.branch.headMessageId) {
|
|
4387
4377
|
const chain = await this.#store.getMessageChain(
|
|
4388
|
-
|
|
4378
|
+
open3.branch.headMessageId
|
|
4389
4379
|
);
|
|
4390
4380
|
for (const msg of chain) {
|
|
4391
4381
|
const data = requireUIMessage(msg.data, `Stored message "${msg.id}"`);
|
|
@@ -4521,14 +4511,14 @@ var ContextEngine = class _ContextEngine {
|
|
|
4521
4511
|
* ```
|
|
4522
4512
|
*/
|
|
4523
4513
|
async save(options) {
|
|
4524
|
-
const
|
|
4514
|
+
const open3 = await this.#open();
|
|
4525
4515
|
if (this.#pendingMessages.length === 0) {
|
|
4526
|
-
return { headMessageId:
|
|
4516
|
+
return { headMessageId: open3.branch.headMessageId ?? void 0 };
|
|
4527
4517
|
}
|
|
4528
4518
|
const pending = this.#pendingMessages;
|
|
4529
4519
|
this.#pendingMessages = [];
|
|
4530
4520
|
const pipeline = new SavePipeline(
|
|
4531
|
-
this.#asSavePipelineEngine(
|
|
4521
|
+
this.#asSavePipelineEngine(open3),
|
|
4532
4522
|
pending,
|
|
4533
4523
|
options?.branch ?? true
|
|
4534
4524
|
);
|
|
@@ -4541,7 +4531,11 @@ var ContextEngine = class _ContextEngine {
|
|
|
4541
4531
|
throw error;
|
|
4542
4532
|
}
|
|
4543
4533
|
}
|
|
4544
|
-
|
|
4534
|
+
/**
|
|
4535
|
+
* Writes the streamed assistant message: the whole message to the reserved
|
|
4536
|
+
* head, until createPrepareStep() binds a reminder session's segments.
|
|
4537
|
+
*/
|
|
4538
|
+
#writeAssistant = (headId, message2) => this.#writeWholeAssistant(headId, message2);
|
|
4545
4539
|
/**
|
|
4546
4540
|
* Build the `prepareStep` hook that injects reminders between model steps.
|
|
4547
4541
|
* Tool-output reminders are evaluated against the preceding step's completed
|
|
@@ -4568,7 +4562,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
4568
4562
|
stepOffset: 0,
|
|
4569
4563
|
lastStepNumber: null
|
|
4570
4564
|
};
|
|
4571
|
-
this.#
|
|
4565
|
+
this.#writeAssistant = (headId, message2) => this.#writeSessionSegment(session, headId, message2);
|
|
4572
4566
|
return async ({ steps, stepNumber, messages }) => {
|
|
4573
4567
|
if (stepNumber === 0 && session.lastStepNumber !== null) {
|
|
4574
4568
|
session.stepOffset += session.lastStepNumber + 1;
|
|
@@ -4693,53 +4687,57 @@ var ContextEngine = class _ContextEngine {
|
|
|
4693
4687
|
"writeAssistantSegment: expected an assistant message at chain head."
|
|
4694
4688
|
);
|
|
4695
4689
|
}
|
|
4696
|
-
|
|
4697
|
-
|
|
4690
|
+
await this.#writeAssistant(head.id, message2);
|
|
4691
|
+
}
|
|
4692
|
+
async #writeWholeAssistant(headId, message2) {
|
|
4693
|
+
this.set(assistant({ ...message2, id: headId }));
|
|
4694
|
+
await this.save({ branch: false });
|
|
4695
|
+
}
|
|
4696
|
+
async #writeSessionSegment(session, headId, message2) {
|
|
4697
|
+
let id = headId;
|
|
4698
4698
|
let parts = message2.parts;
|
|
4699
|
-
if (session) {
|
|
4700
|
-
|
|
4701
|
-
|
|
4702
|
-
|
|
4703
|
-
if (!initial || initial.name !== "assistant") {
|
|
4704
|
-
throw new Error(
|
|
4705
|
-
`writeAssistantSegment: initial segment "${initialId}" was not found`
|
|
4706
|
-
);
|
|
4707
|
-
}
|
|
4708
|
-
session.initialStepStarts = requireUIMessage(
|
|
4709
|
-
initial.data,
|
|
4710
|
-
`Stored assistant message "${initial.id}"`
|
|
4711
|
-
).parts.filter((part) => part.type === "step-start").length;
|
|
4712
|
-
}
|
|
4713
|
-
const streamStepStarts = message2.parts.flatMap(
|
|
4714
|
-
(part, index) => part.type === "step-start" ? [index] : []
|
|
4715
|
-
);
|
|
4716
|
-
const completedSteps = streamStepStarts.length - session.initialStepStarts;
|
|
4717
|
-
if (completedSteps < 0) {
|
|
4699
|
+
if (session.initialStepStarts === null) {
|
|
4700
|
+
const initialId = session.segments[0]?.id ?? headId;
|
|
4701
|
+
const initial = await this.#store.getMessage(initialId);
|
|
4702
|
+
if (!initial || initial.name !== "assistant") {
|
|
4718
4703
|
throw new Error(
|
|
4719
|
-
|
|
4704
|
+
`writeAssistantSegment: initial segment "${initialId}" was not found`
|
|
4720
4705
|
);
|
|
4721
4706
|
}
|
|
4722
|
-
|
|
4723
|
-
|
|
4707
|
+
session.initialStepStarts = requireUIMessage(
|
|
4708
|
+
initial.data,
|
|
4709
|
+
`Stored assistant message "${initial.id}"`
|
|
4710
|
+
).parts.filter((part) => part.type === "step-start").length;
|
|
4711
|
+
}
|
|
4712
|
+
const streamStepStarts = message2.parts.flatMap(
|
|
4713
|
+
(part, index) => part.type === "step-start" ? [index] : []
|
|
4714
|
+
);
|
|
4715
|
+
const completedSteps = streamStepStarts.length - session.initialStepStarts;
|
|
4716
|
+
if (completedSteps < 0) {
|
|
4717
|
+
throw new Error(
|
|
4718
|
+
"writeAssistantSegment: response lost an existing step boundary"
|
|
4724
4719
|
);
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
|
|
4728
|
-
|
|
4729
|
-
|
|
4730
|
-
|
|
4731
|
-
|
|
4732
|
-
|
|
4733
|
-
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
-
|
|
4737
|
-
|
|
4738
|
-
const lastSegment = session.segments.at(-1);
|
|
4739
|
-
if (lastSegment) {
|
|
4740
|
-
id = lastSegment.id;
|
|
4741
|
-
parts = [];
|
|
4720
|
+
}
|
|
4721
|
+
const segmentIndex = session.segments.findLastIndex(
|
|
4722
|
+
(candidate) => candidate.startStep < completedSteps
|
|
4723
|
+
);
|
|
4724
|
+
if (segmentIndex >= 0) {
|
|
4725
|
+
const segment = session.segments[segmentIndex];
|
|
4726
|
+
id = segment.id;
|
|
4727
|
+
if (segmentIndex > 0) {
|
|
4728
|
+
const start = streamStepStarts[session.initialStepStarts + segment.startStep];
|
|
4729
|
+
if (start === void 0) {
|
|
4730
|
+
throw new Error(
|
|
4731
|
+
`writeAssistantSegment: response is missing step ${segment.startStep + 1}`
|
|
4732
|
+
);
|
|
4742
4733
|
}
|
|
4734
|
+
parts = message2.parts.slice(start);
|
|
4735
|
+
}
|
|
4736
|
+
} else {
|
|
4737
|
+
const lastSegment = session.segments.at(-1);
|
|
4738
|
+
if (lastSegment) {
|
|
4739
|
+
id = lastSegment.id;
|
|
4740
|
+
parts = [];
|
|
4743
4741
|
}
|
|
4744
4742
|
}
|
|
4745
4743
|
const fragment2 = assistant({
|
|
@@ -4747,11 +4745,6 @@ var ContextEngine = class _ContextEngine {
|
|
|
4747
4745
|
id,
|
|
4748
4746
|
parts
|
|
4749
4747
|
});
|
|
4750
|
-
if (!session) {
|
|
4751
|
-
this.set(fragment2);
|
|
4752
|
-
await this.save({ branch: false });
|
|
4753
|
-
return;
|
|
4754
|
-
}
|
|
4755
4748
|
const stored = await this.#store.getMessage(id);
|
|
4756
4749
|
if (!stored) {
|
|
4757
4750
|
throw new Error(
|
|
@@ -4881,7 +4874,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
4881
4874
|
session.terminalToolParts
|
|
4882
4875
|
),
|
|
4883
4876
|
sandbox,
|
|
4884
|
-
firedOnceIds:
|
|
4877
|
+
firedOnceIds: chain.firedOnceIds.union(session.firedOnceIds)
|
|
4885
4878
|
};
|
|
4886
4879
|
}
|
|
4887
4880
|
async #evaluateToolOutputReminders(outcomes, session, chain, sandbox) {
|
|
@@ -4897,10 +4890,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
4897
4890
|
const whenCtx = this.#buildWhenCtx(chain, currentMessage);
|
|
4898
4891
|
whenCtx.sandbox = sandbox;
|
|
4899
4892
|
whenCtx.toolOutcome = outcome;
|
|
4900
|
-
whenCtx.firedOnceIds =
|
|
4901
|
-
...chain.firedOnceIds,
|
|
4902
|
-
...session.firedOnceIds
|
|
4903
|
-
]);
|
|
4893
|
+
whenCtx.firedOnceIds = chain.firedOnceIds.union(session.firedOnceIds);
|
|
4904
4894
|
const matched = await evaluateFiredReminders(configs, whenCtx);
|
|
4905
4895
|
texts.push(...matched.map((item) => item.resolved.text));
|
|
4906
4896
|
for (const id of matched.flatMap((item) => item.onceIds)) {
|
|
@@ -4910,36 +4900,36 @@ var ContextEngine = class _ContextEngine {
|
|
|
4910
4900
|
}
|
|
4911
4901
|
return { texts, onceIds: [...onceIds] };
|
|
4912
4902
|
}
|
|
4913
|
-
#asSavePipelineEngine(
|
|
4903
|
+
#asSavePipelineEngine(open3) {
|
|
4914
4904
|
return {
|
|
4915
4905
|
store: this.#store,
|
|
4916
4906
|
chatId: this.#chatId,
|
|
4917
4907
|
getActiveBranch: () => ({
|
|
4918
|
-
id:
|
|
4919
|
-
headMessageId:
|
|
4908
|
+
id: open3.branch.id,
|
|
4909
|
+
headMessageId: open3.branch.headMessageId
|
|
4920
4910
|
}),
|
|
4921
4911
|
commitHead: async (headMessageId, expectedHeadMessageId) => {
|
|
4922
4912
|
const committed = await this.#store.updateBranchHead(
|
|
4923
|
-
|
|
4913
|
+
open3.branch.id,
|
|
4924
4914
|
headMessageId,
|
|
4925
4915
|
expectedHeadMessageId
|
|
4926
4916
|
);
|
|
4927
4917
|
if (committed) {
|
|
4928
|
-
|
|
4918
|
+
open3.branch.headMessageId = headMessageId;
|
|
4929
4919
|
}
|
|
4930
4920
|
return committed;
|
|
4931
4921
|
},
|
|
4932
4922
|
refreshBranch: async () => {
|
|
4933
4923
|
const fresh = await this.#store.getBranch(
|
|
4934
4924
|
this.#chatId,
|
|
4935
|
-
|
|
4925
|
+
open3.branch.name
|
|
4936
4926
|
);
|
|
4937
4927
|
if (!fresh) {
|
|
4938
4928
|
throw new Error(
|
|
4939
|
-
`Branch "${
|
|
4929
|
+
`Branch "${open3.branch.name}" not found for chat "${this.#chatId}"`
|
|
4940
4930
|
);
|
|
4941
4931
|
}
|
|
4942
|
-
|
|
4932
|
+
open3.branch = fresh;
|
|
4943
4933
|
return { id: fresh.id, headMessageId: fresh.headMessageId };
|
|
4944
4934
|
},
|
|
4945
4935
|
rewindForUpdate: (parentId) => this.#rewindForUpdate(parentId)
|
|
@@ -4958,7 +4948,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
4958
4948
|
* @returns Estimate result with token counts, costs, and per-fragment breakdown
|
|
4959
4949
|
*/
|
|
4960
4950
|
async estimate(modelId, options = {}) {
|
|
4961
|
-
const
|
|
4951
|
+
const open3 = await this.#open();
|
|
4962
4952
|
await this.#loaderResolver.resolve(this.#fragments, {
|
|
4963
4953
|
sandbox: options.sandbox,
|
|
4964
4954
|
context: this,
|
|
@@ -4987,9 +4977,9 @@ var ContextEngine = class _ContextEngine {
|
|
|
4987
4977
|
cost
|
|
4988
4978
|
});
|
|
4989
4979
|
}
|
|
4990
|
-
if (
|
|
4980
|
+
if (open3.branch.headMessageId) {
|
|
4991
4981
|
const chain = await this.#store.getMessageChain(
|
|
4992
|
-
|
|
4982
|
+
open3.branch.headMessageId
|
|
4993
4983
|
);
|
|
4994
4984
|
for (const msg of chain) {
|
|
4995
4985
|
const content = estimateMessageContent(msg.data);
|
|
@@ -5061,7 +5051,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
5061
5051
|
* ```
|
|
5062
5052
|
*/
|
|
5063
5053
|
async rewind(messageId) {
|
|
5064
|
-
const
|
|
5054
|
+
const open3 = await this.#open();
|
|
5065
5055
|
const message2 = await this.#store.getMessage(messageId);
|
|
5066
5056
|
if (!message2) {
|
|
5067
5057
|
throw new Error(`Message "${messageId}" not found`);
|
|
@@ -5069,7 +5059,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
5069
5059
|
if (message2.chatId !== this.#chatId) {
|
|
5070
5060
|
throw new Error(`Message "${messageId}" belongs to a different chat`);
|
|
5071
5061
|
}
|
|
5072
|
-
return this.#createBranchFrom(
|
|
5062
|
+
return this.#createBranchFrom(open3, messageId, true);
|
|
5073
5063
|
}
|
|
5074
5064
|
/**
|
|
5075
5065
|
* Create a checkpoint at the current position.
|
|
@@ -5091,15 +5081,15 @@ var ContextEngine = class _ContextEngine {
|
|
|
5091
5081
|
* ```
|
|
5092
5082
|
*/
|
|
5093
5083
|
async checkpoint(name) {
|
|
5094
|
-
const
|
|
5095
|
-
if (!
|
|
5084
|
+
const open3 = await this.#open();
|
|
5085
|
+
if (!open3.branch.headMessageId) {
|
|
5096
5086
|
throw new Error("Cannot create checkpoint: no messages in conversation");
|
|
5097
5087
|
}
|
|
5098
5088
|
const checkpoint = {
|
|
5099
5089
|
id: crypto.randomUUID(),
|
|
5100
5090
|
chatId: this.#chatId,
|
|
5101
5091
|
name,
|
|
5102
|
-
messageId:
|
|
5092
|
+
messageId: open3.branch.headMessageId,
|
|
5103
5093
|
createdAt: Date.now()
|
|
5104
5094
|
};
|
|
5105
5095
|
await this.#store.createCheckpoint(checkpoint);
|
|
@@ -5152,13 +5142,13 @@ var ContextEngine = class _ContextEngine {
|
|
|
5152
5142
|
* ```
|
|
5153
5143
|
*/
|
|
5154
5144
|
async switchBranch(name) {
|
|
5155
|
-
const
|
|
5145
|
+
const open3 = await this.#open();
|
|
5156
5146
|
const branch = await this.#store.getBranch(this.#chatId, name);
|
|
5157
5147
|
if (!branch) {
|
|
5158
5148
|
throw new Error(`Branch "${name}" not found in chat "${this.#chatId}"`);
|
|
5159
5149
|
}
|
|
5160
5150
|
await this.#store.setActiveBranch(this.#chatId, branch.id);
|
|
5161
|
-
|
|
5151
|
+
open3.branch = { ...branch, isActive: true };
|
|
5162
5152
|
this.#pendingMessages = [];
|
|
5163
5153
|
}
|
|
5164
5154
|
/**
|
|
@@ -5193,11 +5183,11 @@ var ContextEngine = class _ContextEngine {
|
|
|
5193
5183
|
* ```
|
|
5194
5184
|
*/
|
|
5195
5185
|
async btw() {
|
|
5196
|
-
const
|
|
5197
|
-
if (!
|
|
5186
|
+
const open3 = await this.#open();
|
|
5187
|
+
if (!open3.branch.headMessageId) {
|
|
5198
5188
|
throw new Error("Cannot create btw branch: no messages in conversation");
|
|
5199
5189
|
}
|
|
5200
|
-
return this.#createBranchFrom(
|
|
5190
|
+
return this.#createBranchFrom(open3, open3.branch.headMessageId, false);
|
|
5201
5191
|
}
|
|
5202
5192
|
/**
|
|
5203
5193
|
* Update metadata for the current chat.
|
|
@@ -5213,8 +5203,8 @@ var ContextEngine = class _ContextEngine {
|
|
|
5213
5203
|
* ```
|
|
5214
5204
|
*/
|
|
5215
5205
|
async updateChat(updates) {
|
|
5216
|
-
const
|
|
5217
|
-
|
|
5206
|
+
const open3 = await this.#open();
|
|
5207
|
+
open3.chat = await this.#store.updateChat(this.#chatId, ({ metadata }) => ({
|
|
5218
5208
|
title: updates.title,
|
|
5219
5209
|
metadata: updates.metadata === void 0 ? void 0 : { ...metadata, ...updates.metadata }
|
|
5220
5210
|
}));
|
|
@@ -5233,8 +5223,8 @@ var ContextEngine = class _ContextEngine {
|
|
|
5233
5223
|
* ```
|
|
5234
5224
|
*/
|
|
5235
5225
|
async trackUsage(usage) {
|
|
5236
|
-
const
|
|
5237
|
-
|
|
5226
|
+
const open3 = await this.#open();
|
|
5227
|
+
open3.chat = await this.#store.updateChat(this.#chatId, ({ metadata }) => {
|
|
5238
5228
|
const storedUsage = metadata?.usage;
|
|
5239
5229
|
const currentUsage = isLanguageModelUsage(storedUsage) ? storedUsage : void 0;
|
|
5240
5230
|
return {
|
|
@@ -5309,7 +5299,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
5309
5299
|
* ```
|
|
5310
5300
|
*/
|
|
5311
5301
|
async inspect(options) {
|
|
5312
|
-
const
|
|
5302
|
+
const open3 = await this.#open();
|
|
5313
5303
|
const { renderer } = options;
|
|
5314
5304
|
const estimateResult = await this.estimate(options.modelId, {
|
|
5315
5305
|
renderer,
|
|
@@ -5318,9 +5308,9 @@ var ContextEngine = class _ContextEngine {
|
|
|
5318
5308
|
});
|
|
5319
5309
|
const rendered = renderer.render(this.#renderableFragments);
|
|
5320
5310
|
const persistedMessages = [];
|
|
5321
|
-
if (
|
|
5311
|
+
if (open3.branch.headMessageId) {
|
|
5322
5312
|
const chain = await this.#store.getMessageChain(
|
|
5323
|
-
|
|
5313
|
+
open3.branch.headMessageId
|
|
5324
5314
|
);
|
|
5325
5315
|
persistedMessages.push(...chain);
|
|
5326
5316
|
}
|
|
@@ -5336,7 +5326,7 @@ var ContextEngine = class _ContextEngine {
|
|
|
5336
5326
|
graph,
|
|
5337
5327
|
meta: {
|
|
5338
5328
|
chatId: this.#chatId,
|
|
5339
|
-
branch:
|
|
5329
|
+
branch: open3.branch.name,
|
|
5340
5330
|
timestamp: Date.now()
|
|
5341
5331
|
}
|
|
5342
5332
|
};
|
|
@@ -5834,7 +5824,24 @@ async function chat(agent2, ...args) {
|
|
|
5834
5824
|
const settled = isAborted ? {
|
|
5835
5825
|
...responseMessage,
|
|
5836
5826
|
parts: sanitizeAbortedParts(responseMessage.parts)
|
|
5837
|
-
} :
|
|
5827
|
+
} : {
|
|
5828
|
+
...responseMessage,
|
|
5829
|
+
// A provider can end at its token limit midway through arguments.
|
|
5830
|
+
// That call failed; it is not waiting for client input or approval.
|
|
5831
|
+
parts: responseMessage.parts.map((part) => {
|
|
5832
|
+
if (!isToolUIPart(part) || part.state !== "input-streaming")
|
|
5833
|
+
return part;
|
|
5834
|
+
const failed = {
|
|
5835
|
+
...part,
|
|
5836
|
+
state: "output-error",
|
|
5837
|
+
input: part.input,
|
|
5838
|
+
errorText: "Tool input ended before the call was complete."
|
|
5839
|
+
};
|
|
5840
|
+
delete failed.rawInput;
|
|
5841
|
+
delete failed.inputEncoding;
|
|
5842
|
+
return failed;
|
|
5843
|
+
})
|
|
5844
|
+
};
|
|
5838
5845
|
const finalMetadata = await options?.finalAssistantMetadata?.(settled);
|
|
5839
5846
|
const mergedMetadata = {
|
|
5840
5847
|
...isRecord(settled.metadata) ? settled.metadata : {},
|
|
@@ -5842,7 +5849,7 @@ async function chat(agent2, ...args) {
|
|
|
5842
5849
|
};
|
|
5843
5850
|
const message2 = Object.keys(mergedMetadata).length > 0 ? { ...settled, metadata: mergedMetadata } : settled;
|
|
5844
5851
|
await context.writeAssistantSegment(message2);
|
|
5845
|
-
const usage = await result?.usage;
|
|
5852
|
+
const usage = await result?.result.usage;
|
|
5846
5853
|
if (usage !== void 0) {
|
|
5847
5854
|
await context.trackUsage(usage);
|
|
5848
5855
|
}
|
|
@@ -7045,7 +7052,7 @@ function review2(options) {
|
|
|
7045
7052
|
var socraticPlan = { path: PLAN_FILE_PATH, instructions: instructions2, review: review2 };
|
|
7046
7053
|
|
|
7047
7054
|
// packages/context/src/lib/guardrails/error-recovery.guardrail.ts
|
|
7048
|
-
import
|
|
7055
|
+
import { styleText as styleText2 } from "node:util";
|
|
7049
7056
|
var errorRecoveryGuardrail = {
|
|
7050
7057
|
id: "error-recovery",
|
|
7051
7058
|
name: "API Error Recovery",
|
|
@@ -7054,16 +7061,16 @@ var errorRecoveryGuardrail = {
|
|
|
7054
7061
|
return pass(part);
|
|
7055
7062
|
}
|
|
7056
7063
|
const errorText = part.errorText || "";
|
|
7057
|
-
const prefix =
|
|
7064
|
+
const prefix = styleText2(["bold", "magenta"], "[ErrorRecovery]");
|
|
7058
7065
|
console.log(
|
|
7059
|
-
`${prefix} ${
|
|
7066
|
+
`${prefix} ${styleText2("red", "Caught error:")} ${styleText2("dim", errorText.slice(0, 150))}`
|
|
7060
7067
|
);
|
|
7061
7068
|
const logAndFail = (pattern, feedback) => {
|
|
7062
7069
|
console.log(
|
|
7063
|
-
`${prefix} ${
|
|
7070
|
+
`${prefix} ${styleText2("yellow", "Pattern:")} ${styleText2("cyan", pattern)}`
|
|
7064
7071
|
);
|
|
7065
7072
|
console.log(
|
|
7066
|
-
`${prefix} ${
|
|
7073
|
+
`${prefix} ${styleText2("green", "Feedback:")} ${styleText2("dim", feedback.slice(0, 80))}...`
|
|
7067
7074
|
);
|
|
7068
7075
|
return fail(feedback);
|
|
7069
7076
|
};
|
|
@@ -7136,7 +7143,7 @@ var errorRecoveryGuardrail = {
|
|
|
7136
7143
|
);
|
|
7137
7144
|
}
|
|
7138
7145
|
console.log(
|
|
7139
|
-
`${prefix} ${
|
|
7146
|
+
`${prefix} ${styleText2("yellow", "Unknown error - stopping without retry")}`
|
|
7140
7147
|
);
|
|
7141
7148
|
return stop(part);
|
|
7142
7149
|
}
|
|
@@ -7156,8 +7163,8 @@ function render(tag, ...fragments) {
|
|
|
7156
7163
|
import { createRepairToolCall as createRepairToolCall2 } from "@deepagents/agent";
|
|
7157
7164
|
|
|
7158
7165
|
// packages/context/src/lib/sandbox/apple-container-sandbox.ts
|
|
7159
|
-
import
|
|
7160
|
-
import { spawn as
|
|
7166
|
+
import spawn, { SubprocessError as SubprocessError2 } from "nano-spawn";
|
|
7167
|
+
import { spawn as childSpawn } from "node:child_process";
|
|
7161
7168
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
7162
7169
|
import { tmpdir } from "node:os";
|
|
7163
7170
|
import { join } from "node:path";
|
|
@@ -7251,12 +7258,6 @@ var AppleContainerVolumeRemoveError = class extends AppleContainerSandboxError {
|
|
|
7251
7258
|
}
|
|
7252
7259
|
};
|
|
7253
7260
|
|
|
7254
|
-
// packages/context/src/lib/sandbox/container-sandbox.ts
|
|
7255
|
-
import spawn2 from "nano-spawn";
|
|
7256
|
-
import { spawn as childSpawn } from "node:child_process";
|
|
7257
|
-
import { createHash } from "node:crypto";
|
|
7258
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
7259
|
-
|
|
7260
7261
|
// packages/context/src/lib/sandbox/cli-process.ts
|
|
7261
7262
|
import { SubprocessError } from "nano-spawn";
|
|
7262
7263
|
import { Readable } from "node:stream";
|
|
@@ -7330,15 +7331,42 @@ function base64WriteCommands(path6, content) {
|
|
|
7330
7331
|
}
|
|
7331
7332
|
return commands;
|
|
7332
7333
|
}
|
|
7333
|
-
function
|
|
7334
|
-
|
|
7334
|
+
async function readFileOverExec(executeCommand, path6) {
|
|
7335
|
+
const result = await executeCommand(`base64 ${shellQuote(path6)}`);
|
|
7336
|
+
if (result.exitCode !== 0) {
|
|
7337
|
+
throw new Error(`Failed to read file "${path6}": ${result.stderr}`);
|
|
7338
|
+
}
|
|
7339
|
+
return Buffer.from(result.stdout, "base64");
|
|
7335
7340
|
}
|
|
7336
|
-
function
|
|
7337
|
-
|
|
7341
|
+
async function existsOverExec(executeCommand, path6) {
|
|
7342
|
+
const result = await executeCommand(
|
|
7343
|
+
`test -e ${shellQuote(path6)} && printf true || printf false`
|
|
7344
|
+
);
|
|
7345
|
+
if (result.stdout === "true") return true;
|
|
7346
|
+
if (result.stdout === "false") return false;
|
|
7347
|
+
throw new Error(`Failed to check "${path6}": ${result.stderr}`);
|
|
7348
|
+
}
|
|
7349
|
+
async function writeFilesOverExec(executeCommand, files) {
|
|
7350
|
+
for (const file of files) {
|
|
7351
|
+
const dir = file.path.substring(0, file.path.lastIndexOf("/"));
|
|
7352
|
+
if (dir) {
|
|
7353
|
+
await executeCommand(`mkdir -p ${shellQuote(dir)}`);
|
|
7354
|
+
}
|
|
7355
|
+
for (const command of base64WriteCommands(file.path, file.content)) {
|
|
7356
|
+
const result = await executeCommand(command);
|
|
7357
|
+
if (result.exitCode !== 0) {
|
|
7358
|
+
throw new Error(
|
|
7359
|
+
`Failed to write file "${file.path}": ${result.stderr}`
|
|
7360
|
+
);
|
|
7361
|
+
}
|
|
7362
|
+
}
|
|
7363
|
+
}
|
|
7338
7364
|
}
|
|
7339
7365
|
|
|
7340
|
-
// packages/context/src/lib/sandbox/
|
|
7341
|
-
import
|
|
7366
|
+
// packages/context/src/lib/sandbox/container-sandbox.ts
|
|
7367
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7368
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
7369
|
+
import { setTimeout as setTimeout2 } from "node:timers/promises";
|
|
7342
7370
|
|
|
7343
7371
|
// packages/context/src/lib/sandbox/docker-sandbox-errors.ts
|
|
7344
7372
|
var DockerSandboxError = class extends ContainerSandboxError {
|
|
@@ -7481,42 +7509,18 @@ function isDebianBased(image) {
|
|
|
7481
7509
|
const debianPatterns = ["debian", "ubuntu", "node", "python"];
|
|
7482
7510
|
return debianPatterns.some((pattern) => lower.includes(pattern));
|
|
7483
7511
|
}
|
|
7484
|
-
function createInstallerContext(
|
|
7512
|
+
function createInstallerContext(shell, containerId, image) {
|
|
7485
7513
|
const packageManager = isDebianBased(image) ? "apt-get" : "apk";
|
|
7486
7514
|
let archPromise = null;
|
|
7487
7515
|
const ensuredTools = /* @__PURE__ */ new Set();
|
|
7488
7516
|
let aptUpdated = false;
|
|
7489
|
-
const exec =
|
|
7490
|
-
try {
|
|
7491
|
-
const result = await spawn(cli.binary, [
|
|
7492
|
-
"exec",
|
|
7493
|
-
containerId,
|
|
7494
|
-
"sh",
|
|
7495
|
-
"-c",
|
|
7496
|
-
command
|
|
7497
|
-
]);
|
|
7498
|
-
return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
|
|
7499
|
-
} catch (error) {
|
|
7500
|
-
if (error instanceof SubprocessError2) {
|
|
7501
|
-
return {
|
|
7502
|
-
stdout: error.stdout,
|
|
7503
|
-
stderr: error.stderr,
|
|
7504
|
-
exitCode: error.exitCode ?? 1
|
|
7505
|
-
};
|
|
7506
|
-
}
|
|
7507
|
-
return {
|
|
7508
|
-
stdout: "",
|
|
7509
|
-
stderr: error instanceof Error ? error.message : "",
|
|
7510
|
-
exitCode: 1
|
|
7511
|
-
};
|
|
7512
|
-
}
|
|
7513
|
-
};
|
|
7517
|
+
const { exec } = shell;
|
|
7514
7518
|
const arch = async () => {
|
|
7515
7519
|
if (!archPromise) {
|
|
7516
7520
|
const attempt = (async () => {
|
|
7517
7521
|
const result = await exec("uname -m");
|
|
7518
7522
|
if (result.exitCode !== 0) {
|
|
7519
|
-
throw new
|
|
7523
|
+
throw new shell.SandboxError(
|
|
7520
7524
|
`Failed to detect container architecture: ${result.stderr}`,
|
|
7521
7525
|
containerId
|
|
7522
7526
|
);
|
|
@@ -7581,8 +7585,24 @@ function readFileContent(bytes, options) {
|
|
|
7581
7585
|
|
|
7582
7586
|
// packages/context/src/lib/sandbox/container-sandbox.ts
|
|
7583
7587
|
var CONTAINER_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
|
|
7588
|
+
function validateSandboxOptions(opts, errors) {
|
|
7589
|
+
for (const key of Object.keys(opts.env ?? {})) {
|
|
7590
|
+
if (key.length === 0 || key.includes("=")) {
|
|
7591
|
+
throw errors.generic(`Invalid environment variable key: "${key}"`);
|
|
7592
|
+
}
|
|
7593
|
+
}
|
|
7594
|
+
if (opts.name !== void 0 && !CONTAINER_NAME_PATTERN.test(opts.name)) {
|
|
7595
|
+
throw errors.generic(
|
|
7596
|
+
`Invalid container name: "${opts.name}". Use only letters, numbers, underscore, period, or hyphen. The "sandbox-" prefix is added automatically.`
|
|
7597
|
+
);
|
|
7598
|
+
}
|
|
7599
|
+
}
|
|
7600
|
+
function suppress(originalError, cleanupError) {
|
|
7601
|
+
if (!(originalError instanceof Error)) return;
|
|
7602
|
+
const suppressed = "suppressed" in originalError && Array.isArray(originalError.suppressed) ? originalError.suppressed : [];
|
|
7603
|
+
Object.assign(originalError, { suppressed: [...suppressed, cleanupError] });
|
|
7604
|
+
}
|
|
7584
7605
|
var ContainerSandboxStrategy = class {
|
|
7585
|
-
context;
|
|
7586
7606
|
engine;
|
|
7587
7607
|
opts;
|
|
7588
7608
|
volumes;
|
|
@@ -7592,42 +7612,39 @@ var ContainerSandboxStrategy = class {
|
|
|
7592
7612
|
constructor(opts, engine) {
|
|
7593
7613
|
this.opts = opts;
|
|
7594
7614
|
this.engine = engine;
|
|
7595
|
-
|
|
7596
|
-
|
|
7597
|
-
if (key.length === 0 || key.includes("=")) {
|
|
7598
|
-
throw this.engine.errors.generic(
|
|
7599
|
-
`Invalid environment variable key: "${key}"`
|
|
7600
|
-
);
|
|
7601
|
-
}
|
|
7602
|
-
}
|
|
7603
|
-
if (name !== void 0 && !CONTAINER_NAME_PATTERN.test(name)) {
|
|
7604
|
-
throw this.engine.errors.generic(
|
|
7605
|
-
`Invalid container name: "${name}". Use only letters, numbers, underscore, period, or hyphen. The "sandbox-" prefix is added automatically.`
|
|
7606
|
-
);
|
|
7607
|
-
}
|
|
7615
|
+
validateSandboxOptions(opts, engine.errors);
|
|
7616
|
+
const { volumes = [], name, workdir = "/workspace" } = opts;
|
|
7608
7617
|
this.volumes = volumes;
|
|
7609
7618
|
this.name = name;
|
|
7610
7619
|
this.workdir = workdir;
|
|
7611
7620
|
}
|
|
7621
|
+
/**
|
|
7622
|
+
* Creates the sandbox. On failure, everything it made is released and the
|
|
7623
|
+
* engine is disposed.
|
|
7624
|
+
*/
|
|
7612
7625
|
async create() {
|
|
7613
|
-
const image = await this.getImage();
|
|
7614
7626
|
let acquired;
|
|
7615
7627
|
try {
|
|
7628
|
+
const image = await this.getImage();
|
|
7616
7629
|
acquired = await this.acquireContainer(image);
|
|
7617
|
-
this.context = { containerId: acquired.containerId, image };
|
|
7618
7630
|
if (!acquired.attached) {
|
|
7619
|
-
await this.engine.ensureWorkdir(
|
|
7620
|
-
await this.configure();
|
|
7631
|
+
await this.engine.ensureWorkdir(acquired.container, this.workdir);
|
|
7632
|
+
await this.configure(acquired.container, image);
|
|
7621
7633
|
}
|
|
7622
|
-
await this.assertBashAvailable();
|
|
7634
|
+
await this.assertBashAvailable(acquired.container);
|
|
7623
7635
|
} catch (error) {
|
|
7624
7636
|
if (acquired && !acquired.attached) {
|
|
7625
|
-
await this.
|
|
7637
|
+
await this.release(acquired.container).catch(
|
|
7638
|
+
(stopError) => suppress(error, stopError)
|
|
7639
|
+
);
|
|
7626
7640
|
}
|
|
7627
|
-
await this.
|
|
7641
|
+
await this.cleanupCreatedVolumes().catch(
|
|
7642
|
+
(cleanupError) => suppress(error, cleanupError)
|
|
7643
|
+
);
|
|
7644
|
+
await this.engine.dispose();
|
|
7628
7645
|
throw error;
|
|
7629
7646
|
}
|
|
7630
|
-
const sandbox = this.createSandboxMethods();
|
|
7647
|
+
const sandbox = this.createSandboxMethods(acquired.container);
|
|
7631
7648
|
if (this.opts.readiness) {
|
|
7632
7649
|
try {
|
|
7633
7650
|
await this.opts.readiness(sandbox);
|
|
@@ -7639,93 +7656,36 @@ var ContainerSandboxStrategy = class {
|
|
|
7639
7656
|
}
|
|
7640
7657
|
return sandbox;
|
|
7641
7658
|
}
|
|
7642
|
-
|
|
7643
|
-
return `sandbox-${this.name}`;
|
|
7644
|
-
}
|
|
7645
|
-
defaultContainerId() {
|
|
7646
|
-
return `sandbox-${crypto.randomUUID().slice(0, 8)}`;
|
|
7659
|
+
containerName() {
|
|
7660
|
+
return this.name ? `sandbox-${this.name}` : `sandbox-${randomUUID().slice(0, 8)}`;
|
|
7647
7661
|
}
|
|
7648
7662
|
async acquireContainer(image) {
|
|
7649
|
-
|
|
7650
|
-
|
|
7651
|
-
await this.
|
|
7652
|
-
|
|
7653
|
-
return { containerId: containerId2, attached: false };
|
|
7654
|
-
}
|
|
7655
|
-
const containerId = this.namedContainerId();
|
|
7656
|
-
const probe = await this.inspectContainer(containerId);
|
|
7657
|
-
if (probe === "running") {
|
|
7658
|
-
return { containerId, attached: true };
|
|
7659
|
-
}
|
|
7660
|
-
if (probe === "stopped") {
|
|
7661
|
-
await this.startStoppedContainer(containerId, image);
|
|
7662
|
-
return { containerId, attached: true };
|
|
7663
|
+
const name = this.containerName();
|
|
7664
|
+
if (this.name) {
|
|
7665
|
+
const container = await this.engine.attach(name, image);
|
|
7666
|
+
if (container) return { container, attached: true };
|
|
7663
7667
|
}
|
|
7664
7668
|
await this.prepareVolumes();
|
|
7665
|
-
|
|
7666
|
-
|
|
7667
|
-
return {
|
|
7668
|
-
} catch (error) {
|
|
7669
|
-
if (this.engine.isNameConflict(this.engine.errorMessage(error))) {
|
|
7670
|
-
await this.cleanupCreatedVolumes();
|
|
7671
|
-
const raced = await this.waitForRacedContainer(containerId, image);
|
|
7672
|
-
if (raced) {
|
|
7673
|
-
return raced;
|
|
7674
|
-
}
|
|
7675
|
-
}
|
|
7676
|
-
throw error;
|
|
7669
|
+
const result = await this.engine.run(image, name, this.opts, this.workdir);
|
|
7670
|
+
if (result.created) {
|
|
7671
|
+
return { container: result.container, attached: false };
|
|
7677
7672
|
}
|
|
7673
|
+
await this.cleanupCreatedVolumes();
|
|
7674
|
+
if (this.name) {
|
|
7675
|
+
const raced = await this.waitForRacedContainer(name, image);
|
|
7676
|
+
if (raced) return raced;
|
|
7677
|
+
}
|
|
7678
|
+
throw this.engine.errors.generic(
|
|
7679
|
+
`Container name "${name}" is already in use`
|
|
7680
|
+
);
|
|
7678
7681
|
}
|
|
7679
|
-
async waitForRacedContainer(
|
|
7682
|
+
async waitForRacedContainer(name, image) {
|
|
7680
7683
|
const timeoutAt = Date.now() + 1e3;
|
|
7681
7684
|
while (true) {
|
|
7682
|
-
const
|
|
7683
|
-
if (
|
|
7684
|
-
|
|
7685
|
-
|
|
7686
|
-
if (state === "stopped") {
|
|
7687
|
-
await this.startStoppedContainer(containerId, image);
|
|
7688
|
-
return { containerId, attached: true };
|
|
7689
|
-
}
|
|
7690
|
-
if (Date.now() >= timeoutAt) {
|
|
7691
|
-
return void 0;
|
|
7692
|
-
}
|
|
7693
|
-
await new Promise((resolve3) => setTimeout(resolve3, 10));
|
|
7694
|
-
}
|
|
7695
|
-
}
|
|
7696
|
-
async startStoppedContainer(containerId, image) {
|
|
7697
|
-
try {
|
|
7698
|
-
await spawn2(this.engine.cli, ["start", containerId]);
|
|
7699
|
-
} catch (error) {
|
|
7700
|
-
const message2 = this.engineErrorMessage(error);
|
|
7701
|
-
if (this.isServiceDown(message2)) {
|
|
7702
|
-
throw this.engine.errors.serviceNotAvailable();
|
|
7703
|
-
}
|
|
7704
|
-
throw this.engine.errors.creation(
|
|
7705
|
-
message2,
|
|
7706
|
-
image,
|
|
7707
|
-
error instanceof Error ? error : void 0
|
|
7708
|
-
);
|
|
7709
|
-
}
|
|
7710
|
-
}
|
|
7711
|
-
async inspectContainer(containerId) {
|
|
7712
|
-
try {
|
|
7713
|
-
const result = await spawn2(
|
|
7714
|
-
this.engine.cli,
|
|
7715
|
-
this.engine.inspectArgs(containerId)
|
|
7716
|
-
);
|
|
7717
|
-
return this.engine.parseStatus(result.stdout.trim());
|
|
7718
|
-
} catch (error) {
|
|
7719
|
-
const message2 = this.engineErrorMessage(error);
|
|
7720
|
-
if (this.isServiceDown(message2)) {
|
|
7721
|
-
throw this.engine.errors.serviceNotAvailable();
|
|
7722
|
-
}
|
|
7723
|
-
if (this.engine.isMissingContainer(message2)) {
|
|
7724
|
-
return "absent";
|
|
7725
|
-
}
|
|
7726
|
-
throw this.engine.errors.generic(
|
|
7727
|
-
`Failed to inspect container "${containerId}": ${message2}`
|
|
7728
|
-
);
|
|
7685
|
+
const container = await this.engine.attach(name, image);
|
|
7686
|
+
if (container) return { container, attached: true };
|
|
7687
|
+
if (Date.now() >= timeoutAt) return void 0;
|
|
7688
|
+
await setTimeout2(10);
|
|
7729
7689
|
}
|
|
7730
7690
|
}
|
|
7731
7691
|
async prepareVolumes() {
|
|
@@ -7735,18 +7695,23 @@ var ContainerSandboxStrategy = class {
|
|
|
7735
7695
|
continue;
|
|
7736
7696
|
}
|
|
7737
7697
|
const lifecycle = volume.lifecycle ?? "external";
|
|
7698
|
+
const exists = await this.engine.volumeExists(volume.name);
|
|
7738
7699
|
if (lifecycle === "external") {
|
|
7739
|
-
|
|
7700
|
+
if (!exists) {
|
|
7701
|
+
throw this.engine.errors.volumeInspect(
|
|
7702
|
+
volume.name,
|
|
7703
|
+
"volume does not exist"
|
|
7704
|
+
);
|
|
7705
|
+
}
|
|
7740
7706
|
continue;
|
|
7741
7707
|
}
|
|
7742
|
-
const exists = await this.volumeExists(volume.name);
|
|
7743
7708
|
if (exists) {
|
|
7744
7709
|
throw this.engine.errors.volumeCreate(
|
|
7745
7710
|
volume.name,
|
|
7746
7711
|
"managed volume already exists"
|
|
7747
7712
|
);
|
|
7748
7713
|
}
|
|
7749
|
-
await this.createVolume(volume);
|
|
7714
|
+
await this.engine.createVolume(volume, this.opts);
|
|
7750
7715
|
if (volume.removeOnDispose !== false) {
|
|
7751
7716
|
this.createdVolumes.add(volume.name);
|
|
7752
7717
|
}
|
|
@@ -7815,182 +7780,47 @@ var ContainerSandboxStrategy = class {
|
|
|
7815
7780
|
`${field} must not contain commas`
|
|
7816
7781
|
);
|
|
7817
7782
|
}
|
|
7818
|
-
buildRunArgs(image, containerId) {
|
|
7819
|
-
return this.engine.runArgs(image, containerId, this.opts, this.workdir);
|
|
7820
|
-
}
|
|
7821
|
-
async inspectVolume(name) {
|
|
7822
|
-
try {
|
|
7823
|
-
await spawn2(this.engine.cli, ["volume", "inspect", name]);
|
|
7824
|
-
} catch (error) {
|
|
7825
|
-
const reason = this.engineErrorMessage(error);
|
|
7826
|
-
if (this.isServiceDown(reason)) {
|
|
7827
|
-
throw this.engine.errors.serviceNotAvailable();
|
|
7828
|
-
}
|
|
7829
|
-
throw this.engine.errors.volumeInspect(name, reason);
|
|
7830
|
-
}
|
|
7831
|
-
}
|
|
7832
|
-
async volumeExists(name) {
|
|
7833
|
-
try {
|
|
7834
|
-
await this.inspectVolume(name);
|
|
7835
|
-
return true;
|
|
7836
|
-
} catch (error) {
|
|
7837
|
-
if (error instanceof ContainerSandboxError && this.engine.isMissingVolume(error.message)) {
|
|
7838
|
-
return false;
|
|
7839
|
-
}
|
|
7840
|
-
throw error;
|
|
7841
|
-
}
|
|
7842
|
-
}
|
|
7843
|
-
async createVolume(volume) {
|
|
7844
|
-
const args = this.engine.volumeCreateArgs(volume, this.opts);
|
|
7845
|
-
try {
|
|
7846
|
-
await spawn2(this.engine.cli, args);
|
|
7847
|
-
} catch (error) {
|
|
7848
|
-
const reason = this.engineErrorMessage(error);
|
|
7849
|
-
if (this.isServiceDown(reason)) {
|
|
7850
|
-
throw this.engine.errors.serviceNotAvailable();
|
|
7851
|
-
}
|
|
7852
|
-
throw this.engine.errors.volumeCreate(volume.name, reason);
|
|
7853
|
-
}
|
|
7854
|
-
}
|
|
7855
7783
|
async cleanupCreatedVolumes() {
|
|
7856
7784
|
const volumes = [...this.createdVolumes].reverse();
|
|
7857
7785
|
for (const volume of volumes) {
|
|
7858
|
-
|
|
7859
|
-
|
|
7860
|
-
this.createdVolumes.delete(volume);
|
|
7861
|
-
} catch (error) {
|
|
7862
|
-
const reason = this.engineErrorMessage(error);
|
|
7863
|
-
if (this.isServiceDown(reason)) {
|
|
7864
|
-
throw this.engine.errors.serviceNotAvailable();
|
|
7865
|
-
}
|
|
7866
|
-
throw this.engine.errors.volumeRemove(volume, reason);
|
|
7867
|
-
}
|
|
7868
|
-
}
|
|
7869
|
-
}
|
|
7870
|
-
async cleanupCreatedVolumesAfterFailure(originalError) {
|
|
7871
|
-
try {
|
|
7872
|
-
await this.cleanupCreatedVolumes();
|
|
7873
|
-
} catch (cleanupError) {
|
|
7874
|
-
if (originalError instanceof Error) {
|
|
7875
|
-
const suppressed = "suppressed" in originalError && Array.isArray(originalError.suppressed) ? originalError.suppressed : [];
|
|
7876
|
-
Object.assign(originalError, {
|
|
7877
|
-
suppressed: [...suppressed, cleanupError]
|
|
7878
|
-
});
|
|
7879
|
-
}
|
|
7880
|
-
}
|
|
7881
|
-
}
|
|
7882
|
-
engineErrorMessage(error) {
|
|
7883
|
-
return this.engine.errorMessage(error);
|
|
7884
|
-
}
|
|
7885
|
-
isServiceDown(message2) {
|
|
7886
|
-
return this.engine.isServiceDown(message2);
|
|
7887
|
-
}
|
|
7888
|
-
async startContainer(image, containerId) {
|
|
7889
|
-
const args = this.buildRunArgs(image, containerId);
|
|
7890
|
-
try {
|
|
7891
|
-
await spawn2(this.engine.cli, args);
|
|
7892
|
-
} catch (error) {
|
|
7893
|
-
const message2 = this.engineErrorMessage(error);
|
|
7894
|
-
if (this.isServiceDown(message2)) {
|
|
7895
|
-
throw this.engine.errors.serviceNotAvailable();
|
|
7896
|
-
}
|
|
7897
|
-
for (const volume of this.volumes) {
|
|
7898
|
-
if (volume.type === "bind" && this.engine.isMissingBindSource?.(message2, volume.hostPath)) {
|
|
7899
|
-
throw this.engine.errors.volumePath(
|
|
7900
|
-
volume.hostPath,
|
|
7901
|
-
volume.containerPath,
|
|
7902
|
-
"hostPath does not exist on host"
|
|
7903
|
-
);
|
|
7904
|
-
}
|
|
7905
|
-
}
|
|
7906
|
-
throw this.engine.errors.creation(
|
|
7907
|
-
message2,
|
|
7908
|
-
image,
|
|
7909
|
-
error instanceof Error ? error : void 0
|
|
7910
|
-
);
|
|
7911
|
-
}
|
|
7912
|
-
}
|
|
7913
|
-
async stopContainer(containerId) {
|
|
7914
|
-
try {
|
|
7915
|
-
await spawn2(this.engine.cli, ["stop", containerId]);
|
|
7916
|
-
} catch {
|
|
7786
|
+
await this.engine.removeVolume(volume);
|
|
7787
|
+
this.createdVolumes.delete(volume);
|
|
7917
7788
|
}
|
|
7918
7789
|
}
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
this.engine.cli,
|
|
7923
|
-
this.engine.execArgs(this.context.containerId, command),
|
|
7924
|
-
{ signal: options?.signal }
|
|
7925
|
-
);
|
|
7926
|
-
return {
|
|
7927
|
-
stdout: result.stdout,
|
|
7928
|
-
stderr: result.stderr,
|
|
7929
|
-
exitCode: 0
|
|
7930
|
-
};
|
|
7931
|
-
} catch (error) {
|
|
7932
|
-
return commandResultFrom(error);
|
|
7933
|
-
}
|
|
7790
|
+
/** Ends the sandbox's hold on its container: stops it, by default. */
|
|
7791
|
+
release(container) {
|
|
7792
|
+
return container.stop();
|
|
7934
7793
|
}
|
|
7935
|
-
async assertBashAvailable() {
|
|
7936
|
-
const result = await
|
|
7794
|
+
async assertBashAvailable(container) {
|
|
7795
|
+
const result = await container.executeCommand(":");
|
|
7937
7796
|
if (result.exitCode === 0) return;
|
|
7938
7797
|
const detail = result.stderr.trim() || result.stdout.trim();
|
|
7939
7798
|
throw this.engine.errors.generic(
|
|
7940
7799
|
`Bash is required to execute sandbox commands but could not be started${detail ? `: ${detail}` : "."}`,
|
|
7941
|
-
|
|
7942
|
-
);
|
|
7943
|
-
}
|
|
7944
|
-
spawnProcess(command, options) {
|
|
7945
|
-
const child = childSpawn(
|
|
7946
|
-
this.engine.cli,
|
|
7947
|
-
this.engine.execArgs(this.context.containerId, command, options)
|
|
7800
|
+
container.name
|
|
7948
7801
|
);
|
|
7949
|
-
return toSandboxProcess(child, options?.signal);
|
|
7950
7802
|
}
|
|
7951
|
-
createSandboxMethods() {
|
|
7952
|
-
|
|
7953
|
-
const
|
|
7954
|
-
|
|
7955
|
-
|
|
7956
|
-
readFile: async (path6, options) => {
|
|
7957
|
-
const result = await sandbox.executeCommand(base64ReadCommand(path6));
|
|
7958
|
-
if (result.exitCode !== 0) {
|
|
7959
|
-
throw new Error(`Failed to read file "${path6}": ${result.stderr}`);
|
|
7960
|
-
}
|
|
7961
|
-
return readFileContent(Buffer.from(result.stdout, "base64"), options);
|
|
7962
|
-
},
|
|
7963
|
-
exists: async (path6) => {
|
|
7964
|
-
const result = await sandbox.executeCommand(existsCommand(path6));
|
|
7965
|
-
if (result.stdout === "true") return true;
|
|
7966
|
-
if (result.stdout === "false") return false;
|
|
7967
|
-
throw new Error(`Failed to check "${path6}": ${result.stderr}`);
|
|
7968
|
-
},
|
|
7969
|
-
writeFiles: async (files) => {
|
|
7970
|
-
for (const file of files) {
|
|
7971
|
-
const dir = file.path.substring(0, file.path.lastIndexOf("/"));
|
|
7972
|
-
if (dir) {
|
|
7973
|
-
await sandbox.executeCommand(`mkdir -p ${shellQuote(dir)}`);
|
|
7974
|
-
}
|
|
7975
|
-
for (const command of base64WriteCommands(file.path, file.content)) {
|
|
7976
|
-
const result = await sandbox.executeCommand(command);
|
|
7977
|
-
if (result.exitCode !== 0) {
|
|
7978
|
-
throw new Error(
|
|
7979
|
-
`Failed to write file "${file.path}": ${result.stderr}`
|
|
7980
|
-
);
|
|
7981
|
-
}
|
|
7982
|
-
}
|
|
7983
|
-
}
|
|
7984
|
-
},
|
|
7985
|
-
dispose: async () => {
|
|
7986
|
-
await this.stopContainer(containerId);
|
|
7803
|
+
createSandboxMethods(container) {
|
|
7804
|
+
let disposal;
|
|
7805
|
+
const dispose = async () => {
|
|
7806
|
+
try {
|
|
7807
|
+
await this.release(container);
|
|
7987
7808
|
await this.cleanupCreatedVolumes();
|
|
7988
|
-
}
|
|
7809
|
+
} finally {
|
|
7810
|
+
await this.engine.dispose();
|
|
7811
|
+
}
|
|
7812
|
+
};
|
|
7813
|
+
return {
|
|
7814
|
+
executeCommand: (command, options) => container.executeCommand(command, options),
|
|
7815
|
+
spawn: (command, options) => container.spawn(command, options),
|
|
7816
|
+
readFile: async (path6, options) => readFileContent(await container.readFile(path6), options),
|
|
7817
|
+
exists: (path6) => container.exists(path6),
|
|
7818
|
+
writeFiles: (files) => container.writeFiles(files),
|
|
7819
|
+
dispose: () => disposal ??= dispose(),
|
|
7989
7820
|
[Symbol.asyncDispose]() {
|
|
7990
7821
|
return this.dispose();
|
|
7991
7822
|
}
|
|
7992
7823
|
};
|
|
7993
|
-
return sandbox;
|
|
7994
7824
|
}
|
|
7995
7825
|
};
|
|
7996
7826
|
var RuntimeStrategy = class extends ContainerSandboxStrategy {
|
|
@@ -8004,11 +7834,8 @@ var RuntimeStrategy = class extends ContainerSandboxStrategy {
|
|
|
8004
7834
|
async getImage() {
|
|
8005
7835
|
return this.image;
|
|
8006
7836
|
}
|
|
8007
|
-
async configure() {
|
|
8008
|
-
const ctx =
|
|
8009
|
-
this.context.containerId,
|
|
8010
|
-
this.image
|
|
8011
|
-
);
|
|
7837
|
+
async configure(container, image) {
|
|
7838
|
+
const ctx = container.installerContext(image);
|
|
8012
7839
|
for (const installer of this.installers) {
|
|
8013
7840
|
await installer.install(ctx);
|
|
8014
7841
|
}
|
|
@@ -8066,7 +7893,7 @@ function buildMountArg(volume) {
|
|
|
8066
7893
|
return parts.join(",");
|
|
8067
7894
|
}
|
|
8068
7895
|
function getCliErrorMessage(error) {
|
|
8069
|
-
if (error instanceof
|
|
7896
|
+
if (error instanceof SubprocessError2) {
|
|
8070
7897
|
return error.stderr.trim() || error.stdout.trim() || error.message;
|
|
8071
7898
|
}
|
|
8072
7899
|
return error instanceof Error && error.message || String(error);
|
|
@@ -8094,9 +7921,80 @@ function readContainerStatus(entry) {
|
|
|
8094
7921
|
`Container is in an unexpected state "${status}"`
|
|
8095
7922
|
);
|
|
8096
7923
|
}
|
|
7924
|
+
function isServiceDown(message2) {
|
|
7925
|
+
return /apiserver|not running|connection refused|could not connect|xpc/i.test(
|
|
7926
|
+
message2
|
|
7927
|
+
);
|
|
7928
|
+
}
|
|
7929
|
+
function isMissing(message2) {
|
|
7930
|
+
return /not found|no such/i.test(message2);
|
|
7931
|
+
}
|
|
7932
|
+
function isNameConflict(message2) {
|
|
7933
|
+
return /already exists/i.test(message2);
|
|
7934
|
+
}
|
|
7935
|
+
function execArgs(name, command, options) {
|
|
7936
|
+
const flags = ["--cwd", options?.cwd || WORKDIR];
|
|
7937
|
+
for (const [key, value] of Object.entries(options?.env ?? {})) {
|
|
7938
|
+
if (key.length === 0 || key.includes("=")) {
|
|
7939
|
+
throw new AppleContainerSandboxError(
|
|
7940
|
+
`Invalid environment variable key: "${key}"`
|
|
7941
|
+
);
|
|
7942
|
+
}
|
|
7943
|
+
flags.push("--env", `${key}=${value}`);
|
|
7944
|
+
}
|
|
7945
|
+
return ["exec", ...flags, name, "bash", "-lc", command];
|
|
7946
|
+
}
|
|
7947
|
+
async function run(args, signal) {
|
|
7948
|
+
try {
|
|
7949
|
+
const result = await spawn(CLI, args, { signal });
|
|
7950
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
|
|
7951
|
+
} catch (error) {
|
|
7952
|
+
return commandResultFrom(error);
|
|
7953
|
+
}
|
|
7954
|
+
}
|
|
7955
|
+
var AppleContainer = class {
|
|
7956
|
+
name;
|
|
7957
|
+
constructor(name) {
|
|
7958
|
+
this.name = name;
|
|
7959
|
+
}
|
|
7960
|
+
executeCommand(command, options) {
|
|
7961
|
+
return run(execArgs(this.name, command), options?.signal);
|
|
7962
|
+
}
|
|
7963
|
+
async spawn(command, options) {
|
|
7964
|
+
return toSandboxProcess(
|
|
7965
|
+
childSpawn(CLI, execArgs(this.name, command, options)),
|
|
7966
|
+
options?.signal
|
|
7967
|
+
);
|
|
7968
|
+
}
|
|
7969
|
+
readFile(path6) {
|
|
7970
|
+
return readFileOverExec((command) => this.executeCommand(command), path6);
|
|
7971
|
+
}
|
|
7972
|
+
writeFiles(files) {
|
|
7973
|
+
return writeFilesOverExec((command) => this.executeCommand(command), files);
|
|
7974
|
+
}
|
|
7975
|
+
exists(path6) {
|
|
7976
|
+
return existsOverExec((command) => this.executeCommand(command), path6);
|
|
7977
|
+
}
|
|
7978
|
+
installerContext(image) {
|
|
7979
|
+
return createInstallerContext(
|
|
7980
|
+
{
|
|
7981
|
+
exec: (command) => run(["exec", this.name, "sh", "-c", command]),
|
|
7982
|
+
SandboxError: AppleContainerSandboxError
|
|
7983
|
+
},
|
|
7984
|
+
this.name,
|
|
7985
|
+
image
|
|
7986
|
+
);
|
|
7987
|
+
}
|
|
7988
|
+
async stop() {
|
|
7989
|
+
try {
|
|
7990
|
+
await spawn(CLI, ["stop", this.name]);
|
|
7991
|
+
} catch {
|
|
7992
|
+
}
|
|
7993
|
+
}
|
|
7994
|
+
};
|
|
8097
7995
|
var appleEngine = {
|
|
8098
|
-
cli: CLI,
|
|
8099
7996
|
bindMountsOnClient: true,
|
|
7997
|
+
defaultImage: "docker.io/library/bash:5.3-alpine3.24",
|
|
8100
7998
|
runArgs(image, containerId, opts) {
|
|
8101
7999
|
const { memory = "1024M", cpus = 2 } = opts.resources ?? {};
|
|
8102
8000
|
const args = [
|
|
@@ -8133,68 +8031,96 @@ var appleEngine = {
|
|
|
8133
8031
|
}
|
|
8134
8032
|
return args;
|
|
8135
8033
|
},
|
|
8136
|
-
execArgs(containerId, command, options) {
|
|
8137
|
-
const flags = ["--cwd", options?.cwd || WORKDIR];
|
|
8138
|
-
if (options?.env) {
|
|
8139
|
-
for (const [key, value] of Object.entries(options.env)) {
|
|
8140
|
-
if (key.length === 0 || key.includes("=")) {
|
|
8141
|
-
throw new AppleContainerSandboxError(
|
|
8142
|
-
`Invalid environment variable key: "${key}"`
|
|
8143
|
-
);
|
|
8144
|
-
}
|
|
8145
|
-
flags.push("--env", `${key}=${value}`);
|
|
8146
|
-
}
|
|
8147
|
-
}
|
|
8148
|
-
return ["exec", ...flags, containerId, "bash", "-lc", command];
|
|
8149
|
-
},
|
|
8150
|
-
inspectArgs(containerId) {
|
|
8151
|
-
return ["inspect", containerId];
|
|
8152
|
-
},
|
|
8153
8034
|
parseStatus(stdout) {
|
|
8154
8035
|
const entries = safeParseArray(stdout);
|
|
8155
8036
|
if (entries.length === 0) return "absent";
|
|
8156
8037
|
return readContainerStatus(entries[0]);
|
|
8157
8038
|
},
|
|
8158
|
-
|
|
8159
|
-
|
|
8160
|
-
|
|
8161
|
-
|
|
8162
|
-
|
|
8163
|
-
|
|
8164
|
-
|
|
8165
|
-
|
|
8166
|
-
|
|
8167
|
-
|
|
8168
|
-
|
|
8039
|
+
async attach(name, image) {
|
|
8040
|
+
let status;
|
|
8041
|
+
try {
|
|
8042
|
+
const result = await spawn(CLI, ["inspect", name]);
|
|
8043
|
+
status = this.parseStatus(result.stdout.trim());
|
|
8044
|
+
} catch (error) {
|
|
8045
|
+
const message2 = getCliErrorMessage(error);
|
|
8046
|
+
if (isServiceDown(message2)) throw new ContainerServiceNotRunningError();
|
|
8047
|
+
if (isMissing(message2)) return void 0;
|
|
8048
|
+
throw new AppleContainerSandboxError(
|
|
8049
|
+
`Failed to inspect container "${name}": ${message2}`
|
|
8050
|
+
);
|
|
8051
|
+
}
|
|
8052
|
+
if (status === "absent") return void 0;
|
|
8053
|
+
if (status === "stopped") {
|
|
8054
|
+
try {
|
|
8055
|
+
await spawn(CLI, ["start", name]);
|
|
8056
|
+
} catch (error) {
|
|
8057
|
+
const message2 = getCliErrorMessage(error);
|
|
8058
|
+
if (isServiceDown(message2)) throw new ContainerServiceNotRunningError();
|
|
8059
|
+
throw new AppleContainerCreationError(
|
|
8060
|
+
message2,
|
|
8061
|
+
image,
|
|
8062
|
+
error instanceof Error ? error : void 0
|
|
8063
|
+
);
|
|
8064
|
+
}
|
|
8065
|
+
}
|
|
8066
|
+
return new AppleContainer(name);
|
|
8067
|
+
},
|
|
8068
|
+
async run(image, name, opts, workdir) {
|
|
8069
|
+
try {
|
|
8070
|
+
await spawn(CLI, this.runArgs(image, name, opts, workdir));
|
|
8071
|
+
} catch (error) {
|
|
8072
|
+
const message2 = getCliErrorMessage(error);
|
|
8073
|
+
if (isServiceDown(message2)) throw new ContainerServiceNotRunningError();
|
|
8074
|
+
if (isNameConflict(message2)) return { created: false };
|
|
8075
|
+
throw new AppleContainerCreationError(
|
|
8076
|
+
message2,
|
|
8077
|
+
image,
|
|
8078
|
+
error instanceof Error ? error : void 0
|
|
8079
|
+
);
|
|
8080
|
+
}
|
|
8081
|
+
return { created: true, container: new AppleContainer(name) };
|
|
8169
8082
|
},
|
|
8170
|
-
|
|
8171
|
-
|
|
8083
|
+
async volumeExists(name) {
|
|
8084
|
+
try {
|
|
8085
|
+
await spawn(CLI, ["volume", "inspect", name]);
|
|
8086
|
+
return true;
|
|
8087
|
+
} catch (error) {
|
|
8088
|
+
const reason = getCliErrorMessage(error);
|
|
8089
|
+
if (isServiceDown(reason)) throw new ContainerServiceNotRunningError();
|
|
8090
|
+
if (isMissing(reason)) return false;
|
|
8091
|
+
throw new AppleContainerVolumeInspectError(name, reason);
|
|
8092
|
+
}
|
|
8172
8093
|
},
|
|
8173
|
-
|
|
8174
|
-
|
|
8094
|
+
async createVolume(volume) {
|
|
8095
|
+
try {
|
|
8096
|
+
await spawn(CLI, ["volume", "create", volume.name]);
|
|
8097
|
+
} catch (error) {
|
|
8098
|
+
const reason = getCliErrorMessage(error);
|
|
8099
|
+
if (isServiceDown(reason)) throw new ContainerServiceNotRunningError();
|
|
8100
|
+
throw new AppleContainerVolumeCreateError(volume.name, reason);
|
|
8101
|
+
}
|
|
8175
8102
|
},
|
|
8176
|
-
|
|
8177
|
-
|
|
8103
|
+
async removeVolume(name) {
|
|
8104
|
+
try {
|
|
8105
|
+
await spawn(CLI, ["volume", "rm", name]);
|
|
8106
|
+
} catch (error) {
|
|
8107
|
+
const reason = getCliErrorMessage(error);
|
|
8108
|
+
if (isServiceDown(reason)) throw new ContainerServiceNotRunningError();
|
|
8109
|
+
throw new AppleContainerVolumeRemoveError(name, reason);
|
|
8110
|
+
}
|
|
8178
8111
|
},
|
|
8179
|
-
async ensureWorkdir(
|
|
8180
|
-
await
|
|
8112
|
+
async ensureWorkdir(container, workdir) {
|
|
8113
|
+
await spawn(CLI, [
|
|
8181
8114
|
"exec",
|
|
8182
|
-
|
|
8115
|
+
container.name,
|
|
8183
8116
|
"bash",
|
|
8184
8117
|
"-lc",
|
|
8185
8118
|
`mkdir -p ${shellQuote(workdir)}`
|
|
8186
8119
|
]);
|
|
8187
8120
|
},
|
|
8188
|
-
defaultImage: "docker.io/library/bash:5.3-alpine3.24",
|
|
8189
|
-
// The Docker installer suite, driven through `container exec`.
|
|
8190
|
-
createInstallerContext: (containerId, image) => createInstallerContext(
|
|
8191
|
-
{ binary: CLI, SandboxError: AppleContainerSandboxError },
|
|
8192
|
-
containerId,
|
|
8193
|
-
image
|
|
8194
|
-
),
|
|
8195
8121
|
async imageExists(tag) {
|
|
8196
8122
|
try {
|
|
8197
|
-
await
|
|
8123
|
+
await spawn(CLI, ["image", "inspect", tag]);
|
|
8198
8124
|
return true;
|
|
8199
8125
|
} catch {
|
|
8200
8126
|
return false;
|
|
@@ -8229,14 +8155,13 @@ var appleEngine = {
|
|
|
8229
8155
|
spec.showBuildLogs
|
|
8230
8156
|
);
|
|
8231
8157
|
},
|
|
8158
|
+
async dispose() {
|
|
8159
|
+
},
|
|
8232
8160
|
errors: {
|
|
8233
|
-
serviceNotAvailable: () => new ContainerServiceNotRunningError(),
|
|
8234
|
-
creation: (message2, image, cause) => new AppleContainerCreationError(message2, image, cause),
|
|
8235
8161
|
generic: (message2, containerId) => new AppleContainerSandboxError(message2, containerId),
|
|
8236
8162
|
volumePath: (source, containerPath, reason) => new AppleContainerVolumePathError(source, containerPath, reason),
|
|
8237
8163
|
volumeInspect: (name, reason) => new AppleContainerVolumeInspectError(name, reason),
|
|
8238
|
-
volumeCreate: (name, reason) => new AppleContainerVolumeCreateError(name, reason)
|
|
8239
|
-
volumeRemove: (name, reason) => new AppleContainerVolumeRemoveError(name, reason)
|
|
8164
|
+
volumeCreate: (name, reason) => new AppleContainerVolumeCreateError(name, reason)
|
|
8240
8165
|
}
|
|
8241
8166
|
};
|
|
8242
8167
|
async function runAppleBuild(args, showBuildLogs) {
|
|
@@ -8244,7 +8169,7 @@ async function runAppleBuild(args, showBuildLogs) {
|
|
|
8244
8169
|
if (showBuildLogs) {
|
|
8245
8170
|
await runStreamed(CLI, args);
|
|
8246
8171
|
} else {
|
|
8247
|
-
await
|
|
8172
|
+
await spawn(CLI, args);
|
|
8248
8173
|
}
|
|
8249
8174
|
} catch (error) {
|
|
8250
8175
|
throw new AppleContainerImageBuildError(getCliErrorMessage(error));
|
|
@@ -8252,7 +8177,7 @@ async function runAppleBuild(args, showBuildLogs) {
|
|
|
8252
8177
|
}
|
|
8253
8178
|
function runStreamed(command, args) {
|
|
8254
8179
|
return new Promise((resolve3, reject) => {
|
|
8255
|
-
const child =
|
|
8180
|
+
const child = childSpawn(command, args, { stdio: "inherit" });
|
|
8256
8181
|
child.once("error", reject);
|
|
8257
8182
|
child.once(
|
|
8258
8183
|
"exit",
|
|
@@ -8349,7 +8274,7 @@ function attachment(input, {
|
|
|
8349
8274
|
type: "file",
|
|
8350
8275
|
data: {
|
|
8351
8276
|
type: "data",
|
|
8352
|
-
data:
|
|
8277
|
+
data: input.bytes.toBase64()
|
|
8353
8278
|
},
|
|
8354
8279
|
mediaType,
|
|
8355
8280
|
filename: path2.posix.basename(input.path)
|
|
@@ -8586,8 +8511,8 @@ function withBashExceptionCatch(sandbox) {
|
|
|
8586
8511
|
}
|
|
8587
8512
|
};
|
|
8588
8513
|
if (sandbox.spawn) {
|
|
8589
|
-
const
|
|
8590
|
-
decorated.spawn = (command, options) =>
|
|
8514
|
+
const spawn5 = sandbox.spawn.bind(sandbox);
|
|
8515
|
+
decorated.spawn = (command, options) => spawn5(command, options);
|
|
8591
8516
|
}
|
|
8592
8517
|
return decorated;
|
|
8593
8518
|
}
|
|
@@ -8802,7 +8727,7 @@ async function createBashTool(options) {
|
|
|
8802
8727
|
// packages/context/src/lib/sandbox/binary-bridges.ts
|
|
8803
8728
|
import { existsSync as existsSync2 } from "fs";
|
|
8804
8729
|
import { defineCommand } from "just-bash";
|
|
8805
|
-
import
|
|
8730
|
+
import spawn2, { SubprocessError as SubprocessError3 } from "nano-spawn";
|
|
8806
8731
|
import * as path5 from "path";
|
|
8807
8732
|
function createBinaryBridges(...binaries) {
|
|
8808
8733
|
return binaries.map((input) => {
|
|
@@ -8840,7 +8765,7 @@ function createBinaryBridges(...binaries) {
|
|
|
8840
8765
|
PATH: process.env.PATH
|
|
8841
8766
|
// Always use host PATH for binary bridges
|
|
8842
8767
|
};
|
|
8843
|
-
const result = await
|
|
8768
|
+
const result = await spawn2(binaryPath, resolvedArgs, {
|
|
8844
8769
|
cwd: realCwd,
|
|
8845
8770
|
env: mergedEnv
|
|
8846
8771
|
});
|
|
@@ -8850,7 +8775,7 @@ function createBinaryBridges(...binaries) {
|
|
|
8850
8775
|
exitCode: 0
|
|
8851
8776
|
};
|
|
8852
8777
|
} catch (error) {
|
|
8853
|
-
if (error instanceof
|
|
8778
|
+
if (error instanceof SubprocessError3) {
|
|
8854
8779
|
if (hasErrorCode(error.cause, "ENOENT")) {
|
|
8855
8780
|
return {
|
|
8856
8781
|
stdout: "",
|
|
@@ -8897,7 +8822,8 @@ function mapToRealPath(fs, cwd) {
|
|
|
8897
8822
|
}
|
|
8898
8823
|
|
|
8899
8824
|
// packages/context/src/lib/sandbox/daytona-sandbox.ts
|
|
8900
|
-
import { randomUUID } from "node:crypto";
|
|
8825
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8826
|
+
import { setTimeout as setTimeout3 } from "node:timers/promises";
|
|
8901
8827
|
var DAYTONA_DEFAULT_DESTINATION = "/home/daytona";
|
|
8902
8828
|
var DAYTONA_EXIT_POLL_INTERVAL_MS = 250;
|
|
8903
8829
|
var DAYTONA_EXIT_POLL_TIMEOUT_MS = 3e4;
|
|
@@ -9129,11 +9055,104 @@ function createDaytonaSandboxMethods(args) {
|
|
|
9129
9055
|
};
|
|
9130
9056
|
return {
|
|
9131
9057
|
executeCommand,
|
|
9132
|
-
spawn(command, options) {
|
|
9133
|
-
|
|
9134
|
-
|
|
9135
|
-
|
|
9136
|
-
|
|
9058
|
+
async spawn(command, options) {
|
|
9059
|
+
const sessionId = `deepagents-spawn-${randomUUID2()}`;
|
|
9060
|
+
const stdout = createTextReadable();
|
|
9061
|
+
const stderr = createTextReadable();
|
|
9062
|
+
const signal = options?.signal;
|
|
9063
|
+
const sessionCommand = buildSessionCommand(command, { ...options });
|
|
9064
|
+
const exit = (async () => {
|
|
9065
|
+
let sessionCreated = false;
|
|
9066
|
+
let aborted = signal?.aborted === true;
|
|
9067
|
+
const { promise: abortPromise, resolve: resolveAbort } = Promise.withResolvers();
|
|
9068
|
+
const abort = () => {
|
|
9069
|
+
aborted = true;
|
|
9070
|
+
resolveAbort("aborted");
|
|
9071
|
+
if (sessionCreated) {
|
|
9072
|
+
sandbox.process.deleteSession(sessionId).catch(() => {
|
|
9073
|
+
});
|
|
9074
|
+
}
|
|
9075
|
+
};
|
|
9076
|
+
if (signal) {
|
|
9077
|
+
if (signal.aborted) abort();
|
|
9078
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
9079
|
+
}
|
|
9080
|
+
try {
|
|
9081
|
+
await sandbox.process.createSession(sessionId);
|
|
9082
|
+
sessionCreated = true;
|
|
9083
|
+
if (aborted) return abortedExitInfo();
|
|
9084
|
+
const response = await sandbox.process.executeSessionCommand(
|
|
9085
|
+
sessionId,
|
|
9086
|
+
{
|
|
9087
|
+
command: sessionCommand,
|
|
9088
|
+
runAsync: true,
|
|
9089
|
+
suppressInputEcho: true
|
|
9090
|
+
},
|
|
9091
|
+
commandTimeout
|
|
9092
|
+
);
|
|
9093
|
+
const commandId = response.cmdId;
|
|
9094
|
+
if (!commandId) {
|
|
9095
|
+
throw new DaytonaCommandError(
|
|
9096
|
+
"Daytona did not return a command id for the spawned session command."
|
|
9097
|
+
);
|
|
9098
|
+
}
|
|
9099
|
+
if (aborted) return abortedExitInfo();
|
|
9100
|
+
const logsTask = sandbox.process.getSessionCommandLogs(
|
|
9101
|
+
sessionId,
|
|
9102
|
+
commandId,
|
|
9103
|
+
stdout.enqueue,
|
|
9104
|
+
stderr.enqueue
|
|
9105
|
+
);
|
|
9106
|
+
logsTask.catch(() => {
|
|
9107
|
+
});
|
|
9108
|
+
const winner = await Promise.race([logsTask, abortPromise]);
|
|
9109
|
+
if (winner === "aborted") {
|
|
9110
|
+
await sandbox.process.deleteSession(sessionId).catch(() => {
|
|
9111
|
+
});
|
|
9112
|
+
return abortedExitInfo();
|
|
9113
|
+
}
|
|
9114
|
+
const timeoutMs = commandTimeout === void 0 ? DAYTONA_EXIT_POLL_TIMEOUT_MS : Math.max(commandTimeout * 1e3, DAYTONA_EXIT_POLL_TIMEOUT_MS);
|
|
9115
|
+
const deadline = Date.now() + timeoutMs;
|
|
9116
|
+
while (true) {
|
|
9117
|
+
if (aborted)
|
|
9118
|
+
throw new DaytonaCommandError("Daytona command aborted.");
|
|
9119
|
+
const info = await sandbox.process.getSessionCommand(
|
|
9120
|
+
sessionId,
|
|
9121
|
+
commandId
|
|
9122
|
+
);
|
|
9123
|
+
if (typeof info.exitCode === "number") {
|
|
9124
|
+
return {
|
|
9125
|
+
code: info.exitCode,
|
|
9126
|
+
signal: null,
|
|
9127
|
+
success: info.exitCode === 0
|
|
9128
|
+
};
|
|
9129
|
+
}
|
|
9130
|
+
if (Date.now() >= deadline) {
|
|
9131
|
+
throw new DaytonaCommandError(
|
|
9132
|
+
`Daytona session command "${commandId}" logs closed before an exit code became available.`
|
|
9133
|
+
);
|
|
9134
|
+
}
|
|
9135
|
+
await setTimeout3(DAYTONA_EXIT_POLL_INTERVAL_MS);
|
|
9136
|
+
}
|
|
9137
|
+
} catch (error) {
|
|
9138
|
+
if (aborted) return abortedExitInfo();
|
|
9139
|
+
const err = toError(error);
|
|
9140
|
+
stdout.error(err);
|
|
9141
|
+
stderr.error(err);
|
|
9142
|
+
throw err;
|
|
9143
|
+
} finally {
|
|
9144
|
+
if (signal) {
|
|
9145
|
+
signal.removeEventListener("abort", abort);
|
|
9146
|
+
}
|
|
9147
|
+
stdout.close();
|
|
9148
|
+
stderr.close();
|
|
9149
|
+
if (sessionCreated) {
|
|
9150
|
+
await sandbox.process.deleteSession(sessionId).catch(() => {
|
|
9151
|
+
});
|
|
9152
|
+
}
|
|
9153
|
+
}
|
|
9154
|
+
})();
|
|
9155
|
+
return { stdout: stdout.stream, stderr: stderr.stream, exit };
|
|
9137
9156
|
},
|
|
9138
9157
|
async readFile(path6, options) {
|
|
9139
9158
|
try {
|
|
@@ -9190,168 +9209,40 @@ function createDaytonaSandboxMethods(args) {
|
|
|
9190
9209
|
}
|
|
9191
9210
|
};
|
|
9192
9211
|
}
|
|
9193
|
-
function spawnDaytonaProcess(sandbox, command, options = {}) {
|
|
9194
|
-
const sessionId = createSessionId("spawn");
|
|
9195
|
-
const stdout = createTextReadable();
|
|
9196
|
-
const stderr = createTextReadable();
|
|
9197
|
-
const exit = runSpawnedSession({
|
|
9198
|
-
sandbox,
|
|
9199
|
-
sessionId,
|
|
9200
|
-
command: buildSessionCommand(command, options),
|
|
9201
|
-
signal: options.signal,
|
|
9202
|
-
commandTimeout: options.commandTimeout,
|
|
9203
|
-
stdout,
|
|
9204
|
-
stderr
|
|
9205
|
-
});
|
|
9206
|
-
return {
|
|
9207
|
-
stdout: stdout.stream,
|
|
9208
|
-
stderr: stderr.stream,
|
|
9209
|
-
exit
|
|
9210
|
-
};
|
|
9211
|
-
}
|
|
9212
|
-
async function runSpawnedSession(args) {
|
|
9213
|
-
const {
|
|
9214
|
-
sandbox,
|
|
9215
|
-
sessionId,
|
|
9216
|
-
command,
|
|
9217
|
-
signal,
|
|
9218
|
-
commandTimeout,
|
|
9219
|
-
stdout,
|
|
9220
|
-
stderr
|
|
9221
|
-
} = args;
|
|
9222
|
-
let sessionCreated = false;
|
|
9223
|
-
let aborted = signal?.aborted ?? false;
|
|
9224
|
-
let resolveAbort;
|
|
9225
|
-
const abortPromise = new Promise((resolve3) => {
|
|
9226
|
-
resolveAbort = () => resolve3("aborted");
|
|
9227
|
-
});
|
|
9228
|
-
const abort = () => {
|
|
9229
|
-
aborted = true;
|
|
9230
|
-
resolveAbort?.();
|
|
9231
|
-
if (sessionCreated) {
|
|
9232
|
-
sandbox.process.deleteSession(sessionId).catch(() => {
|
|
9233
|
-
});
|
|
9234
|
-
}
|
|
9235
|
-
};
|
|
9236
|
-
if (signal) {
|
|
9237
|
-
if (signal.aborted) abort();
|
|
9238
|
-
else signal.addEventListener("abort", abort, { once: true });
|
|
9239
|
-
}
|
|
9240
|
-
try {
|
|
9241
|
-
await sandbox.process.createSession(sessionId);
|
|
9242
|
-
sessionCreated = true;
|
|
9243
|
-
if (aborted) return abortedExitInfo();
|
|
9244
|
-
const response = await sandbox.process.executeSessionCommand(
|
|
9245
|
-
sessionId,
|
|
9246
|
-
{
|
|
9247
|
-
command,
|
|
9248
|
-
runAsync: true,
|
|
9249
|
-
suppressInputEcho: true
|
|
9250
|
-
},
|
|
9251
|
-
commandTimeout
|
|
9252
|
-
);
|
|
9253
|
-
const commandId = response.cmdId;
|
|
9254
|
-
if (!commandId) {
|
|
9255
|
-
throw new DaytonaCommandError(
|
|
9256
|
-
"Daytona did not return a command id for the spawned session command."
|
|
9257
|
-
);
|
|
9258
|
-
}
|
|
9259
|
-
if (aborted) return abortedExitInfo();
|
|
9260
|
-
const logsTask = sandbox.process.getSessionCommandLogs(
|
|
9261
|
-
sessionId,
|
|
9262
|
-
commandId,
|
|
9263
|
-
(chunk) => stdout.enqueue(chunk),
|
|
9264
|
-
(chunk) => stderr.enqueue(chunk)
|
|
9265
|
-
);
|
|
9266
|
-
logsTask.catch(() => {
|
|
9267
|
-
});
|
|
9268
|
-
const winner = await Promise.race([
|
|
9269
|
-
logsTask.then(() => "logs"),
|
|
9270
|
-
abortPromise
|
|
9271
|
-
]);
|
|
9272
|
-
if (winner === "aborted") {
|
|
9273
|
-
await sandbox.process.deleteSession(sessionId).catch(() => {
|
|
9274
|
-
});
|
|
9275
|
-
return abortedExitInfo();
|
|
9276
|
-
}
|
|
9277
|
-
await logsTask;
|
|
9278
|
-
const code = await waitForSessionCommandExitCode({
|
|
9279
|
-
sandbox,
|
|
9280
|
-
sessionId,
|
|
9281
|
-
commandId,
|
|
9282
|
-
timeoutMs: sessionExitPollTimeoutMs(commandTimeout),
|
|
9283
|
-
isAborted: () => aborted
|
|
9284
|
-
});
|
|
9285
|
-
return { code, signal: null, success: code === 0 };
|
|
9286
|
-
} catch (error) {
|
|
9287
|
-
if (aborted) return abortedExitInfo();
|
|
9288
|
-
const err = toError(error);
|
|
9289
|
-
stdout.error(err);
|
|
9290
|
-
stderr.error(err);
|
|
9291
|
-
throw err;
|
|
9292
|
-
} finally {
|
|
9293
|
-
if (signal) {
|
|
9294
|
-
signal.removeEventListener("abort", abort);
|
|
9295
|
-
}
|
|
9296
|
-
stdout.close();
|
|
9297
|
-
stderr.close();
|
|
9298
|
-
if (sessionCreated) {
|
|
9299
|
-
await sandbox.process.deleteSession(sessionId).catch(() => {
|
|
9300
|
-
});
|
|
9301
|
-
}
|
|
9302
|
-
}
|
|
9303
|
-
}
|
|
9304
|
-
async function waitForSessionCommandExitCode(args) {
|
|
9305
|
-
const { sandbox, sessionId, commandId, timeoutMs, isAborted } = args;
|
|
9306
|
-
const deadline = Date.now() + timeoutMs;
|
|
9307
|
-
while (true) {
|
|
9308
|
-
if (isAborted()) throw new DaytonaCommandError("Daytona command aborted.");
|
|
9309
|
-
const info = await sandbox.process.getSessionCommand(sessionId, commandId);
|
|
9310
|
-
if (typeof info.exitCode === "number") {
|
|
9311
|
-
return info.exitCode;
|
|
9312
|
-
}
|
|
9313
|
-
if (Date.now() >= deadline) {
|
|
9314
|
-
throw new DaytonaCommandError(
|
|
9315
|
-
`Daytona session command "${commandId}" logs closed before an exit code became available.`
|
|
9316
|
-
);
|
|
9317
|
-
}
|
|
9318
|
-
await delay(DAYTONA_EXIT_POLL_INTERVAL_MS);
|
|
9319
|
-
}
|
|
9320
|
-
}
|
|
9321
|
-
function sessionExitPollTimeoutMs(commandTimeout) {
|
|
9322
|
-
if (commandTimeout === void 0 || commandTimeout === 0) {
|
|
9323
|
-
return DAYTONA_EXIT_POLL_TIMEOUT_MS;
|
|
9324
|
-
}
|
|
9325
|
-
return Math.max(commandTimeout * 1e3, DAYTONA_EXIT_POLL_TIMEOUT_MS);
|
|
9326
|
-
}
|
|
9327
|
-
function delay(ms) {
|
|
9328
|
-
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
9329
|
-
}
|
|
9330
9212
|
function createTextReadable() {
|
|
9331
9213
|
const encoder = new TextEncoder();
|
|
9332
|
-
|
|
9333
|
-
|
|
9334
|
-
return {
|
|
9335
|
-
stream: new ReadableStream({
|
|
9336
|
-
start(streamController) {
|
|
9337
|
-
controller = streamController;
|
|
9338
|
-
}
|
|
9339
|
-
}),
|
|
9340
|
-
enqueue(chunk) {
|
|
9341
|
-
if (closed || !chunk) return;
|
|
9342
|
-
controller?.enqueue(encoder.encode(chunk));
|
|
9214
|
+
const ended = {
|
|
9215
|
+
enqueue() {
|
|
9343
9216
|
},
|
|
9344
9217
|
close() {
|
|
9345
|
-
if (closed) return;
|
|
9346
|
-
closed = true;
|
|
9347
|
-
controller?.close();
|
|
9348
9218
|
},
|
|
9349
|
-
error(
|
|
9350
|
-
if (closed) return;
|
|
9351
|
-
closed = true;
|
|
9352
|
-
controller?.error(error);
|
|
9219
|
+
error() {
|
|
9353
9220
|
}
|
|
9354
9221
|
};
|
|
9222
|
+
let sink = ended;
|
|
9223
|
+
const stream = new ReadableStream({
|
|
9224
|
+
start(controller) {
|
|
9225
|
+
sink = {
|
|
9226
|
+
enqueue(chunk) {
|
|
9227
|
+
if (chunk) controller.enqueue(encoder.encode(chunk));
|
|
9228
|
+
},
|
|
9229
|
+
close() {
|
|
9230
|
+
sink = ended;
|
|
9231
|
+
controller.close();
|
|
9232
|
+
},
|
|
9233
|
+
error(error) {
|
|
9234
|
+
sink = ended;
|
|
9235
|
+
controller.error(error);
|
|
9236
|
+
}
|
|
9237
|
+
};
|
|
9238
|
+
}
|
|
9239
|
+
});
|
|
9240
|
+
return {
|
|
9241
|
+
stream,
|
|
9242
|
+
enqueue: (chunk) => sink.enqueue(chunk),
|
|
9243
|
+
close: () => sink.close(),
|
|
9244
|
+
error: (error) => sink.error(error)
|
|
9245
|
+
};
|
|
9355
9246
|
}
|
|
9356
9247
|
function buildSessionCommand(command, options) {
|
|
9357
9248
|
const cwdPrefix = options.cwd ? `cd ${shellQuote(options.cwd)} && ` : "";
|
|
@@ -9373,9 +9264,6 @@ function validateEnvKey(key) {
|
|
|
9373
9264
|
);
|
|
9374
9265
|
}
|
|
9375
9266
|
}
|
|
9376
|
-
function createSessionId(kind) {
|
|
9377
|
-
return `deepagents-${kind}-${randomUUID()}`;
|
|
9378
|
-
}
|
|
9379
9267
|
function abortedCommandResult() {
|
|
9380
9268
|
return {
|
|
9381
9269
|
stdout: "",
|
|
@@ -9414,39 +9302,192 @@ function toError(error) {
|
|
|
9414
9302
|
}
|
|
9415
9303
|
|
|
9416
9304
|
// packages/context/src/lib/sandbox/docker-sandbox.ts
|
|
9417
|
-
import
|
|
9418
|
-
|
|
9419
|
-
|
|
9305
|
+
import {
|
|
9306
|
+
BindSourceNotFoundError,
|
|
9307
|
+
ConnectionFailedError,
|
|
9308
|
+
ContainerNotFoundError,
|
|
9309
|
+
Docker,
|
|
9310
|
+
DockerError,
|
|
9311
|
+
ImageNotFoundError,
|
|
9312
|
+
NameConflictError,
|
|
9313
|
+
NotAFileError,
|
|
9314
|
+
VolumeInUseError
|
|
9315
|
+
} from "@zukhruf/docker";
|
|
9316
|
+
import spawn3, { SubprocessError as SubprocessError4 } from "nano-spawn";
|
|
9317
|
+
import { spawn as childSpawn2 } from "node:child_process";
|
|
9318
|
+
import { hash, randomUUID as randomUUID3 } from "node:crypto";
|
|
9420
9319
|
import { readFileSync as readFileSync2 } from "node:fs";
|
|
9421
|
-
import {
|
|
9320
|
+
import { posix as posix2 } from "node:path";
|
|
9321
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
9422
9322
|
function isDockerfileOptions(opts) {
|
|
9423
9323
|
return "dockerfile" in opts;
|
|
9424
9324
|
}
|
|
9425
9325
|
function isComposeOptions(opts) {
|
|
9426
9326
|
return "compose" in opts;
|
|
9427
9327
|
}
|
|
9428
|
-
|
|
9429
|
-
|
|
9430
|
-
|
|
9431
|
-
|
|
9432
|
-
|
|
9433
|
-
|
|
9434
|
-
|
|
9435
|
-
|
|
9436
|
-
|
|
9437
|
-
|
|
9438
|
-
|
|
9328
|
+
var SIZE_UNITS = {
|
|
9329
|
+
"": 1,
|
|
9330
|
+
k: 1024,
|
|
9331
|
+
m: 1024 ** 2,
|
|
9332
|
+
g: 1024 ** 3,
|
|
9333
|
+
t: 1024 ** 4,
|
|
9334
|
+
p: 1024 ** 5
|
|
9335
|
+
};
|
|
9336
|
+
function sizeInBytes(flag, value) {
|
|
9337
|
+
const match = /^(\d+(?:\.\d+)?)\s*([kmgtp]?)(?:i?b)?$/i.exec(value);
|
|
9338
|
+
if (!match) {
|
|
9339
|
+
throw new DockerSandboxError(`Invalid ${flag} size: "${value}"`);
|
|
9439
9340
|
}
|
|
9440
|
-
return
|
|
9341
|
+
return Math.floor(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
|
|
9342
|
+
}
|
|
9343
|
+
function ulimit(value) {
|
|
9344
|
+
const match = /^([a-z]+)=(-?\d+)(?::(-?\d+))?$/.exec(value);
|
|
9345
|
+
if (!match) {
|
|
9346
|
+
throw new DockerSandboxError(`Invalid ulimit: "${value}"`);
|
|
9347
|
+
}
|
|
9348
|
+
const soft = Number(match[2]);
|
|
9349
|
+
return {
|
|
9350
|
+
Name: match[1],
|
|
9351
|
+
Soft: soft,
|
|
9352
|
+
Hard: match[3] === void 0 ? soft : Number(match[3])
|
|
9353
|
+
};
|
|
9354
|
+
}
|
|
9355
|
+
function device(value) {
|
|
9356
|
+
const [host, container = host, permissions = "rwm"] = value.split(":");
|
|
9357
|
+
return {
|
|
9358
|
+
PathOnHost: host,
|
|
9359
|
+
PathInContainer: container,
|
|
9360
|
+
CgroupPermissions: permissions
|
|
9361
|
+
};
|
|
9362
|
+
}
|
|
9363
|
+
function gpuRequest(value) {
|
|
9364
|
+
if (value === "all") return { Count: -1, Capabilities: [["gpu"]] };
|
|
9365
|
+
if (/^\d+$/.test(value)) {
|
|
9366
|
+
return { Count: Number(value), Capabilities: [["gpu"]] };
|
|
9367
|
+
}
|
|
9368
|
+
const devices = /^device=(.+)$/.exec(value);
|
|
9369
|
+
if (devices) {
|
|
9370
|
+
return { DeviceIDs: devices[1].split(","), Capabilities: [["gpu"]] };
|
|
9371
|
+
}
|
|
9372
|
+
throw new DockerSandboxError(`Invalid gpus value: "${value}"`);
|
|
9373
|
+
}
|
|
9374
|
+
function publishedPort(value) {
|
|
9375
|
+
const [address, protocol = "tcp"] = value.split("/");
|
|
9376
|
+
const parts = address.split(":");
|
|
9377
|
+
const containerPort = parts.pop();
|
|
9378
|
+
const hostPort = parts.pop() ?? "";
|
|
9379
|
+
const hostIp = parts.join(":");
|
|
9380
|
+
if (!containerPort || !/^\d+$/.test(containerPort)) {
|
|
9381
|
+
throw new DockerSandboxError(`Invalid publish value: "${value}"`);
|
|
9382
|
+
}
|
|
9383
|
+
return {
|
|
9384
|
+
port: `${containerPort}/${protocol}`,
|
|
9385
|
+
binding: { HostIp: hostIp, HostPort: hostPort }
|
|
9386
|
+
};
|
|
9387
|
+
}
|
|
9388
|
+
function securityOption(entry) {
|
|
9389
|
+
const match = /^seccomp[=:](.+)$/.exec(entry);
|
|
9390
|
+
if (!match || match[1] === "unconfined") return entry;
|
|
9391
|
+
return `seccomp=${JSON.stringify(JSON.parse(readFileSync2(match[1], "utf-8")))}`;
|
|
9392
|
+
}
|
|
9393
|
+
function mount(volume) {
|
|
9394
|
+
const ReadOnly = volume.readOnly !== false;
|
|
9395
|
+
if (volume.type === "bind") {
|
|
9396
|
+
return {
|
|
9397
|
+
Type: "bind",
|
|
9398
|
+
Source: volume.hostPath,
|
|
9399
|
+
Target: volume.containerPath,
|
|
9400
|
+
ReadOnly
|
|
9401
|
+
};
|
|
9402
|
+
}
|
|
9403
|
+
return {
|
|
9404
|
+
Type: "volume",
|
|
9405
|
+
Source: volume.name,
|
|
9406
|
+
Target: volume.containerPath,
|
|
9407
|
+
ReadOnly,
|
|
9408
|
+
...volume.subPath || volume.noCopy ? {
|
|
9409
|
+
VolumeOptions: {
|
|
9410
|
+
...volume.subPath ? { Subpath: volume.subPath } : {},
|
|
9411
|
+
...volume.noCopy ? { NoCopy: true } : {}
|
|
9412
|
+
}
|
|
9413
|
+
} : {}
|
|
9414
|
+
};
|
|
9441
9415
|
}
|
|
9442
|
-
function
|
|
9416
|
+
function containerCreateRequest(image, opts, workdir) {
|
|
9417
|
+
const {
|
|
9418
|
+
memory = "1g",
|
|
9419
|
+
cpus = 2,
|
|
9420
|
+
memorySwap,
|
|
9421
|
+
shmSize,
|
|
9422
|
+
pidsLimit,
|
|
9423
|
+
ulimits = [],
|
|
9424
|
+
cpusetCpus,
|
|
9425
|
+
cpuShares
|
|
9426
|
+
} = opts.resources ?? {};
|
|
9427
|
+
const security = opts.security ?? {};
|
|
9428
|
+
const network = opts.network ?? {};
|
|
9429
|
+
const published = (network.publish ?? []).map(publishedPort);
|
|
9430
|
+
return {
|
|
9431
|
+
Image: image,
|
|
9432
|
+
WorkingDir: workdir,
|
|
9433
|
+
Env: Object.entries(opts.env ?? {}).map(
|
|
9434
|
+
([key, value]) => `${key}=${value}`
|
|
9435
|
+
),
|
|
9436
|
+
Labels: opts.labels ?? {},
|
|
9437
|
+
...opts.command === void 0 ? { Cmd: ["tail", "-f", "/dev/null"] } : opts.command === null || opts.command.length === 0 ? {} : { Cmd: [...opts.command] },
|
|
9438
|
+
...opts.entrypoint === void 0 ? {} : { Entrypoint: [opts.entrypoint] },
|
|
9439
|
+
...security.user ? { User: security.user } : {},
|
|
9440
|
+
...network.hostname ? { Hostname: network.hostname } : {},
|
|
9441
|
+
ExposedPorts: Object.fromEntries(published.map(({ port }) => [port, {}])),
|
|
9442
|
+
HostConfig: {
|
|
9443
|
+
AutoRemove: true,
|
|
9444
|
+
Memory: sizeInBytes("memory", memory),
|
|
9445
|
+
NanoCpus: Math.round(cpus * 1e9),
|
|
9446
|
+
...memorySwap ? {
|
|
9447
|
+
MemorySwap: memorySwap === "-1" ? -1 : sizeInBytes("memorySwap", memorySwap)
|
|
9448
|
+
} : {},
|
|
9449
|
+
...shmSize ? { ShmSize: sizeInBytes("shmSize", shmSize) } : {},
|
|
9450
|
+
...pidsLimit === void 0 ? {} : { PidsLimit: pidsLimit },
|
|
9451
|
+
Ulimits: ulimits.map(ulimit),
|
|
9452
|
+
...cpusetCpus ? { CpusetCpus: cpusetCpus } : {},
|
|
9453
|
+
...cpuShares === void 0 ? {} : { CpuShares: cpuShares },
|
|
9454
|
+
...opts.runtime ? { Runtime: opts.runtime } : {},
|
|
9455
|
+
CapDrop: security.capDrop ?? [],
|
|
9456
|
+
CapAdd: security.capAdd ?? [],
|
|
9457
|
+
ReadonlyRootfs: security.readOnly === true,
|
|
9458
|
+
Tmpfs: Object.fromEntries(
|
|
9459
|
+
(security.tmpfs ?? []).map((entry) => {
|
|
9460
|
+
const separator = entry.indexOf(":");
|
|
9461
|
+
return separator < 0 ? [entry, ""] : [entry.slice(0, separator), entry.slice(separator + 1)];
|
|
9462
|
+
})
|
|
9463
|
+
),
|
|
9464
|
+
SecurityOpt: (security.securityOpt ?? []).map(securityOption),
|
|
9465
|
+
...network.mode ? { NetworkMode: network.mode } : {},
|
|
9466
|
+
PortBindings: published.reduce(
|
|
9467
|
+
(bindings, { port, binding }) => ({
|
|
9468
|
+
...bindings,
|
|
9469
|
+
[port]: [...bindings[port] ?? [], binding]
|
|
9470
|
+
}),
|
|
9471
|
+
{}
|
|
9472
|
+
),
|
|
9473
|
+
Dns: network.dns ?? [],
|
|
9474
|
+
ExtraHosts: network.addHost ?? [],
|
|
9475
|
+
...opts.gpus ? { DeviceRequests: [gpuRequest(opts.gpus)] } : {},
|
|
9476
|
+
Devices: (opts.devices ?? []).map(device),
|
|
9477
|
+
...opts.init ? { Init: true } : {},
|
|
9478
|
+
Sysctls: opts.sysctls ?? {},
|
|
9479
|
+
Mounts: (opts.volumes ?? []).map(mount)
|
|
9480
|
+
}
|
|
9481
|
+
};
|
|
9482
|
+
}
|
|
9483
|
+
function runDockerBuild(args, stdin, showBuildLogs, env) {
|
|
9443
9484
|
const stdio = [
|
|
9444
9485
|
stdin === void 0 ? "inherit" : "pipe",
|
|
9445
9486
|
showBuildLogs ? "inherit" : "ignore",
|
|
9446
9487
|
showBuildLogs ? "inherit" : "pipe"
|
|
9447
9488
|
];
|
|
9448
9489
|
return new Promise((resolve3, reject) => {
|
|
9449
|
-
const child =
|
|
9490
|
+
const child = childSpawn2("docker", args, { stdio, env });
|
|
9450
9491
|
let stderr = "";
|
|
9451
9492
|
child.stderr?.on("data", (chunk) => {
|
|
9452
9493
|
stderr += chunk;
|
|
@@ -9473,229 +9514,593 @@ function runDockerBuild(args, stdin, showBuildLogs) {
|
|
|
9473
9514
|
}
|
|
9474
9515
|
});
|
|
9475
9516
|
}
|
|
9476
|
-
|
|
9477
|
-
|
|
9478
|
-
|
|
9479
|
-
|
|
9480
|
-
|
|
9481
|
-
|
|
9482
|
-
|
|
9517
|
+
async function startContainer(container, image) {
|
|
9518
|
+
try {
|
|
9519
|
+
await container.start();
|
|
9520
|
+
} catch (error) {
|
|
9521
|
+
if (error instanceof ConnectionFailedError) {
|
|
9522
|
+
throw new DockerNotAvailableError();
|
|
9523
|
+
}
|
|
9524
|
+
throw new ContainerCreationError(
|
|
9525
|
+
messageOf(error),
|
|
9526
|
+
image,
|
|
9527
|
+
error instanceof Error ? error : void 0
|
|
9483
9528
|
);
|
|
9484
|
-
|
|
9485
|
-
|
|
9486
|
-
|
|
9487
|
-
|
|
9488
|
-
|
|
9489
|
-
|
|
9490
|
-
|
|
9529
|
+
}
|
|
9530
|
+
}
|
|
9531
|
+
function unavailable(error) {
|
|
9532
|
+
if (error instanceof ConnectionFailedError) {
|
|
9533
|
+
throw new DockerNotAvailableError();
|
|
9534
|
+
}
|
|
9535
|
+
throw error;
|
|
9536
|
+
}
|
|
9537
|
+
function isBindSource(reported, hostPath) {
|
|
9538
|
+
const canonical = hostPath.replace(/^\/(tmp|var|etc)(?=\/|$)/, "/private/$1");
|
|
9539
|
+
return [hostPath, `/host_mnt${hostPath}`, `/host_mnt${canonical}`].includes(
|
|
9540
|
+
reported
|
|
9541
|
+
);
|
|
9542
|
+
}
|
|
9543
|
+
var dockerErrors = {
|
|
9544
|
+
generic: (message2, containerId) => new DockerSandboxError(message2, containerId),
|
|
9545
|
+
volumePath: (source, containerPath, reason) => new VolumePathError(source, containerPath, reason),
|
|
9546
|
+
volumeInspect: (name, reason) => new VolumeInspectError(name, reason),
|
|
9547
|
+
volumeCreate: (name, reason) => new VolumeCreateError(name, reason)
|
|
9548
|
+
};
|
|
9549
|
+
function withoutFinalNewline(text) {
|
|
9550
|
+
return text.replace(/\r?\n$/, "");
|
|
9551
|
+
}
|
|
9552
|
+
function sandboxProcess(process2) {
|
|
9553
|
+
const queue = { highWaterMark: Number.POSITIVE_INFINITY };
|
|
9554
|
+
const stdout = new TransformStream(
|
|
9555
|
+
void 0,
|
|
9556
|
+
void 0,
|
|
9557
|
+
queue
|
|
9558
|
+
);
|
|
9559
|
+
const stderr = new TransformStream(
|
|
9560
|
+
void 0,
|
|
9561
|
+
void 0,
|
|
9562
|
+
queue
|
|
9563
|
+
);
|
|
9564
|
+
const writers = {
|
|
9565
|
+
stdout: stdout.writable.getWriter(),
|
|
9566
|
+
stderr: stderr.writable.getWriter()
|
|
9567
|
+
};
|
|
9568
|
+
const exit = (async () => {
|
|
9569
|
+
try {
|
|
9570
|
+
for await (const { stream, data } of process2) {
|
|
9571
|
+
await writers[stream].write(data);
|
|
9491
9572
|
}
|
|
9492
|
-
)
|
|
9493
|
-
|
|
9494
|
-
|
|
9495
|
-
|
|
9496
|
-
|
|
9497
|
-
|
|
9498
|
-
memorySwap,
|
|
9499
|
-
shmSize,
|
|
9500
|
-
pidsLimit,
|
|
9501
|
-
ulimits = [],
|
|
9502
|
-
cpusetCpus,
|
|
9503
|
-
cpuShares
|
|
9504
|
-
} = opts.resources ?? {};
|
|
9505
|
-
const security = opts.security ?? {};
|
|
9506
|
-
const network = opts.network ?? {};
|
|
9507
|
-
const args = [
|
|
9508
|
-
"run",
|
|
9509
|
-
"-d",
|
|
9510
|
-
"--rm",
|
|
9511
|
-
"--name",
|
|
9512
|
-
containerId,
|
|
9513
|
-
"--memory",
|
|
9514
|
-
memory,
|
|
9515
|
-
"--cpus",
|
|
9516
|
-
String(cpus),
|
|
9517
|
-
"-w",
|
|
9518
|
-
workdir
|
|
9519
|
-
];
|
|
9520
|
-
if (memorySwap) {
|
|
9521
|
-
args.push("--memory-swap", memorySwap);
|
|
9522
|
-
}
|
|
9523
|
-
if (shmSize) {
|
|
9524
|
-
args.push("--shm-size", shmSize);
|
|
9525
|
-
}
|
|
9526
|
-
if (pidsLimit !== void 0) {
|
|
9527
|
-
args.push("--pids-limit", String(pidsLimit));
|
|
9528
|
-
}
|
|
9529
|
-
for (const ulimit of ulimits) {
|
|
9530
|
-
args.push("--ulimit", ulimit);
|
|
9531
|
-
}
|
|
9532
|
-
if (cpusetCpus) {
|
|
9533
|
-
args.push("--cpuset-cpus", cpusetCpus);
|
|
9534
|
-
}
|
|
9535
|
-
if (cpuShares !== void 0) {
|
|
9536
|
-
args.push("--cpu-shares", String(cpuShares));
|
|
9537
|
-
}
|
|
9538
|
-
if (opts.platform) {
|
|
9539
|
-
args.push("--platform", opts.platform);
|
|
9540
|
-
}
|
|
9541
|
-
if (opts.runtime) {
|
|
9542
|
-
args.push("--runtime", opts.runtime);
|
|
9543
|
-
}
|
|
9544
|
-
for (const cap of security.capDrop ?? []) {
|
|
9545
|
-
args.push("--cap-drop", cap);
|
|
9573
|
+
} catch (error) {
|
|
9574
|
+
await Promise.all([
|
|
9575
|
+
writers.stdout.abort(error),
|
|
9576
|
+
writers.stderr.abort(error)
|
|
9577
|
+
]);
|
|
9578
|
+
throw error;
|
|
9546
9579
|
}
|
|
9547
|
-
|
|
9548
|
-
|
|
9580
|
+
await Promise.all([writers.stdout.close(), writers.stderr.close()]);
|
|
9581
|
+
const code = await process2.exitCode;
|
|
9582
|
+
return { code, signal: null, success: code === 0 };
|
|
9583
|
+
})();
|
|
9584
|
+
return { stdout: stdout.readable, stderr: stderr.readable, exit };
|
|
9585
|
+
}
|
|
9586
|
+
function managedDockerCommand(command, controlPath, commandTimeout) {
|
|
9587
|
+
return [
|
|
9588
|
+
"set -m",
|
|
9589
|
+
`control=${shellQuote(controlPath)}`,
|
|
9590
|
+
': > "$control" || exit 1',
|
|
9591
|
+
"timer=",
|
|
9592
|
+
`trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
|
|
9593
|
+
`bash -lc ${shellQuote(command)} &`,
|
|
9594
|
+
"pid=$!",
|
|
9595
|
+
`printf '%s\\n' "$pid" > "$control"`,
|
|
9596
|
+
...commandTimeout ? [
|
|
9597
|
+
// Keep the deadline on the engine host: SSH setup/round trips must not
|
|
9598
|
+
// let the command run past its execution budget.
|
|
9599
|
+
"(",
|
|
9600
|
+
`sleep ${commandTimeout / 1e3} &`,
|
|
9601
|
+
"alarm=$!",
|
|
9602
|
+
`trap 'kill "$alarm" 2>/dev/null || :; wait "$alarm" 2>/dev/null || :; exit 0' TERM`,
|
|
9603
|
+
'wait "$alarm" || exit',
|
|
9604
|
+
'if kill -0 -- "-$pid" 2>/dev/null; then : > "$control.timeout"; kill -KILL -- "-$pid" 2>/dev/null || :; fi',
|
|
9605
|
+
") &",
|
|
9606
|
+
"timer=$!"
|
|
9607
|
+
] : [],
|
|
9608
|
+
'wait "$pid"',
|
|
9609
|
+
"status=$?",
|
|
9610
|
+
'[ ! -e "$control.timeout" ] || exit 124',
|
|
9611
|
+
'exit "$status"'
|
|
9612
|
+
].join("\n");
|
|
9613
|
+
}
|
|
9614
|
+
var MAX_SYMLINK_HOPS = 40;
|
|
9615
|
+
var KERNEL_FILESYSTEMS = ["/proc", "/sys", "/dev"];
|
|
9616
|
+
var RESOLVE_OWNER = [
|
|
9617
|
+
"user=$1 group=$2",
|
|
9618
|
+
'case $user in *[!0-9]*) uid=$(id -u "$user") || exit 1 ;; *) uid=$user ;; esac',
|
|
9619
|
+
"case $group in",
|
|
9620
|
+
' "") gid=$(id -g "$user" 2>/dev/null) || gid=0 ;;',
|
|
9621
|
+
` *[!0-9]*) gid=$(awk -F: -v name="$group" '$1 == name { print $3 }' /etc/group); [ -n "$gid" ] || { echo "unknown group $group" >&2; exit 1; } ;;`,
|
|
9622
|
+
" *) gid=$group ;;",
|
|
9623
|
+
"esac",
|
|
9624
|
+
`printf '%s %s' "$uid" "$gid"`
|
|
9625
|
+
].join("\n");
|
|
9626
|
+
function fileLayout(config, hostConfig) {
|
|
9627
|
+
return {
|
|
9628
|
+
workdir: config?.WorkingDir || "/",
|
|
9629
|
+
execOnly: [...KERNEL_FILESYSTEMS, ...Object.keys(hostConfig?.Tmpfs ?? {})],
|
|
9630
|
+
user: config?.User ?? ""
|
|
9631
|
+
};
|
|
9632
|
+
}
|
|
9633
|
+
async function resolveOwner(container, user2) {
|
|
9634
|
+
if (user2 === "") return void 0;
|
|
9635
|
+
const separator = user2.indexOf(":");
|
|
9636
|
+
const [name, group] = separator < 0 ? [user2, ""] : [user2.slice(0, separator), user2.slice(separator + 1)];
|
|
9637
|
+
const result = await container.exec({
|
|
9638
|
+
Cmd: ["sh", "-c", RESOLVE_OWNER, "sh", name, group]
|
|
9639
|
+
});
|
|
9640
|
+
if (result.exitCode !== 0) {
|
|
9641
|
+
throw new DockerSandboxError(
|
|
9642
|
+
`Failed to resolve the container user "${user2}": ${result.stderr.trim()}`
|
|
9643
|
+
);
|
|
9644
|
+
}
|
|
9645
|
+
const [uid, gid] = result.stdout.split(" ").map(Number);
|
|
9646
|
+
return { uid, gid };
|
|
9647
|
+
}
|
|
9648
|
+
function messageOf(error) {
|
|
9649
|
+
return error instanceof Error ? error.message : String(error);
|
|
9650
|
+
}
|
|
9651
|
+
var DockerContainer = class {
|
|
9652
|
+
name;
|
|
9653
|
+
#container;
|
|
9654
|
+
#layout;
|
|
9655
|
+
/** Who owns the files the sandbox writes: the container user, or root. */
|
|
9656
|
+
#owner;
|
|
9657
|
+
#commandTimeout;
|
|
9658
|
+
constructor(name, container, layout, owner, commandTimeout) {
|
|
9659
|
+
this.name = name;
|
|
9660
|
+
this.#container = container;
|
|
9661
|
+
this.#layout = layout;
|
|
9662
|
+
this.#owner = owner;
|
|
9663
|
+
this.#commandTimeout = commandTimeout;
|
|
9664
|
+
}
|
|
9665
|
+
/** `command` under `bash -lc`, with the spawn options' directory and environment. */
|
|
9666
|
+
#bash(command, options = {}) {
|
|
9667
|
+
const env = Object.entries(options.env ?? {}).map(([key, value]) => {
|
|
9668
|
+
if (key.length === 0 || key.includes("=")) {
|
|
9669
|
+
throw new DockerSandboxError(
|
|
9670
|
+
`Invalid environment variable key: "${key}"`
|
|
9671
|
+
);
|
|
9672
|
+
}
|
|
9673
|
+
return `${key}=${value}`;
|
|
9674
|
+
});
|
|
9675
|
+
return {
|
|
9676
|
+
Cmd: ["bash", "-lc", command],
|
|
9677
|
+
Env: env,
|
|
9678
|
+
...options.cwd ? { WorkingDir: options.cwd } : {}
|
|
9679
|
+
};
|
|
9680
|
+
}
|
|
9681
|
+
async #exec(config) {
|
|
9682
|
+
try {
|
|
9683
|
+
const { stdout, stderr, exitCode } = await this.#container.exec(config);
|
|
9684
|
+
return {
|
|
9685
|
+
stdout: withoutFinalNewline(stdout),
|
|
9686
|
+
stderr: withoutFinalNewline(stderr),
|
|
9687
|
+
exitCode
|
|
9688
|
+
};
|
|
9689
|
+
} catch (error) {
|
|
9690
|
+
if (!(error instanceof DockerError)) throw error;
|
|
9691
|
+
return { stdout: "", stderr: error.message, exitCode: 1 };
|
|
9549
9692
|
}
|
|
9550
|
-
|
|
9551
|
-
|
|
9693
|
+
}
|
|
9694
|
+
async executeCommand(command, options = {}) {
|
|
9695
|
+
if (!this.#commandTimeout && options.signal === void 0) {
|
|
9696
|
+
return this.#exec(this.#bash(command));
|
|
9552
9697
|
}
|
|
9553
|
-
|
|
9554
|
-
|
|
9698
|
+
const process2 = await this.spawn(command, { signal: options.signal });
|
|
9699
|
+
const [stdout, stderr, info] = await Promise.all([
|
|
9700
|
+
new Response(process2.stdout).text(),
|
|
9701
|
+
new Response(process2.stderr).text(),
|
|
9702
|
+
process2.exit
|
|
9703
|
+
]);
|
|
9704
|
+
const result = {
|
|
9705
|
+
stdout: withoutFinalNewline(stdout),
|
|
9706
|
+
stderr: withoutFinalNewline(stderr)
|
|
9707
|
+
};
|
|
9708
|
+
if (info.signal === "SIGKILL") {
|
|
9709
|
+
return {
|
|
9710
|
+
...result,
|
|
9711
|
+
stderr: result.stderr || "Command aborted",
|
|
9712
|
+
exitCode: 1
|
|
9713
|
+
};
|
|
9555
9714
|
}
|
|
9556
|
-
|
|
9557
|
-
|
|
9715
|
+
return { ...result, exitCode: info.code ?? 1 };
|
|
9716
|
+
}
|
|
9717
|
+
async spawn(command, options = {}) {
|
|
9718
|
+
if (!this.#commandTimeout && options.signal === void 0) {
|
|
9719
|
+
return sandboxProcess(
|
|
9720
|
+
await this.#container.spawn(this.#bash(command, options))
|
|
9721
|
+
);
|
|
9558
9722
|
}
|
|
9559
|
-
|
|
9560
|
-
|
|
9723
|
+
const controlPath = `/dev/shm/deepagents-exec-${randomUUID3()}.pid`;
|
|
9724
|
+
const execution = sandboxProcess(
|
|
9725
|
+
await this.#container.spawn(
|
|
9726
|
+
this.#bash(
|
|
9727
|
+
managedDockerCommand(command, controlPath, this.#commandTimeout),
|
|
9728
|
+
options
|
|
9729
|
+
)
|
|
9730
|
+
)
|
|
9731
|
+
);
|
|
9732
|
+
let termination;
|
|
9733
|
+
const onAbort = () => {
|
|
9734
|
+
termination ??= this.#terminate(controlPath, execution.exit);
|
|
9735
|
+
void termination.catch(() => {
|
|
9736
|
+
});
|
|
9737
|
+
};
|
|
9738
|
+
if (options.signal?.aborted) onAbort();
|
|
9739
|
+
else options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
9740
|
+
return {
|
|
9741
|
+
stdout: execution.stdout,
|
|
9742
|
+
stderr: execution.stderr,
|
|
9743
|
+
exit: execution.exit.then(async (info) => {
|
|
9744
|
+
const activeTermination = termination;
|
|
9745
|
+
if (!activeTermination || !await activeTermination) {
|
|
9746
|
+
return info;
|
|
9747
|
+
}
|
|
9748
|
+
return { code: null, signal: "SIGKILL", success: false };
|
|
9749
|
+
}).finally(() => {
|
|
9750
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
9751
|
+
})
|
|
9752
|
+
};
|
|
9753
|
+
}
|
|
9754
|
+
/** The PID that the managed command wrote, or `undefined` once it exited. */
|
|
9755
|
+
async #managedPid(controlPath, exit) {
|
|
9756
|
+
const exited = exit.then(
|
|
9757
|
+
() => true,
|
|
9758
|
+
() => true
|
|
9759
|
+
);
|
|
9760
|
+
const readPid = `if IFS= read -r pid < ${shellQuote(controlPath)}; then printf '%s' "$pid"; fi`;
|
|
9761
|
+
while (true) {
|
|
9762
|
+
const { stdout } = await this.#container.exec(this.#bash(readPid));
|
|
9763
|
+
if (stdout) return Number(stdout);
|
|
9764
|
+
if (await Promise.race([exited, delay(10).then(() => false)])) {
|
|
9765
|
+
return void 0;
|
|
9766
|
+
}
|
|
9561
9767
|
}
|
|
9562
|
-
|
|
9563
|
-
|
|
9768
|
+
}
|
|
9769
|
+
/** Kills the managed command's process group; `true` when it was still running. */
|
|
9770
|
+
async #terminate(controlPath, exit) {
|
|
9771
|
+
const pid = await this.#managedPid(controlPath, exit);
|
|
9772
|
+
if (pid === void 0) return false;
|
|
9773
|
+
const { stdout } = await this.#container.exec(
|
|
9774
|
+
this.#bash(
|
|
9775
|
+
[
|
|
9776
|
+
`pid=${pid}`,
|
|
9777
|
+
`IFS= read -r control_pid < ${shellQuote(controlPath)} || exit 0`,
|
|
9778
|
+
'[ "$control_pid" = "$pid" ] || exit 0',
|
|
9779
|
+
'kill -KILL -- "-$pid" 2>/dev/null || exit 0',
|
|
9780
|
+
"group_alive() {",
|
|
9781
|
+
" local stat rest state pgrp",
|
|
9782
|
+
" for stat_path in /proc/[0-9]*/stat; do",
|
|
9783
|
+
' IFS= read -r stat < "$stat_path" || continue',
|
|
9784
|
+
" rest=${stat##*) }",
|
|
9785
|
+
' read -r state _ pgrp _ <<< "$rest"',
|
|
9786
|
+
' if [ "$pgrp" = "$pid" ] && [ "$state" != Z ]; then return 0; fi',
|
|
9787
|
+
" done",
|
|
9788
|
+
" return 1",
|
|
9789
|
+
"}",
|
|
9790
|
+
"while group_alive; do sleep 0.01; done",
|
|
9791
|
+
"printf terminated"
|
|
9792
|
+
].join("\n")
|
|
9793
|
+
)
|
|
9794
|
+
);
|
|
9795
|
+
return stdout === "terminated";
|
|
9796
|
+
}
|
|
9797
|
+
#resolve(path6) {
|
|
9798
|
+
return posix2.resolve(this.#layout.workdir, path6);
|
|
9799
|
+
}
|
|
9800
|
+
/** The archive requests cannot reach a tmpfs mount or a kernel filesystem. */
|
|
9801
|
+
#isExecOnly(path6) {
|
|
9802
|
+
return this.#layout.execOnly.some(
|
|
9803
|
+
(root) => path6 === root || path6.startsWith(`${root}/`)
|
|
9804
|
+
);
|
|
9805
|
+
}
|
|
9806
|
+
async readFile(path6) {
|
|
9807
|
+
const target = this.#resolve(path6);
|
|
9808
|
+
try {
|
|
9809
|
+
return this.#isExecOnly(target) ? await this.#readByExec(target) : await this.#readArchive(target);
|
|
9810
|
+
} catch (error) {
|
|
9811
|
+
throw new Error(`Failed to read file "${path6}": ${messageOf(error)}`, {
|
|
9812
|
+
cause: error
|
|
9813
|
+
});
|
|
9564
9814
|
}
|
|
9565
|
-
|
|
9566
|
-
|
|
9815
|
+
}
|
|
9816
|
+
/** Follows symbolic links, as reading through the container's shell does. */
|
|
9817
|
+
async #readArchive(path6) {
|
|
9818
|
+
let target = path6;
|
|
9819
|
+
for (let hops = 0; ; hops++) {
|
|
9820
|
+
try {
|
|
9821
|
+
return await this.#container.readFile(target);
|
|
9822
|
+
} catch (error) {
|
|
9823
|
+
if (!(error instanceof NotAFileError && error.kind === "symlink") || hops === MAX_SYMLINK_HOPS) {
|
|
9824
|
+
throw error;
|
|
9825
|
+
}
|
|
9826
|
+
const stat = await this.#container.stat(target);
|
|
9827
|
+
if (!stat) throw error;
|
|
9828
|
+
target = posix2.resolve(posix2.dirname(target), stat.linkTarget);
|
|
9829
|
+
}
|
|
9567
9830
|
}
|
|
9568
|
-
|
|
9569
|
-
|
|
9831
|
+
}
|
|
9832
|
+
async #readByExec(path6) {
|
|
9833
|
+
const process2 = await this.#container.spawn({ Cmd: ["cat", "--", path6] });
|
|
9834
|
+
const stdout = [];
|
|
9835
|
+
const stderr = [];
|
|
9836
|
+
for await (const { stream, data } of process2) {
|
|
9837
|
+
(stream === "stdout" ? stdout : stderr).push(data);
|
|
9570
9838
|
}
|
|
9571
|
-
|
|
9572
|
-
|
|
9839
|
+
if (await process2.exitCode !== 0) {
|
|
9840
|
+
throw new Error(Buffer.concat(stderr).toString("utf-8").trim());
|
|
9573
9841
|
}
|
|
9574
|
-
|
|
9575
|
-
|
|
9842
|
+
return Buffer.concat(stdout);
|
|
9843
|
+
}
|
|
9844
|
+
async writeFiles(files) {
|
|
9845
|
+
const resolved = files.map(({ path: path6, content }) => ({
|
|
9846
|
+
path: this.#resolve(path6),
|
|
9847
|
+
content
|
|
9848
|
+
}));
|
|
9849
|
+
const byArchive = resolved.filter(({ path: path6 }) => !this.#isExecOnly(path6));
|
|
9850
|
+
if (byArchive.length > 0) {
|
|
9851
|
+
try {
|
|
9852
|
+
const owner = this.#owner;
|
|
9853
|
+
const directories = owner ? await this.#missingDirectories(
|
|
9854
|
+
byArchive.map(({ path: path6 }) => posix2.dirname(path6))
|
|
9855
|
+
) : [];
|
|
9856
|
+
await this.#container.writeFiles([
|
|
9857
|
+
...directories.map((path6) => ({
|
|
9858
|
+
path: path6,
|
|
9859
|
+
directory: true,
|
|
9860
|
+
...owner
|
|
9861
|
+
})),
|
|
9862
|
+
...byArchive.map(({ path: path6, content }) => ({
|
|
9863
|
+
path: path6,
|
|
9864
|
+
data: content,
|
|
9865
|
+
...owner
|
|
9866
|
+
}))
|
|
9867
|
+
]);
|
|
9868
|
+
} catch (error) {
|
|
9869
|
+
throw new Error(
|
|
9870
|
+
`Failed to write file "${byArchive.map(({ path: path6 }) => path6).join('", "')}": ${messageOf(error)}`,
|
|
9871
|
+
{ cause: error }
|
|
9872
|
+
);
|
|
9873
|
+
}
|
|
9576
9874
|
}
|
|
9577
|
-
|
|
9578
|
-
|
|
9875
|
+
for (const { path: path6, content } of resolved.filter(
|
|
9876
|
+
({ path: path7 }) => this.#isExecOnly(path7)
|
|
9877
|
+
)) {
|
|
9878
|
+
const result = await this.#container.exec(
|
|
9879
|
+
{
|
|
9880
|
+
Cmd: [
|
|
9881
|
+
"sh",
|
|
9882
|
+
"-c",
|
|
9883
|
+
'mkdir -p "$(dirname "$1")" && cat > "$1"',
|
|
9884
|
+
"sh",
|
|
9885
|
+
path6
|
|
9886
|
+
]
|
|
9887
|
+
},
|
|
9888
|
+
{ stdin: content }
|
|
9889
|
+
);
|
|
9890
|
+
if (result.exitCode !== 0) {
|
|
9891
|
+
throw new Error(`Failed to write file "${path6}": ${result.stderr}`);
|
|
9892
|
+
}
|
|
9579
9893
|
}
|
|
9580
|
-
|
|
9581
|
-
|
|
9894
|
+
}
|
|
9895
|
+
/** The directories, parents first, that a write into `directories` creates. */
|
|
9896
|
+
async #missingDirectories(directories) {
|
|
9897
|
+
const missing = /* @__PURE__ */ new Set();
|
|
9898
|
+
for (const start of new Set(directories)) {
|
|
9899
|
+
for (let directory = start; directory !== "/" && !missing.has(directory); directory = posix2.dirname(directory)) {
|
|
9900
|
+
if (await this.#container.stat(directory)) break;
|
|
9901
|
+
missing.add(directory);
|
|
9902
|
+
}
|
|
9582
9903
|
}
|
|
9583
|
-
|
|
9584
|
-
|
|
9904
|
+
return [...missing].sort((a, b) => a.length - b.length);
|
|
9905
|
+
}
|
|
9906
|
+
async exists(path6) {
|
|
9907
|
+
let target = this.#resolve(path6);
|
|
9908
|
+
if (this.#isExecOnly(target)) {
|
|
9909
|
+
const { exitCode } = await this.#container.exec({
|
|
9910
|
+
Cmd: ["test", "-e", target]
|
|
9911
|
+
});
|
|
9912
|
+
return exitCode === 0;
|
|
9585
9913
|
}
|
|
9586
|
-
for (
|
|
9587
|
-
|
|
9914
|
+
for (let hops = 0; hops <= MAX_SYMLINK_HOPS; hops++) {
|
|
9915
|
+
const stat = await this.#container.stat(target);
|
|
9916
|
+
if (!stat) return false;
|
|
9917
|
+
if (stat.linkTarget === "") return true;
|
|
9918
|
+
target = posix2.resolve(posix2.dirname(target), stat.linkTarget);
|
|
9588
9919
|
}
|
|
9589
|
-
|
|
9590
|
-
|
|
9920
|
+
return false;
|
|
9921
|
+
}
|
|
9922
|
+
installerContext(image) {
|
|
9923
|
+
return createInstallerContext(
|
|
9924
|
+
{
|
|
9925
|
+
// Installers run with `sh -c`, before the sandbox knows Bash exists.
|
|
9926
|
+
exec: (command) => this.#exec({ Cmd: ["sh", "-c", command] }),
|
|
9927
|
+
SandboxError: DockerSandboxError
|
|
9928
|
+
},
|
|
9929
|
+
this.name,
|
|
9930
|
+
image
|
|
9931
|
+
);
|
|
9932
|
+
}
|
|
9933
|
+
async stop() {
|
|
9934
|
+
try {
|
|
9935
|
+
await this.#container.stop();
|
|
9936
|
+
} catch (error) {
|
|
9937
|
+
if (error instanceof ContainerNotFoundError) return;
|
|
9938
|
+
throw error;
|
|
9591
9939
|
}
|
|
9592
|
-
|
|
9593
|
-
|
|
9940
|
+
}
|
|
9941
|
+
};
|
|
9942
|
+
var DockerEngine = class _DockerEngine {
|
|
9943
|
+
bindMountsOnClient = false;
|
|
9944
|
+
defaultImage = "bash:5.3-alpine3.24";
|
|
9945
|
+
errors = dockerErrors;
|
|
9946
|
+
docker;
|
|
9947
|
+
/** The environment of a docker CLI process that targets this engine. */
|
|
9948
|
+
cliEnv;
|
|
9949
|
+
#commandTimeout;
|
|
9950
|
+
constructor(docker, commandTimeout) {
|
|
9951
|
+
this.docker = docker;
|
|
9952
|
+
this.cliEnv = { ...process.env, ...docker.cliEnvironment };
|
|
9953
|
+
this.#commandTimeout = commandTimeout;
|
|
9954
|
+
}
|
|
9955
|
+
/**
|
|
9956
|
+
* Connects to the engine that the Docker CLI selects from `environment`.
|
|
9957
|
+
* `commandTimeout` bounds each command of the sandbox's containers.
|
|
9958
|
+
*/
|
|
9959
|
+
static async connect(environment, commandTimeout) {
|
|
9960
|
+
const docker = await Docker.connect({
|
|
9961
|
+
clock: globalThis,
|
|
9962
|
+
environment
|
|
9963
|
+
}).catch(unavailable);
|
|
9964
|
+
return new _DockerEngine(docker, commandTimeout);
|
|
9965
|
+
}
|
|
9966
|
+
/** A sandbox container handle for a container of this engine. */
|
|
9967
|
+
async container(name, container, info) {
|
|
9968
|
+
const layout = fileLayout(info.Config, info.HostConfig);
|
|
9969
|
+
return new DockerContainer(
|
|
9970
|
+
name,
|
|
9971
|
+
container,
|
|
9972
|
+
layout,
|
|
9973
|
+
await resolveOwner(container, layout.user),
|
|
9974
|
+
this.#commandTimeout
|
|
9975
|
+
);
|
|
9976
|
+
}
|
|
9977
|
+
async attach(name, image) {
|
|
9978
|
+
const found = await this.docker.containers.find(name).catch(unavailable);
|
|
9979
|
+
if (!found) return void 0;
|
|
9980
|
+
const info = await found.inspect();
|
|
9981
|
+
if (info.State?.Status !== "running") {
|
|
9982
|
+
await startContainer(found, image);
|
|
9594
9983
|
}
|
|
9595
|
-
|
|
9596
|
-
|
|
9984
|
+
return this.container(name, found, info);
|
|
9985
|
+
}
|
|
9986
|
+
async run(image, name, opts, workdir) {
|
|
9987
|
+
const started = await this.#createAndStart(image, name, opts, workdir);
|
|
9988
|
+
if (!started) return { created: false };
|
|
9989
|
+
try {
|
|
9990
|
+
return {
|
|
9991
|
+
created: true,
|
|
9992
|
+
// The image's own USER and WORKDIR are in the inspect, not the body.
|
|
9993
|
+
container: await this.container(name, started, await started.inspect())
|
|
9994
|
+
};
|
|
9995
|
+
} catch (error) {
|
|
9996
|
+
await started[Symbol.asyncDispose]();
|
|
9997
|
+
throw error;
|
|
9597
9998
|
}
|
|
9598
|
-
|
|
9599
|
-
|
|
9999
|
+
}
|
|
10000
|
+
/** Creates and starts the container; `undefined` when another caller has the name. */
|
|
10001
|
+
async #createAndStart(image, name, opts, workdir) {
|
|
10002
|
+
try {
|
|
10003
|
+
const body = containerCreateRequest(image, opts, workdir);
|
|
10004
|
+
const create = () => this.docker.containers.createOrGet(body, {
|
|
10005
|
+
name,
|
|
10006
|
+
platform: opts.platform
|
|
10007
|
+
});
|
|
10008
|
+
const result = await create().catch(async (error) => {
|
|
10009
|
+
if (!(error instanceof ImageNotFoundError)) throw error;
|
|
10010
|
+
await this.docker.images.pull(image, { platform: opts.platform });
|
|
10011
|
+
return create();
|
|
10012
|
+
});
|
|
10013
|
+
if (!result.created) return void 0;
|
|
10014
|
+
try {
|
|
10015
|
+
await result.container.start();
|
|
10016
|
+
} catch (error) {
|
|
10017
|
+
await result.container[Symbol.asyncDispose]();
|
|
10018
|
+
throw error;
|
|
10019
|
+
}
|
|
10020
|
+
return result.container;
|
|
10021
|
+
} catch (error) {
|
|
10022
|
+
throw this.#runError(error, image, opts.volumes ?? []);
|
|
9600
10023
|
}
|
|
9601
|
-
|
|
9602
|
-
|
|
9603
|
-
|
|
9604
|
-
|
|
9605
|
-
args.push(...opts.command);
|
|
10024
|
+
}
|
|
10025
|
+
#runError(error, image, volumes) {
|
|
10026
|
+
if (error instanceof ConnectionFailedError) {
|
|
10027
|
+
return new DockerNotAvailableError();
|
|
9606
10028
|
}
|
|
9607
|
-
|
|
9608
|
-
|
|
9609
|
-
|
|
9610
|
-
|
|
9611
|
-
|
|
9612
|
-
|
|
9613
|
-
|
|
9614
|
-
|
|
9615
|
-
|
|
9616
|
-
|
|
9617
|
-
throw new DockerSandboxError(
|
|
9618
|
-
`Invalid environment variable key: "${key}"`
|
|
9619
|
-
);
|
|
9620
|
-
}
|
|
9621
|
-
flags.push("-e", `${key}=${value}`);
|
|
10029
|
+
if (error instanceof BindSourceNotFoundError) {
|
|
10030
|
+
const volume = volumes.find(
|
|
10031
|
+
(candidate) => candidate.type === "bind" && isBindSource(error.source, candidate.hostPath)
|
|
10032
|
+
);
|
|
10033
|
+
if (volume) {
|
|
10034
|
+
return new VolumePathError(
|
|
10035
|
+
error.source,
|
|
10036
|
+
volume.containerPath,
|
|
10037
|
+
"hostPath does not exist on host"
|
|
10038
|
+
);
|
|
9622
10039
|
}
|
|
9623
10040
|
}
|
|
9624
|
-
return
|
|
9625
|
-
|
|
9626
|
-
|
|
9627
|
-
|
|
9628
|
-
|
|
9629
|
-
|
|
9630
|
-
|
|
9631
|
-
|
|
9632
|
-
|
|
9633
|
-
|
|
9634
|
-
|
|
9635
|
-
|
|
9636
|
-
|
|
9637
|
-
|
|
9638
|
-
|
|
9639
|
-
|
|
9640
|
-
|
|
9641
|
-
args.push("--label", `${key}=${value}`);
|
|
9642
|
-
if (volume.driver) {
|
|
9643
|
-
args.push("--driver", volume.driver);
|
|
9644
|
-
}
|
|
9645
|
-
for (const [key, value] of Object.entries(volume.driverOptions ?? {})) {
|
|
9646
|
-
args.push("--opt", `${key}=${value}`);
|
|
10041
|
+
return new ContainerCreationError(
|
|
10042
|
+
error instanceof Error ? error.message : String(error),
|
|
10043
|
+
image,
|
|
10044
|
+
error instanceof Error ? error : void 0
|
|
10045
|
+
);
|
|
10046
|
+
}
|
|
10047
|
+
async volumeExists(name) {
|
|
10048
|
+
try {
|
|
10049
|
+
return await this.docker.volumes.find(name) !== void 0;
|
|
10050
|
+
} catch (error) {
|
|
10051
|
+
if (error instanceof ConnectionFailedError) {
|
|
10052
|
+
throw new DockerNotAvailableError();
|
|
10053
|
+
}
|
|
10054
|
+
throw new VolumeInspectError(
|
|
10055
|
+
name,
|
|
10056
|
+
error instanceof Error ? error.message : String(error)
|
|
10057
|
+
);
|
|
9647
10058
|
}
|
|
9648
|
-
|
|
9649
|
-
|
|
9650
|
-
|
|
9651
|
-
|
|
9652
|
-
|
|
9653
|
-
|
|
10059
|
+
}
|
|
10060
|
+
async createVolume(volume, opts) {
|
|
10061
|
+
try {
|
|
10062
|
+
await this.docker.volumes.create({
|
|
10063
|
+
Name: volume.name,
|
|
10064
|
+
Labels: opts.labels ?? {},
|
|
10065
|
+
...volume.driver ? { Driver: volume.driver } : {},
|
|
10066
|
+
DriverOpts: volume.driverOptions ?? {}
|
|
10067
|
+
});
|
|
10068
|
+
} catch (error) {
|
|
10069
|
+
if (error instanceof ConnectionFailedError) {
|
|
10070
|
+
throw new DockerNotAvailableError();
|
|
10071
|
+
}
|
|
10072
|
+
throw new VolumeCreateError(
|
|
10073
|
+
volume.name,
|
|
10074
|
+
error instanceof NameConflictError ? "managed volume already exists" : error instanceof Error ? error.message : String(error)
|
|
10075
|
+
);
|
|
9654
10076
|
}
|
|
9655
|
-
|
|
9656
|
-
},
|
|
10077
|
+
}
|
|
9657
10078
|
async removeVolume(name) {
|
|
9658
10079
|
const deadline = performance.now() + 3e4;
|
|
9659
10080
|
while (true) {
|
|
9660
10081
|
try {
|
|
9661
|
-
await
|
|
10082
|
+
await this.docker.volumes.find(name).then((volume) => volume?.remove());
|
|
9662
10083
|
return;
|
|
9663
10084
|
} catch (error) {
|
|
9664
|
-
if (
|
|
9665
|
-
|
|
10085
|
+
if (error instanceof VolumeInUseError && performance.now() < deadline) {
|
|
10086
|
+
await delay(25);
|
|
10087
|
+
continue;
|
|
9666
10088
|
}
|
|
9667
|
-
|
|
10089
|
+
if (error instanceof ConnectionFailedError) {
|
|
10090
|
+
throw new DockerNotAvailableError();
|
|
10091
|
+
}
|
|
10092
|
+
throw new VolumeRemoveError(
|
|
10093
|
+
name,
|
|
10094
|
+
error instanceof Error ? error.message : String(error)
|
|
10095
|
+
);
|
|
9668
10096
|
}
|
|
9669
10097
|
}
|
|
9670
|
-
}
|
|
9671
|
-
isServiceDown(message2) {
|
|
9672
|
-
return message2.includes("Cannot connect") || message2.includes("docker daemon");
|
|
9673
|
-
},
|
|
9674
|
-
isMissingContainer(message2) {
|
|
9675
|
-
return message2.toLowerCase().includes("no such container");
|
|
9676
|
-
},
|
|
9677
|
-
isMissingVolume(message2) {
|
|
9678
|
-
return /no such volume|volume \S+ not found/i.test(message2);
|
|
9679
|
-
},
|
|
9680
|
-
isNameConflict(message2) {
|
|
9681
|
-
return message2.toLowerCase().includes("is already in use by container");
|
|
9682
|
-
},
|
|
10098
|
+
}
|
|
9683
10099
|
async ensureWorkdir() {
|
|
9684
|
-
}
|
|
9685
|
-
defaultImage: "bash:5.3-alpine3.24",
|
|
9686
|
-
createInstallerContext: (containerId, image) => createInstallerContext(
|
|
9687
|
-
{ binary: "docker", SandboxError: DockerSandboxError },
|
|
9688
|
-
containerId,
|
|
9689
|
-
image
|
|
9690
|
-
),
|
|
10100
|
+
}
|
|
9691
10101
|
async imageExists(tag) {
|
|
9692
|
-
|
|
9693
|
-
|
|
9694
|
-
return true;
|
|
9695
|
-
} catch {
|
|
9696
|
-
return false;
|
|
9697
|
-
}
|
|
9698
|
-
},
|
|
10102
|
+
return await this.docker.images.inspect(tag) !== void 0;
|
|
10103
|
+
}
|
|
9699
10104
|
async buildImage(spec) {
|
|
9700
10105
|
const inline = spec.dockerfile.includes("\n");
|
|
9701
10106
|
const args = [
|
|
@@ -9710,334 +10115,116 @@ var dockerEngine = {
|
|
|
9710
10115
|
await runDockerBuild(
|
|
9711
10116
|
args,
|
|
9712
10117
|
inline ? spec.dockerfile : void 0,
|
|
9713
|
-
spec.showBuildLogs
|
|
9714
|
-
|
|
9715
|
-
},
|
|
9716
|
-
errors: {
|
|
9717
|
-
serviceNotAvailable: () => new DockerNotAvailableError(),
|
|
9718
|
-
creation: (message2, image, cause) => new ContainerCreationError(message2, image, cause),
|
|
9719
|
-
generic: (message2, containerId) => new DockerSandboxError(message2, containerId),
|
|
9720
|
-
volumePath: (source, containerPath, reason) => new VolumePathError(source, containerPath, reason),
|
|
9721
|
-
volumeInspect: (name, reason) => new VolumeInspectError(name, reason),
|
|
9722
|
-
volumeCreate: (name, reason) => new VolumeCreateError(name, reason),
|
|
9723
|
-
volumeRemove: (name, reason) => new VolumeRemoveError(name, reason)
|
|
9724
|
-
}
|
|
9725
|
-
};
|
|
9726
|
-
function validateEnvKey2(key) {
|
|
9727
|
-
if (key.length === 0 || key.includes("=")) {
|
|
9728
|
-
throw new DockerSandboxError(`Invalid environment variable key: "${key}"`);
|
|
9729
|
-
}
|
|
9730
|
-
}
|
|
9731
|
-
function buildDockerExecFlags(options) {
|
|
9732
|
-
const flags = [];
|
|
9733
|
-
if (options?.cwd) {
|
|
9734
|
-
flags.push("-w", options.cwd);
|
|
9735
|
-
}
|
|
9736
|
-
if (options?.env) {
|
|
9737
|
-
for (const [key, value] of Object.entries(options.env)) {
|
|
9738
|
-
validateEnvKey2(key);
|
|
9739
|
-
flags.push("-e", `${key}=${value}`);
|
|
9740
|
-
}
|
|
9741
|
-
}
|
|
9742
|
-
return flags;
|
|
9743
|
-
}
|
|
9744
|
-
function managedDockerCommand(command, controlPath, commandTimeout) {
|
|
9745
|
-
return [
|
|
9746
|
-
"set -m",
|
|
9747
|
-
`control=${shellQuote(controlPath)}`,
|
|
9748
|
-
': > "$control" || exit 1',
|
|
9749
|
-
"timer=",
|
|
9750
|
-
`trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
|
|
9751
|
-
`bash -lc ${shellQuote(command)} &`,
|
|
9752
|
-
"pid=$!",
|
|
9753
|
-
`printf '%s\\n' "$pid" > "$control"`,
|
|
9754
|
-
...commandTimeout ? [
|
|
9755
|
-
// Keep the deadline on the engine host: SSH setup/round trips must not
|
|
9756
|
-
// let the command run past its execution budget.
|
|
9757
|
-
"(",
|
|
9758
|
-
`sleep ${commandTimeout / 1e3} &`,
|
|
9759
|
-
"alarm=$!",
|
|
9760
|
-
`trap 'kill "$alarm" 2>/dev/null || :; wait "$alarm" 2>/dev/null || :; exit 0' TERM`,
|
|
9761
|
-
'wait "$alarm" || exit',
|
|
9762
|
-
'if kill -0 -- "-$pid" 2>/dev/null; then : > "$control.timeout"; kill -KILL -- "-$pid" 2>/dev/null || :; fi',
|
|
9763
|
-
") &",
|
|
9764
|
-
"timer=$!"
|
|
9765
|
-
] : [],
|
|
9766
|
-
'wait "$pid"',
|
|
9767
|
-
"status=$?",
|
|
9768
|
-
'[ ! -e "$control.timeout" ] || exit 124',
|
|
9769
|
-
'exit "$status"'
|
|
9770
|
-
].join("\n");
|
|
9771
|
-
}
|
|
9772
|
-
async function waitForDockerExecPid(execArgs, controlPath, localExit) {
|
|
9773
|
-
const exited = localExit.then(
|
|
9774
|
-
() => true,
|
|
9775
|
-
() => true
|
|
9776
|
-
);
|
|
9777
|
-
const readPid = `if IFS= read -r pid < ${shellQuote(controlPath)}; then printf '%s' "$pid"; fi`;
|
|
9778
|
-
while (true) {
|
|
9779
|
-
const result = await spawn5("docker", execArgs(readPid));
|
|
9780
|
-
if (result.stdout) return Number(result.stdout);
|
|
9781
|
-
if (await Promise.race([exited, delay2(10).then(() => false)])) {
|
|
9782
|
-
return void 0;
|
|
9783
|
-
}
|
|
9784
|
-
}
|
|
9785
|
-
}
|
|
9786
|
-
async function terminateDockerExec(execArgs, controlPath, localExit) {
|
|
9787
|
-
const pid = await waitForDockerExecPid(execArgs, controlPath, localExit);
|
|
9788
|
-
if (pid === void 0) return false;
|
|
9789
|
-
const result = await spawn5(
|
|
9790
|
-
"docker",
|
|
9791
|
-
execArgs(
|
|
9792
|
-
[
|
|
9793
|
-
`pid=${pid}`,
|
|
9794
|
-
`IFS= read -r control_pid < ${shellQuote(controlPath)} || exit 0`,
|
|
9795
|
-
'[ "$control_pid" = "$pid" ] || exit 0',
|
|
9796
|
-
'kill -KILL -- "-$pid" 2>/dev/null || exit 0',
|
|
9797
|
-
"group_alive() {",
|
|
9798
|
-
" local stat rest state pgrp",
|
|
9799
|
-
" for stat_path in /proc/[0-9]*/stat; do",
|
|
9800
|
-
' IFS= read -r stat < "$stat_path" || continue',
|
|
9801
|
-
" rest=${stat##*) }",
|
|
9802
|
-
' read -r state _ pgrp _ <<< "$rest"',
|
|
9803
|
-
' if [ "$pgrp" = "$pid" ] && [ "$state" != Z ]; then return 0; fi',
|
|
9804
|
-
" done",
|
|
9805
|
-
" return 1",
|
|
9806
|
-
"}",
|
|
9807
|
-
"while group_alive; do sleep 0.01; done",
|
|
9808
|
-
"printf terminated"
|
|
9809
|
-
].join("\n")
|
|
9810
|
-
)
|
|
9811
|
-
);
|
|
9812
|
-
return result.stdout === "terminated";
|
|
9813
|
-
}
|
|
9814
|
-
function spawnDockerProcess(execArgs, command, options = {}, commandTimeout) {
|
|
9815
|
-
if (!commandTimeout && options.signal === void 0) {
|
|
9816
|
-
return toSandboxProcess(
|
|
9817
|
-
childSpawn3("docker", execArgs(command, options)),
|
|
9818
|
-
void 0
|
|
9819
|
-
);
|
|
9820
|
-
}
|
|
9821
|
-
const controlPath = `/dev/shm/deepagents-exec-${randomUUID2()}.pid`;
|
|
9822
|
-
const localProcess = toSandboxProcess(
|
|
9823
|
-
childSpawn3(
|
|
9824
|
-
"docker",
|
|
9825
|
-
execArgs(
|
|
9826
|
-
managedDockerCommand(command, controlPath, commandTimeout),
|
|
9827
|
-
options
|
|
9828
|
-
)
|
|
9829
|
-
),
|
|
9830
|
-
void 0
|
|
9831
|
-
);
|
|
9832
|
-
let termination;
|
|
9833
|
-
const onAbort = () => {
|
|
9834
|
-
termination ??= terminateDockerExec(
|
|
9835
|
-
execArgs,
|
|
9836
|
-
controlPath,
|
|
9837
|
-
localProcess.exit
|
|
9838
|
-
);
|
|
9839
|
-
void termination.catch(() => {
|
|
9840
|
-
});
|
|
9841
|
-
};
|
|
9842
|
-
if (options.signal?.aborted) onAbort();
|
|
9843
|
-
else options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
9844
|
-
return {
|
|
9845
|
-
stdout: localProcess.stdout,
|
|
9846
|
-
stderr: localProcess.stderr,
|
|
9847
|
-
exit: localProcess.exit.then(async (info) => {
|
|
9848
|
-
const activeTermination = termination;
|
|
9849
|
-
if (!activeTermination || !await activeTermination) {
|
|
9850
|
-
return info;
|
|
9851
|
-
}
|
|
9852
|
-
return { code: null, signal: "SIGKILL", success: false };
|
|
9853
|
-
}).finally(() => {
|
|
9854
|
-
options.signal?.removeEventListener("abort", onAbort);
|
|
9855
|
-
})
|
|
9856
|
-
};
|
|
9857
|
-
}
|
|
9858
|
-
async function executeDockerCommand(execArgs, command, options = {}, commandTimeout) {
|
|
9859
|
-
if (!commandTimeout && options.signal === void 0) {
|
|
9860
|
-
try {
|
|
9861
|
-
const result2 = await spawn5("docker", execArgs(command));
|
|
9862
|
-
return { stdout: result2.stdout, stderr: result2.stderr, exitCode: 0 };
|
|
9863
|
-
} catch (error) {
|
|
9864
|
-
return commandResultFrom(error);
|
|
9865
|
-
}
|
|
9866
|
-
}
|
|
9867
|
-
const process2 = spawnDockerProcess(
|
|
9868
|
-
execArgs,
|
|
9869
|
-
command,
|
|
9870
|
-
{ signal: options.signal },
|
|
9871
|
-
commandTimeout
|
|
9872
|
-
);
|
|
9873
|
-
const [stdout, stderr, info] = await Promise.all([
|
|
9874
|
-
new Response(process2.stdout).text(),
|
|
9875
|
-
new Response(process2.stderr).text(),
|
|
9876
|
-
process2.exit
|
|
9877
|
-
]);
|
|
9878
|
-
const result = {
|
|
9879
|
-
stdout: stdout.replace(/\r?\n$/, ""),
|
|
9880
|
-
stderr: stderr.replace(/\r?\n$/, "")
|
|
9881
|
-
};
|
|
9882
|
-
if (info.signal === "SIGKILL") {
|
|
9883
|
-
return {
|
|
9884
|
-
...result,
|
|
9885
|
-
stderr: result.stderr || "Command aborted",
|
|
9886
|
-
exitCode: 1
|
|
9887
|
-
};
|
|
9888
|
-
}
|
|
9889
|
-
return { ...result, exitCode: info.code ?? 1 };
|
|
9890
|
-
}
|
|
9891
|
-
var DockerRuntimeStrategy = class extends RuntimeStrategy {
|
|
9892
|
-
exec(command, options) {
|
|
9893
|
-
return executeDockerCommand(
|
|
9894
|
-
(value, spawnOptions) => this.engine.execArgs(this.context.containerId, value, spawnOptions),
|
|
9895
|
-
command,
|
|
9896
|
-
options,
|
|
9897
|
-
this.opts.commandTimeout
|
|
9898
|
-
);
|
|
9899
|
-
}
|
|
9900
|
-
spawnProcess(command, options) {
|
|
9901
|
-
return spawnDockerProcess(
|
|
9902
|
-
(value, spawnOptions) => this.engine.execArgs(this.context.containerId, value, spawnOptions),
|
|
9903
|
-
command,
|
|
9904
|
-
options,
|
|
9905
|
-
this.opts.commandTimeout
|
|
9906
|
-
);
|
|
9907
|
-
}
|
|
9908
|
-
};
|
|
9909
|
-
var DockerContainerfileStrategy = class extends ContainerfileStrategy {
|
|
9910
|
-
exec(command, options) {
|
|
9911
|
-
return executeDockerCommand(
|
|
9912
|
-
(value, spawnOptions) => this.engine.execArgs(this.context.containerId, value, spawnOptions),
|
|
9913
|
-
command,
|
|
9914
|
-
options,
|
|
9915
|
-
this.opts.commandTimeout
|
|
10118
|
+
spec.showBuildLogs,
|
|
10119
|
+
this.cliEnv
|
|
9916
10120
|
);
|
|
9917
10121
|
}
|
|
9918
|
-
|
|
9919
|
-
return
|
|
9920
|
-
(value, spawnOptions) => this.engine.execArgs(this.context.containerId, value, spawnOptions),
|
|
9921
|
-
command,
|
|
9922
|
-
options,
|
|
9923
|
-
this.opts.commandTimeout
|
|
9924
|
-
);
|
|
10122
|
+
dispose() {
|
|
10123
|
+
return this.docker[Symbol.asyncDispose]();
|
|
9925
10124
|
}
|
|
9926
10125
|
};
|
|
9927
10126
|
var ComposeStrategy = class extends ContainerSandboxStrategy {
|
|
9928
10127
|
projectName;
|
|
9929
10128
|
composeFile;
|
|
9930
10129
|
service;
|
|
9931
|
-
|
|
9932
|
-
constructor(args) {
|
|
9933
|
-
super({ resources: args.resources },
|
|
10130
|
+
dockerEngine;
|
|
10131
|
+
constructor(args, engine) {
|
|
10132
|
+
super({ resources: args.resources }, engine);
|
|
10133
|
+
this.dockerEngine = engine;
|
|
9934
10134
|
this.composeFile = args.compose;
|
|
9935
10135
|
this.service = args.service;
|
|
9936
|
-
this.
|
|
9937
|
-
this.projectName = this.computeProjectName();
|
|
10136
|
+
this.projectName = `sandbox-${hash("sha256", readFileSync2(this.composeFile, "utf-8")).slice(0, 8)}`;
|
|
9938
10137
|
}
|
|
9939
|
-
|
|
9940
|
-
|
|
9941
|
-
|
|
9942
|
-
|
|
10138
|
+
compose(command) {
|
|
10139
|
+
return spawn3(
|
|
10140
|
+
"docker",
|
|
10141
|
+
["compose", "-f", this.composeFile, "-p", this.projectName, ...command],
|
|
10142
|
+
{ env: this.dockerEngine.cliEnv }
|
|
10143
|
+
);
|
|
9943
10144
|
}
|
|
9944
10145
|
async getImage() {
|
|
9945
10146
|
return "";
|
|
9946
10147
|
}
|
|
9947
|
-
async
|
|
10148
|
+
async acquireContainer() {
|
|
9948
10149
|
try {
|
|
9949
|
-
await
|
|
9950
|
-
"compose",
|
|
9951
|
-
"-f",
|
|
9952
|
-
this.composeFile,
|
|
9953
|
-
"-p",
|
|
9954
|
-
this.projectName,
|
|
9955
|
-
"up",
|
|
9956
|
-
"-d"
|
|
9957
|
-
]);
|
|
10150
|
+
await this.compose(["up", "-d"]);
|
|
9958
10151
|
} catch (error) {
|
|
9959
|
-
|
|
9960
|
-
|
|
9961
|
-
|
|
10152
|
+
throw new ComposeStartError(
|
|
10153
|
+
this.composeFile,
|
|
10154
|
+
error instanceof SubprocessError4 && error.stderr || (error instanceof Error ? error.message : String(error))
|
|
10155
|
+
);
|
|
10156
|
+
}
|
|
10157
|
+
const { containers } = this.dockerEngine.docker;
|
|
10158
|
+
const [summary] = await containers.list({
|
|
10159
|
+
filters: {
|
|
10160
|
+
label: [
|
|
10161
|
+
`com.docker.compose.project=${this.projectName}`,
|
|
10162
|
+
`com.docker.compose.service=${this.service}`
|
|
10163
|
+
]
|
|
9962
10164
|
}
|
|
10165
|
+
});
|
|
10166
|
+
const container = summary && await containers.find(summary.Id);
|
|
10167
|
+
if (!container) {
|
|
10168
|
+
await this.compose(["down"]).catch(() => {
|
|
10169
|
+
});
|
|
9963
10170
|
throw new ComposeStartError(
|
|
9964
10171
|
this.composeFile,
|
|
9965
|
-
|
|
10172
|
+
`service "${this.service}" has no running container`
|
|
9966
10173
|
);
|
|
9967
10174
|
}
|
|
9968
|
-
|
|
9969
|
-
|
|
9970
|
-
|
|
10175
|
+
return {
|
|
10176
|
+
container: await this.dockerEngine.container(
|
|
10177
|
+
this.projectName,
|
|
10178
|
+
container,
|
|
10179
|
+
await container.inspect()
|
|
10180
|
+
),
|
|
10181
|
+
attached: false
|
|
10182
|
+
};
|
|
9971
10183
|
}
|
|
9972
10184
|
async configure() {
|
|
9973
10185
|
}
|
|
9974
|
-
async
|
|
9975
|
-
|
|
9976
|
-
|
|
9977
|
-
command,
|
|
9978
|
-
options,
|
|
9979
|
-
this.commandTimeout
|
|
9980
|
-
);
|
|
9981
|
-
}
|
|
9982
|
-
spawnProcess(command, options) {
|
|
9983
|
-
return spawnDockerProcess(
|
|
9984
|
-
(value, spawnOptions) => this.execArgs(value, spawnOptions),
|
|
9985
|
-
command,
|
|
9986
|
-
options,
|
|
9987
|
-
this.commandTimeout
|
|
9988
|
-
);
|
|
9989
|
-
}
|
|
9990
|
-
execArgs(command, options) {
|
|
9991
|
-
return [
|
|
9992
|
-
"compose",
|
|
9993
|
-
"-f",
|
|
9994
|
-
this.composeFile,
|
|
9995
|
-
"-p",
|
|
9996
|
-
this.projectName,
|
|
9997
|
-
"exec",
|
|
9998
|
-
"-T",
|
|
9999
|
-
...buildDockerExecFlags(options),
|
|
10000
|
-
this.service,
|
|
10001
|
-
"bash",
|
|
10002
|
-
"-lc",
|
|
10003
|
-
command
|
|
10004
|
-
];
|
|
10005
|
-
}
|
|
10006
|
-
async stopContainer(_containerId) {
|
|
10007
|
-
try {
|
|
10008
|
-
await spawn5("docker", [
|
|
10009
|
-
"compose",
|
|
10010
|
-
"-f",
|
|
10011
|
-
this.composeFile,
|
|
10012
|
-
"-p",
|
|
10013
|
-
this.projectName,
|
|
10014
|
-
"down"
|
|
10015
|
-
]);
|
|
10016
|
-
} catch {
|
|
10017
|
-
}
|
|
10186
|
+
async release() {
|
|
10187
|
+
await this.compose(["down"]).catch(() => {
|
|
10188
|
+
});
|
|
10018
10189
|
}
|
|
10019
10190
|
};
|
|
10020
10191
|
async function createDockerSandbox(options = {}) {
|
|
10021
|
-
if (isComposeOptions(options)) {
|
|
10022
|
-
|
|
10023
|
-
compose: options.compose,
|
|
10024
|
-
service: options.service,
|
|
10025
|
-
resources: options.resources,
|
|
10026
|
-
commandTimeout: options.commandTimeout
|
|
10027
|
-
}).create();
|
|
10192
|
+
if (!isComposeOptions(options)) {
|
|
10193
|
+
validateSandboxOptions(options, dockerErrors);
|
|
10028
10194
|
}
|
|
10029
|
-
|
|
10030
|
-
|
|
10031
|
-
|
|
10032
|
-
|
|
10033
|
-
|
|
10034
|
-
|
|
10035
|
-
|
|
10195
|
+
const engine = await DockerEngine.connect(
|
|
10196
|
+
options.environment ?? process.env,
|
|
10197
|
+
options.commandTimeout
|
|
10198
|
+
);
|
|
10199
|
+
let strategy;
|
|
10200
|
+
try {
|
|
10201
|
+
if (isComposeOptions(options)) {
|
|
10202
|
+
strategy = new ComposeStrategy(
|
|
10203
|
+
{
|
|
10204
|
+
compose: options.compose,
|
|
10205
|
+
service: options.service,
|
|
10206
|
+
resources: options.resources
|
|
10207
|
+
},
|
|
10208
|
+
engine
|
|
10209
|
+
);
|
|
10210
|
+
} else if (isDockerfileOptions(options)) {
|
|
10211
|
+
strategy = new ContainerfileStrategy(options, engine, {
|
|
10212
|
+
dockerfile: options.dockerfile,
|
|
10213
|
+
context: options.context ?? ".",
|
|
10214
|
+
showBuildLogs: options.showBuildLogs ?? false,
|
|
10215
|
+
identity: options.platform
|
|
10216
|
+
});
|
|
10217
|
+
} else {
|
|
10218
|
+
strategy = new RuntimeStrategy(options, engine, {
|
|
10219
|
+
image: options.image ?? engine.defaultImage,
|
|
10220
|
+
installers: options.installers ?? []
|
|
10221
|
+
});
|
|
10222
|
+
}
|
|
10223
|
+
} catch (error) {
|
|
10224
|
+
await engine.dispose();
|
|
10225
|
+
throw error;
|
|
10036
10226
|
}
|
|
10037
|
-
return
|
|
10038
|
-
image: options.image ?? dockerEngine.defaultImage,
|
|
10039
|
-
installers: options.installers ?? []
|
|
10040
|
-
}).create();
|
|
10227
|
+
return strategy.create();
|
|
10041
10228
|
}
|
|
10042
10229
|
async function useSandbox(options, fn) {
|
|
10043
10230
|
const sandbox = await createDockerSandbox(options);
|
|
@@ -10049,12 +10236,12 @@ async function useSandbox(options, fn) {
|
|
|
10049
10236
|
}
|
|
10050
10237
|
|
|
10051
10238
|
// packages/context/src/lib/sandbox/strace/file-changes.ts
|
|
10052
|
-
import { randomUUID as
|
|
10053
|
-
import { posix as
|
|
10239
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
10240
|
+
import { posix as posix4 } from "node:path";
|
|
10054
10241
|
|
|
10055
10242
|
// packages/context/src/lib/sandbox/strace/index.ts
|
|
10056
|
-
import
|
|
10057
|
-
import { posix as
|
|
10243
|
+
import spawn4, { SubprocessError as SubprocessError5 } from "nano-spawn";
|
|
10244
|
+
import { posix as posix3 } from "node:path";
|
|
10058
10245
|
var STRACE_FLAGS = "-f -y -qq -e trace=%file,write,pwrite64,writev";
|
|
10059
10246
|
function buildStraceCommand(command, traceFile, traceDir) {
|
|
10060
10247
|
return `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- bash -lc ${shellQuote(command)}`;
|
|
@@ -10172,14 +10359,14 @@ function openFlags(args) {
|
|
|
10172
10359
|
return args.match(/\bO_[A-Z_]+(?:\|O_[A-Z_]+)*/)?.[0] ?? "";
|
|
10173
10360
|
}
|
|
10174
10361
|
function matchesGlobs(path6, include, exclude) {
|
|
10175
|
-
return include.some((glob) =>
|
|
10362
|
+
return include.some((glob) => posix3.matchesGlob(path6, glob)) && !exclude?.some((glob) => posix3.matchesGlob(path6, glob));
|
|
10176
10363
|
}
|
|
10177
10364
|
function parseStraceTrace(raw, options) {
|
|
10178
10365
|
const { include, exclude, traceDir, traceFile } = options;
|
|
10179
10366
|
const now = Date.now();
|
|
10180
10367
|
const state = /* @__PURE__ */ new Map();
|
|
10181
10368
|
const renames = [];
|
|
10182
|
-
const resolve3 = (dir, p) =>
|
|
10369
|
+
const resolve3 = (dir, p) => posix3.normalize(p.startsWith("/") ? p : posix3.join(dir, p));
|
|
10183
10370
|
const write = (path6) => {
|
|
10184
10371
|
state.set(path6, "write");
|
|
10185
10372
|
};
|
|
@@ -10224,7 +10411,7 @@ function parseStraceTrace(raw, options) {
|
|
|
10224
10411
|
}
|
|
10225
10412
|
if (WRITE_SYSCALLS.has(syscall)) {
|
|
10226
10413
|
const p = fdPath(args);
|
|
10227
|
-
if (p && Number(call.retval) > 0) write(
|
|
10414
|
+
if (p && Number(call.retval) > 0) write(posix3.normalize(p));
|
|
10228
10415
|
continue;
|
|
10229
10416
|
}
|
|
10230
10417
|
if (TRUNCATE_SYSCALLS.has(syscall)) {
|
|
@@ -10307,8 +10494,8 @@ async function withStraceFileChanges(sandbox, options) {
|
|
|
10307
10494
|
};
|
|
10308
10495
|
const decorated = {
|
|
10309
10496
|
async executeCommand(command, execOptions) {
|
|
10310
|
-
const traceFile = `${traceDir}/${
|
|
10311
|
-
const sentinel = `__dat_trace_${
|
|
10497
|
+
const traceFile = `${traceDir}/${randomUUID4()}.strace`;
|
|
10498
|
+
const sentinel = `__dat_trace_${randomUUID4()}__`;
|
|
10312
10499
|
const wrapped = buildTracedCommand(
|
|
10313
10500
|
command,
|
|
10314
10501
|
traceFile,
|
|
@@ -10359,7 +10546,7 @@ async function withStraceFileChanges(sandbox, options) {
|
|
|
10359
10546
|
writeFiles: async (files) => {
|
|
10360
10547
|
await innerWriteFiles(files);
|
|
10361
10548
|
const now = Date.now();
|
|
10362
|
-
const changes = files.map((f) =>
|
|
10549
|
+
const changes = files.map((f) => posix4.normalize(f.path)).filter((path6) => matchesGlobs(path6, include, exclude)).map((path6) => ({ op: "write", path: path6, timestamp: now }));
|
|
10363
10550
|
if (changes.length) await onFileChanges?.(changes);
|
|
10364
10551
|
},
|
|
10365
10552
|
dispose: async () => {
|
|
@@ -10373,9 +10560,9 @@ async function withStraceFileChanges(sandbox, options) {
|
|
|
10373
10560
|
};
|
|
10374
10561
|
if (sandbox.spawn) {
|
|
10375
10562
|
const innerSpawn = sandbox.spawn.bind(sandbox);
|
|
10376
|
-
decorated.spawn = (command, spawnOptions) => {
|
|
10377
|
-
const traceFile = `${traceDir}/${
|
|
10378
|
-
const child = innerSpawn(
|
|
10563
|
+
decorated.spawn = async (command, spawnOptions) => {
|
|
10564
|
+
const traceFile = `${traceDir}/${randomUUID4()}.strace`;
|
|
10565
|
+
const child = await innerSpawn(
|
|
10379
10566
|
buildStraceCommand(command, traceFile, traceDir),
|
|
10380
10567
|
spawnOptions
|
|
10381
10568
|
);
|
|
@@ -10404,7 +10591,7 @@ function gcs(options) {
|
|
|
10404
10591
|
}
|
|
10405
10592
|
|
|
10406
10593
|
// packages/context/src/lib/sandbox/installers/bin.ts
|
|
10407
|
-
import { basename, posix as
|
|
10594
|
+
import { basename, posix as posix5 } from "node:path";
|
|
10408
10595
|
var NOT_FOUND_EXIT = 11;
|
|
10409
10596
|
var CHMOD_FAILED_EXIT = 12;
|
|
10410
10597
|
var BinInstaller = class extends Installer {
|
|
@@ -10418,13 +10605,13 @@ var BinInstaller = class extends Installer {
|
|
|
10418
10605
|
this.binary = binary;
|
|
10419
10606
|
this.options = options;
|
|
10420
10607
|
this.#name = resolveName(binary, options);
|
|
10421
|
-
this.#target = options.target ??
|
|
10608
|
+
this.#target = options.target ?? posix5.join("/usr/local/bin", this.#name);
|
|
10422
10609
|
this.kind = `bin:${this.#name}`;
|
|
10423
10610
|
}
|
|
10424
10611
|
async install(ctx) {
|
|
10425
10612
|
const b = shellQuote(this.binary);
|
|
10426
10613
|
const t = shellQuote(this.#target);
|
|
10427
|
-
const dir = shellQuote(
|
|
10614
|
+
const dir = shellQuote(posix5.dirname(this.#target));
|
|
10428
10615
|
const result = await ctx.exec(
|
|
10429
10616
|
`test -f ${b} || { echo "binary not found at ${this.binary}" >&2; exit ${NOT_FOUND_EXIT}; }; if ! test -x ${b}; then chmod +x ${b} || exit ${CHMOD_FAILED_EXIT}; fi; mkdir -p ${dir} && ln -sf ${b} ${t}`
|
|
10430
10617
|
);
|
|
@@ -10689,7 +10876,7 @@ function formatVersion(version) {
|
|
|
10689
10876
|
}
|
|
10690
10877
|
|
|
10691
10878
|
// packages/context/src/lib/sandbox/microsandbox-sandbox.ts
|
|
10692
|
-
import { randomUUID as
|
|
10879
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
10693
10880
|
var MICROSANDBOX_DEFAULT_DESTINATION = "/workspace";
|
|
10694
10881
|
var MICROSANDBOX_DEFAULT_IMAGE = "bash:5.3-alpine3.24";
|
|
10695
10882
|
var MICROSANDBOX_MAX_NAME_BYTES = 128;
|
|
@@ -10726,7 +10913,7 @@ async function createMicrosandboxSandbox(options = {}) {
|
|
|
10726
10913
|
validateMicrosandboxOptions(options);
|
|
10727
10914
|
const sdk = await importMicrosandbox();
|
|
10728
10915
|
const ephemeral = options.name === void 0;
|
|
10729
|
-
const name = options.name ?? `deepagents-msb-${
|
|
10916
|
+
const name = options.name ?? `deepagents-msb-${randomUUID5()}`;
|
|
10730
10917
|
const workdir = options.workdir ?? MICROSANDBOX_DEFAULT_DESTINATION;
|
|
10731
10918
|
const sandboxBuilder = (replace) => {
|
|
10732
10919
|
let builder = sdk.Sandbox.builder(name).image(MICROSANDBOX_DEFAULT_IMAGE).patch((patch) => patch.mkdir(workdir));
|
|
@@ -10817,7 +11004,7 @@ function createMicrosandboxMethods(args) {
|
|
|
10817
11004
|
const { sdk, name, ephemeral, commandTimeout, reconnect } = args;
|
|
10818
11005
|
let vm = args.vm;
|
|
10819
11006
|
let reconnecting;
|
|
10820
|
-
const
|
|
11007
|
+
const run2 = async (operation) => {
|
|
10821
11008
|
try {
|
|
10822
11009
|
return await operation(vm);
|
|
10823
11010
|
} catch (error) {
|
|
@@ -10831,8 +11018,8 @@ function createMicrosandboxMethods(args) {
|
|
|
10831
11018
|
return operation(vm);
|
|
10832
11019
|
}
|
|
10833
11020
|
};
|
|
10834
|
-
const
|
|
10835
|
-
return spawnMicrosandboxProcess(sdk,
|
|
11021
|
+
const spawn5 = (command, options = {}) => {
|
|
11022
|
+
return spawnMicrosandboxProcess(sdk, run2, command, {
|
|
10836
11023
|
...options,
|
|
10837
11024
|
commandTimeout
|
|
10838
11025
|
});
|
|
@@ -10844,7 +11031,7 @@ function createMicrosandboxMethods(args) {
|
|
|
10844
11031
|
// in-process native binding, so an abandoned exec keeps the guest process
|
|
10845
11032
|
// and its libuv handle alive.
|
|
10846
11033
|
async executeCommand(command, options) {
|
|
10847
|
-
const proc =
|
|
11034
|
+
const proc = spawn5(command, { signal: options?.signal });
|
|
10848
11035
|
const [stdout, stderr, info] = await Promise.all([
|
|
10849
11036
|
readAllText(proc.stdout),
|
|
10850
11037
|
readAllText(proc.stderr),
|
|
@@ -10855,10 +11042,10 @@ function createMicrosandboxMethods(args) {
|
|
|
10855
11042
|
}
|
|
10856
11043
|
return { stdout, stderr, exitCode: info.code ?? 1 };
|
|
10857
11044
|
},
|
|
10858
|
-
spawn:
|
|
11045
|
+
spawn: async (command, options) => spawn5(command, options),
|
|
10859
11046
|
async readFile(path6, options) {
|
|
10860
11047
|
try {
|
|
10861
|
-
const bytes = await
|
|
11048
|
+
const bytes = await run2((vm2) => vm2.fs().read(path6));
|
|
10862
11049
|
return readFileContent(bytes, options);
|
|
10863
11050
|
} catch (error) {
|
|
10864
11051
|
throw new MicrosandboxCommandError(
|
|
@@ -10869,7 +11056,7 @@ function createMicrosandboxMethods(args) {
|
|
|
10869
11056
|
},
|
|
10870
11057
|
async exists(path6) {
|
|
10871
11058
|
try {
|
|
10872
|
-
return await
|
|
11059
|
+
return await run2((vm2) => vm2.fs().exists(path6));
|
|
10873
11060
|
} catch (error) {
|
|
10874
11061
|
throw new MicrosandboxCommandError(
|
|
10875
11062
|
`Failed to check "${path6}": ${toError2(error).message}`,
|
|
@@ -10879,7 +11066,7 @@ function createMicrosandboxMethods(args) {
|
|
|
10879
11066
|
},
|
|
10880
11067
|
async writeFiles(files) {
|
|
10881
11068
|
try {
|
|
10882
|
-
await
|
|
11069
|
+
await run2(async (vm2) => {
|
|
10883
11070
|
const fs = vm2.fs();
|
|
10884
11071
|
for (const dir of uniqueParentDirectories2(files.map((f) => f.path))) {
|
|
10885
11072
|
await fs.mkdir(dir);
|
|
@@ -10908,14 +11095,14 @@ function createMicrosandboxMethods(args) {
|
|
|
10908
11095
|
}
|
|
10909
11096
|
};
|
|
10910
11097
|
}
|
|
10911
|
-
function spawnMicrosandboxProcess(sdk,
|
|
11098
|
+
function spawnMicrosandboxProcess(sdk, run2, command, options) {
|
|
10912
11099
|
const stdout = createByteReadable();
|
|
10913
11100
|
const stderr = createByteReadable();
|
|
10914
|
-
const exit = pumpExecStream({ sdk, run, command, options, stdout, stderr });
|
|
11101
|
+
const exit = pumpExecStream({ sdk, run: run2, command, options, stdout, stderr });
|
|
10915
11102
|
return { stdout: stdout.stream, stderr: stderr.stream, exit };
|
|
10916
11103
|
}
|
|
10917
11104
|
async function pumpExecStream(args) {
|
|
10918
|
-
const { sdk, run, command, options, stdout, stderr } = args;
|
|
11105
|
+
const { sdk, run: run2, command, options, stdout, stderr } = args;
|
|
10919
11106
|
const { signal } = options;
|
|
10920
11107
|
let handle;
|
|
10921
11108
|
let aborted = signal?.aborted ?? false;
|
|
@@ -10933,7 +11120,7 @@ async function pumpExecStream(args) {
|
|
|
10933
11120
|
}
|
|
10934
11121
|
signal?.addEventListener("abort", abort, { once: true });
|
|
10935
11122
|
try {
|
|
10936
|
-
handle = await
|
|
11123
|
+
handle = await run2(
|
|
10937
11124
|
(vm) => vm.execStreamWith("bash", (builder) => {
|
|
10938
11125
|
builder.args(["-lc", command]).stdinNull();
|
|
10939
11126
|
if (options.cwd) builder.cwd(options.cwd);
|
|
@@ -10988,31 +11175,40 @@ async function pumpExecStream(args) {
|
|
|
10988
11175
|
}
|
|
10989
11176
|
}
|
|
10990
11177
|
function createByteReadable() {
|
|
10991
|
-
|
|
10992
|
-
|
|
10993
|
-
return {
|
|
10994
|
-
stream: new ReadableStream({
|
|
10995
|
-
start(streamController) {
|
|
10996
|
-
controller = streamController;
|
|
10997
|
-
},
|
|
10998
|
-
cancel() {
|
|
10999
|
-
closed = true;
|
|
11000
|
-
}
|
|
11001
|
-
}),
|
|
11002
|
-
enqueue(chunk) {
|
|
11003
|
-
if (closed || chunk.length === 0) return;
|
|
11004
|
-
controller?.enqueue(chunk);
|
|
11178
|
+
const ended = {
|
|
11179
|
+
enqueue() {
|
|
11005
11180
|
},
|
|
11006
11181
|
close() {
|
|
11007
|
-
if (closed) return;
|
|
11008
|
-
closed = true;
|
|
11009
|
-
controller?.close();
|
|
11010
11182
|
},
|
|
11011
|
-
error(
|
|
11012
|
-
|
|
11013
|
-
|
|
11014
|
-
|
|
11183
|
+
error() {
|
|
11184
|
+
}
|
|
11185
|
+
};
|
|
11186
|
+
let sink = ended;
|
|
11187
|
+
const stream = new ReadableStream({
|
|
11188
|
+
start(controller) {
|
|
11189
|
+
sink = {
|
|
11190
|
+
enqueue(chunk) {
|
|
11191
|
+
if (chunk.length > 0) controller.enqueue(chunk);
|
|
11192
|
+
},
|
|
11193
|
+
close() {
|
|
11194
|
+
sink = ended;
|
|
11195
|
+
controller.close();
|
|
11196
|
+
},
|
|
11197
|
+
error(error) {
|
|
11198
|
+
sink = ended;
|
|
11199
|
+
controller.error(error);
|
|
11200
|
+
}
|
|
11201
|
+
};
|
|
11202
|
+
},
|
|
11203
|
+
cancel() {
|
|
11204
|
+
sink = ended;
|
|
11015
11205
|
}
|
|
11206
|
+
});
|
|
11207
|
+
return {
|
|
11208
|
+
stream,
|
|
11209
|
+
enqueue: (chunk) => sink.enqueue(chunk),
|
|
11210
|
+
close: () => sink.close(),
|
|
11211
|
+
error: (error) => sink.error(error)
|
|
11016
11212
|
};
|
|
11017
11213
|
}
|
|
11018
11214
|
async function readAllText(stream) {
|
|
@@ -11074,9 +11270,6 @@ ${usageLines}`,
|
|
|
11074
11270
|
};
|
|
11075
11271
|
});
|
|
11076
11272
|
}
|
|
11077
|
-
function escapeRegExp(s) {
|
|
11078
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
11079
|
-
}
|
|
11080
11273
|
function stripQuoteArtifacts(raw) {
|
|
11081
11274
|
let s = raw.trim();
|
|
11082
11275
|
if (s.startsWith('"')) {
|
|
@@ -11095,9 +11288,9 @@ function repairQuotedArg(rawArgs) {
|
|
|
11095
11288
|
return `'${escaped}'`;
|
|
11096
11289
|
}
|
|
11097
11290
|
function buildSubcommandRepair(name, subcommands) {
|
|
11098
|
-
const subNames = Object.keys(subcommands).map(
|
|
11291
|
+
const subNames = Object.keys(subcommands).map(RegExp.escape).join("|");
|
|
11099
11292
|
const pattern = new RegExp(
|
|
11100
|
-
`^(\\s*${
|
|
11293
|
+
`^(\\s*${RegExp.escape(name)}\\s+(?:${subNames}))\\s+([\\s\\S]+)$`
|
|
11101
11294
|
);
|
|
11102
11295
|
return function repair(raw) {
|
|
11103
11296
|
const match = raw.match(pattern);
|
|
@@ -12158,6 +12351,10 @@ END;
|
|
|
12158
12351
|
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_checkpoints_chatId' AND object_id = OBJECT_ID('[${schema}].[checkpoints]'))
|
|
12159
12352
|
CREATE INDEX [idx_${schema}_checkpoints_chatId] ON [${schema}].[checkpoints](chatId);
|
|
12160
12353
|
|
|
12354
|
+
-- Deleting a message checks this foreign key too, so it needs the same index.
|
|
12355
|
+
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_checkpoints_messageId' AND object_id = OBJECT_ID('[${schema}].[checkpoints]'))
|
|
12356
|
+
CREATE INDEX [idx_${schema}_checkpoints_messageId] ON [${schema}].[checkpoints](messageId);
|
|
12357
|
+
|
|
12161
12358
|
IF OBJECT_ID('[${schema}].[messages_fts]', 'U') IS NULL
|
|
12162
12359
|
BEGIN
|
|
12163
12360
|
CREATE TABLE [${schema}].[messages_fts] (
|
|
@@ -12192,7 +12389,7 @@ END;
|
|
|
12192
12389
|
}
|
|
12193
12390
|
|
|
12194
12391
|
// packages/context/src/lib/store/sqlserver-schema-lock.ts
|
|
12195
|
-
async function withSqlServerSchemaLock(mssql, pool, schema,
|
|
12392
|
+
async function withSqlServerSchemaLock(mssql, pool, schema, run2) {
|
|
12196
12393
|
const holder = new mssql.Transaction(pool);
|
|
12197
12394
|
await holder.begin();
|
|
12198
12395
|
let result;
|
|
@@ -12213,7 +12410,7 @@ async function withSqlServerSchemaLock(mssql, pool, schema, run) {
|
|
|
12213
12410
|
`Could not lock the DDL of schema "${schema}": sp_getapplock returned ${recordset[0].status}.`
|
|
12214
12411
|
);
|
|
12215
12412
|
}
|
|
12216
|
-
result = await
|
|
12413
|
+
result = await run2();
|
|
12217
12414
|
} catch (error) {
|
|
12218
12415
|
await holder.rollback().catch(() => {
|
|
12219
12416
|
});
|
|
@@ -13086,7 +13283,7 @@ async function persistedWriter(options) {
|
|
|
13086
13283
|
}
|
|
13087
13284
|
|
|
13088
13285
|
// packages/context/src/lib/stream/polling-change-source.ts
|
|
13089
|
-
import { setTimeout as
|
|
13286
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
13090
13287
|
|
|
13091
13288
|
// packages/context/src/lib/stream/polling-policy.ts
|
|
13092
13289
|
var DEFAULT_WATCH_POLLING = {
|
|
@@ -13131,7 +13328,7 @@ function nextAdaptivePollingDelay(state) {
|
|
|
13131
13328
|
state.config.minMs,
|
|
13132
13329
|
state.config.maxMs
|
|
13133
13330
|
);
|
|
13134
|
-
const
|
|
13331
|
+
const delay3 = applyJitter(
|
|
13135
13332
|
current,
|
|
13136
13333
|
state.config.jitterRatio,
|
|
13137
13334
|
state.config.minMs,
|
|
@@ -13142,7 +13339,7 @@ function nextAdaptivePollingDelay(state) {
|
|
|
13142
13339
|
state.config.minMs,
|
|
13143
13340
|
state.config.maxMs
|
|
13144
13341
|
);
|
|
13145
|
-
return
|
|
13342
|
+
return delay3;
|
|
13146
13343
|
}
|
|
13147
13344
|
function normalizeAdaptivePolling(polling, fallback) {
|
|
13148
13345
|
const merged = {
|
|
@@ -13242,7 +13439,7 @@ function isTerminal(status) {
|
|
|
13242
13439
|
return status !== "queued" && status !== "running";
|
|
13243
13440
|
}
|
|
13244
13441
|
function waitForDelay(ms, signal) {
|
|
13245
|
-
return
|
|
13442
|
+
return delay2(ms, true, { signal }).catch((err) => {
|
|
13246
13443
|
if (signal.aborted) return false;
|
|
13247
13444
|
throw err;
|
|
13248
13445
|
});
|
|
@@ -13983,16 +14180,12 @@ function assertIdentifier2(value, label) {
|
|
|
13983
14180
|
|
|
13984
14181
|
// packages/context/src/lib/stream/sqlite.stream-store.ts
|
|
13985
14182
|
import { Declaration as Declaration2 } from "@zukhruf/sqlite-drift";
|
|
14183
|
+
import { open as open2 } from "@zukhruf/sqlite-open";
|
|
13986
14184
|
import { transaction as transaction2 } from "@zukhruf/sqlite-transaction";
|
|
13987
|
-
import {
|
|
13988
|
-
DatabaseSync as DatabaseSync2
|
|
13989
|
-
} from "node:sqlite";
|
|
13990
14185
|
import { z as z19 } from "zod";
|
|
13991
14186
|
|
|
13992
14187
|
// packages/context/src/lib/stream/ddl.stream.sqlite.ts
|
|
13993
14188
|
var SETUP2 = `
|
|
13994
|
-
PRAGMA busy_timeout = 5000;
|
|
13995
|
-
PRAGMA journal_mode = WAL;
|
|
13996
14189
|
PRAGMA synchronous = NORMAL;
|
|
13997
14190
|
`;
|
|
13998
14191
|
var statements2 = [
|
|
@@ -14050,7 +14243,7 @@ var SqliteStreamStore = class extends StreamStore {
|
|
|
14050
14243
|
}
|
|
14051
14244
|
constructor(pathOrDb) {
|
|
14052
14245
|
super();
|
|
14053
|
-
this.#db = typeof pathOrDb === "string" ?
|
|
14246
|
+
this.#db = typeof pathOrDb === "string" ? open2(pathOrDb) : pathOrDb;
|
|
14054
14247
|
this.#db.exec(SETUP2);
|
|
14055
14248
|
tables2.apply(this.#db);
|
|
14056
14249
|
this.#sql = this.#db.createTagStore();
|
|
@@ -14668,6 +14861,7 @@ export {
|
|
|
14668
14861
|
DaytonaCommandError,
|
|
14669
14862
|
DaytonaCreationError,
|
|
14670
14863
|
DaytonaSandboxError,
|
|
14864
|
+
DockerEngine,
|
|
14671
14865
|
DockerNotAvailableError,
|
|
14672
14866
|
DockerSandboxError,
|
|
14673
14867
|
DockerfileBuildError,
|
|
@@ -14760,7 +14954,6 @@ export {
|
|
|
14760
14954
|
defaultResolvers,
|
|
14761
14955
|
defaultTokenizer,
|
|
14762
14956
|
defineSubcommandGroup,
|
|
14763
|
-
dockerEngine,
|
|
14764
14957
|
downloadAndInstall,
|
|
14765
14958
|
elapsedExceeds,
|
|
14766
14959
|
encodeSerializedValue,
|
|
@@ -14875,6 +15068,7 @@ export {
|
|
|
14875
15068
|
useAppleContainerSandbox,
|
|
14876
15069
|
useSandbox,
|
|
14877
15070
|
user,
|
|
15071
|
+
validateSandboxOptions,
|
|
14878
15072
|
visualizeGraph,
|
|
14879
15073
|
weekChanged,
|
|
14880
15074
|
withStraceFileChanges,
|