@north-light/api 0.3.747 → 0.3.749

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/objects.d.ts +6 -1
  4. package/dist/api/dto/plugins.d.ts +2 -0
  5. package/dist/clients/attach/chrome/canvas-panels.d.ts +2 -0
  6. package/dist/clients/attach/chrome/canvas-panels.js +19 -1
  7. package/dist/clients/attach/chrome/roster.d.ts +2 -0
  8. package/dist/clients/attach/chrome/roster.js +1 -0
  9. package/dist/clients/attach/chrome/run-facts.d.ts +12 -0
  10. package/dist/clients/attach/chrome/run-facts.js +76 -0
  11. package/dist/clients/attach/chrome/widgets.d.ts +3 -1
  12. package/dist/clients/attach/chrome/widgets.js +14 -5
  13. package/dist/clients/attach/viewer.js +7 -1
  14. package/dist/commands/canvas/list.js +3 -1
  15. package/dist/commands/canvas/read.js +4 -2
  16. package/dist/commands/canvas/search.js +3 -1
  17. package/dist/core/canvas/canvas.js +2 -1
  18. package/dist/core/canvas/schema-version.d.ts +1 -1
  19. package/dist/core/canvas/schema-version.js +1 -1
  20. package/dist/core/command-manifests/registry.d.ts +2 -1
  21. package/dist/core/command-plugins/compose.js +5 -3
  22. package/dist/core/command.d.ts +11 -0
  23. package/dist/core/command.js +34 -1
  24. package/dist/core/environments.d.ts +2 -1
  25. package/dist/core/environments.js +2 -2
  26. package/dist/core/grants/mirror.d.ts +4 -0
  27. package/dist/core/grants/mirror.js +16 -1
  28. package/dist/core/grants/on-sync.js +2 -2
  29. package/dist/core/graph/reader.js +1 -1
  30. package/dist/core/ledger/environment-payer.d.ts +2 -0
  31. package/dist/core/ledger/environment-payer.js +15 -0
  32. package/dist/core/ledger/index.d.ts +1 -0
  33. package/dist/core/ledger/index.js +1 -0
  34. package/dist/core/ledger/payer.d.ts +4 -1
  35. package/dist/core/ledger/payer.js +4 -0
  36. package/dist/core/llm/run.d.ts +1 -0
  37. package/dist/core/llm/run.js +2 -1
  38. package/dist/core/peer/envelope.js +2 -1
  39. package/dist/core/peer/stubs.js +5 -1
  40. package/dist/core/permissions/ceiling.js +4 -0
  41. package/dist/core/permissions/evaluator.js +16 -5
  42. package/dist/core/providers/call.js +2 -2
  43. package/dist/core/runs/node-sub.d.ts +2 -0
  44. package/dist/core/runs/node-sub.js +10 -0
  45. package/dist/core/runtime/host.js +2 -2
  46. package/dist/core/runtime/spawn.js +1 -1
  47. package/dist/core/runtime/start-check.d.ts +1 -0
  48. package/dist/core/runtime/start-check.js +2 -2
  49. package/dist/core/runtime/warm-pool.js +1 -1
  50. package/dist/core/spaces/process.js +5 -4
  51. package/dist/daemon/api/handlers/bash-jobs.js +1 -1
  52. package/dist/daemon/api/handlers/providers.d.ts +2 -0
  53. package/dist/daemon/api/handlers/providers.js +5 -1
  54. package/package.json +1 -1
@@ -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.74";
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`. */
@@ -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.74';
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. */
@@ -35,6 +35,8 @@ export interface CanvasPanelLines {
35
35
  reportIds: string[];
36
36
  /** Actionable cockpit rows. Enter swaps nodes or opens the matching wait detail surface. */
37
37
  items: CanvasPanelItem[];
38
+ /** What `nodeId` itself waits on, for the fact line above the recap. */
39
+ waiting?: string;
38
40
  }
39
41
  /** What the nodes on the manager and report rows are waiting on. Omitted for a remote attach. */
40
42
  export interface OtherNodeWaits {
@@ -263,5 +263,23 @@ export async function buildCanvasPanelLines(nodeId, asks, palette, source, crons
263
263
  line: ` ${eye} ${muted(`${summary} · ↵ details`)}${RESET}`,
264
264
  });
265
265
  }
266
- return { reports: items.map((item) => item.line), reportIds, items };
266
+ // What this node itself waits on: the person first, then named children, then other waits.
267
+ const waits = [];
268
+ if ((asks[nodeId] ?? 0) > 0)
269
+ waits.push('you');
270
+ if (live.length > 0) {
271
+ const first = navLabel((await detail(live[0])) ?? (await node(live[0])), live[0]);
272
+ waits.push(live.length === 1 ? first : `${first} +${live.length - 1}`);
273
+ }
274
+ if (reviews.length > 0)
275
+ waits.push('review');
276
+ if (bashSummary !== undefined)
277
+ waits.push(jobs.length === 1 ? 'a bash job' : `${jobs.length} bash jobs`);
278
+ if (cronSummary !== undefined)
279
+ waits.push(crons.length === 1 ? 'a cron' : `${crons.length} crons`);
280
+ for (const wait of roster?.object_waits ?? [])
281
+ if (wait.node_id === nodeId)
282
+ waits.push(wait.object_name);
283
+ const waiting = waits.length === 0 ? undefined : waits.join(', ');
284
+ return { reports: items.map((item) => item.line), reportIds, items, ...(waiting === undefined ? {} : { waiting }) };
267
285
  }
@@ -25,6 +25,8 @@ export interface RosterHooks {
25
25
  openObject: (objectId: string) => void;
26
26
  /** Recompute the editor's hollow-cursor state (session/pane-focus.ts). */
27
27
  syncCursor: () => void;
28
+ /** What this node waits on, from each rebuild — feeds the fact line above the recap. */
29
+ onWaiting?: (label: string | undefined) => void;
28
30
  }
29
31
  export interface AttachRoster {
30
32
  /** Rebuild the rows from the canvas source, reconcile the selection, repaint. */
@@ -76,6 +76,7 @@ export function createRoster(s, hooks) {
76
76
  const others = remote ? undefined : { crons, reviews: openReviews, jobsOf: async (id) => (await cliClient().listBashJobs(id)).map(toBashJobStatus) };
77
77
  const built = await buildCanvasPanelLines(s.nodeId, hooks.asks(), pal, canvasSource, ownedCrons, bashJobs, reviews, others, view ?? await canvasSource.panelView?.(s.nodeId));
78
78
  items = built.items;
79
+ hooks.onWaiting?.(built.waiting);
79
80
  // After an in-place swap, land on the previously open node, which has taken
80
81
  // the swapped-to node's place in this self-excluding roster.
81
82
  if (autoSelect !== undefined) {
@@ -0,0 +1,12 @@
1
+ import type { BrokerToClient } from '../../../core/runtime/broker-protocol.js';
2
+ export interface RunFacts {
3
+ /** Fold one broker frame: message timestamps move the run window. */
4
+ observe(frame: BrokerToClient): void;
5
+ /** What the node waits on, from the latest roster refresh. */
6
+ setWaiting(label: string | undefined): void;
7
+ /** The fact line, or undefined when there is nothing to show. */
8
+ line(streaming: boolean, nowMs?: number): string | undefined;
9
+ }
10
+ /** `2:31 PM` today, `Nov 18, 2:31 PM` on another day. */
11
+ export declare function finishLabel(atMs: number, nowMs: number): string;
12
+ export declare function createRunFacts(onChange: () => void): RunFacts;
@@ -0,0 +1,76 @@
1
+ // chrome/run-facts.ts — the gray fact line above the recap: how long the agent
2
+ // ran since the person's last message, when it finished, and what it waits on.
3
+ //
4
+ // Run time and finish time come from message timestamps on the broker stream
5
+ // (the welcome snapshot, then live message events). What the node waits on comes
6
+ // from the roster refresh, which already reads asks, children, reviews, jobs,
7
+ // crons and object waits for the wait rows below the editor.
8
+ import { formatBashElapsed } from '../../../core/bash-jobs.js';
9
+ import { isTrueUserMessage } from '../../../shared/tool-groups.js';
10
+ function stamp(message) {
11
+ return typeof message.timestamp === 'number' && Number.isFinite(message.timestamp) ? message.timestamp : undefined;
12
+ }
13
+ /** `2:31 PM` today, `Nov 18, 2:31 PM` on another day. */
14
+ export function finishLabel(atMs, nowMs) {
15
+ const at = new Date(atMs);
16
+ const time = at.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
17
+ if (at.toDateString() === new Date(nowMs).toDateString())
18
+ return time;
19
+ return `${at.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}, ${time}`;
20
+ }
21
+ export function createRunFacts(onChange) {
22
+ let lastUserAt;
23
+ let finishedAt;
24
+ let waiting;
25
+ const take = (message) => {
26
+ const at = stamp(message);
27
+ if (at === undefined)
28
+ return;
29
+ if (isTrueUserMessage(message)) {
30
+ lastUserAt = at;
31
+ finishedAt = undefined;
32
+ }
33
+ else if (message.role === 'assistant') {
34
+ finishedAt = at;
35
+ }
36
+ };
37
+ return {
38
+ observe(frame) {
39
+ if (frame.type === 'welcome') {
40
+ lastUserAt = undefined;
41
+ finishedAt = undefined;
42
+ for (const message of frame.snapshot.messages)
43
+ take(message);
44
+ onChange();
45
+ return;
46
+ }
47
+ if (frame.type === 'agent_start' || frame.type === 'agent_end' || frame.type === 'agent_settled') {
48
+ onChange();
49
+ return;
50
+ }
51
+ if (frame.type === 'message_end' || (frame.type === 'message_start' && frame.message.role === 'user')) {
52
+ take(frame.message);
53
+ onChange();
54
+ }
55
+ },
56
+ setWaiting(label) {
57
+ if (label === waiting)
58
+ return;
59
+ waiting = label;
60
+ onChange();
61
+ },
62
+ line(streaming, nowMs = Date.now()) {
63
+ if (streaming)
64
+ return undefined;
65
+ const parts = [];
66
+ if (finishedAt !== undefined) {
67
+ if (lastUserAt !== undefined && finishedAt >= lastUserAt)
68
+ parts.push(`ran ${formatBashElapsed(finishedAt - lastUserAt)}`);
69
+ parts.push(`finished ${finishLabel(finishedAt, nowMs)}`);
70
+ }
71
+ if (waiting !== undefined)
72
+ parts.push(`waiting on ${waiting}`);
73
+ return parts.length === 0 ? undefined : parts.join(' · ');
74
+ },
75
+ };
76
+ }
@@ -6,4 +6,6 @@ export interface ChromeWidgets {
6
6
  /** Paint the pending steering messages above the editor. */
7
7
  renderQueued: () => void;
8
8
  }
9
- export declare function createChromeWidgets(ctx: Pick<AttachSession, 'tui' | 'pal' | 'containers'>, state: () => SessionState): ChromeWidgets;
9
+ export declare function createChromeWidgets(ctx: Pick<AttachSession, 'tui' | 'pal' | 'containers'>, state: () => SessionState,
10
+ /** The gray fact line (run time, finish time, waiting on), painted above the recap. */
11
+ factLine?: () => string | undefined): ChromeWidgets;
@@ -2,9 +2,11 @@
2
2
  // widgets in their fixed cockpit slots, and the queued-steering panel above
3
3
  // the editor. Both read the folded `SessionState` the orchestrator owns, so it
4
4
  // arrives as a getter rather than a captured value.
5
- import { Text, truncateToWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
5
+ import { Spacer, Text, truncateToWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
6
6
  import { splitRecapLines } from './recap.js';
7
- export function createChromeWidgets(ctx, state) {
7
+ export function createChromeWidgets(ctx, state,
8
+ /** The gray fact line (run time, finish time, waiting on), painted above the recap. */
9
+ factLine = () => undefined) {
8
10
  const { tui, pal } = ctx;
9
11
  const { aboveWidgets, belowWidgets, queued } = ctx.containers;
10
12
  /** Paint serializable extension widgets into their fixed cockpit slots. */
@@ -12,10 +14,17 @@ export function createChromeWidgets(ctx, state) {
12
14
  const session = state();
13
15
  aboveWidgets.clear();
14
16
  belowWidgets.clear();
15
- // The recap widget is split: its goal line is painted by the pinned
16
- // header, while its state line lands here in the widget's own cockpit
17
- // slot, label stripped and faint.
17
+ // The fact line comes first. The recap widget is split: its goal line is
18
+ // painted by the pinned header, while its state line lands here in the
19
+ // widget's own cockpit slot, label stripped, faint, and never cut short.
18
20
  const span = Math.max(1, (process.stdout.columns ?? 80) - 2);
21
+ const facts = factLine();
22
+ if (facts !== undefined) {
23
+ for (const wrapped of wrapTextWithAnsi(pal.faint(facts), span))
24
+ aboveWidgets.addChild(new Text(wrapped, 1, 0));
25
+ if (session.display.widgets['crtr-recap'] !== undefined)
26
+ aboveWidgets.addChild(new Spacer(1));
27
+ }
19
28
  for (const [key, widget] of Object.entries(session.display.widgets)) {
20
29
  const recap = key === 'crtr-recap';
21
30
  const lines = recap ? splitRecapLines(widget.lines).state : widget.lines;
@@ -34,6 +34,7 @@ import { createTicketPanel } from './chrome/ticket-panel.js';
34
34
  import { createPaneFocus } from './session/pane-focus.js';
35
35
  import { createStatusLine } from './chrome/status-line.js';
36
36
  import { createChromeWidgets } from './chrome/widgets.js';
37
+ import { createRunFacts } from './chrome/run-facts.js';
37
38
  import { createRecapHeader } from './chrome/header.js';
38
39
  import { createChromeRefresh, isTransientDaemonFailure } from './session/chrome-refresh.js';
39
40
  import { createTeardown } from './session/teardown.js';
@@ -357,7 +358,9 @@ onConnected) {
357
358
  editorChrome.syncContextBadge();
358
359
  // The two broker-fed container painters: extension widgets in their cockpit
359
360
  // slots, and the queued-steering panel.
360
- const { renderExtensionWidgets, renderQueued } = createChromeWidgets(ctx, () => sync.state());
361
+ // The gray fact line above the recap: run time, finish time, what the node waits on.
362
+ const runFacts = createRunFacts(() => renderExtensionWidgets());
363
+ const { renderExtensionWidgets, renderQueued } = createChromeWidgets(ctx, () => sync.state(), () => runFacts.line(sync.state().engine?.isStreaming === true));
361
364
  // The OWNER of the folded SessionState and of what each delta repaints.
362
365
  sync = createSessionStateSync(role, {
363
366
  setEngineState: (engine) => input.setState(engine),
@@ -424,6 +427,7 @@ onConnected) {
424
427
  openInspector,
425
428
  openObject,
426
429
  syncCursor: () => paneFocus.sync(),
430
+ onWaiting: (label) => runFacts.setWaiting(label),
427
431
  });
428
432
  // The one hollow-cursor owner: pane focus AND neither list holding the highlight.
429
433
  const paneFocus = createPaneFocus(editor, [roster.active, strip.active, ticketPanel.active]);
@@ -714,6 +718,7 @@ onConnected) {
714
718
  if (frame.type === 'welcome' && !welcomed)
715
719
  mark('viewer.welcome_received');
716
720
  handleBrokerFrame(frame);
721
+ runFacts.observe(frame);
717
722
  if (frame.type === 'welcome' && !welcomed)
718
723
  onFirstWelcome();
719
724
  },
@@ -726,6 +731,7 @@ onConnected) {
726
731
  scheduleTmuxBindingInstall();
727
732
  chatView.settleRun();
728
733
  sync.patchLocal({ isStreaming: false });
734
+ renderExtensionWidgets();
729
735
  },
730
736
  onReconnecting: () => chatView.setPendingUndelivered(true),
731
737
  // A message sent on a connection that had already died never reached the broker: send it again now that one answers.
@@ -36,7 +36,8 @@ export const listLeaf = defineLeaf({
36
36
  outputKind: 'object',
37
37
  effects: ['None. Listing records no watch.'],
38
38
  },
39
- run: async (input) => {
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
- run: async (input) => {
83
+ actingAs: true,
84
+ run: async (input, context) => {
84
85
  try {
85
- return { ...(await cliClient().objects.read(input['ref'], input['fields'] === true ? { fields: true } : undefined)) };
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
- run: async (input) => {
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)) };
@@ -1,5 +1,6 @@
1
1
  // The canvas data-access layer. Nodes, their sessions, executions, and managed
2
2
  // worktrees are SQL-authoritative. Node directories hold only artifacts.
3
+ import { parsePrincipal } from '@north-light/identity';
3
4
  import { loadExactProfileManifest } from '../profiles/manifest.js';
4
5
  import { envNodeId } from '../../shared/env.js';
5
6
  import { lstatSync, realpathSync, rmdirSync, rmSync, statSync } from 'node:fs';
@@ -61,7 +62,7 @@ async function seedRow(meta, db) {
61
62
  const profile = meta.profile_id ? await profileObjectFor(db, meta.profile_id, app, meta.grantee ?? 'app:terminal') : null;
62
63
  await createObject(db, { id: meta.node_id, type: 'node', kind: meta.kind, owner: (profile ?? app).id, privacy: 'public', name: meta.name, preview: '' });
63
64
  // A node directly under an app is readable by the person it was made for.
64
- if (profile === null && meta.sub)
65
+ if (profile === null && meta.sub && parsePrincipal(meta.sub)?.kind === 'user')
65
66
  await writeActsFor(db, meta.node_id, meta.sub);
66
67
  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
68
  .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 = 34;
4
+ export declare const CANVAS_SCHEMA_VERSION = 36;
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 = 34;
9
+ export const CANVAS_SCHEMA_VERSION = 36;
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
  }
@@ -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 <principal>` / `--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 {};
@@ -4,6 +4,7 @@
4
4
  // complexity than a plain array walk for this interface contract.
5
5
  // A plain array walk + a small flag parser is ~120 lines and has no surprising
6
6
  // edge cases.
7
+ import { parsePrincipal } from '@north-light/identity';
7
8
  import { renderRoot, renderBranch, renderLeafArgv, withAsyncHelpState, collapseWideChildren, rootPromotedChildren } from './help.js';
8
9
  import { beginPreview, publishPreviewResult, readStdinRaw, peekStdinRaw, emit, handle, setJsonOutput, isJsonOutput } from './io.js';
9
10
  import { renderResult } from './render.js';
@@ -42,6 +43,7 @@ export function defineLeaf(opts) {
42
43
  hookEligible: opts.hookEligible,
43
44
  plugin: opts.plugin,
44
45
  machineSelector: opts.machineSelector,
46
+ actingAs: opts.actingAs,
45
47
  run: opts.run,
46
48
  render: opts.render,
47
49
  preview: opts.preview,
@@ -720,6 +722,31 @@ export function takeMachineSelector(tokens) {
720
722
  }
721
723
  return machine === undefined ? { rest } : { rest, machine };
722
724
  }
725
+ /** Take the `--as <principal>` / `--as=<user:id>` option out of an opted-in leaf's argv. Nothing after a bare `--` is a flag. */
726
+ export function takeActingAs(tokens) {
727
+ const rest = [];
728
+ let as;
729
+ for (let i = 0; i < tokens.length; i++) {
730
+ const token = tokens[i];
731
+ if (token === '--') {
732
+ rest.push(...tokens.slice(i));
733
+ break;
734
+ }
735
+ const inline = token.startsWith('--as=') ? token.slice('--as='.length) : undefined;
736
+ if (token !== '--as' && inline === undefined) {
737
+ rest.push(token);
738
+ continue;
739
+ }
740
+ const value = inline ?? tokens[i + 1];
741
+ if (value === undefined || parsePrincipal(value) === null) {
742
+ throw parseArgvError('missing_parameter', '--as requires a principal like user:<id> or app:<id>/<path>', '--as', 'as', 'Name the principal this call acts for, for example `--as user:alice`.');
743
+ }
744
+ if (inline === undefined)
745
+ i++;
746
+ as = value;
747
+ }
748
+ return as === undefined ? { rest } : { rest, as };
749
+ }
723
750
  export const GLOBAL_TOKENS = new Set(['--json', '--no-autostart']);
724
751
  export async function runCli(root, argv) {
725
752
  // argv is process.argv — strip node binary + script path. `--json` is a
@@ -826,6 +853,12 @@ export async function runCli(root, argv) {
826
853
  leafTokens = selected.rest;
827
854
  machine = selected.machine;
828
855
  }
856
+ let acting;
857
+ if (leaf.actingAs === true && !params.some((param) => param.kind === 'flag' && param.name === 'as')) {
858
+ const taken = takeActingAs(leafTokens);
859
+ leafTokens = taken.rest;
860
+ acting = taken.as;
861
+ }
829
862
  const input = await parseArgv(params, leafTokens, {
830
863
  leafPath: path,
831
864
  onProvidedParams: (provided) => {
@@ -835,7 +868,7 @@ export async function runCli(root, argv) {
835
868
  contextFilePaths = paths;
836
869
  },
837
870
  });
838
- const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }) };
871
+ const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }), ...(acting === undefined ? {} : { as: acting }) };
839
872
  const result = await operationIdContext.fresh(() => leaf.run(input, context));
840
873
  publishPreviewResult(result === undefined || result === null ? result : leaf.preview?.(result) ?? result);
841
874
  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 { personId } from '../canvas/person.js';
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 ?? personId(), node.grant_id ?? null, node.scopes ?? null);
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.
@@ -128,7 +128,7 @@ export async function readerFor(db, principal, reposFn) {
128
128
  if (!grant)
129
129
  throw new ApiError(403, 'app_not_granted', `${principal.actor.app} holds no active grant for ${principal.sub} on this machine`);
130
130
  const stored = principal.actor.node_scopes;
131
- return { class: 'app', app: await appObject(db, principal.actor.app), place: principal.actor.place, launched: stored,
131
+ return { class: 'app', app: await appObject(db, principal.actor.app), sub: principal.sub, place: principal.actor.place, launched: stored,
132
132
  scopes: stored === null ? grant.resolved : stored.filter((scope) => coveredByAny(grant.resolved, scope)) };
133
133
  }
134
134
  if (principal.class === 'cron') {
@@ -0,0 +1,2 @@
1
+ export declare function environmentPayerOfProfile(profileId: string | null | undefined): Promise<string | null>;
2
+ export declare function environmentPayerOfNode(nodeId: string | null | undefined): Promise<string | null>;
@@ -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
- export type PayerCall =
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 };
@@ -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
@@ -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 paid = hosted ? (sub === null ? null : { payer: sub, funding: 'endpoint' }) : app ? payerOf({ call: 'model', route: 'endpoint', grantee: app.grantee }) : sub === null ? null : payerOf({ call: 'model', route: account ? 'subscription' : 'key', sub });
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) {
@@ -8,6 +8,7 @@
8
8
  // Wire form: `Crtr-Envelope: <base64url JSON>` of
9
9
  // {sub:"user:<id>", act:{sub:"runtime:<via>", act?:{sub:"app:<x>", node, node_scopes, place}}}
10
10
  // A missing inner `act` means the person.
11
+ import { parsePrincipal } from '@north-light/identity';
11
12
  import { joinedOwner } from '../directory/join.js';
12
13
  import { nodePlace } from '../permissions/ceiling.js';
13
14
  import { openDb } from '../canvas/db.js';
@@ -75,7 +76,7 @@ export function decodeEnvelope(header) {
75
76
  const inner = act['act'];
76
77
  if (inner === undefined)
77
78
  return { sub: raw['sub'], act: { sub: act['sub'] } };
78
- if (!isRecord(inner) || !isString(inner['sub']) || !inner['sub'].startsWith('app:'))
79
+ if (!isRecord(inner) || !isString(inner['sub']) || parsePrincipal(inner['sub'])?.kind !== 'app')
79
80
  throw new EnvelopeError('the envelope names no calling app');
80
81
  const { node, node_scopes: scopes, place } = inner;
81
82
  if (node !== null && !isString(node))
@@ -9,6 +9,7 @@
9
9
  // A stub that watches carries the envelope identity it acts under (app, node, node_scopes, place).
10
10
  // That identity names who the remote watcher is; it is never authority. What the stub may read is
11
11
  // recomputed from the current mirrored grant every time an event is published (`readerForObject`).
12
+ import { parsePrincipal } from '@north-light/identity';
12
13
  import { createObject, getById, ownerForGrantee, ownerLockKey } from '../graph/objects.js';
13
14
  import { readLegacyPrivacy } from '../graph/types.js';
14
15
  import { upsertKind } from '../graph/custom.js';
@@ -83,7 +84,10 @@ export async function lockInOrder(db, keys) {
83
84
  }
84
85
  /** The lock key to create the owner `grantee` names, or none when it exists (`ensureOwner` locks only a first sighting). */
85
86
  async function missingOwnerKey(db, grantee) {
86
- const [scheme, externalId] = grantee.startsWith('app:') ? ['app', grantee] : ['user', grantee];
87
+ const principal = parsePrincipal(grantee);
88
+ if (principal === null)
89
+ throw new Error(`grantee ${JSON.stringify(grantee)} is not a principal`);
90
+ const [scheme, externalId] = principal.kind === 'app' ? ['app', principal.namespace] : ['user', grantee];
87
91
  return await db.prepare('SELECT 1 FROM identities WHERE scheme = ? AND external_id = ?').get(scheme, externalId) === undefined ? [ownerLockKey(scheme, externalId)] : [];
88
92
  }
89
93
  /** Every advisory lock `ensureStub` takes for this object: the stub, the custom kind its reference declares, and each owner it may create.
@@ -1,6 +1,7 @@
1
1
  // The ceiling: what one of a person's agents may reach, computed in TypeScript from the reader's grant scopes and node row before the query,
2
2
  // then applied inside the same query as the schema check (`ceilingFrag`). A person reader has no ceiling. Privacy (`private` per root), run
3
3
  // confinement (`place`) and the launched own-memory narrowing are all rules here; none of them is schema text.
4
+ import { parsePrincipal } from '@north-light/identity';
4
5
  import { covers } from '@north-light/identity';
5
6
  import { isCloudRole } from '../canvas/person-state.js';
6
7
  import { eligiblePackageApps } from '../packages/eligibility.js';
@@ -147,6 +148,9 @@ export async function resolveCeiling(db, reader, user, access, options = {}) {
147
148
  const objVerb = access === 'write' ? 'write' : options.verb ?? 'read';
148
149
  const watching = reader.class === 'object' && reader.object.type.includes('.');
149
150
  const appRoot = async (ext, match) => {
151
+ const principal = parsePrincipal(ext);
152
+ if (principal?.kind !== 'app' || principal.path.length > 0)
153
+ return;
150
154
  const id = await objectOf(db, 'app', ext);
151
155
  if (id === null || id === reader.app.id)
152
156
  return;
@@ -1,3 +1,5 @@
1
+ // check / permits: the reader's user (schema) AND the reader's ceiling, in one SQL condition over the candidate object.
2
+ import { parsePrincipal } from '@north-light/identity';
1
3
  import { isCloudRole, personIdAsync } from '../canvas/person.js';
2
4
  import { requestPersonId } from '../canvas/person-state.js';
3
5
  import { OBJECT_TYPE, GROUP_TYPE } from './builtin.js';
@@ -10,9 +12,18 @@ export const PERMISSIONS = ['read', 'edit', 'message', 'use', 'share'];
10
12
  /** The ceiling access class a permission asks: read/use → read, edit/share → write, message → message. */
11
13
  const ACCESS = { read: 'read', use: 'read', edit: 'write', share: 'write', message: 'message' };
12
14
  const bareUser = (principal) => principal.replace(/^user:/, '');
15
+ /** A `sub` is a person only when the shared parser says `user:<id>`; an app principal, a bare id and any unknown prefix are no person (denied). 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. */
16
+ const personSub = (sub) => { const p = parsePrincipal(sub); return p?.kind === 'user' ? bareUser(p.namespace) : null; };
13
17
  /** 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
18
  export async function userOf(db, reader) {
15
- return await namedUserOf(db, reader) ?? bareUser(await personIdAsync());
19
+ const named = await namedUserOf(db, reader);
20
+ if (named !== null)
21
+ return named;
22
+ // A sub the parser rejects, or an app principal, never falls back. A reader with no sub falls back to the install's person on a local install only (one person there); a cloud role denies it.
23
+ const subless = reader.class === 'app' && reader.sub === undefined;
24
+ if (reader.class === 'app' && !(subless && !isCloudRole()))
25
+ throw new PermissionError(403, 'no_person', 'an app reader that names no person acts for no one');
26
+ return bareUser(await personIdAsync());
16
27
  }
17
28
  /** The user a reader names itself, without falling back to the process's person; null when it names none. */
18
29
  async function namedUserOf(db, reader) {
@@ -21,12 +32,12 @@ async function namedUserOf(db, reader) {
21
32
  return row === undefined ? null : bareUser(row.external_id);
22
33
  }
23
34
  if (reader.class === 'app')
24
- return reader.sub === undefined ? null : bareUser(reader.sub);
35
+ return reader.sub === undefined ? null : personSub(reader.sub);
25
36
  if (reader.class === 'object' && reader.sub !== undefined)
26
- return bareUser(reader.sub);
37
+ return personSub(reader.sub);
27
38
  const nodeId = reader.class === 'node' ? reader.node.id : reader.object.id;
28
39
  const row = await db.prepare('SELECT sub FROM nodes WHERE node_id = ?').get(nodeId);
29
- return row?.sub == null ? null : bareUser(row.sub);
40
+ return row?.sub == null ? null : personSub(row.sub);
30
41
  }
31
42
  /** The user ids a subject stands for (the user and `*`) and every group it reaches, directly or through nested groups. */
32
43
  export async function subjectSet(db, userId) {
@@ -51,7 +62,7 @@ export function resolveReader(db, reader) {
51
62
  if (shared)
52
63
  return shared;
53
64
  const ev = (async () => {
54
- const userId = isCloudRole() && requestPersonId() === undefined ? await namedUserOf(db, reader) : await userOf(db, reader);
65
+ const userId = (isCloudRole() && requestPersonId() === undefined) ? await namedUserOf(db, reader) : await userOf(db, reader);
55
66
  return { reader, userId, subjects: userId === null ? { userIds: ['*'], groupIds: [] } : await subjectSet(db, userId), defs: await loadDefinitions(db) };
56
67
  })();
57
68
  if (shared === null) {
@@ -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 { personId } from '../canvas/person.js';
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 ?? personId(), grantId: row.grant_id ?? null,
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, personId } from '../canvas/person.js';
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 ?? personId() : grant.sub, grantId: row ? row.grant_id ?? null : grant.id, scopes: row?.scopes ?? null }),
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 ?? personId()))) {
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 ?? personId() : grant.sub, grantId: row ? row.grant_id ?? null : grant.id, scopes: row?.scopes ?? null };
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);
@@ -43,6 +43,8 @@ export interface ProviderCallInput {
43
43
  approval?: string;
44
44
  /** Which device machine takes the call (a `machine_id`, `runtime:` prefix optional); only a provider served by a machine accepts it. */
45
45
  machine?: string;
46
+ /** The principal the call acts for (`--as`): carried through, not yet resolved. */
47
+ as?: string;
46
48
  }
47
49
  export declare function parseProvider(value: unknown): string;
48
50
  export declare function parseCallInput(body: unknown): ProviderCallInput;
@@ -9,6 +9,7 @@
9
9
  // Past the gate, the bodies are filled in by later tasks — `provider.call` by
10
10
  // R4 (`core/providers/call.ts`), `provider.tools` by R8 — and answer
11
11
  // `not_implemented` until then.
12
+ import { parsePrincipal } from '@north-light/identity';
12
13
  import { randomUUID } from 'node:crypto';
13
14
  import { cloudPersonScope } from '../../../core/runs/operations.js';
14
15
  import { directoryIssuer } from '../../../core/directory/issuer.js';
@@ -140,8 +141,11 @@ export function parseCallInput(body) {
140
141
  const machine = fields['machine'];
141
142
  if (machine !== undefined && (typeof machine !== 'string' || !machine.trim()))
142
143
  throw invalid('machine must be a machine id', 'machine');
144
+ const as = fields['as'];
145
+ if (as !== undefined && (typeof as !== 'string' || parsePrincipal(as) === null))
146
+ throw invalid('as must be a principal like user:<id> or app:<id>/<path>', 'as');
143
147
  return { provider, tool: tool.trim(), arguments: args, ...(version === undefined ? {} : { version }), ...(approval === undefined ? {} : { approval }),
144
- ...(machine === undefined ? {} : { machine: machine.trim() }) };
148
+ ...(machine === undefined ? {} : { machine: machine.trim() }), ...(as === undefined ? {} : { as }) };
145
149
  }
146
150
  async function auditList(caller, query = new URLSearchParams()) {
147
151
  const numeric = (name, fallback, max) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.747",
3
+ "version": "0.3.749",
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",