@north-light/api 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 (39) 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 +2 -0
  5. package/dist/clients/attach/config.js +2 -1
  6. package/dist/commands/api-client.d.ts +0 -5
  7. package/dist/commands/api-client.js +1 -12
  8. package/dist/commands/sys/import/move.d.ts +1 -34
  9. package/dist/commands/sys/import/move.js +5 -205
  10. package/dist/commands/sys/import/start.d.ts +0 -3
  11. package/dist/commands/sys/import/start.js +15 -51
  12. package/dist/commands/sys/signin.js +13 -54
  13. package/dist/core/command-plugins/caller-header.d.ts +3 -1
  14. package/dist/core/command-plugins/caller-header.js +2 -2
  15. package/dist/core/command.d.ts +1 -1
  16. package/dist/core/grants/owner.d.ts +2 -0
  17. package/dist/core/grants/owner.js +6 -0
  18. package/dist/core/graph/reader.d.ts +5 -0
  19. package/dist/core/graph/reader.js +15 -1
  20. package/dist/core/graph/types.d.ts +2 -0
  21. package/dist/core/permissions/evaluator.js +2 -0
  22. package/dist/core/providers/call.js +11 -5
  23. package/dist/core/providers/errors.js +1 -0
  24. package/dist/core/providers/mint.d.ts +19 -0
  25. package/dist/core/providers/mint.js +58 -29
  26. package/dist/core/worktree-mutation-async.js +11 -3
  27. package/dist/core/worktree-scripts.d.ts +13 -0
  28. package/dist/core/worktree-scripts.js +72 -0
  29. package/dist/core/worktree-sweep.js +10 -1
  30. package/dist/daemon/api/reader.d.ts +1 -1
  31. package/dist/daemon/api/reader.js +10 -2
  32. package/dist/daemon/machine-link/config.d.ts +0 -24
  33. package/dist/daemon/machine-link/config.js +1 -27
  34. package/dist/daemon/manage.d.ts +1 -1
  35. package/package.json +1 -1
  36. package/dist/commands/sys/import/retry.d.ts +0 -1
  37. package/dist/commands/sys/import/retry.js +0 -38
  38. package/dist/daemon/machine-link/move-notify.d.ts +0 -4
  39. package/dist/daemon/machine-link/move-notify.js +0 -15
@@ -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. */
@@ -3,8 +3,10 @@ export interface CrtrCallerFields {
3
3
  machine?: string | undefined;
4
4
  profile?: string | undefined;
5
5
  run?: string | undefined;
6
+ /** The principal the call acts for (`--as`). */
7
+ as?: string | undefined;
6
8
  }
7
- /** `node=<id>; machine=<id>; profile=<id>; run=<id>`, in that order. A field
9
+ /** `node=<id>; machine=<id>; profile=<id>; run=<id>; as=<principal>`, in that order. A field
8
10
  * that is empty, or whose value holds `;`, `=`, CR or LF, is left out rather
9
11
  * than injected into the header. Returns '' when no field remains. */
10
12
  export declare function formatCrtrCaller(fields: CrtrCallerFields): string;
@@ -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;
@@ -130,7 +130,7 @@ export interface RootDef {
130
130
  kind: 'root';
131
131
  help: RootHelp;
132
132
  subtrees: BranchDef[];
133
- /** Why a moved computer could not read the account's provider commands (`not_signed_in`, `northlight_unreachable`, `move_unfinished`). The tree
133
+ /** Why a moved computer could not read the account's provider commands (`not_signed_in`, `northlight_unreachable`). The tree
134
134
  * was built without them, so a top-level name it lacks may be one of those commands: the dispatcher raises this instead of `unknown_path`. */
135
135
  providerCatalogFailure?: ApiError | CrtrError;
136
136
  }
@@ -5,3 +5,5 @@ export declare function isNamespaceOwner(grantee: string, sub: string): boolean;
5
5
  export declare function ownsWithoutRow(grantee: string, sub: string, grantId: string | null | undefined): boolean;
6
6
  /** The scopes an owner principal holds with no grant row: the app's declared scopes (its `crtr_app_` token's), none when it declares none. */
7
7
  export declare function ownerScopes(grantee: string): Scope[];
8
+ /** Whether two principals lie in one namespace; false when either does not parse. */
9
+ export declare function sameNamespace(a: string, b: string): boolean;
@@ -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
+ }
@@ -20,6 +20,11 @@ export declare function warmNodeRepos(db: CanvasDb, nodeId: string): Promise<voi
20
20
  export declare function warmCloudNodeCheckouts(profileId: string | null, dirs: readonly string[]): Promise<void>;
21
21
  /** Warm the identities of `dirs` for node `nodeId` before a write opens: on a cloud role through its profile's machine, else git here. */
22
22
  export declare function warmNodeDirs(db: CanvasDb, nodeId: string | undefined, dirs: readonly string[]): Promise<void>;
23
+ /** `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.
24
+ * `as` in the node's own namespace needs no grant. A node with no such grant is refused 403 `not_granted`. */
25
+ export declare function actingReaderFor(db: CanvasDb, principal: RequestPrincipal, reposFn: ReposFn, as: string): Promise<Exclude<Reader, {
26
+ class: 'object';
27
+ }>>;
23
28
  export declare function readerFor(db: CanvasDb, principal: RequestPrincipal, reposFn: ReposFn): Promise<Exclude<Reader, {
24
29
  class: 'object';
25
30
  }>>;
@@ -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');
@@ -79,6 +79,8 @@ export type Reader = {
79
79
  app: ObjectRow;
80
80
  scopes: readonly string[] | null;
81
81
  cwd: string;
82
+ /** The principal this read acts for (`--as`), when it is not the node's own `sub`; the scopes are then the grant from it, never wider than the node's. */
83
+ sub?: string;
82
84
  /** The launched `scopes` list as given (see the app reader); null/absent = the run was launched with no list. */
83
85
  launched?: readonly string[] | null;
84
86
  /** The repos enclosing `cwd`, nearest first; `checkouts` pairs each with its checkout root. Only these are repos the node
@@ -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,
@@ -27,3 +27,22 @@ export declare function mintOutboundToken(request: OutboundTokenRequest, options
27
27
  /** The outbound token for `request`: the cached one while `now < exp − 30 s`
28
28
  * (D3-TOK-9), else a fresh mint, cached. Throws a mapped `ProviderError`. */
29
29
  export declare function outboundToken(request: OutboundTokenRequest, options?: MintOptions): Promise<OutboundToken>;
30
+ /** What an acting-for exchange asks the directory (RFC 8693): the node's own call token, the owner principal it acts for, and the call's audience and scope. */
31
+ export interface ExchangeRequest {
32
+ subjectToken: string;
33
+ as: string;
34
+ audience: string;
35
+ scope: readonly string[];
36
+ }
37
+ /** Exchange a node's call token for one whose `sub` is `request.as` and whose `act` is the node (the directory's token exchange). A refusal is 403
38
+ * `not_granted` or `scope_missing`; any other failure is a `server_error`. Nothing is cached: the token is for this call. */
39
+ export declare function exchangeForOwner(request: ExchangeRequest, options?: MintOptions): Promise<CachedToken>;
40
+ /** The token a node presents to act for `as`: its own call token (minted as its `sub` and `grantee`), exchanged at the directory. In the node's own namespace
41
+ * the node mints directly as `as` (an owner link) and no exchange runs. */
42
+ export declare function actingToken(node: {
43
+ sub: string;
44
+ grantee: string;
45
+ }, as: string, call: {
46
+ audience: string;
47
+ scope: readonly string[];
48
+ }, options?: MintOptions): Promise<OutboundToken>;
@@ -19,6 +19,7 @@ import { createHash } from 'node:crypto';
19
19
  import { directoryIssuer } from '../directory/issuer.js';
20
20
  import { emitEvent } from '../events/emit.js';
21
21
  import { OutboundError } from '../events/outbound.js';
22
+ import { sameNamespace } from '../grants/owner.js';
22
23
  import { grantSyncStateFor } from '../grants/mirror.js';
23
24
  import { assertion, machineRevokedMessage, requestGrantSync, runtimeClient } from '../grants/sync.js';
24
25
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
@@ -105,24 +106,13 @@ async function syncIfNewer(request, refused, options) {
105
106
  // The sync logs its own failure; the caller already has its answer.
106
107
  void Promise.resolve().then(() => sync({ fresh: true })).catch(() => { });
107
108
  }
108
- /** Mint one outbound token (no cache). Throws a mapped `ProviderError`. */
109
- export async function mintOutboundToken(request, options = {}) {
110
- const issuer = issuerOf(options);
111
- const endpoint = `${issuer}/token`;
109
+ /** POST a form to the directory's token endpoint (each attempt signs its own assertion: the directory accepts a `jti` once). A 502, 503 or 504 is the directory
110
+ * briefly down, not a refusal: ask again before failing. Unreachable or too slow is a retryable `server_error`. */
111
+ async function postToken(endpoint, form, options) {
112
112
  const client = runtimeClient();
113
113
  const attempt = async () => {
114
- // Each attempt signs its own assertion: the directory accepts a `jti` once.
115
- const body = new URLSearchParams({
116
- grant_type: 'client_credentials',
117
- client_id: client.client_id,
118
- client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
119
- client_assertion: assertion(client, endpoint),
120
- audience: request.audience,
121
- sub: request.sub,
122
- grantee: request.grantee,
123
- scope: [...new Set(request.scope)].sort().join(' '),
124
- initiating_app: request.initiating_app,
125
- });
114
+ const body = new URLSearchParams({ client_id: client.client_id, client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
115
+ client_assertion: assertion(client, endpoint), ...form(client) });
126
116
  const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
127
117
  const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
128
118
  const response = await (options.fetch ?? fetch)(endpoint, { method: 'POST', body, signal, headers: { Accept: 'application/json' } });
@@ -131,7 +121,6 @@ export async function mintOutboundToken(request, options = {}) {
131
121
  let response;
132
122
  let text;
133
123
  try {
134
- // A 502, 503 or 504 is the directory briefly down, not a refusal of this request: ask again before failing the call.
135
124
  for (let tries = 0;; tries++) {
136
125
  ({ response, text } = await attempt());
137
126
  const delay = MINT_RETRY_DELAYS_MS[tries];
@@ -153,16 +142,10 @@ export async function mintOutboundToken(request, options = {}) {
153
142
  catch {
154
143
  parsed = null;
155
144
  }
156
- const json = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
157
- if (!response.ok) {
158
- const { error, grantRefusal } = refusal(response.status, json, request, issuer);
159
- if (error.code === 'machine_revoked')
160
- emitEvent({ level: 'error', event: 'daemon.grants.machine_revoked', fields: { audience: request.audience } });
161
- emitEvent({ level: 'info', event: 'daemon.providers.mint_refused', fields: { audience: request.audience, grantee: request.grantee, code: error.code, directory_error: typeof json['error'] === 'string' ? json['error'] : null, status: response.status } });
162
- if (grantRefusal)
163
- await syncIfNewer(request, refusedGrantState(json), options);
164
- throw error;
165
- }
145
+ return { response, json: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {} };
146
+ }
147
+ /** The cacheable token a successful token response carries. The directory names who is charged; a token without the claim (an older directory) is charged to `payerFallback`. */
148
+ function tokenOf(json, payerFallback, options) {
166
149
  const accessToken = json['access_token'];
167
150
  if (typeof accessToken !== 'string' || !accessToken) {
168
151
  throw new ProviderError('server_error', 'the directory token response has no access_token', { origin: 'directory' });
@@ -178,10 +161,28 @@ export async function mintOutboundToken(request, options = {}) {
178
161
  if (exp === null)
179
162
  throw new ProviderError('server_error', 'the directory token response names no expiry', { origin: 'directory' });
180
163
  const jti = typeof payload.jti === 'string' && payload.jti ? payload.jti : createHash('sha256').update(accessToken).digest('hex');
181
- // The directory names who is charged; a token without the claim (an older directory) is charged to its sub.
182
- const payer = typeof payload.payer === 'string' && payload.payer ? payload.payer : request.sub;
164
+ const payer = typeof payload.payer === 'string' && payload.payer ? payload.payer : payerFallback;
183
165
  return { access_token: accessToken, jti, exp, payer };
184
166
  }
167
+ /** Mint one outbound token (no cache). Throws a mapped `ProviderError`. */
168
+ export async function mintOutboundToken(request, options = {}) {
169
+ const issuer = issuerOf(options);
170
+ const endpoint = `${issuer}/token`;
171
+ const { response, json } = await postToken(endpoint, () => ({
172
+ grant_type: 'client_credentials', audience: request.audience, sub: request.sub, grantee: request.grantee,
173
+ scope: [...new Set(request.scope)].sort().join(' '), initiating_app: request.initiating_app,
174
+ }), options);
175
+ if (!response.ok) {
176
+ const { error, grantRefusal } = refusal(response.status, json, request, issuer);
177
+ if (error.code === 'machine_revoked')
178
+ emitEvent({ level: 'error', event: 'daemon.grants.machine_revoked', fields: { audience: request.audience } });
179
+ emitEvent({ level: 'info', event: 'daemon.providers.mint_refused', fields: { audience: request.audience, grantee: request.grantee, code: error.code, directory_error: typeof json['error'] === 'string' ? json['error'] : null, status: response.status } });
180
+ if (grantRefusal)
181
+ await syncIfNewer(request, refusedGrantState(json), options);
182
+ throw error;
183
+ }
184
+ return tokenOf(json, request.sub, options);
185
+ }
185
186
  // Concurrent calls for one key share one mint.
186
187
  const inflight = new Map();
187
188
  /** The outbound token for `request`: the cached one while `now < exp − 30 s`
@@ -217,3 +218,31 @@ function abortable(work, signal) {
217
218
  work.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
218
219
  });
219
220
  }
221
+ /** Exchange a node's call token for one whose `sub` is `request.as` and whose `act` is the node (the directory's token exchange). A refusal is 403
222
+ * `not_granted` or `scope_missing`; any other failure is a `server_error`. Nothing is cached: the token is for this call. */
223
+ export async function exchangeForOwner(request, options = {}) {
224
+ const { response, json } = await postToken(`${issuerOf(options)}/token`, () => ({
225
+ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', subject_token: request.subjectToken,
226
+ subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', requested_subject: request.as, audience: request.audience,
227
+ scope: [...new Set(request.scope)].sort().join(' '),
228
+ }), options);
229
+ if (!response.ok) {
230
+ const reason = typeof json['error_description'] === 'string' ? json['error_description'] : undefined;
231
+ const details = { directory_status: response.status, ...(typeof json['error'] === 'string' ? { directory_error: json['error'] } : {}), ...(reason ? { directory_description: reason } : {}) };
232
+ if (json['error'] === 'invalid_grant' && reason === 'not_granted')
233
+ throw new ProviderError('not_granted', `${request.as} has not granted this caller access`, { origin: 'directory', details });
234
+ if (json['error'] === 'invalid_grant' && reason === 'scope_missing')
235
+ throw new ProviderError('scope_missing', `the grant from ${request.as} does not cover ${request.scope.join(' ')}`, { origin: 'directory', details, ...(request.scope.length === 1 ? { scope: request.scope[0] } : {}) });
236
+ throw new ProviderError('server_error', `the directory refused the token exchange (${response.status}${reason ? ` ${reason}` : ''})`, { origin: 'directory', details });
237
+ }
238
+ return tokenOf(json, request.as, options);
239
+ }
240
+ /** The token a node presents to act for `as`: its own call token (minted as its `sub` and `grantee`), exchanged at the directory. In the node's own namespace
241
+ * the node mints directly as `as` (an owner link) and no exchange runs. */
242
+ export async function actingToken(node, as, call, options = {}) {
243
+ if (sameNamespace(as, node.grantee))
244
+ return await outboundToken({ ...call, sub: as, grantee: node.grantee, initiating_app: node.grantee }, options);
245
+ const subject = await outboundToken({ ...call, sub: node.sub, grantee: node.grantee, initiating_app: node.grantee }, options);
246
+ const token = await exchangeForOwner({ subjectToken: subject.access_token, as, audience: call.audience, scope: call.scope }, options);
247
+ return { ...token, key: `exchange:${token.jti}` };
248
+ }
@@ -8,6 +8,7 @@ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
8
8
  import { gitAsync } from './git.js';
9
9
  import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, isManagedWorktreeBase, managedWorktreesRoot, managedWorktreePath, persistClosedWorktreeState, worktreeLockPathForCommonDir, WorktreeError, branchIsPushedAtCurrentTip } from './worktree.js';
10
10
  import { proveBranchContained } from './worktree-containment.js';
11
+ import { runWorktreeScript } from './worktree-scripts.js';
11
12
  import { refDeleteTransactionStdin } from './worktree-landing.js';
12
13
  import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
13
14
  // A function, not a constant: `runtime/nodes.ts` imports this module and sits in an import cycle with `worktree.ts`, so a module-level read of its exports would run before they exist.
@@ -116,7 +117,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
116
117
  throw new WorktreeError('managed_worktree_base', `cwd ${repoRoot} is a managed worktree and cannot be used as a managed worktree base`, 'Pass `--cwd` pointing at the repository’s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.');
117
118
  }
118
119
  const commonDir = await commonGitDir(repoRoot);
119
- return withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
120
+ const wt = await withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
120
121
  const baseSha = await resolveLandableBase(repoRoot, baseRef);
121
122
  const path = managedWorktreePath(nodeId);
122
123
  const branch = `crtr/${nodeId}`;
@@ -124,7 +125,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
124
125
  throw new WorktreeError('worktree_path_exists', `managed worktree path already exists: ${path}`, 'Remove the stale path or choose a fresh node id.');
125
126
  if ((await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], repoRoot)).status === 0)
126
127
  throw new WorktreeError('worktree_branch_exists', `managed worktree branch already exists: ${branch}`, 'Remove the stale branch or choose a fresh node id.');
127
- const wt = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
128
+ const created = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
128
129
  await runGit(repoRoot, ['branch', branch, baseSha], 'worktree_branch_create_failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.');
129
130
  const added = await gitAsync(['worktree', 'add', path, branch], repoRoot);
130
131
  if (added.status !== 0) {
@@ -132,8 +133,15 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
132
133
  throw new WorktreeError('worktree_add_failed', 'git worktree add failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.', detailOf(added));
133
134
  }
134
135
  seedExclude(repoRoot, commonDir);
135
- return wt;
136
+ return created;
136
137
  }, { timeoutMs: lockWaitMs(), timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.') });
138
+ // Outside the repository lock: a script may take minutes. A failed setup fails creation and the half-prepared checkout is removed the normal way.
139
+ const setup = await runWorktreeScript('worktree-setup', basename(wt.path), wt);
140
+ if (setup.status === 'failed') {
141
+ await rollbackManagedWorktreeAsync(wt);
142
+ throw new WorktreeError('worktree_setup_failed', '.dev/worktree-setup failed', 'Fix the repository\'s .dev/worktree-setup on its base branch, then retry spawning with --worktree.', setup.detail);
143
+ }
144
+ return wt;
137
145
  }
138
146
  async function cleanTip(wt) {
139
147
  if (wt.state !== 'open' || !existsSync(wt.path))
@@ -0,0 +1,13 @@
1
+ import type { ManagedWorktree } from './canvas/index.js';
2
+ export type WorktreeScript = 'worktree-setup' | 'worktree-teardown';
3
+ /** Fixed, not configurable. */
4
+ export declare const WORKTREE_SCRIPT_TIMEOUT_MS: number;
5
+ export type WorktreeScriptResult = {
6
+ status: 'absent';
7
+ } | {
8
+ status: 'ok';
9
+ } | {
10
+ status: 'failed';
11
+ detail: string;
12
+ };
13
+ export declare function runWorktreeScript(script: WorktreeScript, nodeId: string, wt: ManagedWorktree, timeoutMs?: number): Promise<WorktreeScriptResult>;
@@ -0,0 +1,72 @@
1
+ // A repository's optional `.dev/worktree-setup` and `.dev/worktree-teardown` executables.
2
+ //
3
+ // crtr decides WHEN they run (after a managed worktree is created, and as the first step of its sweep); the
4
+ // repository decides WHAT they do. Each script is read from the worktree's base branch in the primary checkout,
5
+ // never from the worktree itself, so a node's own commits cannot change what crtr executes. A missing file is no step.
6
+ // Async only: the sweep runs on the daemon's event loop.
7
+ import { spawn } from 'node:child_process';
8
+ import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { gitAsync } from './git.js';
12
+ /** Fixed, not configurable. */
13
+ export const WORKTREE_SCRIPT_TIMEOUT_MS = 5 * 60_000;
14
+ const STDERR_TAIL_LINES = 20;
15
+ function tail(text) {
16
+ return text.trim().split('\n').slice(-STDERR_TAIL_LINES).join('\n');
17
+ }
18
+ export async function runWorktreeScript(script, nodeId, wt, timeoutMs = WORKTREE_SCRIPT_TIMEOUT_MS) {
19
+ const ref = `refs/heads/${wt.base_ref}`;
20
+ const spec = `${ref}:.dev/${script}`;
21
+ const exists = await gitAsync(['cat-file', '-e', spec], wt.repo_root);
22
+ if (exists.status !== 0)
23
+ return { status: 'absent' };
24
+ const body = await gitAsync(['show', spec], wt.repo_root);
25
+ if (body.status !== 0)
26
+ return { status: 'failed', detail: `could not read .dev/${script} from ${ref}: ${body.stderr.trim()}` };
27
+ const dir = await mkdtemp(join(tmpdir(), 'crtr-worktree-script-'));
28
+ try {
29
+ const file = join(dir, script);
30
+ await writeFile(file, body.stdout);
31
+ await chmod(file, 0o755);
32
+ return await new Promise((resolve) => {
33
+ const child = spawn(file, [], {
34
+ cwd: wt.path,
35
+ stdio: ['ignore', 'ignore', 'pipe'],
36
+ env: {
37
+ ...process.env,
38
+ CRTR_NODE_ID: nodeId,
39
+ CRTR_WORKTREE_PATH: wt.path,
40
+ CRTR_REPO_ROOT: wt.repo_root,
41
+ CRTR_BASE_REF: wt.base_ref,
42
+ COMPOSE_PROJECT_NAME: `crtr-${nodeId}`,
43
+ },
44
+ });
45
+ let stderr = '';
46
+ let timedOut = false;
47
+ let settled = false;
48
+ const finish = (result) => {
49
+ if (settled)
50
+ return;
51
+ settled = true;
52
+ clearTimeout(timer);
53
+ resolve(result);
54
+ };
55
+ const timer = setTimeout(() => {
56
+ timedOut = true;
57
+ child.kill('SIGKILL');
58
+ finish({ status: 'failed', detail: `.dev/${script} timed out after ${Math.round(timeoutMs / 1000)}s\n${tail(stderr)}`.trim() });
59
+ }, timeoutMs);
60
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-16_384); });
61
+ child.on('error', (err) => finish({ status: 'failed', detail: `could not run .dev/${script}: ${err.message}` }));
62
+ child.on('close', (code, signal) => {
63
+ if (timedOut)
64
+ return;
65
+ finish(code === 0 ? { status: 'ok' } : { status: 'failed', detail: `.dev/${script} exited ${code ?? `by ${signal}`}\n${tail(stderr)}`.trim() });
66
+ });
67
+ });
68
+ }
69
+ finally {
70
+ await rm(dir, { recursive: true, force: true });
71
+ }
72
+ }