@north-light/cli 0.3.690 → 0.3.692

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 (63) hide show
  1. package/dist/api/client.d.ts +6 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/canvas.d.ts +6 -0
  6. package/dist/api/dto/files.d.ts +17 -0
  7. package/dist/api/dto/reviews.d.ts +2 -0
  8. package/dist/api/routes.d.ts +3 -0
  9. package/dist/api/routes.js +1 -1
  10. package/dist/builtin-memory/crouter-sdk/release-notes.md +4 -0
  11. package/dist/clients/attach/chrome/canvas-panels.d.ts +2 -1
  12. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  13. package/dist/clients/attach/chrome/inbox-strip.d.ts +2 -1
  14. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  15. package/dist/clients/attach/chrome/roster.d.ts +2 -1
  16. package/dist/clients/attach/chrome/roster.js +5 -5
  17. package/dist/clients/attach/session/chrome-refresh.d.ts +2 -1
  18. package/dist/clients/attach/session/chrome-refresh.js +1 -1
  19. package/dist/clients/attach/viewer.js +527 -527
  20. package/dist/clients/inbox/review/review-client.js +1 -1
  21. package/dist/commands/api-client.d.ts +2 -1
  22. package/dist/commands/api-client.js +2 -2
  23. package/dist/core/canvas/canvas.d.ts +2 -2
  24. package/dist/core/canvas/canvas.js +2 -2
  25. package/dist/core/canvas/source.d.ts +4 -2
  26. package/dist/core/canvas/waits.d.ts +2 -2
  27. package/dist/core/canvas/waits.js +7 -7
  28. package/dist/core/command-plugins/compose.js +1 -1
  29. package/dist/core/providers/files.d.ts +2 -0
  30. package/dist/core/providers/files.js +1 -1
  31. package/dist/core/review/stage.d.ts +6 -0
  32. package/dist/core/review/stage.js +1 -1
  33. package/dist/core/storage/node-transfer.d.ts +6 -0
  34. package/dist/core/storage/node-transfer.js +1 -0
  35. package/dist/daemon/api/handlers/canvas.js +16 -6
  36. package/dist/daemon/api/handlers/node-files.js +1 -1
  37. package/dist/daemon/api/handlers/reviews.js +1 -1
  38. package/dist/daemon/api/operations.js +1 -1
  39. package/dist/daemon/api/router.d.ts +2 -0
  40. package/dist/daemon/api/router.js +1 -1
  41. package/docs/sdk/release-notes.md +4 -0
  42. package/package.json +3 -3
  43. package/packages/crouter-api/dist/api/client.js +10 -0
  44. package/packages/crouter-api/dist/api/contract.js +1 -1
  45. package/packages/crouter-api/dist/api/routes.js +3 -0
  46. package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +2 -2
  47. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +11 -9
  48. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +2 -2
  49. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +22 -10
  50. package/packages/crouter-api/dist/clients/attach/viewer.js +3 -3
  51. package/packages/crouter-api/dist/clients/inbox/review/review-client.js +3 -1
  52. package/packages/crouter-api/dist/commands/api-client.js +3 -0
  53. package/packages/crouter-api/dist/core/canvas/canvas.js +4 -4
  54. package/packages/crouter-api/dist/core/canvas/waits.js +4 -4
  55. package/packages/crouter-api/dist/core/command-plugins/compose.js +16 -3
  56. package/packages/crouter-api/dist/core/providers/files.js +80 -9
  57. package/packages/crouter-api/dist/core/storage/node-transfer.js +100 -0
  58. package/packages/crouter-api/dist/daemon/api/operations.js +3 -0
  59. package/packages/crouter-api/dist/daemon/api/router.js +11 -0
  60. package/packages/crouter-api/package.json +1 -1
  61. package/packages/crouter-identity/package.json +1 -1
  62. package/packages/crouter-plugin/package.json +3 -3
  63. package/runtime.lock.json +14 -14
@@ -63,7 +63,7 @@ export function createRoster(s, hooks) {
63
63
  tui.requestRender();
64
64
  };
65
65
  const listJobs = async () => (await cliClient().listBashJobs(nodeId)).map(toBashJobStatus);
66
- const refresh = async () => {
66
+ const refresh = async (view) => {
67
67
  const crons = remote ? [] : await cliClient().listCrons();
68
68
  const ownedCrons = crons.filter((cron) => cron.created_by === nodeId);
69
69
  // Local-only, same gate as ownedCrons: a local nodeId collision must never leak background jobs.
@@ -74,7 +74,7 @@ export function createRoster(s, hooks) {
74
74
  const openReviews = remote ? [] : (await cliClient().listReviews({ state: 'open' })).reviews;
75
75
  const reviews = openReviews.filter((review) => review.origin_node_id === nodeId);
76
76
  const others = remote ? undefined : { crons, reviews: openReviews, jobsOf: async (id) => (await cliClient().listBashJobs(id)).map(toBashJobStatus) };
77
- const built = await buildCanvasPanelLines(nodeId, hooks.asks(), pal, canvasSource, ownedCrons, bashJobs, reviews, others);
77
+ const built = await buildCanvasPanelLines(nodeId, hooks.asks(), pal, canvasSource, ownedCrons, bashJobs, reviews, others, view ?? await canvasSource.panelView?.(nodeId));
78
78
  items = built.items;
79
79
  // After an in-place swap, land on the previously open node, which has taken
80
80
  // the swapped-to node's place in this self-excluding roster.
@@ -53,6 +53,12 @@ export function createChromeRefresh(ctx, hooks) {
53
53
  .slice(0, 120);
54
54
  hooks.setNotice(detail === '' ? `${label} delayed` : `${label} delayed — ${detail}`);
55
55
  };
56
+ const setAsks = (counts) => {
57
+ if (JSON.stringify(counts) === JSON.stringify(asksMap))
58
+ return;
59
+ asksMap = counts;
60
+ hooks.renderFooter(); // the closed-inbox footer total tracks asksMap
61
+ };
56
62
  // Refresh all canvas chrome (panels + overlay if open) from the active canvas source.
57
63
  let chromeRefreshInFlight = false;
58
64
  let chromeRefreshQueued = false;
@@ -67,7 +73,11 @@ export function createChromeRefresh(ctx, hooks) {
67
73
  chromeRefreshQueued = false;
68
74
  const seqBefore = failureSeq;
69
75
  try {
70
- await hooks.refreshRoster();
76
+ // One read of this node's tree feeds the panels, the inbox strip and the ask counts.
77
+ const view = await canvasSource.panelView?.(nodeId);
78
+ if (view !== undefined)
79
+ setAsks(view.counts);
80
+ await hooks.refreshRoster(view);
71
81
  if (failureSeq === seqBefore)
72
82
  markHealthy();
73
83
  }
@@ -107,15 +117,17 @@ export function createChromeRefresh(ctx, hooks) {
107
117
  // cadence is what brings its backgrounding hint on screen.
108
118
  hooks.refreshInFlightTools();
109
119
  hooks.renderFooter();
110
- void (async () => {
111
- const root = await climbRootFromSource(nodeId);
112
- const counts = await canvasSource.ticketCountsForView(root);
113
- if (JSON.stringify(counts) !== JSON.stringify(asksMap)) {
114
- asksMap = counts;
115
- refresh();
116
- hooks.renderFooter(); // the closed-inbox footer total tracks asksMap
117
- }
118
- })().catch((err) => reportFailure('canvas attention refresh', err));
120
+ // A remote canvas has no tree read: it climbs and counts node by node.
121
+ if (canvasSource.panelView === undefined)
122
+ void (async () => {
123
+ const root = await climbRootFromSource(nodeId);
124
+ const counts = await canvasSource.ticketCountsForView(root);
125
+ if (JSON.stringify(counts) !== JSON.stringify(asksMap)) {
126
+ asksMap = counts;
127
+ refresh();
128
+ hooks.renderFooter();
129
+ }
130
+ })().catch((err) => reportFailure('canvas attention refresh', err));
119
131
  };
120
132
  const nextDelay = () => stalledPasses === 0 ? ASKS_POLL_MS : Math.min(ASKS_POLL_MS * 2 ** stalledPasses, ASKS_POLL_MAX_MS);
121
133
  // A self-rescheduling timer rather than an interval, so the wait can grow
@@ -439,9 +439,9 @@ onConnected) {
439
439
  const chromeRefresh = createChromeRefresh(ctx, {
440
440
  isTornDown: () => lifecycle.isTornDown(),
441
441
  setNotice,
442
- refreshRoster: async () => {
443
- await roster.refresh();
444
- await strip.refresh();
442
+ refreshRoster: async (view) => {
443
+ await roster.refresh(view);
444
+ await strip.refresh(view);
445
445
  },
446
446
  refreshGraph: () => graphOverlay.refresh(),
447
447
  refreshIdentity: () => identity.refresh(),
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { ApiError } from '../../../api/errors.js';
3
+ import { filesCrossByUpload, uploadNodeFile } from '../../../core/storage/node-transfer.js';
3
4
  import { cliClient } from '../../../commands/api-client.js';
4
5
  import { createCommentAuthority } from './comments-client.js';
5
6
  export class ReviewTerminalError extends Error {
@@ -41,10 +42,11 @@ export function createReviewClient(opts = {}) {
41
42
  return await resolveReview(review, review.companion_node_id, request);
42
43
  },
43
44
  async createInline(p) {
45
+ const uploadId = 'file' in p && filesCrossByUpload() ? await uploadNodeFile(p.file) : undefined;
44
46
  const review = await request(() => cliClient().createReview({
45
47
  origin_kind: 'inline',
46
48
  origin_node_id: p.originNodeId,
47
- ...('file' in p ? { file: p.file } : { document: p.document }),
49
+ ...('file' in p ? (uploadId !== undefined ? { file_upload_id: uploadId } : { file: p.file }) : { document: p.document }),
48
50
  idempotency_key: randomUUID(),
49
51
  }));
50
52
  return await resolveReview(review, review.companion_node_id, request);
@@ -352,6 +352,9 @@ export class ApiCanvasSource {
352
352
  this.rosterCache = { at: Date.now(), index };
353
353
  return snapshot.nodes.map((node) => withRowFault(node));
354
354
  }
355
+ async panelView(nodeId) {
356
+ return await this.client.canvasView(nodeId);
357
+ }
355
358
  async panelRoster() {
356
359
  const index = await this.roster();
357
360
  if (index.snapshot !== undefined)
@@ -839,13 +839,13 @@ export async function childrenOf(id) {
839
839
  return (await (await openDb()).prepare('SELECT node_id FROM nodes WHERE parent = ? ORDER BY created')
840
840
  .all(id)).map((r) => r.node_id);
841
841
  }
842
- /** Every node's lean roster row, oldest first — a single scan indexed by
842
+ /** Every node's lean roster row (only those in `ids` when given), oldest first — a single scan indexed by
843
843
  * `idx_nodes_created`, with no per-row hydration or N+1 query. */
844
- export async function rosterNodes() {
844
+ export async function rosterNodes(ids) {
845
845
  return (await (await openDb())
846
846
  .prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
847
- FROM node_rows WHERE ${NOT_A_SPARE} ORDER BY created`)
848
- .all()).map((r) => ({
847
+ FROM node_rows WHERE ${NOT_A_SPARE}${ids === undefined ? '' : ' AND node_id = ANY(?::text[])'} ORDER BY created`)
848
+ .all(...(ids === undefined ? [] : [[...ids]]))).map((r) => ({
849
849
  node_id: r['node_id'],
850
850
  name: r['name'],
851
851
  kind: r['kind'],
@@ -91,15 +91,15 @@ export async function settleObjectWaits(db, objectId, nodeId = null, now = Date.
91
91
  export async function settleNodeObjectWaits(db, nodeId, now = Date.now()) {
92
92
  return Number((await db.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND node_id = ? AND satisfied_at IS NULL").run(now, nodeId)).changes);
93
93
  }
94
- /** Every node's live object waits with the watched object's kind and name, for the roster. A deleted object
94
+ /** Every node's live object waits (only `nodeIds`' when given) with the watched object's kind and name, for the roster. A deleted object
95
95
  * settles its waits on publish, so none should dangle; a wait whose object row is gone is skipped rather than shown nameless. */
96
- export async function liveObjectWaitsNamed(db) {
96
+ export async function liveObjectWaitsNamed(db, nodeIds) {
97
97
  db ??= await openDb();
98
98
  return (await db.prepare(`SELECT w.wait_id, w.node_id, w.target_id, w.created_at, o.type AS object_type, o.name AS object_name
99
99
  FROM waits w JOIN objects o ON o.id = w.target_id
100
- WHERE w.kind = 'object' AND w.satisfied_at IS NULL AND o.deleted_at IS NULL
100
+ WHERE w.kind = 'object' AND w.satisfied_at IS NULL AND o.deleted_at IS NULL${nodeIds === undefined ? '' : ' AND w.node_id = ANY(?::text[])'}
101
101
  ORDER BY w.node_id, w.created_at, w.seq`)
102
- .all())
102
+ .all(...(nodeIds === undefined ? [] : [[...nodeIds]])))
103
103
  .map((row) => ({ waitId: row.wait_id, nodeId: row.node_id, objectId: row.target_id, createdAt: row.created_at, objectType: row.object_type, objectName: row.object_name }));
104
104
  }
105
105
  export async function hasLiveObjectWait(nodeId) {
@@ -8,6 +8,7 @@ import { defineBranch, defineLeaf } from '../command.js';
8
8
  import { qualifiedTopLevelCommandName, resolveCommandRegistry } from '../command-manifests/registry.js';
9
9
  import { executeExternalLeaf } from './transport/exec-invoke.js';
10
10
  import { invokeHttpLeaf } from './transport/http-invoke.js';
11
+ import { downloadNodeUpload, filesCrossByUpload, uploadNodeFile } from '../storage/node-transfer.js';
11
12
  import { readPathParam } from './transport/http-plan.js';
12
13
  import { sha256Hex, signedHeaderDigest } from './transport/sign.js';
13
14
  import { needsAppToken } from '../plugin-objects-manifest.js';
@@ -64,15 +65,27 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
64
65
  const value = argumentsForDaemon[key];
65
66
  // `file` params are uploaded by the daemon from an absolute path; `path`
66
67
  // params are read here, in the caller's cwd, and travel as their content.
67
- if (param.type === 'file' && typeof value === 'string')
68
- argumentsForDaemon[key] = resolve(value);
68
+ if (param.type === 'file' && typeof value === 'string') {
69
+ // Where the control plane runs this command it cannot open this node's disk: send the file by upload id.
70
+ argumentsForDaemon[key] = filesCrossByUpload() ? { upload_id: await uploadNodeFile(resolve(value)) } : resolve(value);
71
+ }
69
72
  else if (param.type === 'path' && value !== undefined)
70
73
  argumentsForDaemon[key] = readPathParam(`provider command \`${provider} ${tool}\``, param, value);
71
74
  }
72
75
  try {
73
- return await cliClient({ timeoutMs: 0 }).request('POST', '/v1/provider/call', {
76
+ const result = await cliClient({ timeoutMs: 0 }).request('POST', '/v1/provider/call', {
74
77
  provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }),
75
78
  }, { timeout: 0 });
79
+ if (filesCrossByUpload()) {
80
+ for (const field of leaf.output ?? []) {
81
+ const held = result[field.name];
82
+ if (field.type === 'file' && held && typeof held === 'object' && typeof held['upload_id'] === 'string') {
83
+ const { upload_id, size, sha256 } = held;
84
+ result[field.name] = await downloadNodeUpload(upload_id, field.name, size, sha256);
85
+ }
86
+ }
87
+ }
88
+ return result;
76
89
  }
77
90
  catch (error) {
78
91
  // The runtime's own code and details (`machine_required` + candidates, `device_offline`, …) reach the caller, not the status default.
@@ -17,7 +17,7 @@
17
17
  import { createHash } from 'node:crypto';
18
18
  import { closeSync, constants, createWriteStream } from 'node:fs';
19
19
  import { basename, extname, isAbsolute, join } from 'node:path';
20
- import { Transform } from 'node:stream';
20
+ import { Transform, Writable } from 'node:stream';
21
21
  import { pipeline } from 'node:stream/promises';
22
22
  import { appSpace } from '../layout.js';
23
23
  import { RunError } from '../runs/operations.js';
@@ -117,16 +117,46 @@ async function copyOutbound(storage, checked) {
117
117
  }
118
118
  /** Check every file argument, then copy them: a refusal of any argument copies
119
119
  * nothing. Absent (or null) optional file arguments pass through. */
120
+ function uploadRef(value) {
121
+ if (!value || typeof value !== 'object' || Array.isArray(value))
122
+ return null;
123
+ const keys = Object.keys(value);
124
+ const id = value['upload_id'];
125
+ return keys.length === 1 && typeof id === 'string' && id !== '' ? id : null;
126
+ }
127
+ /** A file argument that is an upload the node's CLI made: the control plane cannot open the node's path, so it signs the stored bytes. */
128
+ async function uploadArgument(caller, param, uploadId, storage) {
129
+ if (!isCloudRole())
130
+ throw new ProviderError('invalid_request', `${param} must be an absolute runtime path`, { param });
131
+ const row = await getUpload(uploadId);
132
+ if (!row || row.delete_pending_since || row.grantee !== caller.grantee || (row.sub !== null && row.sub !== (caller.sub ?? null)))
133
+ throw new ProviderError('not_found', `no such upload: ${uploadId}`, { param });
134
+ try {
135
+ const signed = await storage().signDownload(uploadId);
136
+ return { param, path: '', name: row.name, object_id: uploadId, upload_id: uploadId, url: signed.url };
137
+ }
138
+ catch (error) {
139
+ if (error instanceof StorageRefused)
140
+ throw new ProviderError('not_found', `upload ${uploadId} holds no bytes`, { param });
141
+ throw storageFailure(error);
142
+ }
143
+ }
120
144
  async function copyArguments(caller, params, args, storage) {
121
145
  const checked = [];
146
+ const uploaded = [];
122
147
  try {
123
148
  for (const param of params) {
124
149
  if (args[param] === undefined || args[param] === null)
125
150
  continue;
151
+ const ref = uploadRef(args[param]);
152
+ if (ref !== null) {
153
+ uploaded.push(await uploadArgument(caller, param, ref, storage));
154
+ continue;
155
+ }
126
156
  checked.push(checkFileArgument(caller, param, args[param]));
127
157
  }
128
158
  if (!checked.length)
129
- return [];
159
+ return uploaded;
130
160
  let client;
131
161
  try {
132
162
  client = storage();
@@ -134,7 +164,7 @@ async function copyArguments(caller, params, args, storage) {
134
164
  catch (error) {
135
165
  throw storageFailure(error);
136
166
  }
137
- const copies = [];
167
+ const copies = [...uploaded];
138
168
  for (const one of checked)
139
169
  copies.push(await copyOutbound(client, one));
140
170
  return copies;
@@ -165,7 +195,7 @@ async function createResultUpload(caller, field, storage) {
165
195
  // `size` records the declared maximum until the file result is fetched,
166
196
  // when it becomes the stored size.
167
197
  // A row with no use is deleted by the due-work tick after 24 h (D3-FILE-9).
168
- await insertUpload({ upload_id: created.upload_id, grantee: app, name: field, media_type: mediaType, size: UPLOAD_MAX_BYTES, created_at: new Date().toISOString() });
198
+ await insertUpload({ upload_id: created.upload_id, grantee: app, ...(isCloudRole() && caller.sub ? { sub: caller.sub } : {}), name: field, media_type: mediaType, size: UPLOAD_MAX_BYTES, created_at: new Date().toISOString() });
169
199
  return { field, upload_id: created.upload_id, upload_link: created.upload_link, grantee: app };
170
200
  }
171
201
  function uploadHeaders(upload) {
@@ -186,10 +216,6 @@ export async function prepareFileCall(caller, leaf, args, options = {}) {
186
216
  const storage = options.storage ?? storageClient;
187
217
  if (leaf.output) {
188
218
  checkOutputField(leaf.output);
189
- // A cloud role has no folder to land a file result in (a node's files live in its sandbox), so it refuses the call here, before the provider runs
190
- // and does anything it cannot take back, rather than after the upload.
191
- if (isCloudRole())
192
- throw new ProviderError('invalid_request', 'this command returns a file, which cannot be delivered to your computer from here yet, so it is not available from a moved Mac');
193
219
  }
194
220
  const copies = await copyArguments(caller, leaf.params, args, storage);
195
221
  const upload = leaf.output ? await createResultUpload(caller, leaf.output, storage) : null;
@@ -208,7 +234,7 @@ export async function resignForRetry(caller, leaf, args, prepared, options = {})
208
234
  const copies = [];
209
235
  for (const copy of prepared.copies) {
210
236
  try {
211
- const signed = await storage().signOutbound(copy.object_id);
237
+ const signed = copy.upload_id ? await storage().signDownload(copy.upload_id) : await storage().signOutbound(copy.object_id);
212
238
  copies.push({ ...copy, url: signed.url });
213
239
  }
214
240
  catch (error) {
@@ -287,6 +313,10 @@ export async function resolveFileResult(caller, prepared, result, options = {})
287
313
  fetched.body.destroy();
288
314
  throw providerError(`${upload.field} claims ${size} bytes; storage holds ${fetched.size}`);
289
315
  }
316
+ // A cloud role has no folder to land the file in (a node's files live in its sandbox): it checks the stored bytes and records the upload against
317
+ // the run, and the node's CLI downloads it by id into its own attachments folder.
318
+ if (isCloudRole())
319
+ return await keepCloudResult(caller, upload, body, claim, fetched, signal, deadline);
290
320
  const app = upload.grantee;
291
321
  const inNode = caller.node_id !== null;
292
322
  const space = await ensureAppSpace(app);
@@ -388,3 +418,44 @@ export async function resolveFileResult(caller, prepared, result, options = {})
388
418
  }
389
419
  return { result: { ...body, [upload.field]: path }, file: { path, upload_id: upload.upload_id }, cleanup };
390
420
  }
421
+ /** The cloud-role form of D3-FILE-8/9: stream the stored bytes through a hash (nothing touches this server's disk), then record the size and the
422
+ * run's use. The result keeps `{upload_id, size, sha256}` in the file field for the node's CLI to download. */
423
+ async function keepCloudResult(caller, upload, body, claim, fetched, signal, deadline) {
424
+ const size = claim.size;
425
+ const sha256 = claim.sha256.toLowerCase();
426
+ if (!caller.run_id) {
427
+ fetched.body.destroy();
428
+ throw new ProviderError('invalid_request', 'a file result needs a node to deliver it to');
429
+ }
430
+ const runId = caller.run_id;
431
+ const hash = createHash('sha256');
432
+ let bytes = 0;
433
+ try {
434
+ await pipeline(fetched.body, new Writable({ write(chunk, _encoding, next) { hash.update(chunk); bytes += chunk.length; next(); } }), { signal });
435
+ }
436
+ catch (error) {
437
+ fetched.body.destroy();
438
+ if (deadline.aborted)
439
+ throw new ProviderError('storage_unavailable', 'the file result could not be fetched within 110 s');
440
+ throw new ProviderError('storage_unavailable', `storage stopped sending ${upload.field}: ${error instanceof Error ? error.message : String(error)}`);
441
+ }
442
+ if (bytes !== size)
443
+ throw new ProviderError('storage_unavailable', `storage sent ${bytes} of ${size} bytes of ${upload.field}`);
444
+ if (hash.digest('hex') !== sha256)
445
+ throw providerError(`${upload.field}: the stored bytes do not match sha256`);
446
+ const use = { upload_id: upload.upload_id, run_id: runId, path: `upload:${upload.upload_id}` };
447
+ await withCanvasWrite(async (tx) => {
448
+ const row = await getUpload(upload.upload_id, tx);
449
+ if (!row || row.delete_pending_since)
450
+ throw new ProviderError('not_found', `${upload.field}: the upload was deleted while it was checked`);
451
+ const run = await tx.prepare('SELECT deleting_at FROM nodes WHERE node_id = ?').get(runId);
452
+ if (!run || run.deleting_at)
453
+ throw new ProviderError('not_found', `run ${runId} was deleted while its file result was checked`);
454
+ await setUploadSize(upload.upload_id, size, tx);
455
+ await insertUploadUses([use], tx);
456
+ });
457
+ return { result: { ...body, [upload.field]: { upload_id: upload.upload_id, size, sha256 } }, file: { path: '', upload_id: upload.upload_id }, cleanup: async () => { try {
458
+ await deleteUploadUse(use);
459
+ }
460
+ catch { /* best-effort */ } } };
461
+ }
@@ -0,0 +1,100 @@
1
+ // The node's CLI side of files crossing to the control plane by upload id (never by path). On a node whose crtr commands the shared control plane
2
+ // executes, the control plane cannot see this disk: the CLI uploads a file argument and sends its id, and downloads a file result by id into the node's
3
+ // attachments folder.
4
+ import { closeSync, constants, createReadStream, createWriteStream, fstatSync, mkdirSync, openSync } from 'node:fs';
5
+ import { basename, extname, join } from 'node:path';
6
+ import { Readable } from 'node:stream';
7
+ import { pipeline } from 'node:stream/promises';
8
+ import { createHash } from 'node:crypto';
9
+ import { cliClient } from '../../commands/api-client.js';
10
+ import { InputError } from '../io.js';
11
+ import { envNodeId, providerProjectionOverBrokerRelay } from '../../shared/env.js';
12
+ import { contentTypeFor } from './media-types.js';
13
+ import { appSpace } from '../layout.js';
14
+ import { envGrantee } from '../../shared/env.js';
15
+ const UPLOAD_MAX_BYTES = 100 * 1024 * 1024;
16
+ /** True when this CLI's commands run on the control plane, which cannot read this node's disk. */
17
+ export function filesCrossByUpload() {
18
+ return envNodeId() !== undefined && providerProjectionOverBrokerRelay();
19
+ }
20
+ function fail(error, message, next) {
21
+ throw new InputError({ error, message, next });
22
+ }
23
+ /** Upload one regular file the node can read; returns the upload id. */
24
+ export async function uploadNodeFile(path) {
25
+ const nodeId = envNodeId();
26
+ if (!nodeId)
27
+ fail('no_node', 'a file can be uploaded only from a node', 'Run this from a node.');
28
+ let fd;
29
+ try {
30
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
31
+ }
32
+ catch (err) {
33
+ return fail('not_found', `no such file: ${path} (${err.code ?? err.message})`, 'Pass the path of a regular file you can read.');
34
+ }
35
+ try {
36
+ const stat = fstatSync(fd);
37
+ if (!stat.isFile())
38
+ fail('not_found', `${path} is not a regular file`, 'Pass the path of a regular file.');
39
+ if (stat.size > UPLOAD_MAX_BYTES)
40
+ fail('invalid_request', `${path} exceeds 100 MiB`, 'Split or compress the file.');
41
+ const name = basename(path);
42
+ const mediaType = contentTypeFor(name);
43
+ const created = await cliClient().createNodeUpload(nodeId, { name, media_type: mediaType, size: stat.size });
44
+ const response = await fetch(created.upload_link, {
45
+ method: 'PUT', signal: AbortSignal.timeout(110_000),
46
+ headers: { 'Content-Type': mediaType, 'Content-Length': String(stat.size) },
47
+ body: (stat.size === 0 ? new Uint8Array(0) : Readable.toWeb(createReadStream('', { fd, autoClose: false, start: 0, end: stat.size - 1 }))), duplex: 'half',
48
+ });
49
+ await response.body?.cancel().catch(() => { });
50
+ if (!response.ok)
51
+ fail('upload_failed', `storage answered ${response.status} to the upload of ${path}`, 'Run the command again.');
52
+ return created.upload_id;
53
+ }
54
+ finally {
55
+ closeSync(fd);
56
+ }
57
+ }
58
+ function candidate(name, n) {
59
+ if (n === 1)
60
+ return name;
61
+ const ext = extname(name);
62
+ return ext && ext !== name ? `${name.slice(0, -ext.length)}-${n}${ext}` : `${name}-${n}`;
63
+ }
64
+ /** Download an upload the control plane holds for this node into its attachments folder, named after `field`; returns the local path. */
65
+ export async function downloadNodeUpload(uploadId, field, size, sha256) {
66
+ const nodeId = envNodeId();
67
+ if (!nodeId)
68
+ fail('no_node', 'a file result can be saved only on a node', 'Run this from a node.');
69
+ const link = await cliClient().nodeUploadLink(nodeId, uploadId);
70
+ const response = await fetch(link.url, { signal: AbortSignal.timeout(110_000) });
71
+ if (!response.ok || !response.body)
72
+ fail('download_failed', `storage answered ${response.status} to the download of ${field}`, 'Run the command again.');
73
+ const dir = join(appSpace(envGrantee() ?? fail('no_node', 'this node has no app assignment', 'Run this from a node.')).nodes, nodeId, 'attachments');
74
+ mkdirSync(dir, { recursive: true });
75
+ for (let n = 1;; n++) {
76
+ const path = join(dir, candidate(field, n));
77
+ let fd;
78
+ try {
79
+ fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o660);
80
+ }
81
+ catch (err) {
82
+ if (err.code === 'EEXIST')
83
+ continue;
84
+ throw err;
85
+ }
86
+ const hash = createHash('sha256');
87
+ let bytes = 0;
88
+ try {
89
+ const source = Readable.fromWeb(response.body);
90
+ source.on('data', (chunk) => { hash.update(chunk); bytes += chunk.length; });
91
+ await pipeline(source, createWriteStream('', { fd, autoClose: true }));
92
+ }
93
+ catch (err) {
94
+ fail('download_failed', `could not save ${field}: ${err instanceof Error ? err.message : String(err)}`, 'Run the command again.');
95
+ }
96
+ if (bytes !== size || hash.digest('hex') !== sha256.toLowerCase())
97
+ fail('download_failed', `the downloaded ${field} does not match the size and sha256 the server verified`, 'Run the command again.');
98
+ return path;
99
+ }
100
+ }
@@ -91,6 +91,8 @@ export const OPERATIONS = [
91
91
  { name: 'bash-jobs.patch', method: 'PATCH', path: '/v1/nodes/:id/jobs/:jobId', classes: ['person', 'broker'], resource: 'node-write' },
92
92
  { name: 'files.create', method: 'POST', path: '/v1/nodes/:id/files', classes: ['broker'], resource: 'node-own', scope: 'crtr:act' },
93
93
  { name: 'files.complete', method: 'POST', path: '/v1/nodes/:id/files/:fileId/complete', classes: ['broker'], resource: 'node-own', scope: 'crtr:act' },
94
+ { name: 'node-uploads.create', method: 'POST', path: '/v1/nodes/:id/uploads', classes: ['broker'], resource: 'node-own', scope: 'crtr:act' },
95
+ { name: 'node-uploads.link', method: 'POST', path: '/v1/nodes/:id/uploads/:uploadId/link', classes: ['broker'], resource: 'node-own', scope: 'crtr:act' },
94
96
  { name: 'bash-jobs.start', method: 'POST', path: '/v1/nodes/:id/jobs/start', classes: ['broker'], resource: 'node-own', scope: 'crtr:act' },
95
97
  { name: 'hooks.plan', method: 'GET', path: '/v1/nodes/:id/hooks/plan', classes: ['broker'], resource: 'node-own' },
96
98
  { name: 'hooks.exec', method: 'POST', path: '/v1/nodes/:id/hooks/exec', classes: ['broker'], resource: 'node-own' },
@@ -217,6 +219,7 @@ export const OPERATIONS = [
217
219
  { name: 'canvas.post.128', method: 'POST', path: '/v1/canvas/history/stats', classes: ['person', 'broker', 'forwarded'], resource: 'canvas-read' },
218
220
  { name: 'canvas.get.129', method: 'GET', path: '/v1/canvas/snapshot', classes: ['person', 'broker', 'forwarded'], resource: 'canvas-read' },
219
221
  { name: 'canvas.get.130', method: 'GET', path: '/v1/canvas/roster', classes: ['person', 'broker'], resource: 'canvas-read' },
222
+ { name: 'canvas.get.view', method: 'GET', path: '/v1/canvas/view/:id', classes: ['person', 'broker'], resource: 'canvas-read' },
220
223
  { name: 'canvas.get.live-roots', method: 'GET', path: '/v1/canvas/live-roots', classes: ['person'], resource: 'canvas-read' },
221
224
  { name: 'canvas.get.browse', method: 'GET', path: '/v1/canvas/browse', classes: ['person', 'broker'], resource: 'canvas-read' },
222
225
  { name: 'canvas.get.analytics', method: 'GET', path: '/v1/canvas/analytics', classes: ['person', 'broker'], resource: 'canvas-read' },
@@ -139,6 +139,17 @@ export async function readableNodeIds(principal) {
139
139
  const rows = await db.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${may.sql}`).all(...may.params);
140
140
  return new Set(rows.map((r) => r.id));
141
141
  }
142
+ /** Which of `ids` the caller may read: the condition `readableNodeIds()` builds, applied to only those ids. */
143
+ export async function readableAmong(principal, ids) {
144
+ if (actsAsPerson(principal))
145
+ return new Set(ids);
146
+ if (principal.class === 'anonymous' || principal.class === 'machine' || principal.class === 'import' || ids.length === 0)
147
+ return new Set();
148
+ const db = await openDb();
149
+ const may = await permits(db, await readerFor(db, { principal }), 'read');
150
+ const rows = await db.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND o.id = ANY(?::text[]) AND ${may.sql}`).all([...ids], ...may.params);
151
+ return new Set(rows.map((r) => r.id));
152
+ }
142
153
  /** The inbox tickets in `ticketIds` whose requester node the caller may read, decided in one query per chunk with the evaluator's condition.
143
154
  * Same answer per ticket as `getRequestByInboxTicket` → `getNode` → `mayOnNode(read)`: a ticket with no requester node, or whose node row or object is missing, is not readable. */
144
155
  export async function readableTicketIds(principal, ticketIds) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.690",
3
+ "version": "0.3.692",
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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.690",
3
+ "version": "0.3.692",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.690",
3
+ "version": "0.3.692",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.690",
31
- "@north-light/identity": "0.3.690"
30
+ "@north-light/api": "0.3.692",
31
+ "@north-light/identity": "0.3.692"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.690",
3
+ "version": "0.3.692",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.690",
9
+ "version": "0.3.692",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.690",
32
- "@north-light/plugin": "0.3.690",
31
+ "@north-light/identity": "0.3.692",
32
+ "@north-light/plugin": "0.3.692",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.690",
10670
+ "version": "0.3.692",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.690",
10675
+ "version": "0.3.692",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.690",
10680
+ "version": "0.3.692",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.690",
10688
+ "version": "0.3.692",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.690",
10692
- "@north-light/identity": "0.3.690"
10691
+ "@north-light/api": "0.3.692",
10692
+ "@north-light/identity": "0.3.692"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.690",
10697
+ "version": "0.3.692",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.690",
10701
- "@north-light/identity": "0.3.690",
10702
- "@north-light/plugin": "0.3.690",
10700
+ "@north-light/api": "0.3.692",
10701
+ "@north-light/identity": "0.3.692",
10702
+ "@north-light/plugin": "0.3.692",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {