@fitlab-ai/agent-infra 0.9.5 → 0.9.7

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 (172) hide show
  1. package/dist/bin/internal-cli.js +8 -3
  2. package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +171 -20
  3. package/dist/lib/agent-clients/adapters/codex-lifecycle/build-identity.js +162 -0
  4. package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +244 -0
  5. package/dist/lib/agent-clients/adapters/codex-lifecycle/evidence.js +14 -2
  6. package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +370 -0
  7. package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +68 -8
  8. package/dist/lib/agent-clients/adapters/codex.js +1 -1
  9. package/dist/lib/defaults.json +10 -2
  10. package/dist/lib/git/workflow.js +30 -4
  11. package/dist/lib/internal/codex-lifecycle.js +169 -3
  12. package/dist/lib/internal/codex-sandbox-controller.js +106 -0
  13. package/dist/lib/internal/release-workflow.js +108 -11
  14. package/dist/lib/internal/sandbox-control.js +43 -6
  15. package/dist/lib/internal/task-create.js +12 -4
  16. package/dist/lib/internal/task-orchestration.js +40 -7
  17. package/dist/lib/platform/context.js +6 -4
  18. package/dist/lib/platform/github-client.js +55 -2
  19. package/dist/lib/platform/issue-comments.js +2 -1
  20. package/dist/lib/process-data/checkpoint.js +319 -0
  21. package/dist/lib/process-data/index.js +128 -60
  22. package/dist/lib/process-data/materialize.js +84 -0
  23. package/dist/lib/process-data/normalize.js +34 -1
  24. package/dist/lib/process-data/reconcile.js +55 -1
  25. package/dist/lib/process-data/sources.js +422 -1
  26. package/dist/lib/process-data/store.js +341 -11
  27. package/dist/lib/release/workflow.js +29 -21
  28. package/dist/lib/sandbox/commands/create.js +111 -60
  29. package/dist/lib/sandbox/commands/prune.js +40 -16
  30. package/dist/lib/sandbox/commands/rm.js +372 -94
  31. package/dist/lib/sandbox/commands/start.js +4 -3
  32. package/dist/lib/sandbox/control/client.js +138 -22
  33. package/dist/lib/sandbox/control/container-identity.js +64 -0
  34. package/dist/lib/sandbox/control/executor.js +142 -0
  35. package/dist/lib/sandbox/control/lifecycle.js +557 -0
  36. package/dist/lib/sandbox/control/protocol.js +69 -26
  37. package/dist/lib/sandbox/control/server.js +395 -99
  38. package/dist/lib/sandbox/control/state.js +191 -0
  39. package/dist/lib/sandbox/control/timing.js +8 -0
  40. package/dist/lib/sandbox/index.js +2 -2
  41. package/dist/lib/sandbox/managed-fs.js +14 -2
  42. package/dist/lib/sandbox/mounts.js +22 -19
  43. package/dist/lib/sandbox/recovery.js +284 -50
  44. package/dist/lib/sandbox/workspace-view.js +90 -10
  45. package/dist/lib/sandbox/worktree-safety.js +196 -0
  46. package/dist/lib/server/daemon.js +1 -1
  47. package/dist/lib/server/process-control.js +17 -1
  48. package/dist/lib/server/process-state.js +57 -20
  49. package/dist/lib/task/artifact-lifecycle.js +87 -15
  50. package/dist/lib/task/artifact-receipts.js +128 -0
  51. package/dist/lib/task/codex-orchestration.js +236 -0
  52. package/dist/lib/task/commands/status.js +3 -0
  53. package/dist/lib/task/commands/validate.js +289 -0
  54. package/dist/lib/task/commit-finalization.js +36 -9
  55. package/dist/lib/task/create.js +10 -2
  56. package/dist/lib/task/delegation-receipts.js +109 -2
  57. package/dist/lib/task/events.js +149 -6
  58. package/dist/lib/task/finalization-artifacts.js +2 -1
  59. package/dist/lib/task/implementation-inputs.js +1 -7
  60. package/dist/lib/task/index.js +9 -0
  61. package/dist/lib/task/ledger.js +13 -1
  62. package/dist/lib/task/orchestration.js +365 -15
  63. package/dist/lib/task/sections.js +5 -1
  64. package/dist/lib/task/task-execution-lock.js +5 -4
  65. package/dist/lib/task/verification-engine.js +78 -14
  66. package/dist/lib/task/verification.js +1 -0
  67. package/dist/lifecycle-build-manifest.json +6 -0
  68. package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +202 -18
  69. package/lib/agent-clients/adapters/codex-lifecycle/build-identity.ts +227 -0
  70. package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +321 -0
  71. package/lib/agent-clients/adapters/codex-lifecycle/evidence.ts +19 -3
  72. package/lib/agent-clients/adapters/codex-lifecycle/manifest-files.json +26 -0
  73. package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +453 -0
  74. package/lib/agent-clients/adapters/codex-lifecycle/store.ts +83 -6
  75. package/lib/agent-clients/adapters/codex.ts +1 -1
  76. package/lib/defaults.json +10 -2
  77. package/lib/git/workflow.ts +25 -3
  78. package/lib/internal/codex-lifecycle.ts +175 -4
  79. package/lib/internal/codex-sandbox-controller.ts +109 -0
  80. package/lib/internal/release-workflow.ts +107 -11
  81. package/lib/internal/sandbox-control.ts +38 -6
  82. package/lib/internal/task-create.ts +16 -4
  83. package/lib/internal/task-orchestration.ts +34 -7
  84. package/lib/platform/context.ts +8 -5
  85. package/lib/platform/github-client.ts +61 -3
  86. package/lib/platform/issue-comments.ts +2 -1
  87. package/lib/process-data/checkpoint.ts +335 -0
  88. package/lib/process-data/index.ts +112 -60
  89. package/lib/process-data/materialize.ts +83 -0
  90. package/lib/process-data/normalize.ts +29 -1
  91. package/lib/process-data/reconcile.ts +64 -2
  92. package/lib/process-data/sources.ts +449 -2
  93. package/lib/process-data/store.ts +304 -11
  94. package/lib/process-data/types.ts +124 -2
  95. package/lib/release/workflow.ts +69 -20
  96. package/lib/sandbox/commands/create.ts +70 -25
  97. package/lib/sandbox/commands/prune.ts +53 -15
  98. package/lib/sandbox/commands/rm.ts +423 -108
  99. package/lib/sandbox/commands/start.ts +4 -3
  100. package/lib/sandbox/control/client.ts +152 -28
  101. package/lib/sandbox/control/container-identity.ts +93 -0
  102. package/lib/sandbox/control/executor.ts +167 -0
  103. package/lib/sandbox/control/lifecycle.ts +573 -0
  104. package/lib/sandbox/control/protocol.ts +121 -68
  105. package/lib/sandbox/control/server.ts +398 -109
  106. package/lib/sandbox/control/state.ts +213 -0
  107. package/lib/sandbox/control/timing.ts +12 -0
  108. package/lib/sandbox/index.ts +2 -2
  109. package/lib/sandbox/managed-fs.ts +17 -2
  110. package/lib/sandbox/mounts.ts +16 -8
  111. package/lib/sandbox/recovery.ts +335 -65
  112. package/lib/sandbox/workspace-view.ts +102 -11
  113. package/lib/sandbox/worktree-safety.ts +234 -0
  114. package/lib/server/daemon.ts +1 -1
  115. package/lib/server/process-control.ts +24 -3
  116. package/lib/server/process-state.ts +82 -27
  117. package/lib/task/artifact-lifecycle.ts +78 -14
  118. package/lib/task/artifact-receipts.ts +161 -0
  119. package/lib/task/codex-orchestration.ts +319 -0
  120. package/lib/task/commands/status.ts +2 -0
  121. package/lib/task/commands/validate.ts +282 -0
  122. package/lib/task/commit-finalization.ts +52 -9
  123. package/lib/task/create.ts +11 -2
  124. package/lib/task/delegation-receipts.ts +208 -7
  125. package/lib/task/events.ts +131 -5
  126. package/lib/task/finalization-artifacts.ts +2 -1
  127. package/lib/task/implementation-inputs.ts +1 -5
  128. package/lib/task/index.ts +8 -0
  129. package/lib/task/ledger.ts +16 -1
  130. package/lib/task/orchestration.ts +552 -18
  131. package/lib/task/sections.ts +6 -2
  132. package/lib/task/task-execution-lock.ts +11 -9
  133. package/lib/task/verification-engine.ts +93 -24
  134. package/lib/task/verification.ts +2 -1
  135. package/package.json +1 -1
  136. package/templates/.agents/README.en.md +7 -0
  137. package/templates/.agents/README.zh-CN.md +5 -0
  138. package/templates/.agents/hooks/lifecycle-delegation.js +72 -12
  139. package/templates/.agents/rules/lifecycle-orchestration.en.md +8 -2
  140. package/templates/.agents/rules/lifecycle-orchestration.zh-CN.md +8 -2
  141. package/templates/.agents/rules/no-mid-flow-questions.en.md +1 -0
  142. package/templates/.agents/rules/no-mid-flow-questions.zh-CN.md +1 -0
  143. package/templates/.agents/rules/pr-checks-commands.github.en.md +1 -1
  144. package/templates/.agents/rules/pr-checks-commands.github.zh-CN.md +1 -1
  145. package/templates/.agents/rules/review-handshake.en.md +3 -1
  146. package/templates/.agents/rules/review-handshake.zh-CN.md +3 -1
  147. package/templates/.agents/skills/code-task/reference/dual-mode.en.md +3 -1
  148. package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +3 -1
  149. package/templates/.agents/skills/complete-task/SKILL.en.md +4 -0
  150. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +4 -0
  151. package/templates/.agents/skills/post-release/SKILL.en.md +32 -6
  152. package/templates/.agents/skills/post-release/SKILL.zh-CN.md +32 -6
  153. package/templates/.agents/skills/run-manual-validation/SKILL.en.md +42 -0
  154. package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +42 -0
  155. package/templates/.agents/skills/run-manual-validation/config/verify.en.json +25 -0
  156. package/templates/.agents/skills/run-manual-validation/config/verify.zh-CN.json +25 -0
  157. package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.en.md +67 -0
  158. package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.zh-CN.md +67 -0
  159. package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +69 -0
  160. package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +69 -0
  161. package/templates/.agents/skills/run-task/SKILL.en.md +9 -7
  162. package/templates/.agents/skills/run-task/SKILL.zh-CN.md +9 -7
  163. package/templates/.agents/skills/run-task/reference/host-validation.en.md +5 -3
  164. package/templates/.agents/skills/run-task/reference/host-validation.zh-CN.md +5 -3
  165. package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +75 -3
  166. package/templates/.claude/commands/run-manual-validation.en.md +9 -0
  167. package/templates/.claude/commands/run-manual-validation.zh-CN.md +9 -0
  168. package/templates/.codex/hooks.json +8 -8
  169. package/templates/.opencode/commands/run-manual-validation.en.md +11 -0
  170. package/templates/.opencode/commands/run-manual-validation.zh-CN.md +11 -0
  171. package/templates/.agents/workspace/README.en.md +0 -26
  172. package/templates/.agents/workspace/README.zh-CN.md +0 -26
@@ -17,9 +17,9 @@ const USAGE = `Usage: ai sandbox start [--recreate] <branch | TASK-id | N>
17
17
 
18
18
  Start an existing sandbox container that has stopped (for example after the
19
19
  Docker daemon was restarted or replaced). The container must already exist:
20
- if none is found, run 'ai sandbox create <branch>' first. A container that is
21
- already running is checked without modifying healthy runtime state. --recreate
22
- allows container-only replacement after in-place recovery fails.`;
20
+ if none is found, run 'ai sandbox create <branch>' first. Without --recreate, a
21
+ container that is already running is checked without modifying healthy runtime
22
+ state. --recreate replaces the existing container even when it is healthy.`;
23
23
 
24
24
  export function parseStartArgs(args: string[]): { target: string; recreate: boolean; help: boolean } {
25
25
  let recreate = false;
@@ -83,6 +83,7 @@ export async function start(args: string[]): Promise<void> {
83
83
  workspace: target.workspace,
84
84
  row: found,
85
85
  allowRecreate: parsed.recreate,
86
+ forceRecreate: parsed.recreate,
86
87
  recreate: async () => {
87
88
  const { create } = await import('./create.ts');
88
89
  await create([target.requestedRef, '--no-refresh']);
@@ -2,26 +2,91 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import {
5
+ SANDBOX_CONTROL_ADMISSION_WINDOW_MS,
5
6
  SANDBOX_CONTROL_MAX_BYTES,
7
+ SANDBOX_CONTROL_STATUS_STALE_MS,
6
8
  isSandboxControlFamily,
9
+ type SandboxControlError,
7
10
  type SandboxControlRequest,
8
11
  type SandboxControlResponse,
9
12
  type SandboxTaskCreateRequest
10
13
  } from './protocol.ts';
14
+ import { readSandboxControlStatus } from './state.ts';
11
15
  import type { TaskCreateCandidateV1 } from '../../task/create.ts';
12
16
 
17
+ const SANDBOX_CONTROL_RESPONSE_SETTLE_MS = 250;
18
+
19
+ export class SandboxControlClientError extends Error {
20
+ readonly detail: SandboxControlError;
21
+ readonly accepted: boolean;
22
+ constructor(detail: SandboxControlError, accepted = false) {
23
+ super(detail.message);
24
+ this.name = 'SandboxControlClientError';
25
+ this.detail = detail;
26
+ this.accepted = accepted;
27
+ }
28
+ }
29
+
13
30
  function sleep(milliseconds: number): void {
14
31
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
15
32
  }
16
33
 
34
+ function clientError(code: string, message: string, retryable: boolean, accepted = false): never {
35
+ throw new SandboxControlClientError({ code, message: `${code}: ${message}`, retryable }, accepted);
36
+ }
37
+
38
+ function preflight(statusDir: string, generation: string, now = Date.now()): void {
39
+ let status;
40
+ try {
41
+ status = readSandboxControlStatus(statusDir);
42
+ } catch {
43
+ clientError('SANDBOX_CONTROL_BROKER_UNAVAILABLE', 'broker status is missing or invalid', true);
44
+ }
45
+ if (status.generation !== generation) {
46
+ clientError('SANDBOX_CONTROL_GENERATION_INVALID', 'broker status generation does not match this sandbox', false);
47
+ }
48
+ if (now - status.updatedAt > SANDBOX_CONTROL_STATUS_STALE_MS || status.updatedAt > now + 1_000) {
49
+ clientError('SANDBOX_CONTROL_BROKER_UNAVAILABLE', 'broker status heartbeat is stale', true);
50
+ }
51
+ if (status.state === 'busy') clientError('SANDBOX_CONTROL_BUSY', 'broker is executing another request', true);
52
+ if (status.state === 'parked') {
53
+ const code = status.reasonCode ?? 'SANDBOX_CONTROL_BROKER_UNAVAILABLE';
54
+ clientError(code, 'broker is parked until the host restores a valid binding', true);
55
+ }
56
+ if (status.state !== 'healthy') clientError('SANDBOX_CONTROL_BROKER_UNAVAILABLE', 'broker is not ready', true);
57
+ }
58
+
59
+ function parseResponse(raw: string, id: string): SandboxControlResponse {
60
+ const response = JSON.parse(raw) as SandboxControlResponse;
61
+ if (response.version !== 2 || response.id !== id
62
+ || !['accepted', 'completed', 'rejected'].includes(response.phase)
63
+ || (response.phase === 'completed' && !Number.isInteger(response.exitCode))) {
64
+ clientError('SANDBOX_CONTROL_RESPONSE_INVALID', 'broker response is invalid', false);
65
+ }
66
+ return response;
67
+ }
68
+
69
+ function cancelPendingRequest(requestPath: string): boolean {
70
+ try {
71
+ fs.unlinkSync(requestPath);
72
+ return true;
73
+ } catch (error) {
74
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
75
+ throw error;
76
+ }
77
+ }
78
+
17
79
  function exchangeSandboxControl(request: SandboxControlRequest, params: Readonly<{
18
80
  channelDir?: string;
81
+ statusDir?: string;
19
82
  timeoutMs?: number;
20
83
  }>): SandboxControlResponse {
21
84
  const channelDir = params.channelDir ?? process.env.AGENT_INFRA_CONTROL_DIR ?? '/run/agent-infra/control';
85
+ const statusDir = params.statusDir ?? process.env.AGENT_INFRA_CONTROL_STATUS_DIR ?? '/run/agent-infra/control-status';
86
+ preflight(statusDir, request.generation);
22
87
  const encoded = `${JSON.stringify(request)}\n`;
23
88
  if (Buffer.byteLength(encoded, 'utf8') > SANDBOX_CONTROL_MAX_BYTES) {
24
- throw new Error('SANDBOX_CONTROL_REQUEST_TOO_LARGE: request exceeds the control limit');
89
+ clientError('SANDBOX_CONTROL_REQUEST_TOO_LARGE', 'request exceeds the control limit', false);
25
90
  }
26
91
  const requestsDir = path.join(channelDir, 'requests');
27
92
  const responsesDir = path.join(channelDir, 'responses');
@@ -31,49 +96,108 @@ function exchangeSandboxControl(request: SandboxControlRequest, params: Readonly
31
96
  fs.writeFileSync(temporary, encoded, { mode: 0o600, flag: 'wx' });
32
97
  fs.renameSync(temporary, requestPath);
33
98
  const deadline = Date.now() + (params.timeoutMs ?? 30_000);
99
+ let accepted = false;
100
+ let malformedResponseRaw: string | null = null;
101
+ let malformedResponseObservedAt = 0;
34
102
  while (Date.now() < deadline) {
35
103
  if (fs.existsSync(responsePath)) {
36
- const raw = fs.readFileSync(responsePath, 'utf8');
37
- fs.unlinkSync(responsePath);
38
- const response = JSON.parse(raw) as SandboxControlResponse;
39
- if (response.version !== 1 || response.id !== request.id || !Number.isInteger(response.exitCode)) {
40
- throw new Error('SANDBOX_CONTROL_RESPONSE_INVALID: broker response is invalid');
104
+ let raw: string;
105
+ try {
106
+ raw = fs.readFileSync(responsePath, 'utf8');
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
109
+ throw error;
110
+ }
111
+ let response: SandboxControlResponse;
112
+ try {
113
+ response = parseResponse(raw, request.id);
114
+ malformedResponseRaw = null;
115
+ } catch (error) {
116
+ if (!(error instanceof SyntaxError)) throw error;
117
+ const now = Date.now();
118
+ if (malformedResponseRaw !== raw) {
119
+ malformedResponseRaw = raw;
120
+ malformedResponseObservedAt = now;
121
+ } else if (now - malformedResponseObservedAt >= SANDBOX_CONTROL_RESPONSE_SETTLE_MS) {
122
+ clientError('SANDBOX_CONTROL_RESPONSE_INVALID', 'broker response remained malformed', false, accepted);
123
+ }
124
+ sleep(25);
125
+ continue;
126
+ }
127
+ if (response.phase === 'accepted') {
128
+ accepted = true;
129
+ } else {
130
+ fs.rmSync(responsePath, { force: true });
131
+ return response;
132
+ }
133
+ }
134
+ if (!accepted) {
135
+ try {
136
+ preflight(statusDir, request.generation);
137
+ } catch (error) {
138
+ if (cancelPendingRequest(requestPath)) throw error;
139
+ clientError(
140
+ 'SANDBOX_CONTROL_RESULT_UNKNOWN',
141
+ 'request was claimed before broker availability was lost; inspect domain state before retrying',
142
+ false,
143
+ true
144
+ );
41
145
  }
42
- return response;
43
146
  }
44
147
  sleep(25);
45
148
  }
46
- throw new Error(`SANDBOX_CONTROL_TIMEOUT: broker did not respond within ${params.timeoutMs ?? 30_000}ms`);
149
+ if (accepted) {
150
+ clientError(
151
+ 'SANDBOX_CONTROL_RESULT_UNKNOWN',
152
+ 'accepted request did not produce a final result; inspect domain state before retrying',
153
+ false,
154
+ true
155
+ );
156
+ }
157
+ if (!cancelPendingRequest(requestPath)) {
158
+ clientError(
159
+ 'SANDBOX_CONTROL_RESULT_UNKNOWN',
160
+ 'request was claimed but no acceptance result was observed; inspect domain state before retrying',
161
+ false,
162
+ true
163
+ );
164
+ }
165
+ clientError('SANDBOX_CONTROL_BROKER_UNAVAILABLE', `broker did not accept the request within ${params.timeoutMs ?? 30_000}ms`, true);
166
+ }
167
+
168
+ function authority(params: { token?: string; generation?: string }): { token: string; generation: string } {
169
+ const token = params.token ?? process.env.AGENT_INFRA_CONTROL_TOKEN;
170
+ const generation = params.generation ?? process.env.AGENT_INFRA_CONTROL_GENERATION;
171
+ if (!token || !generation) clientError('SANDBOX_CONTROL_UNAVAILABLE', 'control authority is missing', false);
172
+ return { token, generation };
47
173
  }
48
174
 
49
175
  export function requestSandboxControl(params: Readonly<{
50
- family: string;
51
- args: string[];
52
- channelDir?: string;
53
- token?: string;
54
- timeoutMs?: number;
176
+ family: string; args: string[]; channelDir?: string; statusDir?: string;
177
+ token?: string; generation?: string; timeoutMs?: number;
55
178
  }>): SandboxControlResponse {
56
- if (!isSandboxControlFamily(params.family)) {
57
- throw new Error(`SANDBOX_CONTROL_COMMAND_DENIED: '${params.family}' is not allowed`);
58
- }
59
- if (params.family === 'task-create') throw new Error("SANDBOX_CONTROL_COMMAND_DENIED: 'task-create' requires a typed candidate");
60
- const token = params.token ?? process.env.AGENT_INFRA_CONTROL_TOKEN;
61
- if (!token) throw new Error('SANDBOX_CONTROL_UNAVAILABLE: control token is missing');
62
- const id = randomUUID();
63
- const request: SandboxControlRequest = { version: 1, id, token, family: params.family, args: params.args };
179
+ if (!isSandboxControlFamily(params.family)) clientError('SANDBOX_CONTROL_COMMAND_DENIED', `'${params.family}' is not allowed`, false);
180
+ if (params.family === 'task-create') clientError('SANDBOX_CONTROL_COMMAND_DENIED', "'task-create' requires a typed candidate", false);
181
+ const auth = authority(params);
182
+ const issuedAt = Date.now();
183
+ const request: SandboxControlRequest = {
184
+ version: 2, id: randomUUID(), ...auth, issuedAt,
185
+ expiresAt: issuedAt + SANDBOX_CONTROL_ADMISSION_WINDOW_MS,
186
+ family: params.family, args: params.args
187
+ };
64
188
  return exchangeSandboxControl(request, params);
65
189
  }
66
190
 
67
191
  export function requestSandboxTaskCreate(params: Readonly<{
68
- candidate: TaskCreateCandidateV1;
69
- channelDir?: string;
70
- token?: string;
71
- timeoutMs?: number;
192
+ candidate: TaskCreateCandidateV1; channelDir?: string; statusDir?: string;
193
+ token?: string; generation?: string; timeoutMs?: number;
72
194
  }>): SandboxControlResponse {
73
- const token = params.token ?? process.env.AGENT_INFRA_CONTROL_TOKEN;
74
- if (!token) throw new Error('SANDBOX_CONTROL_UNAVAILABLE: control token is missing');
195
+ const auth = authority(params);
196
+ const issuedAt = Date.now();
75
197
  const request: SandboxTaskCreateRequest = {
76
- version: 1, id: randomUUID(), token, family: 'task-create', candidate: params.candidate
198
+ version: 2, id: randomUUID(), ...auth, issuedAt,
199
+ expiresAt: issuedAt + SANDBOX_CONTROL_ADMISSION_WINDOW_MS,
200
+ family: 'task-create', candidate: params.candidate
77
201
  };
78
202
  return exchangeSandboxControl(request, { ...params, timeoutMs: params.timeoutMs ?? 120_000 });
79
203
  }
@@ -0,0 +1,93 @@
1
+ import type { SandboxControlManifest } from './protocol.ts';
2
+ import { commandForEngine, runEngine, runProbe } from '../shell.ts';
3
+
4
+ export type ContainerObservation =
5
+ | Readonly<{ state: 'found'; id: string; running: boolean; labels: Readonly<Record<string, string>> }>
6
+ | Readonly<{ state: 'absent'; id: string }>
7
+ | Readonly<{ state: 'unknown'; reason: string }>;
8
+
9
+ export type ContainerInspection = Readonly<{
10
+ id?: unknown;
11
+ running?: unknown;
12
+ labels?: unknown;
13
+ }>;
14
+
15
+ function isAuthoritativeNotFound(error: unknown): boolean {
16
+ const message = error instanceof Error ? error.message : String(error);
17
+ return /(?:no such container|container .* not found|cannot find container)/i.test(message);
18
+ }
19
+
20
+ export function classifySandboxContainerInspection(
21
+ expected: SandboxControlManifest['containerIdentity'],
22
+ inspection: ContainerInspection | { notFound: true } | { error: unknown }
23
+ ): ContainerObservation {
24
+ if ('notFound' in inspection) return { state: 'absent', id: expected.id };
25
+ if ('error' in inspection) {
26
+ return isAuthoritativeNotFound(inspection.error)
27
+ ? { state: 'absent', id: expected.id }
28
+ : { state: 'unknown', reason: `container inspection failed: ${inspection.error instanceof Error ? inspection.error.message : String(inspection.error)}` };
29
+ }
30
+ const response = inspection as ContainerInspection;
31
+ if (typeof response.id !== 'string' || response.id !== expected.id
32
+ || typeof response.running !== 'boolean' || !response.labels
33
+ || typeof response.labels !== 'object' || Array.isArray(response.labels)) {
34
+ return { state: 'unknown', reason: 'container inspection response is incomplete' };
35
+ }
36
+ const labels = response.labels as Record<string, unknown>;
37
+ for (const [key, value] of Object.entries(expected.labels)) {
38
+ if (labels[key] !== value) return { state: 'unknown', reason: 'container labels do not match the manifest' };
39
+ }
40
+ return {
41
+ state: 'found',
42
+ id: response.id,
43
+ running: response.running,
44
+ labels: Object.fromEntries(
45
+ Object.entries(labels).flatMap(([key, value]) => typeof value === 'string' ? [[key, value]] : [])
46
+ )
47
+ };
48
+ }
49
+
50
+ export async function inspectSandboxControlContainer(
51
+ manifest: SandboxControlManifest,
52
+ options: { run?: typeof runEngine; probe?: typeof runProbe; timeoutMs?: number } = {}
53
+ ): Promise<ContainerObservation> {
54
+ try {
55
+ const args = ['inspect', '--format', '{{json .}}', manifest.containerIdentity.id];
56
+ let raw: string;
57
+ if (options.run) {
58
+ raw = options.run(manifest.engine, 'docker', args, options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs });
59
+ } else {
60
+ const command = commandForEngine(manifest.engine, 'docker', args);
61
+ const result = (options.probe ?? runProbe)(
62
+ command.cmd,
63
+ command.args,
64
+ options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs }
65
+ );
66
+ if (result.status !== 0) {
67
+ const stderr = typeof result.stderr === 'string' ? result.stderr : result.stderr?.toString('utf8') ?? '';
68
+ return classifySandboxContainerInspection(manifest.containerIdentity, {
69
+ error: new Error(stderr || `container inspection exited with ${result.status ?? 'unknown'}`)
70
+ });
71
+ }
72
+ raw = typeof result.stdout === 'string' ? result.stdout : result.stdout?.toString('utf8') ?? '';
73
+ }
74
+ const parsed = JSON.parse(raw) as {
75
+ Id?: unknown;
76
+ State?: { Running?: unknown };
77
+ Config?: { Labels?: unknown };
78
+ } | Array<{
79
+ Id?: unknown;
80
+ State?: { Running?: unknown };
81
+ Config?: { Labels?: unknown };
82
+ }>;
83
+ const value = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
84
+ if (!value || Array.isArray(value)) return { state: 'unknown', reason: 'container inspection response is incomplete' };
85
+ return classifySandboxContainerInspection(manifest.containerIdentity, {
86
+ id: value.Id,
87
+ running: value.State?.Running,
88
+ labels: value.Config?.Labels
89
+ });
90
+ } catch (error) {
91
+ return classifySandboxContainerInspection(manifest.containerIdentity, { error });
92
+ }
93
+ }
@@ -0,0 +1,167 @@
1
+ import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { getProcessStartTime } from '../../server/process-state.ts';
6
+ import { createTask } from '../../task/create-service.ts';
7
+ import { bindSandboxControlTask, type SandboxControlExecution, type SandboxControlManifest, type SandboxControlRequest } from './protocol.ts';
8
+ import { atomicWriteJson, executionPath, terminateSandboxControlExecution } from './state.ts';
9
+
10
+ export type SandboxControlExecutionResult = {
11
+ exitCode: number;
12
+ stdout: string;
13
+ stderr: string;
14
+ };
15
+
16
+ export type PreparedSandboxControlExecution = {
17
+ execution: SandboxControlExecution;
18
+ start(canWrite?: () => boolean): void;
19
+ completion: Promise<SandboxControlExecutionResult>;
20
+ terminate(updateState?: boolean): boolean;
21
+ };
22
+
23
+ function safeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
24
+ return Object.fromEntries(Object.entries(env).filter(([key]) => !key.toUpperCase().startsWith('AGENT_INFRA_CONTROL_')));
25
+ }
26
+
27
+ export function nodeEntryArgs(entry: string, args: string[]): string[] {
28
+ return path.extname(entry) === '.ts'
29
+ ? ['--experimental-strip-types', '--no-warnings', entry, ...args]
30
+ : [entry, ...args];
31
+ }
32
+
33
+ async function waitForStartTime(pid: number, timeoutMs = 2_000): Promise<number> {
34
+ const deadline = Date.now() + timeoutMs;
35
+ while (Date.now() < deadline) {
36
+ const startTime = getProcessStartTime(pid);
37
+ if (startTime !== null) return startTime;
38
+ await new Promise<void>((resolve) => setTimeout(resolve, 10));
39
+ }
40
+ throw new Error('SANDBOX_CONTROL_EXECUTOR_IDENTITY_UNAVAILABLE');
41
+ }
42
+
43
+ export async function prepareSandboxControlExecution(params: {
44
+ manifest: SandboxControlManifest;
45
+ manifestPath: string;
46
+ request: SandboxControlRequest;
47
+ requestPath: string;
48
+ internalCliPath: string;
49
+ }): Promise<PreparedSandboxControlExecution> {
50
+ const nonce = randomUUID();
51
+ const child = spawn(
52
+ process.execPath,
53
+ nodeEntryArgs(params.internalCliPath, [
54
+ 'sandbox-control', 'execute', '--request', params.requestPath, '--nonce', nonce
55
+ ]),
56
+ {
57
+ cwd: params.manifest.repoRoot,
58
+ detached: process.platform !== 'win32',
59
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
60
+ env: { ...safeEnv(process.env), AGENT_INFRA_EXECUTOR_MANIFEST: params.manifestPath }
61
+ }
62
+ );
63
+ if (typeof child.pid !== 'number') throw new Error('SANDBOX_CONTROL_EXECUTOR_SPAWN_FAILED');
64
+ let stdout = '';
65
+ let stderr = '';
66
+ child.stdout?.setEncoding('utf8');
67
+ child.stderr?.setEncoding('utf8');
68
+ child.stdout?.on('data', (chunk: string) => { stdout += chunk; });
69
+ child.stderr?.on('data', (chunk: string) => { stderr += chunk; });
70
+ const completion = new Promise<SandboxControlExecutionResult>((resolve, reject) => {
71
+ child.once('error', reject);
72
+ child.once('close', (code) => resolve({ exitCode: code ?? 1, stdout, stderr }));
73
+ });
74
+ const startTime = await waitForStartTime(child.pid);
75
+ const execution: SandboxControlExecution = {
76
+ version: 2,
77
+ generation: params.manifest.generation,
78
+ requestId: params.request.id,
79
+ nonce,
80
+ child: {
81
+ pid: child.pid,
82
+ startTime,
83
+ processGroupId: process.platform === 'win32' ? null : child.pid
84
+ },
85
+ phase: 'prepared',
86
+ updatedAt: Date.now()
87
+ };
88
+ atomicWriteJson(executionPath(params.manifest, params.request.id), execution);
89
+ return {
90
+ execution,
91
+ start(canWrite = () => true) {
92
+ if (!child.connected) throw new Error('SANDBOX_CONTROL_EXECUTOR_GATE_CLOSED');
93
+ if (!canWrite()) throw new Error('SANDBOX_CONTROL_OWNER_LOST');
94
+ atomicWriteJson(executionPath(params.manifest, params.request.id), { ...execution, phase: 'running', updatedAt: Date.now() });
95
+ if (!canWrite()) throw new Error('SANDBOX_CONTROL_OWNER_LOST');
96
+ child.send({ version: 1, nonce });
97
+ },
98
+ completion,
99
+ terminate(updateState = true) {
100
+ if (updateState) {
101
+ atomicWriteJson(executionPath(params.manifest, params.request.id), {
102
+ ...execution, phase: 'terminating', updatedAt: Date.now()
103
+ });
104
+ }
105
+ return terminateSandboxControlExecution(execution);
106
+ }
107
+ };
108
+ }
109
+
110
+ function waitForGate(nonce: string, timeoutMs = 2_000): Promise<void> {
111
+ return new Promise((resolve, reject) => {
112
+ const timer = setTimeout(() => reject(new Error('SANDBOX_CONTROL_EXECUTOR_GATE_TIMEOUT')), timeoutMs);
113
+ const onDisconnect = () => {
114
+ clearTimeout(timer);
115
+ reject(new Error('SANDBOX_CONTROL_EXECUTOR_GATE_CLOSED'));
116
+ };
117
+ process.once('disconnect', onDisconnect);
118
+ process.once('message', (message: unknown) => {
119
+ clearTimeout(timer);
120
+ process.off('disconnect', onDisconnect);
121
+ const value = message as { version?: unknown; nonce?: unknown } | null;
122
+ if (!value || value.version !== 1 || value.nonce !== nonce) {
123
+ reject(new Error('SANDBOX_CONTROL_EXECUTOR_GATE_INVALID'));
124
+ return;
125
+ }
126
+ resolve();
127
+ });
128
+ });
129
+ }
130
+
131
+ function executeRequest(manifest: SandboxControlManifest, request: SandboxControlRequest): SandboxControlExecutionResult {
132
+ if (request.family === 'task-create') {
133
+ const result = createTask(request.candidate, { repoRoot: manifest.repoRoot });
134
+ return {
135
+ exitCode: result.status === 'blocked' ? 2 : result.status === 'failed' ? 1 : 0,
136
+ stdout: `${JSON.stringify(result)}\n`,
137
+ stderr: ''
138
+ };
139
+ }
140
+ const boundArgs = bindSandboxControlTask(request, manifest.taskId!);
141
+ if (request.family === 'task-orchestration') boundArgs.push('--git-worktree-root', manifest.worktreeRoot);
142
+ const result = spawnSync(
143
+ process.execPath,
144
+ nodeEntryArgs(process.argv[1]!, [request.family, ...boundArgs]),
145
+ { cwd: manifest.repoRoot, encoding: 'utf8', env: safeEnv(process.env) }
146
+ );
147
+ return { exitCode: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
148
+ }
149
+
150
+ export async function runSandboxControlExecutor(requestPath: string, nonce: string): Promise<void> {
151
+ await waitForGate(nonce);
152
+ process.disconnect?.();
153
+ const root = fs.realpathSync.native(process.cwd());
154
+ const request = JSON.parse(fs.readFileSync(requestPath, 'utf8')) as SandboxControlRequest;
155
+ const manifestPath = process.env.AGENT_INFRA_EXECUTOR_MANIFEST;
156
+ if (!manifestPath) throw new Error('SANDBOX_CONTROL_EXECUTOR_MANIFEST_MISSING');
157
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as SandboxControlManifest;
158
+ if (fs.realpathSync.native(manifest.repoRoot) !== root) throw new Error('SANDBOX_CONTROL_EXECUTOR_ROOT_INVALID');
159
+ const result = executeRequest(manifest, request);
160
+ process.stdout.write(result.stdout);
161
+ process.stderr.write(result.stderr);
162
+ process.exitCode = result.exitCode;
163
+ }
164
+
165
+ export function disconnectExecutor(child: ChildProcess): void {
166
+ if (child.connected) child.disconnect();
167
+ }