@north-light/cli 0.3.693 → 0.3.695

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 (208) hide show
  1. package/README.md +4 -7
  2. package/dist/api/command-manifest/result.d.ts +5 -5
  3. package/dist/api/command-manifest/result.js +1 -1
  4. package/dist/api/contract.d.ts +1 -1
  5. package/dist/api/contract.js +1 -1
  6. package/dist/api/dto/run-events.d.ts +1 -0
  7. package/dist/api/dto/run-events.js +1 -0
  8. package/dist/api/dto/worktree.d.ts +0 -4
  9. package/dist/api/errors.js +1 -1
  10. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  11. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
  12. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
  13. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  14. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  15. package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
  16. package/dist/builtin-memory/crouter-sdk/README.md +14 -42
  17. package/dist/builtin-memory/crouter-sdk/client.md +5 -7
  18. package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
  19. package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
  20. package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
  21. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  22. package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
  23. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
  24. package/dist/cli.js +6 -6
  25. package/dist/clients/attach/session/connection.d.ts +11 -2
  26. package/dist/clients/attach/session/connection.js +1 -1
  27. package/dist/clients/attach/session/keys.d.ts +2 -0
  28. package/dist/clients/attach/session/keys.js +1 -1
  29. package/dist/clients/attach/session/pane-tag.d.ts +3 -3
  30. package/dist/clients/attach/session/reconnect.js +1 -1
  31. package/dist/clients/attach/viewer.js +538 -537
  32. package/dist/commands/node/inspect.js +9 -9
  33. package/dist/commands/node-worktree.js +1 -1
  34. package/dist/commands/pkg/market-manage.js +1 -1
  35. package/dist/commands/pkg/plugin-manage.js +1 -1
  36. package/dist/commands/surface/node/placement.d.ts +2 -2
  37. package/dist/commands/surface/node/placement.js +1 -1
  38. package/dist/commands/surface.js +1 -1
  39. package/dist/commands/sys/update.js +1 -1
  40. package/dist/core/broker-client/client.d.ts +6 -9
  41. package/dist/core/broker-client/client.js +1 -1
  42. package/dist/core/canvas/canvas.js +7 -7
  43. package/dist/core/canvas/types.d.ts +0 -2
  44. package/dist/core/config.js +1 -1
  45. package/dist/core/conversation-store/row-store.js +10 -10
  46. package/dist/core/graph/exposures.js +1 -1
  47. package/dist/core/graph/names.js +9 -9
  48. package/dist/core/graph/watches.js +1 -1
  49. package/dist/core/installed-plugins.js +1 -1
  50. package/dist/core/keybindings/attach-control.d.ts +3 -0
  51. package/dist/core/keybindings/attach-control.js +1 -1
  52. package/dist/core/keybindings/catalog.js +1 -1
  53. package/dist/core/ledger/chunks.d.ts +3 -1
  54. package/dist/core/ledger/chunks.js +2 -2
  55. package/dist/core/ledger/index.d.ts +1 -1
  56. package/dist/core/ledger/index.js +1 -1
  57. package/dist/core/ledger/read.d.ts +4 -0
  58. package/dist/core/ledger/read.js +2 -2
  59. package/dist/core/llm/run.js +2 -2
  60. package/dist/core/logged-step-timings.d.ts +7 -0
  61. package/dist/core/logged-step-timings.js +1 -0
  62. package/dist/core/permissions/evaluator.d.ts +2 -1
  63. package/dist/core/permissions/evaluator.js +2 -2
  64. package/dist/core/providers/receipts.js +1 -1
  65. package/dist/core/runs/operations.js +8 -8
  66. package/dist/core/runtime/broker/model-adapter.js +3 -3
  67. package/dist/core/runtime/broker.js +1 -1
  68. package/dist/core/runtime/nodes.d.ts +1 -1
  69. package/dist/core/runtime/nodes.js +1 -1
  70. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  71. package/dist/core/runtime/placement-tmux.js +1 -1
  72. package/dist/core/runtime/revive.js +2 -2
  73. package/dist/core/runtime/runner/machine/ops.d.ts +2 -7
  74. package/dist/core/runtime/runner/machine/ops.js +1 -1
  75. package/dist/core/runtime/runner/machine/runner.d.ts +0 -2
  76. package/dist/core/runtime/runner/machine/runner.js +1 -1
  77. package/dist/core/runtime/tmux-bindings.js +3 -3
  78. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  79. package/dist/core/runtime/tmux-driver.js +6 -6
  80. package/dist/core/scoped-state/imported-mac-installs.d.ts +12 -0
  81. package/dist/core/scoped-state/imported-mac-installs.js +2 -0
  82. package/dist/core/spaces/stop.js +1 -1
  83. package/dist/core/step-timings.d.ts +7 -1
  84. package/dist/core/step-timings.js +1 -1
  85. package/dist/core/worktree-close.js +4 -6
  86. package/dist/core/worktree-landing.d.ts +0 -38
  87. package/dist/core/worktree-landing.js +2 -3
  88. package/dist/core/worktree-sweep.d.ts +0 -1
  89. package/dist/core/worktree-sweep.js +4 -6
  90. package/dist/core/worktree.d.ts +0 -4
  91. package/dist/core/worktree.js +13 -15
  92. package/dist/daemon/api/app-listener.d.ts +1 -0
  93. package/dist/daemon/api/app-listener.js +10 -10
  94. package/dist/daemon/api/bridge.js +4 -4
  95. package/dist/daemon/api/handlers/attach.js +1 -1
  96. package/dist/daemon/api/handlers/conversations.js +3 -3
  97. package/dist/daemon/api/server.d.ts +1 -1
  98. package/dist/daemon/api/server.js +1 -1
  99. package/dist/daemon/cron/armed-context.js +1 -1
  100. package/dist/daemon/crtrd.js +20 -18
  101. package/dist/daemon/machine-link/client.d.ts +5 -1
  102. package/dist/daemon/machine-link/client.js +1 -1
  103. package/dist/daemon/machine-link/forward.js +1 -1
  104. package/dist/daemon/machine-link/holder.js +3 -3
  105. package/dist/daemon/pidfile.js +2 -1
  106. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  107. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  108. package/dist/daemon/runs/append-section.js +2 -2
  109. package/dist/daemon/runs/observer.js +3 -3
  110. package/dist/shared/env.d.ts +8 -3
  111. package/dist/shared/env.js +2 -2
  112. package/dist/types.d.ts +1 -1
  113. package/dist/types.js +1 -1
  114. package/docs/apps/guides/stream-a-run.md +6 -7
  115. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  116. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  117. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  118. package/docs/concepts/scopes-and-trust.md +1 -1
  119. package/docs/concepts/why-a-daemon.md +1 -1
  120. package/docs/sdk/README.md +13 -41
  121. package/docs/sdk/client.md +5 -7
  122. package/docs/sdk/docker.md +1 -1
  123. package/docs/sdk/errors.md +3 -43
  124. package/docs/sdk/getting-started.md +11 -83
  125. package/docs/sdk/release-notes.md +10 -0
  126. package/docs/sdk/resources.md +11 -44
  127. package/package.json +3 -3
  128. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  129. package/packages/crouter-api/dist/api/contract.js +1 -1
  130. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  131. package/packages/crouter-api/dist/api/errors.js +1 -1
  132. package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
  133. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  134. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  135. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  136. package/packages/crouter-api/dist/commands/node/inspect.js +16 -2
  137. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  138. package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
  139. package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
  140. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  141. package/packages/crouter-api/dist/commands/surface.js +2 -3
  142. package/packages/crouter-api/dist/commands/sys/update.js +5 -3
  143. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  144. package/packages/crouter-api/dist/core/canvas/canvas.js +6 -11
  145. package/packages/crouter-api/dist/core/config.js +10 -3
  146. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  147. package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
  148. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  149. package/packages/crouter-api/dist/core/graph/watches.js +1 -1
  150. package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
  151. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  152. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  153. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  154. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  155. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  156. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  157. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  158. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  159. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  160. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  161. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  162. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  163. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  164. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  165. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  166. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +4 -24
  167. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  168. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  169. package/packages/crouter-api/dist/core/scoped-state/imported-mac-installs.js +94 -0
  170. package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
  171. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  172. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  173. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  174. package/packages/crouter-api/dist/core/worktree.js +9 -74
  175. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  176. package/packages/crouter-api/dist/daemon/machine-link/forward.js +13 -2
  177. package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -0
  178. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  179. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  180. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  181. package/packages/crouter-api/dist/shared/env.js +15 -4
  182. package/packages/crouter-api/dist/types.js +1 -1
  183. package/packages/crouter-api/package.json +1 -1
  184. package/packages/crouter-identity/package.json +1 -1
  185. package/packages/crouter-plugin/dist/serve.js +1 -1
  186. package/packages/crouter-plugin/package.json +3 -3
  187. package/runtime.lock.json +14 -14
  188. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  189. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  190. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  191. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  192. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  193. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  194. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  195. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  196. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  197. package/dist/commands/surface-reload.d.ts +0 -7
  198. package/dist/commands/surface-reload.js +0 -1
  199. package/docs/sdk/bash.md +0 -39
  200. package/docs/sdk/files.md +0 -49
  201. package/docs/sdk/guides/README.md +0 -17
  202. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  203. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  204. package/docs/sdk/guides/human-approval.md +0 -24
  205. package/docs/sdk/guides/typed-extraction.md +0 -24
  206. package/docs/sdk/nodes.md +0 -194
  207. package/docs/sdk/streaming.md +0 -149
  208. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -13,11 +13,12 @@ import { listDirs, pathExists, readJsonIfExists } from './fs-utils.js';
13
13
  import { readPluginManifest } from './manifest.js';
14
14
  import { awaitBundleSwap, bundleSwapInFlightElsewhere } from './plugin-swap-lock.js';
15
15
  import { isCloudRole } from './canvas/person-state.js';
16
- import { readCachedSettings } from './scoped-state/person-store.js';
16
+ import { currentSnapshot, readCachedSettings } from './scoped-state/person-store.js';
17
+ import { importedIntoNorthlight, withAppInstalls } from './scoped-state/imported-mac-installs.js';
17
18
  import { pluginsDir } from './scope.js';
18
19
  function pluginConfigForRoot(scope, root) {
19
20
  const cfg = scope === 'user'
20
- ? readCachedSettings('user').settings
21
+ ? (importedIntoNorthlight() ? withAppInstalls(currentSnapshot(), readCachedSettings('user').settings) : readCachedSettings('user').settings)
21
22
  : readJsonIfExists(join(root, CONFIG_FILE));
22
23
  return cfg && cfg.plugins && typeof cfg.plugins === 'object' ? cfg.plugins : {};
23
24
  }
@@ -12,6 +12,7 @@ export const ATTACH_CONTROL_BINDINGS = [
12
12
  { menuId: 'crtr.tmux.menu.attach.profile-files', actionId: 'crtr.attach.profile-files' },
13
13
  { menuId: 'crtr.tmux.menu.attach.search', actionId: 'crtr.attach.search' },
14
14
  { menuId: 'crtr.tmux.menu.attach.whip', actionId: 'crtr.attach.whip' },
15
+ { menuId: 'crtr.tmux.menu.attach.reload-viewer', actionId: 'crtr.attach.reload-viewer' },
15
16
  ];
16
17
  const ATTACH_CONTROL_PREFIX = '\x1b_crtr;';
17
18
  const ATTACH_CONTROL_SUFFIX = '\x1b\\';
@@ -69,7 +69,7 @@ export const BINDING_CATALOG = Object.freeze([
69
69
  ...menuEntry('graph', 'Canvas graph', 'Open the canvas graph.', ['g'], ['tmux.menu']),
70
70
  ...menuEntry('focus-manager', 'Go to manager', 'Focus this node’s manager.', ['h'], ['tmux.menu']),
71
71
  ...menuEntry('copy-id', 'Copy node id', 'Copy the focused node id to the system clipboard.', ['y'], ['tmux.menu']),
72
- ...menuEntry('reload-viewer', 'Reload viewer', 'Respawn this pane’s viewer onto the current runtime generation.', ['r'], ['tmux.menu']),
72
+ ...menuEntry('reload-viewer', 'Reload viewer', 'Restart this pane’s viewer in place on the installed release, keeping its flags and unsent draft.', ['r'], ['tmux.menu']),
73
73
  ...menuEntry('recap', 'Generate recap', 'Generate the focused node’s Goal and State recap and refresh its generated title.', ['s'], ['tmux.menu']),
74
74
  ...menuEntry('issues', 'Open create menu', 'Open the create submenu.', ['c'], ['tmux.menu']),
75
75
  ...menuEntry('issue.idea', 'Create idea', 'Create an idea issue.', ['i'], ['tmux.menu.issue']),
@@ -89,6 +89,7 @@ export const BINDING_CATALOG = Object.freeze([
89
89
  ...attachEntry('crtr.tmux.menu.attach.file-review', 'crtr.attach.file-review', 'Review a file', 'Open a line-anchored review of a file named in the transcript.', [], ['alt+shift+r']),
90
90
  ...attachEntry('crtr.tmux.menu.attach.profile-files', 'crtr.attach.profile-files', 'Search profile files', 'Fuzzy-match path segments across the node family’s working directories, their context directories (files), profile projects and the profile’s own directory; Ctrl+Y copies a selected path.', ['f'], ['ctrl+f']),
91
91
  ...attachEntry('crtr.tmux.menu.attach.search', 'crtr.attach.search', 'Search transcript', 'Search the transcript as it is currently displayed — folded tool output is not searched until it is unfolded.', ['/'], ['alt+/']),
92
+ ...attachEntry('crtr.tmux.menu.attach.reload-viewer', 'crtr.attach.reload-viewer', 'Reload viewer', 'Restart this viewer in place on the installed release.', [], []),
92
93
  ...attachEntry('crtr.tmux.menu.attach.whip', 'crtr.attach.whip', 'Whip agent', 'Interrupt the agent and send a playful command.', ['w'], []),
93
94
  b('crtr.attach.scroll.up', 'Attach', 'Scroll up', 'Scroll the transcript one line up.', ['shift+up'], 'terminal', ATTACH_CONTEXTS),
94
95
  b('crtr.attach.scroll.down', 'Attach', 'Scroll down', 'Scroll the transcript one line down.', ['shift+down'], 'terminal', ATTACH_CONTEXTS),
@@ -6,8 +6,12 @@ import { blobStore } from '../blobs/index.js';
6
6
  import { openDb } from '../canvas/db.js';
7
7
  import { chargeOf } from './charges.js';
8
8
  const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source'];
9
- /** The moved rows of a month (or of every month), read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
9
+ /** The moved rows of a month (or of every month), from month `since` on, read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
10
10
  export class ChunkRows {
11
+ since;
12
+ constructor(since = '0000-00') {
13
+ this.since = since;
14
+ }
11
15
  byMonth = new Map();
12
16
  all;
13
17
  rows(month) {
@@ -21,8 +25,8 @@ export class ChunkRows {
21
25
  return found;
22
26
  }
23
27
  async load(month) {
24
- const chunks = await (await openDb()).prepareUncached(`SELECT blob_key FROM charge_chunks${month === undefined ? '' : ' WHERE month = ?'} ORDER BY month, payer`)
25
- .all(...(month === undefined ? [] : [month]));
28
+ const chunks = await (await openDb()).prepareUncached(`SELECT blob_key FROM charge_chunks WHERE month >= ?${month === undefined ? '' : ' AND month = ?'} ORDER BY month, payer`)
29
+ .all(this.since, ...(month === undefined ? [] : [month]));
26
30
  if (chunks.length === 0)
27
31
  return [];
28
32
  const store = await blobStore();
@@ -5,6 +5,6 @@ export { payerOf } from './payer.js';
5
5
  export { writeCharge, receiptChargeId, chargeOf } from './charges.js';
6
6
  export { check, findRefusal, refusalError, refusedMark, userActionOf } from './check.js';
7
7
  export { upsertLimit, deleteLimit, listLimits } from './limits.js';
8
- export { usageFor, listCharges, monthTotals, assertReference } from './read.js';
8
+ export { usageFor, runUsage, listCharges, monthTotals, assertReference } from './read.js';
9
9
  export { REBUILD_ALL_TOTALS, rebuildTotalsFor } from './totals.js';
10
10
  export { appsHeldBy } from './account.js';
@@ -2,6 +2,7 @@
2
2
  // Everything here reads this runtime only.
3
3
  import { openDb } from '../canvas/db.js';
4
4
  import { subjectSet } from '../permissions/evaluator.js';
5
+ import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
5
6
  import { RunError } from '../runs/operations.js';
6
7
  import { appsHeldBy } from './account.js';
7
8
  import { chargeOf } from './charges.js';
@@ -118,7 +119,7 @@ function decodeCursor(cursor) {
118
119
  * is given), otherwise the month's rows (default the current month). */
119
120
  export async function listCharges(filter = {}) {
120
121
  const limit = Math.min(Math.max(Math.trunc(filter.limit ?? 1000), 1), 10_000);
121
- const chunks = new ChunkRows();
122
+ const chunks = new ChunkRows(filter.since);
122
123
  const conditions = [];
123
124
  const params = [];
124
125
  const tests = [];
@@ -164,6 +165,22 @@ export async function listCharges(filter = {}) {
164
165
  const charges = filter.under !== undefined && filter.reader !== undefined ? await visibleChain(page, filter.reader, chunks) : page;
165
166
  return { charges, next: rows.length > limit ? encodeCursor(page[limit - 1]) : null };
166
167
  }
168
+ /** A run's usage, summed from the rows under `run:<id>` when read (refused and take rows excluded): the ledger is its only copy. */
169
+ export async function runUsage(runId) {
170
+ const usage = { ...ZERO_RUN_USAGE }, since = (await (await openDb()).prepare('SELECT created FROM nodes WHERE node_id = ?').get(runId))?.created.slice(0, 7);
171
+ for (let page; page === undefined || page.next !== null;) {
172
+ page = await listCharges({ under: `run:${runId}`, since, limit: 10_000, ...(page?.next ? { after: page.next } : {}) });
173
+ for (const row of page.charges.filter((charge) => charge.refused === null && charge.kind !== 'take')) {
174
+ const units = (row.kind === 'model' ? row.units ?? {} : {});
175
+ usage.input_tokens += units.input ?? 0;
176
+ usage.output_tokens += units.output ?? 0;
177
+ usage.cache_read_tokens += units.cache_read ?? 0;
178
+ usage.cache_write_tokens += units.cache_write ?? 0;
179
+ usage.cost_usd += Number(row.usd ?? 0);
180
+ }
181
+ }
182
+ return usage;
183
+ }
167
184
  /** The payers a `user:<id>` answers for: itself, and every app held (`ledger_holder`) by it or by a team it belongs to. */
168
185
  export async function payersOf(owner) {
169
186
  const db = await openDb();
@@ -530,7 +530,7 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
530
530
  // When the endpoint's admission row (id `admission:<id>`) is already in this ledger, this insert is a no-op. Otherwise it is the only row
531
531
  // the local `grant:<id>` limit can count, so it carries the list-price amount: a null usd rolls up as zero and the cap never refuses.
532
532
  if (spend !== undefined && paid !== null) {
533
- await writeCharge({ id: chargeId, request: spend.request ?? id, kind: 'model', what: answered, usd: usage.usd_equivalent, payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, node: spend.node ?? null, run: spend.run ?? null, provider, causedBy: await causeOf(), vendorRef });
533
+ await writeCharge({ id: chargeId, request: spend.request ?? id, kind: 'model', what: answered, units: { input: completed.usage.input, output: completed.usage.output, cache_read: completed.usage.cacheRead, cache_write: completed.usage.cacheWrite }, usd: usage.usd_equivalent, payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, node: spend.node ?? null, run: spend.run ?? null, provider, causedBy: await causeOf(), vendorRef });
534
534
  }
535
535
  }
536
536
  else if (spend !== undefined && paid !== null) {
@@ -0,0 +1,52 @@
1
+ // logged-step-timings.ts — step timings of a request nobody on the calling side reads (the broker's conversation POST, the machine link, a viewer's
2
+ // WebSocket upgrade), written to the process's own event log as one `daemon.timing.<name>` event. Same recorder as step-timings.ts, so the same
3
+ // `timedStep` / `addStepTiming` calls feed both the `Server-Timing` header and this log. Names, durations in ms and byte counts only.
4
+ // Read on the machine that ran it: `crtr sys logs --component daemon --pattern daemon.timing.`
5
+ import { emitEvent } from './events/emit.js';
6
+ import { addStepTiming, collectStepTimings, receiptOf, sinceCollectionStart } from './step-timings.js';
7
+ /** Run `fn`, then log every step recorded beneath it as `daemon.timing.<name>`. `duration_ms` runs from when the listener received `req` to the end of `fn`;
8
+ * `handler_ms` is `fn` alone, `auth_ms` is receipt to the end of authentication. A step named `refused_status` marks a refused upgrade as failed. `fields` are identifiers and counts. */
9
+ export async function withLoggedStepTimings(name, fields, req, fn) {
10
+ const { receivedAt, authenticatedAt } = receiptOf(req);
11
+ const start = performance.now();
12
+ const steps = [];
13
+ let threw = true;
14
+ try {
15
+ const value = await collectStepTimings(fn, steps).then((collected) => collected.value);
16
+ threw = false;
17
+ return value;
18
+ }
19
+ finally {
20
+ const end = performance.now();
21
+ const stepFields = {
22
+ ...(authenticatedAt === undefined ? {} : { auth_ms: authenticatedAt - receivedAt, authenticated_to_handler_ms: start - authenticatedAt }),
23
+ receive_to_handler_ms: start - receivedAt,
24
+ handler_ms: end - start,
25
+ };
26
+ for (const [step, ms] of steps) {
27
+ let key = step;
28
+ for (let n = 2; key in stepFields; n++)
29
+ key = `${step}_${n}`;
30
+ stepFields[key] = ms;
31
+ }
32
+ for (const key of Object.keys(stepFields))
33
+ stepFields[key] = Math.round(stepFields[key] * 10) / 10;
34
+ const failed = threw || steps.some(([step]) => step === 'refused_status');
35
+ emitEvent({ level: 'info', event: `daemon.timing.${name}`, duration_ms: end - receivedAt, outcome: failed ? 'failed' : 'succeeded', fields: { ...fields, ...stepFields } });
36
+ }
37
+ }
38
+ /** Run `fn` and record when it began (ms since collection began, `<name>_begin_at`) and how long it took (`<name>_ms`), whether it returns or throws. */
39
+ export async function timedSpan(name, fn) {
40
+ addStepTiming(`${name}_begin_at`, sinceCollectionStart());
41
+ const start = performance.now();
42
+ try {
43
+ return await fn();
44
+ }
45
+ finally {
46
+ addStepTiming(`${name}_ms`, performance.now() - start);
47
+ }
48
+ }
49
+ /** Record that a point was reached: ms since collection began, as `<name>_at`. */
50
+ export function markAt(name) {
51
+ addStepTiming(`${name}_at`, sinceCollectionStart());
52
+ }
@@ -73,11 +73,25 @@ export async function permits(db, reader, permission, alias = 'o', options = {})
73
73
  }
74
74
  const schemaPart = cases.length === 0 ? f `(CASE WHEN ${raw(alias)}.schema_type IS NULL THEN ${builtin} ELSE FALSE END)`
75
75
  : f `(CASE WHEN ${raw(alias)}.schema_type IS NULL THEN ${builtin} ${{ sql: cases.map((c) => c.sql).join(' '), params: cases.flatMap((c) => c.params) }} ELSE FALSE END)`;
76
- const ceiling = await resolveCeiling(db, ev.reader, ev.userId, ACCESS[permission], options);
76
+ const ceiling = await ceilingOf(db, ev, ACCESS[permission], options);
77
77
  if (ceiling === null)
78
78
  return schemaPart;
79
79
  return and([ceilingFrag(ceiling, alias), schemaPart]);
80
80
  }
81
+ const ceilings = new WeakMap();
82
+ export function ceilingOf(db, ev, access, options = {}) {
83
+ let m = ceilings.get(ev.reader);
84
+ if (m === undefined)
85
+ ceilings.set(ev.reader, m = new Map());
86
+ const k = `${access} ${options.verb ?? ''} ${ev.userId} ${ev.subjects.groupIds.join(',')}`;
87
+ let c = m.get(k);
88
+ if (c === undefined) {
89
+ c = resolveCeiling(db, ev.reader, ev.userId, access, options);
90
+ m.set(k, c);
91
+ c.catch(() => m.delete(k));
92
+ }
93
+ return c;
94
+ }
81
95
  async function ownNamespaceTypes(db, appObjectId) {
82
96
  const rows = await db.prepare(`SELECT s.namespace FROM schemas s JOIN identities i ON i.external_id = s.app AND i.scheme = 'app' WHERE i.object = ?`).all(appObjectId);
83
97
  return new Set(rows.map((r) => r.namespace));
@@ -41,20 +41,9 @@ export async function acceptProviderReceipt(value, call) {
41
41
  await withCanvasWrite(async (db) => {
42
42
  for (const receipt of accepted) {
43
43
  // One row per receipt, keyed by (provider, receipt id): a repeat delivery writes nothing and adds nothing.
44
- const { written } = await writeCharge({ id: receiptChargeId(call.provider, receipt.receipt_id), request: call.request_id, kind: 'tool', what: `${call.provider}:${call.tool}`,
44
+ await writeCharge({ id: receiptChargeId(call.provider, receipt.receipt_id), request: call.request_id, kind: 'tool', what: `${call.provider}:${call.tool}`,
45
45
  units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub,
46
46
  grantee: call.ledger_grantee ?? call.grantee, node: call.node_id, run: call.run_id, provider: `app:${call.provider}`, causedBy: call.caused_by, vendorRef: receipt.receipt_id });
47
- if (!written)
48
- continue;
49
- if (!call.run_id)
50
- continue;
51
- const root = await db.prepare('SELECT usage_json FROM nodes WHERE node_id = ? AND run_id = ?')
52
- .get(call.run_id, call.run_id);
53
- if (!root)
54
- continue;
55
- const usage = root.usage_json ? JSON.parse(root.usage_json) : {};
56
- usage['cost_usd'] = (typeof usage['cost_usd'] === 'number' ? usage['cost_usd'] : 0) + receipt.usd_equivalent;
57
- await db.prepare('UPDATE nodes SET usage_json = ? WHERE node_id = ?').run(JSON.stringify(usage), call.run_id);
58
47
  }
59
48
  });
60
49
  return accepted[0].receipt_id;
@@ -34,6 +34,8 @@ import { isPortableModelToken } from '../runtime/launch.js';
34
34
  import { parseDurationMs } from '../wake.js';
35
35
  import { expandModelCandidates, parseModelSpec } from '../model-routes.js';
36
36
  import { payerOfGrant } from '../grants/mirror.js';
37
+ import { runUsage } from '../ledger/read.js';
38
+ import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
37
39
  import { isolatedBrokerLauncherAvailable } from '../runtime/host.js';
38
40
  import { blaxelEnvironmentOf } from '../runtime/blaxel-environment.js';
39
41
  import { resolveRunKind, resolveRunModel } from '../runtime/launch-target.js';
@@ -80,7 +82,6 @@ export class RunError extends Error {
80
82
  }
81
83
  const invalid = (message, param) => new RunError(400, 'invalid_request', message, param);
82
84
  const missing = () => new RunError(404, 'not_found', 'run not found');
83
- const usage = () => ({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 });
84
85
  const db = async () => await openDb();
85
86
  export async function ownedRun(id, grantee, allowDeleting = false) {
86
87
  const node = await getNode(id);
@@ -139,7 +140,7 @@ export async function runObject(root) {
139
140
  ...(result === undefined ? {} : { result }),
140
141
  ...(report !== undefined ? { last_report: report } : {}), ...(recap ? { recap } : {}), pending_question_ids: pending, open_notice_ids: status === 'settled' ? [] : await openNoticeIds(root.node_id),
141
142
  ...(root.last_turn_error_json ? { last_turn_error: JSON.parse(root.last_turn_error_json) } : {}),
142
- usage: JSON.parse(root.usage_json ?? JSON.stringify(usage())), payer: await payerOfGrant(root.grant_id), scopes: root.scopes,
143
+ usage: await runUsage(root.node_id), payer: await payerOfGrant(root.grant_id), scopes: root.scopes,
143
144
  metadata: root.metadata_json ? JSON.parse(root.metadata_json) : {}, created_at: root.created,
144
145
  ...(status === 'settled' && root.outcome_at ? { settled_at: root.outcome_at } : {}), latest_sequence: (root.event_cursor ?? 1) - 1,
145
146
  last_activity_at: root.last_activity_at, activity: await runActivity(root.node_id, status),
@@ -335,7 +336,7 @@ export async function startRun(principal, input, idempotencyKey, resolveAttachme
335
336
  ...(input.deadline === undefined ? {} : { deadlineAt: new Date(Date.now() + parseRunDeadlineMs(input.deadline)).toISOString() }),
336
337
  ...(input.scopes === null ? {} : { scopes: input.scopes }),
337
338
  run: { grantee: principal.grantee, sub: principal.sub, grant_id: principal.grant, client_id: principal.client_id,
338
- metadata_json: JSON.stringify(input.metadata), run_id: runId, event_cursor: 1, usage_json: JSON.stringify(usage()) },
339
+ metadata_json: JSON.stringify(input.metadata), run_id: runId, event_cursor: 1 },
339
340
  withinCreate: async (tx, row) => {
340
341
  // A concurrent start under this key may have committed while this one fetched attachments and awaited the
341
342
  // spawn: re-check on the transaction before any write, so exactly one start creates the run.
@@ -351,7 +352,7 @@ export async function startRun(principal, input, idempotencyKey, resolveAttachme
351
352
  await insertUploadUses(uses.map(({ upload_id, path, blob_key }) => ({ upload_id, path, blob_key, run_id: runId })), tx);
352
353
  }
353
354
  response = { run_id: runId, node_id: runId, grantee: principal.grantee, grant: principal.grant, rev: principal.rev, scopes: input.scopes, payer, status: 'running', created_at: row.created, metadata: input.metadata, sequence_number: 0 };
354
- await appendRunEvent(tx, runId, runId, 'run.started', { scopes: input.scopes, payer, usage: usage() });
355
+ await appendRunEvent(tx, runId, runId, 'run.started', { scopes: input.scopes, payer, usage: ZERO_RUN_USAGE });
355
356
  if (firstMessage) {
356
357
  const accepted = await acceptRunMessage(tx, runId, principal.grantee, principal.sub, firstMessage, false);
357
358
  response.message = { run_id: runId, message_id: accepted.messageId, sequence_number: accepted.sequence };
@@ -179,6 +179,15 @@ function parseRefusal(value) {
179
179
  throw new Error('llm returned an invalid refusal');
180
180
  return error;
181
181
  }
182
+ /** A model-call answer that is not JSON (an HTML error page from a server in between) means the model service is unavailable, which is retried. */
183
+ function parseAnswer(text) {
184
+ try {
185
+ return JSON.parse(text);
186
+ }
187
+ catch {
188
+ throw new UpstreamModelUnavailableError(`llm returned a non-JSON answer: ${text.slice(0, 120)}`);
189
+ }
190
+ }
182
191
  /** `Crtr-Caused-By: message:<id>` for the turn running now; nothing when the turn has no input message. */
183
192
  /** `/v1/llm` at `CRTR_API_URL` (the control plane, from a sandbox) or on the local API socket. */
184
193
  function llmUrl() {
@@ -280,8 +289,10 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
280
289
  });
281
290
  const response = await unwrapDeferredHead(fetched);
282
291
  if (!response.ok) {
283
- const error = parseRefusal(await response.json());
284
- if (response.status === 413 || error.code === 'payload_too_large')
292
+ if (response.status === 413)
293
+ throw contextTooLargeError(bytes, MODEL_CONTEXT_BODY_MAX_BYTES);
294
+ const error = parseRefusal(parseAnswer(await response.text()));
295
+ if (error.code === 'payload_too_large')
285
296
  throw contextTooLargeError(bytes, MODEL_CONTEXT_BODY_MAX_BYTES);
286
297
  applyServedModel(message, refusalRoute(error));
287
298
  if (error.retryable !== true)
@@ -318,7 +329,7 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
318
329
  let receivedUsage = false;
319
330
  let receivedServedModel = false;
320
331
  const apply = (line) => {
321
- const chunk = JSON.parse(line);
332
+ const chunk = parseAnswer(line);
322
333
  if (chunk.error) {
323
334
  // An error after headers still names the route that was serving: the
324
335
  // errored turn, and the fault recorded from it, belong to that route.
@@ -18,6 +18,7 @@ import { activeGrant, terminalGrant } from '../grants/mirror.js';
18
18
  import { callerPerson, nodeTerminalGrant } from '../grants/terminal.js';
19
19
  import { grantSnapshotMissing } from '../../daemon/readiness.js';
20
20
  import { appendRunEvent } from '../runs/events.js';
21
+ import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
21
22
  import { isCloudRole, personId } from '../canvas/person.js';
22
23
  import { InputError } from '../io.js';
23
24
  import { ApiError } from '../../api/errors.js';
@@ -319,7 +320,6 @@ export async function spawnNode(opts) {
319
320
  metadata_json: isRoot ? opts.run?.metadata_json ?? null : null,
320
321
  run_id: isRoot ? nodeId : opts.run?.run_id ?? null,
321
322
  event_cursor: isRoot ? opts.run?.event_cursor ?? 1 : null,
322
- usage_json: isRoot ? opts.run?.usage_json ?? JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 }) : null,
323
323
  passive_default: opts.passiveDefault ?? false,
324
324
  caused_by: opts.causedBy ?? null,
325
325
  ...(opts.managedWorktree !== undefined ? { managed_worktree: opts.managedWorktree } : {}),
@@ -494,7 +494,7 @@ export async function spawnNode(opts) {
494
494
  if (row.run_id && row.run_id !== row.node_id)
495
495
  await assertRunNotDeleting(db, row.run_id);
496
496
  if (isRoot && opts.run === undefined)
497
- await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: 'user', usage: JSON.parse(row.usage_json) });
497
+ await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: 'user', usage: ZERO_RUN_USAGE });
498
498
  await opts.withinCreate?.(db, row);
499
499
  await recordBirth(db, row);
500
500
  } }));
@@ -20,7 +20,7 @@ import { paneLocation, ensureSession, openNodeWindow, splitWindow, selectLayout,
20
20
  import { BROKER_VIEW_SOCKET_WAIT_MS } from './view-socket.js';
21
21
  // Re-export the pure tmux driver verbs the CLI/viewer consumers need without
22
22
  // exposing the canvas focuses table or sending command modules to the raw driver.
23
- export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, respawnPaneInPlace, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, panePid, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
23
+ export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
24
24
  export { installTmuxBindings } from './tmux-bindings.js';
25
25
  // view.sock readiness — the one shared broker-cold-start primitive
26
26
  export { BROKER_VIEW_SOCKET_WAIT_MS, waitForBrokerViewSocket } from './view-socket.js';
@@ -42,7 +42,7 @@ import { isCloudRole } from '../canvas/person.js';
42
42
  import { asNodePerson } from '../../daemon/reconcilers/node-lifecycle/node-person.js';
43
43
  import { processRunner } from './runner/process.js';
44
44
  import { runnerForEnvironment } from './runner/index.js';
45
- import { MachineLaunchUncertainError, MachineOfflineError } from './runner/machine/ops.js';
45
+ import { MachineOfflineError } from './runner/machine/ops.js';
46
46
  import { blaxelEnvironmentOf } from './blaxel-environment.js';
47
47
  import { recordLaunchFailure } from '../../daemon/reconcilers/node-lifecycle/launch-failure.js';
48
48
  import { acceptedRelease, remoteMachineEnvironmentOf, checkBilledWake, EnvironmentImagePending, imageForWake } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
@@ -679,7 +679,7 @@ async function launchRevive(nodeId, meta, opts) {
679
679
  }
680
680
  }
681
681
  catch (error) {
682
- // A machine with no live link started nothing: the node is not crashed, the caller leaves it dormant with its mail pending (the outer catch ends the execution).
682
+ // A machine call that failed (offline, or sent and unanswered) does not crash the node; the caller leaves it dormant with its mail pending (the outer catch ends the execution).
683
683
  if (error instanceof MachineOfflineError)
684
684
  throw error;
685
685
  try {
@@ -734,9 +734,9 @@ async function launchRevive(nodeId, meta, opts) {
734
734
  };
735
735
  }
736
736
  catch (error) {
737
- // A forwarded start whose outcome is unknown leaves its execution launching: the Mac may have spawned the broker, and the lifecycle
738
- // tick asks `status` of this execution after the link returns (adopt it when running, end it when gone) before any new one starts.
739
- if (error instanceof MachineLaunchUncertainError)
737
+ // A start sent to the Mac and unanswered leaves its execution launching: the Mac may have spawned the broker, and the lifecycle
738
+ // tick's `recoverLaunching` asks `status` of it once the link is back (running is adopted, gone is ended).
739
+ if (error instanceof MachineOfflineError && error.sent)
740
740
  throw error;
741
741
  await abortExecution(executionId, { reason: 'launch_failed' });
742
742
  // Best effort after the exit transition: a failed diagnostic write must neither leave the row live nor replace the launch error.
@@ -5,6 +5,7 @@ export class MachineOfflineError extends Error {
5
5
  environmentId;
6
6
  sent;
7
7
  code = 'machine_offline';
8
+ status = 503;
8
9
  /** True when the call was written to the link before it dropped: the machine may have run it. False: it ran nowhere. */
9
10
  constructor(environmentId, detail, sent = false) {
10
11
  super(`machine ${environmentId} is offline${detail ? `: ${detail}` : ''}`);
@@ -12,13 +13,7 @@ export class MachineOfflineError extends Error {
12
13
  this.sent = sent;
13
14
  }
14
15
  }
15
- /** A forwarded `start` whose outcome is unknown (link dropped or call lost): the execution stays `launching`, the caller never aborts it
16
- * and never starts another. After the link returns `status` of that execution decides: running is adopted, gone is ended. */
17
- export class MachineLaunchUncertainError extends MachineOfflineError {
18
- uncertain = true;
19
- constructor(environmentId, detail) { super(environmentId, detail, true); }
20
- }
21
- /** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The caller runs `status` before a new `start`. */
16
+ /** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The machine runner reports a lost `start` as offline after send. */
22
17
  export class MachineLostError extends Error {
23
18
  environmentId;
24
19
  callId;
@@ -9,7 +9,7 @@ import { openDb } from '../../../canvas/db.js';
9
9
  import { mintExecutionToken } from '../../../canvas/node-tokens.js';
10
10
  import { callMachine } from './call.js';
11
11
  import { machineEnvironmentOfProfile } from './environment.js';
12
- import { MachineLaunchUncertainError, MachineLostError, MachineOfflineError } from './ops.js';
12
+ import { MachineLostError, MachineOfflineError } from './ops.js';
13
13
  /** The machine environment of a node's profile, or null when the profile points at no machine environment. */
14
14
  export async function machineEnvironmentOfNode(nodeId) {
15
15
  const row = await (await openDb()).prepare('SELECT profile_id FROM nodes WHERE node_id = ?').get(nodeId);
@@ -21,7 +21,6 @@ const defaultEnvironmentOf = async (nodeId) => {
21
21
  throw new Error(`node ${nodeId} has no machine environment`);
22
22
  return environment;
23
23
  };
24
- const defaultTokenMinted = async (executionId) => await (await openDb()).prepare('SELECT 1 AS x FROM node_tokens WHERE broker_process_id = ?').get(executionId) !== undefined;
25
24
  const asError = (error) => error instanceof Error ? error : new Error(String(error));
26
25
  export function createMachineRunner(deps = {}) {
27
26
  const environmentOf = deps.environmentOf ?? defaultEnvironmentOf;
@@ -29,34 +28,15 @@ export function createMachineRunner(deps = {}) {
29
28
  kind: 'machine',
30
29
  async start(input) {
31
30
  const environment = await environmentOf(input.nodeId);
32
- const tokenMinted = deps.tokenMinted ?? defaultTokenMinted;
33
- const uncertain = (why) => new MachineLaunchUncertainError(environment, `the launch of execution ${input.executionId} is unconfirmed: ${why}`);
34
- // `status` of THIS execution decides. A repeated start (a reconciler whose lease was taken, a start whose answer was lost) finds the
35
- // broker of this execution and adopts it. A token is never minted twice for one execution (D75): one that exists means a start was
36
- // already handed over, so what is left to learn is whether its broker exists.
37
- const handedOver = await tokenMinted(input.executionId);
38
- let status;
39
- try {
40
- status = await callMachine(environment, 'status', { execution: input });
41
- }
42
- catch (error) {
43
- if (handedOver && (error instanceof MachineOfflineError || error instanceof MachineLostError))
44
- throw uncertain('the machine could not be asked');
45
- throw error;
46
- }
47
- if (status.state === 'running')
48
- return { pid: status.pid, exited: null };
49
- if (handedOver)
50
- throw uncertain('a start was handed over and no broker is running yet');
51
31
  const nodeToken = await (deps.mintToken ?? ((i) => mintExecutionToken(i.executionId, i.nodeId)))(input);
52
32
  try {
53
33
  const result = await callMachine(environment, 'start', { ...input, nodeToken });
54
34
  return { pid: result.pid, exited: null };
55
35
  }
56
36
  catch (error) {
57
- // Sent and unanswered (the link dropped, or the lease ran out): the Mac may have spawned the broker. The execution stays launching.
58
- if (error instanceof MachineLostError || (error instanceof MachineOfflineError && error.sent))
59
- throw uncertain(error.message);
37
+ // Sent and unanswered (the lease ran out): the Mac may have spawned the broker, so it is offline-after-send and the execution stays launching.
38
+ if (error instanceof MachineLostError)
39
+ throw new MachineOfflineError(environment, error.message, true);
60
40
  throw error;
61
41
  }
62
42
  },
@@ -49,7 +49,7 @@ const LEAF_MENU_ACTIONS = {
49
49
  'crtr.tmux.menu.graph': { description: 'canvas graph', action: { kind: 'keys', keys: '/graph' } },
50
50
  'crtr.tmux.menu.focus-manager': { description: 'go to manager', action: { kind: 'command', run: 'surface node focus {manager}' } },
51
51
  'crtr.tmux.menu.copy-id': { description: 'copy node id', action: { kind: 'direct', run: 'surface node id --pane {pane}' } },
52
- 'crtr.tmux.menu.reload-viewer': { description: 'reload viewer', action: { kind: 'direct', run: 'surface reload --pane {pane}' } },
52
+ 'crtr.tmux.menu.reload-viewer': { description: 'reload viewer', action: { kind: 'literal-input', input: encodeAttachControlInput('crtr.attach.reload-viewer') } },
53
53
  'crtr.tmux.menu.recap': { description: 'generate recap', action: { kind: 'keys', keys: '/recap' } },
54
54
  'crtr.tmux.menu.pin': { description: 'pin conversation', action: { kind: 'direct', run: 'surface node pin --pane {pane}' } },
55
55
  'crtr.tmux.menu.issue.idea': { description: 'idea', action: { kind: 'popup', run: 'canvas issue new --type idea' } },
@@ -624,24 +624,6 @@ export function paneCurrentCommand(pane) {
624
624
  const r = tmux(['display-message', '-p', '-t', pane, '#{pane_current_command}']);
625
625
  return r.ok && r.stdout !== '' ? r.stdout : undefined;
626
626
  }
627
- /** The pane's root process pid (`#{pane_pid}`) — the process tmux launched in
628
- * the pane (the viewer itself, or the login shell hosting it). undefined when
629
- * tmux is unreachable or the pane is gone. */
630
- export function panePid(pane) {
631
- const r = tmux(['display-message', '-p', '-t', pane, '#{pane_pid}']);
632
- if (!r.ok)
633
- return undefined;
634
- const pid = Number.parseInt(r.stdout, 10);
635
- return Number.isInteger(pid) && pid > 0 ? pid : undefined;
636
- }
637
- /** Kill a pane's current process and re-run the SAME command line it was
638
- * started with (`respawn-pane -k` with no command reuses the pane's original
639
- * command). Used to hot-reload a viewer pane in place: the fresh process
640
- * re-resolves `crtr` and picks up the currently selected runtime generation,
641
- * while the pane id, geometry, and the node's broker are untouched. */
642
- export function respawnPaneInPlace(pane) {
643
- return tmux(['respawn-pane', '-k', '-t', pane]).ok;
644
- }
645
627
  // pi command assembly
646
628
  /** Turn a pi argv array into a single shell command string.
647
629
  *
@@ -0,0 +1,94 @@
1
+ // imported-mac-installs.ts — on a Mac imported into Northlight (`runtime/machine.json`), the person's settings are the control plane's rows,
2
+ // which keep plugin and marketplace installs only in app blocks (`app-plugins.replace`), never in `settings.replace`. The Mac still runs plugin
3
+ // code from its own `runtime/{plugins,marketplaces}` directories, so the local `pkg` leaves keep cloning and updating on disk; only the user
4
+ // scope's `plugins` and `marketplaces` keys are read from and written to the terminal app's block.
5
+ import { importedIntoNorthlight } from '../../shared/env.js';
6
+ import { appRevisionOf } from './person-store.js';
7
+ export const TERMINAL_APP = 'app:terminal';
8
+ export { importedIntoNorthlight };
9
+ /** The user settings with the terminal app's install block in place of their `plugins` and `marketplaces` keys. */
10
+ export function withAppInstalls(snapshot, raw) {
11
+ const block = snapshot.apps[TERMINAL_APP];
12
+ if (block === undefined && raw === null)
13
+ return null;
14
+ return { ...(raw ?? {}), plugins: structuredClone(block?.plugins ?? {}), marketplaces: structuredClone(block?.marketplaces ?? {}) };
15
+ }
16
+ /** Split a user-settings write into the settings op (without install keys) and, when the installs changed, the app-block op. */
17
+ export function splitUserSettingsWrite(snapshot, next, ifRevision) {
18
+ const { plugins, marketplaces, ...rest } = next;
19
+ const block = snapshot.apps[TERMINAL_APP];
20
+ const ops = [{ op: 'settings.replace', owner: 'user', raw: rest, ifRevision }];
21
+ // A sandbox fetches each block plugin from its marketplace; a Mac-only install (a local path or git URL) has no source it can fetch, and the
22
+ // control plane refuses to start any sandbox of the app while such a row exists. It stays on this Mac's disk only, listing as enabled.
23
+ const fetchable = Object.fromEntries(Object.entries((plugins ?? {})).filter(([, p]) => p.source_marketplace !== undefined));
24
+ const nextBlock = { plugins: fetchable, marketplaces: (marketplaces ?? {}) };
25
+ const current = { plugins: block?.plugins ?? {}, marketplaces: block?.marketplaces ?? {} };
26
+ if (appRevisionOf(nextBlock) !== appRevisionOf(current))
27
+ ops.push({ op: 'app-plugins.replace', app: TERMINAL_APP, ...nextBlock, ifRevision: appRevisionOf(block) });
28
+ return ops;
29
+ }
30
+ const OFFICIAL_MARKETPLACE = { name: 'crouter-official-marketplace', url: 'https://github.com/crouton-labs/crouter-official-marketplace.git' };
31
+ /** Once per imported Mac: the import moved no installs into the terminal app's block, while the legacy `runtime/scope/config.json` and the
32
+ * plugin directories still name them. Copy every missing marketplace and plugin row into the block; rows already there win. A provider
33
+ * bundle (`provider` in its manifest) is the runtime's, refreshed on grant sync, and is not an install. A marker file ends the migration. */
34
+ export async function migrateLegacyInstallsOnce() {
35
+ if (!importedIntoNorthlight())
36
+ return;
37
+ const { existsSync, readFileSync, readdirSync, writeFileSync, mkdirSync } = await import('node:fs');
38
+ const { join } = await import('node:path');
39
+ const { runtimeRoot } = await import('../layout.js');
40
+ const marker = join(runtimeRoot(), 'import', 'app-installs-migrated');
41
+ if (existsSync(marker))
42
+ return;
43
+ const { writeSettings } = await import('./person-store.js');
44
+ const { readPluginManifest } = await import('../manifest.js');
45
+ // Only a missing file or directory reads as empty: any other read error throws before the marker is written, so the migration runs again.
46
+ const missing = (error) => error.code === 'ENOENT';
47
+ const legacy = (() => { try {
48
+ return JSON.parse(readFileSync(join(runtimeRoot(), 'scope', 'config.json'), 'utf8'));
49
+ }
50
+ catch (error) {
51
+ if (missing(error))
52
+ return {};
53
+ throw error;
54
+ } })();
55
+ const onDisk = (dir) => { try {
56
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith('.') && (e.isDirectory() || e.isSymbolicLink())).map((e) => e.name);
57
+ }
58
+ catch (error) {
59
+ if (missing(error))
60
+ return [];
61
+ throw error;
62
+ } };
63
+ const pluginsDir = join(runtimeRoot(), 'plugins');
64
+ await writeSettings((snapshot) => {
65
+ const block = snapshot.apps[TERMINAL_APP];
66
+ const next = structuredClone({ plugins: block?.plugins ?? {}, marketplaces: block?.marketplaces ?? {} });
67
+ for (const [name, entry] of Object.entries(legacy.marketplaces ?? {})) {
68
+ if (next.marketplaces[name] !== undefined)
69
+ continue;
70
+ next.marketplaces[name] = name === OFFICIAL_MARKETPLACE.name ? { ...entry, url: OFFICIAL_MARKETPLACE.url } : entry;
71
+ }
72
+ for (const name of onDisk(join(runtimeRoot(), 'marketplaces'))) {
73
+ if (next.marketplaces[name] === undefined && name === OFFICIAL_MARKETPLACE.name)
74
+ next.marketplaces[name] = { url: OFFICIAL_MARKETPLACE.url, ref: 'main' };
75
+ }
76
+ for (const name of onDisk(pluginsDir)) {
77
+ if (next.plugins[name] !== undefined)
78
+ continue;
79
+ const manifest = readPluginManifest(join(pluginsDir, name));
80
+ if (manifest === null || manifest.provider !== undefined)
81
+ continue;
82
+ const entry = legacy.plugins?.[name];
83
+ // Only marketplace installs go to the block: see `splitUserSettingsWrite`.
84
+ if (entry?.source_marketplace === undefined)
85
+ continue;
86
+ next.plugins[name] = { enabled: entry.enabled ?? true, source_marketplace: entry.source_marketplace, ...(entry.version === undefined ? {} : { version: entry.version }) };
87
+ }
88
+ if (appRevisionOf(next) === appRevisionOf(block))
89
+ return [];
90
+ return [{ op: 'app-plugins.replace', app: TERMINAL_APP, plugins: next.plugins, marketplaces: next.marketplaces, ifRevision: appRevisionOf(block) }];
91
+ });
92
+ mkdirSync(join(runtimeRoot(), 'import'), { recursive: true });
93
+ writeFileSync(marker, `${new Date().toISOString()}\n`);
94
+ }
@@ -130,9 +130,9 @@ export async function stopNodeSandboxes(nodeId, reason, options = {}) {
130
130
  catch (error) {
131
131
  return { confirmed: false, error: error instanceof Error ? error : new Error(String(error)) };
132
132
  }
133
- })();
133
+ })().finally(() => hold.release().catch(() => undefined));
134
134
  stopping.set(nodeId, completion);
135
- void completion.finally(() => { void hold.release().catch(() => undefined); if (stopping.get(nodeId) === completion)
135
+ void completion.finally(() => { if (stopping.get(nodeId) === completion)
136
136
  stopping.delete(nodeId); });
137
137
  return completion;
138
138
  }