@north-light/cli 0.3.751 → 0.3.753

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 (78) hide show
  1. package/README.md +1 -1
  2. package/dist/api/contract.d.ts +1 -1
  3. package/dist/api/contract.js +1 -1
  4. package/dist/api/dto/environments.d.ts +37 -0
  5. package/dist/api/dto/health.d.ts +3 -0
  6. package/dist/api/routes.d.ts +2 -0
  7. package/dist/api/routes.js +1 -1
  8. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  9. package/dist/clients/attach/viewer.js +342 -342
  10. package/dist/commands/sys/daemon.js +1 -1
  11. package/dist/core/audit.d.ts +2 -0
  12. package/dist/core/audit.js +2 -2
  13. package/dist/core/canvas/canvas.d.ts +1 -1
  14. package/dist/core/canvas/canvas.js +26 -19
  15. package/dist/core/canvas/schema-pg/038-actor.sql +4 -0
  16. package/dist/core/canvas/schema-version.d.ts +1 -1
  17. package/dist/core/canvas/schema-version.js +1 -1
  18. package/dist/core/environments.js +1 -1
  19. package/dist/core/graph/objects.d.ts +3 -1
  20. package/dist/core/graph/objects.js +10 -10
  21. package/dist/core/import/load/copy.js +9 -9
  22. package/dist/core/import/load/keys.d.ts +5 -0
  23. package/dist/core/import/load/keys.js +8 -0
  24. package/dist/core/import/load/rollback.js +7 -7
  25. package/dist/core/import/load/run.js +2 -3
  26. package/dist/core/import/load/verify.js +8 -8
  27. package/dist/core/ledger/charges.js +1 -1
  28. package/dist/core/ledger/chunks.js +1 -1
  29. package/dist/core/ledger/read.js +1 -1
  30. package/dist/core/ledger/types.d.ts +4 -0
  31. package/dist/core/profiles/manifest.d.ts +5 -0
  32. package/dist/core/profiles/manifest.js +1 -1
  33. package/dist/core/providers/audit.js +3 -3
  34. package/dist/core/providers/call.d.ts +2 -0
  35. package/dist/core/providers/call.js +1 -1
  36. package/dist/core/providers/receipts.d.ts +2 -0
  37. package/dist/core/providers/receipts.js +1 -1
  38. package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
  39. package/dist/core/runtime/runner/blaxel/image-build.js +7 -6
  40. package/dist/daemon/api/handlers/app-environments.d.ts +2 -0
  41. package/dist/daemon/api/handlers/app-environments.js +1 -0
  42. package/dist/daemon/api/handlers/providers.d.ts +2 -0
  43. package/dist/daemon/api/handlers/providers.js +1 -1
  44. package/dist/daemon/api/operations.js +1 -1
  45. package/dist/daemon/api/server.js +1 -1
  46. package/dist/daemon/crtrd.js +12 -12
  47. package/dist/daemon/machine-daemon.js +1 -1
  48. package/dist/daemon/manage.js +3 -3
  49. package/dist/daemon/peer/ingress.js +1 -1
  50. package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
  51. package/dist/daemon/reconcilers/recipe-image.js +5 -5
  52. package/docs/sdk/release-notes.md +6 -0
  53. package/package.json +3 -3
  54. package/packages/crouter-api/dist/api/contract.js +1 -1
  55. package/packages/crouter-api/dist/api/routes.js +2 -0
  56. package/packages/crouter-api/dist/commands/sys/daemon.js +8 -3
  57. package/packages/crouter-api/dist/core/canvas/canvas.js +14 -4
  58. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  59. package/packages/crouter-api/dist/core/environments.js +3 -2
  60. package/packages/crouter-api/dist/core/graph/objects.js +2 -2
  61. package/packages/crouter-api/dist/core/import/load/copy.js +47 -23
  62. package/packages/crouter-api/dist/core/import/load/keys.js +77 -0
  63. package/packages/crouter-api/dist/core/ledger/charges.js +3 -3
  64. package/packages/crouter-api/dist/core/ledger/chunks.js +1 -1
  65. package/packages/crouter-api/dist/core/ledger/read.js +1 -1
  66. package/packages/crouter-api/dist/core/profiles/manifest.js +1 -1
  67. package/packages/crouter-api/dist/core/providers/audit.js +2 -2
  68. package/packages/crouter-api/dist/core/providers/call.js +2 -2
  69. package/packages/crouter-api/dist/core/providers/receipts.js +1 -1
  70. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +42 -44
  71. package/packages/crouter-api/dist/daemon/api/handlers/providers.js +1 -1
  72. package/packages/crouter-api/dist/daemon/api/operations.js +4 -0
  73. package/packages/crouter-api/dist/daemon/manage.js +3 -2
  74. package/packages/crouter-api/dist/daemon/reconcilers/recipe-image.js +9 -1
  75. package/packages/crouter-api/package.json +1 -1
  76. package/packages/crouter-identity/package.json +1 -1
  77. package/packages/crouter-plugin/package.json +3 -3
  78. package/runtime.lock.json +14 -14
@@ -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
  }
@@ -6,6 +6,9 @@ import { BODIES_TABLE, COPIED_TABLES, KEY_MAPPED_TABLES } from '../bundle/layout
6
6
  import { q, rowKey, topologicalOrder } from './catalog.js';
7
7
  import { fillEnvironments } from './prepare.js';
8
8
  import { ImportLaneError } from './stage.js';
9
+ import { encodeKeyBatches } from './keys.js';
10
+ /** Rows per INSERT. The staged table is read in ordinal ranges, so a statement returns at most this many keys to JS. */
11
+ const COPY_BATCH = 20_000;
9
12
  const sq = (schema, table) => `${q(schema)}.${q(table)}`;
10
13
  /** `import_manifest.inserted_keys`: a zstd-compressed JSON array of primary-key tuples (each value as text). */
11
14
  export const encodeKeys = (keys) => zstdCompressSync(Buffer.from(JSON.stringify(keys)));
@@ -42,20 +45,41 @@ export async function copyRows(input) {
42
45
  result.inserted[table] = keys.length;
43
46
  await db.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encodeKeys(keys));
44
47
  };
48
+ /** Numbers the staged rows `from` (a FROM/WHERE tail over alias `s`) in `order`, in Postgres: the ordinal table `_ord` holds each row's ctid and number. */
49
+ const number = async (table, order, where) => {
50
+ await db.exec(`DROP TABLE IF EXISTS ${S('_ord')}; CREATE TABLE ${S('_ord')} AS SELECT s.ctid AS row_id, (row_number() OVER (ORDER BY ${order}))::bigint AS n FROM ${S(table)} s${where}; CREATE INDEX ON ${S('_ord')} (n)`);
51
+ return Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S('_ord')}`).get()).n);
52
+ };
53
+ /** Runs `insert(low, high)` for each ordinal range of `total` rows (it returns that range's keys) and writes the keys to the table's manifest row, compressed as they arrive. */
54
+ const inBatches = async (table, total, insert, record = true) => {
55
+ let inserted = 0;
56
+ const batches = (async function* () {
57
+ for (let low = 0; low < total; low += COPY_BATCH) {
58
+ const keys = await insert(low, low + COPY_BATCH);
59
+ inserted += keys.length;
60
+ yield keys;
61
+ }
62
+ })();
63
+ const encoded = await encodeKeyBatches(batches);
64
+ if (record)
65
+ await db.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encoded);
66
+ return inserted;
67
+ };
45
68
  // The two identity-keyed tables first (nothing references them by a foreign key): the target numbers them in source order and the key map remembers it.
46
69
  // One statement per table: each staged row takes the next number of the target's identity sequence (in source order), is inserted under it, and is
47
70
  // recorded in the key map under its source key, so the pairing is explicit and no row costs a round trip.
48
71
  for (const [table, column] of Object.entries(KEY_MAPPED_TABLES)) {
49
72
  const info = catalog.tables.get(table);
50
73
  const columns = info.columns.filter((c) => c !== column);
51
- const rows = await db.prepareUncached(`WITH src AS MATERIALIZED (
52
- SELECT s.${q(column)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}
53
- FROM (SELECT * FROM ${S(table)} ORDER BY ${q(column)}::bigint) s),
74
+ // Source order is the numbering order: each batch takes the next numbers of the target's identity sequence, so batches in ordinal order keep the pairing.
75
+ const total = await number(table, `s.${q(column)}::bigint`, '');
76
+ const inserted = await inBatches(table, total, async (low, high) => (await db.prepareUncached(`WITH src AS MATERIALIZED (
77
+ SELECT s.source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}
78
+ FROM (SELECT s.${q(column)}::text AS source_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}, o.n FROM ${S(table)} s JOIN ${S('_ord')} o ON o.row_id = s.ctid WHERE o.n > ${low} AND o.n <= ${high} ORDER BY o.n) s),
54
79
  ins AS (INSERT INTO ${T(table)} (${q(column)}, ${columns.map(q).join(', ')}) SELECT target_key, ${columns.map(q).join(', ')} FROM src RETURNING 1),
55
80
  km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
56
- SELECT target_key FROM km ORDER BY target_key::bigint`)
57
- .all(T(table), column, source.installId, table);
58
- await manifest(table, rows.map((r) => [r.target_key]));
81
+ SELECT target_key FROM km ORDER BY target_key::bigint`).all(T(table), column, source.installId, table)).map((r) => [r.target_key]));
82
+ result.inserted[table] = inserted;
59
83
  }
60
84
  // `review_comments.created_seq` follows its event.
61
85
  await db.prepareUncached(`UPDATE ${S('review_comments')} c SET created_seq = m.target_key::bigint FROM import_key_map m
@@ -84,26 +108,29 @@ export async function copyRows(input) {
84
108
  const orderBy = info.identity.length > 0 ? info.identity.map((c) => `s.${q(c)}`).join(', ') : pk.map((c) => `s.${q(c)}`).join(', ');
85
109
  let select = columns.map((c) => `s.${q(c)}`);
86
110
  let where = '';
111
+ let last = 0;
87
112
  if (table === 'messages') {
88
113
  // `messages.seq` is a plain unique column: advance the counter once by the number of new rows and number them from the old value.
89
- const fresh = `NOT EXISTS (SELECT 1 FROM ${T('messages')} t WHERE t.message_id = s.message_id)`;
90
- const n = Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S('messages')} s WHERE ${fresh}`).get()).n);
91
- where = ` WHERE ${fresh}`;
92
- if (n === 0) {
114
+ where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T('messages')} t WHERE t.message_id = s.message_id)`;
115
+ }
116
+ // A table with no primary key is keyed by all its columns: a row the target already holds with equal columns is skipped.
117
+ const keyless = info.primaryKey.length === 0;
118
+ if (keyless)
119
+ where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T(table)} t WHERE ${pk.map((c) => `t.${q(c)} IS NOT DISTINCT FROM s.${q(c)}`).join(' AND ')})`;
120
+ // The rows to insert are decided and numbered once, before the first batch, so a batch never sees an earlier batch's rows as already in the target.
121
+ const total = await number(table, table === 'messages' ? 's.seq' : orderBy, where);
122
+ if (table === 'messages') {
123
+ if (total === 0) {
93
124
  result.inserted[table] = 0;
94
125
  await manifest(table, []);
95
126
  continue;
96
127
  }
97
- const last = Number((await db.prepare('UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq').get(n)).seq);
98
- select = columns.map((c) => c === 'seq' ? `${last - n} + row_number() OVER (ORDER BY s.seq)` : `s.${q(c)}`);
128
+ last = Number((await db.prepare('UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq').get(total)).seq);
129
+ select = columns.map((c) => c === 'seq' ? `${last - total} + o.n` : `s.${q(c)}`);
99
130
  }
100
131
  const returning = pk.map((c) => `${q(c)}::text`).join(', ');
101
- // A table with no primary key is keyed by all its columns: a row the target already holds with equal columns is skipped.
102
- const keyless = info.primaryKey.length === 0;
103
- if (keyless)
104
- where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T(table)} t WHERE ${pk.map((c) => `t.${q(c)} IS NOT DISTINCT FROM s.${q(c)}`).join(' AND ')})`;
105
- const inserted = await db.prepareUncached(`INSERT INTO ${T(table)} (${columns.map(q).join(', ')}) SELECT ${select.join(', ')} FROM ${S(table)} s${where}
106
- ORDER BY ${orderBy}${keyless ? '' : ` ON CONFLICT (${pk.map(q).join(', ')}) DO NOTHING`} RETURNING ${returning}`).all();
132
+ const insertedCount = await inBatches(table, total, async (low, high) => (await db.prepareUncached(`INSERT INTO ${T(table)} (${columns.map(q).join(', ')}) SELECT ${select.join(', ')} FROM ${S(table)} s JOIN ${S('_ord')} o ON o.row_id = s.ctid WHERE o.n > ${low} AND o.n <= ${high}
133
+ ORDER BY o.n${keyless ? '' : ` ON CONFLICT (${pk.map(q).join(', ')}) DO NOTHING`} RETURNING ${returning}`).all()).map((row) => Object.values(row)), table !== BODIES_TABLE);
107
134
  // `ON CONFLICT DO NOTHING` kept the target's row for a key it already held: that row must hold the same text (the pre-check compared them earlier, outside this transaction).
108
135
  if (table === BODIES_TABLE) {
109
136
  const clash = await db.prepareUncached(`SELECT s.hash FROM ${S(table)} s JOIN ${T(table)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();
@@ -112,11 +139,8 @@ export async function copyRows(input) {
112
139
  }
113
140
  }
114
141
  // `bodies` rows are never deleted (design-fleet D106), so a rollback must not remove them: no manifest row. The hash is the key on both sides.
115
- if (table === BODIES_TABLE)
116
- result.inserted[table] = inserted.length;
117
- else
118
- await manifest(table, inserted.map((row) => Object.values(row)));
119
- result.mapped[table] = staged - inserted.length;
142
+ result.inserted[table] = insertedCount;
143
+ result.mapped[table] = staged - insertedCount;
120
144
  }
121
145
  for (const f of filled)
122
146
  await db.prepare(`INSERT INTO ${S('_filled')} VALUES (?, ?::jsonb)`).run(f.table, JSON.stringify(f.key));
@@ -0,0 +1,77 @@
1
+ // Manifest keys without whole-account arrays. `import_manifest.inserted_keys` is a zstd-compressed JSON array of primary-key tuples; the streaming writer puts one tuple per
2
+ // line (`[`, `k1,`, `k2`, `]`: still one valid JSON array, so `decodeKeys` reads it) and the streaming reader yields batches of tuples, so memory is one batch plus the compressed bytes.
3
+ // An array written in one line by an earlier release is read whole.
4
+ import { createZstdCompress, createZstdDecompress } from 'node:zlib';
5
+ import { once } from 'node:events';
6
+ export const KEY_BATCH = 5000;
7
+ /** Compress the batches into one `inserted_keys` value. */
8
+ export async function encodeKeyBatches(batches) {
9
+ const zst = createZstdCompress();
10
+ const out = [];
11
+ zst.on('data', (chunk) => out.push(chunk));
12
+ const done = once(zst, 'end');
13
+ const put = async (text) => { if (!zst.write(text, 'utf8'))
14
+ await once(zst, 'drain'); };
15
+ await put('[\n');
16
+ let first = true;
17
+ for await (const batch of batches) {
18
+ if (batch.length === 0)
19
+ continue;
20
+ await put((first ? '' : ',\n') + batch.map((key) => JSON.stringify(key)).join(',\n'));
21
+ first = false;
22
+ }
23
+ await put('\n]');
24
+ zst.end();
25
+ await done;
26
+ return Buffer.concat(out);
27
+ }
28
+ /** The tuples of an `inserted_keys` value, `size` at a time. */
29
+ export async function* keyBatches(data, size = KEY_BATCH) {
30
+ const zst = createZstdDecompress({ chunkSize: 1 << 20 });
31
+ zst.end(data);
32
+ let pending = '';
33
+ let batch = [];
34
+ let streaming;
35
+ let legacy = [];
36
+ for await (const chunk of zst) {
37
+ if (streaming === false) {
38
+ legacy.push(chunk);
39
+ continue;
40
+ }
41
+ pending += chunk.toString('utf8');
42
+ if (streaming === undefined) {
43
+ if (pending.length < 2)
44
+ continue;
45
+ streaming = pending.startsWith('[\n') || pending === '[]';
46
+ if (!streaming) {
47
+ legacy.push(Buffer.from(pending));
48
+ pending = '';
49
+ continue;
50
+ }
51
+ }
52
+ let at = pending.indexOf('\n');
53
+ while (at !== -1) {
54
+ const line = pending.slice(0, at).replace(/,$/, '');
55
+ pending = pending.slice(at + 1);
56
+ if (line !== '[' && line !== ']' && line !== '') {
57
+ batch.push(JSON.parse(line));
58
+ if (batch.length >= size) {
59
+ yield batch;
60
+ batch = [];
61
+ }
62
+ }
63
+ at = pending.indexOf('\n');
64
+ }
65
+ }
66
+ if (streaming === false || streaming === undefined) {
67
+ const all = legacy.length > 0 ? JSON.parse(Buffer.concat(legacy).toString('utf8')) : (pending === '' ? [] : JSON.parse(pending));
68
+ for (let i = 0; i < all.length; i += size)
69
+ yield all.slice(i, i + size);
70
+ return;
71
+ }
72
+ const tail = pending.replace(/,$/, '').trim();
73
+ if (tail !== '' && tail !== ']' && tail !== '[')
74
+ batch.push(JSON.parse(tail));
75
+ if (batch.length > 0)
76
+ yield batch;
77
+ }
@@ -5,8 +5,8 @@ import { takePercent } from './rates.js';
5
5
  import { usageMonth } from './months.js';
6
6
  /** The id of a tool charge: the receipt-level idempotency key, so two providers' receipt ids never collide. */
7
7
  export const receiptChargeId = (provider, receiptId) => `receipt:${provider}:${receiptId}`;
8
- const COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger';
9
- const PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true';
8
+ const COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger, actor';
9
+ const PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true, ?';
10
10
  /** Write one charge row; the `charges` trigger (schema delta 007) adds it to `charge_totals`. A refused row is stored with
11
11
  * usd 0 and never rolled up; a take row (written only while `CRTR_LEDGER_TAKE_PCT` > 0) is stored and never rolled up. Inside a
12
12
  * caller's `withCanvasWrite` it joins that transaction. */
@@ -22,7 +22,7 @@ export async function writeCharge(input) {
22
22
  rowId, input.request ?? null, at.toISOString(), month, kind, what, input.units == null ? null : JSON.stringify(input.units), rowUsd,
23
23
  input.payer, funding, input.sub ?? null, input.grantee, input.node ?? null, input.run ?? null, input.provider ?? null,
24
24
  input.causedBy ?? null, input.vendorRef ?? null, refused === null ? null : JSON.stringify(refused), input.account ?? null, input.billedUsd ?? null,
25
- null, null, null, null
25
+ null, null, null, null, input.actor ?? null
26
26
  ];
27
27
  const inserted = await db.prepare(`INSERT INTO charges (${COLUMNS}) VALUES (${PLACEHOLDERS}) ON CONFLICT (id) DO NOTHING`)
28
28
  .run(...row(id, input.kind, input.what, usd, input.funding));
@@ -5,7 +5,7 @@ import { zstdDecompressSync } from 'node:zlib';
5
5
  import { blobStore } from '../blobs/index.js';
6
6
  import { openDb } from '../canvas/db.js';
7
7
  import { chargeOf } from './charges.js';
8
- const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source'];
8
+ const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source', 'actor'];
9
9
  /** The moved rows of a month (or of every month), from month `since` on, read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
10
10
  export class ChunkRows {
11
11
  since;
@@ -9,7 +9,7 @@ import { chargeOf } from './charges.js';
9
9
  import { ChunkRows } from './chunks.js';
10
10
  import { listLimits } from './limits.js';
11
11
  import { resetAt, usageMonth } from './months.js';
12
- const CHARGE_COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source';
12
+ const CHARGE_COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, actor';
13
13
  /** `usage.get` for one grantee and month, computed from `charges`. `by_model` and `app_paid.by_model` group the `model` rows
14
14
  * of a `user:` / `app:` payer by `what`, with token sums from `units` and `usd_equivalent` null when every row's `usd` is null.
15
15
  * `usd_equivalent` is what the grant's limit reads: every `user:` payer charge for this grantee, model and tool, refused and
@@ -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) {
@@ -9,8 +9,8 @@ export async function writeProviderAudit(row) {
9
9
  const chain = sub && grantee ? [sub, grantee, `runtime:${runtimeId()}`] : null;
10
10
  await (await openDb()).prepare(`INSERT INTO audit_rows
11
11
  (request_id, time, grantee, sub, client_id, class, operation, scope_checked,
12
- outcome, node_id, run_id, resource, initiator_chain, provider, tool, jti, receipt_id, responder, question_id)
13
- VALUES (?, ?, ?, ?, ?, ?, 'provider.call', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.request_id, new Date().toISOString(), grantee, sub, caller.client_id, caller.class, row.scope_checked ?? null, row.outcome, caller.node_id, caller.run_id, `${row.provider} ${row.tool}`, chain ? JSON.stringify(chain) : null, row.provider, row.tool, row.jti ?? null, row.receipt_id ?? null, row.responder ?? null, row.question_id ?? null);
12
+ outcome, node_id, run_id, resource, initiator_chain, provider, tool, jti, receipt_id, responder, question_id, actor)
13
+ VALUES (?, ?, ?, ?, ?, ?, 'provider.call', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.request_id, new Date().toISOString(), grantee, sub, caller.client_id, caller.class, row.scope_checked ?? null, row.outcome, caller.node_id, caller.run_id, `${row.provider} ${row.tool}`, chain ? JSON.stringify(chain) : null, row.provider, row.tool, row.jti ?? null, row.receipt_id ?? null, row.responder ?? null, row.question_id ?? null, caller.actor ?? null);
14
14
  }
15
15
  export async function listAudit(grantee, filters) {
16
16
  const where = [];
@@ -285,7 +285,7 @@ export async function callProvider(caller, rawInput, request) {
285
285
  const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub, environmentPayer: await environmentPayerOfNode(caller.node_id) });
286
286
  const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee, provider: `app:${bundle.id}` });
287
287
  if (refusal !== null) {
288
- await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee,
288
+ await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, actor: caller.actor ?? null, grantee: chargeGrantee,
289
289
  node: caller.node_id, run: caller.run_id, provider: `app:${bundle.id}`, causedBy: request.causedBy ?? null, refused: refusedMark(refusal) });
290
290
  throw refusalError(refusal);
291
291
  }
@@ -317,7 +317,7 @@ export async function callProvider(caller, rawInput, request) {
317
317
  }
318
318
  // R7 receives every response, including errors, before the mapping.
319
319
  receiptId ??= await onProviderResponse({ provider: bundle.id, tool: input.tool, request_id: requestId, run_id: caller.run_id,
320
- sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
320
+ sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, actor: caller.actor ?? null, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
321
321
  responder = response.headers['crtr-responder'];
322
322
  if (response.status === 401)
323
323
  discardFile(token.key);
@@ -42,7 +42,7 @@ export async function acceptProviderReceipt(value, call) {
42
42
  for (const receipt of accepted) {
43
43
  // One row per receipt, keyed by (provider, receipt id): a repeat delivery writes nothing and adds nothing.
44
44
  await writeCharge({ id: receiptChargeId(call.provider, receipt.receipt_id), request: call.request_id, kind: 'tool', what: `${call.provider}:${call.tool}`,
45
- units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub,
45
+ units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub, actor: call.actor ?? null,
46
46
  grantee: call.ledger_grantee ?? call.grantee, node: call.node_id, run: call.run_id, provider: `app:${call.provider}`, causedBy: call.caused_by, vendorRef: receipt.receipt_id });
47
47
  }
48
48
  });
@@ -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
  }
@@ -65,7 +65,7 @@ export async function callerFromRequest(principal) {
65
65
  run_id: principal.run ?? (await getNode(principal.node))?.run_id ?? null, node_id: principal.node };
66
66
  }
67
67
  export function callerFromApp(principal) {
68
- return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
68
+ return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, actor: principal.actor, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
69
69
  }
70
70
  /** A provider scope `<provider>:<group>` (the identity grammar's `provider`
71
71
  * selector kind). `covers()` grants such a scope only by exact equality. */
@@ -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' },
@@ -8,7 +8,7 @@ import { createRequire } from 'node:module';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { fileURLToPath, pathToFileURL } from 'node:url';
10
10
  import { existsSync, lstatSync, mkdirSync, openSync, closeSync, fstatSync, readSync } from 'node:fs';
11
- import { crtrHome } from '../core/canvas/paths.js';
11
+ import { apiSocketPath, crtrHome } from '../core/canvas/paths.js';
12
12
  import { listProcessTable } from '../core/canvas/pid.js';
13
13
  import { bindDaemonEventSource, eventSource } from '../core/events/source.js';
14
14
  import { hostExecPath } from '../core/runtime/branded-host.js';
@@ -245,7 +245,8 @@ const DAEMON_HEALTH_PROBE_TIMEOUT_MS = 1_000;
245
245
  /** Make one `/healthz` observation without client-side recovery. The caller owns the availability window, so this probe cannot extend it. */
246
246
  export async function probeDaemonHealth(timeoutMs = DAEMON_HEALTH_PROBE_TIMEOUT_MS) {
247
247
  const probeTimeoutMs = Math.min(timeoutMs, DAEMON_HEALTH_PROBE_TIMEOUT_MS);
248
- return localClient({ autostart: false, timeoutMs: probeTimeoutMs }).probeHealthz(probeTimeoutMs);
248
+ // This computer's daemon socket, never a node's `CRTR_API_SOCKET` relay: inside a node on an imported Mac that relay answers for the shared control plane.
249
+ return localClient({ autostart: false, timeoutMs: probeTimeoutMs, socketPath: apiSocketPath() }).probeHealthz(probeTimeoutMs);
249
250
  }
250
251
  export function probeErrorMessage(error) {
251
252
  const message = error instanceof Error ? error.message : String(error);
@@ -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
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.751",
3
+ "version": "0.3.753",
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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.751",
3
+ "version": "0.3.753",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.751",
3
+ "version": "0.3.753",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.751",
31
- "@north-light/identity": "0.3.751"
30
+ "@north-light/api": "0.3.753",
31
+ "@north-light/identity": "0.3.753"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {