@north-light/cli 0.3.759 → 0.3.761

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 (81) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/error-codes.d.ts +5 -0
  4. package/dist/api/error-codes.js +1 -1
  5. package/dist/builtin-memory/crouter-sdk/release-notes.md +4 -0
  6. package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
  7. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  8. package/dist/cli.js +5 -5
  9. package/dist/clients/attach/config.js +1 -1
  10. package/dist/clients/attach/viewer.js +467 -467
  11. package/dist/commands/api-client.d.ts +0 -5
  12. package/dist/commands/api-client.js +3 -3
  13. package/dist/commands/daemon-generation.js +1 -1
  14. package/dist/commands/sys/import/move.d.ts +1 -34
  15. package/dist/commands/sys/import/move.js +5 -9
  16. package/dist/commands/sys/import/start.d.ts +0 -3
  17. package/dist/commands/sys/import/start.js +1 -1
  18. package/dist/commands/sys/signin.js +2 -2
  19. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -0
  20. package/dist/core/canvas/managed-worktree-sweep-candidates.js +6 -4
  21. package/dist/core/command-plugins/caller-header.d.ts +3 -1
  22. package/dist/core/command-plugins/caller-header.js +1 -1
  23. package/dist/core/command.d.ts +1 -1
  24. package/dist/core/grants/owner.d.ts +2 -0
  25. package/dist/core/grants/owner.js +1 -1
  26. package/dist/core/graph/reader.d.ts +5 -0
  27. package/dist/core/graph/reader.js +3 -3
  28. package/dist/core/graph/types.d.ts +2 -0
  29. package/dist/core/permissions/evaluator.js +2 -2
  30. package/dist/core/providers/call.js +1 -1
  31. package/dist/core/providers/errors.js +1 -1
  32. package/dist/core/providers/mint.d.ts +19 -0
  33. package/dist/core/providers/mint.js +1 -1
  34. package/dist/core/runtime/front-door.js +9 -10
  35. package/dist/core/user-settings.d.ts +2 -2
  36. package/dist/core/worktree-mutation-async.js +5 -5
  37. package/dist/core/worktree-scripts.d.ts +13 -0
  38. package/dist/core/worktree-scripts.js +5 -0
  39. package/dist/core/worktree-sweep.js +4 -4
  40. package/dist/daemon/api/handlers/daemon.js +1 -1
  41. package/dist/daemon/api/handlers/memory.js +5 -5
  42. package/dist/daemon/api/handlers/plugin-app-token.js +1 -1
  43. package/dist/daemon/api/reader.d.ts +1 -1
  44. package/dist/daemon/api/reader.js +1 -1
  45. package/dist/daemon/crtrd.js +11 -11
  46. package/dist/daemon/import-dump-run.js +4 -4
  47. package/dist/daemon/machine-daemon.js +1 -1
  48. package/dist/daemon/machine-link/config.d.ts +0 -24
  49. package/dist/daemon/machine-link/config.js +4 -4
  50. package/dist/daemon/manage.d.ts +1 -1
  51. package/docs/sdk/release-notes.md +4 -0
  52. package/package.json +3 -3
  53. package/packages/crouter-api/dist/api/contract.js +1 -1
  54. package/packages/crouter-api/dist/api/error-codes.js +2 -0
  55. package/packages/crouter-api/dist/clients/attach/config.js +2 -1
  56. package/packages/crouter-api/dist/commands/api-client.js +1 -12
  57. package/packages/crouter-api/dist/commands/sys/import/move.js +5 -205
  58. package/packages/crouter-api/dist/commands/sys/import/start.js +15 -51
  59. package/packages/crouter-api/dist/commands/sys/signin.js +13 -54
  60. package/packages/crouter-api/dist/core/command-plugins/caller-header.js +2 -2
  61. package/packages/crouter-api/dist/core/grants/owner.js +6 -0
  62. package/packages/crouter-api/dist/core/graph/reader.js +15 -1
  63. package/packages/crouter-api/dist/core/permissions/evaluator.js +2 -0
  64. package/packages/crouter-api/dist/core/providers/call.js +11 -5
  65. package/packages/crouter-api/dist/core/providers/errors.js +1 -0
  66. package/packages/crouter-api/dist/core/providers/mint.js +58 -29
  67. package/packages/crouter-api/dist/core/worktree-mutation-async.js +11 -3
  68. package/packages/crouter-api/dist/core/worktree-scripts.js +72 -0
  69. package/packages/crouter-api/dist/core/worktree-sweep.js +10 -1
  70. package/packages/crouter-api/dist/daemon/api/reader.js +10 -2
  71. package/packages/crouter-api/dist/daemon/machine-link/config.js +1 -27
  72. package/packages/crouter-api/package.json +1 -1
  73. package/packages/crouter-identity/package.json +1 -1
  74. package/packages/crouter-plugin/package.json +3 -3
  75. package/runtime.lock.json +14 -14
  76. package/dist/commands/sys/import/retry.d.ts +0 -1
  77. package/dist/commands/sys/import/retry.js +0 -1
  78. package/dist/daemon/machine-link/move-notify.d.ts +0 -4
  79. package/dist/daemon/machine-link/move-notify.js +0 -1
  80. package/packages/crouter-api/dist/commands/sys/import/retry.js +0 -38
  81. package/packages/crouter-api/dist/daemon/machine-link/move-notify.js +0 -15
@@ -1,26 +1,21 @@
1
- // The exporter's run (design-import "Exporter") and the move of a person's computer into their Northlight account (design-crtr-northlight-signin
2
- // component 4): `exportRun` uploads, drains, dumps and loads one run; `runMove` wraps it for a computer with the move record, the two commit
3
- // boundaries (the cloud run reaching `done`; activation) and the messages to the node that asked; `finishMove` is activation, shared with
4
- // `crtr sys signin` finishing an unfinished switch-over.
1
+ // The hosted exporter's run (design-import "Exporter"): `exportRun` uploads, drains, dumps and loads one run. `registerThisMac` is `crtr sys signin`'s directory registration.
5
2
  import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
6
3
  import { tmpdir } from 'node:os';
7
4
  import { join } from 'node:path';
8
5
  import { CrtrError, general } from '../../../core/errors.js';
9
6
  import { ExitCode } from '../../../types.js';
10
7
  import { cliClient } from '../../api-client.js';
11
- import { ImportCloud, STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
8
+ import { STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
12
9
  import { Uploader, localObjects, reviewSourceObject } from '../../../core/import/export/files.js';
13
10
  import { BODIES_TABLE, bundleKeys } from '../../../core/import/bundle/layout.js';
14
11
  import { crtrVersion } from '../../../shared/crtr-version.js';
15
12
  import { nodeArchive } from '../../../core/import/export/archive.js';
16
13
  import { buildSourceJson } from '../../../core/import/export/source.js';
17
- import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId, spawnDaemon, stopAllDaemons } from '../../../daemon/manage.js';
18
- import { deleteMoveRecord, moveUnfinishedError, readMachineConfig, readMoveRecord, writeMachineConfig, writeMachineCredential, writeMoveRecord } from '../../../daemon/machine-link/config.js';
19
- import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
14
+ import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId } from '../../../daemon/manage.js';
15
+ import { readMachineConfig } from '../../../daemon/machine-link/config.js';
20
16
  import { registerSignedInMac } from '../../../core/directory/join.js';
21
- import { controlPlaneUrl, forgetSignIn, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../../core/directory/person-credential.js';
17
+ import { personBearer, readPersonCredential } from '../../../core/directory/person-credential.js';
22
18
  import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
23
- import { isPidAlive } from '../../../core/canvas/pid.js';
24
19
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
20
  /** The directory a sign-in or move uses when none is typed: `runtime/machine.json`'s, else the stored sign-in's, else Northlight's (design D5). */
26
21
  export function defaultDirectoryUrl() {
@@ -198,29 +193,6 @@ export async function exportRun(kind, cloud, existingRun, step, onStarted = () =
198
193
  }
199
194
  }
200
195
  }
201
- /** Activation, the second commit boundary: the asking node's message first (stored in the account as mail; the node can wake only once the machine
202
- * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
203
- * crtrd in machine role, and the move record's deletion. Safe to repeat. */
204
- export async function finishMove(move) {
205
- await notifyMoveFinished(move);
206
- const cloud = new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl));
207
- let credential;
208
- try {
209
- credential = await cloud.machineCredential(move.runId);
210
- }
211
- catch (error) {
212
- if (!(error instanceof CrtrError) || error.details?.['code'] !== 'credential_exists')
213
- throw error;
214
- credential = await cloud.machineCredential(move.runId, true);
215
- }
216
- writeMachineCredential(credential.credential);
217
- writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
218
- await registerThisMac(move.directoryUrl);
219
- await stopAllDaemons();
220
- await spawnDaemon();
221
- // Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
222
- deleteMoveRecord();
223
- }
224
196
  /** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
225
197
  export async function registerThisMac(directoryUrl) {
226
198
  try {
@@ -231,175 +203,3 @@ export async function registerThisMac(directoryUrl) {
231
203
  process.stderr.write(`this computer was not registered with the directory: ${error instanceof Error ? error.message : String(error)}\nRun \`crtr sys signin\` again to register it.\n`);
232
204
  }
233
205
  }
234
- const ACTIVATION_ATTEMPTS = 3;
235
- const ACTIVATION_GAP_MS = 30_000;
236
- /** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
237
- * sign-in is revoked and deleted, the move record goes, and `notify` (a node) is told through the local daemon. After `done` the move record says
238
- * `committed` and activation is retried three times over a minute; still failing, the record, the sign-in and the drain stay for `crtr sys signin`. */
239
- export async function runMove(opts) {
240
- const step = { name: 'sign-in', timings: [] };
241
- let move;
242
- let runId = '';
243
- let base;
244
- try {
245
- const account = await personAccount(opts.directoryUrl);
246
- const apiUrl = opts.apiUrl ?? await controlPlaneUrl(opts.directoryUrl);
247
- const cloud = new ImportCloud(apiUrl, () => personBearer(opts.directoryUrl));
248
- base = { apiUrl, directoryUrl: opts.directoryUrl, account, notify: opts.notify, notified: false, pid: process.pid };
249
- await exportRun('machine', cloud, undefined, step, (id) => { runId = id; writeMoveRecord({ ...base, runId: id, state: 'running' }); }, deleteMoveRecord);
250
- }
251
- catch (error) {
252
- // Once `load` was sent and its outcome is unknown, the record and the drain stay: the next starter (`crtr sys signin`, the local daemon's start)
253
- // asks the control plane and settles the move.
254
- if (error instanceof CrtrError && error.code === 'move_outcome_unknown')
255
- throw error;
256
- throw await undoMove(step.name, error, opts.notify);
257
- }
258
- // The run is `done`: from here nothing may undo the move, so a failed record write is reported as it is and the `running` record settles to `committed` later.
259
- move = { ...base, runId, state: 'committed' };
260
- writeMoveRecord(move);
261
- let last;
262
- const activating = Date.now();
263
- for (let attempt = 1; attempt <= ACTIVATION_ATTEMPTS; attempt++) {
264
- try {
265
- await finishMove(move);
266
- step.timings.push(`restart=${((Date.now() - activating) / 1000).toFixed(1)}s`);
267
- process.stderr.write(`restart ${((Date.now() - activating) / 1000).toFixed(1)}s\n`);
268
- return { runId: move.runId, account: move.account.display, timings: step.timings.join(' ') };
269
- }
270
- catch (error) {
271
- last = error;
272
- process.stderr.write(`switch-over attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}\n`);
273
- if (attempt < ACTIVATION_ATTEMPTS)
274
- await sleep(ACTIVATION_GAP_MS);
275
- move = readMoveRecord() ?? move;
276
- }
277
- }
278
- throw moveUnfinishedError(last instanceof Error ? last.message : String(last));
279
- }
280
- /** Undo a move that never reached `done` (the drain is already confirmed ended), tell the asking node, and return the error to throw. */
281
- async function undoMove(step, error, notify) {
282
- const reason = error instanceof Error ? error.message : String(error);
283
- const still = error instanceof CrtrError && error.code === 'drain_not_ended' ? 'crtr is still local, but its pause could not be ended: run `crtr sys import resume`' : 'crtr is still local and working as before';
284
- const failed = `The move to Northlight failed at ${step}: ${reason}. ${still}.`;
285
- const revokeFailure = await dropMove(failed, notify);
286
- const code = error instanceof CrtrError && error.code !== 'error' ? error.code : (error instanceof CrtrError && typeof error.details?.['code'] === 'string' ? error.details['code'] : 'move_failed');
287
- return new CrtrError(code, `the move to Northlight failed at ${step}: ${reason}. ${still}, and ${signedOutText(revokeFailure)}`, ExitCode.GENERAL);
288
- }
289
- /** What the person is told about the sign-in a failed move removes: revoked at Northlight, or removed here only. */
290
- const signedOutText = (revokeFailure) => revokeFailure === undefined ? 'this computer is signed out.' : `this computer's sign-in was removed here but could not be revoked at Northlight (${revokeFailure}); revoke it on your Northlight account page.`;
291
- /** The shared end of a failed move: delete the record, sign this computer out, and tell the node that asked (a failed revoke is added to its
292
- * message). Returns why the sign-in could not be revoked at Northlight, or undefined when it was revoked or already ended: the secret is deleted here either way,
293
- * so a failed revoke leaves one that is still valid there. */
294
- async function dropMove(message, notify) {
295
- deleteMoveRecord();
296
- let revokeFailure;
297
- try {
298
- await signOut();
299
- }
300
- catch (error) {
301
- forgetSignIn();
302
- revokeFailure = error instanceof Error ? error.message : String(error);
303
- process.stderr.write(`could not revoke the sign-in at Northlight: ${revokeFailure}\n`);
304
- }
305
- if (notify === null)
306
- return revokeFailure;
307
- try {
308
- await cliClient({ local: true }).sendMessage(notify, { from: null, body: `${message} Tell the person the move failed.${revokeFailure === undefined ? '' : ` ${signedOutText(revokeFailure)}`}` });
309
- }
310
- catch (sendError) {
311
- process.stderr.write(`could not message ${notify}: ${sendError instanceof Error ? sendError.message : String(sendError)}\n`);
312
- }
313
- return revokeFailure;
314
- }
315
- /** Where an earlier move stands before a new sign-in or move starts, and when the local daemon starts. A `running` record whose exporter is alive
316
- * refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
317
- * `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
318
- * loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
319
- * the control plane unreachable or refusing, no working sign-in — leaves the record and the drain as they are and throws. With no working sign-in
320
- * `show` signs back in first, and only to the account that owns the move (another account is refused, nothing written); without `show` (the daemon) it throws `not_signed_in`.
321
- * Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
322
- export async function settleEarlierMove(show) {
323
- const move = readMoveRecord();
324
- if (move === undefined || move.state === 'activated')
325
- return undefined;
326
- const signBackIn = async () => {
327
- await signIn(move.directoryUrl, show, { accept: async (approved) => approved.account.id === move.account.id ? undefined
328
- : new CrtrError('signin_other_account', `This computer's move belongs to the Northlight account ${move.account.display}. Sign in to that account.`, ExitCode.USAGE) });
329
- };
330
- if (move.state === 'committed') {
331
- if (show !== undefined) {
332
- try {
333
- await personAccount(move.directoryUrl);
334
- }
335
- catch (error) {
336
- if (!(error instanceof CrtrError && error.code === 'not_signed_in'))
337
- throw error;
338
- await signBackIn();
339
- }
340
- }
341
- return move;
342
- }
343
- if (move.pid > 0 && isPidAlive(move.pid)) {
344
- throw new CrtrError('move_running', `a move to Northlight is already running (process ${move.pid}).`, ExitCode.USAGE, { next: 'Wait for it to finish; the node that asked is messaged when it does.' });
345
- }
346
- const ask = () => new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl)).get(move.runId);
347
- let run;
348
- try {
349
- run = await ask();
350
- }
351
- catch (error) {
352
- if (!(error instanceof CrtrError && error.code === 'not_signed_in') || show === undefined)
353
- throw error;
354
- await signBackIn();
355
- run = await ask();
356
- }
357
- if (run.state === 'done') {
358
- const committed = { ...move, state: 'committed' };
359
- writeMoveRecord(committed);
360
- return committed;
361
- }
362
- if (run.state === 'loading' || run.state === 'committed') {
363
- throw new CrtrError('move_running', 'Northlight is still loading this computer\'s records from an earlier move.', ExitCode.USAGE, { next: 'Retry in a minute.' });
364
- }
365
- if (run.state !== 'failed' && run.state !== 'rolled_back' && run.state !== 'uploading') {
366
- throw new CrtrError('move_outcome_unknown', 'Northlight did not report a settled outcome for this move.', ExitCode.GENERAL, { next: 'Run `crtr sys signin` to settle the move.' });
367
- }
368
- const step = run.failure?.step ?? 'an earlier step';
369
- const reason = run.failure == null ? 'the process that was moving this computer stopped before Northlight had the records' : run.failure.message;
370
- deleteMoveRecord();
371
- try {
372
- await endDrainConfirmed(cliClient({ local: true }));
373
- }
374
- catch (error) {
375
- throw await undoMove(step, new CrtrError('drain_not_ended', `${reason} (and ${error instanceof Error ? error.message : String(error)})`, ExitCode.GENERAL), move.notify);
376
- }
377
- await dropMove(`The move to Northlight failed at ${step}: ${reason}. crtr is still local and working as before.`, move.notify);
378
- return undefined;
379
- }
380
- const DAEMON_SETTLE_GAP_MS = 60_000;
381
- /** The daemon answers its own socket only once startup is done, which is a moment after the settle is scheduled. */
382
- const DAEMON_SETTLE_FIRST_MS = 5_000;
383
- /** The local daemon's start is a starter of the move record (design-crtr-northlight-signin component 4): a `running` record whose exporter died (a crash,
384
- * a reboot) leaves the daemon drained and the asking node untold until someone runs `crtr sys signin`, so the daemon settles it itself once it serves.
385
- * Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
386
- * for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
387
- export async function settleMoveAtDaemonStart(stopped, onRetry) {
388
- await sleep(DAEMON_SETTLE_FIRST_MS);
389
- while (!stopped()) {
390
- const move = readMoveRecord();
391
- if (move === undefined || move.state !== 'running' || (move.pid > 0 && isPidAlive(move.pid)))
392
- return;
393
- try {
394
- await settleEarlierMove();
395
- return;
396
- }
397
- catch (error) {
398
- onRetry(error);
399
- // No working sign-in: only the person signing back in (`crtr sys signin`) can settle it, so asking again every minute cannot help.
400
- if (error instanceof CrtrError && error.code === 'not_signed_in')
401
- return;
402
- }
403
- await sleep(DAEMON_SETTLE_GAP_MS);
404
- }
405
- }
@@ -1,36 +1,25 @@
1
1
  // `crtr sys import start`: the source side of an import (design-import, "Exporter"). Uploads blobs, drains the daemon, dumps the rows and file
2
- // stores, uploads them, asks the control plane to load, and on a computer switches this install to the machine role (`./move.ts`).
2
+ // stores, uploads them, asks the control plane to load, and (`./move.ts`).
3
3
  import { defineBranch, defineLeaf } from '../../../core/command.js';
4
4
  import { general, usage } from '../../../core/errors.js';
5
5
  import { ImportCloud } from '../../../core/import/export/cloud.js';
6
6
  import { ensureSignedIn } from '../../../core/directory/person-credential.js';
7
- import { isPidAlive } from '../../../core/canvas/pid.js';
8
7
  import { showSignIn } from '../signin.js';
9
8
  import { insideBroker } from '../join.js';
10
- import { defaultDirectoryUrl, exportRun, settleEarlierMove, finishMove, runMove } from './move.js';
9
+ import { defaultDirectoryUrl, exportRun } from './move.js';
11
10
  import { resume } from './resume.js';
12
- import { retry } from './retry.js';
13
- /** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
14
- * so it is never in a broker's process tree. */
15
- export const WAIT_FOR_PID_ENV = 'CRTR_IMPORT_WAIT_PID';
16
- async function waitForExit(pid) {
17
- while (isPidAlive(pid))
18
- await new Promise((resolve) => setTimeout(resolve, 200));
19
- }
20
11
  const start = defineLeaf({
21
12
  name: 'start',
22
- description: 'export this runtime into the person\'s Northlight account',
23
- whenToUse: 'moving this computer or hosted runtime\'s canvas into Northlight: run it from a plain terminal, not from inside a node',
13
+ description: 'export this hosted runtime into the person\'s Northlight account',
14
+ whenToUse: 'hosting runs it inside a hosted runtime to move that runtime\'s canvas into Northlight: from a plain terminal, not from inside a node',
24
15
  help: {
25
16
  name: 'sys import start',
26
17
  summary: 'upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them',
27
- guide: 'Order: open the run, upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before; a computer\'s move also signs it out. On `done` the daemon stays drained: a hosted runtime until hosting quiesces it (`crtr sys import resume` ends it), a computer until it has switched over — machine credential, `runtime/machine.json`, daemon restarted in machine role — which is retried three times over a minute and otherwise finished by `crtr sys signin`. A machine import signs the person in first when this computer has no stored sign-in. `crtr sys signin` normally starts a computer\'s move itself. With `--run`, hosting has already opened the run: the exporter uses it and reads that run\'s import token from the environment variable `CRTR_IMPORT_TOKEN`.',
18
+ guide: 'Order: open the run (hosting already did, with `--run`), upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, archive running nodes\' files, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before. On `done` the daemon stays drained until hosting quiesces it (`crtr sys import resume` ends it). The run\'s import token is read from the environment variable `CRTR_IMPORT_TOKEN`.',
28
19
  params: [
29
- { kind: 'flag', name: 'kind', type: 'enum', choices: ['machine', 'hosted'], required: true, constraint: '`machine` for a person\'s computer, `hosted` for a hosted runtime (also archives running nodes\' files).' },
30
- { kind: 'flag', name: 'api-url', type: 'string', required: false, constraint: 'Control plane base URL (http or https). Required with `--kind hosted`; with `--kind machine` the default is the control plane the person\'s sign-in is for.' },
31
- { kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime (only with `--kind hosted`); its import token is read from `CRTR_IMPORT_TOKEN`.' },
32
- { kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https) the person signs in against, with `--kind machine`. Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
33
- { kind: 'flag', name: 'notify', type: 'string', required: false, constraint: 'With `--kind machine`: a node id told by message when the move fails or finishes.' },
20
+ { kind: 'flag', name: 'kind', type: 'enum', choices: ['hosted'], required: true, constraint: '`hosted`, the only kind: a hosted runtime (also archives running nodes\' files).' },
21
+ { kind: 'flag', name: 'api-url', type: 'string', required: true, constraint: 'Control plane base URL (http or https) hosting opened the run on.' },
22
+ { kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime; its import token is read from `CRTR_IMPORT_TOKEN`.' },
34
23
  ],
35
24
  output: [
36
25
  { name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
@@ -40,41 +29,16 @@ const start = defineLeaf({
40
29
  outputKind: 'object',
41
30
  effects: [
42
31
  'Drains the local daemon (no new wake or cron fire); the drain is a `runtime_state` row, so it survives a daemon restart. Ended on a failure before `done`; kept after `done`.',
43
- 'Machine: writes `runtime/import/move.json` (0600) from the run\'s start until the switch-over, then deletes it. On `done`: writes `runtime/machine.json` and `runtime/secrets/machine-credential` (0600) and restarts the daemon in machine role. On a failure before `done`: revokes and deletes the stored sign-in.',
44
- 'Machine with `--notify`: sends that node one message when the move fails or finishes.',
45
32
  'Opens a temporary directory holding the opened file stores (0600), removed before the command ends.',
46
33
  ],
47
34
  },
48
35
  run: async (input) => {
49
- const kind = input['kind'];
50
36
  const existingRun = input['run'] === undefined ? undefined : String(input['run']);
51
- const apiUrl = input.apiUrl === undefined ? undefined : String(input.apiUrl);
52
- const notify = input['notify'] === undefined ? null : String(input['notify']);
53
- if (kind === 'hosted') {
54
- if (apiUrl === undefined)
55
- throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
56
- if (notify !== null)
57
- throw usage('--notify names the node that asked for a computer\'s move: use it only with --kind machine');
58
- }
59
- else if (existingRun !== undefined) {
60
- throw usage('--run takes an existing run, which only a hosted import has: use --kind hosted');
61
- }
62
- const waitFor = Number(process.env[WAIT_FOR_PID_ENV] ?? '');
63
- if (Number.isInteger(waitFor) && waitFor > 0)
64
- await waitForExit(waitFor);
37
+ const apiUrl = String(input.apiUrl ?? '');
38
+ if (apiUrl === '')
39
+ throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
65
40
  if (insideBroker())
66
41
  throw general('import_inside_node: run this from a plain terminal; a node\'s broker ends with the daemon restart', { code: 'import_inside_node' });
67
- if (kind === 'machine') {
68
- const earlier = await settleEarlierMove(showSignIn);
69
- if (earlier !== undefined) {
70
- await finishMove(earlier);
71
- return { run_id: earlier.runId, state: 'done', timings: '' };
72
- }
73
- const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
74
- await ensureSignedIn(directoryUrl, showSignIn);
75
- const moved = await runMove({ directoryUrl, ...(apiUrl === undefined ? {} : { apiUrl }), notify });
76
- return { run_id: moved.runId, state: 'done', timings: moved.timings };
77
- }
78
42
  const token = (existingRun === undefined ? await ensureSignedIn(defaultDirectoryUrl(), showSignIn) : process.env['CRTR_IMPORT_TOKEN'] ?? '').trim();
79
43
  if (token === '')
80
44
  throw usage('set CRTR_IMPORT_TOKEN to the run\'s import token');
@@ -86,8 +50,8 @@ const start = defineLeaf({
86
50
  });
87
51
  export const sysImportBranch = defineBranch({
88
52
  name: 'import',
89
- description: 'move this runtime into the person\'s Northlight account',
90
- whenToUse: 'importing this computer or hosted runtime into Northlight',
91
- help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database, and on a computer switches it to the machine role.' },
92
- children: [start, resume, retry],
53
+ description: 'move this hosted runtime into the person\'s Northlight account',
54
+ whenToUse: 'importing a hosted runtime into Northlight',
55
+ help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database.' },
56
+ children: [start, resume],
93
57
  });
@@ -1,19 +1,14 @@
1
1
  // `crtr sys signin` / `crtr sys signout`: the person's own sign-in on this computer (proposal-mac-cli-auth, option A).
2
2
  import { spawn } from 'node:child_process';
3
- import { mkdirSync, openSync } from 'node:fs';
4
- import { dirname, join } from 'node:path';
5
3
  import { defineLeaf } from '../../core/command.js';
6
4
  import { CrtrError } from '../../core/errors.js';
7
5
  import { controlPlaneUrl, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../core/directory/person-credential.js';
8
- import { hasLocalCanvas, moveRecordPath, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
9
- import { probeDaemonHealth, sanitizedDaemonEnv, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
6
+ import { hasLocalCanvas, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
7
+ import { probeDaemonHealth, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
10
8
  import { hostname } from 'node:os';
11
9
  import { northlightUnreachable } from '../../core/directory/reach.js';
12
- import { envNodeId } from '../../shared/env.js';
13
10
  import { ExitCode } from '../../types.js';
14
- import { insideBroker } from './join.js';
15
- import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
16
- import { WAIT_FOR_PID_ENV } from './import/start.js';
11
+ import { defaultDirectoryUrl, registerThisMac } from './import/move.js';
17
12
  /** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
18
13
  function openBrowser(url) {
19
14
  const [command, args] = process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
@@ -50,19 +45,6 @@ function sameAccountOnly(machine) {
50
45
  return new CrtrError('signin_unchecked', `the control plane did not say which account owns this computer (HTTP ${response.status}); nothing was written.`, ExitCode.GENERAL, { next: 'Retry `crtr sys signin`.' });
51
46
  };
52
47
  }
53
- /** Start the move in a process of its own: a node's tool call cannot run it, because the drain waits for that very turn to end and the restart
54
- * ends the broker it runs under. The exporter waits for this process to exit, so it is outside every broker's process tree when it drains. */
55
- function startDetachedMove(notify) {
56
- const log = join(dirname(moveRecordPath()), 'move.log');
57
- mkdirSync(dirname(log), { recursive: true });
58
- const fd = openSync(log, 'a', 0o600);
59
- const env = sanitizedDaemonEnv();
60
- for (const key of ['CRTR_API_SOCKET', 'CRTR_API_TOKEN', 'CRTR_API_URL'])
61
- delete env[key];
62
- env[WAIT_FOR_PID_ENV] = String(process.pid);
63
- const args = [...process.execArgv, process.argv[1], 'sys', 'import', 'start', '--kind', 'machine', ...(notify === undefined ? [] : ['--notify', notify])];
64
- spawn(process.execPath, args, { detached: true, stdio: ['ignore', fd, fd], env }).unref();
65
- }
66
48
  /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
67
49
  * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
68
50
  export async function registerFreshComputer(directoryUrl) {
@@ -94,47 +76,32 @@ export async function registerFreshComputer(directoryUrl) {
94
76
  await spawnDaemon();
95
77
  return { account: account.display };
96
78
  }
97
- const MOVING = (account) => `Signed in as ${account}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`;
98
79
  export const sysSigninLeaf = defineLeaf({
99
80
  name: 'signin',
100
81
  description: 'sign this computer\'s crtr in to the person\'s Northlight account and register it as one of their machines',
101
- whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`',
82
+ whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in`',
102
83
  help: {
103
84
  name: 'sys signin',
104
- summary: 'pair this computer with the person\'s Northlight account in the browser, move this computer\'s records into it, and register it with the directory',
105
- guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account\'s move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account\'s machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
85
+ summary: 'pair this computer with the person\'s Northlight account in the browser, register it as one of their machines, and register it with the directory',
86
+ guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. A computer already registered accepts only the account it was registered under. A computer holding a local canvas and no `runtime/machine.json` is refused with `local_canvas_unsupported`: moving a local canvas into Northlight is no longer supported. A computer is also registered with the directory: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
106
87
  params: [
107
88
  { kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
108
89
  ],
109
90
  output: [
110
91
  { name: 'account', type: 'string', required: true, constraint: 'The account this computer is now signed in as.' },
111
- { name: 'moved', type: 'boolean', required: false, constraint: 'Present when this command moved the records, or finished an earlier move\'s switch-over.' },
112
- { name: 'moving', type: 'boolean', required: false, constraint: 'Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails.' },
113
92
  ],
114
93
  outputKind: 'object',
115
94
  effects: [
116
95
  'Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.',
117
- 'Starts the local daemon first when it is not running, and waits until it serves.',
118
- 'On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account\'s result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.',
119
- 'On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
120
- 'On a moved computer: restarts the daemon so it reconnects to Northlight.',
96
+ 'On a computer with no `machine.json`: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
97
+ 'On a registered computer: restarts the daemon so it reconnects to Northlight.',
121
98
  'Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity.',
122
99
  ],
123
100
  },
124
101
  run: async (input) => {
125
- // A computer with local records needs its daemon (the move reads the canvas through it) and a machine's daemon is the machine role; a fresh computer starts none until it is registered.
126
- if (readMachineConfig() !== undefined || hasLocalCanvas())
102
+ if (readMachineConfig() !== undefined)
127
103
  await spawnDaemon();
128
104
  const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
129
- const unfinished = await settleEarlierMove(showSignIn);
130
- if (unfinished !== undefined) {
131
- if (insideBroker()) {
132
- startDetachedMove(undefined);
133
- return { account: unfinished.account.display, moving: true };
134
- }
135
- await finishMove(unfinished);
136
- return { account: unfinished.account.display, moved: true };
137
- }
138
105
  const machine = readMachineConfig();
139
106
  if (machine !== undefined) {
140
107
  const { account } = await signIn(directoryUrl, showSignIn, { accept: sameAccountOnly(machine) });
@@ -143,19 +110,11 @@ export const sysSigninLeaf = defineLeaf({
143
110
  await spawnDaemon();
144
111
  return { account };
145
112
  }
146
- if (!hasLocalCanvas())
147
- return await registerFreshComputer(directoryUrl);
148
- const { account } = await signIn(directoryUrl, showSignIn);
149
- if (insideBroker()) {
150
- startDetachedMove(envNodeId());
151
- return { account, moving: true };
152
- }
153
- await runMove({ directoryUrl, notify: null });
154
- return { account, moved: true };
113
+ if (hasLocalCanvas())
114
+ throw new CrtrError('local_canvas_unsupported', 'this computer holds a local crtr canvas, and moving one into Northlight is no longer supported.', ExitCode.USAGE, { next: 'Remove the local canvas (the `pg`, `canvas.db` and `canvas.db.imported` entries under the runtime folder) to sign this computer in fresh.' });
115
+ return await registerFreshComputer(directoryUrl);
155
116
  },
156
- render: (r) => r['moving'] === true
157
- ? `<signin account="${r['account']}" moving="true">${MOVING(String(r['account']))}</signin>`
158
- : `<signin account="${r['account']}"${r['moved'] === true ? ' moved="true"' : ''}/>`,
117
+ render: (r) => `<signin account="${r['account']}"/>`,
159
118
  });
160
119
  /** Restart crtrd on a moved computer after sign-out; the machine daemon, finding no sign-in, stops every agent and cron on this computer and only
161
120
  * then answers `/healthz` with `signed_in: false`. Answers whether it did. */
@@ -1,11 +1,11 @@
1
1
  // The `Crtr-Caller` request header: who is behind a plugin call. Canvas-free so
2
2
  // the CLI and the daemon share one formatter.
3
- /** `node=<id>; machine=<id>; profile=<id>; run=<id>`, in that order. A field
3
+ /** `node=<id>; machine=<id>; profile=<id>; run=<id>; as=<principal>`, in that order. A field
4
4
  * that is empty, or whose value holds `;`, `=`, CR or LF, is left out rather
5
5
  * than injected into the header. Returns '' when no field remains. */
6
6
  export function formatCrtrCaller(fields) {
7
7
  const parts = [];
8
- for (const key of ['node', 'machine', 'profile', 'run']) {
8
+ for (const key of ['node', 'machine', 'profile', 'run', 'as']) {
9
9
  const value = fields[key];
10
10
  if (typeof value !== 'string' || value === '' || /[;=\r\n]/.test(value))
11
11
  continue;
@@ -13,3 +13,9 @@ export function ownsWithoutRow(grantee, sub, grantId) {
13
13
  export function ownerScopes(grantee) {
14
14
  return (pluginAppToken(grantee.replace(/^app:/, ''))?.scopes ?? []).map((scope) => parseScope(scope));
15
15
  }
16
+ /** Whether two principals lie in one namespace; false when either does not parse. */
17
+ export function sameNamespace(a, b) {
18
+ const first = parsePrincipal(a);
19
+ const second = parsePrincipal(b);
20
+ return first !== null && second !== null && first.namespace === second.namespace;
21
+ }
@@ -4,7 +4,7 @@ import { existsSync } from 'node:fs';
4
4
  import { CrtrError } from '../errors.js';
5
5
  import { getCachedProfile } from '../scoped-state/person-store.js';
6
6
  import { parseScope } from '@north-light/identity';
7
- import { isNamespaceOwner, ownerScopes } from '../grants/owner.js';
7
+ import { isNamespaceOwner, ownerScopes, sameNamespace } from '../grants/owner.js';
8
8
  import { activeGrant, grantFor, runtimeScope } from '../grants/mirror.js';
9
9
  import { withCanvasWrite } from '../canvas/db.js';
10
10
  import { ApiError } from '../../api/errors.js';
@@ -111,6 +111,20 @@ export async function warmNodeDirs(db, nodeId, dirs) {
111
111
  const row = nodeId === undefined ? undefined : await db.prepare('SELECT profile_id FROM nodes WHERE node_id = ?').get(nodeId);
112
112
  await warmCheckoutDirs(row?.profile_id, dirs);
113
113
  }
114
+ /** `readerFor` for a call that acts for `as` (`--as`): a node reads as `as` under the grant `as` made to the node's app, never wider than the node's own scopes.
115
+ * `as` in the node's own namespace needs no grant. A node with no such grant is refused 403 `not_granted`. */
116
+ export async function actingReaderFor(db, principal, reposFn, as) {
117
+ const reader = await readerFor(db, principal, reposFn);
118
+ if (reader.class !== 'node' || principal.class !== 'broker')
119
+ throw new ApiError(403, 'not_granted', '`--as` is for a node acting for another principal');
120
+ const grantee = principal.app;
121
+ if (sameNamespace(as, grantee))
122
+ return { ...reader, sub: as };
123
+ const grant = await grantFor(grantee, as);
124
+ if (grant === null)
125
+ throw new ApiError(403, 'not_granted', `${as} has not granted ${grantee} access`);
126
+ return { ...reader, sub: as, scopes: reader.launched == null ? grant.resolved : reader.launched.filter((scope) => coveredByAny(grant.resolved, scope)) };
127
+ }
114
128
  export async function readerFor(db, principal, reposFn) {
115
129
  if (principal.class === 'anonymous')
116
130
  throw new Error('a publish token cannot read as a principal');
@@ -35,6 +35,8 @@ async function namedUserOf(db, reader) {
35
35
  return reader.sub === undefined ? null : personSub(reader.sub);
36
36
  if (reader.class === 'object' && reader.sub !== undefined)
37
37
  return personSub(reader.sub);
38
+ if (reader.class === 'node' && reader.sub !== undefined)
39
+ return personSub(reader.sub);
38
40
  const nodeId = reader.class === 'node' ? reader.node.id : reader.object.id;
39
41
  const row = await db.prepare('SELECT sub FROM nodes WHERE node_id = ?').get(nodeId);
40
42
  return row?.sub == null ? null : personSub(row.sub);
@@ -11,7 +11,7 @@ import { providerToolPath } from '../plugin-objects-manifest.js';
11
11
  import { ensureProviderBundle, refreshProviderBundle, resolveProviderBundle, unavailableProviderError } from './bundles.js';
12
12
  import { prepareFileCall, resignForRetry, resolveFileResult } from './files.js';
13
13
  import { consumeApproval, requireProviderApproval } from './approval.js';
14
- import { outboundToken } from './mint.js';
14
+ import { actingToken, outboundToken } from './mint.js';
15
15
  import { discardFile } from './token-cache.js';
16
16
  import { registerProviderCall } from './inflight.js';
17
17
  import { buildRequestPlan, paramKey } from '../command-plugins/transport/http-plan.js';
@@ -255,8 +255,12 @@ export async function callProvider(caller, rawInput, request) {
255
255
  if (repeatedFiles)
256
256
  prepared = await resignForRetry(caller, files, input.arguments, repeatedFiles, { signal: controller.signal });
257
257
  prepared ??= await prepareFileCall(caller, files, input.arguments, { signal: controller.signal });
258
- const { sub, grantee } = await identity(caller);
258
+ const own = await identity(caller);
259
+ const { grantee } = own;
260
+ const sub = input.as ?? own.sub;
259
261
  if (bundle.transport.kind === 'machine') {
262
+ if (input.as !== undefined)
263
+ throw new ProviderError('not_granted', '`--as` is not available on a provider served by a device', { param: 'as' });
260
264
  const device = await callDevice(caller, bundle, input, leaf, prepared, { sub, requestId, deadlineAt: deviceDeadline, signal: controller.signal, machine: deviceMachine });
261
265
  responder = device.responder;
262
266
  cleanup = device.cleanup;
@@ -265,7 +269,9 @@ export async function callProvider(caller, rawInput, request) {
265
269
  const audience = bundle.transport.endpoint;
266
270
  let token;
267
271
  try {
268
- token = await outboundToken({ audience, sub, grantee, initiating_app: grantee, scope: callScope(bundle, leaf) }, { signal: controller.signal });
272
+ token = input.as === undefined
273
+ ? await outboundToken({ audience, sub, grantee, initiating_app: grantee, scope: callScope(bundle, leaf) }, { signal: controller.signal })
274
+ : await actingToken(own, input.as, { audience, scope: callScope(bundle, leaf) }, { signal: controller.signal });
269
275
  }
270
276
  catch (error) {
271
277
  // The directory no longer accepts the cached bundle's endpoint as an audience: fetch the bundle once more and retry only if it names a different endpoint.
@@ -285,7 +291,7 @@ export async function callProvider(caller, rawInput, request) {
285
291
  const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub, environmentPayer: await environmentPayerOfNode(caller.node_id) });
286
292
  const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee, provider: `app:${bundle.id}` });
287
293
  if (refusal !== null) {
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,
294
+ await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, actor: caller.actor ?? (input.as === undefined ? null : grantee), grantee: chargeGrantee,
289
295
  node: caller.node_id, run: caller.run_id, provider: `app:${bundle.id}`, causedBy: request.causedBy ?? null, refused: refusedMark(refusal) });
290
296
  throw refusalError(refusal);
291
297
  }
@@ -317,7 +323,7 @@ export async function callProvider(caller, rawInput, request) {
317
323
  }
318
324
  // R7 receives every response, including errors, before the mapping.
319
325
  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, actor: caller.actor ?? null, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
326
+ sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, actor: caller.actor ?? (input.as === undefined ? null : grantee), caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
321
327
  responder = response.headers['crtr-responder'];
322
328
  if (response.status === 401)
323
329
  discardFile(token.key);
@@ -27,6 +27,7 @@ const OTHER_CODES = {
27
27
  grant_revoked: errorCodes.grant_revoked,
28
28
  machine_revoked: errorCodes.machine_revoked,
29
29
  scope_missing: errorCodes.scope_missing,
30
+ not_granted: errorCodes.not_granted,
30
31
  permission_error: errorCodes.permission_error,
31
32
  invalid_request: errorCodes.invalid_request,
32
33
  not_found: errorCodes.not_found,