@north-light/api 0.3.751 → 0.3.752

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.
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.75";
2
+ export declare const CONTRACT_LEVEL = "1.76";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.75';
15
+ export const CONTRACT_LEVEL = '1.76';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -27,3 +27,40 @@ export interface SetProfileEnvironmentRequest {
27
27
  /** Also let the environment's sandboxes merge pull requests; false (the default) gives contents write only. Builds no new image. */
28
28
  allow_pull_request_write?: boolean;
29
29
  }
30
+ /** An app's environment (`/v1/environments`): a profile of the app with its own blaxel environment, paid by the app. */
31
+ export interface AppEnvironmentDTO {
32
+ /** The environment's name, unique per app; it is the name of its profile. */
33
+ name: string;
34
+ profile_id: string;
35
+ environment_id: string;
36
+ /** Who pays for runs in it: the app itself (`app:<id>`). */
37
+ payer: string;
38
+ setup_script: string | null;
39
+ pi_packages: string | null;
40
+ memory_mb: number;
41
+ recipe_revision: number;
42
+ }
43
+ /** `POST /v1/environments` body. Same name and same recipe returns the existing environment (200); a different recipe is `409 conflict` (use patch). */
44
+ export interface CreateAppEnvironmentRequest {
45
+ name: string;
46
+ /** A principal the calling app speaks for (its namespace), or the owner of a grant to the app that names itself payer; `invalid_request` otherwise. */
47
+ payer: string;
48
+ recipe?: {
49
+ /** Not supported for an app yet: a non-empty list is `400 repositories_not_supported`. */
50
+ repositories?: string[];
51
+ setup_script?: string | null;
52
+ pi_packages?: string | null;
53
+ /** 2048, 4096 or 8192; default 2048. */
54
+ memory_mb?: number;
55
+ };
56
+ }
57
+ /** `PATCH /v1/environments/{name}` body; a field left out keeps its value. */
58
+ export interface PatchAppEnvironmentRequest {
59
+ repositories?: string[];
60
+ setup_script?: string | null;
61
+ pi_packages?: string | null;
62
+ memory_mb?: number;
63
+ }
64
+ export interface AppEnvironmentListDTO {
65
+ environments: AppEnvironmentDTO[];
66
+ }
@@ -160,6 +160,8 @@ export declare const routes: {
160
160
  readonly appEnvVar: (variable: string) => string;
161
161
  readonly profileEnv: (name: string) => string;
162
162
  readonly profileEnvVar: (name: string, variable: string) => string;
163
+ readonly environments: () => string;
164
+ readonly environment: (name: string) => string;
163
165
  readonly profileEnvironment: (name: string) => string;
164
166
  readonly settings: () => string;
165
167
  readonly modelAuths: () => string;
@@ -188,6 +188,8 @@ export const routes = {
188
188
  appEnvVar: (variable) => `${V}/apps/self/env/${encodeURIComponent(variable)}`,
189
189
  profileEnv: (name) => `${V}/profiles/${name}/env`,
190
190
  profileEnvVar: (name, variable) => `${V}/profiles/${name}/env/${variable}`,
191
+ environments: () => `${V}/environments`,
192
+ environment: (name) => `${V}/environments/${name}`,
191
193
  profileEnvironment: (name) => `${V}/profiles/${name}/environment`,
192
194
  // Person settings
193
195
  settings: () => `${V}/settings`,
@@ -11,9 +11,10 @@ import { setCloudProfileWriter } from './profiles/manifest.js';
11
11
  * across them, while the handle is unique per object type. Returns the environment's object id. */
12
12
  export async function createProfileBlaxelEnvironment(db, spec) {
13
13
  const app = await ownerForGrantee(db, spec.grantee);
14
- const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
14
+ const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app, { noActsFor: spec.person.startsWith('app:') });
15
15
  const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
16
- await writeActsFor(db, object.id, spec.person);
16
+ if (!spec.person.startsWith('app:'))
17
+ await writeActsFor(db, object.id, spec.person); // an app environment is kept for no person
17
18
  await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
18
19
  if (spec.recipe !== undefined)
19
20
  await writeEnvironmentRecipe(db, object.id, spec.recipe);
@@ -22,7 +22,9 @@ export declare const ownerLockKey: (scheme: string, externalId: string, person?:
22
22
  * holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
23
23
  * by a different identity of the same type throws `conflict` naming both; it is
24
24
  * never renamed silently. */
25
- export declare function ensureOwner(db: CanvasDb, type: OwnerType, scheme: string, externalId: string, handle: string, owner?: ObjectRow): Promise<ObjectRow>;
25
+ export declare function ensureOwner(db: CanvasDb, type: OwnerType, scheme: string, externalId: string, handle: string, owner?: ObjectRow, options?: {
26
+ noActsFor?: boolean;
27
+ }): Promise<ObjectRow>;
26
28
  /** Give the live profile object of `profileId` the handle `handle`, so `[[handle/x]]` links,
27
29
  * `owner=` listings and `--owner profile:<handle>` follow a profile rename. Refuses with
28
30
  * `conflict` — before changing anything — when another live profile object holds the handle.
@@ -26,7 +26,7 @@ export const ownerLockKey = (scheme, externalId, person = '') => `owner:${person
26
26
  * holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
27
27
  * by a different identity of the same type throws `conflict` naming both; it is
28
28
  * never renamed silently. */
29
- export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
29
+ export async function ensureOwner(db, type, scheme, externalId, handle, owner, options = {}) {
30
30
  if (!OWNER_TYPES.has(type))
31
31
  throw new Error(`ensureOwner: ${type} is not an owner type`);
32
32
  // An owner that exists needs no lock: taking one here would acquire it outside the order a peer ingest locked its keys in.
@@ -57,7 +57,7 @@ export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
57
57
  await writeActsFor(db, created.id, userSubject(externalId).id);
58
58
  else if (type === 'repo')
59
59
  await writeActsFor(db, created.id, userSubject(person).id);
60
- else if (type === 'profile')
60
+ else if (type === 'profile' && options.noActsFor !== true)
61
61
  await writeActsFor(db, created.id, userSubject(await personIdAsync()).id);
62
62
  return created;
63
63
  }
@@ -62,6 +62,7 @@ export type CloudProfileWriter = (spec: {
62
62
  profileId: string;
63
63
  grantee: string;
64
64
  person: string;
65
+ payer?: string;
65
66
  memoryMb?: number;
66
67
  recipe?: EnvironmentRecipeInput;
67
68
  }, insert: (environmentId: string) => Promise<void>) => Promise<void>;
@@ -86,6 +87,10 @@ export declare function createProfile(name: string, projects?: ProfileProject[],
86
87
  grantee?: string;
87
88
  /** Memory of the cloud environment created with the profile; ignored off a cloud role. */
88
89
  memoryMb?: number;
90
+ /** An app environment: the app is the person the environment acts for and the payer (cloud role only). */
91
+ appEnvironment?: boolean;
92
+ /** The environment's payer (default: the app). */
93
+ payer?: string;
89
94
  /** Recipe written with the cloud environment, in the same write as the profile row. */
90
95
  recipe?: EnvironmentRecipeInput;
91
96
  }): Promise<ProfileEntry>;
@@ -367,7 +367,7 @@ export async function createProfile(name, projects = [], opts = {}) {
367
367
  else if (cloudProfileWriter === null)
368
368
  throw new Error('a cloud role has no profile environment writer registered');
369
369
  else
370
- await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: personId(), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
370
+ await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: opts.appEnvironment === true ? profileApp(manifest) : personId(), ...(opts.appEnvironment === true ? { payer: opts.payer ?? profileApp(manifest) } : {}), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
371
371
  return { profileId, manifest };
372
372
  }
373
373
  export async function ensureAppProfile(grantee) {
@@ -28,32 +28,31 @@ export declare const RUN_USER_NPMRC: string[];
28
28
  /** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
29
29
  * this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
30
30
  export declare const RUN_USER_NPMRC_ENV = "ENV NPM_CONFIG_USERCONFIG=/home/crtr/.npmrc";
31
- export declare const REPOS_DIR = "repos";
31
+ /** The build argument that carries the GitHub installation token into the build stage. */
32
+ export declare const GIT_TOKEN_ARG = "CRTR_GIT_TOKEN";
32
33
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
33
34
  export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
34
35
  export declare const SETUP_FAILED_FILE = "/work/.crtr/setup-failed";
35
36
  /** `gh` for a sandbox: /usr/local/bin comes before /usr/bin, so this wrapper runs first. It asks git's credential helper (set at sandbox start, so it reaches the control plane's
36
37
  * git-credential route) for a fresh installation token, exports it as GH_TOKEN for this one call and runs the real gh. No token is stored on disk. */
37
38
  export declare const GH_WRAPPER_PATH = "/usr/local/bin/gh";
38
- /** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
39
- * Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
40
- * the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
41
- export declare function recipeDockerfile(recipe: Recipe, revision: number, packagesToken?: boolean): string;
42
- export type GitRunner = (args: string[], env: Record<string, string>, cwd: string) => Promise<void>;
39
+ /** Throws when a repository's name, full name or branch could escape its place in the Dockerfile. */
40
+ export declare function assertRepositoryShape(repo: RecipeRepository): void;
41
+ /** The Dockerfile for a recipe revision. Pure. Two stages: `build` clones the repositories and runs the setup script as root; the final image copies
42
+ * only the installed trees out of it, never `/root`. Each token the build stage needs is declared there as an ARG (its value comes from `.env.build`
43
+ * in the upload) and never in the final stage, so no token is in a layer of the final image. */
44
+ export declare function recipeDockerfile(recipe: Recipe, revision: number, packagesToken?: boolean, gitToken?: boolean): string;
43
45
  export interface PrepareBuildDirInput {
44
46
  recipe: Recipe;
45
47
  revision: number;
46
- /** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. */
48
+ /** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. It goes only into `.env.build`. */
47
49
  token: string | null;
48
50
  /** The packages token (`NODE_AUTH_TOKEN`) for the build stage, or null. It goes only into `.env.build` of the upload. */
49
51
  packagesToken?: string | null;
50
52
  /** An empty directory. */
51
53
  dir: string;
52
- git?: GitRunner;
53
- /** The clone URL of a repository; the default is `https://github.com/<full name>.git`. */
54
- cloneUrl?: (githubFullName: string) => string;
55
54
  }
56
- /** Clones each repository into `<dir>/repos/<name>` and writes the Dockerfile and the setup script beside it. */
55
+ /** Writes the Dockerfile, `blaxel.toml`, the setup script and `.env.build` into `dir`. Clones nothing: the build stage on Blaxel does. */
57
56
  export declare function prepareBuildDir(input: PrepareBuildDirInput): Promise<void>;
58
57
  /** A zip of every file under `dir` (deflate, unix modes kept so scripts stay executable). Empty directories are not carried. */
59
58
  export declare function zipDirectory(dir: string): Buffer;
@@ -1,12 +1,12 @@
1
- // src/core/runtime/runner/blaxel/image-build.ts — the recipe image: Dockerfile writer, build-directory clone, Blaxel image build (C-A5, D25/D93/D94).
1
+ // src/core/runtime/runner/blaxel/image-build.ts — the recipe image: Dockerfile writer, build-directory writer, Blaxel image build (C-A5, D25/D93/D94).
2
2
  //
3
3
  // An environment recipe (repositories, pi packages, setup script) becomes one Blaxel sandbox image per recipe revision. The control plane
4
- // clones each repository into a build directory with a short-lived GitHub token, writes a Dockerfile that only COPYs the clones, zips the
5
- // directory and uploads it to Blaxel's build API. The token is handed to `git` through the environment of the clone process: it is in no
6
- // file, no Dockerfile line, no build argument and no `.git/config`, so it is in no image layer. Nothing of the person's secrets reaches the build.
7
- // `fetch` and `git` are injectable so the unit lane runs the whole flow against fakes.
8
- import { spawn } from 'node:child_process';
9
- import { constants as fsConstants, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs';
4
+ // writes a small build directory (Dockerfile, setup script, `blaxel.toml`, `.env.build`), zips it and uploads it to Blaxel's build API. The
5
+ // repositories are cloned by the build stage on Blaxel, never on the control plane, so a large repository costs the control plane nothing.
6
+ // The short-lived GitHub installation token reaches that stage as the build argument `CRTR_GIT_TOKEN` (its value only in `.env.build`), as
7
+ // the packages token does: the final stage declares no ARG and copies only the installed trees, so neither token is in the final image.
8
+ // `fetch` is injectable so the unit lane runs the whole flow against fakes.
9
+ import { constants as fsConstants, lstatSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs';
10
10
  import { join, relative } from 'node:path';
11
11
  import { crc32, deflateRawSync } from 'node:zlib';
12
12
  import { BlaxelApiError } from './client.js';
@@ -34,7 +34,8 @@ export const RUN_USER_NPMRC = [
34
34
  * this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
35
35
  export const RUN_USER_NPMRC_ENV = `ENV NPM_CONFIG_USERCONFIG=/home/${RUN_USER}/.npmrc`;
36
36
  const writeRunUserNpmrc = () => `printf '%s\\n' ${RUN_USER_NPMRC.map((l) => `'${l}'`).join(' ')} > /home/${RUN_USER}/.npmrc`;
37
- export const REPOS_DIR = 'repos';
37
+ /** The build argument that carries the GitHub installation token into the build stage. */
38
+ export const GIT_TOKEN_ARG = 'CRTR_GIT_TOKEN';
38
39
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
39
40
  export const SETUP_LOG_FILE = '/work/.crtr/setup.log';
40
41
  export const SETUP_FAILED_FILE = '/work/.crtr/setup-failed';
@@ -52,10 +53,27 @@ const lines = (text) => (text ?? '').split('\n').map((l) => l.trim()).filter((l)
52
53
  /** A RUN step that cannot fail the build (Blaxel hangs on a failed step and its build log is unreadable): its output goes to `SETUP_LOG_FILE` and a
53
54
  * failure appends `<label> exited <status>` to `SETUP_FAILED_FILE`, which the sandbox start script refuses to start on. */
54
55
  const guarded = (label, command) => `RUN { ${command}; } >> ${SETUP_LOG_FILE} 2>&1 || echo ${shellQuote(label)} "exited $?" >> ${SETUP_FAILED_FILE}`;
55
- /** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
56
- * Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
57
- * the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
58
- export function recipeDockerfile(recipe, revision, packagesToken = false) {
56
+ /** A repository's clone step in the build stage. Blobless (`--filter=blob:none`): full history, file contents fetched for the checkout only, so a
57
+ * large repository stays small in the image while `git log` and branching still work; older contents are fetched on demand through the sandbox's
58
+ * credential helper. The token is handed to git as a config entry of that one process: not in the URL, not in `.git/config`. */
59
+ const cloneStep = (repo, revision, withToken) => {
60
+ const auth = withToken ? `-c http.https://github.com/.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${GIT_TOKEN_ARG}" | base64 | tr -d '\\n')" ` : '';
61
+ // `: r<revision>` keeps a rebuild from reusing a cached clone layer of an earlier revision.
62
+ return guarded(`clone ${repo.github_full_name}`, `: r${Math.trunc(revision)}; GIT_TERMINAL_PROMPT=0 git ${auth}clone --quiet --filter=blob:none --branch ${shellQuote(repo.default_branch)} ${shellQuote(`https://github.com/${repo.github_full_name}.git`)} ${shellQuote(`/work/${repo.name}`)}`);
63
+ };
64
+ /** Throws when a repository's name, full name or branch could escape its place in the Dockerfile. */
65
+ export function assertRepositoryShape(repo) {
66
+ if (!/^[A-Za-z0-9._-]+$/.test(repo.name) || repo.name === '.' || repo.name === '..')
67
+ throw new Error(`repository name ${JSON.stringify(repo.name)} is not a plain directory name`);
68
+ if (!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo.github_full_name))
69
+ throw new Error(`repository ${JSON.stringify(repo.github_full_name)} is not an owner/name pair`);
70
+ if (repo.default_branch === '' || /[\s\x00-\x1f'"`$\\]/.test(repo.default_branch))
71
+ throw new Error(`branch ${JSON.stringify(repo.default_branch)} of ${repo.github_full_name} is not a plain branch name`);
72
+ }
73
+ /** The Dockerfile for a recipe revision. Pure. Two stages: `build` clones the repositories and runs the setup script as root; the final image copies
74
+ * only the installed trees out of it, never `/root`. Each token the build stage needs is declared there as an ARG (its value comes from `.env.build`
75
+ * in the upload) and never in the final stage, so no token is in a layer of the final image. */
76
+ export function recipeDockerfile(recipe, revision, packagesToken = false, gitToken = false) {
59
77
  const packages = lines(recipe.pi_packages);
60
78
  const hasScript = recipe.setup_script !== null && recipe.setup_script.trim() !== '';
61
79
  const base = [
@@ -65,10 +83,12 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
65
83
  `COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
66
84
  `RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /work/.crtr ${RECIPE_PI_AGENT_DIR} && chown -R ${RUN_USER} /work /var/lib/crtr`,
67
85
  ];
68
- const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...base.slice(1), `RUN rm -f ${SETUP_FAILED_FILE} ${SETUP_LOG_FILE}`, guarded('npm install -g pnpm', 'npm install -g pnpm && mkdir -p /var/lib/postgresql')];
69
- // An empty `repos/` is not in the zip, and a COPY of a missing directory fails the build.
70
- if (recipe.repositories.length > 0)
71
- out.push(`COPY --chown=${RUN_USER} ${REPOS_DIR}/ /work/`);
86
+ for (const repo of recipe.repositories)
87
+ assertRepositoryShape(repo);
88
+ const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...(gitToken && recipe.repositories.length > 0 ? [`ARG ${GIT_TOKEN_ARG}`] : []), ...base.slice(1), `RUN rm -f ${SETUP_FAILED_FILE} ${SETUP_LOG_FILE}`, guarded('npm install -g pnpm', 'npm install -g pnpm && mkdir -p /var/lib/postgresql')];
89
+ // A failed clone fails no step (see `guarded`): it is in the setup log, and the sandbox start script refuses to start on it.
90
+ for (const repo of recipe.repositories)
91
+ out.push(cloneStep(repo, revision, gitToken));
72
92
  if (packages.length > 0)
73
93
  out.push(guarded('npm install pi', `npm install -g @earendil-works/pi-coding-agent@${PI_VERSION}`));
74
94
  if (hasScript)
@@ -99,37 +119,15 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
99
119
  out.push(RUN_USER_NPMRC_ENV, `USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
100
120
  return out.join('\n');
101
121
  }
102
- const runGit = (args, env, cwd) => new Promise((resolve, reject) => {
103
- const child = spawn('git', args, { cwd, env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: '0' }, stdio: ['ignore', 'ignore', 'pipe'] });
104
- let stderr = '';
105
- child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
106
- child.on('error', reject);
107
- child.on('close', (code) => { if (code === 0)
108
- resolve();
109
- else
110
- reject(new Error(`git ${args[0]} failed (${code}): ${stderr.slice(0, 300)}`)); });
111
- });
112
- /** Clones each repository into `<dir>/repos/<name>` and writes the Dockerfile and the setup script beside it. */
122
+ /** Writes the Dockerfile, `blaxel.toml`, the setup script and `.env.build` into `dir`. Clones nothing: the build stage on Blaxel does. */
113
123
  export async function prepareBuildDir(input) {
114
- const git = input.git ?? runGit;
115
124
  const packagesToken = input.packagesToken ?? null;
116
- const cloneUrl = input.cloneUrl ?? ((full) => `https://github.com/${full}.git`);
117
- mkdirSync(join(input.dir, REPOS_DIR), { recursive: true });
118
- // The token travels as a git config entry in the clone process's environment: not in argv, not written to `.git/config`.
119
- const auth = input.token === null ? {} : {
120
- GIT_CONFIG_COUNT: '1',
121
- GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
122
- GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${input.token}`).toString('base64')}`,
123
- };
124
- for (const repo of input.recipe.repositories) {
125
- if (!/^[A-Za-z0-9._-]+$/.test(repo.name) || repo.name === '.' || repo.name === '..')
126
- throw new Error(`repository name ${JSON.stringify(repo.name)} is not a plain directory name`);
127
- await git(['clone', '--quiet', '--branch', repo.default_branch, cloneUrl(repo.github_full_name), join(REPOS_DIR, repo.name)], auth, input.dir);
128
- }
125
+ const gitToken = input.recipe.repositories.length > 0 ? input.token : null;
129
126
  writeFileSync(join(input.dir, BLAXEL_TOML_FILE), BLAXEL_TOML);
130
- writeFileSync(join(input.dir, 'Dockerfile'), recipeDockerfile(input.recipe, input.revision, packagesToken !== null));
131
- if (packagesToken !== null)
132
- writeFileSync(join(input.dir, '.env.build'), `NODE_AUTH_TOKEN=${packagesToken}\n`, { mode: 0o600 });
127
+ writeFileSync(join(input.dir, 'Dockerfile'), recipeDockerfile(input.recipe, input.revision, packagesToken !== null, gitToken !== null));
128
+ const buildEnv = [...(packagesToken !== null ? [`NODE_AUTH_TOKEN=${packagesToken}`] : []), ...(gitToken !== null ? [`${GIT_TOKEN_ARG}=${gitToken}`] : [])];
129
+ if (buildEnv.length > 0)
130
+ writeFileSync(join(input.dir, '.env.build'), `${buildEnv.join('\n')}\n`, { mode: 0o600 });
133
131
  if (input.recipe.setup_script !== null && input.recipe.setup_script.trim() !== '')
134
132
  writeFileSync(join(input.dir, SETUP_SCRIPT_FILE), input.recipe.setup_script.endsWith('\n') ? input.recipe.setup_script : `${input.recipe.setup_script}\n`);
135
133
  }
@@ -195,6 +195,10 @@ export const OPERATIONS = [
195
195
  { name: 'profile.env.remove', method: 'DELETE', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
196
196
  { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
197
197
  { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
198
+ { name: 'environment.create', method: 'POST', path: '/v1/environments', classes: ['app'], resource: 'profile' },
199
+ { name: 'environment.list', method: 'GET', path: '/v1/environments', classes: ['app', 'person'], resource: 'profile' },
200
+ { name: 'environment.patch', method: 'PATCH', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
201
+ { name: 'environment.delete', method: 'DELETE', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
198
202
  { name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
199
203
  { name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker', 'cron'], resource: 'profile', stage: 'chat' },
200
204
  { name: 'profiles.get.118', method: 'GET', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
@@ -40,6 +40,8 @@ export interface RecipeImageDeps {
40
40
  deleteImage?: (name: string) => Promise<void>;
41
41
  now?: () => number;
42
42
  }
43
+ /** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
44
+ export declare function removeLeftoverBuildDirs(root?: string): void;
43
45
  export declare class RecipeImageReconciler {
44
46
  private readonly deps;
45
47
  constructor(deps?: RecipeImageDeps);
@@ -12,7 +12,7 @@
12
12
  // the image with every tag (a 404 is done); success clears all four image columns, so a later undelete finds an unbuilt environment and
13
13
  // the build pass rebuilds it; failure writes `image_error` and a retry time in `image_building_at`, as a failed build does. A build that
14
14
  // finishes after the environment was deleted records nothing and deletes the image it made.
15
- import { mkdtempSync } from 'node:fs';
15
+ import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
16
16
  import { tmpdir } from 'node:os';
17
17
  import { join } from 'node:path';
18
18
  import { hasUnseenWakeMail } from '../../core/canvas/deliveries.js';
@@ -62,6 +62,12 @@ async function defaultBuild(input, config) {
62
62
  removeBuildDir(dir);
63
63
  }
64
64
  }
65
+ /** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
66
+ export function removeLeftoverBuildDirs(root = tmpdir()) {
67
+ for (const name of readdirSync(root))
68
+ if (name.startsWith('crtr-recipe-image-'))
69
+ rmSync(join(root, name), { recursive: true, force: true });
70
+ }
65
71
  export class RecipeImageReconciler {
66
72
  deps;
67
73
  constructor(deps = {}) {
@@ -148,6 +154,8 @@ export class RecipeImageReconciler {
148
154
  const person = await (await openDb()).prepare('SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1').get(environmentId);
149
155
  if (person === undefined)
150
156
  throw new Error(`no profile runs in environment ${environmentId}, so there is no person to take a GitHub token for`);
157
+ // Recorded before the build so a process that dies mid-build leaves the reason; success clears it.
158
+ await (await openDb()).prepare('UPDATE environments SET image_error = ? WHERE object = ? AND image_building_at = ?').run(`the build of revision ${revision} started and its process exited before it finished`, environmentId, currentLease());
151
159
  const input = { environmentId, revision, recipe, person: person.person };
152
160
  built = await (this.deps.build ?? ((i) => defaultBuild(i, blaxelConfigFromEnv())))(input);
153
161
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.751",
3
+ "version": "0.3.752",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",