@north-light/api 0.3.752 → 0.3.753

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.76";
2
+ export declare const CONTRACT_LEVEL = "1.77";
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.76';
15
+ export const CONTRACT_LEVEL = '1.77';
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`. */
@@ -12,6 +12,9 @@ export interface HealthDTO {
12
12
  link_connected?: boolean;
13
13
  /** Present on a machine-role daemon only: false when this computer has no person sign-in, so it opens no link and runs no agent or cron. */
14
14
  signed_in?: boolean;
15
+ /** Present on a machine-role daemon only: id of the runtime generation it was launched from, null when it runs from a source checkout. That
16
+ * daemon serves no `/v1/status`, so `crtr sys daemon status` reads its generation here. */
17
+ generation_id?: string | null;
15
18
  /** Present while corpus migration or normal daemon startup is incomplete. */
16
19
  startup_blocked?: string;
17
20
  /** Always present; only `ready` admits normal daemon work. */
@@ -13,6 +13,7 @@ import { DaemonNotPreparedError, probeDaemonHealth, probeErrorMessage, spawnDaem
13
13
  import { isDaemonRunning, readPidfile, isPidAlive } from '../../daemon/pidfile.js';
14
14
  import { cliClient } from '../api-client.js';
15
15
  import { readMachineConfig } from '../../daemon/machine-link/config.js';
16
+ import { apiSocketPath } from '../../core/canvas/paths.js';
16
17
  import { localClient } from '../../api/node-transport.js';
17
18
  import { defineSysBranch } from './branch.js';
18
19
  import { selectedGeneration } from './shared.js';
@@ -156,9 +157,13 @@ const daemonAdmit = defineLeaf({
156
157
  });
157
158
  // daemon status
158
159
  /** The generation id the live daemon reports on `/v1/status`; undefined when it reports none or cannot be asked. */
159
- async function servingGenerationId() {
160
+ /** The generation this computer's daemon runs. It asks this computer's daemon socket, never a node's relay, which on an imported Mac answers
161
+ * for the shared control plane. A machine-role daemon serves no `/v1/status` and reports its generation in `/healthz` instead. */
162
+ async function servingGenerationId(health) {
163
+ if (health.generation_id !== undefined)
164
+ return health.generation_id ?? undefined;
160
165
  try {
161
- const status = await localClient({ autostart: false }).status();
166
+ const status = await localClient({ autostart: false, socketPath: apiSocketPath() }).status();
162
167
  return status.generation_id ?? undefined;
163
168
  }
164
169
  catch {
@@ -193,7 +198,7 @@ const daemonStatus = defineLeaf({
193
198
  return { running: false };
194
199
  try {
195
200
  const health = await probeDaemonHealth();
196
- const serving = await servingGenerationId();
201
+ const serving = await servingGenerationId(health);
197
202
  const selected = selectedGeneration().generation?.id;
198
203
  return {
199
204
  running: true,
@@ -183,7 +183,7 @@ export declare const terminalPlacementResidueSql = "SELECT\n node_id, creat
183
183
  export declare function listTerminalPlacementResidue(): Promise<TerminalPlacementResidue[]>;
184
184
  /** The daemon's complete supervision set. Live rows participate regardless of
185
185
  * PID; terminal rows participate only while they retain a PID or freeze mark. */
186
- export declare const nodesForSupervisionSql = "WITH candidates AS MATERIALIZED (\n SELECT node_id FROM nodes WHERE status IN ('active', 'idle')\n UNION\n SELECT node_id FROM nodes\n WHERE frozen_at IS NOT NULL AND status IN ('done', 'canceled', 'dead')\n UNION\n SELECT node_id FROM executions\n WHERE state != 'exited' AND state = 'running' AND pid IS NOT NULL\n )\n SELECT v.* FROM candidates c CROSS JOIN node_rows v\n WHERE v.node_id = c.node_id\n AND v.node_id NOT IN (SELECT node_id FROM warm_pool)\n AND v.kind != 'human'\n AND (v.status IN ('active', 'idle') OR (v.status IN ('done', 'canceled', 'dead') AND (v.pi_pid IS NOT NULL OR v.frozen_at IS NOT NULL)))\n ORDER BY v.created";
186
+ export declare const nodesForSupervisionSql: string;
187
187
  export declare function listNodesForSupervision(): Promise<NodeRow[]>;
188
188
  /** A parked resident the runtime may reopen when wake mail reaches it: `done` +
189
189
  * `intent='parked'`, resident, no final latch, and not being deleted. Finalized,
@@ -80,6 +80,16 @@ const turnOpen = (r) => r['turn_open_at'] != null && r['turn_closed_at'] == null
80
80
  /** Whether the engine behind an open turn is alive. A cloud role never hosts a broker (it runs on a Mac or in a sandbox),
81
81
  * so a pid probe on this host always fails there and the execution row is the only liveness record. */
82
82
  const engineLive = (pidPresentHere) => pidPresentHere || isCloudRole();
83
+ /** The `node_rows` columns `rowFrom` reads. Whole-table scans select these, never `*`: the view also carries each node's
84
+ * initial prompt, launch config and tool summaries (about 60 KB per finished node in prod), which no `NodeRow` holds. */
85
+ const NODE_ROW_COLUMNS = `node_id, name, description, cycles, kind, mode, lifecycle, status, cwd, host_kind, profile_id, scopes_json, isolated,
86
+ grantee, sub, grant_id, client_id, metadata_json, run_id, event_cursor, last_activity_at, caused_by, last_turn_error_json, deleting_at,
87
+ parent, created, intent, cycle_pending, frozen_at, respawn_failures, respawn_not_before, launched_at, last_settled_at, terminal_reason,
88
+ final_report, finalized_at, outcome_kind, outcome_reason, outcome_at, outcome_revision, outcome_detail_json, deadline_at,
89
+ telemetry_tokens_in, telemetry_context_tokens, telemetry_last_activity, telemetry_updated_at, pi_pid, pi_pid_identity,
90
+ "window", tmux_session, pane, turn_open_at, turn_closed_at,
91
+ fault_id, fault_link, fault_op, fault_kind, fault_message, fault_since, fault_operation_id, fault_anchor_entry_id,
92
+ fault_retry_disposition, fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at, fault_provider_error_json`;
83
93
  function rowFrom(r) {
84
94
  const node = {
85
95
  node_id: r['node_id'],
@@ -670,7 +680,7 @@ export async function listNodes(filter) {
670
680
  if (filter?.withRecordedPidOrFrozen === true)
671
681
  clauses.push('(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)');
672
682
  const rows = await (await openDb())
673
- .prepareUncached(`SELECT * FROM node_rows WHERE ${clauses.join(' AND ')} ORDER BY created`)
683
+ .prepareUncached(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows WHERE ${clauses.join(' AND ')} ORDER BY created`)
674
684
  .all(...params);
675
685
  return rows.map(rowFrom);
676
686
  }
@@ -702,7 +712,7 @@ export const nodesForSupervisionSql = `WITH candidates AS MATERIALIZED (
702
712
  SELECT node_id FROM executions
703
713
  WHERE state != 'exited' AND state = 'running' AND pid IS NOT NULL
704
714
  )
705
- SELECT v.* FROM candidates c CROSS JOIN node_rows v
715
+ SELECT ${NODE_ROW_COLUMNS.split(',').map((c) => `v.${c.trim()}`).join(', ')} FROM candidates c CROSS JOIN node_rows v
706
716
  WHERE v.node_id = c.node_id
707
717
  AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
708
718
  AND v.kind != 'human'
@@ -1109,13 +1119,13 @@ export async function pruneNodes(opts) {
1109
1119
  const quiet = (row) => lastActivityMs(row) < cutoffMs;
1110
1120
  const toPruned = (row) => ({ node_id: row.node_id, status: row.status, created: row.created });
1111
1121
  const watchedOwners = await ownersOfWatchedDocuments();
1112
- const terminal = (await filterAsync((await db.prepare(`SELECT * FROM node_rows
1122
+ const terminal = (await filterAsync((await db.prepare(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows
1113
1123
  WHERE status IN ('dead', 'done', 'canceled') AND created < ?
1114
1124
  ORDER BY created`)
1115
1125
  .all(cutoff))
1116
1126
  .map(rowFrom), async (row) => await isCollectible(row, { pastTtl: true }) && quiet(row) && !watchedOwners.has(row.node_id) && !await opts.held(row.node_id)))
1117
1127
  .map(toPruned);
1118
- const stale = !includeStale ? [] : (await filterAsync((await db.prepare(`SELECT * FROM node_rows
1128
+ const stale = !includeStale ? [] : (await filterAsync((await db.prepare(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows
1119
1129
  WHERE status IN ('active', 'idle') AND created < ?
1120
1130
  ORDER BY created`)
1121
1131
  .all(cutoff))
@@ -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 = 37;
4
+ export declare const CANVAS_SCHEMA_VERSION = 38;
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 = 37;
9
+ export const CANVAS_SCHEMA_VERSION = 38;
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. */
@@ -6,6 +6,9 @@ import { BODIES_TABLE, COPIED_TABLES, KEY_MAPPED_TABLES } from '../bundle/layout
6
6
  import { q, rowKey, topologicalOrder } from './catalog.js';
7
7
  import { fillEnvironments } from './prepare.js';
8
8
  import { ImportLaneError } from './stage.js';
9
+ import { encodeKeyBatches } from './keys.js';
10
+ /** Rows per INSERT. The staged table is read in ordinal ranges, so a statement returns at most this many keys to JS. */
11
+ const COPY_BATCH = 20_000;
9
12
  const sq = (schema, table) => `${q(schema)}.${q(table)}`;
10
13
  /** `import_manifest.inserted_keys`: a zstd-compressed JSON array of primary-key tuples (each value as text). */
11
14
  export const encodeKeys = (keys) => zstdCompressSync(Buffer.from(JSON.stringify(keys)));
@@ -42,20 +45,41 @@ export async function copyRows(input) {
42
45
  result.inserted[table] = keys.length;
43
46
  await db.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encodeKeys(keys));
44
47
  };
48
+ /** Numbers the staged rows `from` (a FROM/WHERE tail over alias `s`) in `order`, in Postgres: the ordinal table `_ord` holds each row's ctid and number. */
49
+ const number = async (table, order, where) => {
50
+ await db.exec(`DROP TABLE IF EXISTS ${S('_ord')}; CREATE TABLE ${S('_ord')} AS SELECT s.ctid AS row_id, (row_number() OVER (ORDER BY ${order}))::bigint AS n FROM ${S(table)} s${where}; CREATE INDEX ON ${S('_ord')} (n)`);
51
+ return Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S('_ord')}`).get()).n);
52
+ };
53
+ /** Runs `insert(low, high)` for each ordinal range of `total` rows (it returns that range's keys) and writes the keys to the table's manifest row, compressed as they arrive. */
54
+ const inBatches = async (table, total, insert, record = true) => {
55
+ let inserted = 0;
56
+ const batches = (async function* () {
57
+ for (let low = 0; low < total; low += COPY_BATCH) {
58
+ const keys = await insert(low, low + COPY_BATCH);
59
+ inserted += keys.length;
60
+ yield keys;
61
+ }
62
+ })();
63
+ const encoded = await encodeKeyBatches(batches);
64
+ if (record)
65
+ await db.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encoded);
66
+ return inserted;
67
+ };
45
68
  // The two identity-keyed tables first (nothing references them by a foreign key): the target numbers them in source order and the key map remembers it.
46
69
  // One statement per table: each staged row takes the next number of the target's identity sequence (in source order), is inserted under it, and is
47
70
  // recorded in the key map under its source key, so the pairing is explicit and no row costs a round trip.
48
71
  for (const [table, column] of Object.entries(KEY_MAPPED_TABLES)) {
49
72
  const info = catalog.tables.get(table);
50
73
  const columns = info.columns.filter((c) => c !== column);
51
- const rows = await db.prepareUncached(`WITH src AS MATERIALIZED (
52
- SELECT s.${q(column)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}
53
- FROM (SELECT * FROM ${S(table)} ORDER BY ${q(column)}::bigint) s),
74
+ // Source order is the numbering order: each batch takes the next numbers of the target's identity sequence, so batches in ordinal order keep the pairing.
75
+ const total = await number(table, `s.${q(column)}::bigint`, '');
76
+ const inserted = await inBatches(table, total, async (low, high) => (await db.prepareUncached(`WITH src AS MATERIALIZED (
77
+ SELECT s.source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}
78
+ FROM (SELECT s.${q(column)}::text AS source_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}, o.n FROM ${S(table)} s JOIN ${S('_ord')} o ON o.row_id = s.ctid WHERE o.n > ${low} AND o.n <= ${high} ORDER BY o.n) s),
54
79
  ins AS (INSERT INTO ${T(table)} (${q(column)}, ${columns.map(q).join(', ')}) SELECT target_key, ${columns.map(q).join(', ')} FROM src RETURNING 1),
55
80
  km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
56
- SELECT target_key FROM km ORDER BY target_key::bigint`)
57
- .all(T(table), column, source.installId, table);
58
- await manifest(table, rows.map((r) => [r.target_key]));
81
+ SELECT target_key FROM km ORDER BY target_key::bigint`).all(T(table), column, source.installId, table)).map((r) => [r.target_key]));
82
+ result.inserted[table] = inserted;
59
83
  }
60
84
  // `review_comments.created_seq` follows its event.
61
85
  await db.prepareUncached(`UPDATE ${S('review_comments')} c SET created_seq = m.target_key::bigint FROM import_key_map m
@@ -84,26 +108,29 @@ export async function copyRows(input) {
84
108
  const orderBy = info.identity.length > 0 ? info.identity.map((c) => `s.${q(c)}`).join(', ') : pk.map((c) => `s.${q(c)}`).join(', ');
85
109
  let select = columns.map((c) => `s.${q(c)}`);
86
110
  let where = '';
111
+ let last = 0;
87
112
  if (table === 'messages') {
88
113
  // `messages.seq` is a plain unique column: advance the counter once by the number of new rows and number them from the old value.
89
- const fresh = `NOT EXISTS (SELECT 1 FROM ${T('messages')} t WHERE t.message_id = s.message_id)`;
90
- const n = Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S('messages')} s WHERE ${fresh}`).get()).n);
91
- where = ` WHERE ${fresh}`;
92
- if (n === 0) {
114
+ where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T('messages')} t WHERE t.message_id = s.message_id)`;
115
+ }
116
+ // A table with no primary key is keyed by all its columns: a row the target already holds with equal columns is skipped.
117
+ const keyless = info.primaryKey.length === 0;
118
+ if (keyless)
119
+ where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T(table)} t WHERE ${pk.map((c) => `t.${q(c)} IS NOT DISTINCT FROM s.${q(c)}`).join(' AND ')})`;
120
+ // The rows to insert are decided and numbered once, before the first batch, so a batch never sees an earlier batch's rows as already in the target.
121
+ const total = await number(table, table === 'messages' ? 's.seq' : orderBy, where);
122
+ if (table === 'messages') {
123
+ if (total === 0) {
93
124
  result.inserted[table] = 0;
94
125
  await manifest(table, []);
95
126
  continue;
96
127
  }
97
- const last = Number((await db.prepare('UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq').get(n)).seq);
98
- select = columns.map((c) => c === 'seq' ? `${last - n} + row_number() OVER (ORDER BY s.seq)` : `s.${q(c)}`);
128
+ last = Number((await db.prepare('UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq').get(total)).seq);
129
+ select = columns.map((c) => c === 'seq' ? `${last - total} + o.n` : `s.${q(c)}`);
99
130
  }
100
131
  const returning = pk.map((c) => `${q(c)}::text`).join(', ');
101
- // A table with no primary key is keyed by all its columns: a row the target already holds with equal columns is skipped.
102
- const keyless = info.primaryKey.length === 0;
103
- if (keyless)
104
- where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T(table)} t WHERE ${pk.map((c) => `t.${q(c)} IS NOT DISTINCT FROM s.${q(c)}`).join(' AND ')})`;
105
- const inserted = await db.prepareUncached(`INSERT INTO ${T(table)} (${columns.map(q).join(', ')}) SELECT ${select.join(', ')} FROM ${S(table)} s${where}
106
- ORDER BY ${orderBy}${keyless ? '' : ` ON CONFLICT (${pk.map(q).join(', ')}) DO NOTHING`} RETURNING ${returning}`).all();
132
+ const insertedCount = await inBatches(table, total, async (low, high) => (await db.prepareUncached(`INSERT INTO ${T(table)} (${columns.map(q).join(', ')}) SELECT ${select.join(', ')} FROM ${S(table)} s JOIN ${S('_ord')} o ON o.row_id = s.ctid WHERE o.n > ${low} AND o.n <= ${high}
133
+ ORDER BY o.n${keyless ? '' : ` ON CONFLICT (${pk.map(q).join(', ')}) DO NOTHING`} RETURNING ${returning}`).all()).map((row) => Object.values(row)), table !== BODIES_TABLE);
107
134
  // `ON CONFLICT DO NOTHING` kept the target's row for a key it already held: that row must hold the same text (the pre-check compared them earlier, outside this transaction).
108
135
  if (table === BODIES_TABLE) {
109
136
  const clash = await db.prepareUncached(`SELECT s.hash FROM ${S(table)} s JOIN ${T(table)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();
@@ -112,11 +139,8 @@ export async function copyRows(input) {
112
139
  }
113
140
  }
114
141
  // `bodies` rows are never deleted (design-fleet D106), so a rollback must not remove them: no manifest row. The hash is the key on both sides.
115
- if (table === BODIES_TABLE)
116
- result.inserted[table] = inserted.length;
117
- else
118
- await manifest(table, inserted.map((row) => Object.values(row)));
119
- result.mapped[table] = staged - inserted.length;
142
+ result.inserted[table] = insertedCount;
143
+ result.mapped[table] = staged - insertedCount;
120
144
  }
121
145
  for (const f of filled)
122
146
  await db.prepare(`INSERT INTO ${S('_filled')} VALUES (?, ?::jsonb)`).run(f.table, JSON.stringify(f.key));
@@ -0,0 +1,5 @@
1
+ export declare const KEY_BATCH = 5000;
2
+ /** Compress the batches into one `inserted_keys` value. */
3
+ export declare function encodeKeyBatches(batches: AsyncIterable<string[][]>): Promise<Buffer>;
4
+ /** The tuples of an `inserted_keys` value, `size` at a time. */
5
+ export declare function keyBatches(data: Buffer, size?: number): AsyncGenerator<string[][]>;
@@ -0,0 +1,77 @@
1
+ // Manifest keys without whole-account arrays. `import_manifest.inserted_keys` is a zstd-compressed JSON array of primary-key tuples; the streaming writer puts one tuple per
2
+ // line (`[`, `k1,`, `k2`, `]`: still one valid JSON array, so `decodeKeys` reads it) and the streaming reader yields batches of tuples, so memory is one batch plus the compressed bytes.
3
+ // An array written in one line by an earlier release is read whole.
4
+ import { createZstdCompress, createZstdDecompress } from 'node:zlib';
5
+ import { once } from 'node:events';
6
+ export const KEY_BATCH = 5000;
7
+ /** Compress the batches into one `inserted_keys` value. */
8
+ export async function encodeKeyBatches(batches) {
9
+ const zst = createZstdCompress();
10
+ const out = [];
11
+ zst.on('data', (chunk) => out.push(chunk));
12
+ const done = once(zst, 'end');
13
+ const put = async (text) => { if (!zst.write(text, 'utf8'))
14
+ await once(zst, 'drain'); };
15
+ await put('[\n');
16
+ let first = true;
17
+ for await (const batch of batches) {
18
+ if (batch.length === 0)
19
+ continue;
20
+ await put((first ? '' : ',\n') + batch.map((key) => JSON.stringify(key)).join(',\n'));
21
+ first = false;
22
+ }
23
+ await put('\n]');
24
+ zst.end();
25
+ await done;
26
+ return Buffer.concat(out);
27
+ }
28
+ /** The tuples of an `inserted_keys` value, `size` at a time. */
29
+ export async function* keyBatches(data, size = KEY_BATCH) {
30
+ const zst = createZstdDecompress({ chunkSize: 1 << 20 });
31
+ zst.end(data);
32
+ let pending = '';
33
+ let batch = [];
34
+ let streaming;
35
+ let legacy = [];
36
+ for await (const chunk of zst) {
37
+ if (streaming === false) {
38
+ legacy.push(chunk);
39
+ continue;
40
+ }
41
+ pending += chunk.toString('utf8');
42
+ if (streaming === undefined) {
43
+ if (pending.length < 2)
44
+ continue;
45
+ streaming = pending.startsWith('[\n') || pending === '[]';
46
+ if (!streaming) {
47
+ legacy.push(Buffer.from(pending));
48
+ pending = '';
49
+ continue;
50
+ }
51
+ }
52
+ let at = pending.indexOf('\n');
53
+ while (at !== -1) {
54
+ const line = pending.slice(0, at).replace(/,$/, '');
55
+ pending = pending.slice(at + 1);
56
+ if (line !== '[' && line !== ']' && line !== '') {
57
+ batch.push(JSON.parse(line));
58
+ if (batch.length >= size) {
59
+ yield batch;
60
+ batch = [];
61
+ }
62
+ }
63
+ at = pending.indexOf('\n');
64
+ }
65
+ }
66
+ if (streaming === false || streaming === undefined) {
67
+ const all = legacy.length > 0 ? JSON.parse(Buffer.concat(legacy).toString('utf8')) : (pending === '' ? [] : JSON.parse(pending));
68
+ for (let i = 0; i < all.length; i += size)
69
+ yield all.slice(i, i + size);
70
+ return;
71
+ }
72
+ const tail = pending.replace(/,$/, '').trim();
73
+ if (tail !== '' && tail !== ']' && tail !== '[')
74
+ batch.push(JSON.parse(tail));
75
+ if (batch.length > 0)
76
+ yield batch;
77
+ }
@@ -5,8 +5,8 @@ import { takePercent } from './rates.js';
5
5
  import { usageMonth } from './months.js';
6
6
  /** The id of a tool charge: the receipt-level idempotency key, so two providers' receipt ids never collide. */
7
7
  export const receiptChargeId = (provider, receiptId) => `receipt:${provider}:${receiptId}`;
8
- const COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger';
9
- const PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true';
8
+ const COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger, actor';
9
+ const PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true, ?';
10
10
  /** Write one charge row; the `charges` trigger (schema delta 007) adds it to `charge_totals`. A refused row is stored with
11
11
  * usd 0 and never rolled up; a take row (written only while `CRTR_LEDGER_TAKE_PCT` > 0) is stored and never rolled up. Inside a
12
12
  * caller's `withCanvasWrite` it joins that transaction. */
@@ -22,7 +22,7 @@ export async function writeCharge(input) {
22
22
  rowId, input.request ?? null, at.toISOString(), month, kind, what, input.units == null ? null : JSON.stringify(input.units), rowUsd,
23
23
  input.payer, funding, input.sub ?? null, input.grantee, input.node ?? null, input.run ?? null, input.provider ?? null,
24
24
  input.causedBy ?? null, input.vendorRef ?? null, refused === null ? null : JSON.stringify(refused), input.account ?? null, input.billedUsd ?? null,
25
- null, null, null, null
25
+ null, null, null, null, input.actor ?? null
26
26
  ];
27
27
  const inserted = await db.prepare(`INSERT INTO charges (${COLUMNS}) VALUES (${PLACEHOLDERS}) ON CONFLICT (id) DO NOTHING`)
28
28
  .run(...row(id, input.kind, input.what, usd, input.funding));
@@ -5,7 +5,7 @@ import { zstdDecompressSync } from 'node:zlib';
5
5
  import { blobStore } from '../blobs/index.js';
6
6
  import { openDb } from '../canvas/db.js';
7
7
  import { chargeOf } from './charges.js';
8
- const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source'];
8
+ const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source', 'actor'];
9
9
  /** The moved rows of a month (or of every month), from month `since` on, read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
10
10
  export class ChunkRows {
11
11
  since;
@@ -9,7 +9,7 @@ import { chargeOf } from './charges.js';
9
9
  import { ChunkRows } from './chunks.js';
10
10
  import { listLimits } from './limits.js';
11
11
  import { resetAt, usageMonth } from './months.js';
12
- const CHARGE_COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source';
12
+ const CHARGE_COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, actor';
13
13
  /** `usage.get` for one grantee and month, computed from `charges`. `by_model` and `app_paid.by_model` group the `model` rows
14
14
  * of a `user:` / `app:` payer by `what`, with token sums from `units` and `usd_equivalent` null when every row's `usd` is null.
15
15
  * `usd_equivalent` is what the grant's limit reads: every `user:` payer charge for this grantee, model and tool, refused and
@@ -21,6 +21,8 @@ export interface Charge {
21
21
  payer: string;
22
22
  funding: Funding;
23
23
  sub: string | null;
24
+ /** The principal that presented the call; null when unknown. */
25
+ actor: string | null;
24
26
  grantee: string;
25
27
  node: string | null;
26
28
  run: string | null;
@@ -52,6 +54,8 @@ export interface ChargeInput {
52
54
  payer: string;
53
55
  funding: Funding;
54
56
  sub?: string | null;
57
+ /** The principal that presented the call (`Principal.actor`). */
58
+ actor?: string | null;
55
59
  grantee: string;
56
60
  node?: string | null;
57
61
  run?: string | null;
@@ -9,8 +9,8 @@ export async function writeProviderAudit(row) {
9
9
  const chain = sub && grantee ? [sub, grantee, `runtime:${runtimeId()}`] : null;
10
10
  await (await openDb()).prepare(`INSERT INTO audit_rows
11
11
  (request_id, time, grantee, sub, client_id, class, operation, scope_checked,
12
- outcome, node_id, run_id, resource, initiator_chain, provider, tool, jti, receipt_id, responder, question_id)
13
- VALUES (?, ?, ?, ?, ?, ?, 'provider.call', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.request_id, new Date().toISOString(), grantee, sub, caller.client_id, caller.class, row.scope_checked ?? null, row.outcome, caller.node_id, caller.run_id, `${row.provider} ${row.tool}`, chain ? JSON.stringify(chain) : null, row.provider, row.tool, row.jti ?? null, row.receipt_id ?? null, row.responder ?? null, row.question_id ?? null);
12
+ outcome, node_id, run_id, resource, initiator_chain, provider, tool, jti, receipt_id, responder, question_id, actor)
13
+ VALUES (?, ?, ?, ?, ?, ?, 'provider.call', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.request_id, new Date().toISOString(), grantee, sub, caller.client_id, caller.class, row.scope_checked ?? null, row.outcome, caller.node_id, caller.run_id, `${row.provider} ${row.tool}`, chain ? JSON.stringify(chain) : null, row.provider, row.tool, row.jti ?? null, row.receipt_id ?? null, row.responder ?? null, row.question_id ?? null, caller.actor ?? null);
14
14
  }
15
15
  export async function listAudit(grantee, filters) {
16
16
  const where = [];
@@ -35,6 +35,8 @@ export interface ProviderResponseContext {
35
35
  /** The calling node, and the `Crtr-Caused-By` the call arrived with; null when none. */
36
36
  node_id: string | null;
37
37
  caused_by: string | null;
38
+ /** The caller's presenting principal; null when none. */
39
+ actor?: string | null;
38
40
  jti: string;
39
41
  status: number;
40
42
  headers: Record<string, string | string[] | undefined>;
@@ -285,7 +285,7 @@ export async function callProvider(caller, rawInput, request) {
285
285
  const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub, environmentPayer: await environmentPayerOfNode(caller.node_id) });
286
286
  const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee, provider: `app:${bundle.id}` });
287
287
  if (refusal !== null) {
288
- await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee,
288
+ await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, actor: caller.actor ?? null, grantee: chargeGrantee,
289
289
  node: caller.node_id, run: caller.run_id, provider: `app:${bundle.id}`, causedBy: request.causedBy ?? null, refused: refusedMark(refusal) });
290
290
  throw refusalError(refusal);
291
291
  }
@@ -317,7 +317,7 @@ export async function callProvider(caller, rawInput, request) {
317
317
  }
318
318
  // R7 receives every response, including errors, before the mapping.
319
319
  receiptId ??= await onProviderResponse({ provider: bundle.id, tool: input.tool, request_id: requestId, run_id: caller.run_id,
320
- sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
320
+ sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, actor: caller.actor ?? null, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
321
321
  responder = response.headers['crtr-responder'];
322
322
  if (response.status === 401)
323
323
  discardFile(token.key);
@@ -15,6 +15,8 @@ type ReceiptCall = {
15
15
  /** The calling node and the call's `Crtr-Caused-By`; null when none. */
16
16
  node_id: string | null;
17
17
  caused_by: string | null;
18
+ /** The caller's presenting principal; null when none. */
19
+ actor?: string | null;
18
20
  };
19
21
  /**
20
22
  * A provider's informational receipts must belong to the call that carried them. The header is one
@@ -42,7 +42,7 @@ export async function acceptProviderReceipt(value, call) {
42
42
  for (const receipt of accepted) {
43
43
  // One row per receipt, keyed by (provider, receipt id): a repeat delivery writes nothing and adds nothing.
44
44
  await writeCharge({ id: receiptChargeId(call.provider, receipt.receipt_id), request: call.request_id, kind: 'tool', what: `${call.provider}:${call.tool}`,
45
- units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub,
45
+ units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub, actor: call.actor ?? null,
46
46
  grantee: call.ledger_grantee ?? call.grantee, node: call.node_id, run: call.run_id, provider: `app:${call.provider}`, causedBy: call.caused_by, vendorRef: receipt.receipt_id });
47
47
  }
48
48
  });
@@ -13,6 +13,8 @@ export interface ProviderCaller {
13
13
  sub: string | null;
14
14
  grantee: string | null;
15
15
  client_id: string | null;
16
+ /** The principal that presented the call (`Principal.actor`); absent when the caller is not a token presenter. */
17
+ actor?: string;
16
18
  resolved: readonly string[] | null;
17
19
  nodeScopes: readonly string[] | null;
18
20
  run_id: string | null;
@@ -65,7 +65,7 @@ export async function callerFromRequest(principal) {
65
65
  run_id: principal.run ?? (await getNode(principal.node))?.run_id ?? null, node_id: principal.node };
66
66
  }
67
67
  export function callerFromApp(principal) {
68
- return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
68
+ return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, actor: principal.actor, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
69
69
  }
70
70
  /** A provider scope `<provider>:<group>` (the identity grammar's `provider`
71
71
  * selector kind). `covers()` grants such a scope only by exact equality. */
@@ -8,7 +8,7 @@ import { createRequire } from 'node:module';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { fileURLToPath, pathToFileURL } from 'node:url';
10
10
  import { existsSync, lstatSync, mkdirSync, openSync, closeSync, fstatSync, readSync } from 'node:fs';
11
- import { crtrHome } from '../core/canvas/paths.js';
11
+ import { apiSocketPath, crtrHome } from '../core/canvas/paths.js';
12
12
  import { listProcessTable } from '../core/canvas/pid.js';
13
13
  import { bindDaemonEventSource, eventSource } from '../core/events/source.js';
14
14
  import { hostExecPath } from '../core/runtime/branded-host.js';
@@ -245,7 +245,8 @@ const DAEMON_HEALTH_PROBE_TIMEOUT_MS = 1_000;
245
245
  /** Make one `/healthz` observation without client-side recovery. The caller owns the availability window, so this probe cannot extend it. */
246
246
  export async function probeDaemonHealth(timeoutMs = DAEMON_HEALTH_PROBE_TIMEOUT_MS) {
247
247
  const probeTimeoutMs = Math.min(timeoutMs, DAEMON_HEALTH_PROBE_TIMEOUT_MS);
248
- return localClient({ autostart: false, timeoutMs: probeTimeoutMs }).probeHealthz(probeTimeoutMs);
248
+ // This computer's daemon socket, never a node's `CRTR_API_SOCKET` relay: inside a node on an imported Mac that relay answers for the shared control plane.
249
+ return localClient({ autostart: false, timeoutMs: probeTimeoutMs, socketPath: apiSocketPath() }).probeHealthz(probeTimeoutMs);
249
250
  }
250
251
  export function probeErrorMessage(error) {
251
252
  const message = error instanceof Error ? error.message : String(error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.752",
3
+ "version": "0.3.753",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",