@jmanuelcorral/bond-app 0.1.3 → 0.1.5

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 (40) hide show
  1. package/README.md +41 -1
  2. package/app/mods/bond-agents/config.js +4 -0
  3. package/app/mods/bond-agents/main.js +10 -5
  4. package/app/mods/bond-agents/model.js +52 -4
  5. package/app/mods/bond-board/config.js +4 -0
  6. package/app/mods/bond-board/main.js +555 -84
  7. package/app/mods/bond-board/model.js +115 -2
  8. package/app/mods/bond-settings/config.js +4 -0
  9. package/app/mods/bond-settings/main.js +689 -12
  10. package/app/mods/bond-settings/pi-models.js +144 -0
  11. package/app/mods/bond-status/config.js +4 -0
  12. package/app/mods/bond-titlebar/main.js +63 -46
  13. package/package.json +1 -1
  14. package/runner/Dockerfile +42 -13
  15. package/runner/SPIKE-BOND.md +85 -0
  16. package/runner/build-config/.none +0 -0
  17. package/runner/build-creds/.none +0 -0
  18. package/runner/config.example/README.md +27 -0
  19. package/runner/config.example/pi/models.json +22 -0
  20. package/runner/credentials.example.env +27 -0
  21. package/runner/setup.sh +496 -0
  22. package/runner/versions.env +30 -0
  23. package/scripts/app-install.ts +38 -7
  24. package/src/config.ts +11 -0
  25. package/src/core/delivery.ts +61 -7
  26. package/src/core/hub-session.ts +154 -17
  27. package/src/core/hub.ts +55 -20
  28. package/src/core/orchestrator.ts +844 -200
  29. package/src/core/setup.ts +178 -0
  30. package/src/core/watchdog.ts +2 -2
  31. package/src/db/database.ts +14 -0
  32. package/src/db/run-repo.ts +8 -1
  33. package/src/db/settings-repo.ts +108 -0
  34. package/src/db/ticket-repo.ts +34 -4
  35. package/src/runner/docker-client.ts +42 -0
  36. package/src/runner/github-client.ts +126 -2
  37. package/src/runner/hc-client.ts +67 -9
  38. package/src/runner/image-builder.ts +146 -6
  39. package/src/server/app.ts +263 -36
  40. package/src/types.ts +40 -0
@@ -190,6 +190,9 @@ export class HcClient {
190
190
  labels?: Record<string, string>;
191
191
  foreground?: { name?: string };
192
192
  };
193
+ const rawAgent = (res as any).agent || res.name || res.foreground?.name;
194
+ const isGeneric = rawAgent === 'agent' || (typeof rawAgent === 'string' && /^t\d+$/.test(rawAgent));
195
+ const agent = isGeneric ? undefined : rawAgent;
193
196
  return {
194
197
  address,
195
198
  name: res.name,
@@ -199,16 +202,49 @@ export class HcClient {
199
202
  exit_code: res.exit_code ?? null,
200
203
  turn: typeof res.turn === 'number' ? res.turn : 0,
201
204
  labels: res.labels ?? {},
202
- agent: res.name || res.foreground?.name,
205
+ agent,
203
206
  };
204
207
  }
205
208
 
206
209
  /**
207
210
  * P9: List live terminals across machines, or only terminals on a specific machine.
208
211
  */
209
- async listTerminals(machine?: string): Promise<Array<{ address: string; name?: string; cwd?: string; state?: string; turn?: number }>> {
210
- const res = (await this.call(['ls', '--json'])) as { terminals?: Array<{ address: string; name?: string; cwd?: string; state?: string; turn?: number }> };
211
- const all = res.terminals ?? [];
212
+ async listTerminals(machine?: string): Promise<Array<{
213
+ address: string;
214
+ name?: string;
215
+ cwd?: string;
216
+ state?: string;
217
+ status?: unknown;
218
+ exit_code?: number | null;
219
+ turn?: number;
220
+ labels?: Record<string, string>;
221
+ agent?: string;
222
+ }>> {
223
+ const res = (await this.call(['ls', '--json'])) as {
224
+ terminals?: Array<{
225
+ address: string;
226
+ name?: string;
227
+ cwd?: string;
228
+ state?: string;
229
+ status?: unknown;
230
+ exit_code?: number | null;
231
+ turn?: number;
232
+ labels?: Record<string, string>;
233
+ agent?: string;
234
+ foreground?: { name?: string };
235
+ }>;
236
+ };
237
+ const all = (res.terminals ?? []).map((t) => ({
238
+ address: t.address,
239
+ name: t.name,
240
+ cwd: t.cwd,
241
+ state: t.state,
242
+ status: t.status,
243
+ exit_code: t.exit_code,
244
+ turn: t.turn,
245
+ labels: t.labels,
246
+ agent: t.agent || t.foreground?.name,
247
+ }));
212
248
  if (!machine) return all;
213
249
  const prefix = `${machine}/`;
214
250
  return all.filter((t) => t.address.startsWith(prefix) || t.address === machine);
@@ -217,23 +253,45 @@ export class HcClient {
217
253
  /**
218
254
  * P9: Query all terminals of a machine with full details (labels, status, turn)
219
255
  * directly from hc, with NO docker exec.
256
+ * P1 criterion 3: obtains state from `hc ls --json` without N+1 `hc get` per terminal,
257
+ * falling back to `getTerminal` only if the data is missing from ls.
220
258
  */
221
259
  async getMachineTerminals(machine: string): Promise<HcTerminalDetails[]> {
222
260
  const listed = await this.listTerminals(machine);
223
261
  const details = await Promise.all(
224
262
  listed.map(async (t) => {
263
+ const hasStatus = t.status !== undefined;
264
+ const hasLabels = t.labels !== undefined && typeof t.labels === 'object' && t.labels !== null;
265
+ if (hasStatus && hasLabels) {
266
+ return {
267
+ address: t.address,
268
+ name: t.name,
269
+ cwd: t.cwd,
270
+ state: t.state ?? null,
271
+ status: agentStatusOf(t.status),
272
+ exit_code: t.exit_code ?? null,
273
+ turn: typeof t.turn === 'number' ? t.turn : 0,
274
+ labels: t.labels,
275
+ agent: t.agent || t.name,
276
+ };
277
+ }
225
278
  try {
226
- return await this.getTerminal(t.address);
279
+ const detail = await this.getTerminal(t.address);
280
+ return {
281
+ ...detail,
282
+ agent: detail.agent && detail.agent !== 'agent' ? detail.agent : (t.agent || t.name),
283
+ };
227
284
  } catch {
228
285
  return {
229
286
  address: t.address,
230
287
  name: t.name,
231
288
  cwd: t.cwd,
232
289
  state: t.state ?? null,
233
- status: null,
234
- exit_code: null,
235
- turn: t.turn ?? 0,
236
- labels: {},
290
+ status: t.status !== undefined ? agentStatusOf(t.status) : null,
291
+ exit_code: t.exit_code ?? null,
292
+ turn: typeof t.turn === 'number' ? t.turn : 0,
293
+ labels: t.labels ?? {},
294
+ agent: t.agent || t.name,
237
295
  };
238
296
  }
239
297
  })
@@ -1,5 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
+ import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
5
6
 
@@ -29,6 +30,26 @@ export interface RunnerVersions {
29
30
  pi?: string;
30
31
  }
31
32
 
33
+ /**
34
+ * Image plan P2: what a rebuild bakes besides versions. `agents` is the setup.sh agent
35
+ * list (default ['pi'], parity with the current image). `config_dir` and `credentials_file`
36
+ * are absolute paths that must live inside `data_dir` (validated: no traversal, no
37
+ * symlink escape); they get staged into the build context for the duration of the build.
38
+ */
39
+ export interface RunnerBuildOptions extends RunnerVersions {
40
+ agents?: string[];
41
+ /** System CLIs (setup.sh --skip-gh / --skip-az); az is heavy and rarely needed. */
42
+ skip_az?: boolean;
43
+ skip_gh?: boolean;
44
+ config_dir?: string;
45
+ credentials_file?: string;
46
+ /** Root the staged paths must resolve inside of (the orchestrator injects its data dir). */
47
+ data_dir?: string;
48
+ }
49
+
50
+ /** The agent list runner/setup.sh accepts (kept in sync; setup.sh is still the judge). */
51
+ export const RUNNER_AGENT_NAMES = ['pi', 'claude', 'codex', 'copilot', 'agy'] as const;
52
+
32
53
  export class InvalidVersionError extends Error {
33
54
  constructor(message: string) {
34
55
  super(message);
@@ -36,6 +57,14 @@ export class InvalidVersionError extends Error {
36
57
  }
37
58
  }
38
59
 
60
+ /** P2 (image plan): bad agents/config_dir/credentials_file; the server maps it to 400. */
61
+ export class InvalidBuildOptionsError extends Error {
62
+ constructor(message: string) {
63
+ super(message);
64
+ this.name = 'InvalidBuildOptionsError';
65
+ }
66
+ }
67
+
39
68
  /** Sanitized build failure: the message never carries docker's stderr. */
40
69
  export class RunnerBuildError extends Error {
41
70
  constructor(message: string) {
@@ -57,16 +86,115 @@ export type DockerExec = (
57
86
  options: Record<string, unknown>
58
87
  ) => Promise<unknown>;
59
88
 
89
+ /** Validate the agent list: non-empty array of known names, no duplicates. */
90
+ export function validateRunnerAgents(agents: unknown): string[] {
91
+ if (!Array.isArray(agents) || agents.length === 0) {
92
+ throw new InvalidBuildOptionsError("'agents' must be a non-empty array of agent names");
93
+ }
94
+ const out: string[] = [];
95
+ for (const a of agents) {
96
+ if (typeof a !== 'string' || !a) {
97
+ throw new InvalidBuildOptionsError("'agents' must contain non-empty strings");
98
+ }
99
+ if (!(RUNNER_AGENT_NAMES as readonly string[]).includes(a)) {
100
+ throw new InvalidBuildOptionsError(
101
+ `unsupported agent '${a}': setup.sh installs ${RUNNER_AGENT_NAMES.join(', ')}`
102
+ );
103
+ }
104
+ if (out.includes(a)) {
105
+ throw new InvalidBuildOptionsError(`duplicate agent in 'agents': '${a}'`);
106
+ }
107
+ out.push(a);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * A staged path (config_dir / credentials_file) must be absolute and resolve — following
114
+ * symlinks — inside data_dir. Rejects traversal ('..') and symlink escape (V).
115
+ */
116
+ function assertInsideDataDir(p: string, dataDir: string, label: string): string {
117
+ if (!path.isAbsolute(p)) {
118
+ throw new InvalidBuildOptionsError(`'${label}' must be an absolute path inside the data dir`);
119
+ }
120
+ const root = fs.realpathSync(dataDir);
121
+ let real: string;
122
+ try {
123
+ real = fs.realpathSync(p);
124
+ } catch {
125
+ throw new InvalidBuildOptionsError(`'${label}' does not exist: not a readable path`);
126
+ }
127
+ if (real !== root && !real.startsWith(root + path.sep)) {
128
+ throw new InvalidBuildOptionsError(`'${label}' must stay inside the data dir`);
129
+ }
130
+ return real;
131
+ }
132
+
133
+ /**
134
+ * Stage the optional config/credentials into the build context and return a cleanup that
135
+ * restores the empty (".none") state. The Dockerfile COPYs both directories unconditionally:
136
+ * build-config/.none / build-creds/.none mean "nothing staged".
137
+ */
138
+ export function stageBuildContext(
139
+ context: string,
140
+ options: Pick<RunnerBuildOptions, 'config_dir' | 'credentials_file' | 'data_dir'>
141
+ ): () => void {
142
+ const configDir = path.join(context, 'build-config');
143
+ const credsDir = path.join(context, 'build-creds');
144
+
145
+ const resetDir = (dir: string) => {
146
+ fs.rmSync(dir, { recursive: true, force: true });
147
+ fs.mkdirSync(dir, { recursive: true });
148
+ fs.writeFileSync(path.join(dir, '.none'), '');
149
+ };
150
+ resetDir(configDir);
151
+ resetDir(credsDir);
152
+
153
+ if (options.config_dir !== undefined) {
154
+ const src = assertInsideDataDir(options.config_dir, options.data_dir ?? '', 'config_dir');
155
+ if (!fs.statSync(src).isDirectory()) {
156
+ throw new InvalidBuildOptionsError("'config_dir' is not a directory");
157
+ }
158
+ fs.rmSync(configDir, { recursive: true, force: true });
159
+ fs.cpSync(src, configDir, { recursive: true });
160
+ fs.rmSync(path.join(configDir, '.none'), { force: true });
161
+ }
162
+ if (options.credentials_file !== undefined) {
163
+ const src = assertInsideDataDir(
164
+ options.credentials_file,
165
+ options.data_dir ?? '',
166
+ 'credentials_file'
167
+ );
168
+ const st = fs.statSync(src);
169
+ if (!st.isFile()) {
170
+ throw new InvalidBuildOptionsError("'credentials_file' is not a regular file");
171
+ }
172
+ if ((st.mode & 0o777) !== 0o600) {
173
+ throw new InvalidBuildOptionsError("'credentials_file' must have mode 0600");
174
+ }
175
+ fs.writeFileSync(path.join(credsDir, 'env'), fs.readFileSync(src), { mode: 0o600 });
176
+ fs.chmodSync(path.join(credsDir, 'env'), 0o600);
177
+ fs.rmSync(path.join(credsDir, '.none'), { force: true });
178
+ }
179
+
180
+ return () => {
181
+ resetDir(configDir);
182
+ resetDir(credsDir);
183
+ };
184
+ }
185
+
60
186
  /**
61
- * P2 criterion 7 (D7): rebuild the runner image to pick up new pinned versions of
62
- * bond, hc and the agents. Credentials are never part of the image, so a rebuild
63
- * never touches them; nothing secret is passed to `docker build`.
187
+ * P2 criterion 7 (D7) + image plan P2: rebuild the runner image to pick up new pinned
188
+ * versions and a new agent list. Credentials only ever reach the build through the
189
+ * staged 0600 file when explicitly asked for (D-A: that image is a local secret);
190
+ * nothing secret is passed on the docker command line.
64
191
  */
65
192
  export async function rebuildRunnerImage(
66
193
  image: string,
67
- versions: RunnerVersions = {},
194
+ options: RunnerBuildOptions = {},
68
195
  exec: DockerExec = execFileAsync as unknown as DockerExec
69
196
  ): Promise<void> {
197
+ const { agents, skip_az, skip_gh, config_dir, credentials_file, data_dir, ...versions } = options;
70
198
  const args: string[] = ['build', '--pull'];
71
199
  if ((versions.hc === undefined) !== (versions.hc_sha256 === undefined)) {
72
200
  throw new InvalidVersionError("'hc' and 'hc_sha256' go together: a new hc version needs its checksum");
@@ -98,10 +226,20 @@ export async function rebuildRunnerImage(
98
226
  }
99
227
  args.push('--build-arg', `${argName}=${value}`);
100
228
  }
101
- args.push('-t', image, runnerBuildContext);
102
229
 
230
+ // Image plan P2: the agent list (default pi = parity with the current image) and the
231
+ // optional staged config/credentials.
232
+ const agentList = agents === undefined ? ['pi'] : validateRunnerAgents(agents);
233
+ args.push('--build-arg', `AGENTS=${agentList.join(',')}`);
234
+ if (skip_az !== undefined) args.push('--build-arg', `SKIP_AZ=${skip_az ? '1' : '0'}`);
235
+ if (skip_gh !== undefined) args.push('--build-arg', `SKIP_GH=${skip_gh ? '1' : '0'}`);
236
+ if ((config_dir !== undefined || credentials_file !== undefined) && !data_dir) {
237
+ throw new InvalidBuildOptionsError("'data_dir' is required to stage config or credentials");
238
+ }
239
+
240
+ const cleanup = stageBuildContext(runnerBuildContext, { config_dir, credentials_file, data_dir });
103
241
  try {
104
- await exec('docker', args, {
242
+ await exec('docker', [...args, '-t', image, runnerBuildContext], {
105
243
  env: { ...process.env, DOCKER_BUILDKIT: '0' },
106
244
  timeout: BUILD_TIMEOUT_MS,
107
245
  maxBuffer: 32 * 1024 * 1024,
@@ -111,5 +249,7 @@ export async function rebuildRunnerImage(
111
249
  // Full docker output stays in the orchestrator's log only, never in the HTTP body.
112
250
  console.error(`[bond-app] docker build failed for ${image}: ${detail}`);
113
251
  throw new RunnerBuildError(`Runner image build failed for ${image}`);
252
+ } finally {
253
+ cleanup();
114
254
  }
115
255
  }