@north-light/api 0.3.748 → 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.
@@ -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.
@@ -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 && !meta.sub.startsWith('app:'))
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 = 35;
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 = 35;
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. */
@@ -239,7 +239,7 @@ export declare function takeMachineSelector(tokens: readonly string[]): {
239
239
  rest: string[];
240
240
  machine?: string;
241
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. */
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
243
  export declare function takeActingAs(tokens: readonly string[]): {
244
244
  rest: string[];
245
245
  as?: string;
@@ -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';
@@ -721,7 +722,7 @@ export function takeMachineSelector(tokens) {
721
722
  }
722
723
  return machine === undefined ? { rest } : { rest, machine };
723
724
  }
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
+ /** Take the `--as <principal>` / `--as=<user:id>` option out of an opted-in leaf's argv. Nothing after a bare `--` is a flag. */
725
726
  export function takeActingAs(tokens) {
726
727
  const rest = [];
727
728
  let as;
@@ -737,8 +738,8 @@ export function takeActingAs(tokens) {
737
738
  continue;
738
739
  }
739
740
  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`.');
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`.');
742
743
  }
743
744
  if (inline === undefined)
744
745
  i++;
@@ -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') {
@@ -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,11 +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:/, '');
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);
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; };
15
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. */
16
18
  export async function userOf(db, reader) {
17
- 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());
18
27
  }
19
28
  /** The user a reader names itself, without falling back to the process's person; null when it names none. */
20
29
  async function namedUserOf(db, reader) {
@@ -53,7 +62,7 @@ export function resolveReader(db, reader) {
53
62
  if (shared)
54
63
  return shared;
55
64
  const ev = (async () => {
56
- 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);
57
66
  return { reader, userId, subjects: userId === null ? { userIds: ['*'], groupIds: [] } : await subjectSet(db, userId), defs: await loadDefinitions(db) };
58
67
  })();
59
68
  if (shared === null) {
@@ -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.748",
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",