@nanoseil/agentseil-farm 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +33 -1
  2. package/dist/main.js +236 -252
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -17,7 +17,39 @@ Run `npx @nanoseil/agentseil-farm@latest configure` to change or clear the PAT,
17
17
 
18
18
  On headless hosts, supply `AGENTSEIL_GITHUB_TOKEN` at startup through your secret manager. An empty value enables public-only access. This variable takes precedence over the credential store and applies to the current process.
19
19
 
20
- If you run multiple Farms on the same host, set a distinct `AGENTSEIL_FARM_ID` for each one. Farm uses the PAT to connect directly to GitHub. Gateway shows the GitHub username in the Farm selector.
20
+ ## Set the sandbox idle time
21
+
22
+ Farm stops each retained sandbox after 60 minutes of inactivity by default. To use 30 minutes, set `AGENTSEIL_SANDBOX_IDLE_MINUTES=30` or pass the option when starting the Farm.
23
+
24
+ ```sh
25
+ npx @nanoseil/agentseil-farm@latest --gateway-url https://gateway.example.com --sandbox-idle-minutes 30
26
+ ```
27
+
28
+ The option overrides the environment variable. Use whole minutes. Setting `0` makes the sandbox eligible for stopping as soon as the turn ends. A configuration change applies when the Farm next finishes a turn in that sandbox. Existing stop deadlines stay in effect until the sandbox stops or the next turn finishes.
29
+
30
+ ## Run multiple Farms on one host
31
+
32
+ Start each Farm in a separate terminal or process manager service. Give each instance a distinct `AGENTSEIL_FARM_ID`. The default is the hostname, so processes on the same host would otherwise share an ID. If you are adding an instance to an existing setup, keep the existing Farm's ID. Reuse each instance's ID on restart so Gateway can route tasks back to the Farm that owns their sandboxes.
33
+
34
+ Both processes can use the same Docker Sandboxes setup on the host. If Gateway requires a Farm token, set `AGENTSEIL_FARM_TOKEN` to the Gateway's token in both terminals.
35
+
36
+ Start `host-farm-1` in the first terminal.
37
+
38
+ ```sh
39
+ AGENTSEIL_FARM_ID=host-farm-1 npx @nanoseil/agentseil-farm@latest --gateway-url https://gateway.example.com
40
+ ```
41
+
42
+ Start `host-farm-2` in the second terminal, using the same Gateway URL.
43
+
44
+ ```sh
45
+ AGENTSEIL_FARM_ID=host-farm-2 npx @nanoseil/agentseil-farm@latest --gateway-url https://gateway.example.com
46
+ ```
47
+
48
+ When running from source after `pnpm build`, use `pnpm farm` in place of `npx @nanoseil/agentseil-farm@latest` in both commands.
49
+
50
+ Each Farm ID has its own GitHub PAT entry in the OS credential store. To change one, run `AGENTSEIL_FARM_ID=host-farm-2 npx @nanoseil/agentseil-farm@latest configure` and restart that instance. On a headless host, supply `AGENTSEIL_GITHUB_TOKEN` separately to each process.
51
+
52
+ Open **接続状況** (Connections) in the Gateway Web UI and check that both Farm IDs appear as connected. In the project settings, select the Farms that should run its tasks. Gateway shows the GitHub username next to each Farm ID.
21
53
 
22
54
  ## Update
23
55
 
package/dist/main.js CHANGED
@@ -18,10 +18,12 @@ var relatedIssueUrlSchema = z.string().trim().max(512).refine((url) => repositor
18
18
  function uniqueStrings(values) {
19
19
  return new Set(values.map((value) => value.toLowerCase())).size === values.length;
20
20
  }
21
- var repositoryListSchema = z.array(repositorySchema).max(50).refine(uniqueStrings, "Remove duplicate repositories");
21
+ var checkoutRepositoryListSchema = z.array(repositorySchema).refine(uniqueStrings, "Remove duplicate repositories");
22
+ var repositoryListSchema = checkoutRepositoryListSchema.max(50);
22
23
  var farmIdSchema = z.string().regex(/^[a-zA-Z0-9._:-]{1,128}$/);
24
+ var projectFarmIdsSchema = z.array(farmIdSchema).min(1, "Select at least one Farm").refine((ids) => new Set(ids).size === ids.length, "Remove duplicate Farms");
23
25
  var githubLoginSchema = z.string().regex(/^[a-z\d][a-z\d_-]{0,38}$/i);
24
- var projectFarmInputSchema = z.object({ farmId: farmIdSchema.nullable() });
26
+ var projectFarmInputSchema = z.strictObject({ farmIds: projectFarmIdsSchema });
25
27
  var repositoryRegistrationSchema = z.object({
26
28
  repository: z.string().trim().transform((value) => value.replace(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/?$/i, "$1")).pipe(repositorySchema)
27
29
  });
@@ -35,7 +37,7 @@ var projectRepositoriesInputSchema = projectRepositoriesSchema.safeExtend({
35
37
  });
36
38
  var projectCreateInputSchema = projectRepositoriesSchema.safeExtend({
37
39
  name: z.string().trim().min(1).max(200),
38
- farmId: farmIdSchema.nullable().optional()
40
+ farmIds: projectFarmIdsSchema
39
41
  }).strict();
40
42
  var repositoryCandidateSchema = z.object({
41
43
  repository: repositorySchema,
@@ -87,8 +89,9 @@ var imageUploadSchema = z.object({
87
89
  }, { message: "Upload a PNG, JPEG, WebP, or GIF image up to 1 MiB", path: ["data"] });
88
90
  var imageUploadsSchema = z.array(imageUploadSchema).max(maxImages);
89
91
  var imageIdSchema = z.strictObject({ id: z.uuid() });
90
- var artifactFormats = ["markdown", "html", "text"];
91
- var maxArtifactBytes = 128 * 1024;
92
+ var artifactFormats = ["markdown", "html", "text", "image"];
93
+ var maxArtifactBytes = 5 * 1024 * 1024;
94
+ var maxArtifactBase64Length = Math.ceil(maxArtifactBytes / 3) * 4;
92
95
  var maxTaskArtifacts = 8;
93
96
  var artifactIdsSchema = z.array(z.uuid()).max(maxTaskArtifacts).refine(uniqueStrings, "Remove duplicate artifacts");
94
97
  var artifactTitleSchema = z.string().trim().min(1).max(200);
@@ -100,8 +103,7 @@ var taskFields = {
100
103
  description: z.string().trim().max(TASK_DESCRIPTION_MAX_LENGTH),
101
104
  repositories: repositoryListSchema.default([]),
102
105
  projectId: z.uuid().optional(),
103
- codexSettings: codexSettingsSchema.optional(),
104
- artifactIds: artifactIdsSchema.optional()
106
+ codexSettings: codexSettingsSchema.optional()
105
107
  };
106
108
  var hasTaskContent = ({ description, images, artifactIds }) => Boolean(description || images?.length || artifactIds?.length);
107
109
  var taskContentError = {
@@ -112,16 +114,18 @@ var taskUploadFields = {
112
114
  ...taskFields,
113
115
  images: imageUploadsSchema.optional()
114
116
  };
115
- var taskInputSchema = z.object(taskUploadFields).refine(hasTaskContent, taskContentError);
117
+ var taskUploadContentError = { ...taskContentError, message: "Enter a description or attach an image" };
118
+ var taskInputSchema = z.object(taskUploadFields).refine(hasTaskContent, taskUploadContentError);
116
119
  var taskEditInputSchema = z.object({
117
120
  ...taskFields,
121
+ artifactIds: artifactIdsSchema.optional(),
118
122
  images: z.array(z.union([imageIdSchema, imageUploadSchema])).max(maxImages).optional()
119
123
  }).refine(hasTaskContent, taskContentError);
120
124
  var taskCreateInputSchema = z.object({
121
125
  ...taskUploadFields,
122
126
  title: taskTitleSchema.optional(),
123
127
  sourceIssueUrl: relatedIssueUrlSchema.optional()
124
- }).refine(hasTaskContent, taskContentError);
128
+ }).refine(hasTaskContent, taskUploadContentError);
125
129
  var pullRequestSchema = z.object({
126
130
  repository: repositorySchema,
127
131
  url: z.string().regex(pullUrl, "Use a GitHub pull request URL")
@@ -137,6 +141,10 @@ var farmSettingsCapabilitiesSchema = farmConnectInputSchema.extend({
137
141
  var farmSandboxCleanupInputSchema = farmConnectInputSchema.extend({
138
142
  sandboxName: z.string().regex(/^agentseil-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/)
139
143
  });
144
+ var farmSandboxStopResultSchema = farmSandboxCleanupInputSchema.extend({
145
+ claimToken: z.uuid(),
146
+ stopped: z.boolean()
147
+ });
140
148
  var farmGitHubOperationSchema = z.discriminatedUnion("kind", [
141
149
  z.object({ kind: z.literal("catalog") }),
142
150
  z.object({ kind: z.literal("issues"), repository: repositorySchema, page: z.int().positive().max(Number.MAX_SAFE_INTEGER - 1) }),
@@ -156,7 +164,8 @@ var commitIdentitySettingsSchema = z.object({ commitIdentity: commitIdentitySche
156
164
  var projectCommitIdentitySettingsSchema = z.object({ commitIdentity: commitIdentitySchema.nullable() });
157
165
  var farmClaimInputSchema = farmSettingsCapabilitiesSchema.extend({
158
166
  claimRequestId: z.uuid(),
159
- projectTasks: z.boolean().optional()
167
+ projectTasks: z.boolean().optional(),
168
+ supportsIdleSandboxStop: z.literal(true).optional()
160
169
  });
161
170
  var farmLeaseInputSchema = farmConnectInputSchema.extend({
162
171
  claimToken: z.uuid()
@@ -168,9 +177,15 @@ var farmPublishArtifactInputSchema = farmLeaseInputSchema.extend({
168
177
  artifactId: z.uuid().transform((id) => id.toLowerCase()),
169
178
  title: artifactTitleSchema.optional(),
170
179
  format: z.enum(artifactFormats),
171
- content: z.string().min(1).max(maxArtifactBytes).refine((content3) => content3.trim() && !content3.includes("\0") && new TextEncoder().encode(content3).byteLength <= maxArtifactBytes, "Provide a UTF-8 artifact up to 128 KiB"),
180
+ content: z.string().min(1).max(maxArtifactBase64Length),
172
181
  replaces: z.uuid().optional()
173
- }).refine(({ title, replaces }) => Boolean(title || replaces), { message: "Name the artifact", path: ["title"] });
182
+ }).refine(({ title, replaces }) => Boolean(title || replaces), { message: "Name the artifact", path: ["title"] }).refine(({ format, content: content3 }) => {
183
+ if (format !== "image") {
184
+ return content3.length <= maxArtifactBytes && Boolean(content3.trim()) && !/[\0\uD800-\uDFFF]/u.test(content3) && new TextEncoder().encode(content3).byteLength <= maxArtifactBytes;
185
+ }
186
+ const padding = content3.endsWith("==") ? 2 : content3.endsWith("=") ? 1 : 0;
187
+ return content3.length <= maxArtifactBase64Length && content3.length / 4 * 3 - padding <= maxArtifactBytes && Boolean(detectImageMediaType(content3)) && z.base64().safeParse(content3).success;
188
+ }, { message: "Provide a UTF-8 document or PNG, JPEG, WebP, or GIF image up to 5 MiB", path: ["content"] });
174
189
  var farmTaskTitleInputSchema = farmLeaseInputSchema.extend({
175
190
  title: taskFields.title
176
191
  });
@@ -242,17 +257,20 @@ var codexTokenUsageSchema = z.object({
242
257
  cachedInputTokens: z.int().nonnegative(),
243
258
  outputTokens: z.int().nonnegative()
244
259
  });
260
+ var DEFAULT_SANDBOX_IDLE_MINUTES = 60;
261
+ var sandboxIdleMinutesSchema = z.int().nonnegative();
245
262
  var farmCompleteInputSchema = farmLeaseInputSchema.extend({
246
263
  status: z.enum(["succeeded", "failed"]),
247
264
  taskCompleted: z.boolean().optional(),
248
265
  summary: z.string().trim().min(1).max(4e3),
249
266
  pullRequests: z.array(pullRequestSchema).max(100),
250
- selectedRepositories: repositoryListSchema.optional(),
267
+ selectedRepositories: checkoutRepositoryListSchema.optional(),
251
268
  resume: taskResumeSchema.nullable().optional(),
252
269
  conversationOnly: z.boolean().optional(),
253
270
  lazyEventIds: lazyEventIdsSchema.optional(),
254
271
  generatedTitle: taskFields.title.optional(),
255
- tokenUsage: codexTokenUsageSchema.optional()
272
+ tokenUsage: codexTokenUsageSchema.optional(),
273
+ sandboxIdleMinutes: sandboxIdleMinutesSchema.optional()
256
274
  });
257
275
  var farmRepositoryCompleteSchema = farmConnectInputSchema.extend({
258
276
  repository: repositorySchema,
@@ -650,14 +668,14 @@ var GatewayError = class extends Error {
650
668
  this.status = status;
651
669
  }
652
670
  };
653
- async function retryGatewayRequest(call, signal) {
654
- while (true) {
671
+ async function retryGatewayRequest(call, signal, maxAttempts = Infinity) {
672
+ for (let attempt = 1; ; attempt++) {
655
673
  signal.throwIfAborted();
656
674
  try {
657
675
  return await call(AbortSignal.any([signal, AbortSignal.timeout(1e4)]));
658
676
  } catch (error) {
659
677
  signal.throwIfAborted();
660
- if (error instanceof GatewayError && error.status >= 400 && error.status < 500 && error.status !== 429)
678
+ if (attempt >= maxAttempts || error instanceof GatewayError && error.status >= 400 && error.status < 500 && error.status !== 429)
661
679
  throw error;
662
680
  }
663
681
  await sleep(1e3, void 0, { signal });
@@ -701,7 +719,7 @@ function gatewayClient(url, token) {
701
719
  return { codexDefaults: defaults.data, commitIdentity: identity.data };
702
720
  },
703
721
  async claim(json, signal) {
704
- const response = await rpc.api.farms.claim.$post({ json: { ...json, localGithub: true } }, { init: { signal } });
722
+ const response = await rpc.api.farms.claim.$post({ json: { ...json, localGithub: true, supportsIdleSandboxStop: true } }, { init: { signal } });
705
723
  if (response.status !== 200)
706
724
  throw await gatewayError(response);
707
725
  return (await response.json()).assignment;
@@ -796,6 +814,17 @@ function gatewayClient(url, token) {
796
814
  if (response.status !== 200)
797
815
  throw await gatewayError(response);
798
816
  },
817
+ async claimIdleSandboxStop(json, signal) {
818
+ const response = await rpc.api.farms["sandbox-stop"].claim.$post({ json }, { init: { signal } });
819
+ if (response.status !== 200)
820
+ throw await gatewayError(response);
821
+ return (await response.json()).job;
822
+ },
823
+ async completeIdleSandboxStop(json, signal) {
824
+ const response = await rpc.api.farms["sandbox-stop"].complete.$post({ json }, { init: { signal } });
825
+ if (response.status !== 200)
826
+ throw await gatewayError(response);
827
+ },
799
828
  async pendingRepositoryCheck(json, signal) {
800
829
  const response = await rpc.api.farms.repositories.pending.$post({ json }, { init: { signal } });
801
830
  if (response.status !== 200)
@@ -825,11 +854,12 @@ function gatewayClient(url, token) {
825
854
  import { randomUUID as randomUUID3 } from "node:crypto";
826
855
  import { chmod, mkdtemp, rm } from "node:fs/promises";
827
856
  import { tmpdir } from "node:os";
828
- import { join as join2, posix as posix2 } from "node:path";
829
- import { z as z6 } from "zod";
857
+ import { join as join2, posix as posix3 } from "node:path";
858
+ import { z as z5 } from "zod";
830
859
 
831
860
  // apps/farm/dist/artifacts.js
832
861
  import { randomUUID } from "node:crypto";
862
+ import { posix } from "node:path";
833
863
  import { z as z3 } from "zod";
834
864
 
835
865
  // apps/farm/dist/codex-session.js
@@ -1267,20 +1297,23 @@ var artifactInstructions = [
1267
1297
  "Treat attached artifact files as reference material and read them when relevant to the operator\u2019s request.",
1268
1298
  "When the operator requests an Artifact or a standalone deliverable for review (such as a mockup, report, or plan), create it and publish it in Agentseil. This applies to the original task and to requests in chat.",
1269
1299
  "Save the deliverable as a UTF-8 Markdown, HTML, or text file and call publish_artifact with a recognizable title. For an HTML preview, include any styles and scripts in the file so it can run on its own.",
1300
+ 'Share images from the sandbox by embedding them in an Artifact or publishing a PNG, JPEG, WebP, or GIF file with format "image". Published Artifacts appear as links in the current task chat.',
1270
1301
  "When revising an existing Artifact, use list_artifacts to find its latest version and pass that version ID as replaces to publish_artifact.",
1271
1302
  "Confirm publication from the tool result and mention the published title and version in your summary. If publication cannot be completed, explain what prevented it."
1272
1303
  ].join(" ");
1304
+ var filePath = z3.string().min(1).max(4096).refine((path) => !path.includes("\0"));
1273
1305
  var publishInput = z3.strictObject({
1274
- path: z3.string().min(1).max(4096).refine((path) => !path.includes("\0")),
1306
+ path: filePath,
1275
1307
  title: artifactTitleSchema.optional(),
1276
1308
  format: z3.enum(artifactFormats),
1277
1309
  replaces: z3.uuid().optional()
1278
1310
  });
1279
- function artifactTools(gateway, { taskId, ...claim }, signal, readFile) {
1311
+ var legacyImageInput = z3.strictObject({ path: filePath, caption: z3.string().trim().max(4e3).optional() });
1312
+ function artifactTools(gateway, { taskId, ...claim }, signal, readFile, resumed) {
1280
1313
  const deadline = () => AbortSignal.any([signal, AbortSignal.timeout(2e4)]);
1281
- return [{
1314
+ const tools = [{
1282
1315
  name: "list_artifacts",
1283
- description: "List the latest published Artifact versions in this Agentseil project or standalone task.",
1316
+ description: "List the latest published Artifact versions in this Agentseil task.",
1284
1317
  inputSchema: { type: "object", additionalProperties: false, properties: {} },
1285
1318
  async execute() {
1286
1319
  const artifacts = await retryGatewayRequest((requestSignal2) => gateway.listArtifacts(taskId, claim, requestSignal2), deadline());
@@ -1293,7 +1326,7 @@ function artifactTools(gateway, { taskId, ...claim }, signal, readFile) {
1293
1326
  }
1294
1327
  }, {
1295
1328
  name: "publish_artifact",
1296
- description: "Publish a UTF-8 sandbox file up to 128 KiB for review in Agentseil. Supply a title for a new Artifact or the latest version ID for a revision.",
1329
+ description: 'Publish and share a sandbox file up to 5 MiB in this Agentseil task. Use UTF-8 for Markdown, HTML, and text, or format "image" for PNG, JPEG, WebP, or GIF. Supply a title for a new Artifact or the latest version ID for a revision.',
1297
1330
  inputSchema: {
1298
1331
  type: "object",
1299
1332
  additionalProperties: false,
@@ -1305,30 +1338,47 @@ function artifactTools(gateway, { taskId, ...claim }, signal, readFile) {
1305
1338
  replaces: { type: "string", description: "Latest version ID, from list_artifacts or a previous publish_artifact call." }
1306
1339
  }
1307
1340
  },
1308
- async execute(arguments_) {
1309
- const parsed = publishInput.safeParse(arguments_);
1310
- if (!parsed.success || !(parsed.data.title || parsed.data.replaces)) {
1311
- throw new CodexToolError("Provide a file path and format, plus a title or the latest artifact version ID.");
1312
- }
1313
- const { path, ...fields } = parsed.data;
1314
- const input = farmPublishArtifactInputSchema.safeParse({
1315
- ...claim,
1316
- ...fields,
1317
- artifactId: randomUUID(),
1318
- content: await readFile(path, deadline())
1319
- });
1320
- if (!input.success)
1321
- throw new CodexToolError(`Provide a non-empty UTF-8 file up to ${maxArtifactBytes / 1024} KiB.`);
1322
- try {
1323
- const published = await retryGatewayRequest((requestSignal2) => gateway.publishArtifact(taskId, input.data, requestSignal2), deadline());
1324
- return JSON.stringify(published);
1325
- } catch (error) {
1326
- if (error instanceof GatewayError && error.status < 500)
1327
- throw new CodexToolError(error.message);
1328
- throw error;
1341
+ execute: publish
1342
+ }];
1343
+ if (resumed) {
1344
+ tools.push({
1345
+ name: "attach_task_image",
1346
+ description: "Publish an image Artifact from a legacy Codex thread.",
1347
+ inputSchema: { type: "object" },
1348
+ async execute(arguments_) {
1349
+ const parsed = legacyImageInput.safeParse(arguments_);
1350
+ if (!parsed.success)
1351
+ throw new CodexToolError("Provide a file path and an optional caption.");
1352
+ const { path, caption } = parsed.data;
1353
+ const title = (caption || posix.basename(path)).slice(0, 200).replace(/[\uD800-\uDBFF]$/, "").trim() || "Image";
1354
+ return publish({ path, title, format: "image" });
1329
1355
  }
1356
+ });
1357
+ }
1358
+ return tools;
1359
+ async function publish(arguments_) {
1360
+ const parsed = publishInput.safeParse(arguments_);
1361
+ if (!parsed.success || !(parsed.data.title || parsed.data.replaces)) {
1362
+ throw new CodexToolError("Provide a file path and format, plus a title or the latest artifact version ID.");
1330
1363
  }
1331
- }];
1364
+ const { path, ...fields } = parsed.data;
1365
+ const input = farmPublishArtifactInputSchema.safeParse({
1366
+ ...claim,
1367
+ ...fields,
1368
+ artifactId: randomUUID(),
1369
+ content: await readFile(path, fields.format, deadline())
1370
+ });
1371
+ if (!input.success)
1372
+ throw new CodexToolError(input.error.issues.map(({ message }) => message).join(" "));
1373
+ try {
1374
+ const published = await retryGatewayRequest((requestSignal2) => gateway.publishArtifact(taskId, input.data, requestSignal2), deadline());
1375
+ return JSON.stringify(published);
1376
+ } catch (error) {
1377
+ if (error instanceof GatewayError && error.status < 500)
1378
+ throw new CodexToolError(error.message);
1379
+ throw error;
1380
+ }
1381
+ }
1332
1382
  }
1333
1383
 
1334
1384
  // apps/farm/dist/command.js
@@ -1467,63 +1517,8 @@ async function resolveCommitIdentity(choice, token, signal) {
1467
1517
  return { name: login, email: `${id}+${login}@users.noreply.github.com` };
1468
1518
  }
1469
1519
 
1470
- // apps/farm/dist/repository-selection.js
1471
- import { z as z5 } from "zod";
1472
- var repositorySelectionOutputSchema = {
1473
- type: "object",
1474
- additionalProperties: false,
1475
- required: ["repositories", "summary"],
1476
- properties: {
1477
- repositories: { type: "array", items: { type: "string" } },
1478
- summary: { type: "string" }
1479
- }
1480
- };
1481
- var selectionSchema = z5.object({
1482
- repositories: z5.array(z5.string().trim()).max(50),
1483
- summary: z5.string().trim().min(1).max(4e3)
1484
- });
1485
- function repositorySelectionPrompt(task, candidates, project, artifacts = []) {
1486
- const checkout = project?.primaryRepository ? "The farm will check out the project primary repository as the starting directory, along with any additional repositories you select." : "The farm will check out the repositories you select.";
1487
- return `Choose the GitHub repositories needed for the task below. No files have been cloned. ${checkout} A separate step will perform the task.
1488
-
1489
- Use the task description, any attachments, links in the description, and already registered related issues as context. Return exact owner/repository names from candidateRepositories and choose only repositories you expect to need. Return no duplicates. Use tools only if you need to read the listed local artifact files. Do not access the links, fetch repositories, implement changes, or publish anything in this step. If the verified catalog does not include a suitable repository or there is not enough information to choose, return an empty repository list and explain what is missing. Return a short summary in the language of the task.
1490
-
1491
- ${JSON.stringify({
1492
- title: task.autoTitlePending ? void 0 : task.title,
1493
- description: task.description,
1494
- artifacts: artifacts.length ? artifacts : void 0,
1495
- issues: task.issues,
1496
- previousPullRequests: task.pullRequests,
1497
- candidateRepositories: candidates,
1498
- project
1499
- }, null, 2)}`;
1500
- }
1501
- function validateRepositorySelection(value, candidates, primaryRepository) {
1502
- const selection = selectionSchema.parse(value);
1503
- if (!selection.repositories.length && !primaryRepository)
1504
- throw new Error(selection.summary);
1505
- const canonicalNames = new Map(candidates.map((name) => [name.toLowerCase(), name]));
1506
- const primary = primaryRepository ? canonicalNames.get(primaryRepository.toLowerCase()) : void 0;
1507
- if (primaryRepository && !primary)
1508
- throw new Error("The project primary repository is not verified on this farm.");
1509
- const seen = /* @__PURE__ */ new Set();
1510
- const selected = selection.repositories.map((requested) => {
1511
- const normalized = requested.toLowerCase();
1512
- const repository = canonicalNames.get(normalized);
1513
- if (!repository)
1514
- throw new Error(`Codex selected a repository outside the verified catalog: ${requested}`);
1515
- if (seen.has(normalized))
1516
- throw new Error(`Codex selected the same repository more than once: ${repository}`);
1517
- seen.add(normalized);
1518
- return repository;
1519
- });
1520
- if (primary && !seen.has(primary.toLowerCase()))
1521
- selected.unshift(primary);
1522
- return selected;
1523
- }
1524
-
1525
1520
  // apps/farm/dist/repositories.js
1526
- import { join, posix } from "node:path";
1521
+ import { join, posix as posix2 } from "node:path";
1527
1522
  var workspace = "/home/agent/workspace";
1528
1523
  var repositoryPattern = /^[a-z\d](?:[a-z\d-]{0,38})\/[a-z\d_.-]{1,100}$/i;
1529
1524
  function hostedRepository(repository) {
@@ -1597,7 +1592,7 @@ async function prepareRepository(name, index, dir, remote, signal) {
1597
1592
  name,
1598
1593
  url,
1599
1594
  workBundle,
1600
- sandboxDir: posix.join(workspace, name),
1595
+ sandboxDir: posix2.join(workspace, name),
1601
1596
  sandboxBundle: `/home/agent/.agentseil-repo-${index}.bundle`
1602
1597
  };
1603
1598
  }
@@ -1608,7 +1603,6 @@ import { setTimeout as sleep2 } from "node:timers/promises";
1608
1603
  var pollIntervalMs = 1e3;
1609
1604
  var responseLanguage = "Use the language of the operator\u2019s original task for progress updates, replies, and the final summary. A brief follow-up in another language or a pasted command does not change the reply language. Honor explicit requests about reply language and carry forward preferences meant for the rest of the conversation.";
1610
1605
  var decisionInstructions = "When a decision from the operator is needed, use request_operator_decision with a self-contained question and concrete choices in the operator\u2019s language. The tool posts the question and returns immediately. Continue work that does not depend on the answer. If blocked, end the turn with a summary of what is waiting, using the required result schema. A decision answer arrives as an [eager] task chat message. Use it to continue any work the decision was blocking. If the tool is unavailable on an older thread, ask in visible task chat.";
1611
- var imageInstructions = "When an image from the sandbox helps answer the operator, use attach_task_image if available. Give it the local path and an optional caption in the operator\u2019s language. The image appears in the chat as a separate reply.";
1612
1606
  var activityLabels = {
1613
1607
  read: "\u30D5\u30A1\u30A4\u30EB\u3092\u78BA\u8A8D\u3057\u307E\u3057\u305F\u3002",
1614
1608
  edit: "\u30D5\u30A1\u30A4\u30EB\u3092\u7DE8\u96C6\u3057\u307E\u3057\u305F\u3002",
@@ -1621,7 +1615,7 @@ var activityLabels = {
1621
1615
  function decisionTool(gateway, { taskId, ...claim }, signal) {
1622
1616
  return {
1623
1617
  name: "request_operator_decision",
1624
- description: "Post a question for the operator on the Agentseil decisions page. The operator can select a choice, write a free-text answer, or do both. Returns immediately and the answer arrives in this thread as an eager message.",
1618
+ description: "Post a question for the operator on the Agentseil task detail page. The operator can select a choice, write a free-text answer, or do both. Returns immediately and the answer arrives in this thread as an eager message.",
1625
1619
  inputSchema: {
1626
1620
  type: "object",
1627
1621
  additionalProperties: false,
@@ -1722,11 +1716,7 @@ ${githubUpdates(lazyEvents, true)}` : eager;
1722
1716
  outbox.push({ ...claim, responseId: randomUUID2(), text: activityLabels[kind], activity: { kind, count: 1 } });
1723
1717
  }
1724
1718
  }
1725
- async function postImage(image, caption) {
1726
- outbox.push({ ...claim, responseId: randomUUID2(), text: caption, images: [image] });
1727
- await flush();
1728
- }
1729
- const session = await startSession(message, activity, postImage);
1719
+ const session = await startSession(message, activity);
1730
1720
  async function pendingChat(pollSignal, sealIfEmpty) {
1731
1721
  const pending = await retryGatewayRequest((requestSignal2) => gateway.pendingTaskChat(taskId, {
1732
1722
  ...claim,
@@ -1815,13 +1805,12 @@ ${githubUpdates(lazyEvents, true)}` : eager;
1815
1805
 
1816
1806
  Artifacts attached to the task description:
1817
1807
  ${JSON.stringify(initialArtifacts, null, 2)}` : "";
1808
+ const legacyImageContext = followUp ? ' If publish_artifact in this resumed thread does not accept format "image", use attach_task_image if available. It publishes an image Artifact.' : "";
1818
1809
  let text = `${instructions}
1819
1810
 
1820
1811
  ${decisionInstructions}
1821
1812
 
1822
- ${imageInstructions}
1823
-
1824
- ${artifactInstructions}${artifactsContext}
1813
+ ${artifactInstructions}${legacyImageContext}${artifactsContext}
1825
1814
 
1826
1815
  ${pendingContext}`;
1827
1816
  const eagerFormat = { schema, parseResult };
@@ -1873,7 +1862,7 @@ Use any images included with these messages in the previous turn.`, { messages:
1873
1862
  var githubHosts = ["github.com", "api.github.com"];
1874
1863
  var progressTimeoutMs = 2e3;
1875
1864
  var resultSchema = farmCompleteInputSchema.pick({ status: true, summary: true, pullRequests: true }).extend({
1876
- taskCompleted: z6.boolean().nullable()
1865
+ taskCompleted: z5.boolean().nullable()
1877
1866
  });
1878
1867
  var outputSchema = {
1879
1868
  type: "object",
@@ -1894,27 +1883,23 @@ var outputSchema = {
1894
1883
  }
1895
1884
  }
1896
1885
  };
1897
- var resumeResultSchema = resultSchema.extend({ kind: z6.enum(["answer", "work"]) }).refine(({ kind, status, pullRequests }) => kind === "work" || status === "succeeded" && pullRequests.length === 0, "A chat answer must succeed without pull requests");
1886
+ var resumeResultSchema = resultSchema.extend({ kind: z5.enum(["answer", "work"]) }).refine(({ kind, status, pullRequests }) => kind === "work" || status === "succeeded" && pullRequests.length === 0, "A chat answer must succeed without pull requests");
1898
1887
  var resumeOutputSchema = {
1899
1888
  ...outputSchema,
1900
1889
  required: [...outputSchema.required, "kind"],
1901
1890
  properties: { ...outputSchema.properties, kind: { type: "string", enum: ["answer", "work"] } }
1902
1891
  };
1903
- var lazyResultSchema = z6.union([resumeResultSchema, resultSchema.extend({
1904
- kind: z6.literal("noop"),
1905
- status: z6.literal("succeeded"),
1906
- taskCompleted: z6.null(),
1907
- pullRequests: z6.tuple([])
1892
+ var lazyResultSchema = z5.union([resumeResultSchema, resultSchema.extend({
1893
+ kind: z5.literal("noop"),
1894
+ status: z5.literal("succeeded"),
1895
+ taskCompleted: z5.null(),
1896
+ pullRequests: z5.tuple([])
1908
1897
  })]);
1909
1898
  var lazyOutputSchema = {
1910
1899
  ...resumeOutputSchema,
1911
1900
  properties: { ...resumeOutputSchema.properties, kind: { type: "string", enum: ["answer", "work", "noop"] } }
1912
1901
  };
1913
- var relatedIssueToolInput = z6.strictObject({ url: relatedIssueUrlSchema });
1914
- var imageToolInput = z6.strictObject({
1915
- path: z6.string().trim().min(1).max(4096).refine((path) => !path.includes("\0")),
1916
- caption: z6.string().trim().max(4e3).optional()
1917
- });
1902
+ var relatedIssueToolInput = z5.strictObject({ url: relatedIssueUrlSchema });
1918
1903
  var completionInstructions = `Use taskCompleted to report your judgment about the whole task. Set it to true when the task's completion conditions are met and no operator decision is pending. For changes delivered through pull requests, verify that every required PR has merged unless the operator defined an earlier completion point. Check both the previously reported PRs and any new PRs that are required for this task. If the current work succeeded and the task is still waiting for a decision, merges, or other follow-up, return status "succeeded" and taskCompleted false, and describe what remains. Operator answers and GitHub updates can resume the task later. If the run fails, return status "failed" and taskCompleted null.`;
1919
1904
  function githubInstructions(githubAvailable) {
1920
1905
  return `${githubAvailable ? "Git and the gh CLI are authenticated in this sandbox. Use them for the GitHub operations called for by the task, including pushing branches and opening or updating pull requests. Reuse an open pull request for the same work. To resolve conflicts or catch up with the base branch, inspect the existing pull request, update its current head branch, and push to that branch. Open a new pull request when the task calls for a separate one or there is no applicable open pull request." : "GitHub credentials are unavailable in this sandbox. If publication is needed, report what could not be published."}
@@ -1956,6 +1941,7 @@ Use the project name and repository list below to identify where this task belon
1956
1941
  }
1957
1942
  function prompt(task, repositories, githubAvailable, project) {
1958
1943
  return `Complete the operator\u2019s task inside the Docker Sandbox. The initial repository checkouts are listed below. Read and follow the applicable repository AGENTS.md files. Validate your work using the real project tools and summarize the results.
1944
+ Each repository starts with a sparse checkout of its top-level files. When you need its full working tree, run git sparse-checkout disable in that repository. Read any nested AGENTS.md files before working in the newly available directories.
1959
1945
  ${projectInstructions(project)}
1960
1946
 
1961
1947
  ${completionInstructions}
@@ -2044,10 +2030,10 @@ var Sandbox = class {
2044
2030
  return this.command(["exec", ...flags, "-w", workspace, this.name, ...args], { ...options, signal });
2045
2031
  }
2046
2032
  async prepare(repository, signal) {
2047
- await this.exec(["mkdir", "-p", posix2.dirname(repository.sandboxDir)], signal);
2033
+ await this.exec(["mkdir", "-p", posix3.dirname(repository.sandboxDir)], signal);
2048
2034
  await chmod(repository.workBundle, 420);
2049
2035
  await this.command(["cp", repository.workBundle, `${this.name}:${repository.sandboxBundle}`], { signal });
2050
- await this.exec(["env", "GIT_LFS_SKIP_SMUDGE=1", "git", "clone", "--quiet", "--no-tags", "--", repository.sandboxBundle, repository.sandboxDir], signal);
2036
+ await this.exec(["env", "GIT_LFS_SKIP_SMUDGE=1", "git", "clone", "--quiet", "--no-tags", "--sparse", "--", repository.sandboxBundle, repository.sandboxDir], signal);
2051
2037
  await this.exec(["rm", repository.sandboxBundle], signal);
2052
2038
  await this.exec(["git", "-C", repository.sandboxDir, "remote", "set-url", "origin", repository.url], signal);
2053
2039
  }
@@ -2093,95 +2079,28 @@ var Sandbox = class {
2093
2079
  await this.setGithubNetwork("allow", signal);
2094
2080
  await this.exec(["gh", "auth", "setup-git", "--hostname", "github.com"], signal, { discardOutput: true });
2095
2081
  }
2096
- async selectRepositories(task, candidates, settings, signal, project, images, artifacts) {
2097
- const schemaPath = "/tmp/agentseil-selection-schema.json";
2098
- const resultPath = "/tmp/agentseil-selection-result.json";
2099
- await this.exec(["sh", "-c", 'umask 077; cat > "$1"', "sh", schemaPath], signal, { input: JSON.stringify(repositorySelectionOutputSchema) });
2100
- const imagePaths = [];
2101
- try {
2102
- for (const { data, mediaType } of images) {
2103
- const path = `/tmp/agentseil-selection-${randomUUID3()}.${mediaType.split("/")[1]}`;
2104
- imagePaths.push(path);
2105
- await this.exec(["sh", "-c", 'umask 077; base64 -d > "$1"', "sh", path], signal, { input: data });
2106
- }
2107
- await this.exec([
2108
- "codex",
2109
- "exec",
2110
- "--dangerously-bypass-approvals-and-sandbox",
2111
- "--skip-git-repo-check",
2112
- ...imagePaths.map((path) => `--image=${path}`),
2113
- "--output-schema",
2114
- schemaPath,
2115
- "--output-last-message",
2116
- resultPath,
2117
- ...settings.model ? [`--model=${settings.model}`] : [],
2118
- ...settings.reasoningEffort ? ["-c", `model_reasoning_effort="${settings.reasoningEffort}"`] : [],
2119
- ...settings.serviceTier ? ["-c", `service_tier="${settings.serviceTier}"`] : [],
2120
- "-"
2121
- ], signal, { input: repositorySelectionPrompt(task, candidates, project, artifacts), discardOutput: true });
2122
- const output = await this.exec(["cat", resultPath], signal, { stdoutLimit: 12 * 1024 * 1024 });
2123
- return validateRepositorySelection(JSON.parse(output), candidates, project?.primaryRepository ?? void 0);
2124
- } finally {
2125
- if (imagePaths.length) {
2126
- await this.exec(["rm", "-f", "--", ...imagePaths], AbortSignal.timeout(1e4)).catch(() => void 0);
2127
- }
2128
- }
2129
- }
2130
- imageTool(cwd, signal, postImage) {
2131
- return {
2132
- name: "attach_task_image",
2133
- description: "Attach a local PNG, JPEG, WebP or GIF image up to 1 MiB to the Agentseil task chat.",
2134
- inputSchema: {
2135
- type: "object",
2136
- additionalProperties: false,
2137
- required: ["path"],
2138
- properties: {
2139
- path: { type: "string", description: "Absolute path in the Docker Sandbox, or a path relative to the Codex working directory." },
2140
- caption: { type: "string", description: "Optional caption displayed with the image." }
2141
- }
2142
- },
2143
- execute: async (arguments_) => {
2144
- const input = imageToolInput.safeParse(arguments_);
2145
- if (!input.success)
2146
- throw new CodexToolError("Provide an image path and an optional caption up to 4000 characters.");
2147
- const path = posix2.resolve(cwd, input.data.path);
2148
- const deadline = AbortSignal.any([signal, AbortSignal.timeout(1e4)]);
2149
- let data;
2150
- try {
2151
- data = await this.exec([
2152
- "sh",
2153
- "-c",
2154
- 'test -f "$1" && head -c "$2" -- "$1" | base64 -w 0',
2155
- "sh",
2156
- path,
2157
- String(maxImageBytes + 1)
2158
- ], deadline, { stdoutLimit: maxImageBase64Length });
2159
- } catch {
2160
- throw new CodexToolError("The sandbox image could not be read.");
2161
- }
2162
- const image = imageUploadSchema.safeParse({
2163
- name: posix2.basename(path),
2164
- mediaType: detectImageMediaType(data),
2165
- data
2166
- });
2167
- if (!image.success)
2168
- throw new CodexToolError("Provide a PNG, JPEG, WebP or GIF file up to 1 MiB.");
2169
- await postImage(image.data, input.data.caption ?? "");
2170
- return "The image was attached to the Agentseil task chat.";
2171
- }
2172
- };
2173
- }
2174
2082
  async stageArtifact(gateway, { taskId, ...claim }, reference, signal) {
2175
2083
  const deadline = AbortSignal.any([signal, AbortSignal.timeout(2e4)]);
2176
2084
  const { content: content3, format } = await retryGatewayRequest((requestSignal2) => gateway.getArtifact(taskId, reference.id, claim, requestSignal2), deadline);
2177
- const path = (await this.exec(["sh", "-c", 'file=$(mktemp /tmp/agentseil-artifact.XXXXXXXX) && cat > "$file" && chmod 400 "$file" && printf "%s" "$file"'], deadline, { input: content3, stdoutLimit: 256 })).trim();
2178
- if (!/^\/tmp\/agentseil-artifact\.[a-zA-Z0-9]{8}$/.test(path))
2085
+ const extension = format === "image" ? detectImageMediaType(content3)?.split("/")[1] : { markdown: "md", html: "html", text: "txt" }[format];
2086
+ if (!extension)
2087
+ throw new Error("The published image Artifact has an unknown format");
2088
+ const path = (await this.exec([
2089
+ "sh",
2090
+ "-c",
2091
+ 'file=$(mktemp --suffix=".$1" /tmp/agentseil-artifact.XXXXXXXX) && (if [ "$2" = image ]; then base64 -d; else cat; fi) > "$file" && chmod 400 "$file" && printf "%s" "$file"',
2092
+ "sh",
2093
+ extension,
2094
+ format
2095
+ ], deadline, { input: content3, stdoutLimit: 256 })).trim();
2096
+ if (!/^\/tmp\/agentseil-artifact\.[a-zA-Z0-9]{8}\.[a-z]+$/.test(path))
2179
2097
  throw new Error("Could not stage the artifact in the sandbox");
2180
2098
  return { ...reference, format, path };
2181
2099
  }
2182
- async readArtifactFile(path, signal) {
2100
+ async readArtifactFile(path, format, signal) {
2101
+ let encoded;
2183
2102
  try {
2184
- const encoded = await this.exec([
2103
+ encoded = await this.exec([
2185
2104
  "sh",
2186
2105
  "-c",
2187
2106
  'test -f "$1" && head -c "$2" -- "$1" | base64 -w 0',
@@ -2189,9 +2108,17 @@ var Sandbox = class {
2189
2108
  path,
2190
2109
  String(maxArtifactBytes + 1)
2191
2110
  ], signal, { stdoutLimit: Math.ceil((maxArtifactBytes + 1) / 3) * 4 });
2111
+ } catch {
2112
+ throw new CodexToolError("Could not read the artifact file in the sandbox.");
2113
+ }
2114
+ if (Buffer.byteLength(encoded, "base64") > maxArtifactBytes)
2115
+ throw new CodexToolError("Provide an artifact file up to 5 MiB.");
2116
+ if (format === "image")
2117
+ return encoded;
2118
+ try {
2192
2119
  return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(Buffer.from(encoded, "base64"));
2193
2120
  } catch {
2194
- throw new CodexToolError("Could not read the UTF-8 artifact file in the sandbox.");
2121
+ throw new CodexToolError("Provide a UTF-8 artifact file.");
2195
2122
  }
2196
2123
  }
2197
2124
  async run(instructions, settings, gateway, lease, signal, report, options) {
@@ -2221,7 +2148,7 @@ var Sandbox = class {
2221
2148
  schema: lazyOutputSchema,
2222
2149
  parseResult: (text) => lazyResultSchema.parse(JSON.parse(text))
2223
2150
  } : void 0,
2224
- startSession: async (onMessage, onActivity, postImage) => {
2151
+ startSession: async (onMessage, onActivity) => {
2225
2152
  await report("codex-start", followUp ? "Codex \u3092\u8D77\u52D5\u3057\u3001\u4F5C\u696D\u30B9\u30EC\u30C3\u30C9\u3092\u5FA9\u5143\u3057\u3066\u3044\u307E\u3059\u3002" : "\u4F5C\u696D\u7528\u306E Codex \u3092\u8D77\u52D5\u3057\u3066\u3044\u307E\u3059\u3002");
2226
2153
  const session = await startCodexSession({
2227
2154
  ...appServer(cwd),
@@ -2234,8 +2161,7 @@ var Sandbox = class {
2234
2161
  tools: [
2235
2162
  relatedIssueTool(gateway, lease, signal),
2236
2163
  decisionTool(gateway, lease, signal),
2237
- this.imageTool(cwd, signal, postImage),
2238
- ...artifactTools(gateway, lease, signal, (path, requestSignal2) => this.readArtifactFile(posix2.resolve(cwd, path), requestSignal2))
2164
+ ...artifactTools(gateway, lease, signal, (path, format, requestSignal2) => this.readArtifactFile(posix3.resolve(cwd, path), format, requestSignal2), followUp)
2239
2165
  ]
2240
2166
  });
2241
2167
  sessionId = session.id;
@@ -2276,13 +2202,22 @@ async function removeArchivedSandbox(name, signal) {
2276
2202
  throw error;
2277
2203
  }
2278
2204
  }
2279
- async function executeTask({ task, candidateRepositories, claimToken, project, resume, lazyEvents }, { githubToken, commitIdentity, ...codexSettings }, gateway, signal) {
2205
+ async function stopIdleSandbox(name) {
2206
+ const sandbox = new Sandbox(name);
2207
+ try {
2208
+ await sandbox.stop();
2209
+ } catch (error) {
2210
+ if (await sandbox.exists(AbortSignal.timeout(1e4)))
2211
+ throw error;
2212
+ }
2213
+ }
2214
+ async function executeTask({ task, candidateRepositories, claimToken, project, resume, lazyEvents, deferSandboxStop }, { githubToken, commitIdentity, sandboxIdleMinutes, ...codexSettings }, gateway, signal) {
2280
2215
  const claim = { farmId: task.farmId, claimToken };
2281
2216
  const lease = { taskId: task.id, ...claim };
2282
2217
  const sandbox = new Sandbox(task.sandboxName, resume !== void 0);
2283
2218
  let ownsSandbox = false;
2284
2219
  let temporaryDir;
2285
- let selectedRepositories;
2220
+ let checkedOutRepositories;
2286
2221
  let checkpoint;
2287
2222
  let unreportedTitle;
2288
2223
  let tokenUsage;
@@ -2310,16 +2245,17 @@ async function executeTask({ task, candidateRepositories, claimToken, project, r
2310
2245
  signal.throwIfAborted();
2311
2246
  if (lazyEvents?.length && !resume)
2312
2247
  throw new Error("GitHub updates require the retained Codex thread");
2313
- const checkoutCandidates = task.repositories.length ? task.repositories : candidateRepositories;
2248
+ const checkoutNames = task.repositories.length ? task.repositories : candidateRepositories;
2249
+ if (!resume && !checkoutNames.length)
2250
+ throw new Error("No verified repositories are available for this assignment");
2314
2251
  const primaryName = project?.primaryRepository?.toLowerCase();
2315
- const primary = primaryName ? checkoutCandidates.find((repository) => repository.toLowerCase() === primaryName) : void 0;
2252
+ const primary = primaryName ? checkoutNames.find((repository) => repository.toLowerCase() === primaryName) : void 0;
2316
2253
  if (primaryName && !primary)
2317
2254
  throw new Error("The project primary repository is unavailable for this assignment");
2318
2255
  if (primary)
2319
2256
  hostedRepository(primary);
2320
2257
  const images = resume ? [] : await loadTaskImages(gateway, lease, task.images ?? [], signal);
2321
2258
  let artifacts = [];
2322
- const stageInitialArtifacts = () => Promise.all((task.artifacts ?? []).map((reference) => sandbox.stageArtifact(gateway, lease, reference, signal)));
2323
2259
  if (resume) {
2324
2260
  await report("sandbox-resume", "\u4FDD\u5B58\u6E08\u307F\u306E sbx \u3068\u4F5C\u696D\u74B0\u5883\u3092\u78BA\u8A8D\u3057\u3066\u3044\u307E\u3059\u3002");
2325
2261
  if (!await sandbox.exists(signal)) {
@@ -2330,40 +2266,28 @@ async function executeTask({ task, candidateRepositories, claimToken, project, r
2330
2266
  await sandbox.revokeGithubAccess();
2331
2267
  }
2332
2268
  const identity = await resolveCommitIdentity(commitIdentity, githubToken, signal);
2333
- if (!resume && !task.repositories.length) {
2334
- if (!candidateRepositories.length)
2335
- throw new Error("No verified repositories are available for selection on this farm.");
2336
- await createSandbox();
2337
- artifacts = await stageInitialArtifacts();
2338
- await report("repository-select", `${candidateRepositories.length} \u4EF6\u306E\u5019\u88DC\u304B\u3089\u4F5C\u696D\u5BFE\u8C61\u306E\u30EA\u30DD\u30B8\u30C8\u30EA\u3092\u9078\u629E\u3057\u3066\u3044\u307E\u3059\u3002`);
2339
- selectedRepositories = await sandbox.selectRepositories(task, candidateRepositories, codexSettings, signal, project, images, artifacts);
2340
- const names = selectedRepositories.join("\u3001");
2341
- const displayNames = names.length > 3800 ? `${names.slice(0, 3800)}\u2026` : names;
2342
- await report("repository-selected", `${selectedRepositories.length} \u4EF6\u306E\u30EA\u30DD\u30B8\u30C8\u30EA\u3092\u9078\u629E\u3057\u307E\u3057\u305F\u3002 ${displayNames}`);
2343
- }
2344
2269
  const repositories = [];
2345
2270
  if (!resume) {
2271
+ await createSandbox();
2272
+ artifacts = await Promise.all((task.artifacts ?? []).map((reference) => sandbox.stageArtifact(gateway, lease, reference, signal)));
2346
2273
  temporaryDir = await mkdtemp(join2(tmpdir(), "agentseil-"));
2347
- const names = selectedRepositories ?? task.repositories;
2348
- for (const [index, name] of names.entries()) {
2349
- await report("repository-clone", `${name} \u3092\u30AF\u30ED\u30FC\u30F3\u3057\u3066\u3044\u307E\u3059\uFF08${index + 1}/${names.length}\uFF09\u3002`);
2274
+ for (const [index, name] of checkoutNames.entries()) {
2275
+ await report("repository-clone", `${name} \u3092\u30AF\u30ED\u30FC\u30F3\u3057\u3066\u3044\u307E\u3059\uFF08${index + 1}/${checkoutNames.length}\uFF09\u3002`);
2350
2276
  const remote = githubRemote(name, githubToken);
2351
2277
  repositories.push(await prepareRepository(name, index, temporaryDir, remote, signal));
2352
2278
  }
2353
2279
  signal.throwIfAborted();
2354
- if (!ownsSandbox) {
2355
- await createSandbox();
2356
- artifacts = await stageInitialArtifacts();
2357
- }
2358
2280
  for (const [index, repository] of repositories.entries()) {
2359
- await report("sandbox-checkout", `${repository.name} \u3092 sbx \u306B\u5C55\u958B\u3057\u3066\u3044\u307E\u3059\uFF08${index + 1}/${repositories.length}\uFF09\u3002`);
2281
+ await report("sandbox-checkout", `${repository.name} \u3092 sbx \u306B\u758E\u30C1\u30A7\u30C3\u30AF\u30A2\u30A6\u30C8\u3057\u3066\u3044\u307E\u3059\uFF08${index + 1}/${repositories.length}\uFF09\u3002`);
2360
2282
  await sandbox.prepare(repository, signal);
2361
2283
  await sandbox.setCommitIdentity(repository.sandboxDir, identity, signal);
2362
2284
  }
2285
+ if (!task.repositories.length)
2286
+ checkedOutRepositories = checkoutNames;
2363
2287
  } else {
2364
- for (const name of checkoutCandidates) {
2288
+ for (const name of checkoutNames) {
2365
2289
  hostedRepository(name);
2366
- await sandbox.setCommitIdentity(posix2.join(workspace, name), identity, signal);
2290
+ await sandbox.setCommitIdentity(posix3.join(workspace, name), identity, signal);
2367
2291
  }
2368
2292
  }
2369
2293
  if (githubToken) {
@@ -2373,7 +2297,7 @@ async function executeTask({ task, candidateRepositories, claimToken, project, r
2373
2297
  const githubAvailable = githubToken !== null;
2374
2298
  const instructions = resume ? followUpPrompt(task, githubAvailable, project) : prompt(task, repositories, githubAvailable, project);
2375
2299
  const { response, threadId } = await sandbox.run(instructions, codexSettings, gateway, lease, signal, report, {
2376
- cwd: primary ? posix2.join(workspace, primary) : workspace,
2300
+ cwd: primary ? posix3.join(workspace, primary) : workspace,
2377
2301
  threadId: resume?.threadId,
2378
2302
  lazyEvents,
2379
2303
  images,
@@ -2402,18 +2326,22 @@ async function executeTask({ task, candidateRepositories, claimToken, project, r
2402
2326
  result = { status: "failed", summary: errorMessage(error), pullRequests: [] };
2403
2327
  }
2404
2328
  if (ownsSandbox) {
2329
+ let githubAccessRevoked = false;
2405
2330
  try {
2406
2331
  await sandbox.revokeGithubAccess();
2332
+ githubAccessRevoked = true;
2407
2333
  } catch (error) {
2408
2334
  result.summary = `${result.summary}
2409
2335
 
2410
2336
  GitHub cleanup failed: ${errorMessage(error)}`.slice(0, 4e3);
2411
2337
  }
2412
2338
  try {
2413
- if (resume || checkpoint)
2414
- await sandbox.stop();
2415
- else
2339
+ if (!resume && !checkpoint)
2416
2340
  await sandbox.remove();
2341
+ else if (deferSandboxStop && githubAccessRevoked && !signal.aborted)
2342
+ result.sandboxIdleMinutes = sandboxIdleMinutes;
2343
+ else
2344
+ await sandbox.stop();
2417
2345
  } catch (error) {
2418
2346
  result.summary = `${result.summary}
2419
2347
 
@@ -2428,7 +2356,7 @@ Temporary files cleanup failed: ${errorMessage(error)}`.slice(0, 4e3);
2428
2356
  });
2429
2357
  return {
2430
2358
  ...result,
2431
- ...selectedRepositories ? { selectedRepositories } : {},
2359
+ ...checkedOutRepositories ? { selectedRepositories: checkedOutRepositories } : {},
2432
2360
  ...checkpoint !== void 0 ? { resume: checkpoint } : {},
2433
2361
  ...unreportedTitle ? { generatedTitle: unreportedTitle } : {},
2434
2362
  ...tokenUsage ? { tokenUsage } : {}
@@ -2469,6 +2397,8 @@ async function pollFarmGitHub(gateway, farmId, token, githubLogin, pollMs, signa
2469
2397
  var requestTimeout = 1e4;
2470
2398
  var retryDelay = 2e3;
2471
2399
  var maxChecksOnce = 50;
2400
+ var idleStopPollMs = 15e3;
2401
+ var sandboxCleanupFetchAttempts = 3;
2472
2402
  function permanent(error) {
2473
2403
  return error instanceof GatewayError && error.status >= 400 && error.status < 500 && error.status !== 429;
2474
2404
  }
@@ -2509,7 +2439,7 @@ async function pollRepositoryConnections(gateway, config, shutdown) {
2509
2439
  async function cleanupArchivedSandboxes(gateway, { farmId }, shutdown, activeSandboxes) {
2510
2440
  let sandboxNames;
2511
2441
  try {
2512
- sandboxNames = await gateway.pendingSandboxCleanup({ farmId }, requestSignal(shutdown));
2442
+ sandboxNames = await retryGatewayRequest((signal) => gateway.pendingSandboxCleanup({ farmId }, signal), shutdown, sandboxCleanupFetchAttempts);
2513
2443
  } catch (error) {
2514
2444
  if (shutdown.aborted || error instanceof GatewayError && error.status === 404)
2515
2445
  return true;
@@ -2540,6 +2470,41 @@ async function pollSandboxCleanup(gateway, config, shutdown, activeSandboxes) {
2540
2470
  await sleep4(config.pollMs, void 0, { signal: shutdown }).catch(() => void 0);
2541
2471
  }
2542
2472
  }
2473
+ async function stopNextIdleSandbox(gateway, farmId, polling) {
2474
+ if (polling.aborted)
2475
+ return true;
2476
+ let job;
2477
+ try {
2478
+ job = await gateway.claimIdleSandboxStop({ farmId }, requestSignal(polling));
2479
+ } catch (error) {
2480
+ if (polling.aborted || error instanceof GatewayError && error.status === 404)
2481
+ return true;
2482
+ console.error(`Could not claim an idle sandbox stop: ${errorMessage(error)}`);
2483
+ return false;
2484
+ }
2485
+ if (!job)
2486
+ return true;
2487
+ let stopped = false;
2488
+ try {
2489
+ await stopIdleSandbox(job.sandboxName);
2490
+ stopped = true;
2491
+ } catch (error) {
2492
+ console.error(`Could not stop idle sandbox ${job.sandboxName}: ${errorMessage(error)}`);
2493
+ }
2494
+ try {
2495
+ await gateway.completeIdleSandboxStop({ farmId, ...job, stopped }, requestSignal());
2496
+ } catch (error) {
2497
+ console.error(`Could not report idle sandbox stop for ${job.sandboxName}: ${errorMessage(error)}`);
2498
+ return false;
2499
+ }
2500
+ return stopped;
2501
+ }
2502
+ async function pollIdleSandboxStops(gateway, farmId, polling) {
2503
+ while (!polling.aborted) {
2504
+ await stopNextIdleSandbox(gateway, farmId, polling);
2505
+ await sleep4(idleStopPollMs, void 0, { signal: polling }).catch(() => void 0);
2506
+ }
2507
+ }
2543
2508
  async function refreshAssignmentSettings(gateway, { taskId, ...lease }, signal) {
2544
2509
  while (true) {
2545
2510
  signal.throwIfAborted();
@@ -2601,7 +2566,12 @@ async function handleAssignment(assignment, gateway, config, shutdown) {
2601
2566
  serviceTier: task.codexSettings?.serviceTier ?? codexDefaults.serviceTier ?? void 0
2602
2567
  };
2603
2568
  console.log(`Running task ${task.id} in ${task.sandboxName}`);
2604
- result = await executeTask(assignment, { ...codexSettings, githubToken: config.githubToken, commitIdentity }, gateway, executionSignal);
2569
+ result = await executeTask(assignment, {
2570
+ ...codexSettings,
2571
+ githubToken: config.githubToken,
2572
+ commitIdentity,
2573
+ sandboxIdleMinutes: config.sandboxIdleMinutes
2574
+ }, gateway, executionSignal);
2605
2575
  } catch (error) {
2606
2576
  result = { status: "failed", summary: errorMessage(error), pullRequests: [] };
2607
2577
  }
@@ -2699,18 +2669,20 @@ async function serveFarm(gateway, config, shutdown, lifecycle = {}) {
2699
2669
  const activeSandboxes = /* @__PURE__ */ new Set();
2700
2670
  if (lifecycle.once) {
2701
2671
  const cleaned = await cleanupArchivedSandboxes(gateway, config, shutdown, activeSandboxes);
2702
- return await pollTasks(gateway, config, shutdown, shutdown, activeSandboxes, lifecycle) && cleaned;
2672
+ const stopped = await stopNextIdleSandbox(gateway, config.farmId, shutdown);
2673
+ return await pollTasks(gateway, config, shutdown, shutdown, activeSandboxes, lifecycle) && cleaned && stopped;
2703
2674
  }
2704
2675
  const stopPolling = new AbortController();
2705
2676
  const pollSignal = AbortSignal.any([shutdown, stopPolling.signal, ...lifecycle.drain ? [lifecycle.drain] : []]);
2706
2677
  const verifier = pollRepositoryConnections(gateway, config, pollSignal);
2707
2678
  const cleanup = pollSandboxCleanup(gateway, config, pollSignal, activeSandboxes);
2679
+ const idleStops = pollIdleSandboxStops(gateway, config.farmId, pollSignal);
2708
2680
  const github = pollFarmGitHub(gateway, config.farmId, config.githubToken, config.githubLogin, config.pollMs, pollSignal);
2709
2681
  try {
2710
2682
  return await pollTasks(gateway, config, shutdown, pollSignal, activeSandboxes, lifecycle);
2711
2683
  } finally {
2712
2684
  stopPolling.abort();
2713
- await Promise.all([verifier, cleanup, github]);
2685
+ await Promise.all([verifier, cleanup, idleStops, github]);
2714
2686
  }
2715
2687
  }
2716
2688
 
@@ -2777,14 +2749,15 @@ Environment:
2777
2749
  AGENTSEIL_FARM_TOKEN Shared token for authenticating to the Gateway
2778
2750
  AGENTSEIL_GITHUB_TOKEN GitHub PAT override (empty for public repositories)
2779
2751
  AGENTSEIL_CODEX_MODEL Fallback model when the task and Gateway do not specify one
2780
- AGENTSEIL_POLL_MS Poll interval in milliseconds (default 2000)`;
2752
+ AGENTSEIL_POLL_MS Poll interval in milliseconds (default 2000)
2753
+ AGENTSEIL_SANDBOX_IDLE_MINUTES Minutes before stopping a retained sandbox (default ${DEFAULT_SANDBOX_IDLE_MINUTES})`;
2781
2754
  var pkg = cliPackage(import.meta.url);
2782
2755
  var program = new Command("agentseil-farm").description("Run Gateway assignments concurrently in separate Docker Sandboxes.").version(pkg.version, "-v, --version").addHelpText("after", `
2783
2756
  Examples:
2784
2757
  agentseil-farm --gateway-url https://gateway.example.com
2785
2758
  agentseil-farm serve --once
2786
2759
  ${environment}`);
2787
- program.command("serve", { isDefault: true }).description("Run the Farm (default).").option("--gateway-url <url>", "Override AGENTSEIL_GATEWAY_URL for this run.").option("--once", "Check up to 50 pending repositories as needed and claim at most one task.").addHelpText("after", "\nOn Linux and macOS, send SIGUSR2 to the Farm PID to finish active tasks and exit.").action((options) => runFarm(options));
2760
+ program.command("serve", { isDefault: true }).description("Run the Farm (default).").option("--gateway-url <url>", "Override AGENTSEIL_GATEWAY_URL for this run.").option("--sandbox-idle-minutes <minutes>", "Minutes before stopping a retained sandbox. Overrides AGENTSEIL_SANDBOX_IDLE_MINUTES.").option("--once", "Check up to 50 pending repositories as needed and claim at most one task.").addHelpText("after", "\nOn Linux and macOS, send SIGUSR2 to the Farm PID to finish active tasks and exit.").action((options) => runFarm(options));
2788
2761
  program.command("configure").description("Set or clear the GitHub PAT in the OS credential store.").action(() => runFarm());
2789
2762
  program.command("self-update").description("Fetch the latest Farm package from npm.").action(() => pkg.selfUpdate());
2790
2763
  async function runFarm(options) {
@@ -2797,6 +2770,7 @@ async function runFarm(options) {
2797
2770
  const pollMs = Number(process.env.AGENTSEIL_POLL_MS ?? "2000");
2798
2771
  if (!Number.isInteger(pollMs) || pollMs < 250 || pollMs > 6e4)
2799
2772
  throw new Error("AGENTSEIL_POLL_MS must be an integer from 250 to 60000");
2773
+ const sandboxIdleMinutes = options ? parseSandboxIdleMinutes(options.sandboxIdleMinutes) : DEFAULT_SANDBOX_IDLE_MINUTES;
2800
2774
  const model = process.env.AGENTSEIL_CODEX_MODEL || void 0;
2801
2775
  const stop = new AbortController();
2802
2776
  const drain = new AbortController();
@@ -2818,7 +2792,7 @@ async function runFarm(options) {
2818
2792
  console.log(credentials.githubLogin ? `GitHub account: @${credentials.githubLogin}` : "GitHub PAT cleared.");
2819
2793
  return;
2820
2794
  }
2821
- const success = await serveFarm(gateway, { farmId, pollMs, model, ...credentials }, stop.signal, {
2795
+ const success = await serveFarm(gateway, { farmId, pollMs, sandboxIdleMinutes, model, ...credentials }, stop.signal, {
2822
2796
  once,
2823
2797
  drain: drain.signal,
2824
2798
  onReady: once ? void 0 : () => console.log(`Farm ${farmId} ${pkg.version} is ready (PID ${process.pid})`)
@@ -2835,6 +2809,16 @@ async function runFarm(options) {
2835
2809
  process.off("SIGTERM", onShutdown);
2836
2810
  }
2837
2811
  }
2812
+ function parseSandboxIdleMinutes(override) {
2813
+ const value = override ?? process.env.AGENTSEIL_SANDBOX_IDLE_MINUTES;
2814
+ if (value === void 0)
2815
+ return DEFAULT_SANDBOX_IDLE_MINUTES;
2816
+ const minutes = sandboxIdleMinutesSchema.safeParse(/^\d+$/.test(value.trim()) ? Number(value) : NaN);
2817
+ if (minutes.success)
2818
+ return minutes.data;
2819
+ const source = override === void 0 ? "AGENTSEIL_SANDBOX_IDLE_MINUTES" : "--sandbox-idle-minutes";
2820
+ throw new Error(`${source} must be a non-negative whole number of minutes`);
2821
+ }
2838
2822
  function createGatewayClient(override) {
2839
2823
  const value = override ?? process.env.AGENTSEIL_GATEWAY_URL ?? DEFAULT_GATEWAY_URL;
2840
2824
  const source = override === void 0 ? "AGENTSEIL_GATEWAY_URL" : "--gateway-url";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanoseil/agentseil-farm",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "agentseil-farm": "./dist/main.js"