@north-light/api 0.3.750 → 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`,
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 36;
4
+ export declare const CANVAS_SCHEMA_VERSION = 37;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -6,7 +6,7 @@
6
6
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
7
7
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
8
8
  * one below the live database's `schema_min_reader`. */
9
- export const CANVAS_SCHEMA_VERSION = 36;
9
+ export const CANVAS_SCHEMA_VERSION = 37;
10
10
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
11
11
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
12
12
  * it is put in a `search_path` connection option. */
@@ -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,5 +22,5 @@ export async function installLocalTerminalGrant(installId, person) {
22
22
  await replaceGrants([{ id, runtime: installId, sub: person,
23
23
  grantee: 'app:terminal', rev: 1, scopes: TERMINAL_SCOPES,
24
24
  resolved_scopes: TERMINAL_SCOPES, spend_cap: null, expires_at: null,
25
- status: 'active', revoked_at: null, approved_at: now, payer: 'user', dependencies: {}, synced_at: now }], now, 'local');
25
+ status: 'active', revoked_at: null, approved_at: now, payer: person, dependencies: {}, synced_at: now }], now, 'local');
26
26
  }
@@ -17,6 +17,8 @@ export interface GrantRecord {
17
17
  runtime: string;
18
18
  sub: string;
19
19
  grantee: string;
20
+ /** A wildcard grant (`grantee = '*'`): the grantee-principal prefix it covers; null on an exact grant. */
21
+ grantee_prefix?: string | null;
20
22
  rev: number;
21
23
  scopes: GrantScope[];
22
24
  resolved_scopes: GrantScope[];
@@ -25,15 +27,20 @@ export interface GrantRecord {
25
27
  status: 'active' | 'revoked' | 'removed';
26
28
  revoked_at: string | null;
27
29
  approved_at: string | null;
28
- payer: 'user' | 'app' | null;
30
+ /** The principal that pays: the grant's `sub` for an owner-paid grant, its `grantee` for an app-paid one. Null reads as `sub`. */
31
+ payer: string | null;
29
32
  /** The directory's setup entry (`{ state, message?, next, step? }`) per setup id the grantee requires. Absent (an older directory) reads as `{}`. */
30
33
  dependencies?: GrantDependencies;
31
34
  /** The grantee's registered run-notice endpoint (https), or null: runs of this grant send no notice. */
32
35
  run_notice_url?: string | null;
33
- /** The endpoint of an app-paid grant (`payer: 'app'`); null on a user-paid grant or one the directory sent no valid endpoint for. */
36
+ /** The endpoint of an app-paid grant (its payer is an app namespace root); null on a grant that app does not pay or one the directory sent no valid endpoint for. */
34
37
  inference_endpoint?: InferenceEndpoint | null;
35
38
  synced_at: string;
36
39
  }
40
+ /** The payer a mirrored grant carries, as a principal. The directory's older `'user'` (the grant's `sub`) and `'app'` (its `grantee`) read as those principals; anything else must parse as a principal. */
41
+ export declare function principalPayer(payer: unknown, sub: string, grantee: string): string;
42
+ /** Whether the app's inference endpoint pays for this grant's model calls: its payer is an `app:` namespace root. */
43
+ export declare function endpointPays(grant: Pick<GrantRecord, 'payer'>): boolean;
37
44
  export interface ActiveGrant extends GrantRecord {
38
45
  resolved: Scope[];
39
46
  }
@@ -147,9 +154,10 @@ export interface GrantStanding {
147
154
  export declare function grantStanding(grantId: string): Promise<GrantStanding>;
148
155
  /** Ids of the grants in `status` (this runtime's), for a catch-up pass. */
149
156
  export declare function grantIdsWhere(where: string): Promise<string[]>;
150
- /** Who a grant's model calls are charged to: `app` only for a mirrored grant the directory marked app-paid, else the person. */
157
+ /** Who a grant's model calls are charged to: `app` only when the app's endpoint pays (`endpointPays`), else the person. */
151
158
  export declare function payerOfGrant(grantId: string | null | undefined): Promise<'user' | 'app'>;
152
159
  export declare function activeGrant(grantId: string): Promise<ActiveGrant | null>;
160
+ /** `sub`'s active grant to `grantee`: the exact row, else the wildcard row whose `grantee_prefix` is the longest prefix of `grantee`. The `'*'` sentinel never matches as an exact grantee. */
153
161
  export declare function grantFor(grantee: string, sub: string): Promise<ActiveGrant | null>;
154
162
  /** The app's own active grant on this machine. Null for a mirror-only grant: an
155
163
  * unsandboxed machine runs no app, so a fanned-out hosted grant is never "the
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { parseScope } from '@north-light/identity';
2
+ import { parsePrincipal, parseScope } from '@north-light/identity';
3
3
  import { openDb, withCanvasWrite } from '../canvas/db.js';
4
4
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
5
5
  import { replaceWrittenBy, userSubject } from '../permissions/facts.js';
@@ -7,6 +7,21 @@ import { GROUP_TYPE, OBJECT_TYPE } from '../permissions/builtin.js';
7
7
  import { shadowCheck } from './shadow.js';
8
8
  const SETUP_STATES = ['not_started', 'pending', 'ready', 'failed', 'unavailable'];
9
9
  const STRENGTHS = ['ultra', 'strong', 'medium', 'light'];
10
+ /** The payer a mirrored grant carries, as a principal. The directory's older `'user'` (the grant's `sub`) and `'app'` (its `grantee`) read as those principals; anything else must parse as a principal. */
11
+ export function principalPayer(payer, sub, grantee) {
12
+ if (payer === undefined || payer === null || payer === 'user')
13
+ return sub;
14
+ if (payer === 'app')
15
+ return grantee;
16
+ if (typeof payer !== 'string' || parsePrincipal(payer) === null)
17
+ throw new TypeError('invalid grant payer');
18
+ return payer;
19
+ }
20
+ /** Whether the app's inference endpoint pays for this grant's model calls: its payer is an `app:` namespace root. */
21
+ export function endpointPays(grant) {
22
+ const payer = grant.payer === null ? null : parsePrincipal(grant.payer);
23
+ return payer !== null && payer.kind === 'app' && payer.path.length === 0;
24
+ }
10
25
  /** The fleet's runtime principal (`CRTR_RUNTIME`): a cloud role reads only its own runtime's grants, so a person's VM or laptop grants are never used. A Mac sets none. */
11
26
  export function runtimeScope() {
12
27
  const runtime = process.env['CRTR_RUNTIME'];
@@ -93,7 +108,7 @@ function record(row) {
93
108
  // A row whose computed columns lag its revision (a consent written but not yet computed) reads as no grant, never as the previous scopes.
94
109
  if (!computedFor(row.rev, row.computed_rev, row.scopes_json !== null, row.resolved_scopes_json !== null))
95
110
  throw new TypeError('grant columns are not computed for this revision');
96
- return { id: row.id, runtime: row.runtime, sub: row.sub, grantee: row.grantee,
111
+ return { id: row.id, runtime: row.runtime, sub: row.sub, grantee: row.grantee, grantee_prefix: row.grantee_prefix ?? null,
97
112
  rev: row.rev, scopes: entries(JSON.parse(row.scopes_json)),
98
113
  resolved_scopes: entries(JSON.parse(row.resolved_scopes_json)),
99
114
  spend_cap: row.spend_cap, expires_at: row.expires_at, status: row.status,
@@ -342,15 +357,22 @@ export async function grantStanding(grantId) {
342
357
  export async function grantIdsWhere(where) {
343
358
  return (await grantRows('id', where)).map((row) => row.id);
344
359
  }
345
- /** Who a grant's model calls are charged to: `app` only for a mirrored grant the directory marked app-paid, else the person. */
360
+ /** Who a grant's model calls are charged to: `app` only when the app's endpoint pays (`endpointPays`), else the person. */
346
361
  export async function payerOfGrant(grantId) {
347
- return (grantId ? (await grantRecord(grantId))?.payer : null) ?? 'user';
362
+ const grant = grantId ? await grantRecord(grantId) : null;
363
+ return grant !== null && endpointPays(grant) ? 'app' : 'user';
348
364
  }
349
365
  export async function activeGrant(grantId) {
350
366
  return active(await grantRow('*', 'id = ?', [grantId]));
351
367
  }
368
+ /** `sub`'s active grant to `grantee`: the exact row, else the wildcard row whose `grantee_prefix` is the longest prefix of `grantee`. The `'*'` sentinel never matches as an exact grantee. */
352
369
  export async function grantFor(grantee, sub) {
353
- return active(await grantRow('*', 'grantee = ? AND sub = ?', [grantee, sub]));
370
+ const exact = await grantRow('*', 'grantee = ? AND grantee_prefix IS NULL AND sub = ?', [grantee, sub]);
371
+ if (exact)
372
+ return active(exact);
373
+ const rows = await grantRows('*', 'sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)', [sub, grantee]);
374
+ rows.sort((a, b) => b.grantee_prefix.length - a.grantee_prefix.length);
375
+ return active(rows[0]);
354
376
  }
355
377
  /** The app's own active grant on this machine. Null for a mirror-only grant: an
356
378
  * unsandboxed machine runs no app, so a fanned-out hosted grant is never "the
@@ -430,6 +452,8 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
430
452
  !Number.isInteger(grant.rev) || !['active', 'revoked', 'removed'].includes(grant.status)) {
431
453
  throw new TypeError('invalid grant sync response');
432
454
  }
455
+ if ((grant.grantee === '*') !== (grant.grantee_prefix != null))
456
+ throw new TypeError('invalid grant sync response');
433
457
  ids.add(grant.id);
434
458
  entries(grant.scopes);
435
459
  entries(grant.resolved_scopes);
@@ -443,22 +467,22 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
443
467
  ? db.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${kept.map(() => '?').join(',')})`).run(...kept)
444
468
  : db.prepareUncached('DELETE FROM grants').run())).changes);
445
469
  const upsert = db.prepare(`INSERT INTO grants
446
- (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
470
+ (id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
447
471
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
448
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
449
- ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, rev = excluded.rev,
472
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
473
+ ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, grantee_prefix = excluded.grantee_prefix, rev = excluded.rev,
450
474
  scopes_json = excluded.scopes_json, resolved_scopes_json = excluded.resolved_scopes_json, spend_cap = excluded.spend_cap,
451
475
  expires_at = excluded.expires_at, status = excluded.status, revoked_at = excluded.revoked_at, approved_at = excluded.approved_at,
452
476
  payer = excluded.payer, dependencies_json = excluded.dependencies_json, run_notice_url = excluded.run_notice_url,
453
477
  inference_endpoint_json = excluded.inference_endpoint_json, synced_at = excluded.synced_at, computed_rev = excluded.computed_rev
454
- WHERE (grants.runtime, grants.sub, grants.grantee, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
478
+ WHERE (grants.runtime, grants.sub, grants.grantee, grants.grantee_prefix, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
455
479
  grants.expires_at, grants.status, grants.revoked_at, grants.approved_at, grants.payer, grants.dependencies_json,
456
480
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
457
- IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
481
+ IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
458
482
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
459
483
  excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);
460
484
  for (const grant of grants) {
461
- changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, grant.payer, JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
485
+ changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.grantee_prefix ?? null, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, principalPayer(grant.payer, grant.sub, grant.grantee), JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
462
486
  }
463
487
  await replaceWrittenBy(db, 'directory', GROUP_TYPE, 'member', teams.flatMap(({ team, members }) => members.map((member) => ({ resourceId: team, subject: userSubject(member) }))));
464
488
  await reconcileAppAdminFacts(db);
@@ -3,7 +3,7 @@
3
3
  import { directoryIssuer } from '../directory/issuer.js';
4
4
  import { outboundFetch } from '../events/outbound.js';
5
5
  import { warn } from '../output.js';
6
- import { canonicalJson } from './mirror.js';
6
+ import { canonicalJson, principalPayer } from './mirror.js';
7
7
  let ttlMs = 5_000;
8
8
  /** Test hook: how long a cached answer is used before its epochs are re-checked. */
9
9
  export function setShadowTtl(ms) { ttlMs = ms; }
@@ -67,7 +67,9 @@ async function compare(stored) {
67
67
  shadowCounts.lagging++;
68
68
  return;
69
69
  }
70
- const fields = COMPARED.filter((key) => canonicalJson(live[key] ?? null) !== canonicalJson(stored[key] ?? null));
70
+ // The directory may still send the older `'user'`/`'app'` payer; the mirror stores it as a principal.
71
+ const liveSide = { ...live, payer: principalPayer(live['payer'], stored.sub, stored.grantee) };
72
+ const fields = COMPARED.filter((key) => canonicalJson(liveSide[key] ?? null) !== canonicalJson(stored[key] ?? null));
71
73
  if (fields.length === 0) {
72
74
  shadowCounts.agree++;
73
75
  return;
@@ -7,7 +7,7 @@ import { reconcilePackages } from '../graph/package-reconcile.js';
7
7
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
8
8
  import { emitEvent } from '../events/emit.js';
9
9
  import { describeOutboundFailure, outboundFetch, outboundJson, outboundRefusal } from '../events/outbound.js';
10
- import { dependenciesOf, inferenceEndpointOf, replaceGrants, teamsOf } from './mirror.js';
10
+ import { dependenciesOf, endpointPays, inferenceEndpointOf, principalPayer, replaceGrants, teamsOf } from './mirror.js';
11
11
  import { onGrantSync } from './on-sync.js';
12
12
  import { hostedEndpointOf, paymentSetupUrlOf, storeHostedEndpoint } from './hosted-endpoint.js';
13
13
  import { adoptInstallPerson } from '../scoped-state/migrate.js';
@@ -108,11 +108,12 @@ function responseGrant(value, client) {
108
108
  const approvedAt = revisions?.find((revision) => revision.rev === grant.rev)?.approved_at;
109
109
  if (typeof approvedAt !== 'string')
110
110
  throw new TypeError('grant revision has no approval time');
111
- // An absent or unrecognised payer is `user` (an older directory sends none); the endpoint rides only an app-paid grant.
112
- const payer = grant.payer === 'app' ? 'app' : 'user';
111
+ // The payer is a principal; an older directory's `'user'`/`'app'` (or none) maps to the grant's `sub`/`grantee`. The endpoint rides only a grant the app's endpoint pays for.
112
+ const payer = principalPayer(grant.payer, grant.sub, grant.grantee);
113
113
  return { ...grant, spend_cap: grant.spend_cap ?? null, expires_at: grant.expires_at ?? null,
114
+ grantee_prefix: typeof grant.grantee_prefix === 'string' ? grant.grantee_prefix : null,
114
115
  revoked_at: grant.revoked_at ?? null, approved_at: approvedAt, payer, dependencies: dependenciesOf(grant.dependencies),
115
- inference_endpoint: payer === 'app' ? inferenceEndpointOf(grant.inference_endpoint) : null,
116
+ inference_endpoint: endpointPays({ payer }) ? inferenceEndpointOf(grant.inference_endpoint) : null,
116
117
  run_notice_url: typeof grant.run_notice_url === 'string' && grant.run_notice_url !== '' ? grant.run_notice_url : null };
117
118
  }
118
119
  /** The person this pull serves: the bound one, else (a hosted first boot has none until its first snapshot commits) the one
@@ -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
  }
@@ -18,16 +18,16 @@ export type PayerCall = (
18
18
  route: 'subscription' | 'key';
19
19
  sub: string;
20
20
  }
21
- /** A tool call over HTTP: the outbound token's `payer` claim (`app:<id>` when the app pays, else the person). Both are `bill`: the app's holder is invoiced for an app-paid call. */
21
+ /** A tool call over HTTP: the outbound token's `payer` claim, any principal. It is always `bill`; `sub` is used only when the claim is absent. */
22
22
  | {
23
23
  call: 'tool';
24
- tokenPayer: string;
24
+ tokenPayer: string | null | undefined;
25
25
  sub: string;
26
26
  }
27
- /** The payer of a node's model calls, for the start check: `app:<grantee>` when the grant is app-paid, else the person. */
27
+ /** The payer of a node's model calls, for the start check: the grant's principal payer. With none, the grantee's namespace owner when `sub` is in that namespace, else `sub`. */
28
28
  | {
29
29
  call: 'start';
30
- grantPayer: 'user' | 'app' | null | undefined;
30
+ grantPayer: string | null | undefined;
31
31
  sub: string;
32
32
  grantee: string;
33
33
  }) & {
@@ -1,5 +1,7 @@
1
1
  // Payer resolution (design-ledger, "Payer resolution"): one function. It reads the grant's payer and the credential route,
2
2
  // never a request header, so a caller cannot name its payer.
3
+ import { endpointPays } from '../grants/mirror.js';
4
+ import { isNamespaceOwner } from '../grants/owner.js';
3
5
  /** Who pays, and with what funding. A device call is not priced and never asks. */
4
6
  export function payerOf(call) {
5
7
  const paid = fundedBy(call);
@@ -10,9 +12,12 @@ function fundedBy(call) {
10
12
  case 'model':
11
13
  return call.route === 'endpoint' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: call.route };
12
14
  case 'tool':
13
- return call.tokenPayer.startsWith('app:') ? { payer: call.tokenPayer, funding: 'bill' } : { payer: call.sub, funding: 'bill' };
14
- case 'start':
15
+ return { payer: call.tokenPayer || call.sub, funding: 'bill' };
16
+ case 'start': {
15
17
  // Funding is chosen per candidate later; a start check ignores it.
16
- return call.grantPayer === 'app' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: 'bill' };
18
+ if (call.grantPayer)
19
+ return { payer: call.grantPayer, funding: endpointPays({ payer: call.grantPayer }) ? 'endpoint' : 'bill' };
20
+ return { payer: isNamespaceOwner(call.grantee, call.sub) ? call.grantee : call.sub, funding: 'bill' };
21
+ }
17
22
  }
18
23
  }
@@ -5,7 +5,7 @@ import { defaultModelLaddersConfig } from '../../types.js';
5
5
  import { MODEL_STRENGTHS, stripThinkingSuffix } from '../runtime/model-selection.js';
6
6
  import { modelTokenStrength } from '../runtime/launch.js';
7
7
  import { RunError } from '../runs/operations.js';
8
- import { grantRecord } from '../grants/mirror.js';
8
+ import { endpointPays, grantRecord } from '../grants/mirror.js';
9
9
  const STRENGTHS = MODEL_STRENGTHS;
10
10
  /** The endpoint's declared rungs, nearest to `strength` first (the stronger on a tie). */
11
11
  function rungsByDistance(endpoint, strength) {
@@ -55,7 +55,7 @@ export function appCandidates(endpoint, requested, exact = false) {
55
55
  * each rung's own level. */
56
56
  export async function appRungForGrant(grantId, requested, exact = false) {
57
57
  const grant = grantId ? await grantRecord(grantId) : null;
58
- if (grant?.payer !== 'app')
58
+ if (!grant || !endpointPays(grant))
59
59
  return null;
60
60
  if (!grant.inference_endpoint)
61
61
  throw new RunError(404, 'model_unavailable', `${grant.grantee} is app-paid but its grant carries no inference endpoint`);
@@ -1,7 +1,7 @@
1
1
  import { type ThinkingLevel } from '@earendil-works/pi-ai/compat';
2
2
  import { openModelRegistry } from '../runtime/model-registry.js';
3
3
  import { type ManagedProviderId, type SubscriptionCredential } from '../managed-providers.js';
4
- import type { GrantRecord, InferenceEndpoint } from '../grants/mirror.js';
4
+ import { type GrantRecord, type InferenceEndpoint } from '../grants/mirror.js';
5
5
  type WireContent = string | null | Array<{
6
6
  type: 'text';
7
7
  text: string;
@@ -70,7 +70,7 @@ export declare function usdEquivalent(model: {
70
70
  }, total: number): number | null;
71
71
  /** Who the call is made for: the caller's grant decides the payer (RT-RTE-12). A caller with no grant (the person) is user-paid. */
72
72
  export interface LlmCaller {
73
- payer: 'user' | 'app';
73
+ payer: string | null;
74
74
  sub: string;
75
75
  grantee: string;
76
76
  inference_endpoint: InferenceEndpoint | null;
@@ -15,6 +15,7 @@ import { eligibleHostedEndpoint, readHostedEndpoint } from '../grants/hosted-end
15
15
  import { parseProviderPayment } from '../provider-failure.js';
16
16
  import { personIdAsync } from '../canvas/person.js';
17
17
  import { getNode } from '../canvas/canvas.js';
18
+ import { endpointPays } from '../grants/mirror.js';
18
19
  import { outboundToken } from '../providers/mint.js';
19
20
  import { discardFile } from '../providers/token-cache.js';
20
21
  import { ProviderError } from '../providers/errors.js';
@@ -154,7 +155,7 @@ function allowedFallback(model, responseModel) {
154
155
  return fallbacks?.find((fallback) => fallback.provider === model.provider && fallback.model === responseModel);
155
156
  }
156
157
  export function llmCallerOf(grant) {
157
- return grant ? { payer: grant.payer ?? 'user', sub: grant.sub, grantee: grant.grantee, inference_endpoint: grant.inference_endpoint ?? null } : undefined;
158
+ return grant ? { payer: grant.payer, sub: grant.sub, grantee: grant.grantee, inference_endpoint: grant.inference_endpoint ?? null } : undefined;
158
159
  }
159
160
  /** A directory-token failure as the `llm` refusal it is (RT-RTE-26): the directory unreachable or failing is
160
161
  * transient, a refused mint is a configuration fault. */
@@ -184,7 +185,7 @@ function vendorRequestId(headers) {
184
185
  * and a completed call writes one `charges` row. Omitted, the call is neither checked nor recorded.
185
186
  * `causedBy`: the request's `Crtr-Caused-By` value (`message:<id>`, `request:<id>`, `cron_run:<id>`), when it carried one; stored on the row. */
186
187
  export async function runLlm(input, signal, onChunk, target, spend, caller, causedBy) {
187
- const app = caller?.payer === 'app' ? caller : undefined;
188
+ const app = caller && endpointPays(caller) ? caller : undefined;
188
189
  if (input.payer === 'app' && !app)
189
190
  throw new RunError(403, 'payer_not_app', 'this grant is not app-paid');
190
191
  if (input.payer === 'user' && app)
@@ -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
  }
@@ -2,7 +2,7 @@
2
2
  // starts or a dormant node revives. The candidate's payer is whoever pays the node's model calls.
3
3
  import { check, environmentPayerOfProfile, findRefusal, payerOf } from '../ledger/index.js';
4
4
  import { RunError } from '../runs/operations.js';
5
- import { grantStanding, payerOfGrant } from '../grants/mirror.js';
5
+ import { grantRecord, grantStanding } from '../grants/mirror.js';
6
6
  import { callerTerminalGrant } from '../grants/terminal.js';
7
7
  /** The start candidate for an identity, or null when no person is known yet (a terminal node before its first grant snapshot). */
8
8
  export async function startCandidateOf(who) {
@@ -10,7 +10,7 @@ export async function startCandidateOf(who) {
10
10
  const sub = who.sub ?? (grantee === 'app:terminal' ? (await callerTerminalGrant())?.sub : undefined) ?? null;
11
11
  if (sub === null)
12
12
  return null;
13
- const paid = await payerOfGrant(who.grant_id);
13
+ const paid = who.grant_id ? (await grantRecord(who.grant_id))?.payer : null;
14
14
  const payer = payerOf({ call: 'start', grantPayer: paid, sub, grantee, environmentPayer: await environmentPayerOfProfile(who.profile_id) });
15
15
  return { scope: 'start', payer: payer.payer, sub, grantee };
16
16
  }
@@ -48,8 +48,18 @@ export async function mintInstallationToken(sub, repositories, allowPullRequestW
48
48
  if (!response.ok) {
49
49
  const code = typeof parsed.error === 'object' ? parsed.error?.code : parsed.code;
50
50
  const message = (typeof parsed.error === 'object' ? parsed.error?.message : parsed.message) ?? `the GitHub service answered ${response.status}`;
51
- if (response.status === 409 && (code === 'repositories_span_installations' || code === 'github_not_connected'))
52
- throw new ApiError(409, code, message, { repositories });
51
+ // The GitHub app names the page where the person links GitHub and installs the App; the CLI shows it as the next step.
52
+ const next = typeof parsed.error === 'object' ? parsed.error?.next : parsed.next;
53
+ if (response.status === 409 && (code === 'repositories_span_installations' || code === 'github_not_connected')) {
54
+ const connect = typeof next === 'string' && next !== '' ? next : undefined;
55
+ throw new ApiError(409, code, message, { repositories, ...(connect === undefined ? {} : {
56
+ error: code, message,
57
+ next: code === 'github_not_connected'
58
+ ? `Ask the person to open ${connect}, link GitHub and install the Northlight GitHub App on the account that owns these repositories (choose "All repositories"), then retry.`
59
+ : `List repositories from one GitHub account only; manage installations at ${connect}.`,
60
+ url: connect,
61
+ }) });
62
+ }
53
63
  throw new ApiError(502, 'github_service_failed', message, { status: response.status, ...(code === undefined ? {} : { code }) });
54
64
  }
55
65
  if (typeof parsed.token !== 'string' || typeof parsed.expires_at !== 'string')
@@ -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' },
@@ -5,9 +5,12 @@ import { type NoticeTicket } from './sync-notice.js';
5
5
  export interface AppPrincipal {
6
6
  sub: string;
7
7
  grantee: string;
8
+ /** The caller: the token's presenting link (an app, an app owning `sub`'s namespace, or a person acting through an exchanged token). */
9
+ actor: string;
8
10
  client_id: string;
9
- grant: string;
10
- rev: number;
11
+ /** Null for an owner principal, which holds its namespace without a grant row. */
12
+ grant: string | null;
13
+ rev: number | null;
11
14
  resolved: Scope[];
12
15
  resolved_scopes: GrantScope[];
13
16
  spend_cap: number | null;
@@ -58,9 +61,10 @@ export declare class AppPrincipalResolver {
58
61
  * 503 before the mirror loads; every other failure is 401. */
59
62
  verifyCall(authorization: string | undefined): Promise<CallToken>;
60
63
  resolve(authorization: string | undefined, scope?: string): Promise<AppPrincipal>;
61
- /** The caller an already-verified app token names. Grantee, grant and rev come from the token's app link
62
- * (`chain[0]`, which must be the whole chain); the mirror is made to cover the link's `rev` and the grant
63
- * is read now (`coverGrant`). A token whose presenter is not an app link holding a grant is refused 401. */
64
+ /** The caller an already-verified token names, from `chain[0]` (which must be the whole chain): (a) an app link holding a
65
+ * grant, (b) an owner link (a grantless app link whose app owns `sub`'s namespace: no grant row, the app's declared
66
+ * scopes), or (c) a person's grant-bearing link on an exchanged token. A grant is covered by the mirror and read now
67
+ * (`coverGrant`). Any other presenter is refused 401. */
64
68
  resolveVerified(token: CallToken, scope?: string): Promise<AppPrincipal>;
65
69
  }
66
70
  /** The mirrored grant a caller's token names, read now, when it is still the
@@ -68,3 +72,5 @@ export declare class AppPrincipalResolver {
68
72
  * Otherwise 401 `grant_revoked`. `resolve()` and every later re-read during a
69
73
  * request (a `grant.get` long-poll waking) apply this one check. */
70
74
  export declare function callerGrant(caller: Pick<AppPrincipal, 'grant' | 'sub' | 'grantee'>): Promise<ActiveGrant>;
75
+ /** The grant id of a caller that must hold a grant row; an owner principal (CR-9 (b)) holds none, so the operation is 403. */
76
+ export declare function grantIdOf(caller: Pick<AppPrincipal, 'grant'>): string;
@@ -1,6 +1,7 @@
1
- import { covers, JwksCache, MissingRevClaimError, verifyCallToken } from '@north-light/identity';
1
+ import { covers, JwksCache, parsePrincipal, MissingRevClaimError, verifyCallToken } from '@north-light/identity';
2
2
  import { createLocalJWKSet, decodeProtectedHeader, jwtVerify } from 'jose';
3
3
  import { callerGrantOf, coverGrant } from '../../core/grants/cover.js';
4
+ import { ownerScopes } from '../../core/grants/owner.js';
4
5
  import { RunError } from '../../core/runs/operations.js';
5
6
  import { NoticeLedger } from './sync-notice.js';
6
7
  /** The 401 for a handoff that does not verify; one message per purpose, shared by the resolver and the vendor and key pages. */
@@ -119,21 +120,33 @@ export class AppPrincipalResolver {
119
120
  async resolve(authorization, scope) {
120
121
  return this.resolveVerified(await this.verifyCall(authorization), scope);
121
122
  }
122
- /** The caller an already-verified app token names. Grantee, grant and rev come from the token's app link
123
- * (`chain[0]`, which must be the whole chain); the mirror is made to cover the link's `rev` and the grant
124
- * is read now (`coverGrant`). A token whose presenter is not an app link holding a grant is refused 401. */
123
+ /** The caller an already-verified token names, from `chain[0]` (which must be the whole chain): (a) an app link holding a
124
+ * grant, (b) an owner link (a grantless app link whose app owns `sub`'s namespace: no grant row, the app's declared
125
+ * scopes), or (c) a person's grant-bearing link on an exchanged token. A grant is covered by the mirror and read now
126
+ * (`coverGrant`). Any other presenter is refused 401. */
125
127
  async resolveVerified(token, scope) {
126
128
  const link = token.chain[0];
127
129
  const claims = token.claims;
128
- if (token.chain.length !== 1 || !link || !link.sub.startsWith('app:') || link.grant === undefined || link.rev === undefined || !/^[A-Za-z0-9_-]{1,64}$/.test(claims.client_id) ||
130
+ const grantLink = link !== undefined && link.grant !== undefined && link.rev !== undefined;
131
+ const person = link !== undefined && parsePrincipal(link.sub)?.kind === 'user';
132
+ if (token.chain.length !== 1 || !link || !/^[A-Za-z0-9_-]{1,64}$/.test(claims.client_id) ||
133
+ !(link.owner === true || (grantLink && (link.sub.startsWith('app:') || person))) ||
129
134
  (claims.grantee !== undefined && claims.grantee !== link.sub) || (claims['rev'] !== undefined && claims['rev'] !== link.rev)) {
130
135
  throw new RunError(401, 'unauthorized', 'invalid directory access token');
131
136
  }
137
+ if (link.owner === true) {
138
+ const resolved = ownerScopes(link.sub);
139
+ if (scope && !resolved.some((held) => covers(held, scope))) {
140
+ throw new RunError(403, 'scope_missing', `missing scope ${scope}`, undefined, undefined, scope);
141
+ }
142
+ return { sub: token.sub, grantee: link.sub, actor: link.sub, client_id: claims.client_id, grant: null, rev: null, resolved,
143
+ resolved_scopes: resolved.map((held) => ({ scope: held, mode: 'always' })), spend_cap: null, dependencies: {}, exp: claims.exp };
144
+ }
132
145
  const grant = await coverGrant(link.grant, link.rev, token.sub, link.sub, this.syncGrants);
133
146
  if (scope && !grant.resolved.some((held) => covers(held, scope))) {
134
147
  throw new RunError(403, 'scope_missing', `missing scope ${scope}`, undefined, undefined, scope);
135
148
  }
136
- return { sub: token.sub, grantee: link.sub, client_id: claims.client_id, grant: link.grant,
149
+ return { sub: token.sub, grantee: link.sub, actor: link.sub, client_id: claims.client_id, grant: link.grant,
137
150
  rev: grant.rev, resolved: grant.resolved, resolved_scopes: grant.resolved_scopes,
138
151
  spend_cap: grant.spend_cap, dependencies: grant.dependencies ?? {}, exp: claims.exp };
139
152
  }
@@ -143,5 +156,11 @@ export class AppPrincipalResolver {
143
156
  * Otherwise 401 `grant_revoked`. `resolve()` and every later re-read during a
144
157
  * request (a `grant.get` long-poll waking) apply this one check. */
145
158
  export async function callerGrant(caller) {
146
- return await callerGrantOf(caller.grant, caller.sub, caller.grantee);
159
+ return await callerGrantOf(grantIdOf(caller), caller.sub, caller.grantee);
160
+ }
161
+ /** The grant id of a caller that must hold a grant row; an owner principal (CR-9 (b)) holds none, so the operation is 403. */
162
+ export function grantIdOf(caller) {
163
+ if (caller.grant === null)
164
+ throw new RunError(403, 'permission_error', 'this operation needs a grant; an owner token holds none');
165
+ return caller.grant;
147
166
  }
@@ -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.750",
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",