@truefoundry/trueforge-core 0.1.0-rc.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/README.md +27 -0
  2. package/dist/agent-session/TurnResourceResolver.d.ts.map +1 -1
  3. package/dist/agent-session/TurnResourceResolver.js +6 -2
  4. package/dist/agent-session/TurnResourceResolver.js.map +1 -1
  5. package/dist/agent-session/TurnResourceResolver.mjs +6 -2
  6. package/dist/agent-session/TurnResourceResolver.mjs.map +1 -1
  7. package/dist/agent-session/schemas/turn.d.ts.map +1 -1
  8. package/dist/agent-session/schemas/turn.js +3 -1
  9. package/dist/agent-session/schemas/turn.js.map +1 -1
  10. package/dist/agent-session/schemas/turn.mjs +3 -1
  11. package/dist/agent-session/schemas/turn.mjs.map +1 -1
  12. package/dist/agent-session/store/InMemorySessionStore.d.ts.map +1 -1
  13. package/dist/agent-session/store/InMemorySessionStore.js +24 -8
  14. package/dist/agent-session/store/InMemorySessionStore.js.map +1 -1
  15. package/dist/agent-session/store/InMemorySessionStore.mjs +24 -8
  16. package/dist/agent-session/store/InMemorySessionStore.mjs.map +1 -1
  17. package/dist/agent-session/store/OffsetPageToken.d.ts.map +1 -1
  18. package/dist/agent-session/store/OffsetPageToken.js +3 -1
  19. package/dist/agent-session/store/OffsetPageToken.js.map +1 -1
  20. package/dist/agent-session/store/OffsetPageToken.mjs +3 -1
  21. package/dist/agent-session/store/OffsetPageToken.mjs.map +1 -1
  22. package/dist/agent-session/store/SessionListPageToken.d.ts.map +1 -1
  23. package/dist/agent-session/store/SessionListPageToken.js +3 -1
  24. package/dist/agent-session/store/SessionListPageToken.js.map +1 -1
  25. package/dist/agent-session/store/SessionListPageToken.mjs +3 -1
  26. package/dist/agent-session/store/SessionListPageToken.mjs.map +1 -1
  27. package/dist/core/InstructionBuilder.d.ts.map +1 -1
  28. package/dist/core/InstructionBuilder.js +12 -4
  29. package/dist/core/InstructionBuilder.js.map +1 -1
  30. package/dist/core/InstructionBuilder.mjs +12 -4
  31. package/dist/core/InstructionBuilder.mjs.map +1 -1
  32. package/dist/core/capabilities/builtins/AskUserQuestion.d.ts.map +1 -1
  33. package/dist/core/capabilities/builtins/AskUserQuestion.js +5 -0
  34. package/dist/core/capabilities/builtins/AskUserQuestion.js.map +1 -1
  35. package/dist/core/capabilities/builtins/AskUserQuestion.mjs +5 -0
  36. package/dist/core/capabilities/builtins/AskUserQuestion.mjs.map +1 -1
  37. package/dist/core/capabilities/builtins/LargeToolResponse.d.ts.map +1 -1
  38. package/dist/core/capabilities/builtins/LargeToolResponse.js +6 -2
  39. package/dist/core/capabilities/builtins/LargeToolResponse.js.map +1 -1
  40. package/dist/core/capabilities/builtins/LargeToolResponse.mjs +6 -2
  41. package/dist/core/capabilities/builtins/LargeToolResponse.mjs.map +1 -1
  42. package/dist/core/index.d.ts +9 -3
  43. package/dist/core/index.d.ts.map +1 -1
  44. package/dist/core/index.js +25 -0
  45. package/dist/core/index.js.map +1 -1
  46. package/dist/core/index.mjs +24 -2
  47. package/dist/core/index.mjs.map +1 -1
  48. package/dist/core/llm/VercelAILLM.d.ts +1 -0
  49. package/dist/core/llm/VercelAILLM.d.ts.map +1 -1
  50. package/dist/core/llm/VercelAILLM.js +13 -14
  51. package/dist/core/llm/VercelAILLM.js.map +1 -1
  52. package/dist/core/llm/VercelAILLM.mjs +13 -15
  53. package/dist/core/llm/VercelAILLM.mjs.map +1 -1
  54. package/dist/core/mcp/RemoteMCP.d.ts.map +1 -1
  55. package/dist/core/mcp/RemoteMCP.js +15 -5
  56. package/dist/core/mcp/RemoteMCP.js.map +1 -1
  57. package/dist/core/mcp/RemoteMCP.mjs +15 -5
  58. package/dist/core/mcp/RemoteMCP.mjs.map +1 -1
  59. package/dist/core/mcp/ToolSelectorPolicy.d.ts.map +1 -1
  60. package/dist/core/mcp/ToolSelectorPolicy.js +3 -1
  61. package/dist/core/mcp/ToolSelectorPolicy.js.map +1 -1
  62. package/dist/core/mcp/ToolSelectorPolicy.mjs +3 -1
  63. package/dist/core/mcp/ToolSelectorPolicy.mjs.map +1 -1
  64. package/dist/core/mcp/ToolSet.d.ts.map +1 -1
  65. package/dist/core/mcp/ToolSet.js +9 -3
  66. package/dist/core/mcp/ToolSet.js.map +1 -1
  67. package/dist/core/mcp/ToolSet.mjs +9 -3
  68. package/dist/core/mcp/ToolSet.mjs.map +1 -1
  69. package/dist/core/mcp/convertMCPServers.d.ts.map +1 -1
  70. package/dist/core/mcp/convertMCPServers.js +6 -2
  71. package/dist/core/mcp/convertMCPServers.js.map +1 -1
  72. package/dist/core/mcp/convertMCPServers.mjs +6 -2
  73. package/dist/core/mcp/convertMCPServers.mjs.map +1 -1
  74. package/dist/core/mcp/remoteMcpClient.d.ts.map +1 -1
  75. package/dist/core/mcp/remoteMcpClient.js +21 -7
  76. package/dist/core/mcp/remoteMcpClient.js.map +1 -1
  77. package/dist/core/mcp/remoteMcpClient.mjs +21 -7
  78. package/dist/core/mcp/remoteMcpClient.mjs.map +1 -1
  79. package/dist/core/mcp/toolSelectors.d.ts.map +1 -1
  80. package/dist/core/mcp/toolSelectors.js +18 -6
  81. package/dist/core/mcp/toolSelectors.js.map +1 -1
  82. package/dist/core/mcp/toolSelectors.mjs +18 -6
  83. package/dist/core/mcp/toolSelectors.mjs.map +1 -1
  84. package/dist/core/runtime/AgentThread.d.ts.map +1 -1
  85. package/dist/core/runtime/AgentThread.js +45 -15
  86. package/dist/core/runtime/AgentThread.js.map +1 -1
  87. package/dist/core/runtime/AgentThread.mjs +45 -15
  88. package/dist/core/runtime/AgentThread.mjs.map +1 -1
  89. package/dist/core/runtime/AgentThreadOrchestrator.d.ts.map +1 -1
  90. package/dist/core/runtime/AgentThreadOrchestrator.js +27 -9
  91. package/dist/core/runtime/AgentThreadOrchestrator.js.map +1 -1
  92. package/dist/core/runtime/AgentThreadOrchestrator.mjs +27 -9
  93. package/dist/core/runtime/AgentThreadOrchestrator.mjs.map +1 -1
  94. package/dist/core/runtime/DeferredTool.d.ts.map +1 -1
  95. package/dist/core/runtime/DeferredTool.js +15 -5
  96. package/dist/core/runtime/DeferredTool.js.map +1 -1
  97. package/dist/core/runtime/DeferredTool.mjs +15 -5
  98. package/dist/core/runtime/DeferredTool.mjs.map +1 -1
  99. package/dist/core/runtime/contextUtils.d.ts.map +1 -1
  100. package/dist/core/runtime/contextUtils.js +3 -1
  101. package/dist/core/runtime/contextUtils.js.map +1 -1
  102. package/dist/core/runtime/contextUtils.mjs +3 -1
  103. package/dist/core/runtime/contextUtils.mjs.map +1 -1
  104. package/dist/core/sandbox/Sandbox.d.ts +7 -9
  105. package/dist/core/sandbox/Sandbox.d.ts.map +1 -1
  106. package/dist/core/sandbox/Sandbox.js +55 -63
  107. package/dist/core/sandbox/Sandbox.js.map +1 -1
  108. package/dist/core/sandbox/Sandbox.mjs +56 -64
  109. package/dist/core/sandbox/Sandbox.mjs.map +1 -1
  110. package/dist/core/sandbox/codeMode/CodeModeDispatcher.d.ts +29 -0
  111. package/dist/core/sandbox/codeMode/CodeModeDispatcher.d.ts.map +1 -0
  112. package/dist/core/sandbox/codeMode/CodeModeDispatcher.js +134 -0
  113. package/dist/core/sandbox/codeMode/CodeModeDispatcher.js.map +1 -0
  114. package/dist/core/sandbox/codeMode/CodeModeDispatcher.mjs +113 -0
  115. package/dist/core/sandbox/codeMode/CodeModeDispatcher.mjs.map +1 -0
  116. package/dist/core/sandbox/codeMode/CodeModeTransport.d.ts +21 -0
  117. package/dist/core/sandbox/codeMode/CodeModeTransport.d.ts.map +1 -0
  118. package/dist/core/sandbox/codeMode/CodeModeTransport.js +19 -0
  119. package/dist/core/sandbox/codeMode/CodeModeTransport.js.map +1 -0
  120. package/dist/core/sandbox/codeMode/CodeModeTransport.mjs +1 -0
  121. package/dist/core/sandbox/codeMode/CodeModeTransport.mjs.map +1 -0
  122. package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.d.ts +34 -0
  123. package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.d.ts.map +1 -0
  124. package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.js +193 -0
  125. package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.js.map +1 -0
  126. package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.mjs +168 -0
  127. package/dist/core/sandbox/codeMode/nats/CodeModeNatsTransport.mjs.map +1 -0
  128. package/dist/core/sandbox/codeMode/types.d.ts +34 -0
  129. package/dist/core/sandbox/codeMode/types.d.ts.map +1 -0
  130. package/dist/core/sandbox/codeMode/types.js +59 -0
  131. package/dist/core/sandbox/codeMode/types.js.map +1 -0
  132. package/dist/core/sandbox/codeMode/types.mjs +32 -0
  133. package/dist/core/sandbox/codeMode/types.mjs.map +1 -0
  134. package/dist/core/sandbox/provider/DaytonaProvider.d.ts +19 -1
  135. package/dist/core/sandbox/provider/DaytonaProvider.d.ts.map +1 -1
  136. package/dist/core/sandbox/provider/DaytonaProvider.js +96 -23
  137. package/dist/core/sandbox/provider/DaytonaProvider.js.map +1 -1
  138. package/dist/core/sandbox/provider/DaytonaProvider.mjs +96 -23
  139. package/dist/core/sandbox/provider/DaytonaProvider.mjs.map +1 -1
  140. package/dist/core/sandbox/provider/Provider.d.ts +4 -3
  141. package/dist/core/sandbox/provider/Provider.d.ts.map +1 -1
  142. package/dist/core/sandbox/provider/Provider.js.map +1 -1
  143. package/dist/core/sandbox/provider/Provider.mjs.map +1 -1
  144. package/dist/core/sandbox/provider/TFYSandboxProvider.d.ts +2 -1
  145. package/dist/core/sandbox/provider/TFYSandboxProvider.d.ts.map +1 -1
  146. package/dist/core/sandbox/provider/TFYSandboxProvider.js +20 -6
  147. package/dist/core/sandbox/provider/TFYSandboxProvider.js.map +1 -1
  148. package/dist/core/sandbox/provider/TFYSandboxProvider.mjs +20 -6
  149. package/dist/core/sandbox/provider/TFYSandboxProvider.mjs.map +1 -1
  150. package/dist/core/sandbox/sandboxImage.d.ts +1 -1
  151. package/dist/core/sandbox/sandboxImage.d.ts.map +1 -1
  152. package/dist/core/sandbox/sandboxImage.js +1 -1
  153. package/dist/core/sandbox/sandboxImage.js.map +1 -1
  154. package/dist/core/sandbox/sandboxImage.mjs +1 -1
  155. package/dist/core/sandbox/sandboxImage.mjs.map +1 -1
  156. package/dist/core/sandbox/sandboxScripts.gen.d.ts +1 -1
  157. package/dist/core/sandbox/sandboxScripts.gen.d.ts.map +1 -1
  158. package/dist/core/sandbox/sandboxScripts.gen.js +8 -8
  159. package/dist/core/sandbox/sandboxScripts.gen.js.map +1 -1
  160. package/dist/core/sandbox/sandboxScripts.gen.mjs +8 -8
  161. package/dist/core/sandbox/sandboxScripts.gen.mjs.map +1 -1
  162. package/dist/core/sandbox/skills/SkillMounter.d.ts.map +1 -1
  163. package/dist/core/sandbox/skills/SkillMounter.js +3 -1
  164. package/dist/core/sandbox/skills/SkillMounter.js.map +1 -1
  165. package/dist/core/sandbox/skills/SkillMounter.mjs +3 -1
  166. package/dist/core/sandbox/skills/SkillMounter.mjs.map +1 -1
  167. package/dist/core/util/abort.d.ts.map +1 -1
  168. package/dist/core/util/abort.js +3 -1
  169. package/dist/core/util/abort.js.map +1 -1
  170. package/dist/core/util/abort.mjs +3 -1
  171. package/dist/core/util/abort.mjs.map +1 -1
  172. package/dist/core/util/errorLogFields.d.ts +5 -0
  173. package/dist/core/util/errorLogFields.d.ts.map +1 -1
  174. package/dist/core/util/errorLogFields.js +38 -2
  175. package/dist/core/util/errorLogFields.js.map +1 -1
  176. package/dist/core/util/errorLogFields.mjs +37 -2
  177. package/dist/core/util/errorLogFields.mjs.map +1 -1
  178. package/package.json +10 -6
  179. package/dist/core/sandbox/SandboxNatsBridge.d.ts +0 -33
  180. package/dist/core/sandbox/SandboxNatsBridge.d.ts.map +0 -1
  181. package/dist/core/sandbox/SandboxNatsBridge.js +0 -222
  182. package/dist/core/sandbox/SandboxNatsBridge.js.map +0 -1
  183. package/dist/core/sandbox/SandboxNatsBridge.mjs +0 -201
  184. package/dist/core/sandbox/SandboxNatsBridge.mjs.map +0 -1
@@ -10,14 +10,20 @@ import {
10
10
  SandboxNotAvailableError,
11
11
  SandboxPathIsDirectoryError
12
12
  } from "../SandboxErrors.mjs";
13
+ import { CodeModeNatsTransport } from "../codeMode/nats/CodeModeNatsTransport.mjs";
13
14
  import { DEFAULT_PREVIEW_URL_EXPIRY_SECONDS, DEFAULT_SANDBOX_NATS_WS_PORT } from "../constants.mjs";
14
15
  var SANDBOX_NOT_FOUND_STATUS = 404;
16
+ var SNAPSHOT_CONFLICT_STATUS = 409;
15
17
  var SANDBOX_STATE_STARTED = "started";
16
18
  var BUILD_STATE_ACTIVE = "active";
17
19
  var BUILD_STATE_INACTIVE = "inactive";
18
20
  var BUILD_STATE_ERROR = "error";
19
21
  var BUILD_STATE_BUILD_FAILED = "build_failed";
20
22
  var IMAGE_BUILD_NAME_PREFIX = "trueforge-build-";
23
+ var DEFAULT_DAYTONA_API_URL = "https://app.daytona.io/api";
24
+ function isRecord(value) {
25
+ return typeof value === "object" && value !== null;
26
+ }
21
27
  function imageDigest(image) {
22
28
  const lastSegment = image.slice(image.lastIndexOf("/") + 1);
23
29
  const colon = lastSegment.lastIndexOf(":");
@@ -34,8 +40,11 @@ function isFailedBuildState(state) {
34
40
  }
35
41
  function httpUrlToWsUrl(url) {
36
42
  const parsed = new URL(url);
37
- if (parsed.protocol === "https:") parsed.protocol = "wss:";
38
- else if (parsed.protocol === "http:") parsed.protocol = "ws:";
43
+ if (parsed.protocol === "https:") {
44
+ parsed.protocol = "wss:";
45
+ } else if (parsed.protocol === "http:") {
46
+ parsed.protocol = "ws:";
47
+ }
39
48
  return parsed.toString();
40
49
  }
41
50
  var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
@@ -51,6 +60,8 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
51
60
  fileMaxBytesForDownload;
52
61
  natsBridgePort;
53
62
  previewUrlExpirySeconds;
63
+ apiKey;
64
+ apiUrl;
54
65
  logger;
55
66
  daytona;
56
67
  static cachedSandboxes = /* @__PURE__ */ new Map();
@@ -58,6 +69,8 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
58
69
  static inFlightRecoveries = /* @__PURE__ */ new Map();
59
70
  constructor(options) {
60
71
  this.daytona = options.client;
72
+ this.apiKey = options.apiKey;
73
+ this.apiUrl = options.apiUrl ?? DEFAULT_DAYTONA_API_URL;
61
74
  this.tenantName = options.tenantName;
62
75
  this.imageUri = options.sandboxImage;
63
76
  this.buildRef = options.buildRef ?? deriveImageBuildName(imageDigest(options.sandboxImage));
@@ -73,7 +86,9 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
73
86
  async getOrCreateSandbox(sandboxId) {
74
87
  if (sandboxId) {
75
88
  const cached = _DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);
76
- if (cached) return cached;
89
+ if (cached) {
90
+ return cached;
91
+ }
77
92
  }
78
93
  const sandbox = sandboxId ? await this.restoreExistingSandbox(sandboxId) : await this.daytona.create({
79
94
  name: `${this.tenantName}.${randomUUID()}`,
@@ -89,12 +104,18 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
89
104
  // Returns true iff the caller should retry: either we restarted a stopped sandbox, or the cache entry is missing and the retry will rebuild it via the cold path.
90
105
  static recoverSandboxIfStopped(sandboxId) {
91
106
  const existing = _DaytonaSandboxProvider.inFlightRecoveries.get(sandboxId);
92
- if (existing) return existing;
107
+ if (existing) {
108
+ return existing;
109
+ }
93
110
  const cached = _DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);
94
- if (!cached) return Promise.resolve(true);
111
+ if (!cached) {
112
+ return Promise.resolve(true);
113
+ }
95
114
  const recovery = (async () => {
96
115
  await cached.sandbox.refreshData();
97
- if (cached.sandbox.state === SANDBOX_STATE_STARTED) return false;
116
+ if (cached.sandbox.state === SANDBOX_STATE_STARTED) {
117
+ return false;
118
+ }
98
119
  await cached.sandbox.start();
99
120
  return true;
100
121
  })().finally(() => {
@@ -107,7 +128,9 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
107
128
  try {
108
129
  return await operation();
109
130
  } catch (originalError) {
110
- if (!(originalError instanceof DaytonaError)) throw originalError;
131
+ if (!(originalError instanceof DaytonaError)) {
132
+ throw originalError;
133
+ }
111
134
  let recovered;
112
135
  try {
113
136
  recovered = await _DaytonaSandboxProvider.recoverSandboxIfStopped(sandboxId);
@@ -118,7 +141,9 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
118
141
  });
119
142
  throw new Error("Sandbox is unavailable; recovery attempt failed.", { cause: recoveryError });
120
143
  }
121
- if (!recovered) throw originalError;
144
+ if (!recovered) {
145
+ throw originalError;
146
+ }
122
147
  try {
123
148
  return await operation();
124
149
  } catch (retryError) {
@@ -189,6 +214,40 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
189
214
  return { status: "pending", reason: `Sandbox image build in progress (${state}).`, metadata };
190
215
  }
191
216
  }
217
+ /**
218
+ * Registers the snapshot and returns its initial state without waiting for the build.
219
+ *
220
+ * The SDK's `snapshot.create` issues this same POST and then polls until the snapshot is active
221
+ * or failed (minutes on a cold image pull). Configure only needs the registration result, so
222
+ * credential errors surface on the request while build progress stays observable via `getSnapshot`.
223
+ */
224
+ async registerSnapshot() {
225
+ let response;
226
+ try {
227
+ response = await fetch(`${this.apiUrl}/snapshots`, {
228
+ method: "POST",
229
+ headers: {
230
+ Authorization: `Bearer ${this.apiKey}`,
231
+ "Content-Type": "application/json"
232
+ },
233
+ body: JSON.stringify({ name: this.buildRef, imageName: this.imageUri })
234
+ });
235
+ } catch (error) {
236
+ throw new Error("Daytona snapshot registration request failed.", { cause: error });
237
+ }
238
+ const body = await response.json().catch(() => null);
239
+ if (!response.ok) {
240
+ const message = isRecord(body) && typeof body["message"] === "string" ? body["message"] : `Daytona snapshot registration failed (${String(response.status)})`;
241
+ throw new DaytonaError(message, response.status);
242
+ }
243
+ if (!isRecord(body) || typeof body["state"] !== "string") {
244
+ throw new DaytonaError("Failed to register snapshot. Daytona didn't return a snapshot state.");
245
+ }
246
+ return {
247
+ state: body["state"],
248
+ errorReason: typeof body["errorReason"] === "string" ? body["errorReason"] : null
249
+ };
250
+ }
192
251
  async buildImage() {
193
252
  const existing = await this.getSnapshot(this.buildRef);
194
253
  if (existing) {
@@ -201,14 +260,20 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
201
260
  }
202
261
  await this.deleteFailedBuild(existing);
203
262
  }
204
- void this.daytona.snapshot.create({ name: this.buildRef, image: this.imageUri }).catch((error) => {
205
- this.logger.error(`Daytona snapshot create failed: name=${this.buildRef}`, extractErrorLogFields(error));
206
- });
207
- return {
208
- status: "pending",
209
- reason: "Sandbox image build started.",
210
- metadata: { build_ref: this.buildRef, image_uri: this.imageUri }
211
- };
263
+ try {
264
+ const registered = await this.registerSnapshot();
265
+ return this.toBuild(registered.state, registered.errorReason);
266
+ } catch (error) {
267
+ if (error instanceof DaytonaError && error.statusCode === SNAPSHOT_CONFLICT_STATUS) {
268
+ this.logger.info(`Daytona snapshot already created concurrently: name=${this.buildRef}`);
269
+ return {
270
+ status: "pending",
271
+ reason: "Sandbox image build started by another server replica.",
272
+ metadata: { build_ref: this.buildRef, image_uri: this.imageUri }
273
+ };
274
+ }
275
+ throw error;
276
+ }
212
277
  }
213
278
  async getImageBuildStatus() {
214
279
  const snapshot = await this.getSnapshot(this.buildRef);
@@ -264,7 +329,9 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
264
329
  return await sandbox.fs.downloadFile(params.path);
265
330
  });
266
331
  } catch (e) {
267
- if (e instanceof SandboxPathIsDirectoryError || e instanceof SandboxFileTooLargeError) throw e;
332
+ if (e instanceof SandboxPathIsDirectoryError || e instanceof SandboxFileTooLargeError) {
333
+ throw e;
334
+ }
268
335
  if (e instanceof DaytonaError && e.statusCode === SANDBOX_NOT_FOUND_STATUS) {
269
336
  throw new SandboxFileNotFoundError(params.path);
270
337
  }
@@ -302,13 +369,19 @@ var DaytonaSandboxProvider = class _DaytonaSandboxProvider {
302
369
  }
303
370
  });
304
371
  }
305
- async getNatsBridgeUrl(sandboxId) {
306
- const previewUrl = await this.getPreviewUrl({
307
- sandboxId,
308
- port: this.natsBridgePort,
309
- expiresInSeconds: this.previewUrlExpirySeconds
372
+ createCodeModeTransport() {
373
+ return new CodeModeNatsTransport({
374
+ resolveHostUrl: async (sandboxId) => {
375
+ const previewUrl = await this.getPreviewUrl({
376
+ sandboxId,
377
+ port: this.natsBridgePort,
378
+ expiresInSeconds: this.previewUrlExpirySeconds
379
+ });
380
+ return httpUrlToWsUrl(previewUrl);
381
+ },
382
+ sandboxClientNatsUrl: `ws://localhost:${String(this.natsBridgePort)}`,
383
+ logger: this.logger
310
384
  });
311
- return httpUrlToWsUrl(previewUrl);
312
385
  }
313
386
  getAdditionalInstructions() {
314
387
  return void 0;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/core/sandbox/provider/DaytonaProvider.ts"],"sourcesContent":["import type { Sandbox, Snapshot } from '@daytona/sdk';\nimport { Daytona, DaytonaError } from '@daytona/sdk';\nimport { context } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport { randomUUID } from 'crypto';\nimport type { Logger } from 'winston';\nimport { extractErrorLogFields } from '../../util/errorLogFields';\nimport {\n SandboxFileNotFoundError,\n SandboxFileTooLargeError,\n SandboxNotAvailableError,\n SandboxPathIsDirectoryError,\n} from '../SandboxErrors';\nimport { DEFAULT_PREVIEW_URL_EXPIRY_SECONDS, DEFAULT_SANDBOX_NATS_WS_PORT } from '../constants';\nimport type { ExecResult, SandboxBuild, SandboxExecParams, SandboxFileInfo, SandboxProvider } from './Provider';\n\nconst SANDBOX_NOT_FOUND_STATUS = 404;\nconst SANDBOX_STATE_STARTED = 'started';\n\nconst BUILD_STATE_ACTIVE = 'active';\nconst BUILD_STATE_INACTIVE = 'inactive';\nconst BUILD_STATE_ERROR = 'error';\nconst BUILD_STATE_BUILD_FAILED = 'build_failed';\n\nconst IMAGE_BUILD_NAME_PREFIX = 'trueforge-build-';\n\n/**\n * Digest portion of a container image reference (the tag/digest after the final `:`)\n * The release image is always published with an explicit digest tag\n */\nfunction imageDigest(image: string): string {\n const lastSegment = image.slice(image.lastIndexOf('/') + 1);\n const colon = lastSegment.lastIndexOf(':');\n if (colon === -1) {\n throw new Error(`Sandbox image reference has no tag/digest: ${image}`);\n }\n return lastSegment.slice(colon + 1);\n}\n\n/** Deterministic build name per image digest so every server replica converges on one build. */\nfunction deriveImageBuildName(digest: string): string {\n return `${IMAGE_BUILD_NAME_PREFIX}${digest}`;\n}\n\n/** Terminal-failure build states: a build stuck here never becomes ready on its own. */\nfunction isFailedBuildState(state: Snapshot['state']): boolean {\n return state === BUILD_STATE_ERROR || state === BUILD_STATE_BUILD_FAILED;\n}\n\n/** Convert Daytona https preview URLs to wss for the NATS client. */\nfunction httpUrlToWsUrl(url: string): string {\n const parsed = new URL(url);\n if (parsed.protocol === 'https:') parsed.protocol = 'wss:';\n else if (parsed.protocol === 'http:') parsed.protocol = 'ws:';\n return parsed.toString();\n}\n\nexport interface DaytonaSandboxProviderOptions {\n /** Caller-owned Daytona SDK client (credentials / lifetime). */\n client: Daytona;\n tenantName: string;\n /** Release-owned sandbox image reference; built into a Daytona snapshot and cloned per sandbox. */\n sandboxImage: string;\n /**\n * Daytona snapshot name to clone sandboxes from. When omitted it is derived from the image\n * digest. Callers that create sandboxes pass the persisted build_ref so cloning targets the\n * snapshot that was actually built, not a speculative name derived from the current image.\n */\n buildRef?: string | undefined;\n timeoutMs: number;\n autoStopIntervalInMinutes: number;\n autoArchiveIntervalInMinutes: number;\n autoDeleteIntervalInMinutes: number;\n fileMaxBytesForDownload: number;\n /** Defaults to the built-in sandbox NATS WebSocket port (4444). */\n natsBridgePort?: number;\n /** Defaults to 1 hour (same as the gateway's max agent execution time). */\n previewUrlExpirySeconds?: number;\n logger: Logger;\n}\n\nexport class DaytonaSandboxProvider implements SandboxProvider {\n private readonly tenantName: string;\n /** Release-owned sandbox image reference; built into a Daytona snapshot and cloned per sandbox. */\n private readonly imageUri: string;\n /** Daytona snapshot name sandboxes are cloned from; the persisted build_ref, or derived from the image digest. */\n private readonly buildRef: string;\n private readonly timeoutMs: number;\n private readonly autoStopIntervalInMinutes: number;\n private readonly autoArchiveIntervalInMinutes: number;\n private readonly autoDeleteIntervalInMinutes: number;\n private readonly fileMaxBytesForDownload: number;\n private readonly natsBridgePort: number;\n private readonly previewUrlExpirySeconds: number;\n private readonly logger: Logger;\n private readonly daytona: Daytona;\n private static readonly cachedSandboxes = new Map<string, { sandbox: Sandbox; defaultTimeoutMs: number }>();\n // De-dupes concurrent recovery attempts on the same sandbox to a single refreshData+start round-trip.\n private static readonly inFlightRecoveries = new Map<string, Promise<boolean>>();\n\n constructor(options: DaytonaSandboxProviderOptions) {\n this.daytona = options.client;\n this.tenantName = options.tenantName;\n this.imageUri = options.sandboxImage;\n this.buildRef = options.buildRef ?? deriveImageBuildName(imageDigest(options.sandboxImage));\n this.timeoutMs = options.timeoutMs;\n this.autoStopIntervalInMinutes = options.autoStopIntervalInMinutes;\n this.autoArchiveIntervalInMinutes = options.autoArchiveIntervalInMinutes;\n this.autoDeleteIntervalInMinutes = options.autoDeleteIntervalInMinutes;\n this.fileMaxBytesForDownload = options.fileMaxBytesForDownload;\n this.natsBridgePort = options.natsBridgePort ?? DEFAULT_SANDBOX_NATS_WS_PORT;\n this.previewUrlExpirySeconds = options.previewUrlExpirySeconds ?? DEFAULT_PREVIEW_URL_EXPIRY_SECONDS;\n this.logger = options.logger.child({ module: 'DaytonaProvider' });\n }\n\n private async getOrCreateSandbox(sandboxId?: string): Promise<{ sandbox: Sandbox; defaultTimeoutMs: number }> {\n if (sandboxId) {\n const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);\n if (cached) return cached;\n }\n\n const sandbox = sandboxId\n ? await this.restoreExistingSandbox(sandboxId)\n : await this.daytona.create({\n name: `${this.tenantName}.${randomUUID()}`,\n snapshot: this.buildRef,\n autoStopInterval: this.autoStopIntervalInMinutes,\n autoArchiveInterval: this.autoArchiveIntervalInMinutes,\n autoDeleteInterval: this.autoDeleteIntervalInMinutes,\n });\n\n const entry = { sandbox, defaultTimeoutMs: this.timeoutMs };\n DaytonaSandboxProvider.cachedSandboxes.set(sandbox.name, entry);\n return entry;\n }\n\n // Returns true iff the caller should retry: either we restarted a stopped sandbox, or the cache entry is missing and the retry will rebuild it via the cold path.\n private static recoverSandboxIfStopped(sandboxId: string): Promise<boolean> {\n const existing = DaytonaSandboxProvider.inFlightRecoveries.get(sandboxId);\n if (existing) return existing;\n\n const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);\n // Cache may have been evicted by a concurrent error path; signal retry so getOrCreateSandbox rebuilds via restoreExistingSandbox.\n if (!cached) return Promise.resolve(true);\n\n const recovery = (async () => {\n await cached.sandbox.refreshData();\n if (cached.sandbox.state === SANDBOX_STATE_STARTED) return false;\n // start() covers both stopped and archived per Daytona; throws on unrecoverable states (error/destroyed).\n await cached.sandbox.start();\n return true;\n })().finally(() => {\n DaytonaSandboxProvider.inFlightRecoveries.delete(sandboxId);\n });\n\n DaytonaSandboxProvider.inFlightRecoveries.set(sandboxId, recovery);\n return recovery;\n }\n\n private async executeWithSandboxRecovery<T>(sandboxId: string, operation: () => Promise<T>): Promise<T> {\n try {\n return await operation();\n } catch (originalError) {\n // TODO: Narrow to a specific Daytona error code once @daytona/sdk exposes one for \"sandbox not running\".\n if (!(originalError instanceof DaytonaError)) throw originalError;\n\n let recovered: boolean;\n try {\n recovered = await DaytonaSandboxProvider.recoverSandboxIfStopped(sandboxId);\n } catch (recoveryError) {\n this.logger.error('Sandbox recovery failed', {\n ...extractErrorLogFields(recoveryError),\n originalError: extractErrorLogFields(originalError),\n });\n throw new Error('Sandbox is unavailable; recovery attempt failed.', { cause: recoveryError });\n }\n\n if (!recovered) throw originalError;\n\n try {\n return await operation();\n } catch (retryError) {\n this.logger.error('Sandbox operation failed after successful recovery', {\n ...extractErrorLogFields(retryError),\n originalError: extractErrorLogFields(originalError),\n });\n // Rethrow as-is so callers can match domain error types (SandboxPathIsDirectoryError, DaytonaError statusCode mappings, etc.).\n throw retryError;\n }\n }\n }\n\n private async restoreExistingSandbox(sandboxId: string): Promise<Sandbox> {\n try {\n const sandbox = await this.daytona.get(sandboxId);\n if (sandbox.state !== SANDBOX_STATE_STARTED) {\n await sandbox.start();\n }\n return sandbox;\n } catch (ex) {\n if (ex instanceof DaytonaError && ex.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n throw new SandboxNotAvailableError(sandboxId);\n }\n throw ex;\n }\n }\n\n async createSandbox(): Promise<{ sandboxId: string }> {\n return context.with(suppressTracing(context.active()), async () => {\n const { sandbox } = await this.getOrCreateSandbox();\n this.logger.debug(`Sandbox created: name=${sandbox.name}`);\n return { sandboxId: sandbox.name };\n });\n }\n\n /** Resolves undefined when no snapshot carries that name; auth/other failures throw. */\n private async getSnapshot(name: string): Promise<Snapshot | undefined> {\n try {\n return await this.daytona.snapshot.get(name);\n } catch (error) {\n if (error instanceof DaytonaError && error.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * Drops a build stuck in a terminal-failure state so a fresh create can reuse its\n * deterministic name. A concurrent replica may have deleted it already (404) — that\n * is fine and treated as success.\n */\n private async deleteFailedBuild(snapshot: Snapshot): Promise<void> {\n try {\n await this.daytona.snapshot.delete(snapshot);\n } catch (error) {\n if (error instanceof DaytonaError && error.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n return;\n }\n throw error;\n }\n }\n\n private toBuild(state: Snapshot['state'], errorReason: string | null): SandboxBuild {\n const metadata = { build_ref: this.buildRef, image_uri: this.imageUri };\n switch (state) {\n case BUILD_STATE_ACTIVE:\n return { status: 'ready', reason: null, metadata };\n case BUILD_STATE_ERROR:\n case BUILD_STATE_BUILD_FAILED:\n return { status: 'failed', reason: errorReason ?? `Sandbox image build failed (${state}).`, metadata };\n default:\n // pending / building / pulling / removing / future states: not ready yet.\n return { status: 'pending', reason: `Sandbox image build in progress (${state}).`, metadata };\n }\n }\n\n async buildImage(): Promise<SandboxBuild> {\n const existing = await this.getSnapshot(this.buildRef);\n if (existing) {\n // Daytona parks unused snapshots as 'inactive' after ~2 idle weeks; reactivate rather than rebuild.\n if (existing.state === BUILD_STATE_INACTIVE) {\n const activated = await this.daytona.snapshot.activate(existing);\n return this.toBuild(activated.state, activated.errorReason);\n }\n if (!isFailedBuildState(existing.state)) {\n return this.toBuild(existing.state, existing.errorReason);\n }\n // A failed build keeps the deterministic name occupied and never self-heals, so\n // re-saving settings (which calls buildImage) could never retry. Drop it, then recreate.\n await this.deleteFailedBuild(existing);\n }\n // Fire the create in the background: the SDK's snapshot.create polls until the snapshot is\n // terminal (minutes on a cold image pull), but Daytona registers it on the first request, so\n // progress is observed via getImageBuildStatus. A concurrent-create conflict is harmless.\n void this.daytona.snapshot.create({ name: this.buildRef, image: this.imageUri }).catch((error: unknown) => {\n this.logger.error(`Daytona snapshot create failed: name=${this.buildRef}`, extractErrorLogFields(error));\n });\n return {\n status: 'pending',\n reason: 'Sandbox image build started.',\n metadata: { build_ref: this.buildRef, image_uri: this.imageUri },\n };\n }\n\n async getImageBuildStatus(): Promise<SandboxBuild> {\n const snapshot = await this.getSnapshot(this.buildRef);\n // Read-only: a missing build reports pending; PUT /settings/sandbox-providers starts the build.\n if (!snapshot) {\n return {\n status: 'pending',\n reason: 'Sandbox image build not started.',\n metadata: { build_ref: this.buildRef, image_uri: this.imageUri },\n };\n }\n return this.toBuild(snapshot.state, snapshot.errorReason);\n }\n\n async exec(params: SandboxExecParams): Promise<ExecResult> {\n return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {\n try {\n return await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox, defaultTimeoutMs } = await this.getOrCreateSandbox(params.sandboxId);\n const response = await sandbox.process.executeCommand(\n params.command,\n params.cwd,\n params.env ?? {},\n params.timeoutSeconds ?? defaultTimeoutMs / 1000,\n );\n return {\n success: true,\n response: { exitCode: response.exitCode, result: response.result },\n };\n });\n } catch (e: unknown) {\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n this.logger.error('Sandbox execution error', extractErrorLogFields(e));\n const message = e instanceof Error ? e.message : 'Unknown error';\n return { success: false, error: message };\n }\n });\n }\n\n private async getFileInfo(sandbox: Sandbox, path: string): Promise<SandboxFileInfo> {\n const details = await sandbox.fs.getFileDetails(path);\n return { size: details.size, isDir: details.isDir };\n }\n\n async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {\n return context.with(suppressTracing(context.active()), async () => {\n try {\n return await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);\n\n const info = await this.getFileInfo(sandbox, params.path);\n if (info.isDir) {\n throw new SandboxPathIsDirectoryError(params.path);\n }\n if (info.size > this.fileMaxBytesForDownload) {\n throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytesForDownload);\n }\n\n return await sandbox.fs.downloadFile(params.path);\n });\n } catch (e: unknown) {\n if (e instanceof SandboxPathIsDirectoryError || e instanceof SandboxFileTooLargeError) throw e;\n if (e instanceof DaytonaError && e.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n throw new SandboxFileNotFoundError(params.path);\n }\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n throw e;\n }\n });\n }\n\n async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {\n return context.with(suppressTracing(context.active()), async () => {\n try {\n await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);\n await sandbox.fs.uploadFile(params.content, params.remotePath);\n });\n } catch (e: unknown) {\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n throw e;\n }\n });\n }\n\n // Mints a signed, time-limited https preview URL exposing the given sandbox port.\n private async getPreviewUrl(params: { sandboxId: string; port: number; expiresInSeconds: number }): Promise<string> {\n return context.with(suppressTracing(context.active()), async () => {\n try {\n return await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);\n const signed = await sandbox.getSignedPreviewUrl(params.port, params.expiresInSeconds);\n return signed.url;\n });\n } catch (e: unknown) {\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n this.logger.error('Failed to create signed preview URL', extractErrorLogFields(e));\n throw e;\n }\n });\n }\n\n async getNatsBridgeUrl(sandboxId: string): Promise<string> {\n // Daytona hands us a signed https preview URL; convert http(s) -> ws(s) for the NATS client.\n const previewUrl = await this.getPreviewUrl({\n sandboxId,\n port: this.natsBridgePort,\n expiresInSeconds: this.previewUrlExpirySeconds,\n });\n return httpUrlToWsUrl(previewUrl);\n }\n\n getAdditionalInstructions(): string | undefined {\n return undefined;\n }\n\n getToolResultDumpDir(): string {\n return '/tmp/tool-results';\n }\n\n getGitCredentialsPath(): string {\n // Isolated container per sandbox; absolute path so GIT_CONFIG_* needs no $HOME expansion.\n return '/tmp/.git-credentials';\n }\n}\n"],"mappings":";AACA,SAAkB,oBAAoB;AACtC,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAE3B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC,oCAAoC;AAGjF,IAAM,2BAA2B;AACjC,IAAM,wBAAwB;AAE9B,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB;AAC1B,IAAM,2BAA2B;AAEjC,IAAM,0BAA0B;AAMhC,SAAS,YAAY,OAAuB;AAC1C,QAAM,cAAc,MAAM,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1D,QAAM,QAAQ,YAAY,YAAY,GAAG;AACzC,MAAI,UAAU,IAAI;AAChB,UAAM,IAAI,MAAM,8CAA8C,KAAK,EAAE;AAA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,cAAc,QAAwF;AAClH,WAAO,QAAQ,KAAK,gBAAgB,QAAQ,OAAO,CAAC,GAAG,YAAY;AACjE,UAAI;AACF,eAAO,MAAM,KAAK,2BAA2B,OAAO,WAAW,YAAY;AACzE,gBAAM,EAAE,QAAQ,IAAI,MAAM,KAAK,mBAAmB,OAAO,SAAS;AAClE,gBAAM,SAAS,MAAM,QAAQ,oBAAoB,OAAO,MAAM,OAAO,gBAAgB;AACrF,iBAAO,OAAO;AAAA,QAChB,CAAC;AAAA,MACH,SAAS,GAAY;AACnB,gCAAuB,gBAAgB,OAAO,OAAO,SAAS;AAC9D,aAAK,OAAO,MAAM,uCAAuC,sBAAsB,CAAC,CAAC;AACjF,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,iBAAiB,WAAoC;AAEzD,UAAM,aAAa,MAAM,KAAK,cAAc;AAAA,MAC1C;AAAA,MACA,MAAM,KAAK;AAAA,MACX,kBAAkB,KAAK;AAAA,IACzB,CAAC;AACD,WAAO,eAAe,UAAU;AAAA,EAClC;AAAA,EAEA,4BAAgD;AAC9C,WAAO;AAAA,EACT;AAAA,EAEA,uBAA+B;AAC7B,WAAO;AAAA,EACT;AAAA,EAEA,wBAAgC;AAE9B,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/core/sandbox/provider/DaytonaProvider.ts"],"sourcesContent":["import type { Sandbox, Snapshot } from '@daytona/sdk';\nimport { Daytona, DaytonaError } from '@daytona/sdk';\nimport { context } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport { randomUUID } from 'crypto';\nimport type { Logger } from 'winston';\nimport { extractErrorLogFields } from '../../util/errorLogFields';\nimport {\n SandboxFileNotFoundError,\n SandboxFileTooLargeError,\n SandboxNotAvailableError,\n SandboxPathIsDirectoryError,\n} from '../SandboxErrors';\nimport type { CodeModeTransport } from '../codeMode/CodeModeTransport';\nimport { CodeModeNatsTransport } from '../codeMode/nats/CodeModeNatsTransport';\nimport { DEFAULT_PREVIEW_URL_EXPIRY_SECONDS, DEFAULT_SANDBOX_NATS_WS_PORT } from '../constants';\nimport type { ExecResult, SandboxBuild, SandboxExecParams, SandboxFileInfo, SandboxProvider } from './Provider';\n\nconst SANDBOX_NOT_FOUND_STATUS = 404;\n/** Another replica already registered this build name; its create is the one that counts. */\nconst SNAPSHOT_CONFLICT_STATUS = 409;\nconst SANDBOX_STATE_STARTED = 'started';\n\nconst BUILD_STATE_ACTIVE = 'active';\nconst BUILD_STATE_INACTIVE = 'inactive';\nconst BUILD_STATE_ERROR = 'error';\nconst BUILD_STATE_BUILD_FAILED = 'build_failed';\n\nconst IMAGE_BUILD_NAME_PREFIX = 'trueforge-build-';\n/** Same default the Daytona SDK applies when `DaytonaConfig.apiUrl` is omitted. */\nconst DEFAULT_DAYTONA_API_URL = 'https://app.daytona.io/api';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Digest portion of a container image reference (the tag/digest after the final `:`)\n * The release image is always published with an explicit digest tag\n */\nfunction imageDigest(image: string): string {\n const lastSegment = image.slice(image.lastIndexOf('/') + 1);\n const colon = lastSegment.lastIndexOf(':');\n if (colon === -1) {\n throw new Error(`Sandbox image reference has no tag/digest: ${image}`);\n }\n return lastSegment.slice(colon + 1);\n}\n\n/** Deterministic build name per image digest so every server replica converges on one build. */\nfunction deriveImageBuildName(digest: string): string {\n return `${IMAGE_BUILD_NAME_PREFIX}${digest}`;\n}\n\n/** Terminal-failure build states: a build stuck here never becomes ready on its own. */\nfunction isFailedBuildState(state: Snapshot['state']): boolean {\n return state === BUILD_STATE_ERROR || state === BUILD_STATE_BUILD_FAILED;\n}\n\n/** Convert Daytona https preview URLs to wss for the NATS client. */\nfunction httpUrlToWsUrl(url: string): string {\n const parsed = new URL(url);\n if (parsed.protocol === 'https:') {\n parsed.protocol = 'wss:';\n } else if (parsed.protocol === 'http:') {\n parsed.protocol = 'ws:';\n }\n return parsed.toString();\n}\n\nexport interface DaytonaSandboxProviderOptions {\n /** Caller-owned Daytona SDK client (credentials / lifetime). */\n client: Daytona;\n /**\n * Same API key the client was built with; used for the register-only snapshot POST because the\n * SDK's `snapshot.create` polls to a terminal state instead of returning once registered.\n */\n apiKey: string;\n /** Daytona API base URL (including `/api`). Defaults to the SDK's public cloud endpoint. */\n apiUrl?: string | undefined;\n tenantName: string;\n /** Release-owned sandbox image reference; built into a Daytona snapshot and cloned per sandbox. */\n sandboxImage: string;\n /**\n * Daytona snapshot name to clone sandboxes from. When omitted it is derived from the image\n * digest. Callers that create sandboxes pass the persisted build_ref so cloning targets the\n * snapshot that was actually built, not a speculative name derived from the current image.\n */\n buildRef?: string | undefined;\n timeoutMs: number;\n autoStopIntervalInMinutes: number;\n autoArchiveIntervalInMinutes: number;\n autoDeleteIntervalInMinutes: number;\n fileMaxBytesForDownload: number;\n /** Defaults to the built-in sandbox NATS WebSocket port (4444). */\n natsBridgePort?: number;\n /** Defaults to 1 hour (same as the gateway's max agent execution time). */\n previewUrlExpirySeconds?: number;\n logger: Logger;\n}\n\nexport class DaytonaSandboxProvider implements SandboxProvider {\n private readonly tenantName: string;\n /** Release-owned sandbox image reference; built into a Daytona snapshot and cloned per sandbox. */\n private readonly imageUri: string;\n /** Daytona snapshot name sandboxes are cloned from; the persisted build_ref, or derived from the image digest. */\n private readonly buildRef: string;\n private readonly timeoutMs: number;\n private readonly autoStopIntervalInMinutes: number;\n private readonly autoArchiveIntervalInMinutes: number;\n private readonly autoDeleteIntervalInMinutes: number;\n private readonly fileMaxBytesForDownload: number;\n private readonly natsBridgePort: number;\n private readonly previewUrlExpirySeconds: number;\n private readonly apiKey: string;\n private readonly apiUrl: string;\n private readonly logger: Logger;\n private readonly daytona: Daytona;\n private static readonly cachedSandboxes = new Map<string, { sandbox: Sandbox; defaultTimeoutMs: number }>();\n // De-dupes concurrent recovery attempts on the same sandbox to a single refreshData+start round-trip.\n private static readonly inFlightRecoveries = new Map<string, Promise<boolean>>();\n\n constructor(options: DaytonaSandboxProviderOptions) {\n this.daytona = options.client;\n this.apiKey = options.apiKey;\n this.apiUrl = options.apiUrl ?? DEFAULT_DAYTONA_API_URL;\n this.tenantName = options.tenantName;\n this.imageUri = options.sandboxImage;\n this.buildRef = options.buildRef ?? deriveImageBuildName(imageDigest(options.sandboxImage));\n this.timeoutMs = options.timeoutMs;\n this.autoStopIntervalInMinutes = options.autoStopIntervalInMinutes;\n this.autoArchiveIntervalInMinutes = options.autoArchiveIntervalInMinutes;\n this.autoDeleteIntervalInMinutes = options.autoDeleteIntervalInMinutes;\n this.fileMaxBytesForDownload = options.fileMaxBytesForDownload;\n this.natsBridgePort = options.natsBridgePort ?? DEFAULT_SANDBOX_NATS_WS_PORT;\n this.previewUrlExpirySeconds = options.previewUrlExpirySeconds ?? DEFAULT_PREVIEW_URL_EXPIRY_SECONDS;\n this.logger = options.logger.child({ module: 'DaytonaProvider' });\n }\n\n private async getOrCreateSandbox(sandboxId?: string): Promise<{ sandbox: Sandbox; defaultTimeoutMs: number }> {\n if (sandboxId) {\n const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);\n if (cached) {\n return cached;\n }\n }\n\n const sandbox = sandboxId\n ? await this.restoreExistingSandbox(sandboxId)\n : await this.daytona.create({\n name: `${this.tenantName}.${randomUUID()}`,\n snapshot: this.buildRef,\n autoStopInterval: this.autoStopIntervalInMinutes,\n autoArchiveInterval: this.autoArchiveIntervalInMinutes,\n autoDeleteInterval: this.autoDeleteIntervalInMinutes,\n });\n\n const entry = { sandbox, defaultTimeoutMs: this.timeoutMs };\n DaytonaSandboxProvider.cachedSandboxes.set(sandbox.name, entry);\n return entry;\n }\n\n // Returns true iff the caller should retry: either we restarted a stopped sandbox, or the cache entry is missing and the retry will rebuild it via the cold path.\n private static recoverSandboxIfStopped(sandboxId: string): Promise<boolean> {\n const existing = DaytonaSandboxProvider.inFlightRecoveries.get(sandboxId);\n if (existing) {\n return existing;\n }\n\n const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);\n // Cache may have been evicted by a concurrent error path; signal retry so getOrCreateSandbox rebuilds via restoreExistingSandbox.\n if (!cached) {\n return Promise.resolve(true);\n }\n\n const recovery = (async () => {\n await cached.sandbox.refreshData();\n if (cached.sandbox.state === SANDBOX_STATE_STARTED) {\n return false;\n }\n // start() covers both stopped and archived per Daytona; throws on unrecoverable states (error/destroyed).\n await cached.sandbox.start();\n return true;\n })().finally(() => {\n DaytonaSandboxProvider.inFlightRecoveries.delete(sandboxId);\n });\n\n DaytonaSandboxProvider.inFlightRecoveries.set(sandboxId, recovery);\n return recovery;\n }\n\n private async executeWithSandboxRecovery<T>(sandboxId: string, operation: () => Promise<T>): Promise<T> {\n try {\n return await operation();\n } catch (originalError) {\n // TODO: Narrow to a specific Daytona error code once @daytona/sdk exposes one for \"sandbox not running\".\n if (!(originalError instanceof DaytonaError)) {\n throw originalError;\n }\n\n let recovered: boolean;\n try {\n recovered = await DaytonaSandboxProvider.recoverSandboxIfStopped(sandboxId);\n } catch (recoveryError) {\n this.logger.error('Sandbox recovery failed', {\n ...extractErrorLogFields(recoveryError),\n originalError: extractErrorLogFields(originalError),\n });\n throw new Error('Sandbox is unavailable; recovery attempt failed.', { cause: recoveryError });\n }\n\n if (!recovered) {\n throw originalError;\n }\n\n try {\n return await operation();\n } catch (retryError) {\n this.logger.error('Sandbox operation failed after successful recovery', {\n ...extractErrorLogFields(retryError),\n originalError: extractErrorLogFields(originalError),\n });\n // Rethrow as-is so callers can match domain error types (SandboxPathIsDirectoryError, DaytonaError statusCode mappings, etc.).\n throw retryError;\n }\n }\n }\n\n private async restoreExistingSandbox(sandboxId: string): Promise<Sandbox> {\n try {\n const sandbox = await this.daytona.get(sandboxId);\n if (sandbox.state !== SANDBOX_STATE_STARTED) {\n await sandbox.start();\n }\n return sandbox;\n } catch (ex) {\n if (ex instanceof DaytonaError && ex.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n throw new SandboxNotAvailableError(sandboxId);\n }\n throw ex;\n }\n }\n\n async createSandbox(): Promise<{ sandboxId: string }> {\n return context.with(suppressTracing(context.active()), async () => {\n const { sandbox } = await this.getOrCreateSandbox();\n this.logger.debug(`Sandbox created: name=${sandbox.name}`);\n return { sandboxId: sandbox.name };\n });\n }\n\n /** Resolves undefined when no snapshot carries that name; auth/other failures throw. */\n private async getSnapshot(name: string): Promise<Snapshot | undefined> {\n try {\n return await this.daytona.snapshot.get(name);\n } catch (error) {\n if (error instanceof DaytonaError && error.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * Drops a build stuck in a terminal-failure state so a fresh create can reuse its\n * deterministic name. A concurrent replica may have deleted it already (404) — that\n * is fine and treated as success.\n */\n private async deleteFailedBuild(snapshot: Snapshot): Promise<void> {\n try {\n await this.daytona.snapshot.delete(snapshot);\n } catch (error) {\n if (error instanceof DaytonaError && error.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n return;\n }\n throw error;\n }\n }\n\n private toBuild(state: string, errorReason: string | null): SandboxBuild {\n const metadata = { build_ref: this.buildRef, image_uri: this.imageUri };\n switch (state) {\n case BUILD_STATE_ACTIVE:\n return { status: 'ready', reason: null, metadata };\n case BUILD_STATE_ERROR:\n case BUILD_STATE_BUILD_FAILED:\n return { status: 'failed', reason: errorReason ?? `Sandbox image build failed (${state}).`, metadata };\n default:\n // pending / building / pulling / removing / future states: not ready yet.\n return { status: 'pending', reason: `Sandbox image build in progress (${state}).`, metadata };\n }\n }\n\n /**\n * Registers the snapshot and returns its initial state without waiting for the build.\n *\n * The SDK's `snapshot.create` issues this same POST and then polls until the snapshot is active\n * or failed (minutes on a cold image pull). Configure only needs the registration result, so\n * credential errors surface on the request while build progress stays observable via `getSnapshot`.\n */\n private async registerSnapshot(): Promise<{ state: string; errorReason: string | null }> {\n let response: Response;\n try {\n response = await fetch(`${this.apiUrl}/snapshots`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ name: this.buildRef, imageName: this.imageUri }),\n });\n } catch (error) {\n throw new Error('Daytona snapshot registration request failed.', { cause: error });\n }\n\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const message =\n isRecord(body) && typeof body['message'] === 'string'\n ? body['message']\n : `Daytona snapshot registration failed (${String(response.status)})`;\n throw new DaytonaError(message, response.status);\n }\n if (!isRecord(body) || typeof body['state'] !== 'string') {\n throw new DaytonaError(\"Failed to register snapshot. Daytona didn't return a snapshot state.\");\n }\n return {\n state: body['state'],\n errorReason: typeof body['errorReason'] === 'string' ? body['errorReason'] : null,\n };\n }\n\n async buildImage(): Promise<SandboxBuild> {\n const existing = await this.getSnapshot(this.buildRef);\n if (existing) {\n // Daytona parks unused snapshots as 'inactive' after ~2 idle weeks; reactivate rather than rebuild.\n if (existing.state === BUILD_STATE_INACTIVE) {\n const activated = await this.daytona.snapshot.activate(existing);\n return this.toBuild(activated.state, activated.errorReason);\n }\n if (!isFailedBuildState(existing.state)) {\n return this.toBuild(existing.state, existing.errorReason);\n }\n // A failed build keeps the deterministic name occupied and never self-heals, so\n // re-saving settings (which calls buildImage) could never retry. Drop it, then recreate.\n await this.deleteFailedBuild(existing);\n }\n\n try {\n const registered = await this.registerSnapshot();\n // Registration returns pending almost always; map whatever Daytona sent so a fast\n // active/error still surfaces correctly without a follow-up GET.\n return this.toBuild(registered.state, registered.errorReason);\n } catch (error) {\n // A losing concurrent create is not a build failure: the winner owns the deterministic name.\n if (error instanceof DaytonaError && error.statusCode === SNAPSHOT_CONFLICT_STATUS) {\n this.logger.info(`Daytona snapshot already created concurrently: name=${this.buildRef}`);\n return {\n status: 'pending',\n reason: 'Sandbox image build started by another server replica.',\n metadata: { build_ref: this.buildRef, image_uri: this.imageUri },\n };\n }\n throw error;\n }\n }\n\n async getImageBuildStatus(): Promise<SandboxBuild> {\n const snapshot = await this.getSnapshot(this.buildRef);\n // Read-only: a missing build reports pending; PUT /settings/sandbox-providers starts the build.\n if (!snapshot) {\n return {\n status: 'pending',\n reason: 'Sandbox image build not started.',\n metadata: { build_ref: this.buildRef, image_uri: this.imageUri },\n };\n }\n return this.toBuild(snapshot.state, snapshot.errorReason);\n }\n\n async exec(params: SandboxExecParams): Promise<ExecResult> {\n return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {\n try {\n return await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox, defaultTimeoutMs } = await this.getOrCreateSandbox(params.sandboxId);\n const response = await sandbox.process.executeCommand(\n params.command,\n params.cwd,\n params.env ?? {},\n params.timeoutSeconds ?? defaultTimeoutMs / 1000,\n );\n return {\n success: true,\n response: { exitCode: response.exitCode, result: response.result },\n };\n });\n } catch (e: unknown) {\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n this.logger.error('Sandbox execution error', extractErrorLogFields(e));\n const message = e instanceof Error ? e.message : 'Unknown error';\n return { success: false, error: message };\n }\n });\n }\n\n private async getFileInfo(sandbox: Sandbox, path: string): Promise<SandboxFileInfo> {\n const details = await sandbox.fs.getFileDetails(path);\n return { size: details.size, isDir: details.isDir };\n }\n\n async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {\n return context.with(suppressTracing(context.active()), async () => {\n try {\n return await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);\n\n const info = await this.getFileInfo(sandbox, params.path);\n if (info.isDir) {\n throw new SandboxPathIsDirectoryError(params.path);\n }\n if (info.size > this.fileMaxBytesForDownload) {\n throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytesForDownload);\n }\n\n return await sandbox.fs.downloadFile(params.path);\n });\n } catch (e: unknown) {\n if (e instanceof SandboxPathIsDirectoryError || e instanceof SandboxFileTooLargeError) {\n throw e;\n }\n if (e instanceof DaytonaError && e.statusCode === SANDBOX_NOT_FOUND_STATUS) {\n throw new SandboxFileNotFoundError(params.path);\n }\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n throw e;\n }\n });\n }\n\n async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {\n return context.with(suppressTracing(context.active()), async () => {\n try {\n await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);\n await sandbox.fs.uploadFile(params.content, params.remotePath);\n });\n } catch (e: unknown) {\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n throw e;\n }\n });\n }\n\n // Mints a signed, time-limited https preview URL exposing the given sandbox port.\n private async getPreviewUrl(params: { sandboxId: string; port: number; expiresInSeconds: number }): Promise<string> {\n return context.with(suppressTracing(context.active()), async () => {\n try {\n return await this.executeWithSandboxRecovery(params.sandboxId, async () => {\n const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);\n const signed = await sandbox.getSignedPreviewUrl(params.port, params.expiresInSeconds);\n return signed.url;\n });\n } catch (e: unknown) {\n DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);\n this.logger.error('Failed to create signed preview URL', extractErrorLogFields(e));\n throw e;\n }\n });\n }\n\n createCodeModeTransport(): CodeModeTransport {\n return new CodeModeNatsTransport({\n resolveHostUrl: async (sandboxId: string) => {\n const previewUrl = await this.getPreviewUrl({\n sandboxId,\n port: this.natsBridgePort,\n expiresInSeconds: this.previewUrlExpirySeconds,\n });\n return httpUrlToWsUrl(previewUrl);\n },\n sandboxClientNatsUrl: `ws://localhost:${String(this.natsBridgePort)}`,\n logger: this.logger,\n });\n }\n\n getAdditionalInstructions(): string | undefined {\n return undefined;\n }\n\n getToolResultDumpDir(): string {\n return '/tmp/tool-results';\n }\n\n getGitCredentialsPath(): string {\n // Isolated container per sandbox; absolute path so GIT_CONFIG_* needs no $HOME expansion.\n return '/tmp/.git-credentials';\n }\n}\n"],"mappings":";AACA,SAAkB,oBAAoB;AACtC,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,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K;AAAA,QACzB,CAAC;AACD,eAAO,eAAe,UAAU;AAAA,MAClC;AAAA,MACA,sBAAsB,kBAAkB,OAAO,KAAK,cAAc,CAAC;AAAA,MACnE,QAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEA,4BAAgD;AAC9C,WAAO;AAAA,EACT;AAAA,EAEA,uBAA+B;AAC7B,WAAO;AAAA,EACT;AAAA,EAEA,wBAAgC;AAE9B,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,3 +1,4 @@
1
+ import type { CodeModeTransport } from '../codeMode/CodeModeTransport';
1
2
  /** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */
2
3
  export interface ExecSuccessResult {
3
4
  success: true;
@@ -75,9 +76,9 @@ export interface SandboxProvider {
75
76
  content: Buffer;
76
77
  }): Promise<void>;
77
78
  /**
78
- * Returns a ready-to-use `ws(s)://` URL for this sandbox's pod-local NATS broker, which the
79
- * gateway connects to as the MCP responder. Throws on failure (caller retries on a later exec).
79
+ * Construct a Code Mode transport for this provider (no connect/listen yet).
80
+ * Throws if the provider does not support Code Mode.
80
81
  */
81
- getNatsBridgeUrl(sandboxId: string): Promise<string>;
82
+ createCodeModeTransport(): CodeModeTransport;
82
83
  }
83
84
  //# sourceMappingURL=Provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Provider.d.ts","sourceRoot":"","sources":["../../../../src/core/sandbox/provider/Provider.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,IAAI,CAAC;IACd,QAAQ,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAChD;AAED,6FAA6F;AAC7F,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,KAAK,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,UAAU,GAAG,iBAAiB,GAAG,eAAe,CAAC;AA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;IAChD,0EAA0E;IAC1E,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IAChD,gGAAgG;IAChG,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IACjD,0KAA0K;IAC1K,YAAY,CAAC,MAAM,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3E,qCAAqC;IACrC,UAAU,CAAC,MAAM,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE9F;;;OAGG;IACH,uBAAuB,IAAI,iBAAiB,CAAC;CAC9C"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/core/sandbox/provider/Provider.ts"],"sourcesContent":["/** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */\nexport interface ExecSuccessResult {\n success: true;\n response: { exitCode: number; result: string };\n}\n\n/** Sandbox infrastructure failure — command never ran (e.g. network error, auth failure). */\nexport interface ExecErrorResult {\n success: false;\n error: string;\n}\n\nexport type ExecResult = ExecSuccessResult | ExecErrorResult;\n\n/**\n * Wraps a value in single quotes for safe use in a shell command. Inner single quotes are\n * escaped via the standard shell idiom: ' -> '\\''. Use for any user-controlled value that is\n * interpolated into an exec command string.\n */\nexport function shellEscape(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** Throws if the exec result indicates failure (infra error or non-zero exit code). */\nexport function ensureExecSuccess(result: ExecResult): void {\n if (!result.success) {\n throw new Error(result.error);\n }\n if (result.response.exitCode !== 0) {\n throw new Error(`(exit code ${String(result.response.exitCode)}): ${result.response.result}`);\n }\n}\n\nexport interface SandboxFileInfo {\n size: number;\n isDir: boolean;\n}\n\n/** Parameters for a single sandbox command. */\nexport interface SandboxExecParams {\n sandboxId: string;\n command: string;\n cwd?: string | undefined;\n env?: Record<string, string> | undefined;\n /** Overrides the provider's default exec timeout (e.g. for long skill downloads). */\n timeoutSeconds?: number | undefined;\n}\n\n// An init command a producer (e.g. a skill mounter) hands to the Sandbox, which supplies `sandboxId`.\nexport type SandboxInit = Omit<SandboxExecParams, 'sandboxId'>;\n\nexport type SandboxBuildStatus = 'pending' | 'ready' | 'failed';\n\n/** Provider-specific opaque build metadata (string map). */\nexport type SandboxBuildMetadata = Record<string, string>;\n\nexport interface SandboxBuild {\n status: SandboxBuildStatus;\n /** Human-readable detail for the current status (shown to the user); null when ready. */\n reason: string | null;\n /** Provider-specific build details; null when the provider has none. */\n metadata: SandboxBuildMetadata | null;\n}\n\nexport interface SandboxProvider {\n /**\n * Ensures the release image is being built into the provider's backing store and\n * returns its current status. Idempotent: an already-built image reports `ready`;\n * a fresh build starts in the background and reports `pending`.\n */\n buildImage(): Promise<SandboxBuild>;\n /** Current build status of the release image. Read-only: never kicks off a build. */\n getImageBuildStatus(): Promise<SandboxBuild>;\n createSandbox(): Promise<{ sandboxId: string }>;\n exec(params: SandboxExecParams): Promise<ExecResult>;\n /** Provider-specific instructions appended to the agent system prompt. */\n getAdditionalInstructions(): string | undefined;\n /** Directory inside the sandbox where large tool responses are dumped. */\n getToolResultDumpDir(sandboxId: string): string;\n /** Absolute path for the git credential-store file (per logical sandbox when sharing a pod). */\n getGitCredentialsPath(sandboxId: string): string;\n /** Downloads a file from the sandbox as a Buffer. Throws SandboxFileNotFoundError / SandboxNotAvailableError / SandboxPathIsDirectoryError / SandboxFileTooLargeError. */\n downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer>;\n /** Uploads a file to the sandbox. */\n uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void>;\n\n /**\n * Returns a ready-to-use `ws(s)://` URL for this sandbox's pod-local NATS broker, which the\n * gateway connects to as the MCP responder. Throws on failure (caller retries on a later exec).\n */\n getNatsBridgeUrl(sandboxId: string): Promise<string>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBO,SAAS,YAAY,OAAuB;AACjD,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAGO,SAAS,kBAAkB,QAA0B;AAC1D,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI,MAAM,OAAO,KAAK;AAAA,EAC9B;AACA,MAAI,OAAO,SAAS,aAAa,GAAG;AAClC,UAAM,IAAI,MAAM,cAAc,OAAO,OAAO,SAAS,QAAQ,CAAC,MAAM,OAAO,SAAS,MAAM,EAAE;AAAA,EAC9F;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/core/sandbox/provider/Provider.ts"],"sourcesContent":["import type { CodeModeTransport } from '../codeMode/CodeModeTransport';\n\n/** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */\nexport interface ExecSuccessResult {\n success: true;\n response: { exitCode: number; result: string };\n}\n\n/** Sandbox infrastructure failure — command never ran (e.g. network error, auth failure). */\nexport interface ExecErrorResult {\n success: false;\n error: string;\n}\n\nexport type ExecResult = ExecSuccessResult | ExecErrorResult;\n\n/**\n * Wraps a value in single quotes for safe use in a shell command. Inner single quotes are\n * escaped via the standard shell idiom: ' -> '\\''. Use for any user-controlled value that is\n * interpolated into an exec command string.\n */\nexport function shellEscape(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** Throws if the exec result indicates failure (infra error or non-zero exit code). */\nexport function ensureExecSuccess(result: ExecResult): void {\n if (!result.success) {\n throw new Error(result.error);\n }\n if (result.response.exitCode !== 0) {\n throw new Error(`(exit code ${String(result.response.exitCode)}): ${result.response.result}`);\n }\n}\n\nexport interface SandboxFileInfo {\n size: number;\n isDir: boolean;\n}\n\n/** Parameters for a single sandbox command. */\nexport interface SandboxExecParams {\n sandboxId: string;\n command: string;\n cwd?: string | undefined;\n env?: Record<string, string> | undefined;\n /** Overrides the provider's default exec timeout (e.g. for long skill downloads). */\n timeoutSeconds?: number | undefined;\n}\n\n// An init command a producer (e.g. a skill mounter) hands to the Sandbox, which supplies `sandboxId`.\nexport type SandboxInit = Omit<SandboxExecParams, 'sandboxId'>;\n\nexport type SandboxBuildStatus = 'pending' | 'ready' | 'failed';\n\n/** Provider-specific opaque build metadata (string map). */\nexport type SandboxBuildMetadata = Record<string, string>;\n\nexport interface SandboxBuild {\n status: SandboxBuildStatus;\n /** Human-readable detail for the current status (shown to the user); null when ready. */\n reason: string | null;\n /** Provider-specific build details; null when the provider has none. */\n metadata: SandboxBuildMetadata | null;\n}\n\nexport interface SandboxProvider {\n /**\n * Ensures the release image is being built into the provider's backing store and\n * returns its current status. Idempotent: an already-built image reports `ready`;\n * a fresh build starts in the background and reports `pending`.\n */\n buildImage(): Promise<SandboxBuild>;\n /** Current build status of the release image. Read-only: never kicks off a build. */\n getImageBuildStatus(): Promise<SandboxBuild>;\n createSandbox(): Promise<{ sandboxId: string }>;\n exec(params: SandboxExecParams): Promise<ExecResult>;\n /** Provider-specific instructions appended to the agent system prompt. */\n getAdditionalInstructions(): string | undefined;\n /** Directory inside the sandbox where large tool responses are dumped. */\n getToolResultDumpDir(sandboxId: string): string;\n /** Absolute path for the git credential-store file (per logical sandbox when sharing a pod). */\n getGitCredentialsPath(sandboxId: string): string;\n /** Downloads a file from the sandbox as a Buffer. Throws SandboxFileNotFoundError / SandboxNotAvailableError / SandboxPathIsDirectoryError / SandboxFileTooLargeError. */\n downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer>;\n /** Uploads a file to the sandbox. */\n uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void>;\n\n /**\n * Construct a Code Mode transport for this provider (no connect/listen yet).\n * Throws if the provider does not support Code Mode.\n */\n createCodeModeTransport(): CodeModeTransport;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,SAAS,YAAY,OAAuB;AACjD,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAGO,SAAS,kBAAkB,QAA0B;AAC1D,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI,MAAM,OAAO,KAAK;AAAA,EAC9B;AACA,MAAI,OAAO,SAAS,aAAa,GAAG;AAClC,UAAM,IAAI,MAAM,cAAc,OAAO,OAAO,SAAS,QAAQ,CAAC,MAAM,OAAO,SAAS,MAAM,EAAE;AAAA,EAC9F;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/core/sandbox/provider/Provider.ts"],"sourcesContent":["/** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */\nexport interface ExecSuccessResult {\n success: true;\n response: { exitCode: number; result: string };\n}\n\n/** Sandbox infrastructure failure — command never ran (e.g. network error, auth failure). */\nexport interface ExecErrorResult {\n success: false;\n error: string;\n}\n\nexport type ExecResult = ExecSuccessResult | ExecErrorResult;\n\n/**\n * Wraps a value in single quotes for safe use in a shell command. Inner single quotes are\n * escaped via the standard shell idiom: ' -> '\\''. Use for any user-controlled value that is\n * interpolated into an exec command string.\n */\nexport function shellEscape(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** Throws if the exec result indicates failure (infra error or non-zero exit code). */\nexport function ensureExecSuccess(result: ExecResult): void {\n if (!result.success) {\n throw new Error(result.error);\n }\n if (result.response.exitCode !== 0) {\n throw new Error(`(exit code ${String(result.response.exitCode)}): ${result.response.result}`);\n }\n}\n\nexport interface SandboxFileInfo {\n size: number;\n isDir: boolean;\n}\n\n/** Parameters for a single sandbox command. */\nexport interface SandboxExecParams {\n sandboxId: string;\n command: string;\n cwd?: string | undefined;\n env?: Record<string, string> | undefined;\n /** Overrides the provider's default exec timeout (e.g. for long skill downloads). */\n timeoutSeconds?: number | undefined;\n}\n\n// An init command a producer (e.g. a skill mounter) hands to the Sandbox, which supplies `sandboxId`.\nexport type SandboxInit = Omit<SandboxExecParams, 'sandboxId'>;\n\nexport type SandboxBuildStatus = 'pending' | 'ready' | 'failed';\n\n/** Provider-specific opaque build metadata (string map). */\nexport type SandboxBuildMetadata = Record<string, string>;\n\nexport interface SandboxBuild {\n status: SandboxBuildStatus;\n /** Human-readable detail for the current status (shown to the user); null when ready. */\n reason: string | null;\n /** Provider-specific build details; null when the provider has none. */\n metadata: SandboxBuildMetadata | null;\n}\n\nexport interface SandboxProvider {\n /**\n * Ensures the release image is being built into the provider's backing store and\n * returns its current status. Idempotent: an already-built image reports `ready`;\n * a fresh build starts in the background and reports `pending`.\n */\n buildImage(): Promise<SandboxBuild>;\n /** Current build status of the release image. Read-only: never kicks off a build. */\n getImageBuildStatus(): Promise<SandboxBuild>;\n createSandbox(): Promise<{ sandboxId: string }>;\n exec(params: SandboxExecParams): Promise<ExecResult>;\n /** Provider-specific instructions appended to the agent system prompt. */\n getAdditionalInstructions(): string | undefined;\n /** Directory inside the sandbox where large tool responses are dumped. */\n getToolResultDumpDir(sandboxId: string): string;\n /** Absolute path for the git credential-store file (per logical sandbox when sharing a pod). */\n getGitCredentialsPath(sandboxId: string): string;\n /** Downloads a file from the sandbox as a Buffer. Throws SandboxFileNotFoundError / SandboxNotAvailableError / SandboxPathIsDirectoryError / SandboxFileTooLargeError. */\n downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer>;\n /** Uploads a file to the sandbox. */\n uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void>;\n\n /**\n * Returns a ready-to-use `ws(s)://` URL for this sandbox's pod-local NATS broker, which the\n * gateway connects to as the MCP responder. Throws on failure (caller retries on a later exec).\n */\n getNatsBridgeUrl(sandboxId: string): Promise<string>;\n}\n"],"mappings":";AAmBO,SAAS,YAAY,OAAuB;AACjD,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAGO,SAAS,kBAAkB,QAA0B;AAC1D,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI,MAAM,OAAO,KAAK;AAAA,EAC9B;AACA,MAAI,OAAO,SAAS,aAAa,GAAG;AAClC,UAAM,IAAI,MAAM,cAAc,OAAO,OAAO,SAAS,QAAQ,CAAC,MAAM,OAAO,SAAS,MAAM,EAAE;AAAA,EAC9F;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/core/sandbox/provider/Provider.ts"],"sourcesContent":["import type { CodeModeTransport } from '../codeMode/CodeModeTransport';\n\n/** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */\nexport interface ExecSuccessResult {\n success: true;\n response: { exitCode: number; result: string };\n}\n\n/** Sandbox infrastructure failure — command never ran (e.g. network error, auth failure). */\nexport interface ExecErrorResult {\n success: false;\n error: string;\n}\n\nexport type ExecResult = ExecSuccessResult | ExecErrorResult;\n\n/**\n * Wraps a value in single quotes for safe use in a shell command. Inner single quotes are\n * escaped via the standard shell idiom: ' -> '\\''. Use for any user-controlled value that is\n * interpolated into an exec command string.\n */\nexport function shellEscape(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** Throws if the exec result indicates failure (infra error or non-zero exit code). */\nexport function ensureExecSuccess(result: ExecResult): void {\n if (!result.success) {\n throw new Error(result.error);\n }\n if (result.response.exitCode !== 0) {\n throw new Error(`(exit code ${String(result.response.exitCode)}): ${result.response.result}`);\n }\n}\n\nexport interface SandboxFileInfo {\n size: number;\n isDir: boolean;\n}\n\n/** Parameters for a single sandbox command. */\nexport interface SandboxExecParams {\n sandboxId: string;\n command: string;\n cwd?: string | undefined;\n env?: Record<string, string> | undefined;\n /** Overrides the provider's default exec timeout (e.g. for long skill downloads). */\n timeoutSeconds?: number | undefined;\n}\n\n// An init command a producer (e.g. a skill mounter) hands to the Sandbox, which supplies `sandboxId`.\nexport type SandboxInit = Omit<SandboxExecParams, 'sandboxId'>;\n\nexport type SandboxBuildStatus = 'pending' | 'ready' | 'failed';\n\n/** Provider-specific opaque build metadata (string map). */\nexport type SandboxBuildMetadata = Record<string, string>;\n\nexport interface SandboxBuild {\n status: SandboxBuildStatus;\n /** Human-readable detail for the current status (shown to the user); null when ready. */\n reason: string | null;\n /** Provider-specific build details; null when the provider has none. */\n metadata: SandboxBuildMetadata | null;\n}\n\nexport interface SandboxProvider {\n /**\n * Ensures the release image is being built into the provider's backing store and\n * returns its current status. Idempotent: an already-built image reports `ready`;\n * a fresh build starts in the background and reports `pending`.\n */\n buildImage(): Promise<SandboxBuild>;\n /** Current build status of the release image. Read-only: never kicks off a build. */\n getImageBuildStatus(): Promise<SandboxBuild>;\n createSandbox(): Promise<{ sandboxId: string }>;\n exec(params: SandboxExecParams): Promise<ExecResult>;\n /** Provider-specific instructions appended to the agent system prompt. */\n getAdditionalInstructions(): string | undefined;\n /** Directory inside the sandbox where large tool responses are dumped. */\n getToolResultDumpDir(sandboxId: string): string;\n /** Absolute path for the git credential-store file (per logical sandbox when sharing a pod). */\n getGitCredentialsPath(sandboxId: string): string;\n /** Downloads a file from the sandbox as a Buffer. Throws SandboxFileNotFoundError / SandboxNotAvailableError / SandboxPathIsDirectoryError / SandboxFileTooLargeError. */\n downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer>;\n /** Uploads a file to the sandbox. */\n uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void>;\n\n /**\n * Construct a Code Mode transport for this provider (no connect/listen yet).\n * Throws if the provider does not support Code Mode.\n */\n createCodeModeTransport(): CodeModeTransport;\n}\n"],"mappings":";AAqBO,SAAS,YAAY,OAAuB;AACjD,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAGO,SAAS,kBAAkB,QAA0B;AAC1D,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI,MAAM,OAAO,KAAK;AAAA,EAC9B;AACA,MAAI,OAAO,SAAS,aAAa,GAAG;AAClC,UAAM,IAAI,MAAM,cAAc,OAAO,OAAO,SAAS,QAAQ,CAAC,MAAM,OAAO,SAAS,MAAM,EAAE;AAAA,EAC9F;AACF;","names":[]}
@@ -1,4 +1,5 @@
1
1
  import type { Logger } from 'winston';
2
+ import type { CodeModeTransport } from '../codeMode/CodeModeTransport';
2
3
  import { type ExecResult, type SandboxBuild, type SandboxExecParams, type SandboxProvider } from './Provider';
3
4
  export interface TFYSandboxProviderOptions {
4
5
  serverUrl: string;
@@ -33,7 +34,7 @@ export declare class TFYSandboxProvider implements SandboxProvider {
33
34
  remotePath: string;
34
35
  content: Buffer;
35
36
  }): Promise<void>;
36
- getNatsBridgeUrl(): Promise<string>;
37
+ createCodeModeTransport(): CodeModeTransport;
37
38
  getAdditionalInstructions(): string;
38
39
  getToolResultDumpDir(sandboxId: string): string;
39
40
  getGitCredentialsPath(sandboxId: string): string;
@@ -1 +1 @@
1
- {"version":3,"file":"TFYSandboxProvider.d.ts","sourceRoot":"","sources":["../../../../src/core/sandbox/provider/TFYSandboxProvider.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAGtC,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAEtB,KAAK,eAAe,EACrB,MAAM,YAAY,CAAC;AAYpB,MAAM,WAAW,yBAAyB;IACxC,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,uBAAuB,EAAE,MAAM,CAAC;IAChC,oBAAoB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,MAAM,EAAE,MAAM,CAAC;CAChB;AAOD,qBAAa,kBAAmB,YAAW,eAAe;IACxD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAS;IACjD,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAS;IACnD,OAAO,CAAC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yB,IAAI,MAAM,CAOlC;IAED,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE9C;IAED,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE/C;CACF"}
@@ -38,6 +38,8 @@ var import_core = require("@opentelemetry/core");
38
38
  var import_crypto = require("crypto");
39
39
  var import_dedent = __toESM(require("dedent"), 1);
40
40
  var import_errorLogFields = require("../../util/errorLogFields.js");
41
+ var import_CodeModeNatsTransport = require("../codeMode/nats/CodeModeNatsTransport.js");
42
+ var import_constants = require("../constants.js");
41
43
  var import_SandboxErrors = require("../SandboxErrors.js");
42
44
  var import_Provider = require("./Provider.js");
43
45
  var DEFAULT_TIMEOUT_SECONDS = 60;
@@ -124,8 +126,12 @@ var TFYSandboxProvider = class _TFYSandboxProvider {
124
126
  sandboxId: params.sandboxId,
125
127
  command: `stat -L --printf='{"size":%s,"type":"%F"}' ${shellEscape(params.path)}`
126
128
  });
127
- if (!result.success) throw new Error(`Failed to stat file: ${result.error}`);
128
- if (result.response.exitCode !== 0) throw new import_SandboxErrors.SandboxFileNotFoundError(params.path);
129
+ if (!result.success) {
130
+ throw new Error(`Failed to stat file: ${result.error}`);
131
+ }
132
+ if (result.response.exitCode !== 0) {
133
+ throw new import_SandboxErrors.SandboxFileNotFoundError(params.path);
134
+ }
129
135
  const parsed = JSON.parse(result.response.result);
130
136
  return { size: parsed.size, isDir: parsed.type === "directory" };
131
137
  }
@@ -141,8 +147,12 @@ var TFYSandboxProvider = class _TFYSandboxProvider {
141
147
  sandboxId: params.sandboxId,
142
148
  command: `base64 -w0 ${shellEscape(params.path)}`
143
149
  });
144
- if (!result.success) throw new Error(`Failed to download file: ${result.error}`);
145
- if (result.response.exitCode !== 0) throw new import_SandboxErrors.SandboxFileNotFoundError(params.path);
150
+ if (!result.success) {
151
+ throw new Error(`Failed to download file: ${result.error}`);
152
+ }
153
+ if (result.response.exitCode !== 0) {
154
+ throw new import_SandboxErrors.SandboxFileNotFoundError(params.path);
155
+ }
146
156
  return Buffer.from(result.response.result.trim(), "base64");
147
157
  }
148
158
  async uploadFile(params) {
@@ -155,8 +165,12 @@ var TFYSandboxProvider = class _TFYSandboxProvider {
155
165
  (0, import_Provider.ensureExecSuccess)(result);
156
166
  }
157
167
  // The TFY sandbox exposes a static, cluster-internal NATS WebSocket URL (no signed URLs).
158
- getNatsBridgeUrl() {
159
- return Promise.resolve(this.natsBridgeUrl);
168
+ createCodeModeTransport() {
169
+ return new import_CodeModeNatsTransport.CodeModeNatsTransport({
170
+ resolveHostUrl: () => Promise.resolve(this.natsBridgeUrl),
171
+ sandboxClientNatsUrl: `ws://localhost:${String(import_constants.DEFAULT_SANDBOX_NATS_WS_PORT)}`,
172
+ logger: this.logger
173
+ });
160
174
  }
161
175
  getAdditionalInstructions() {
162
176
  return import_dedent.default`
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/core/sandbox/provider/TFYSandboxProvider.ts"],"sourcesContent":["import { context } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport { randomUUID } from 'crypto';\nimport dedent from 'dedent';\nimport type { Logger } from 'winston';\nimport { extractErrorLogFields } from '../../util/errorLogFields';\nimport { SandboxFileNotFoundError, SandboxFileTooLargeError, SandboxPathIsDirectoryError } from '../SandboxErrors';\nimport {\n ensureExecSuccess,\n type ExecResult,\n type SandboxBuild,\n type SandboxExecParams,\n type SandboxFileInfo,\n type SandboxProvider,\n} from './Provider';\n\nconst DEFAULT_TIMEOUT_SECONDS = 60;\n// Buffer for network latency + response processing on top of the server-side timeout.\nconst CLIENT_TIMEOUT_BUFFER_SECONDS = 5;\n\n// Wraps a value in single quotes for safe use in shell commands.\n// Inner single quotes are escaped via the standard shell idiom: ' → '\\''\nfunction shellEscape(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nexport interface TFYSandboxProviderOptions {\n serverUrl: string;\n natsBridgeUrl: string;\n tenantName: string;\n fileMaxBytesForDownload: number;\n defaultExecTimeoutMs?: number | undefined;\n logger: Logger;\n}\n\ninterface StatResult {\n size: number;\n type: string;\n}\n\nexport class TFYSandboxProvider implements SandboxProvider {\n private readonly serverUrl: string;\n private readonly natsBridgeUrl: string;\n private readonly tenantName: string;\n private readonly fileMaxBytesForDownload: number;\n private readonly defaultExecTimeoutSeconds: number;\n private readonly logger: Logger;\n\n constructor(options: TFYSandboxProviderOptions) {\n this.serverUrl = options.serverUrl.replace(/\\/+$/, '');\n this.natsBridgeUrl = options.natsBridgeUrl;\n this.tenantName = options.tenantName;\n this.fileMaxBytesForDownload = options.fileMaxBytesForDownload;\n this.defaultExecTimeoutSeconds = Math.ceil((options.defaultExecTimeoutMs ?? DEFAULT_TIMEOUT_SECONDS * 1000) / 1000);\n this.logger = options.logger.child({ module: 'TFYSandboxProvider' });\n }\n\n // TFY sandboxes run a prebuilt server image with no per-image build step, so the image is always ready.\n private static readonly readyBuild: SandboxBuild = {\n status: 'ready',\n reason: null,\n metadata: null,\n };\n\n buildImage(): Promise<SandboxBuild> {\n return Promise.resolve(TFYSandboxProvider.readyBuild);\n }\n\n getImageBuildStatus(): Promise<SandboxBuild> {\n return Promise.resolve(TFYSandboxProvider.readyBuild);\n }\n\n createSandbox(): Promise<{ sandboxId: string }> {\n const sandboxId = `${this.tenantName}.${randomUUID()}`;\n this.logger.debug(`Sandbox created: id=${sandboxId}`);\n return Promise.resolve({ sandboxId });\n }\n\n async exec(params: SandboxExecParams): Promise<ExecResult> {\n return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {\n // Honor the per-call timeout (e.g. the longer skill-download timeout) for both the server-side\n // request timeout and the client abort timer; fall back to the provider default otherwise.\n const timeoutSeconds = params.timeoutSeconds ?? this.defaultExecTimeoutSeconds;\n const body = {\n sandbox_id: params.sandboxId,\n command: params.command,\n cwd: params.cwd,\n env: params.env,\n timeout: timeoutSeconds,\n };\n\n const controller = new AbortController();\n const clientTimeoutMs = (timeoutSeconds + CLIENT_TIMEOUT_BUFFER_SECONDS) * 1000;\n const timer = setTimeout(() => {\n controller.abort();\n }, clientTimeoutMs);\n\n try {\n const response = await fetch(`${this.serverUrl}/exec`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const text = await response.text();\n this.logger.error(`Sandbox server returned ${String(response.status)}: ${text}`);\n return { success: false, error: `Sandbox server returned ${String(response.status)}: ${text}` };\n }\n\n const result = (await response.json()) as ExecResult;\n return result;\n } catch (e: unknown) {\n if (e instanceof Error && e.name === 'AbortError') {\n this.logger.error(`Sandbox exec timed out after ${String(timeoutSeconds)}s`, extractErrorLogFields(e));\n return { success: false, error: `Sandbox exec timed out after ${String(timeoutSeconds)}s` };\n }\n this.logger.error('Sandbox exec failed', extractErrorLogFields(e));\n const message = e instanceof Error ? e.message : 'Unknown error';\n return { success: false, error: message };\n } finally {\n clearTimeout(timer);\n }\n });\n }\n\n private async getFileInfo(params: { sandboxId: string; path: string }): Promise<SandboxFileInfo> {\n const result = await this.exec({\n sandboxId: params.sandboxId,\n command: `stat -L --printf='{\"size\":%s,\"type\":\"%F\"}' ${shellEscape(params.path)}`,\n });\n\n if (!result.success) throw new Error(`Failed to stat file: ${result.error}`);\n if (result.response.exitCode !== 0) throw new SandboxFileNotFoundError(params.path);\n\n const parsed = JSON.parse(result.response.result) as StatResult;\n return { size: parsed.size, isDir: parsed.type === 'directory' };\n }\n\n async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {\n const info = await this.getFileInfo(params);\n if (info.isDir) {\n throw new SandboxPathIsDirectoryError(params.path);\n }\n if (info.size > this.fileMaxBytesForDownload) {\n throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytesForDownload);\n }\n\n const result = await this.exec({\n sandboxId: params.sandboxId,\n command: `base64 -w0 ${shellEscape(params.path)}`,\n });\n\n if (!result.success) throw new Error(`Failed to download file: ${result.error}`);\n if (result.response.exitCode !== 0) throw new SandboxFileNotFoundError(params.path);\n\n return Buffer.from(result.response.result.trim(), 'base64');\n }\n\n async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {\n const encoded = params.content.toString('base64');\n const escapedPath = shellEscape(params.remotePath);\n\n const result = await this.exec({\n sandboxId: params.sandboxId,\n command: `echo ${shellEscape(encoded)} | base64 -d > ${escapedPath}`,\n });\n ensureExecSuccess(result);\n }\n\n // The TFY sandbox exposes a static, cluster-internal NATS WebSocket URL (no signed URLs).\n getNatsBridgeUrl(): Promise<string> {\n return Promise.resolve(this.natsBridgeUrl);\n }\n\n getAdditionalInstructions(): string {\n return dedent`\n SANDBOX RULES:\n - The Agent's first sandbox command should be \\`pwd\\` to discover the working directory.\n - ALL file creation and writes MUST stay within that working directory.\n - The Agent must NOT write to /tmp/, ~/, or any absolute path outside the working directory.\n `;\n }\n\n getToolResultDumpDir(sandboxId: string): string {\n return `/tmp/${sandboxId}/tool-results`;\n }\n\n getGitCredentialsPath(sandboxId: string): string {\n return `/tmp/${sandboxId}/.git-credentials`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AACxB,kBAAgC;AAChC,oBAA2B;AAC3B,oBAAmB;AAEnB,4BAAsC;AACtC,2BAAgG;AAChG,sBAOO;AAEP,IAAM,0BAA0B;AAEhC,IAAM,gCAAgC;AAItC,SAAS,YAAY,OAAuB;AAC1C,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAgBO,IAAM,qBAAN,MAAM,oBAA8C;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAAoC;AAC9C,SAAK,YAAY,QAAQ,UAAU,QAAQ,QAAQ,EAAE;AACrD,SAAK,gBAAgB,QAAQ;AAC7B,SAAK,aAAa,QAAQ;AAC1B,SAAK,0BAA0B,QAAQ;AACvC,SAAK,4BAA4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A4B,OAAO,IAAI;AAAA,IACnD;AACA,QAAI,KAAK,OAAO,KAAK,yBAAyB;AAC5C,YAAM,IAAI,8CAAyB,OAAO,MAAM,KAAK,MAAM,KAAK,uBAAuB;AAAA,IACzF;AAEA,UAAM,SAAS,MAAM,KAAK,KAAK;AAAA,MAC7B,WAAW,OAAO;AAAA,MAClB,SAAS,cAAc,YAAY,OAAO,IAAI,CAAC;AAAA,IACjD,CAAC;AAED,QAAI,CAAC,OAAO,QAAS,OAAM,IAAI,MAAM,4BAA4B,OAAO,KAAK,EAAE;AAC/E,QAAI,OAAO,SAAS,aAAa,EAAG,OAAM,IAAI,8CAAyB,OAAO,IAAI;AAElF,WAAO,OAAO,KAAK,OAAO,SAAS,OAAO,KAAK,GAAG,QAAQ;AAAA,EAC5D;AAAA,EAEA,MAAM,WAAW,QAAmF;AAClG,UAAM,UAAU,OAAO,QAAQ,SAAS,QAAQ;AAChD,UAAM,cAAc,YAAY,OAAO,UAAU;AAEjD,UAAM,SAAS,MAAM,KAAK,KAAK;AAAA,MAC7B,WAAW,OAAO;AAAA,MAClB,SAAS,QAAQ,YAAY,OAAO,CAAC,kBAAkB,WAAW;AAAA,IACpE,CAAC;AACD,2CAAkB,MAAM;AAAA,EAC1B;AAAA;AAAA,EAGA,mBAAoC;AAClC,WAAO,QAAQ,QAAQ,KAAK,aAAa;AAAA,EAC3C;AAAA,EAEA,4BAAoC;AAClC,WAAO,cAAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT;AAAA,EAEA,qBAAqB,WAA2B;AAC9C,WAAO,QAAQ,SAAS;AAAA,EAC1B;AAAA,EAEA,sBAAsB,WAA2B;AAC/C,WAAO,QAAQ,SAAS;AAAA,EAC1B;AACF;","names":["dedent"]}
1
+ {"version":3,"sources":["../../../../src/core/sandbox/provider/TFYSandboxProvider.ts"],"sourcesContent":["import { context } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport { randomUUID } from 'crypto';\nimport dedent from 'dedent';\nimport type { Logger } from 'winston';\nimport { extractErrorLogFields } from '../../util/errorLogFields';\nimport type { CodeModeTransport } from '../codeMode/CodeModeTransport';\nimport { CodeModeNatsTransport } from '../codeMode/nats/CodeModeNatsTransport';\nimport { DEFAULT_SANDBOX_NATS_WS_PORT } from '../constants';\nimport { SandboxFileNotFoundError, SandboxFileTooLargeError, SandboxPathIsDirectoryError } from '../SandboxErrors';\nimport {\n ensureExecSuccess,\n type ExecResult,\n type SandboxBuild,\n type SandboxExecParams,\n type SandboxFileInfo,\n type SandboxProvider,\n} from './Provider';\n\nconst DEFAULT_TIMEOUT_SECONDS = 60;\n// Buffer for network latency + response processing on top of the server-side timeout.\nconst CLIENT_TIMEOUT_BUFFER_SECONDS = 5;\n\n// Wraps a value in single quotes for safe use in shell commands.\n// Inner single quotes are escaped via the standard shell idiom: ' → '\\''\nfunction shellEscape(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nexport interface TFYSandboxProviderOptions {\n serverUrl: string;\n natsBridgeUrl: string;\n tenantName: string;\n fileMaxBytesForDownload: number;\n defaultExecTimeoutMs?: number | undefined;\n logger: Logger;\n}\n\ninterface StatResult {\n size: number;\n type: string;\n}\n\nexport class TFYSandboxProvider implements SandboxProvider {\n private readonly serverUrl: string;\n private readonly natsBridgeUrl: string;\n private readonly tenantName: string;\n private readonly fileMaxBytesForDownload: number;\n private readonly defaultExecTimeoutSeconds: number;\n private readonly logger: Logger;\n\n constructor(options: TFYSandboxProviderOptions) {\n this.serverUrl = options.serverUrl.replace(/\\/+$/, '');\n this.natsBridgeUrl = options.natsBridgeUrl;\n this.tenantName = options.tenantName;\n this.fileMaxBytesForDownload = options.fileMaxBytesForDownload;\n this.defaultExecTimeoutSeconds = Math.ceil((options.defaultExecTimeoutMs ?? DEFAULT_TIMEOUT_SECONDS * 1000) / 1000);\n this.logger = options.logger.child({ module: 'TFYSandboxProvider' });\n }\n\n // TFY sandboxes run a prebuilt server image with no per-image build step, so the image is always ready.\n private static readonly readyBuild: SandboxBuild = {\n status: 'ready',\n reason: null,\n metadata: null,\n };\n\n buildImage(): Promise<SandboxBuild> {\n return Promise.resolve(TFYSandboxProvider.readyBuild);\n }\n\n getImageBuildStatus(): Promise<SandboxBuild> {\n return Promise.resolve(TFYSandboxProvider.readyBuild);\n }\n\n createSandbox(): Promise<{ sandboxId: string }> {\n const sandboxId = `${this.tenantName}.${randomUUID()}`;\n this.logger.debug(`Sandbox created: id=${sandboxId}`);\n return Promise.resolve({ sandboxId });\n }\n\n async exec(params: SandboxExecParams): Promise<ExecResult> {\n return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {\n // Honor the per-call timeout (e.g. the longer skill-download timeout) for both the server-side\n // request timeout and the client abort timer; fall back to the provider default otherwise.\n const timeoutSeconds = params.timeoutSeconds ?? this.defaultExecTimeoutSeconds;\n const body = {\n sandbox_id: params.sandboxId,\n command: params.command,\n cwd: params.cwd,\n env: params.env,\n timeout: timeoutSeconds,\n };\n\n const controller = new AbortController();\n const clientTimeoutMs = (timeoutSeconds + CLIENT_TIMEOUT_BUFFER_SECONDS) * 1000;\n const timer = setTimeout(() => {\n controller.abort();\n }, clientTimeoutMs);\n\n try {\n const response = await fetch(`${this.serverUrl}/exec`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const text = await response.text();\n this.logger.error(`Sandbox server returned ${String(response.status)}: ${text}`);\n return { success: false, error: `Sandbox server returned ${String(response.status)}: ${text}` };\n }\n\n const result = (await response.json()) as ExecResult;\n return result;\n } catch (e: unknown) {\n if (e instanceof Error && e.name === 'AbortError') {\n this.logger.error(`Sandbox exec timed out after ${String(timeoutSeconds)}s`, extractErrorLogFields(e));\n return { success: false, error: `Sandbox exec timed out after ${String(timeoutSeconds)}s` };\n }\n this.logger.error('Sandbox exec failed', extractErrorLogFields(e));\n const message = e instanceof Error ? e.message : 'Unknown error';\n return { success: false, error: message };\n } finally {\n clearTimeout(timer);\n }\n });\n }\n\n private async getFileInfo(params: { sandboxId: string; path: string }): Promise<SandboxFileInfo> {\n const result = await this.exec({\n sandboxId: params.sandboxId,\n command: `stat -L --printf='{\"size\":%s,\"type\":\"%F\"}' ${shellEscape(params.path)}`,\n });\n\n if (!result.success) {\n throw new Error(`Failed to stat file: ${result.error}`);\n }\n if (result.response.exitCode !== 0) {\n throw new SandboxFileNotFoundError(params.path);\n }\n\n const parsed = JSON.parse(result.response.result) as StatResult;\n return { size: parsed.size, isDir: parsed.type === 'directory' };\n }\n\n async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {\n const info = await this.getFileInfo(params);\n if (info.isDir) {\n throw new SandboxPathIsDirectoryError(params.path);\n }\n if (info.size > this.fileMaxBytesForDownload) {\n throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytesForDownload);\n }\n\n const result = await this.exec({\n sandboxId: params.sandboxId,\n command: `base64 -w0 ${shellEscape(params.path)}`,\n });\n\n if (!result.success) {\n throw new Error(`Failed to download file: ${result.error}`);\n }\n if (result.response.exitCode !== 0) {\n throw new SandboxFileNotFoundError(params.path);\n }\n\n return Buffer.from(result.response.result.trim(), 'base64');\n }\n\n async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {\n const encoded = params.content.toString('base64');\n const escapedPath = shellEscape(params.remotePath);\n\n const result = await this.exec({\n sandboxId: params.sandboxId,\n command: `echo ${shellEscape(encoded)} | base64 -d > ${escapedPath}`,\n });\n ensureExecSuccess(result);\n }\n\n // The TFY sandbox exposes a static, cluster-internal NATS WebSocket URL (no signed URLs).\n createCodeModeTransport(): CodeModeTransport {\n return new CodeModeNatsTransport({\n resolveHostUrl: () => Promise.resolve(this.natsBridgeUrl),\n sandboxClientNatsUrl: `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`,\n logger: this.logger,\n });\n }\n\n getAdditionalInstructions(): string {\n return dedent`\n SANDBOX RULES:\n - The Agent's first sandbox command should be \\`pwd\\` to discover the working directory.\n - ALL file creation and writes MUST stay within that working directory.\n - The Agent must NOT write to /tmp/, ~/, or any absolute path outside the working directory.\n `;\n }\n\n getToolResultDumpDir(sandboxId: string): string {\n return `/tmp/${sandboxId}/tool-results`;\n }\n\n getGitCredentialsPath(sandboxId: string): string {\n return `/tmp/${sandboxId}/.git-credentials`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAwB;AACxB,kBAAgC;AAChC,oBAA2B;AAC3B,oBAAmB;AAEnB,4BAAsC;AAEtC,mCAAsC;AACtC,uBAA6C;AAC7C,2BAAgG;AAChG,sBAOO;AAEP,IAAM,0BAA0B;AAEhC,IAAM,gCAAgC;AAItC,SAAS,YAAY,OAAuB;AAC1C,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAgBO,IAAM,qBAAN,MAAM,oBAA8C;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAAoC;AAC9C,SAAK,YAAY,QAAQ,UAAU,QAAQ,QAAQ,EAAE;AACrD,SAAK,gBAAgB,QAAQ;AAC7B,SAAK,aAAa,QAAQ;AAC1B,SAAK,0BAA0B,QAAQ;AACvC,SAAK,4BAA4B,KAAK,MAAM,QAAQ,wBAAwB,0BAA0B,OAAQ,GAAI;AAClH,SAAK,SAAS,QAAQ,OAAO,MAAM,EAAE,QAAQ,qBAAqB,CAAC;AAAA,EACrE;AAAA;AAAA,EAGA,OAAwB,aAA2B;AAAA,IACjD,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EAEA,aAAoC;AAClC,WAAO,QAAQ,QAAQ,oBAAmB,UAAU;AAAA,EACtD;AAAA,EAEA,sBAA6C;AAC3C,WAAO,QAAQ,QAAQ,oBAAmB,UAAU;AAAA,EACtD;AAAA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EAAE;AAAA,IAC5D;AACA,QAAI,OAAO,SAAS,aAAa,GAAG;AAClC,YAAM,IAAI,8CAAyB,OAAO,IAAI;AAAA,IAChD;AAEA,WAAO,OAAO,KAAK,OAAO,SAAS,OAAO,KAAK,GAAG,QAAQ;AAAA,EAC5D;AAAA,EAEA,MAAM,WAAW,QAAmF;AAClG,UAAM,UAAU,OAAO,QAAQ,SAAS,QAAQ;AAChD,UAAM,cAAc,YAAY,OAAO,UAAU;AAEjD,UAAM,SAAS,MAAM,KAAK,KAAK;AAAA,MAC7B,WAAW,OAAO;AAAA,MAClB,SAAS,QAAQ,YAAY,OAAO,CAAC,kBAAkB,WAAW;AAAA,IACpE,CAAC;AACD,2CAAkB,MAAM;AAAA,EAC1B;AAAA;AAAA,EAGA,0BAA6C;AAC3C,WAAO,IAAI,mDAAsB;AAAA,MAC/B,gBAAgB,MAAM,QAAQ,QAAQ,KAAK,aAAa;AAAA,MACxD,sBAAsB,kBAAkB,OAAO,6CAA4B,CAAC;AAAA,MAC5E,QAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEA,4BAAoC;AAClC,WAAO,cAAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT;AAAA,EAEA,qBAAqB,WAA2B;AAC9C,WAAO,QAAQ,SAAS;AAAA,EAC1B;AAAA,EAEA,sBAAsB,WAA2B;AAC/C,WAAO,QAAQ,SAAS;AAAA,EAC1B;AACF;","names":["dedent"]}
@@ -4,6 +4,8 @@ import { suppressTracing } from "@opentelemetry/core";
4
4
  import { randomUUID } from "crypto";
5
5
  import dedent from "dedent";
6
6
  import { extractErrorLogFields } from "../../util/errorLogFields.mjs";
7
+ import { CodeModeNatsTransport } from "../codeMode/nats/CodeModeNatsTransport.mjs";
8
+ import { DEFAULT_SANDBOX_NATS_WS_PORT } from "../constants.mjs";
7
9
  import { SandboxFileNotFoundError, SandboxFileTooLargeError, SandboxPathIsDirectoryError } from "../SandboxErrors.mjs";
8
10
  import {
9
11
  ensureExecSuccess
@@ -92,8 +94,12 @@ var TFYSandboxProvider = class _TFYSandboxProvider {
92
94
  sandboxId: params.sandboxId,
93
95
  command: `stat -L --printf='{"size":%s,"type":"%F"}' ${shellEscape(params.path)}`
94
96
  });
95
- if (!result.success) throw new Error(`Failed to stat file: ${result.error}`);
96
- if (result.response.exitCode !== 0) throw new SandboxFileNotFoundError(params.path);
97
+ if (!result.success) {
98
+ throw new Error(`Failed to stat file: ${result.error}`);
99
+ }
100
+ if (result.response.exitCode !== 0) {
101
+ throw new SandboxFileNotFoundError(params.path);
102
+ }
97
103
  const parsed = JSON.parse(result.response.result);
98
104
  return { size: parsed.size, isDir: parsed.type === "directory" };
99
105
  }
@@ -109,8 +115,12 @@ var TFYSandboxProvider = class _TFYSandboxProvider {
109
115
  sandboxId: params.sandboxId,
110
116
  command: `base64 -w0 ${shellEscape(params.path)}`
111
117
  });
112
- if (!result.success) throw new Error(`Failed to download file: ${result.error}`);
113
- if (result.response.exitCode !== 0) throw new SandboxFileNotFoundError(params.path);
118
+ if (!result.success) {
119
+ throw new Error(`Failed to download file: ${result.error}`);
120
+ }
121
+ if (result.response.exitCode !== 0) {
122
+ throw new SandboxFileNotFoundError(params.path);
123
+ }
114
124
  return Buffer.from(result.response.result.trim(), "base64");
115
125
  }
116
126
  async uploadFile(params) {
@@ -123,8 +133,12 @@ var TFYSandboxProvider = class _TFYSandboxProvider {
123
133
  ensureExecSuccess(result);
124
134
  }
125
135
  // The TFY sandbox exposes a static, cluster-internal NATS WebSocket URL (no signed URLs).
126
- getNatsBridgeUrl() {
127
- return Promise.resolve(this.natsBridgeUrl);
136
+ createCodeModeTransport() {
137
+ return new CodeModeNatsTransport({
138
+ resolveHostUrl: () => Promise.resolve(this.natsBridgeUrl),
139
+ sandboxClientNatsUrl: `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`,
140
+ logger: this.logger
141
+ });
128
142
  }
129
143
  getAdditionalInstructions() {
130
144
  return dedent`