@north-light/api 0.3.747 → 0.3.748
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.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/objects.d.ts +6 -1
- package/dist/api/dto/plugins.d.ts +2 -0
- package/dist/commands/canvas/list.js +3 -1
- package/dist/commands/canvas/read.js +4 -2
- package/dist/commands/canvas/search.js +3 -1
- package/dist/core/canvas/canvas.js +1 -1
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command-manifests/registry.d.ts +2 -1
- package/dist/core/command-plugins/compose.js +5 -3
- package/dist/core/command.d.ts +11 -0
- package/dist/core/command.js +33 -1
- package/dist/core/environments.d.ts +2 -1
- package/dist/core/environments.js +2 -2
- package/dist/core/grants/mirror.d.ts +4 -0
- package/dist/core/grants/mirror.js +16 -1
- package/dist/core/grants/on-sync.js +2 -2
- package/dist/core/ledger/environment-payer.d.ts +2 -0
- package/dist/core/ledger/environment-payer.js +15 -0
- package/dist/core/ledger/index.d.ts +1 -0
- package/dist/core/ledger/index.js +1 -0
- package/dist/core/ledger/payer.d.ts +4 -1
- package/dist/core/ledger/payer.js +4 -0
- package/dist/core/llm/run.d.ts +1 -0
- package/dist/core/llm/run.js +2 -1
- package/dist/core/permissions/evaluator.js +5 -3
- package/dist/core/providers/call.js +2 -2
- package/dist/core/runs/node-sub.d.ts +2 -0
- package/dist/core/runs/node-sub.js +10 -0
- package/dist/core/runtime/host.js +2 -2
- package/dist/core/runtime/spawn.js +1 -1
- package/dist/core/runtime/start-check.d.ts +1 -0
- package/dist/core/runtime/start-check.js +2 -2
- package/dist/core/runtime/warm-pool.js +1 -1
- package/dist/core/spaces/process.js +5 -4
- package/dist/daemon/api/handlers/bash-jobs.js +1 -1
- package/package.json +1 -1
package/dist/api/contract.d.ts
CHANGED
|
@@ -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.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.75";
|
|
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`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -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.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.75';
|
|
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`. */
|
|
@@ -127,7 +127,8 @@ export interface ObjectRemoteDTO {
|
|
|
127
127
|
export type ObjectReadDTO = ObjectLiveReadDTO | ObjectDeletedDTO | ObjectRemoteDTO | ObjectUnknownDTO;
|
|
128
128
|
export interface ObjectReadQuery {
|
|
129
129
|
fields?: boolean; /** Read on this machine (`runtime:<id>`), as a merged listing or inbox entry names it. */
|
|
130
|
-
machine?: string;
|
|
130
|
+
machine?: string; /** The person (`user:<id>`) this read acts for, from `--as`. */
|
|
131
|
+
as?: string;
|
|
131
132
|
}
|
|
132
133
|
export interface ObjectListRequest {
|
|
133
134
|
/** A kind name. */
|
|
@@ -143,6 +144,8 @@ export interface ObjectListRequest {
|
|
|
143
144
|
cursor?: string;
|
|
144
145
|
/** List only this machine (`runtime:<id>`), paging through its cursor. `self` lists only this machine without labels. */
|
|
145
146
|
machine?: string;
|
|
147
|
+
/** The person (`user:<id>`) this read acts for, from `--as`. */
|
|
148
|
+
as?: string;
|
|
146
149
|
/** Documents whose `extensions` hold these top-level fields (equality), e.g. `{ firstlight: { workspace_id: 'w1', state: 'active' } }`. Applied inside the permission-filtered query, before `limit`. */
|
|
147
150
|
extensions?: Record<string, Record<string, unknown>>;
|
|
148
151
|
/** Documents that are instances of this app type (`firstlight/memory`). */
|
|
@@ -184,6 +187,8 @@ export interface ObjectSearchRequest {
|
|
|
184
187
|
kind?: string;
|
|
185
188
|
owner?: string;
|
|
186
189
|
limit?: number;
|
|
190
|
+
/** The person (`user:<id>`) this read acts for, from `--as`. */
|
|
191
|
+
as?: string;
|
|
187
192
|
/** As on `ObjectListRequest`: applied inside the query in every search mode (name, `body`, `grep`). */
|
|
188
193
|
extensions?: Record<string, Record<string, unknown>>;
|
|
189
194
|
schema_type?: string;
|
|
@@ -15,6 +15,8 @@ export interface PluginCallHeadersRequestDTO {
|
|
|
15
15
|
header_names: string[];
|
|
16
16
|
/** Lowercase hex sha256 over `<name>:<value>\n` for each name in `header_names`. */
|
|
17
17
|
headers_sha256: string;
|
|
18
|
+
/** The person (`user:<id>`) this call acts for, from `--as`; absent when the node acts for itself. */
|
|
19
|
+
as?: string;
|
|
18
20
|
}
|
|
19
21
|
export interface PluginCallHeadersDTO {
|
|
20
22
|
/** `Crtr-Caller`, and `Crtr-Signature` when the call qualifies for signing. */
|
|
@@ -36,7 +36,8 @@ export const listLeaf = defineLeaf({
|
|
|
36
36
|
outputKind: 'object',
|
|
37
37
|
effects: ['None. Listing records no watch.'],
|
|
38
38
|
},
|
|
39
|
-
|
|
39
|
+
actingAs: true,
|
|
40
|
+
run: async (input, context) => {
|
|
40
41
|
const query = {
|
|
41
42
|
...(input['type'] ? { type: input['type'] } : {}),
|
|
42
43
|
...(input['kind'] ? { kind: input['kind'] } : {}),
|
|
@@ -46,6 +47,7 @@ export const listLeaf = defineLeaf({
|
|
|
46
47
|
...(input['deleted'] === true ? { deleted: true } : {}),
|
|
47
48
|
...(input['shared'] === true ? { shared: true } : {}),
|
|
48
49
|
...(input['machine'] ? { machine: input['machine'] } : {}),
|
|
50
|
+
...(context?.as === undefined ? {} : { as: context.as }),
|
|
49
51
|
limit: input['limit'] ?? 50,
|
|
50
52
|
...(input['cursor'] ? { cursor: input['cursor'] } : {}),
|
|
51
53
|
};
|
|
@@ -80,9 +80,11 @@ export const readLeaf = defineLeaf({
|
|
|
80
80
|
outputKind: 'object',
|
|
81
81
|
effects: ['A live read records a watch on the object for you (every event subject) and publishes a read event to its other watchers. A deleted or remote answer records nothing.'],
|
|
82
82
|
},
|
|
83
|
-
|
|
83
|
+
actingAs: true,
|
|
84
|
+
run: async (input, context) => {
|
|
84
85
|
try {
|
|
85
|
-
|
|
86
|
+
const query = { ...(input['fields'] === true ? { fields: true } : {}), ...(context?.as === undefined ? {} : { as: context.as }) };
|
|
87
|
+
return { ...(await cliClient().objects.read(input['ref'], Object.keys(query).length === 0 ? undefined : query)) };
|
|
86
88
|
}
|
|
87
89
|
catch (err) {
|
|
88
90
|
rethrowAsCliError(err);
|
|
@@ -23,7 +23,8 @@ export const searchLeaf = defineLeaf({
|
|
|
23
23
|
outputKind: 'object',
|
|
24
24
|
effects: ['None. Searching records no watch.'],
|
|
25
25
|
},
|
|
26
|
-
|
|
26
|
+
actingAs: true,
|
|
27
|
+
run: async (input, context) => {
|
|
27
28
|
const request = {
|
|
28
29
|
text: input['text'],
|
|
29
30
|
...(input['body'] === true ? { body: true } : {}),
|
|
@@ -32,6 +33,7 @@ export const searchLeaf = defineLeaf({
|
|
|
32
33
|
...(input['kind'] ? { kind: input['kind'] } : {}),
|
|
33
34
|
...(input['owner'] ? { owner: input['owner'] } : {}),
|
|
34
35
|
...(input['limit'] ? { limit: input['limit'] } : {}),
|
|
36
|
+
...(context?.as === undefined ? {} : { as: context.as }),
|
|
35
37
|
};
|
|
36
38
|
try {
|
|
37
39
|
return { ...(await cliClient().objects.search(request)) };
|
|
@@ -61,7 +61,7 @@ async function seedRow(meta, db) {
|
|
|
61
61
|
const profile = meta.profile_id ? await profileObjectFor(db, meta.profile_id, app, meta.grantee ?? 'app:terminal') : null;
|
|
62
62
|
await createObject(db, { id: meta.node_id, type: 'node', kind: meta.kind, owner: (profile ?? app).id, privacy: 'public', name: meta.name, preview: '' });
|
|
63
63
|
// A node directly under an app is readable by the person it was made for.
|
|
64
|
-
if (profile === null && meta.sub)
|
|
64
|
+
if (profile === null && meta.sub && !meta.sub.startsWith('app:'))
|
|
65
65
|
await writeActsFor(db, meta.node_id, meta.sub);
|
|
66
66
|
await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill('?').join(', ')})`)
|
|
67
67
|
.run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.deleting_at ?? null, meta.caused_by ?? null, app.id);
|
|
@@ -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 =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 35;
|
|
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 =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 35;
|
|
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. */
|
|
@@ -18,7 +18,8 @@ export declare function qualifiedTopLevelCommandName(contributor: Pick<CommandCo
|
|
|
18
18
|
export type LeafAdapter = (leaf: DeclLeafBase, commandPath: readonly string[]) => {
|
|
19
19
|
outputKind: 'object' | 'jsonl';
|
|
20
20
|
run: LeafDef['run']; /** The leaf calls a device machine: it takes `--machine <id>` (see `LeafDef.machineSelector`). */
|
|
21
|
-
machineSelector?: true;
|
|
21
|
+
machineSelector?: true; /** The leaf takes `--as <user:id>` (see `LeafDef.actingAs`). */
|
|
22
|
+
actingAs?: true;
|
|
22
23
|
};
|
|
23
24
|
/** One accepted external contribution after collision resolution: a validated
|
|
24
25
|
* top-level branch node, contributor identity, and the adapter callback that
|
|
@@ -56,6 +56,7 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
56
56
|
return {
|
|
57
57
|
outputKind: 'object',
|
|
58
58
|
...(machineTransport ? { machineSelector: true } : {}),
|
|
59
|
+
actingAs: true,
|
|
59
60
|
run: async (input, context) => {
|
|
60
61
|
const argumentsForDaemon = { ...input };
|
|
61
62
|
for (const param of leaf.params) {
|
|
@@ -79,7 +80,7 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
79
80
|
}
|
|
80
81
|
try {
|
|
81
82
|
const result = await cliClient({ timeoutMs: 0 }).request('POST', '/v1/provider/call', {
|
|
82
|
-
provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }),
|
|
83
|
+
provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }), ...(context?.as === undefined ? {} : { as: context.as }),
|
|
83
84
|
}, { timeout: 0 });
|
|
84
85
|
if (filesCrossByUpload()) {
|
|
85
86
|
for (const field of leaf.output ?? []) {
|
|
@@ -201,6 +202,7 @@ function adaptLeaf(contribution, commandPathFor) {
|
|
|
201
202
|
const httpLeaf = leaf;
|
|
202
203
|
return {
|
|
203
204
|
outputKind: httpLeaf.rest.streaming === true ? 'jsonl' : 'object',
|
|
205
|
+
actingAs: true,
|
|
204
206
|
run: (input, context) => invokeHttpLeaf({
|
|
205
207
|
registration: { name: contribution.plugin.name, endpoint: transport.endpoint, ...(transport.authEnv !== undefined ? { authEnv: transport.authEnv } : {}) },
|
|
206
208
|
...(contribution.manifest?.baseUrl !== undefined ? { baseUrl: contribution.manifest.baseUrl } : {}),
|
|
@@ -209,7 +211,7 @@ function adaptLeaf(contribution, commandPathFor) {
|
|
|
209
211
|
}, input, context, {
|
|
210
212
|
// crtrd names the caller and decides, from the final URL, whether to sign. Only digests leave this process.
|
|
211
213
|
callHeaders: (plan) => cliClient().plugins.callHeaders(contribution.plugin.name, {
|
|
212
|
-
method: plan.method, url: plan.url.href, body_sha256: sha256Hex(plan.body), ...signedHeaderDigest(plan.headers),
|
|
214
|
+
method: plan.method, url: plan.url.href, body_sha256: sha256Hex(plan.body), ...signedHeaderDigest(plan.headers), ...(context?.as === undefined ? {} : { as: context.as }),
|
|
213
215
|
}).then((answer) => answer.headers, (error) => { throw error instanceof ApiError ? apiErrorToCliError(error) : error; }),
|
|
214
216
|
}),
|
|
215
217
|
};
|
|
@@ -257,5 +259,5 @@ function buildBranch(contribution, node, path, toolPrefixLength = 1, allowedTool
|
|
|
257
259
|
}
|
|
258
260
|
function buildLeaf(contribution, node, path) {
|
|
259
261
|
const adapted = contribution.adaptLeaf(node, path);
|
|
260
|
-
return defineLeaf({ name: node.name, description: node.description, whenToUse: node.whenToUse, ...(node.tier !== undefined ? { tier: node.tier } : {}), ...(contribution.plugin !== undefined ? { plugin: contribution.plugin } : {}), ...(adapted.machineSelector === true ? { machineSelector: true } : {}), help: { name: path.join(' '), summary: node.summary, ...(adapted.machineSelector === true ? { guide: MACHINE_SELECTOR_GUIDE } : {}), params: node.params, output: node.output, outputKind: adapted.outputKind, effects: [...node.effects] }, run: adapted.run });
|
|
262
|
+
return defineLeaf({ name: node.name, description: node.description, whenToUse: node.whenToUse, ...(node.tier !== undefined ? { tier: node.tier } : {}), ...(contribution.plugin !== undefined ? { plugin: contribution.plugin } : {}), ...(adapted.machineSelector === true ? { machineSelector: true } : {}), ...(adapted.actingAs === true ? { actingAs: true } : {}), help: { name: path.join(' '), summary: node.summary, ...(adapted.machineSelector === true ? { guide: MACHINE_SELECTOR_GUIDE } : {}), params: node.params, output: node.output, outputKind: adapted.outputKind, effects: [...node.effects] }, run: adapted.run });
|
|
261
263
|
}
|
package/dist/core/command.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export interface LeafRunContext {
|
|
|
21
21
|
/** The `--machine <id>` selector of a provider leaf, parsed outside the leaf's declared params
|
|
22
22
|
* (see `LeafDef.machineSelector`); absent when the caller did not pass one. */
|
|
23
23
|
readonly machine?: string;
|
|
24
|
+
/** The `--as <user:id>` of a leaf that opted in with `actingAs`: the person this one call acts for, parsed outside the leaf's declared params. */
|
|
25
|
+
readonly as?: string;
|
|
24
26
|
}
|
|
25
27
|
/** Opt-in flag that surfaces a node as an editor slash command (a pi prompt
|
|
26
28
|
* template / Claude Code command). When set, the bootstrap auto-writes a
|
|
@@ -63,6 +65,8 @@ export interface LeafDef {
|
|
|
63
65
|
/** A capability-provider leaf: the dispatcher takes `--machine <id>` (or `--machine=<id>`) out of argv before the leaf's params
|
|
64
66
|
* parse and hands it to `run` as `context.machine`. It is a call selector, never one of the leaf's declared parameters. */
|
|
65
67
|
machineSelector?: true;
|
|
68
|
+
/** The dispatcher takes `--as <user:id>` out of argv before the leaf's params parse and hands it to `run` as `context.as`. Never one of the leaf's declared parameters. */
|
|
69
|
+
actingAs?: true;
|
|
66
70
|
run: (input: Record<string, unknown>, context?: LeafRunContext) => Promise<Record<string, unknown> | void>;
|
|
67
71
|
/** Optional bespoke renderer: turn the result into instruction-shaped
|
|
68
72
|
* XML+markdown the agent acts on. Omit to fall back to the schema-driven
|
|
@@ -145,6 +149,8 @@ export declare function defineLeaf(opts: {
|
|
|
145
149
|
hookEligible?: false;
|
|
146
150
|
/** See `LeafDef.machineSelector`. */
|
|
147
151
|
machineSelector?: true;
|
|
152
|
+
/** See `LeafDef.actingAs`. */
|
|
153
|
+
actingAs?: true;
|
|
148
154
|
run: (input: Record<string, unknown>, context?: LeafRunContext) => Promise<Record<string, unknown> | void>;
|
|
149
155
|
render?: (result: Record<string, unknown>) => string;
|
|
150
156
|
preview?: (result: Record<string, unknown>) => Record<string, unknown>;
|
|
@@ -233,6 +239,11 @@ export declare function takeMachineSelector(tokens: readonly string[]): {
|
|
|
233
239
|
rest: string[];
|
|
234
240
|
machine?: string;
|
|
235
241
|
};
|
|
242
|
+
/** Take the `--as <user:id>` / `--as=<user:id>` option out of an opted-in leaf's argv. Nothing after a bare `--` is a flag. */
|
|
243
|
+
export declare function takeActingAs(tokens: readonly string[]): {
|
|
244
|
+
rest: string[];
|
|
245
|
+
as?: string;
|
|
246
|
+
};
|
|
236
247
|
export declare const GLOBAL_TOKENS: ReadonlySet<string>;
|
|
237
248
|
export declare function runCli(root: RootDef, argv: string[]): Promise<void>;
|
|
238
249
|
export {};
|
package/dist/core/command.js
CHANGED
|
@@ -42,6 +42,7 @@ export function defineLeaf(opts) {
|
|
|
42
42
|
hookEligible: opts.hookEligible,
|
|
43
43
|
plugin: opts.plugin,
|
|
44
44
|
machineSelector: opts.machineSelector,
|
|
45
|
+
actingAs: opts.actingAs,
|
|
45
46
|
run: opts.run,
|
|
46
47
|
render: opts.render,
|
|
47
48
|
preview: opts.preview,
|
|
@@ -720,6 +721,31 @@ export function takeMachineSelector(tokens) {
|
|
|
720
721
|
}
|
|
721
722
|
return machine === undefined ? { rest } : { rest, machine };
|
|
722
723
|
}
|
|
724
|
+
/** Take the `--as <user:id>` / `--as=<user:id>` option out of an opted-in leaf's argv. Nothing after a bare `--` is a flag. */
|
|
725
|
+
export function takeActingAs(tokens) {
|
|
726
|
+
const rest = [];
|
|
727
|
+
let as;
|
|
728
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
729
|
+
const token = tokens[i];
|
|
730
|
+
if (token === '--') {
|
|
731
|
+
rest.push(...tokens.slice(i));
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
const inline = token.startsWith('--as=') ? token.slice('--as='.length) : undefined;
|
|
735
|
+
if (token !== '--as' && inline === undefined) {
|
|
736
|
+
rest.push(token);
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
const value = inline ?? tokens[i + 1];
|
|
740
|
+
if (value === undefined || !/^user:[^\s]+$/.test(value)) {
|
|
741
|
+
throw parseArgvError('missing_parameter', '--as requires a person id like user:<id>', '--as', 'as', 'Name the person this call acts for, for example `--as user:alice`.');
|
|
742
|
+
}
|
|
743
|
+
if (inline === undefined)
|
|
744
|
+
i++;
|
|
745
|
+
as = value;
|
|
746
|
+
}
|
|
747
|
+
return as === undefined ? { rest } : { rest, as };
|
|
748
|
+
}
|
|
723
749
|
export const GLOBAL_TOKENS = new Set(['--json', '--no-autostart']);
|
|
724
750
|
export async function runCli(root, argv) {
|
|
725
751
|
// argv is process.argv — strip node binary + script path. `--json` is a
|
|
@@ -826,6 +852,12 @@ export async function runCli(root, argv) {
|
|
|
826
852
|
leafTokens = selected.rest;
|
|
827
853
|
machine = selected.machine;
|
|
828
854
|
}
|
|
855
|
+
let acting;
|
|
856
|
+
if (leaf.actingAs === true && !params.some((param) => param.kind === 'flag' && param.name === 'as')) {
|
|
857
|
+
const taken = takeActingAs(leafTokens);
|
|
858
|
+
leafTokens = taken.rest;
|
|
859
|
+
acting = taken.as;
|
|
860
|
+
}
|
|
829
861
|
const input = await parseArgv(params, leafTokens, {
|
|
830
862
|
leafPath: path,
|
|
831
863
|
onProvidedParams: (provided) => {
|
|
@@ -835,7 +867,7 @@ export async function runCli(root, argv) {
|
|
|
835
867
|
contextFilePaths = paths;
|
|
836
868
|
},
|
|
837
869
|
});
|
|
838
|
-
const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }) };
|
|
870
|
+
const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }), ...(acting === undefined ? {} : { as: acting }) };
|
|
839
871
|
const result = await operationIdContext.fresh(() => leaf.run(input, context));
|
|
840
872
|
publishPreviewResult(result === undefined || result === null ? result : leaf.preview?.(result) ?? result);
|
|
841
873
|
if (result !== undefined && result !== null) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { CanvasDb } from './canvas/db.js';
|
|
2
2
|
import { type EnvironmentRecipeInput } from './environment-recipe.js';
|
|
3
3
|
/** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
|
|
4
|
-
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
|
|
4
|
+
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. `payer` (null by default: the run's `sub` pays) names who pays; an app environment passes `person` and `grantee` as `app:<id>` and `payer` the same. Runs in the
|
|
5
5
|
* caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
|
|
6
6
|
* here under `grantee`'s app, with the profile id as its handle: a cloud role serves many people and a profile name is not unique
|
|
7
7
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
@@ -9,6 +9,7 @@ export declare function createProfileBlaxelEnvironment(db: CanvasDb, spec: {
|
|
|
9
9
|
profileId: string;
|
|
10
10
|
grantee: string;
|
|
11
11
|
person: string;
|
|
12
|
+
payer?: string;
|
|
12
13
|
memoryMb?: number;
|
|
13
14
|
recipe?: EnvironmentRecipeInput;
|
|
14
15
|
}): Promise<string>;
|
|
@@ -5,7 +5,7 @@ import { writeActsFor } from './permissions/facts.js';
|
|
|
5
5
|
import { writeEnvironmentRecipe } from './environment-recipe.js';
|
|
6
6
|
import { setCloudProfileWriter } from './profiles/manifest.js';
|
|
7
7
|
/** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
|
|
8
|
-
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
|
|
8
|
+
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. `payer` (null by default: the run's `sub` pays) names who pays; an app environment passes `person` and `grantee` as `app:<id>` and `payer` the same. Runs in the
|
|
9
9
|
* caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
|
|
10
10
|
* here under `grantee`'s app, with the profile id as its handle: a cloud role serves many people and a profile name is not unique
|
|
11
11
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
@@ -14,7 +14,7 @@ export async function createProfileBlaxelEnvironment(db, spec) {
|
|
|
14
14
|
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
|
|
15
15
|
const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
|
|
16
16
|
await writeActsFor(db, object.id, spec.person);
|
|
17
|
-
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)`).run(object.id, spec.memoryMb ?? 2048, new Date().toISOString());
|
|
17
|
+
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
18
|
if (spec.recipe !== undefined)
|
|
19
19
|
await writeEnvironmentRecipe(db, object.id, spec.recipe);
|
|
20
20
|
return object.id;
|
|
@@ -189,6 +189,10 @@ export declare function teamsOf(value: unknown): TeamRecord[];
|
|
|
189
189
|
/** Replace the mirror with `grants` and the `written_by = 'directory'` team `member` facts with `teams`, in one transaction. The
|
|
190
190
|
* ledger's `grant:<id>` limit rows follow from the `grants` trigger `crtr_grant_limit` (schema delta 002). */
|
|
191
191
|
export declare function replaceGrants(grants: readonly GrantRecord[], syncedAt: string, source: string, teams?: readonly TeamRecord[]): Promise<void>;
|
|
192
|
+
export declare const APP_ADMIN_WRITER = "app-admin";
|
|
193
|
+
/** Make `editor`, `messenger` and `user_of` on each app object exactly its app's `admin` tuples (a `user` or a `crtr/group#member` team),
|
|
194
|
+
* so a removed admin loses them. Runs in the caller's transaction; the admin tuples are the directory's, the facts it writes are `written_by = 'app-admin'`. */
|
|
195
|
+
export declare function reconcileAppAdminFacts(db: CanvasDb): Promise<void>;
|
|
192
196
|
/** Bumped by every `replaceGrants`. A launch compiled against one generation
|
|
193
197
|
* and started under another may hold mounts the new mirror no longer grants. */
|
|
194
198
|
export declare function grantsGeneration(): Promise<number>;
|
|
@@ -3,7 +3,7 @@ import { 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';
|
|
6
|
-
import { GROUP_TYPE } from '../permissions/builtin.js';
|
|
6
|
+
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'];
|
|
@@ -461,11 +461,26 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
|
|
|
461
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);
|
|
462
462
|
}
|
|
463
463
|
await replaceWrittenBy(db, 'directory', GROUP_TYPE, 'member', teams.flatMap(({ team, members }) => members.map((member) => ({ resourceId: team, subject: userSubject(member) }))));
|
|
464
|
+
await reconcileAppAdminFacts(db);
|
|
464
465
|
await db.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(source);
|
|
465
466
|
if (changed > 0)
|
|
466
467
|
await db.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run();
|
|
467
468
|
});
|
|
468
469
|
}
|
|
470
|
+
/** The relations an app's admins hold on the app object: they reach its profiles, environments and nodes through `parent->` (app-runtimes D8). */
|
|
471
|
+
const ADMIN_RELATIONS = ['editor', 'messenger', 'user_of'];
|
|
472
|
+
export const APP_ADMIN_WRITER = 'app-admin';
|
|
473
|
+
/** Make `editor`, `messenger` and `user_of` on each app object exactly its app's `admin` tuples (a `user` or a `crtr/group#member` team),
|
|
474
|
+
* so a removed admin loses them. Runs in the caller's transaction; the admin tuples are the directory's, the facts it writes are `written_by = 'app-admin'`. */
|
|
475
|
+
export async function reconcileAppAdminFacts(db) {
|
|
476
|
+
const admins = await db.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
|
|
477
|
+
JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
|
|
478
|
+
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(GROUP_TYPE);
|
|
479
|
+
const facts = admins.map((a) => ({ resourceId: a.object,
|
|
480
|
+
subject: a.subject_type === GROUP_TYPE ? { type: GROUP_TYPE, id: a.subject_id, relation: 'member' } : { type: 'user', id: a.subject_id, relation: '' } }));
|
|
481
|
+
for (const relation of ADMIN_RELATIONS)
|
|
482
|
+
await replaceWrittenBy(db, APP_ADMIN_WRITER, OBJECT_TYPE, relation, facts);
|
|
483
|
+
}
|
|
469
484
|
/** Bumped by every `replaceGrants`. A launch compiled against one generation
|
|
470
485
|
* and started under another may hold mounts the new mirror no longer grants. */
|
|
471
486
|
export async function grantsGeneration() {
|
|
@@ -14,7 +14,7 @@ import { checkCronFire } from '../../daemon/cron/authority.js';
|
|
|
14
14
|
import { cronExecutionFor } from '../../daemon/cron/live-runs.js';
|
|
15
15
|
import { cronExecutionsReady } from '../../daemon/cron/run-socket.js';
|
|
16
16
|
import { flatMapAsync } from '../async-array.js';
|
|
17
|
-
import {
|
|
17
|
+
import { launchSub } from '../runs/node-sub.js';
|
|
18
18
|
async function appUserOwners() {
|
|
19
19
|
return new Map((await (await openDb()).prepare('SELECT uid, app, status FROM app_users').all())
|
|
20
20
|
.map((row) => [row.uid, { app: row.app, status: row.status }]));
|
|
@@ -51,7 +51,7 @@ export async function exceeds(sandbox, owners) {
|
|
|
51
51
|
permissions = await permissionsForRun(cronExecution.grantee, cronExecution.sub, cronExecution.grantId, cronScopes);
|
|
52
52
|
}
|
|
53
53
|
else if (node && node.grantee === owner.app) {
|
|
54
|
-
permissions = await permissionsForRun(owner.app, node.sub
|
|
54
|
+
permissions = await permissionsForRun(owner.app, launchSub(node.sub, node.node_id), node.grant_id ?? null, node.scopes ?? null);
|
|
55
55
|
}
|
|
56
56
|
else {
|
|
57
57
|
// A process without a node (an unanchored cron, a delivery) runs on the app's whole grant.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The payer stored on the environment a profile or node runs in (`environments.payer`); null when the profile has no environment
|
|
2
|
+
// or the environment names none, in which case the run's `sub` pays as before.
|
|
3
|
+
import { openDb } from '../canvas/db.js';
|
|
4
|
+
export async function environmentPayerOfProfile(profileId) {
|
|
5
|
+
if (!profileId)
|
|
6
|
+
return null;
|
|
7
|
+
const row = await (await openDb()).prepare('SELECT e.payer AS payer FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?').get(profileId);
|
|
8
|
+
return row?.payer ?? null;
|
|
9
|
+
}
|
|
10
|
+
export async function environmentPayerOfNode(nodeId) {
|
|
11
|
+
if (!nodeId)
|
|
12
|
+
return null;
|
|
13
|
+
const row = await (await openDb()).prepare('SELECT e.payer AS payer FROM nodes n JOIN profiles p ON p.id = n.profile_id JOIN environments e ON e.object = p.environment_id WHERE n.node_id = ?').get(nodeId);
|
|
14
|
+
return row?.payer ?? null;
|
|
15
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
2
|
export * from './months.js';
|
|
3
|
+
export { environmentPayerOfNode, environmentPayerOfProfile } from './environment-payer.js';
|
|
3
4
|
export { payerOf, type Payer, type PayerCall } from './payer.js';
|
|
4
5
|
export { writeCharge, receiptChargeId, chargeOf, type WriteResult } from './charges.js';
|
|
5
6
|
export { check, findRefusal, refusalError, refusedMark, userActionOf, type Candidate, type CallCandidate, type StartCandidate, type Refusal } from './check.js';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The ledger core (design-ledger, cycle 4). Every site calls these.
|
|
2
2
|
export * from './types.js';
|
|
3
3
|
export * from './months.js';
|
|
4
|
+
export { environmentPayerOfNode, environmentPayerOfProfile } from './environment-payer.js';
|
|
4
5
|
export { payerOf } from './payer.js';
|
|
5
6
|
export { writeCharge, receiptChargeId, chargeOf } from './charges.js';
|
|
6
7
|
export { check, findRefusal, refusalError, refusedMark, userActionOf } from './check.js';
|
|
@@ -3,7 +3,8 @@ export interface Payer {
|
|
|
3
3
|
payer: string;
|
|
4
4
|
funding: Funding;
|
|
5
5
|
}
|
|
6
|
-
|
|
6
|
+
/** `environmentPayer`: the payer stored on the environment the calling node runs in (`environments.payer`). When set it is the payer of every call; funding is unchanged. */
|
|
7
|
+
export type PayerCall = (
|
|
7
8
|
/** A model call on an app-paid grant: the app's inference endpoint pays. `grantee` is the app principal (`app:<id>`). */
|
|
8
9
|
{
|
|
9
10
|
call: 'model';
|
|
@@ -29,6 +30,8 @@ export type PayerCall =
|
|
|
29
30
|
grantPayer: 'user' | 'app' | null | undefined;
|
|
30
31
|
sub: string;
|
|
31
32
|
grantee: string;
|
|
33
|
+
}) & {
|
|
34
|
+
environmentPayer?: string | null;
|
|
32
35
|
};
|
|
33
36
|
/** Who pays, and with what funding. A device call is not priced and never asks. */
|
|
34
37
|
export declare function payerOf(call: PayerCall): Payer;
|
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// never a request header, so a caller cannot name its payer.
|
|
3
3
|
/** Who pays, and with what funding. A device call is not priced and never asks. */
|
|
4
4
|
export function payerOf(call) {
|
|
5
|
+
const paid = fundedBy(call);
|
|
6
|
+
return call.environmentPayer ? { payer: call.environmentPayer, funding: paid.funding } : paid;
|
|
7
|
+
}
|
|
8
|
+
function fundedBy(call) {
|
|
5
9
|
switch (call.call) {
|
|
6
10
|
case 'model':
|
|
7
11
|
return call.route === 'endpoint' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: call.route };
|
package/dist/core/llm/run.d.ts
CHANGED
|
@@ -86,6 +86,7 @@ export interface LlmSpend {
|
|
|
86
86
|
node?: string | null;
|
|
87
87
|
run?: string | null;
|
|
88
88
|
request?: string;
|
|
89
|
+
environmentPayer?: string | null;
|
|
89
90
|
spend_cap?: number | null;
|
|
90
91
|
}
|
|
91
92
|
/** `spend`: who the call is attributed to. With it, the ledger check runs for each candidate route before its vendor request
|
package/dist/core/llm/run.js
CHANGED
|
@@ -324,7 +324,8 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
|
|
|
324
324
|
const served = `${model.provider}/${model.id}`;
|
|
325
325
|
const requested = input.model ?? served;
|
|
326
326
|
// The ledger check, once the account, key or endpoint is chosen and before this candidate's vendor request or token mint.
|
|
327
|
-
const
|
|
327
|
+
const environmentPayer = spend?.environmentPayer;
|
|
328
|
+
const paid = hosted ? (sub === null ? null : { payer: environmentPayer ?? sub, funding: 'endpoint' }) : app ? payerOf({ call: 'model', route: 'endpoint', grantee: app.grantee, environmentPayer }) : sub === null ? null : payerOf({ call: 'model', route: account ? 'subscription' : 'key', sub, environmentPayer });
|
|
328
329
|
if (spend !== undefined && paid !== null) {
|
|
329
330
|
const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, provider });
|
|
330
331
|
if (refusal !== null) {
|
|
@@ -10,6 +10,8 @@ export const PERMISSIONS = ['read', 'edit', 'message', 'use', 'share'];
|
|
|
10
10
|
/** The ceiling access class a permission asks: read/use → read, edit/share → write, message → message. */
|
|
11
11
|
const ACCESS = { read: 'read', use: 'read', edit: 'write', share: 'write', message: 'message' };
|
|
12
12
|
const bareUser = (principal) => principal.replace(/^user:/, '');
|
|
13
|
+
/** An app acting as its own subject (`app:<id>`) is no person: it never becomes a user, so no `acts_for` or subject set is built from it. */
|
|
14
|
+
const personSub = (sub) => sub.startsWith('app:') ? null : bareUser(sub);
|
|
13
15
|
/** The user a reader acts for: a person's own identity; an app call's `sub`; a node's `sub`; otherwise the install's person. */
|
|
14
16
|
export async function userOf(db, reader) {
|
|
15
17
|
return await namedUserOf(db, reader) ?? bareUser(await personIdAsync());
|
|
@@ -21,12 +23,12 @@ async function namedUserOf(db, reader) {
|
|
|
21
23
|
return row === undefined ? null : bareUser(row.external_id);
|
|
22
24
|
}
|
|
23
25
|
if (reader.class === 'app')
|
|
24
|
-
return reader.sub === undefined ? null :
|
|
26
|
+
return reader.sub === undefined ? null : personSub(reader.sub);
|
|
25
27
|
if (reader.class === 'object' && reader.sub !== undefined)
|
|
26
|
-
return
|
|
28
|
+
return personSub(reader.sub);
|
|
27
29
|
const nodeId = reader.class === 'node' ? reader.node.id : reader.object.id;
|
|
28
30
|
const row = await db.prepare('SELECT sub FROM nodes WHERE node_id = ?').get(nodeId);
|
|
29
|
-
return row?.sub == null ? null :
|
|
31
|
+
return row?.sub == null ? null : personSub(row.sub);
|
|
30
32
|
}
|
|
31
33
|
/** The user ids a subject stands for (the user and `*`) and every group it reaches, directly or through nested groups. */
|
|
32
34
|
export async function subjectSet(db, userId) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { validateDeclaredResult } from '../../api/command-manifest/result.js';
|
|
2
2
|
import { callerAllows, requireGroup } from '../../daemon/api/handlers/providers.js';
|
|
3
3
|
import { callerTerminalGrant } from '../grants/terminal.js';
|
|
4
|
-
import { findRefusal, payerOf, refusalError, refusedMark, writeCharge } from '../ledger/index.js';
|
|
4
|
+
import { environmentPayerOfNode, findRefusal, payerOf, refusalError, refusedMark, writeCharge } from '../ledger/index.js';
|
|
5
5
|
import { listInstalledPlugins } from '../resolver.js';
|
|
6
6
|
import { emitEvent } from '../events/emit.js';
|
|
7
7
|
import { ProviderError, scopeMissing } from './errors.js';
|
|
@@ -282,7 +282,7 @@ export async function callProvider(caller, rawInput, request) {
|
|
|
282
282
|
jti = token.jti;
|
|
283
283
|
// The payer is the token's claim, so the check runs once the token is in hand and before anything is sent to the provider.
|
|
284
284
|
const chargeGrantee = caller.class === 'person' ? TERMINAL_GRANTEE : grantee;
|
|
285
|
-
const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub });
|
|
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
288
|
await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee,
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** The subject a node launches as. A node carries its own `sub`; only an unjoined single-person install, whose nodes may predate it, falls back to the install's person. A cloud role never does: it serves many subjects and has no person of its own. */
|
|
2
|
+
export declare function launchSub(sub: string | null | undefined, nodeId: string): string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { isCloudRole, personId } from '../canvas/person.js';
|
|
2
|
+
import { RunError } from './operations.js';
|
|
3
|
+
/** The subject a node launches as. A node carries its own `sub`; only an unjoined single-person install, whose nodes may predate it, falls back to the install's person. A cloud role never does: it serves many subjects and has no person of its own. */
|
|
4
|
+
export function launchSub(sub, nodeId) {
|
|
5
|
+
if (sub != null)
|
|
6
|
+
return sub;
|
|
7
|
+
if (isCloudRole())
|
|
8
|
+
throw new RunError(500, 'node_without_sub', `node ${nodeId} has no sub`);
|
|
9
|
+
return personId();
|
|
10
|
+
}
|
|
@@ -43,7 +43,7 @@ import { bindBrokerEventSource, eventSource } from '../events/source.js';
|
|
|
43
43
|
import { envBrokerEngine } from '../../shared/env.js';
|
|
44
44
|
import { conversationIdFromPath, conversationStore, ConversationNotFoundError } from '../conversation-store/index.js';
|
|
45
45
|
import { mintNodeToken } from '../canvas/node-tokens.js';
|
|
46
|
-
import {
|
|
46
|
+
import { launchSub } from '../runs/node-sub.js';
|
|
47
47
|
// HeadlessBrokerHost (design §3.3): a detached broker PROCESS, no tmux pane. It
|
|
48
48
|
// boots the dedicated broker-cli entry directly (NEVER src/cli.ts), supervises
|
|
49
49
|
// via the broker pid recorded as pi_pid, and tears down over the node's unix
|
|
@@ -532,7 +532,7 @@ export const headlessBrokerHost = {
|
|
|
532
532
|
// The second serves the one relaunch a grant sync during launch can force.
|
|
533
533
|
const readFds = [openSync(`/proc/self/fd/${tokenFd}`, 'r'), openSync(`/proc/self/fd/${tokenFd}`, 'r')];
|
|
534
534
|
closeSync(tokenFd);
|
|
535
|
-
const launchNode = { nodeId, app, sub: row.sub
|
|
535
|
+
const launchNode = { nodeId, app, sub: launchSub(row.sub, nodeId), grantId: row.grant_id ?? null,
|
|
536
536
|
scopes: row.scopes ?? null, isolated: row.isolated === true,
|
|
537
537
|
...(row.isolated === true ? { cwd: row.cwd } : {}),
|
|
538
538
|
command: [process.execPath, resolveBrokerEntry(), '--canvas-home', crtrHome(), '--epoch', fleet.epoch(), nodeId],
|
|
@@ -441,7 +441,7 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
|
|
|
441
441
|
})).launch, launchGrant, opts.model);
|
|
442
442
|
await assertLaunchModelRegistered(requestFromLaunch(preflightLaunch), { cwd: birthCwd, profileId });
|
|
443
443
|
// The start check, before any worktree or node row exists: a refusal leaves nothing behind.
|
|
444
|
-
await checkStart({ grantee: payerSource?.grantee ?? 'app:terminal', sub: payerSource?.sub, grant_id: payerSource?.grant_id });
|
|
444
|
+
await checkStart({ grantee: payerSource?.grantee ?? 'app:terminal', sub: payerSource?.sub, grant_id: payerSource?.grant_id, profile_id: profileId });
|
|
445
445
|
const forkSourceNodeId = forkSourceMeta?.node_id ?? null;
|
|
446
446
|
let managedWorktree;
|
|
447
447
|
let spawnCwd = birthCwd;
|
|
@@ -4,6 +4,7 @@ export interface StartIdentity {
|
|
|
4
4
|
grantee?: string;
|
|
5
5
|
sub?: string | null;
|
|
6
6
|
grant_id?: string | null;
|
|
7
|
+
profile_id?: string | null;
|
|
7
8
|
}
|
|
8
9
|
/** The start candidate for an identity, or null when no person is known yet (a terminal node before its first grant snapshot). */
|
|
9
10
|
export declare function startCandidateOf(who: StartIdentity): Promise<StartCandidate | null>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The start check (design-ledger, "The check → Start check"): run before a node is born, a run starts, a cron fires, a job
|
|
2
2
|
// starts or a dormant node revives. The candidate's payer is whoever pays the node's model calls.
|
|
3
|
-
import { check, findRefusal, payerOf } from '../ledger/index.js';
|
|
3
|
+
import { check, environmentPayerOfProfile, findRefusal, payerOf } from '../ledger/index.js';
|
|
4
4
|
import { RunError } from '../runs/operations.js';
|
|
5
5
|
import { grantStanding, payerOfGrant } from '../grants/mirror.js';
|
|
6
6
|
import { callerTerminalGrant } from '../grants/terminal.js';
|
|
@@ -11,7 +11,7 @@ export async function startCandidateOf(who) {
|
|
|
11
11
|
if (sub === null)
|
|
12
12
|
return null;
|
|
13
13
|
const paid = await payerOfGrant(who.grant_id);
|
|
14
|
-
const payer = payerOf({ call: 'start', grantPayer: paid, sub, grantee });
|
|
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
|
}
|
|
17
17
|
/** Throw `402 cap_exhausted` (limit named) when a limit covering every charge of this identity's payer is reached. */
|
|
@@ -123,7 +123,7 @@ async function resolveRecipe(request) {
|
|
|
123
123
|
* and the create request uncommitted. A claimed spare is a started node like any birth. */
|
|
124
124
|
async function checkClaimantStart(request) {
|
|
125
125
|
const creator = request.creator === null ? null : await getNode(request.creator);
|
|
126
|
-
await checkStart({ grantee: creator?.grantee ?? 'app:terminal', sub: creator?.sub, grant_id: creator?.grant_id });
|
|
126
|
+
await checkStart({ grantee: creator?.grantee ?? 'app:terminal', sub: creator?.sub, grant_id: creator?.grant_id, profile_id: creator?.profile_id });
|
|
127
127
|
}
|
|
128
128
|
/** Claim a spare for `request`, reshaped onto its persona — or null when the
|
|
129
129
|
* pool cannot serve it. The caller falls back to a cold spawn; a refused
|
|
@@ -13,7 +13,8 @@ import { pinSandboxRuntimeHome } from './runtime-home.js';
|
|
|
13
13
|
import { sandboxCacheEnv } from './cache-env.js';
|
|
14
14
|
import { launcherRequest } from '../../launcher/client.js';
|
|
15
15
|
import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
|
|
16
|
-
import { isCloudRole
|
|
16
|
+
import { isCloudRole } from '../canvas/person.js';
|
|
17
|
+
import { launchSub } from '../runs/node-sub.js';
|
|
17
18
|
/** The launcher's node id for one cron execution; its run folder is `nodeRunDir(<this>)`. */
|
|
18
19
|
export function cronLaunchId(executionId) { return `cron-${executionId}`; }
|
|
19
20
|
/** The same mount compiler and launcher request used by broker launches. A node
|
|
@@ -48,7 +49,7 @@ export async function cwdIsMounted(app, cwd, nodeId, isolated = false, folder, p
|
|
|
48
49
|
const spec = await compileLaunch({ nodeId: nodeId ?? `proc-cwd-check`, app,
|
|
49
50
|
...(principal !== undefined
|
|
50
51
|
? { sub: principal.sub, grantId: grant?.id ?? null, scopes: principal.scopes }
|
|
51
|
-
: { sub: row ? row.sub
|
|
52
|
+
: { sub: row ? launchSub(row.sub, row.node_id) : grant.sub, grantId: row ? row.grant_id ?? null : grant.id, scopes: row?.scopes ?? null }),
|
|
52
53
|
command: ['true'], env: {},
|
|
53
54
|
...(nodeId === undefined ? { withoutNode: true } : {}),
|
|
54
55
|
...(folder === undefined ? {} : { folder }),
|
|
@@ -91,7 +92,7 @@ export async function launchAppProcess(options) {
|
|
|
91
92
|
throw new Error(`no active grant for ${app}`);
|
|
92
93
|
}
|
|
93
94
|
else if (row) {
|
|
94
|
-
if (app !== 'app:terminal' && !(row.grant_id ? await activeGrant(row.grant_id) : await grantFor(app, row.sub
|
|
95
|
+
if (app !== 'app:terminal' && !(row.grant_id ? await activeGrant(row.grant_id) : await grantFor(app, launchSub(row.sub, row.node_id)))) {
|
|
95
96
|
throw new Error(`no active grant for ${app}`);
|
|
96
97
|
}
|
|
97
98
|
}
|
|
@@ -117,7 +118,7 @@ export async function launchAppProcess(options) {
|
|
|
117
118
|
}).filter((entry) => entry[1] !== undefined)));
|
|
118
119
|
const launchNode = stored !== undefined
|
|
119
120
|
? { nodeId, app, sub: stored.sub, grantId: grant?.id ?? null, scopes: stored.scopes }
|
|
120
|
-
: { nodeId, app, sub: row ? row.sub
|
|
121
|
+
: { nodeId, app, sub: row ? launchSub(row.sub, row.node_id) : grant.sub, grantId: row ? row.grant_id ?? null : grant.id, scopes: row?.scopes ?? null };
|
|
121
122
|
const compile = async () => {
|
|
122
123
|
const spec = await compileLaunch({ ...launchNode, command: options.command, env,
|
|
123
124
|
...(options.nodeId === undefined ? { withoutNode: true } : {}),
|
|
@@ -62,7 +62,7 @@ async function handleStart(ctx) {
|
|
|
62
62
|
}
|
|
63
63
|
// The start check with the node's payer, before the job is marked started: a refusal launches nothing.
|
|
64
64
|
const owner = (await getNode(nodeId));
|
|
65
|
-
await checkStart({ grantee: owner.grantee ?? 'app:terminal', sub: owner.sub, grant_id: owner.grant_id });
|
|
65
|
+
await checkStart({ grantee: owner.grantee ?? 'app:terminal', sub: owner.sub, grant_id: owner.grant_id, profile_id: owner.profile_id });
|
|
66
66
|
if (!appProcessSandboxed())
|
|
67
67
|
throw new ApiError(400, 'invalid_request', 'job.start is only used with the root launcher');
|
|
68
68
|
const paths = bashJobPaths(dir, jobId);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.748",
|
|
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",
|