@north-light/cli 0.3.679 → 0.3.681

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 (58) hide show
  1. package/dist/api/client.js +3 -3
  2. package/dist/api/contract.d.ts +1 -1
  3. package/dist/api/contract.js +1 -1
  4. package/dist/api/dto/profiles.d.ts +1 -1
  5. package/dist/api/server-timing.d.ts +3 -0
  6. package/dist/api/server-timing.js +1 -0
  7. package/dist/clients/attach/viewer.js +489 -489
  8. package/dist/core/checkout-identities.js +3 -3
  9. package/dist/core/conversation-store/client.d.ts +9 -0
  10. package/dist/core/conversation-store/client.js +2 -2
  11. package/dist/core/conversation-store/index.d.ts +10 -2
  12. package/dist/core/conversation-store/index.js +1 -1
  13. package/dist/core/conversation-store/patch.js +1 -1
  14. package/dist/core/conversation-store/row-store.js +9 -9
  15. package/dist/core/profiles/manifest.js +1 -1
  16. package/dist/core/runtime/broker.d.ts +3 -1
  17. package/dist/core/runtime/broker.js +1 -1
  18. package/dist/core/runtime/front-door.js +4 -4
  19. package/dist/core/runtime/host.js +3 -3
  20. package/dist/core/runtime/runner/blaxel/image-build.js +3 -3
  21. package/dist/core/runtime/runner/blaxel/release-image.js +2 -2
  22. package/dist/core/runtime/runner/machine/call.d.ts +5 -0
  23. package/dist/core/runtime/runner/machine/call.js +2 -2
  24. package/dist/core/runtime/runner/machine/executor.js +1 -1
  25. package/dist/core/runtime/runner/machine/ops.d.ts +2 -0
  26. package/dist/core/runtime/spawn.js +2 -2
  27. package/dist/core/step-timings.d.ts +13 -0
  28. package/dist/core/step-timings.js +1 -0
  29. package/dist/core/timing.d.ts +2 -0
  30. package/dist/core/timing.js +2 -2
  31. package/dist/core/user-settings.d.ts +2 -2
  32. package/dist/daemon/api/handlers/conversations.js +1 -1
  33. package/dist/daemon/api/handlers/nodes.d.ts +1 -0
  34. package/dist/daemon/api/handlers/nodes.js +1 -1
  35. package/dist/daemon/api/handlers/profiles.js +1 -1
  36. package/dist/daemon/crtrd.js +15 -15
  37. package/package.json +3 -3
  38. package/packages/crouter-api/dist/api/client.js +5 -1
  39. package/packages/crouter-api/dist/api/contract.js +1 -1
  40. package/packages/crouter-api/dist/api/server-timing.js +11 -0
  41. package/packages/crouter-api/dist/core/checkout-identities.js +4 -1
  42. package/packages/crouter-api/dist/core/conversation-store/client.js +8 -1
  43. package/packages/crouter-api/dist/core/conversation-store/index.js +1 -0
  44. package/packages/crouter-api/dist/core/conversation-store/patch.js +1 -2
  45. package/packages/crouter-api/dist/core/conversation-store/row-store.js +2 -2
  46. package/packages/crouter-api/dist/core/profiles/manifest.js +7 -1
  47. package/packages/crouter-api/dist/core/runtime/host.js +9 -0
  48. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +2 -2
  49. package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +1 -0
  50. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +7 -0
  51. package/packages/crouter-api/dist/core/runtime/spawn.js +43 -10
  52. package/packages/crouter-api/dist/core/step-timings.js +37 -0
  53. package/packages/crouter-api/dist/core/timing.js +14 -0
  54. package/packages/crouter-api/package.json +1 -1
  55. package/packages/crouter-identity/package.json +1 -1
  56. package/packages/crouter-plugin/package.json +3 -3
  57. package/runtime.lock.json +14 -14
  58. package/scripts/sandbox-bootstrap.sh +1 -8
@@ -7,6 +7,7 @@ import { resolve } from 'node:path';
7
7
  import { withCanvasWrite } from './canvas/db.js';
8
8
  import { isCloudRole, PersonOutsideRequestError } from './canvas/person-state.js';
9
9
  import { emitEvent } from './events/emit.js';
10
+ import { timedStep } from './step-timings.js';
10
11
  import { realpathOrSelf } from './fs-utils.js';
11
12
  import { checkoutChain } from './graph/repo-sync/identity.js';
12
13
  import { callMachine } from './runtime/runner/machine/call.js';
@@ -17,10 +18,12 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
17
18
  export const machineCheckoutHandlers = {
18
19
  'repo.identify': async ({ dirs }) => {
19
20
  // A directory whose lookup failed (anywhere in its chain) is left out of the answer, so the cloud keeps what it stored; `[]` means not a repo.
21
+ const startedAt = performance.now();
20
22
  const answers = await Promise.all(dirs.map(async (dir) => {
21
23
  const chain = await checkoutChain(realpathOrSelf(resolve(dir)));
22
24
  return chain.every((id) => id.ok) ? [dir, chain] : null;
23
25
  }));
26
+ emitEvent({ level: 'info', event: 'machine.repo_identify.timing', fields: { dirs: dirs.length, duration_ms: Math.round(performance.now() - startedAt) } });
24
27
  return Object.fromEntries(answers.filter((a) => a !== null));
25
28
  },
26
29
  };
@@ -32,7 +35,7 @@ export async function warmMachineCheckouts(environment, dirs) {
32
35
  return true;
33
36
  let answer;
34
37
  try {
35
- answer = await callMachine(environment, 'repo.identify', { dirs: wanted });
38
+ answer = await timedStep('repo_identify_call', () => callMachine(environment, 'repo.identify', { dirs: wanted }));
36
39
  }
37
40
  catch (error) {
38
41
  if (!(error instanceof MachineOfflineError || error instanceof MachineLostError || error instanceof MachineCallFailedError))
@@ -1,8 +1,12 @@
1
1
  import { MessageChannel, Worker, receiveMessageOnPort } from 'node:worker_threads';
2
2
  import { ConversationNotFoundError } from './index.js';
3
+ let requestMark;
4
+ export function setConversationRequestMark(mark) { requestMark = mark; }
3
5
  export function createStoreClient(address, token) {
4
6
  const worker = new Worker(new URL(import.meta.url.endsWith('.ts') ? './client-worker.ts' : './client-worker.js', import.meta.url), { workerData: { address, token } });
5
7
  worker.unref();
8
+ const workerStartedAt = Date.now();
9
+ let requests = 0;
6
10
  let workerFailure;
7
11
  worker.on('error', (error) => { workerFailure = error; });
8
12
  worker.on('exit', (code) => { workerFailure = new Error(`conversation store worker exited with ${code}`); });
@@ -22,9 +26,12 @@ export function createStoreClient(address, token) {
22
26
  throw workerFailure;
23
27
  const signal = new SharedArrayBuffer(4);
24
28
  const { port1, port2 } = new MessageChannel();
29
+ const startedAt = process.hrtime.bigint();
30
+ const firstRequest = requests++ === 0;
25
31
  try {
26
32
  worker.postMessage({ method, path, data, signal, reply: port2 }, [port2]);
27
33
  const result = Atomics.wait(new Int32Array(signal), 0, 0, 30_000);
34
+ requestMark?.({ method, route: path.replace(/\/[0-9a-f-]{36}/gi, '/:id'), durationMs: Number(process.hrtime.bigint() - startedAt) / 1_000_000, firstRequest, workerAgeMs: Date.now() - workerStartedAt });
28
35
  if (result === 'timed-out') {
29
36
  port1.postMessage('cancel');
30
37
  throw new Error(`conversation store request timed out: ${method} ${path}`);
@@ -91,7 +98,7 @@ export function createStoreClient(address, token) {
91
98
  const readPath = (id, window) => window ? `${url(id)}?head=${window.head}&tail=${window.tail}` : url(id);
92
99
  return {
93
100
  create(nodeId, header, entries, path) {
94
- return JSON.parse(call('POST', '/conversations', { node_id: nodeId, header, entries, path }).body).conversation_id;
101
+ return JSON.parse(call('POST', '/conversations', { node_id: nodeId, header, entries, path }).body);
95
102
  },
96
103
  append(id, entries) { enqueueAppend(id, entries); },
97
104
  flush,
@@ -1,6 +1,7 @@
1
1
  import { appsRoot } from '../layout.js';
2
2
  import { apiSocketPath } from '../canvas/paths.js';
3
3
  import { createStoreClient } from './client.js';
4
+ export { setConversationRequestMark } from './client.js';
4
5
  import { currentNodeToken } from '../runtime/broker/node-token.js';
5
6
  export class ConversationNotFoundError extends Error {
6
7
  code = 'not_found';
@@ -49,8 +49,7 @@ export function installSessionManagerStorePatch(nodeId, store = conversationClie
49
49
  const [header, ...entries] = manager.fileEntries;
50
50
  if (!header || header.type !== 'session')
51
51
  throw new Error('conversation has no session header');
52
- store.create(nodeId, header, entries);
53
- manager.sessionFile = store.header(header.id).path;
52
+ manager.sessionFile = store.create(nodeId, header, entries).path;
54
53
  manager.sessionDir = dirname(manager.sessionFile);
55
54
  manager.flushed = true;
56
55
  }
@@ -164,7 +164,7 @@ export function createRowStore() {
164
164
  await tx.prepare('UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?').run(entries.at(-1)?.id ?? null, JSON.stringify(pending), id, nodeId);
165
165
  }
166
166
  });
167
- return id;
167
+ return { conversation_id: id, path };
168
168
  },
169
169
  async append(id, entries) {
170
170
  if (!entries.length)
@@ -276,7 +276,7 @@ export function createRowStore() {
276
276
  manager.createBranchedSession(leafId);
277
277
  entries = manager.getEntries();
278
278
  }
279
- return await store.create(nodeId ?? (await initial(id, await openDb())).binding?.node_id ?? legacy.get(id).node, { ...source.header, id: randomUUID(), timestamp: at(), cwd: cwd ?? source.header.cwd, parentSession: source.path }, entries);
279
+ return (await store.create(nodeId ?? (await initial(id, await openDb())).binding?.node_id ?? legacy.get(id).node, { ...source.header, id: randomUUID(), timestamp: at(), cwd: cwd ?? source.header.cwd, parentSession: source.path }, entries)).conversation_id;
280
280
  },
281
281
  async delete(id, knownPath) {
282
282
  const db = await openDb();
@@ -10,6 +10,7 @@ import { cachedPausedProfileIds, cachedProfilePaused, getCachedProfile as getSto
10
10
  import { usage, notFound, ambiguous, general } from '../errors.js';
11
11
  import { fuzzyMatchProfile } from './fuzzy-match.js';
12
12
  import { isCloudRole, personId } from '../canvas/person-state.js';
13
+ import { readMachineConfig } from '../../daemon/machine-link/config.js';
13
14
  // A generated id and its stored app determine the memory and environment paths.
14
15
  /** `<slug>-<shortid>`: slug is lower-case, non-alphanumeric collapsed to `-`,
15
16
  * trimmed to 40 chars (defaulting to `profile`); shortid is 8 lowercase hex
@@ -353,8 +354,13 @@ export async function createProfile(name, projects = [], opts = {}) {
353
354
  };
354
355
  scaffoldProfile(profileId, manifest);
355
356
  const insert = async () => { await writeSettings(() => [{ op: 'profile.insert', profile: { profileId, manifest } }]); };
356
- if (!isCloudRole())
357
+ if (!isCloudRole()) {
358
+ // A profile made on an imported Mac runs on that Mac: store its environment, or the control plane finds no machine for it.
359
+ const machine = readMachineConfig();
360
+ if (machine !== undefined)
361
+ manifest.environment_id = machine.environmentId;
357
362
  await insert();
363
+ }
358
364
  else if (cloudProfileWriter === null)
359
365
  throw new Error('a cloud role has no profile environment writer registered');
360
366
  else
@@ -590,6 +590,15 @@ export const headlessBrokerHost = {
590
590
  env: childEnv,
591
591
  });
592
592
  child = spawned;
593
+ // Wait for the OS to start or refuse the process, so a refusal (a missing cwd or executable) reaches the caller as the
594
+ // original spawn error naming what was attempted, never as a handle with no pid.
595
+ try {
596
+ await new Promise((resolve, reject) => { spawned.once('spawn', resolve); spawned.once('error', reject); });
597
+ }
598
+ catch (error) {
599
+ emitEvent({ level: 'error', event: 'broker.launch.failed', node_id: nodeId, error, fields: { cwd: opts.cwd, executable: brokerExec } });
600
+ throw new Error(`could not spawn the broker (executable ${brokerExec}, cwd ${opts.cwd}): ${error.message}`, { cause: error });
601
+ }
593
602
  const tokenPipe = spawned.stdio[3];
594
603
  if (!tokenPipe || !('end' in tokenPipe))
595
604
  throw new Error('broker token pipe did not open');
@@ -57,7 +57,7 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
57
57
  out.push(guarded('setup script', `bash /tmp/${SETUP_SCRIPT_FILE}`));
58
58
  out.push(guarded('finalize', `echo ${Math.trunc(revision)} > /work/.crtr/recipe-revision && chown -R ${RUN_USER} /work /home/${RUN_USER} /var/lib/crtr`));
59
59
  out.push('', ...base);
60
- // Blaxel's image conversion makes every file root-owned whatever these chowns say; sandbox-bootstrap.sh restores ownership at start. They keep the image correct for any other runtime.
60
+ // Blaxel keeps the ownership set in the Dockerfile only for an image that declares a final USER (an image without one is built all root-owned); the final USER is below.
61
61
  for (const dir of ['/work', `/home/${RUN_USER}`, '/var/lib/crtr'])
62
62
  out.push(`COPY --from=build --chown=${RUN_USER}:${RUN_USER} ${dir} ${dir}`);
63
63
  for (const dir of ['/usr/local', '/usr', '/etc', '/lib'])
@@ -67,7 +67,7 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
67
67
  out.push('RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi');
68
68
  if (packagesToken)
69
69
  out.push(`RUN rm -f /work/.npmrc /home/${RUN_USER}/.npmrc`);
70
- out.push('WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
70
+ out.push(`USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
71
71
  return out.join('\n');
72
72
  }
73
73
  const runGit = (args, env, cwd) => new Promise((resolve, reject) => {
@@ -51,6 +51,7 @@ export function releaseImageDockerfile(version, sha256) {
51
51
  `COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
52
52
  `RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${RUN_USER} /run/crtr /var/lib/crtr /work`,
53
53
  'COPY --from=release /opt/crtr /opt/crtr',
54
+ `USER ${RUN_USER}`,
54
55
  'WORKDIR /work',
55
56
  'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',
56
57
  '',
@@ -16,6 +16,13 @@ export const MACHINE_CALL_TIMEOUT_S = {
16
16
  'repo.identify': 15,
17
17
  };
18
18
  const REREAD_MS = 1000;
19
+ /** When a call was queued and when its holder settled it (epoch ms), for the create request's step timings. Null when the row is gone or unsettled. */
20
+ export async function callTimes(callId) {
21
+ const row = await (await openDb()).prepare('SELECT created_at, finished_at FROM machine_calls WHERE call_id = ?').get(callId);
22
+ if (row === undefined || row.finished_at === null)
23
+ return null;
24
+ return { createdAt: Date.parse(row.created_at), finishedAt: Date.parse(row.finished_at) };
25
+ }
19
26
  /** Write the `pending` call row and notify the link's holder, in the caller's transaction when it has one (the notification is delivered at its commit,
20
27
  * so a call queued by a transaction that rolls back is never sent). No live link → MachineOfflineError, nothing written. Returns the call id for `awaitMachineCall`. */
21
28
  export async function enqueueMachineCall(environmentId, op, args) {
@@ -9,7 +9,7 @@
9
9
  // direct driving, or, with `rootLifecycle: 'terminal'`, an
10
10
  // unattended parentless worker that still owes a final (so it
11
11
  // reaps) and is never placed on screen.
12
- import { accessSync, constants } from 'node:fs';
12
+ import { accessSync, constants, existsSync } from 'node:fs';
13
13
  import { isAbsolute, resolve, join } from 'node:path';
14
14
  import { appSpace } from '../layout.js';
15
15
  import { ApiError } from '../../api/errors.js';
@@ -21,6 +21,8 @@ import { devEnvironmentCwd, runsOnBlaxel, sandboxWorktreeRequest } from '../../d
21
21
  import { createManagedWorktreeAsync, rollbackManagedWorktreeAsync } from '../worktree-mutation-async.js';
22
22
  import { createManagedWorktreeOnMachine, rollbackManagedWorktreeOnMachine, worktreeMachineOf } from '../worktree-machine.js';
23
23
  import { usage, brokerLaunchFailed } from '../errors.js';
24
+ import { InputError } from '../io.js';
25
+ import { isCloudRole } from '../canvas/person-state.js';
24
26
  import { writeGoal } from './kickoff.js';
25
27
  import { appendSituationalContext, formatSituationalProse } from './situational-context.js';
26
28
  import { ensureRoadmap } from './roadmap.js';
@@ -48,7 +50,8 @@ import { personIdAsync } from '../canvas/person.js';
48
50
  import { recordLaunch } from '../canvas/canvas.js';
49
51
  import { setExecutionLaunchJson } from '../canvas/executions.js';
50
52
  import { acceptedRelease, remoteMachineEnvironmentOf } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
51
- import { enqueueMachineCall, awaitMachineCall } from './runner/machine/call.js';
53
+ import { enqueueMachineCall, awaitMachineCall, callTimes } from './runner/machine/call.js';
54
+ import { addStepTiming, timedStep } from '../step-timings.js';
52
55
  import { MachineLostError, MachineOfflineError } from './runner/machine/ops.js';
53
56
  import { isDrained } from '../../daemon/drain.js';
54
57
  import { ensureDaemon } from '../../daemon/manage.js';
@@ -92,7 +95,7 @@ async function launchBrokerOrCrash(nodeId, inv, opts) {
92
95
  // `[broker] refusing to launch <id>:` lead, so re-surface them as-is
93
96
  // rather than double-prefixing the now caller-visible text.
94
97
  const cause = error.message;
95
- throw brokerLaunchFailed(cause.startsWith('[broker]') ? cause : `[broker] refusing to launch ${nodeId}: ${cause}`, 'Inspect the cause above, fix the launch recipe or environment, then retry.');
98
+ throw brokerLaunchFailed(cause.startsWith('[broker]') ? cause : `[broker] refusing to launch ${nodeId}: ${cause}`, `Inspect the cause above and \`crtr sys logs --node ${nodeId}\`, fix the launch recipe or environment, then retry.`);
96
99
  }
97
100
  }
98
101
  /** The last `broker.startup.*` step a freshly created root broker logged, or null when it logged none (it never got
@@ -270,6 +273,16 @@ export function resolveSpawner(parent, ctxNodeId, root) {
270
273
  }
271
274
  return spawner;
272
275
  }
276
+ /** Record how long the `start` call took from being queued to being answered (both times are written once, by the queuer and by the link
277
+ * holder that settles it), and the steps the Mac reported inside `executor.start`. The row keeps no time for when the holder sent the call, so
278
+ * the enqueue-to-sent and sent-to-answer halves are not reported; the Mac's own steps show its share. */
279
+ async function recordStartCallTimings(callId, answer) {
280
+ const times = await callTimes(callId);
281
+ if (times !== null)
282
+ addStepTiming('start_enqueue_to_answer', times.finishedAt - times.createdAt);
283
+ for (const [name, ms] of Object.entries(answer?.timings ?? {}))
284
+ addStepTiming(`mac_${name}`, ms);
285
+ }
273
286
  /** Launch a just-born node on its remote machine in two transactions: the node and execution rows are committed (as a birth always does), then one
274
287
  * transaction renders the start data, mints the token and queues the `start` call; the call is awaited after that commit. The bundle's network work
275
288
  * (GitHub token, blob store) runs before that transaction opens. 'failed': nothing started, the caller freezes the node for the lifecycle tick to wake.
@@ -298,10 +311,10 @@ async function startOnMachine(meta, environmentId, inv) {
298
311
  const launchJson = await brokerLaunchJson(meta.node_id, inv, meta.cwd);
299
312
  await setExecutionLaunchJson(executionId, launchJson);
300
313
  const execId = executionId;
301
- await warmNodeRepos(await openDb(), meta.node_id);
314
+ await timedStep('warm_repos', async () => await warmNodeRepos(await openDb(), meta.node_id));
302
315
  const sub = meta.sub ?? await personIdAsync();
303
- const bundle = await buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' });
304
- callId = await withCanvasWrite(async (db) => {
316
+ const bundle = await timedStep('start_bundle', () => buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' }));
317
+ callId = await timedStep('render_transaction', () => withCanvasWrite(async (db) => {
305
318
  // The reader is built here, after the goal and every birth write have landed, so the rendered bearings see them.
306
319
  const start = await renderCarriedStart(meta.node_id);
307
320
  const nodeToken = await mintNodeToken(db, execId, meta.node_id, new Date().toISOString());
@@ -309,15 +322,16 @@ async function startOnMachine(meta, environmentId, inv) {
309
322
  executionId: execId, nodeId: meta.node_id, attempt: 1, sandboxName: null, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
310
323
  nodeToken, bundle, start,
311
324
  });
312
- });
325
+ }));
313
326
  }
314
327
  catch (error) {
315
328
  emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
316
329
  await abortExecution(executionId, { reason: 'launch_failed' });
317
330
  return 'failed';
318
331
  }
332
+ let startAnswer;
319
333
  try {
320
- await awaitMachineCall(environmentId, 'start', callId);
334
+ startAnswer = await awaitMachineCall(environmentId, 'start', callId);
321
335
  }
322
336
  catch (error) {
323
337
  emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
@@ -327,9 +341,16 @@ async function startOnMachine(meta, environmentId, inv) {
327
341
  await abortExecution(executionId, { reason: 'launch_failed' });
328
342
  return 'failed';
329
343
  }
330
- // The Mac has confirmed the start: a failure to record it must not end a running execution.
344
+ // The Mac has confirmed the start: timing marks are diagnostics only and never change the outcome.
345
+ try {
346
+ await recordStartCallTimings(callId, startAnswer);
347
+ }
348
+ catch (error) {
349
+ emitEvent({ level: 'warn', event: 'broker.create_start_timing_failed', node_id: meta.node_id, error });
350
+ }
351
+ // A failure to record it must not end a running execution.
331
352
  try {
332
- await recordLaunch(meta.node_id, new Date().toISOString());
353
+ await timedStep('record_launch', () => recordLaunch(meta.node_id, new Date().toISOString()));
333
354
  }
334
355
  catch (error) {
335
356
  emitEvent({ level: 'warn', event: 'broker.create_start_record_failed', node_id: meta.node_id, error });
@@ -337,6 +358,7 @@ async function startOnMachine(meta, environmentId, inv) {
337
358
  return 'started';
338
359
  }
339
360
  export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCreated) {
361
+ const birthStart = performance.now();
340
362
  try {
341
363
  ensureDaemon();
342
364
  }
@@ -567,6 +589,8 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
567
589
  // Mac needs, so the node is never left dormant for the lifecycle tick to wake.
568
590
  const machine = opts.start === true ? await remoteMachineEnvironmentOf(meta.profile_id ?? null) : null;
569
591
  if (machine !== null) {
592
+ // Billing admission, node creation, goal write, birth hooks and the broker invocation are done; the start steps follow.
593
+ addStepTiming('birth', performance.now() - birthStart);
570
594
  const started = await startOnMachine(meta, machine, inv);
571
595
  if (started === 'started' || started === 'uncertain')
572
596
  return { node: meta, frozen: false, window: null, session: null };
@@ -575,6 +599,15 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
575
599
  emitEvent({ level: 'info', event: 'broker.frozen', node_id: meta.node_id, fields: { reason: 'remote_environment' } });
576
600
  return { node: { ...meta, frozen_at: frozenAt }, frozen: true, window: null, session: null };
577
601
  }
602
+ // Here the broker would start on this host. On a cloud role that is the control plane's own pod, never a person's machine: a profile
603
+ // with no environment and a directory this host does not have names a path from the person's computer, so fail with that reason.
604
+ if (isCloudRole() && !existsSync(meta.cwd)) {
605
+ throw new InputError({
606
+ error: 'profile_environment_missing',
607
+ message: `${meta.cwd} does not exist on the control plane, and profile ${meta.profile_id ?? '(none)'} has no environment to run it in.`,
608
+ next: 'Bind the profile to the environment of the computer that holds this directory, then retry.',
609
+ });
610
+ }
578
611
  const slot = await fleet.reserveSlot(meta.node_id);
579
612
  // The slot is held while the launcher measures the app's memory; a denial gives it back before freezing.
580
613
  const memory = slot ? await admitBrokerMemory(meta.node_id) : null;
@@ -0,0 +1,37 @@
1
+ // step-timings.ts — step durations of one control plane request, returned to its caller in a `Server-Timing` header.
2
+ // The client prints them through `markServerTiming` in timing.ts.
3
+ //
4
+ // The control plane's logs may not be readable by the person who made a request, so the steps of one request are returned to them in a
5
+ // `Server-Timing` response header. A request opts in by running inside `collectStepTimings`; `timedStep` / `addStepTiming` record nothing
6
+ // outside one. Names and durations only: never a token, secret, env value or document body.
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ const stepTimings = new AsyncLocalStorage();
9
+ /** Run `fn`, collecting the steps recorded beneath it. */
10
+ export async function collectStepTimings(fn) {
11
+ const steps = [];
12
+ const value = await stepTimings.run({ steps, start: performance.now() }, fn);
13
+ return { value, steps };
14
+ }
15
+ /** Record a step's duration in ms, when a request is collecting. */
16
+ export function addStepTiming(name, ms) {
17
+ stepTimings.getStore()?.steps.push([name, ms]);
18
+ }
19
+ /** ms since the collection began (0 outside one). */
20
+ export function sinceCollectionStart() {
21
+ const store = stepTimings.getStore();
22
+ return store === undefined ? 0 : performance.now() - store.start;
23
+ }
24
+ /** Run `fn` and record how long it took under `name`, whether it returns or throws. */
25
+ export async function timedStep(name, fn) {
26
+ const start = performance.now();
27
+ try {
28
+ return await fn();
29
+ }
30
+ finally {
31
+ addStepTiming(name, performance.now() - start);
32
+ }
33
+ }
34
+ /** The `Server-Timing` header value for these steps: `name;dur=<ms>` joined by commas. */
35
+ export function serverTimingHeader(steps) {
36
+ return steps.map(([name, ms]) => `${name};dur=${ms.toFixed(1)}`).join(', ');
37
+ }
@@ -18,6 +18,7 @@
18
18
  //
19
19
  // Off by default and effectively free when off: one env read, one comparison.
20
20
  // Output goes to stderr only — never stdout, which is the CLI's data contract.
21
+ import { onServerTiming } from '../api/server-timing.js';
21
22
  const FLAG = 'CRTR_TIMING';
22
23
  const ORIGIN = 'CRTR_TIMING_T0';
23
24
  /** Wall-clock epoch ms with sub-ms precision, comparable across processes. */
@@ -92,3 +93,16 @@ export function mark(phase, fields) {
92
93
  // what lets its markers be merged into the cli/viewer timeline after the fact.
93
94
  process.stderr.write(`[timing] +${fmt(since)}ms Δ${fmt(delta)}ms up=${fmt(up)}ms t=${abs.toFixed(1)} ${name}/${process.pid} ${phase}${tail}\n`);
94
95
  }
96
+ // The server side that produces the `Server-Timing` header is in step-timings.ts (it needs node:async_hooks, which the API client must not import).
97
+ /** Print each step of a response's `Server-Timing` header as a phase marker (`server.<name>`). */
98
+ export function markServerTiming(header) {
99
+ if (!enabled)
100
+ return;
101
+ for (const part of header.split(',')) {
102
+ const [name, ...params] = part.trim().split(';');
103
+ const dur = params.find((p) => p.startsWith('dur='))?.slice(4);
104
+ if (name !== undefined && name !== '' && dur !== undefined)
105
+ mark(`server.${name}`, { dur_ms: dur });
106
+ }
107
+ }
108
+ onServerTiming(markServerTiming);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.679",
3
+ "version": "0.3.681",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.679",
3
+ "version": "0.3.681",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.679",
3
+ "version": "0.3.681",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.679",
31
- "@north-light/identity": "0.3.679"
30
+ "@north-light/api": "0.3.681",
31
+ "@north-light/identity": "0.3.681"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.679",
3
+ "version": "0.3.681",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.679",
9
+ "version": "0.3.681",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.679",
32
- "@north-light/plugin": "0.3.679",
31
+ "@north-light/identity": "0.3.681",
32
+ "@north-light/plugin": "0.3.681",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.679",
10670
+ "version": "0.3.681",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.679",
10675
+ "version": "0.3.681",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.679",
10680
+ "version": "0.3.681",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.679",
10688
+ "version": "0.3.681",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.679",
10692
- "@north-light/identity": "0.3.679"
10691
+ "@north-light/api": "0.3.681",
10692
+ "@north-light/identity": "0.3.681"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.679",
10697
+ "version": "0.3.681",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.679",
10701
- "@north-light/identity": "0.3.679",
10702
- "@north-light/plugin": "0.3.679",
10700
+ "@north-light/api": "0.3.681",
10701
+ "@north-light/identity": "0.3.681",
10702
+ "@north-light/plugin": "0.3.681",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {
@@ -41,14 +41,7 @@ if ! id "$RUN_USER" >/dev/null 2>&1; then
41
41
  fi
42
42
  mkdir -p /run/crtr /var/lib/crtr /work "$RELEASES"
43
43
  chown "$RUN_USER" /run/crtr /var/lib/crtr /work
44
- # Blaxel's image conversion makes every file of a built image root-owned whatever the Dockerfile chowns, so git would refuse /work ("dubious ownership")
45
- # and `crtr` could not write node_modules, its home or the Postgres data directory. Hand the trees over here, still as root, once per sandbox
46
- # (the marker is in the sandbox's own filesystem, so a later start skips the recursive chown).
47
- if [ ! -e "$ROOT/.owned" ]; then
48
- for dir in /work "/home/$RUN_USER" /var/lib/crtr; do [ ! -e "$dir" ] || chown -R "$RUN_USER:$RUN_USER" "$dir"; done
49
- if id postgres >/dev/null 2>&1 && [ -d /var/lib/postgresql ]; then chown -R postgres /var/lib/postgresql; fi
50
- mkdir -p "$ROOT" && : > "$ROOT/.owned"
51
- fi
44
+ [ ! -d "/home/$RUN_USER" ] || chown "$RUN_USER" "/home/$RUN_USER"
52
45
  # pi's grep tool wants ripgrep; the release image has it, and installing it once per sandbox avoids a GitHub download at the first grep.
53
46
  rg=present
54
47
  if ! command -v rg >/dev/null 2>&1; then